Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
plugin: turning an agent plugin off or removing it puts the agent's config back first (#3810)
yetone3ec3cb704b7e
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.mdindex 55462eec9..792614361 100644--- a/docs/subsystems/agent-wiring.md+++ b/docs/subsystems/agent-wiring.md@@ -117,7 +117,7 @@ something else shows up as drift.- A Codex thread keeps the provider it was started on. While a magpie model is on, CC Switch's provider tables go through magpie too (`takeTables`), and get their own base URL back when Codex steps off magpie (`giveTables`, stash `codex.tables`). CC Switch's OpenAI mirror (a table of another id, `name = "OpenAI"`, `requires_openai_auth`, no `base_url`) isn't reached by `openai_base_url`, which takes only the built-in provider to magpie: a thread started on it and reopened went straight to ChatGPT, which refused the magpie model picked in it, and magpie never saw the request (#1796). While Codex goes to magpie by the base URL, `takeMirrors` gives each such mirror magpie's ChatGPT backend as its `base_url` (stash `codex.mirrors`), and `giveMirrors` takes it off again; a mirror a profile names, or one whose `base_url` was changed since, stays as it is. Moving the threads onto another provider is the Sessions page's Move (#887).- An agent's config is written in the form the installed version reads, taken from what that version declares, not the latest one. VSCodium has no Copilot Chat of its own, and the Marketplace's last one (0.48.1) has no Custom Endpoint provider, only OpenAI Compatible (`customoai`, #1014). magpie reads the provider list in the package.json of the `github.copilot-chat` installed under `~/.vscode-oss/extensions` (`vscodeChatOf`). It writes its group for `customendpoint` when that is declared, for `customoai` when only that is, with each model's window as `maxInputTokens` + `maxOutputTokens` and the token as `x-api-key` (that version drops an Authorization in `requestHeaders`). A missing or unreadable extension keeps `customendpoint`. Sync rewrites a group written for the other provider, and Check reports it, as it does a Copilot Chat declaring neither. That Copilot Chat registers its providers only while signed in to GitHub with a personal Copilot plan, which the Notice says.- Tuned settings are written only on the user's click, never by Sync or Connect. The value there before is stashed once (`tune.<agent>.<knob>[.<model>]` in `stash.json`), so Undo puts it back, or takes the key out (and a `modelSettings` entry left empty). A value the user changed after the click is theirs: Undo then only forgets the stash. A variable that comes before the setting (`CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `FORCE_PROMPT_CACHING_5M`, `CLAUDE_CODE_PROMPT_CACHE_TTL`, `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`, in settings.json's `env` or magpie's own) is shown as `locked` and Apply refuses, since the setting would change nothing. Claude Code compacts at the smaller of the window set and the model's own (its `/autocompact` says "capped to 200k by model"), so advice starts from that, and a model that isn't Claude's has no window here (magpie's own compact wiring serves it). Codex's window is the one magpie's catalog lists for each model it ran (typed, or the vendor's), and with none in config.toml it runs now at what magpie tells Codex (`provider.CompactFor`, else Long conversations in the agent's opened row, as `codexcat` writes it); a model of magpie's whose window isn't known caps nothing short of 1M (or the user's own larger value), never the largest prompt seen (zhemu on Discord: a 1M model at 750K was offered up to 410K), and only Codex's own models, outside the catalog, keep 272K or the largest prompt (`codexWindow`, `TestTuneWindowsAreTheUsers`). Advice changes a value only when the replay saves 3% or more, and of the windows within 1% of the cheapest takes the largest; with the compactions timed, it never advises a window that compacts more often than the one now, so never a longer wait: of the windows that compact no more often it takes the cheapest, and of those within 3% of that (`sameCost`, the same bar as changing at all) the one that compacts least, the larger of two that compact as often. Tokens and seconds share no unit the files measure, so the advice doesn't trade one for the other at a guessed rate; a cheaper window that waits longer is said with its wait in the row and the picker, for the user to choose. The wait per compaction is taken as the same at every window: the files time compactions only near the window the user ran with, too narrow to fit how it grows with the prompt. Tokens are weighed as billed: cache reads 0.1, 5-minute writes 1.25, hour writes 2, output 5 for Claude; reads 0.1, writes 1, output 8 otherwise.-- A plugin's agent writes each key in place (JSON, YAML or env), the user's comments and other keys kept. An object or array `connect` returns is taken as its JSON text (`agentplug.keys`), so it is written in the order the plugin gave it, not sorted as a Go map would be: Kilo lists its effort variants in key order (#1890, `TestPluggedKeepsPluginOrder`). What each key held before the first write is stashed under `plugin:<id>:<path>`, typed, and its own model or Disconnect puts every key back and takes out the ones that weren't there; the file is never written whole. A `connect` that throws or takes over a second writes nothing and says why. Its gateway key is `magpie-<id>` (`agentKeyAt`), and usage names its requests by that key or by its `ua` words (`usage.PluginAgents`). Its `agent.library` (instructions, `mcp` with `mcpFormat`, skills) gives it the Library's three as well, written by `internal/library` as any agent's are ([library](library.md)); a `mcpFormat` outside `agentplug.MCPFormats`, or an `mcp` without one, keeps the plugin from loading.+- A plugin's agent writes each key in place (JSON, YAML or env), the user's comments and other keys kept. An object or array `connect` returns is taken as its JSON text (`agentplug.keys`), so it is written in the order the plugin gave it, not sorted as a Go map would be: Kilo lists its effort variants in key order (#1890, `TestPluggedKeepsPluginOrder`). What each key held before the first write is stashed under `plugin:<id>:<path>`, typed, and its own model or Disconnect puts every key back and takes out the ones that weren't there; the file is never written whole. A `connect` that throws or takes over a second writes nothing and says why. Its gateway key is `magpie-<id>` (`agentKeyAt`), and usage names its requests by that key or by its `ua` words (`usage.PluginAgents`). Its `agent.library` (instructions, `mcp` with `mcpFormat`, skills) gives it the Library's three as well, written by `internal/library` as any agent's are ([library](library.md)); a `mcpFormat` outside `agentplug.MCPFormats`, or an `mcp` without one, keeps the plugin from loading. Turning the plugin off or removing it (`provider.SetPluginOff`, `provider.RemovePlugin`, from the CLI or the Plugins page) first disconnects its agent as `magpie <agent> default` does (`provider.PluginAgentGoing`, set to `agent.UnwirePlugin` in [`plugged_gone.go`](../../internal/agent/plugged_gone.go)), since without the plugin magpie no longer knows the agent (#3810); a plugin already off is read from its module as it is, and one whose module is gone puts back each file whose stash names its spec. A failure keeps the plugin as it was. On again, the agent stays as the user had it, and connecting it puts back the model it was on (Disconnect's `.reconnect`). The stash records the plugin's spec and the file's format, so `magpie <id> default` for the agent of a plugin deleted on disk puts the file back from the stash alone (`agent.RestoreGone`; an older stash's format is its file's name, `agentplug.FormatOf`); a file that no longer holds the gateway's key is the user's and left alone, and one that can't be read is put back over by nothing; with the plugin only switched off, it says the agent is off magpie already, not "unknown agent" (`TestPluginOffPutsItsAgentBack`, `TestRestoreGoneAgent`, `TestGoneAgentDefault`).- StepCode config root resolves to the parent of an absolute `STEP_CODING_AGENT_DIR` (agent resources directory differs from config root; relative values ignored), or `STEPCODE_CONFIG_DIR` under home when native, defaulting to `~/.stepcode` ([`stepcode.go`](../../internal/agent/stepcode.go)). Project configs override global configs in StepCode, but magpie manages global configuration only (`config.toml` and `models.json`). Detection is strictly directory-only via `agentDir`, avoiding collision with Smallstep's bare `step` command on `PATH`. Wiring performs an atomic two-file edit (`models.json` provider block and `config.toml` top-level defaults/scope) backed by `stash.json`. Custom fields within `providers.magpie` are preserved during sync, and the original provider block is restored on disconnect. A renamed provider's `magpie/<old>/` entries in `enabledModels` follow it, a glob or a thinking level included, and the scope remembered for disconnect follows too; the user's other entries stay. Disconnect restores original defaults, preserves user native changes and custom scope edits, and removes newly created files only when empty.- MothX's folder is `$MOTHX_DIR` as it is (no `~`), else `%APPDATA%\mothx` on Windows, else `~/.mothx`; a WSL distro's is its `~/.mothx` ([`mothx.go`](../../internal/agent/mothx.go)). Its `thinkingFormat` is `openai` unless the user set one: with it empty, MothX picks Qwen's `enable_thinking`, DeepSeek's `thinking` or Doubao's levels by the model id, which for magpie's ids says nothing of the vendor that serves them. MothX's `/model` and `/statusline … global` rewrite the whole file, so Disconnect after one takes out magpie's provider, the pick and a `providers` left empty (MothX omits an empty one), and keeps the rest.- PenguinHarness's file is `$PENGUIN_HOME` (else `~/.penguin/data`, on Windows too) `/<project>/.project_config.toml`, the Project `$PENGUIN_PROJECT_ID` when it is a folder's name (`agentenv.NotPaths`, so a relative name isn't dropped as a path), else `default_project`; a WSL distro's is its `~/.penguin/data/default_project` ([`penguin.go`](../../internal/agent/penguin.go)). Magpie's models are `[[models]]` array entries with `provider = "magpie"`, replaced together where the first one was by `edit.SetTOMLArrayTables`, which leaves the user's entries, the blank lines between them and the file's time alone when nothing changed (Penguin's server reads the file again on every mtime change). `default_model` is spelled `{ provider = …, model_id = … }` as Penguin's own writer (smol-toml) spells it; that writer rewrites the whole file, so Disconnect takes out magpie's provider, entries and a vision model on them rather than putting back a copy. A default naming no entry is refused by Penguin, so entries go in before `default_model` and out after it.diff --git a/internal/agent/plugged.go b/internal/agent/plugged.goindex 0b1fed9f2..0a9284038 100644--- a/internal/agent/plugged.go+++ b/internal/agent/plugged.go@@ -53,6 +53,11 @@ type pluggedStash struct {// Wrote are the strings magpie wrote, by key, for Check to tell// one changed sinceWrote map[string]string `json:"wrote,omitempty"`+ // Spec and Format are the plugin's and its file's, so what the user+ // had can be put back with the plugin gone (#3810); a stash written+ // before them has neither, and its file's name says its format+ Spec string `json:"spec,omitempty"`+ Format string `json:"format,omitempty"`}// PluginErrors is why an agent a plugin adds isn't listed, by plugin@@ -208,6 +213,38 @@ func (f pluggedFile) del(keys []string) error {return edit.DelEnvFile(f.path, keys...)}+// wired says the agent id's file is still as magpie wired it, by st: the+// gateway's key magpie wrote is there.+func (f pluggedFile) wired(id string, st pluggedStash) bool {+ if st.Mark == "" {+ return true+ }+ v, _ := f.get(st.Mark)+ return v == st.Value || ourKey(v) || v == gateway.TokenFor(id)+}++// restore puts back what the user had under every key magpie wrote, as st+// stashed it under key, and forgets it.+func (f pluggedFile) restore(key string, st pluggedStash) error {+ var del []string+ var kvs []edit.KV+ for _, k := range sortedKeys(st.Had) {+ if v := st.Had[k]; v == "\x00" {+ del = append(del, k)+ } else {+ kvs = append(kvs, edit.KV{Path: k, Value: f.back(v)})+ }+ }+ if err := f.del(del); err != nil {+ return err+ }+ if err := f.set(kvs); err != nil {+ return err+ }+ forget(key)+ return nil+}+// plugged is the Agent of a plugin's agent at home.func plugged(home string, p *agentplug.Agent) *Agent {d := p.Desc@@ -228,37 +265,9 @@ func plugged(home string, p *agentplug.Agent) *Agent {// still thereonMagpie := func() (pluggedStash, bool) {st, ok := saved()- if !ok {- return st, false- }- if st.Mark != "" {- v, _ := f.get(st.Mark)- if v != st.Value && !ourKey(v) && v != gateway.TokenFor(id) {- return st, false- }- }- return st, true- }- // restore puts back what the user had under every key magpie wrote- restore := func(st pluggedStash) error {- var del []string- var kvs []edit.KV- for _, k := range sortedKeys(st.Had) {- if v := st.Had[k]; v == "\x00" {- del = append(del, k)- } else {- kvs = append(kvs, edit.KV{Path: k, Value: f.back(v)})- }- }- if err := f.del(del); err != nil {- return err- }- if err := f.set(kvs); err != nil {- return err- }- forget(key)- return nil+ return st, ok && f.wired(id, st)}+ restore := func(st pluggedStash) error { return f.restore(key, st) }// only: the agent picks its model itself among those connect writes// (#2374), so magpie writes no model, and the switch is its one fieldonly := d.Model == ""@@ -354,6 +363,7 @@ func plugged(home string, p *agentplug.Agent) *Agent {delete(st.Had, k)}st.Ref, st.Mark, st.Value, st.Wrote = ref, mark, gk, strs+ st.Spec, st.Format = p.Spec, f.formatif err := f.del(del); err != nil {return err}diff --git a/internal/agent/plugged_gone.go b/internal/agent/plugged_gone.gonew file mode 100644index 000000000..dd6c7057d--- /dev/null+++ b/internal/agent/plugged_gone.go@@ -0,0 +1,181 @@+package agent++// An agent a plugin adds is known to magpie only while the plugin is on:+// turned off or removed, `magpie <agent> default` said "unknown agent" and+// the agent's config was left on magpie, with nothing to put it back+// (#3810). So magpie takes itself out of the agent's config before the+// plugin goes (UnwirePlugin, which internal/provider calls), and what it+// stashed of the file is enough to put it back with the plugin gone+// (RestoreGone, for a plugin deleted on disk).++import (+ "bytes"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "slices"+ "strings"++ "github.com/yetone/magpie/internal/agentplug"+ "github.com/yetone/magpie/internal/edit"+ "github.com/yetone/magpie/internal/plugin"+ "github.com/yetone/magpie/internal/provider"+)++func init() {+ provider.PluginAgentGoing = UnwirePlugin+}++// UnwirePlugin takes magpie out of the config of the agent the plugin spec+// adds and puts back what the user had, as `magpie <agent> default` does+// (Disconnect), before the plugin is turned off or removed. The agent is+// the one listed while the plugin is on, else its module read as it is (a+// plugin off already); with no module that loads, each file stashed as+// the plugin's is put back from the stash alone. An agent not on magpie is+// left as it is.+func UnwirePlugin(spec string) error {+ var a *Agent+ for _, x := range All() {+ if x.Plugin == spec {+ a = x+ break+ }+ }+ if a == nil {+ a = pluggedOff(spec)+ }+ if a != nil {+ if !a.Wired() {+ return nil+ }+ if err := a.Disconnect(); err != nil {+ return fmt.Errorf("%s: %w", a.Name, err)+ }+ return nil+ }+ _, _, err := restoreLeft(func(_ string, st pluggedStash) bool { return st.Spec == spec })+ return err+}++// pluggedOff is the agent of a plugin that isn't listed (switched off, or+// its list not read again yet), its module read as it is; nil when it adds+// none, its module doesn't load, or its id is one of magpie's own agents'.+func pluggedOff(spec string) *Agent {+ file, _ := plugin.Agent(plugin.Target(spec))+ if file == "" {+ return nil+ }+ p, err := agentplug.Compile(spec, file)+ if err != nil {+ return nil+ }+ home, cfg := homes()+ for _, b := range append(builtins(home, cfg), others...) {+ if b.ID == p.Desc.ID || slices.Contains(b.Aliases, p.Desc.ID) {+ return nil+ }+ }+ return plugged(home, p)+}++// Gone is what RestoreGone did: the files it put back as the user had+// them, and those magpie was already out of. PluginOff names the agent of+// a plugin switched off with nothing stashed: magpie is out of it already.+type Gone struct {+ Put, Off []string+ PluginOff string+}++// RestoreGone puts back what the user had in each file magpie wired for+// the agent id of a plugin that is gone (deleted on disk, or taken out of+// plugins.json by hand), from the stash alone, for `magpie <id> default`.+// ok is false when id is an agent here, or nothing is stashed for it and+// no plugin switched off adds it.+func RestoreGone(id string) (g Gone, ok bool, err error) {+ id = strings.ToLower(strings.TrimSpace(id))+ for _, a := range All() {+ if strings.EqualFold(a.ID, id) {+ return g, false, nil+ }+ }+ g.Put, g.Off, err = restoreLeft(func(sid string, _ pluggedStash) bool { return sid == id })+ if len(g.Put)+len(g.Off) > 0 || err != nil {+ return g, true, err+ }+ for _, e := range plugin.Load().Plugins {+ if !e.Off {+ continue+ }+ if a := pluggedOff(e.Spec); a != nil && a.ID == id {+ g.PluginOff = a.Name+ return g, true, nil+ }+ }+ return g, false, nil+}++// restoreLeft puts back each agent plugin's file stashed that match+// takes, from the stash: put are the files put back, off those whose+// wiring was gone already (its stash is forgotten). A stash that doesn't+// parse is left alone.+func restoreLeft(match func(id string, st pluggedStash) bool) (put, off []string, err error) {+ m := stashLoad()+ for _, k := range sortedKeys(m) {+ rest, ok := strings.CutPrefix(k, "plugin:")+ if !ok {+ continue+ }+ // an id has no ':' (agentplug's idOK), a Windows path may+ id, path, ok := strings.Cut(rest, ":")+ if !ok {+ continue+ }+ var st pluggedStash+ if json.Unmarshal([]byte(m[k]), &st) != nil || !match(id, st) {+ continue+ }+ format := st.Format+ if format == "" {+ format = agentplug.FormatOf(path)+ }+ if format == "" {+ err = errors.Join(err, fmt.Errorf("%s: its format isn't known, so magpie keeps what it had in its stash", path))+ continue+ }+ f := pluggedFile{path, format}+ held, e := f.holds(st.Value)+ if e != nil {+ err = errors.Join(err, fmt.Errorf("%s: %w", path, e))+ continue+ }+ if !held || !f.wired(id, st) {+ forget(k)+ off = append(off, path)+ continue+ }+ if e := edit.Atomically(func() error { return f.restore(k, st) }, path); e != nil {+ err = errors.Join(err, fmt.Errorf("%s: %w", path, e))+ continue+ }+ put = append(put, path)+ }+ return put, off, err+}++// holds says the file still has the gateway's key magpie wrote somewhere+// in it: with no plugin to say which key is the model (an object connect+// returned has no Mark), a file that has lost it, or is gone, was taken+// off magpie by hand, and what the user wrote since is theirs. A file+// that can't be read is an error: nothing is put back over it, and its+// stash is kept.+func (f pluggedFile) holds(key string) (bool, error) {+ b, err := os.ReadFile(f.path)+ if os.IsNotExist(err) {+ return false, nil+ }+ if err != nil {+ return false, err+ }+ return key == "" || bytes.Contains(b, []byte(key)), nil+}diff --git a/internal/agent/plugged_gone_test.go b/internal/agent/plugged_gone_test.gonew file mode 100644index 000000000..19d1e9fa9--- /dev/null+++ b/internal/agent/plugged_gone_test.go@@ -0,0 +1,240 @@+package agent++import (+ "context"+ "encoding/json"+ "os"+ "path/filepath"+ "runtime"+ "testing"++ "github.com/yetone/magpie/internal/agentplug"+ "github.com/yetone/magpie/internal/plugin"+ "github.com/yetone/magpie/internal/provider"+ "github.com/yetone/magpie/internal/settings"+)++// kiloGoneSrc is an agent plugin as agent-kilo is: a JSONC file, the model+// under "model" with the provider's prefix, and a provider block of its own.+const kiloGoneSrc = `+export const agent = { id: "kilo", name: "Kilo", config: "~/.config/kilo/kilo.jsonc", model: "model", prefix: "magpie/" };+export function connect({ gateway, models }) {+ return { "provider.magpie": { npm: "@ai-sdk/openai-compatible", options: { baseURL: gateway.v1, apiKey: gateway.key }, models: Object.fromEntries(models.map(m => [m.id, { name: m.name }])) } };+}+`++// kiloMine is a kilo.jsonc as its user wrote it: comments, a model of+// their own and a provider block of their own.+const kiloMine = `{+ // my Kilo+ "$schema": "https://app.kilo.ai/config.json",+ "model": "anthropic/claude-sonnet-4-5", // mine+ "provider": {+ "anthropic": { "options": { "apiKey": "sk-mine" } }+ }+}+`++// kiloWired is a home with the kilo plugin and kilo.jsonc as its user+// wrote it, put on one of magpie's models; it returns the file and the+// plugin's spec.+func kiloWired(t *testing.T) (string, string) {+ t.Helper()+ home := pluggedHome(t, kiloGoneSrc)+ path := filepath.Join(home, ".config", "kilo", "kilo.jsonc")+ os.MkdirAll(filepath.Dir(path), 0o755)+ if err := os.WriteFile(path, []byte(kiloMine), 0o644); err != nil {+ t.Fatal(err)+ }+ a, err := Find("kilo")+ if err != nil {+ t.Fatal(err)+ }+ if err := a.Field("model").Set("magpie/deepseek/pro"); err != nil {+ t.Fatal(err)+ }+ if b, _ := os.ReadFile(path); string(b) == kiloMine || !a.Wired() {+ t.Fatalf("not wired:\n%s", b)+ }+ return path, a.Plugin+}++func fileAsMine(t *testing.T, path, want string) {+ t.Helper()+ if b, err := os.ReadFile(path); err != nil || string(b) != want {+ t.Fatalf("%s is not as the user had it (%v):\n%s", path, err, b)+ }+}++// Turning an agent plugin off puts back the agent's config byte for byte+// (#3810), and on again the agent's switch puts back the model it was on.+func TestPluginOffPutsItsAgentBack(t *testing.T) {+ path, spec := kiloWired(t)+ if err := provider.SetPluginOff(context.Background(), spec, true); err != nil {+ t.Fatal(err)+ }+ fileAsMine(t, path, kiloMine)+ if _, ok := stashLoad()["plugin:kilo:"+path]; ok {+ t.Fatal("the stash outlived the wiring")+ }+ agentplug.Reload()+ if _, err := Find("kilo"); err == nil {+ t.Fatal("kilo is still an agent with its plugin off")+ }+ // `magpie kilo default` with the plugin off says so, not "unknown agent"+ if g, ok, err := RestoreGone("kilo"); !ok || err != nil || g.PluginOff != "Kilo" || len(g.Put)+len(g.Off) != 0 {+ t.Fatalf("kilo default with its plugin off: %+v, %v, %v", g, ok, err)+ }+ fileAsMine(t, path, kiloMine)+ if err := provider.SetPluginOff(context.Background(), spec, false); err != nil {+ t.Fatal(err)+ }+ agentplug.Reload()+ a, err := Find("kilo")+ if err != nil {+ t.Fatal(err)+ }+ // on again it stays as the user had it, till they switch it on+ fileAsMine(t, path, kiloMine)+ if a.Wired() {+ t.Fatal("on again, magpie wired kilo by itself")+ }+ c, err := a.ConnectHow()+ if err != nil {+ t.Fatal(err)+ }+ if c.How != "again" || a.Field("model").Get() != "magpie/deepseek/pro" {+ t.Fatalf("switched on: %+v, model %q", c, a.Field("model").Get())+ }+}++// Removing it does the same.+func TestPluginRemovePutsItsAgentBack(t *testing.T) {+ path, spec := kiloWired(t)+ if err := provider.RemovePlugin(context.Background(), spec); err != nil {+ t.Fatal(err)+ }+ fileAsMine(t, path, kiloMine)+ if len(plugin.Load().Plugins) != 0 {+ t.Fatal("not removed")+ }+}++// A plugin switched off before magpie did this (its stash from then, with+// no spec or format) and then removed: its module, read as it is, puts the+// agent back.+func TestPluginRemovedWhileOffPutsItsAgentBack(t *testing.T) {+ path, spec := kiloWired(t)+ oldStash(t, "plugin:kilo:"+path)+ if err := plugin.SetOff(spec, true); err != nil {+ t.Fatal(err)+ }+ agentplug.Reload()+ if err := provider.RemovePlugin(context.Background(), spec); err != nil {+ t.Fatal(err)+ }+ fileAsMine(t, path, kiloMine)+}++// A plugin whose module is gone from disk, still listed: what magpie+// stashed of the file puts it back.+func TestPluginWithItsModuleGonePutsItsAgentBack(t *testing.T) {+ path, spec := kiloWired(t)+ if err := os.Remove(filepath.Join(spec, "agent.js")); err != nil {+ t.Fatal(err)+ }+ agentplug.Reload()+ if err := provider.SetPluginOff(context.Background(), spec, true); err != nil {+ t.Fatal(err)+ }+ fileAsMine(t, path, kiloMine)+}++// A plugin deleted on disk and off plugins.json: `magpie kilo default`+// (RestoreGone) puts the file back from the stash alone, an old stash+// with no format by its file's name.+func TestRestoreGoneAgent(t *testing.T) {+ path, spec := kiloWired(t)+ oldStash(t, "plugin:kilo:"+path)+ os.RemoveAll(spec)+ os.WriteFile(filepath.Join(settings.Dir(), "plugins.json"), []byte(`{"plugins":[]}`), 0o644)+ agentplug.Reload()+ if _, err := Find("kilo"); err == nil {+ t.Fatal("kilo is still an agent")+ }+ g, ok, err := RestoreGone("kilo")+ if err != nil || !ok || len(g.Put) != 1 || g.Put[0] != path {+ t.Fatalf("restored %+v, %v, %v", g, ok, err)+ }+ fileAsMine(t, path, kiloMine)+ // once is all: nothing is left for it, nor for an agent never wired,+ // nor one here+ for _, id := range []string{"kilo", "nobody", "codex"} {+ if g, ok, err := RestoreGone(id); ok || err != nil {+ t.Fatalf("%s: %+v, %v, %v", id, g, ok, err)+ }+ }+}++// A file the user took off magpie by hand since is theirs: RestoreGone+// leaves it and forgets the stash.+func TestRestoreGoneLeavesAFileOffMagpie(t *testing.T) {+ path, spec := kiloWired(t)+ os.RemoveAll(spec)+ agentplug.Reload()+ mine := `{"model": "openai/gpt-5"}`+ if err := os.WriteFile(path, []byte(mine), 0o644); err != nil {+ t.Fatal(err)+ }+ g, ok, err := RestoreGone("kilo")+ if err != nil || !ok || len(g.Off) != 1 || len(g.Put) != 0 {+ t.Fatalf("restored %+v, %v, %v", g, ok, err)+ }+ fileAsMine(t, path, mine)+ if _, ok := stashLoad()["plugin:kilo:"+path]; ok {+ t.Fatal("the stash is kept")+ }+}++// oldStash takes the spec and format out of the stash under key, as a+// magpie before #3810 wrote it.+func oldStash(t *testing.T, key string) {+ t.Helper()+ var st map[string]any+ if err := json.Unmarshal([]byte(stashLoad()[key]), &st); err != nil {+ t.Fatal(err)+ }+ if st["spec"] == nil || st["format"] == nil {+ t.Fatalf("stash has no spec or format: %v", st)+ }+ delete(st, "spec")+ delete(st, "format")+ b, _ := json.Marshal(st)+ stash(map[string]string{key: string(b)})+}++// A file that can't be read is unknown: nothing is put back over it, and+// its stash is kept for when it can be.+func TestRestoreGoneKeepsAnUnreadableFile(t *testing.T) {+ if runtime.GOOS == "windows" || os.Geteuid() == 0 {+ t.Skip("a file's mode doesn't keep it from being read here")+ }+ path, spec := kiloWired(t)+ os.RemoveAll(spec)+ agentplug.Reload()+ wired, _ := os.ReadFile(path)+ os.Chmod(path, 0o000)+ t.Cleanup(func() { os.Chmod(path, 0o644) })+ if _, ok, err := RestoreGone("kilo"); !ok || err == nil {+ t.Fatalf("an unreadable file: %v, %v", ok, err)+ }+ if _, ok := stashLoad()["plugin:kilo:"+path]; !ok {+ t.Fatal("the stash is gone")+ }+ os.Chmod(path, 0o644)+ fileAsMine(t, path, string(wired))+ if g, ok, err := RestoreGone("kilo"); !ok || err != nil || len(g.Put) != 1 {+ t.Fatalf("readable again: %+v, %v, %v", g, ok, err)+ }+ fileAsMine(t, path, kiloMine)+}diff --git a/internal/agentplug/agentplug.go b/internal/agentplug/agentplug.goindex c15bfe2ff..e6647ec92 100644--- a/internal/agentplug/agentplug.go+++ b/internal/agentplug/agentplug.go@@ -62,6 +62,15 @@ var Formats = map[string]string{".env": "env",}+// FormatOf is the format a config file's name says it is in, "" for one+// it doesn't say.+func FormatOf(config string) string {+ if strings.HasPrefix(strings.ToLower(filepath.Base(config)), ".env") {+ return "env"+ }+ return Formats[strings.ToLower(filepath.Ext(config))]+}+// Desc is what a module's agent export says.type Desc struct {ID string `json:"id"`@@ -284,10 +293,7 @@ func (d *Desc) check() error {d.Name = d.ID}if d.Format == "" {- d.Format = Formats[strings.ToLower(filepath.Ext(d.Config))]- if strings.HasPrefix(strings.ToLower(filepath.Base(d.Config)), ".env") {- d.Format = "env"- }+ d.Format = FormatOf(d.Config)}switch d.Format {case "json", "yaml", "env":diff --git a/internal/cli/main.go b/internal/cli/main.goindex 6f969a6d2..a10f13ef3 100644--- a/internal/cli/main.go+++ b/internal/cli/main.go@@ -480,6 +480,13 @@ func run(args []string) error {return claudeCodeCmd(args[1:])}+ // the agent of a plugin that is gone (deleted on disk) is no agent+ // here, but what magpie stashed of its file puts it back (#3810)+ if len(args) == 2 && strings.EqualFold(args[1], "default") {+ if g, ok, err := agent.RestoreGone(args[0]); ok {+ return goneDefault(args[0], g, err)+ }+ }a, err := agent.Find(args[0])if err != nil {return err@@ -661,6 +668,27 @@ func disconnect(a *agent.Agent) error {return nil}+// goneDefault says what `magpie <id> default` did for the agent of a+// plugin that is gone.+func goneDefault(id string, g agent.Gone, err error) error {+ for _, p := range g.Put {+ fmt.Println(green.Render("✓"), bold.Render(id), muted.Render(p))+ }+ for _, p := range g.Off {+ fmt.Println(green.Render("✓"), bold.Render(id), muted.Render(p+": magpie was out of it already"))+ }+ if len(g.Put) > 0 {+ fmt.Println(muted.Render(" its plugin is gone; disconnected from magpie, back to what it had before"))+ }+ if g.PluginOff != "" {+ fmt.Println(green.Render("✓"), bold.Render(g.PluginOff), muted.Render("is not on magpie: its plugin is off, and magpie put back what it had when the plugin was turned off"))+ }+ if err != nil {+ return fmt.Errorf("%s's plugin is gone, and magpie couldn't put its config back: %w", id, err)+ }+ return nil+}+func fieldForValue(a *agent.Agent, v string) *agent.Field {vals := a.Values()// the agent's suffix after a model (omp's ":max") aside: a role on thediff --git a/internal/cli/plugin_agent_gone_cli_test.go b/internal/cli/plugin_agent_gone_cli_test.gonew file mode 100644index 000000000..659b8f667--- /dev/null+++ b/internal/cli/plugin_agent_gone_cli_test.go@@ -0,0 +1,91 @@+package cli++import (+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ "github.com/yetone/magpie/internal/agentplug"+ "github.com/yetone/magpie/internal/plugin"+ "github.com/yetone/magpie/internal/settings"+)++// goneAgentSrc is an agent plugin as agent-kilo is: a JSONC file, the+// model under "model", a provider block of its own.+const goneAgentSrc = `+export const agent = { id: "kilo", name: "Kilo", config: "~/.config/kilo/kilo.jsonc", model: "model", prefix: "magpie/" };+export function connect({ gateway }) {+ return { "provider.magpie": { npm: "@ai-sdk/openai-compatible", options: { baseURL: gateway.v1, apiKey: gateway.key } } };+}+`++const goneAgentMine = "{\n // mine\n \"model\": \"anthropic/claude-sonnet-4-5\", // mine\n \"provider\": {\n \"anthropic\": {}\n }\n}\n"++// goneAgentHome has the kilo plugin, its kilo.jsonc as the user wrote it,+// and kilo on magpie's a/m through `magpie kilo a/m`; it returns the file+// and the plugin's folder.+func goneAgentHome(t *testing.T) (string, string) {+ t.Helper()+ groupsHome(t)+ home := os.Getenv("HOME")+ dir := filepath.Join(home, "plugins", "kilo")+ os.MkdirAll(dir, 0o755)+ os.WriteFile(filepath.Join(dir, "package.json"), []byte(`{"name":"agent-kilo","magpie":{"agent":"./agent.js"}}`), 0o644)+ os.WriteFile(filepath.Join(dir, "agent.js"), []byte(goneAgentSrc), 0o644)+ b, _ := json.Marshal(plugin.List{Plugins: []plugin.Entry{{Spec: dir}}})+ os.MkdirAll(settings.Dir(), 0o755)+ if err := os.WriteFile(filepath.Join(settings.Dir(), "plugins.json"), b, 0o644); err != nil {+ t.Fatal(err)+ }+ agentplug.Reload()+ t.Cleanup(agentplug.Reload)+ path := filepath.Join(home, ".config", "kilo", "kilo.jsonc")+ os.MkdirAll(filepath.Dir(path), 0o755)+ os.WriteFile(path, []byte(goneAgentMine), 0o644)+ if err := run([]string{"kilo", "a/m"}); err != nil {+ t.Fatal(err)+ }+ if b, _ := os.ReadFile(path); string(b) == goneAgentMine {+ t.Fatal("not wired")+ }+ return path, dir+}++func fileIs(t *testing.T, path, want string) {+ t.Helper()+ if b, _ := os.ReadFile(path); string(b) != want {+ t.Fatalf("%s isn't as the user had it:\n%s", path, b)+ }+}++// `magpie plugin off` and `magpie plugin rm` put the agent's config back+// byte for byte before the plugin goes (#3810).+func TestPluginOffAndRemovePutTheAgentBack(t *testing.T) {+ for _, op := range []string{"off", "rm"} {+ t.Run(op, func(t *testing.T) {+ path, dir := goneAgentHome(t)+ if err := run([]string{"plugin", op, dir}); err != nil {+ t.Fatal(err)+ }+ fileIs(t, path, goneAgentMine)+ })+ }+}++// With the plugin deleted on disk, `magpie kilo default` puts kilo.jsonc+// back from what magpie stashed, where it said "unknown agent".+func TestGoneAgentDefault(t *testing.T) {+ path, dir := goneAgentHome(t)+ os.RemoveAll(dir)+ os.WriteFile(filepath.Join(settings.Dir(), "plugins.json"), []byte(`{"plugins":[]}`), 0o644)+ agentplug.Reload()+ if err := run([]string{"kilo", "default"}); err != nil {+ t.Fatal(err)+ }+ fileIs(t, path, goneAgentMine)+ // nothing left to put back: it is an unknown agent again+ if err := run([]string{"kilo", "default"}); err == nil {+ t.Fatal("kilo is known with nothing of it left")+ }+}diff --git a/internal/cli/plugins_cli.go b/internal/cli/plugins_cli.goindex dc9734062..2bb88af86 100644--- a/internal/cli/plugins_cli.go+++ b/internal/cli/plugins_cli.go@@ -11,6 +11,7 @@ import ("strings""time"+ "github.com/yetone/magpie/internal/agent""github.com/yetone/magpie/internal/gateway""github.com/yetone/magpie/internal/middleware""github.com/yetone/magpie/internal/plugin"@@ -72,10 +73,12 @@ func pluginCmd(args []string) error {}rest[0] = installedName(rest[0])moved := provider.MovedOnto(rest[0])+ wired := wiredPluginAgent(rest[0])if err := provider.RemovePlugin(ctx, rest[0]); err != nil {return err}fmt.Println(green.Render("✓"), "removed", rest[0])+ sayAgentBack(wired)for _, id := range moved {fmt.Println(faint.Render(" " + id + " is off until the plugin is added again; its accounts are kept"))}@@ -92,10 +95,15 @@ func pluginCmd(args []string) error {return errors.New(pluginUsage)}rest[0] = installedName(rest[0])+ var wired *agent.Agent+ if sub == "off" {+ wired = wiredPluginAgent(rest[0])+ }if err := provider.SetPluginOff(ctx, rest[0], sub == "off"); err != nil {return err}fmt.Println(green.Render("✓"), rest[0], "is", sub)+ sayAgentBack(wired)if sub == "off" {for _, id := range provider.MovedOnto(rest[0]) {fmt.Println(faint.Render(" " + id + " is off with it; its accounts are kept"))@@ -673,3 +681,23 @@ func readsText(reads []string) string {}return "reads " + strings.Join(reads, ", ")}++// wiredPluginAgent is the agent the plugin named adds, while magpie is in+// its config: turning the plugin off or removing it takes magpie out+// first (provider.PluginAgentGoing, #3810).+func wiredPluginAgent(name string) *agent.Agent {+ for _, a := range agent.All() {+ if a.Plugin != "" && (a.Plugin == name || plugin.Name(a.Plugin) == name) && a.Wired() {+ return a+ }+ }+ return nil+}++// sayAgentBack says that the agent a plugin added was taken off magpie.+func sayAgentBack(a *agent.Agent) {+ if a == nil {+ return+ }+ fmt.Println(faint.Render(" " + a.Name + " is disconnected from magpie, back to what it had before; with the plugin back, connecting it (its switch on the Agents page) puts back the model it was on"))+}diff --git a/internal/provider/migrate.go b/internal/provider/migrate.goindex d3ae57273..623d41cbf 100644--- a/internal/provider/migrate.go+++ b/internal/provider/migrate.go@@ -1181,12 +1181,36 @@ func MovedOnto(name string) []string {return out}+// PluginAgentGoing, set by internal/agent, takes magpie out of the config+// of the agent the plugin spec adds and puts back what the user had, as+// `magpie <agent> default` does. It runs before the plugin is turned off+// or removed, while magpie still knows the agent: after, nothing could+// (#3810).+var PluginAgentGoing func(spec string) error++// agentGoing runs PluginAgentGoing for the installed plugin named; an+// error keeps the plugin as it is.+func agentGoing(name, left string) error {+ spec := installedSpec(name)+ if spec == "" || PluginAgentGoing == nil {+ return nil+ }+ if err := PluginAgentGoing(spec); err != nil {+ return fmt.Errorf("%s is left %s: magpie couldn't put back its agent's config as it was (%w); switch the agent off magpie first", name, left, err)+ }+ return nil+}+// RemovePlugin removes the plugin named and sets aside the model picks of// its providers it leaves in providers.json (plugin_left.go). A built-in// moved onto it isn't moved back, as the built-in is going: it is// MoveRemoved, its accounts kept with the plugin's sign-ins for when the-// plugin is installed again.+// plugin is installed again. The agent it adds is taken off magpie first+// (PluginAgentGoing).func RemovePlugin(ctx context.Context, name string) error {+ if err := agentGoing(name, "installed"); err != nil {+ return err+ }// what it served is read while it is still on the listmoved := MovedOnto(name)spec := installedSpec(name)@@ -1213,7 +1237,14 @@ func RemovePlugin(ctx context.Context, name string) error {// SetPluginOff turns the plugin named off, or back on. A built-in moved// onto it stays moved, off with it: nothing moves it back, as the built-in-// is going.+// is going. The agent it adds is taken off magpie before it is off+// (PluginAgentGoing), and stays off when it is on again: the agent's+// switch puts back the model it was on.func SetPluginOff(_ context.Context, name string, off bool) error {+ if off {+ if err := agentGoing(name, "on"); err != nil {+ return err+ }+ }return plugin.SetOff(name, off)}