diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 6d2329b79..ca253c0ad 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -56,7 +56,7 @@ something else shows up as drift. - Claude Code 2.1.296 reads a Claude model whose version has a dot (`relay/claude-opus-4.6-us`) as Claude Opus 4: a retired warning, budget thinking, 32000 output tokens, no effort. With dashes (`relay/claude-opus-4-6-us`) it knows the model (misteer_ti. on Discord). So every model magpie writes into its settings (`model`, the tier envs, `ANTHROPIC_SMALL_FAST_MODEL`, `CLAUDE_CODE_SUBAGENT_MODEL`, `modelPicker`), T3 Code's Claude slugs and Claude Desktop's Code-tab ids (`claudeLooking`) spell a dotted Claude version with dashes (`provider.ClaudeSpelled`), only when that spelling stands for one served id. Every read of those keys takes it back (`provider.ClaudeRead`: `claudeIn`'s `env`, `claudeMain`, `claudeStandInAt`), so magpie's fields, applied state and Drift keep the dotted id. The user's own values are stashed and given back as written. Values an older magpie wrote dotted are rewritten on the next Sync. Other vendors' ids are never respelled ([`claudedash.go`](../../internal/provider/claudedash.go)). - Codex's "subagents" field is `[agents] default_subagent_model`: only the model a subagent starts on when its lead names none in `spawn_agent` (codex-rs `core/src/agent/child_config.rs`). Unset, it isn't "same as model": the lead may still name another, so the GUI calls it the lead's pick, else the model (`leadPicks` in app.js), and its title points at the "subagent model" field. - Codex's "subagent model" field writes nothing to Codex's config: its lead names each subagent's model in `spawn_agent`, which `[agents]` can't overrule. It is magpie's setting (`settings.CodexSubagentModel`, [`codex_subagent.go`](../../internal/provider/codex_subagent.go)), and the gateway moves the subagent's request onto it (see [gateway routing](gateway-routing.md)). Its options are only ChatGPT accounts' models, as a subagent's task is sealed for them. Its setter keeps a ChatGPT account's model no account serves now, so a profile or backup put back on another computer still applies (`ApplyFields` stops at the first failed Set), and refuses any other provider's model. -- Snow CLI runs on one profile at a time (`profiles/.json` in `~/.snow` or `$SNOW_CONFIG_DIR`, named in `active-profile.json`) and copies the active one over `config.json` at every start, `snow --ask` too ([`snow.go`](../../internal/agent/snow.go)). magpie writes a `magpie` profile, makes it the active one, and copies it to `config.json` itself, so a Snow already running and Snow App's "Sync Snow CLI API config" see the same. It is made from the profile the user was on, their settings kept and its OAuth sign-in left out. A vision model of that profile comes along only with an endpoint and key of its own (`snowOwnVision`), since one on the profile's would now go to the gateway. `maxContextTokens`, `maxTokens` and `supportsVision` follow the model from the catalog (`snowSynced`; `supportsVision` as every agent is told, true while magpie's Vision describes images); what magpie last wrote of them is stashed, and one the user changed since in Snow's own settings is kept through later picks and syncs. The small field is magpie's profile's `basicModel`, Snow's light model for summaries, compaction and file search: empty while it follows the main model, a model through magpie of its own kept through new main models and syncs; on a profile of the user's it offers nothing and is hidden. The thinking field is magpie's profile's `chatThinking` (`{enabled: true, reasoning_effort}`), the only thinking setting Snow reads on the chat protocol; empty deletes it, Snow's default, which sends thinking disabled. A chatThinking the user brought from their profile is shown, not written over. The profile they were on (or that there was no `active-profile.json`) and a `magpie.json` of their own are stashed and put back by Disconnect. A Snow from before profiles (`config.json` alone) gets the `default.json` Snow itself would have made of it, so its next start doesn't take magpie's for the user's. Picking a model of another of the user's profiles switches Snow to that profile. +- Snow CLI runs on one profile at a time (`profiles/.json` in `~/.snow` or `$SNOW_CONFIG_DIR`, named in `active-profile.json`) and copies the active one over `config.json` at every start, `snow --ask` too ([`snow.go`](../../internal/agent/snow.go)). magpie writes a `magpie` profile, makes it the active one, and copies it to `config.json` itself, so a Snow already running and Snow App's "Sync Snow CLI API config" see the same. It is made from the profile the user was on, their settings kept and its OAuth sign-in left out. A vision model of that profile comes along only with an endpoint and key of its own (`snowOwnVision`), since one on the profile's would now go to the gateway. `maxContextTokens`, `maxTokens` and `supportsVision` follow the model from the catalog (`snowSynced`; `supportsVision` as every agent is told, true while magpie's Vision describes images); what magpie last wrote of them is stashed, and one the user changed since in Snow's own settings is kept through later picks and syncs. The small field is magpie's profile's `basicModel`, Snow's light model for summaries, compaction and file search: empty while it follows the main model, a model through magpie of its own kept through new main models and syncs; on a profile of the user's it offers nothing and is hidden. The thinking field is magpie's profile's `chatThinking` (`{enabled: true, reasoning_effort}`), the only thinking setting Snow reads on the chat protocol; empty deletes it, Snow's default, which sends thinking disabled. A chatThinking the user brought from their profile is shown, not written over. The profile they were on (or that there was no `active-profile.json`) and a `magpie.json` of their own are stashed and put back by Disconnect. A Snow from before profiles (`config.json` alone) gets the `default.json` Snow itself would have made of it, so its next start doesn't take magpie's for the user's. Picking a model of another of the user's profiles switches Snow to that profile. On magpie's profile, a value that is neither a model through magpie nor the model of one of the user's profiles is refused and changes nothing (#1457: `magpie snow --help` used to take magpie out and write `--help` as the model of the profile it went back to). Gemini CLI's auth field refuses an auth it doesn't know before it unroutes, for the same reason. On the CLI, `-h`/`--help` after any command or agent only prints its usage, before `run` reads or moves anything, and any other flag given to `magpie …` is refused (`help_cli.go`; `TestHelpOnEveryCommandDoesNothing` walks `run`'s switch and every agent). - A value an agent spells as its own provider's model is never taken for one of magpie's, even when magpie has a provider of the same name (`Spelled`, #835). - `Reapply` on `unwired` sets again every field on one of magpie's models and every field set to magpie itself (`magpieID`, as `Wired` takes it): Claude Desktop's drift shows on a tier, and its `provider` field is what writes the gateway back (dumplings on Discord). Claude Desktop's `Check` judges only the set of folders whose Claude-3p it ran in last (`desktopRead`, by `desktopdir.LastRun`), every set when it ran in none: magpie writes both of an MSIX install's sets, and 2.31226 reads the real `%LOCALAPPDATA%\Claude-3p`, so the package's copy being emptied is not Desktop off magpie. - `unreachable` never sets anything: the config is right, and the page's pill only says what has to listen. The exception is an address a WSL distro reached Windows at before (`distro.Was`, kept in `wsl.json`) while it reaches Windows at another now: the pill offers that one, and `Reapply` moves the config there (`Agent.move`, Codex's `codexMoveGateway`). An address no distro was seen at is the user's own and is never moved. An unknown answer (no probe yet) and a gateway down on loopback too are not drift. Tests stub `reachProbe` in `TestMain`. diff --git a/help_cli.go b/help_cli.go new file mode 100644 index 000000000..d6d83e356 --- /dev/null +++ b/help_cli.go @@ -0,0 +1,135 @@ +package main + +import ( + "fmt" + "strconv" + "strings" + + "github.com/yetone/magpie/internal/agent" +) + +// helpAsked is whether args ask for help rather than for the command to +// run: -h or --help anywhere, or help as the word after the command. It +// is looked at before run does anything, since a command that took +// --help for a value acted on it: `magpie snow --help` set Snow's model +// to "--help", which took magpie out of it (#1457), and `magpie serve +// --help` started a gateway. +func helpAsked(args []string) bool { + // what magpie is started with by others (Claude Code's MCP helper, the + // Agents page's dry run, a link, Windows' -Embedding) never carries + // an exact -h, --help or help + for _, a := range args { + if a == "-h" || a == "--help" { + return true + } + } + return len(args) > 1 && args[1] == "help" +} + +// helpFor is what `magpie --help` prints: the command's own +// usage where it has one, its lines of magpie's usage otherwise, an +// agent's forms and fields for an agent, and the whole usage for +// anything else. +func helpFor(args []string) string { + cmd := args[0] + switch cmd { + case "-h", "--help", "help": + return usage + case "model": + return modelUsage + case "group", "groups": + if len(args) > 1 && (args[1] == "rule" || args[1] == "rules") { + return ruleUsage + } + return groupUsage + case "library", "lib": + return " " + libraryUsage + case "plugin", "plugins": + return pluginUsage + case "quota", "quotas": + return quotaUsage + case "sessions": + return sessionsUsage + case "search": + return searchUsage + case "visible": + return visibleUsage + case "webdav", "dav": + return webdavUsage + case "s3": + return s3Usage + case "claude-code": + return claudeCodeUsage + case "list": + cmd = "ls" + case "account": + cmd = "accounts" + case "app", "gui": + cmd = "" + } + if cmd != "" && !strings.HasPrefix(cmd, "-") { + if lines := usageLines(cmd); lines != "" { + return lines + } + } + if a, err := agent.Find(cmd); err == nil && cmd != "" { + return agentHelp(a) + } + return usage +} + +// usageLines are the lines of magpie's usage for `magpie `, with the +// lines that carry on from them. +func usageLines(cmd string) string { + var b strings.Builder + in := false + for _, l := range strings.Split(usage, "\n") { + if rest, ok := strings.CutPrefix(l, " magpie "); ok { + in = rest == cmd || strings.HasPrefix(rest, cmd+" ") + } else if !strings.HasPrefix(l, " ") { + in = false + } + if in { + b.WriteString(l + "\n") + } + } + return b.String() +} + +// agentHelp is `magpie --help`: the forms that set it, and its +// fields. +func agentHelp(a *agent.Agent) string { + var b strings.Builder + id := a.ID + fmt.Fprintf(&b, "%s\n\n", a.Name) + fmt.Fprintf(&b, " magpie %s show it\n", id) + if len(a.Fields) == 0 { + return b.String() + } + fmt.Fprintf(&b, " magpie %s set its model (magpie models %s lists them)\n", id, id) + fmt.Fprintf(&b, " magpie %s set another field\n", id) + fmt.Fprintf(&b, " magpie %s default take magpie out: back on what it had before\n", id) + fmt.Fprintf(&b, " magpie %s default that field back to its own default\n", id) + var keys []string + for _, f := range a.Fields { + keys = append(keys, f.Key) + } + fmt.Fprintf(&b, "\nfields: %s\n", strings.Join(keys, ", ")) + return b.String() +} + +// flagArg is an argument to `magpie …` that is a flag, which no +// agent form takes: it is said to be one, rather than set as a model or a +// field's value. A negative number is a value. +func flagArg(args []string) string { + for _, a := range args { + if !strings.HasPrefix(a, "-") { + continue + } + if _, err := strconv.ParseFloat(a, 64); err == nil { + continue + } + return a + } + return "" +} diff --git a/help_cli_test.go b/help_cli_test.go new file mode 100644 index 000000000..4b7305622 --- /dev/null +++ b/help_cli_test.go @@ -0,0 +1,240 @@ +package main + +import ( + "go/ast" + "go/parser" + "go/token" + "io" + "io/fs" + "os" + "path/filepath" + "reflect" + "strconv" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/agent" +) + +// helpHome points the home and every config, cache and data folder into +// one new folder, and gives it. +func helpHome(t *testing.T) string { + t.Helper() + root := t.TempDir() + for k, v := range map[string]string{ + "HOME": root, "USERPROFILE": root, + "XDG_CONFIG_HOME": filepath.Join(root, ".config"), + "XDG_CACHE_HOME": filepath.Join(root, ".cache"), + "XDG_DATA_HOME": filepath.Join(root, ".local", "share"), + "XDG_STATE_HOME": filepath.Join(root, ".local", "state"), + "APPDATA": filepath.Join(root, "AppData", "Roaming"), + "LOCALAPPDATA": filepath.Join(root, "AppData", "Local"), + "SNOW_CONFIG_DIR": "", + "DSH_HOME": "", + } { + t.Setenv(k, v) + } + return root +} + +// tree is every file and folder under root, with each file's bytes and +// time. +func tree(t *testing.T, root string) map[string]string { + t.Helper() + out := map[string]string{} + filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return nil + } + rel, _ := filepath.Rel(root, p) + if d.IsDir() { + out[rel] = "dir" + return nil + } + b, _ := os.ReadFile(p) + info, _ := d.Info() + out[rel] = string(b) + "@" + info.ModTime().String() + return nil + }) + return out +} + +// runOut runs magpie with args and gives what it printed; a run that +// doesn't come back in time (a gateway started, a window waited on) fails +// the test. +func runOut(t *testing.T, args ...string) (string, error) { + t.Helper() + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + old := os.Stdout + os.Stdout = w + var out strings.Builder + read := make(chan struct{}) + go func() { + b, _ := io.ReadAll(r) + out.Write(b) + close(read) + }() + done := make(chan error, 1) + go func() { done <- run(args) }() + select { + case err = <-done: + case <-time.After(20 * time.Second): + os.Stdout = old + t.Fatalf("magpie %s didn't come back: it ran", strings.Join(args, " ")) + } + w.Close() + os.Stdout = old + <-read + r.Close() + return out.String(), err +} + +// runCommands are the commands run's switch dispatches on, read from +// main.go, so a command added there is covered without a list to keep. +func runCommands(t *testing.T) []string { + t.Helper() + f, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0) + if err != nil { + t.Fatal(err) + } + var cmds []string + for _, d := range f.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Name.Name != "run" { + continue + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + sw, ok := n.(*ast.SwitchStmt) + if !ok { + return true + } + if ix, ok := sw.Tag.(*ast.IndexExpr); !ok || types(ix) != "args[0]" { + return true + } + for _, s := range sw.Body.List { + for _, e := range s.(*ast.CaseClause).List { + if lit, ok := e.(*ast.BasicLit); ok { + v, _ := strconv.Unquote(lit.Value) + cmds = append(cmds, v) + } + } + } + return false + }) + } + if len(cmds) < 40 { + t.Fatalf("read %d commands from run's switch: %v", len(cmds), cmds) + } + return append(cmds, "healthcheck") +} + +func types(ix *ast.IndexExpr) string { + id, ok := ix.X.(*ast.Ident) + lit, ok2 := ix.Index.(*ast.BasicLit) + if !ok || !ok2 { + return "" + } + return id.Name + "[" + lit.Value + "]" +} + +// --help, -h or help after any command, and every agent, in any place, +// prints its usage and does nothing else: no file under the home is +// written and nothing is started. `magpie snow --help` set Snow's model to +// "--help" and took magpie out of it (#1457), and `magpie serve --help` +// ran a gateway. +func TestHelpOnEveryCommandDoesNothing(t *testing.T) { + root := helpHome(t) + cmds := runCommands(t) + for _, a := range agent.All() { + cmds = append(cmds, a.ID) + } + before := tree(t, root) + for _, c := range cmds { + t.Run(c, func(t *testing.T) { + for _, args := range [][]string{ + {c, "--help"}, {c, "-h"}, {c, "help"}, + {c, "x", "--help"}, {c, "x", "y", "-h"}, {c, "--help", "x"}, + } { + out, err := runOut(t, args...) + if err != nil { + t.Errorf("magpie %s: %v", strings.Join(args, " "), err) + } + if !strings.Contains(out, "magpie") && !strings.Contains(out, "usage") { + t.Errorf("magpie %s printed no usage: %q", strings.Join(args, " "), out) + } + if got := tree(t, root); !reflect.DeepEqual(got, before) { + t.Fatalf("magpie %s wrote under the home:\nbefore %v\nafter %v", strings.Join(args, " "), before, got) + } + } + }) + } +} + +// The reporter's case (#1457, blackrion): Snow on magpie's profile, then +// `magpie snow --help` and its other forms. Each prints Snow's usage, a +// flag no agent form takes is refused, and Snow's files stay as they were. +func TestAgentHelpLeavesSnowWired(t *testing.T) { + groupsHome(t) + t.Setenv("SNOW_CONFIG_DIR", "") + dir := filepath.Join(os.Getenv("HOME"), ".snow") + os.MkdirAll(filepath.Join(dir, "profiles"), 0o755) + own := `{ + "snowcfg": { + "baseUrl": "https://idealab.example.com/v1", + "apiKey": "team-key", + "requestMethod": "chat", + "advancedModel": "glm-5", + "basicModel": "glm-5" + } +}` + for f, s := range map[string]string{ + "profiles/default.json": own, + "config.json": own, + "active-profile.json": "{\n \"activeProfile\": \"default\"\n}", + } { + if err := os.WriteFile(filepath.Join(dir, f), []byte(s), 0o644); err != nil { + t.Fatal(err) + } + } + if _, err := runOut(t, "snow", "a/m"); err != nil { + t.Fatal(err) + } + before := tree(t, dir) + if _, ok := before[filepath.Join("profiles", "magpie.json")]; !ok { + t.Fatalf("not wired: %v", before) + } + for _, args := range [][]string{ + {"snow", "--help"}, {"snow", "-h"}, {"snow", "help"}, {"snow", "model", "--help"}, {"snow-cli", "--help"}, + } { + out, err := runOut(t, args...) + if err != nil || !strings.Contains(out, "magpie snow ") { + t.Errorf("magpie %s: %v %q", strings.Join(args, " "), err, out) + } + if got := tree(t, dir); !reflect.DeepEqual(got, before) { + t.Fatalf("magpie %s changed Snow's files:\nbefore %v\nafter %v", strings.Join(args, " "), before, got) + } + } + for _, args := range [][]string{ + {"snow", "--verbose"}, {"snow", "model", "--x"}, {"snow", "-"}, {"snow", "effort", "--high"}, + } { + _, err := runOut(t, args...) + if err == nil || !strings.Contains(err.Error(), "nothing was changed") { + t.Errorf("magpie %s: %v", strings.Join(args, " "), err) + } + if got := tree(t, dir); !reflect.DeepEqual(got, before) { + t.Fatalf("magpie %s changed Snow's files:\nbefore %v\nafter %v", strings.Join(args, " "), before, got) + } + } + // a model no profile of the user's is on, typed without a flag, is + // refused by Snow itself the same way + if _, err := runOut(t, "snow", "nonsense"); err == nil { + t.Error("magpie snow nonsense taken") + } + if got := tree(t, dir); !reflect.DeepEqual(got, before) { + t.Fatalf("magpie snow nonsense changed Snow's files:\nbefore %v\nafter %v", before, got) + } +} diff --git a/internal/agent/disconnect_test.go b/internal/agent/disconnect_test.go index be1d1761c..72449e703 100644 --- a/internal/agent/disconnect_test.go +++ b/internal/agent/disconnect_test.go @@ -219,3 +219,34 @@ func TestDisconnectUnwiredLeavesConfig(t *testing.T) { t.Fatalf("changed:\n%s\nwant\n%s", got, was) } } + +// An auth Gemini CLI doesn't know, set on its provider field, is refused +// before magpie is taken out. `magpie gemini ` sets that field (it is the first), and took Gemini CLI off magpie, +// its sign-in and key put back, before saying the auth was unknown: the +// sibling of `magpie snow --help` (#1457). +func TestGeminiUnknownAuthChangesNothing(t *testing.T) { + home, _ := codexHome(t, "", "") + dir := filepath.Join(home, ".gemini") + os.MkdirAll(dir, 0o755) + os.WriteFile(filepath.Join(dir, "settings.json"), []byte(`{"security":{"auth":{"selectedType":"gemini-api-key"}},"model":{"name":"gemini-2.5-pro"}}`), 0o644) + os.WriteFile(filepath.Join(dir, ".env"), []byte("GEMINI_API_KEY=mine\n"), 0o600) + g := gemini(home) + if err := g.Apply("model", "fake/m1"); err != nil { + t.Fatal(err) + } + read := func() string { + s, _ := os.ReadFile(filepath.Join(dir, "settings.json")) + e, _ := os.ReadFile(filepath.Join(dir, ".env")) + return string(s) + "\n" + string(e) + } + was, vals := read(), g.Values() + for _, v := range []string{"nonsense-model", "--help"} { + if err := g.Field("provider").Set(v); err == nil { + t.Errorf("%q taken", v) + } + if got := read(); got != was || !g.Wired() || !reflect.DeepEqual(g.Values(), vals) { + t.Fatalf("%q changed Gemini CLI:\n%s\nwas\n%s", v, got, was) + } + } +} diff --git a/internal/agent/gemini.go b/internal/agent/gemini.go index e2a4474b2..f6e3fbc34 100644 --- a/internal/agent/gemini.go +++ b/internal/agent/gemini.go @@ -135,6 +135,15 @@ func geminiIn(at place) *Agent { } return fmt.Errorf("pick a model via magpie instead; that routes Gemini CLI through the gateway") } + // an auth it doesn't know is refused before magpie is taken out: + // `magpie gemini ` comes here, and + // unrouted Gemini CLI first, as `magpie snow --help` took magpie + // out of Snow (#1457) + switch id { + case "", "custom", "google", "vertex", "api-key": + default: + return fmt.Errorf("%q is neither one of Gemini CLI's models nor an auth (google, api-key, vertex): nothing was changed", id) + } if err := unroute(); err != nil { return err } diff --git a/internal/agent/snow.go b/internal/agent/snow.go index 86c197cc8..905176155 100644 --- a/internal/agent/snow.go +++ b/internal/agent/snow.go @@ -29,6 +29,7 @@ package agent import ( "encoding/json" "errors" + "fmt" "io/fs" "os" "path/filepath" @@ -263,7 +264,11 @@ func snowIn(at place) *Agent { Key: "model", Label: "model", Get: get, Set: func(v string) error { - if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) { + ref, through := strings.CutPrefix(v, magpieID+"/") + if through && !isMagpie(ref) { + return fmt.Errorf("%s isn't a model in magpie's catalog (magpie models snow lists them)", ref) + } + if through { base := active() if !onOurs() { if b, err := edit.Read(ours); err == nil && b != nil && !snowIsOurs(b) { @@ -319,21 +324,16 @@ func snowIn(at place) *Agent { return mirror(name) } // leaving magpie's profile: for the user's profile with - // that model, or the one they were on + // that model. A model no profile of theirs is on is + // refused rather than written into one on the way out: + // `magpie snow --help` took magpie out of Snow and left + // "--help" as the model of the profile it went back to + // (#1457). An empty value goes back to the one they were on. to := "" if v != "" { - was := stashLoad()[keyActive] - to = snowFindProfile(profiles, v, was) + to = snowFindProfile(profiles, v, stashLoad()[keyActive]) if to == "" { - to = was - if to == "" { - to = "default" - } - if _, err := os.Stat(profileOf(to)); err == nil { - if err := edit.SetJSON(profileOf(to), edit.KV{Path: "snowcfg.advancedModel", Value: v}); err != nil { - return err - } - } + return fmt.Errorf("%q is neither a model through magpie nor the model of one of Snow CLI's profiles: nothing was changed (magpie models snow lists them; magpie snow default goes back to your own profile)", v) } } return leave(to) diff --git a/internal/agent/snow_test.go b/internal/agent/snow_test.go index 5d06c2d75..bf6dba57c 100644 --- a/internal/agent/snow_test.go +++ b/internal/agent/snow_test.go @@ -4,6 +4,7 @@ import ( "encoding/json" "os" "path/filepath" + "reflect" "strings" "testing" @@ -656,3 +657,53 @@ func TestSnowThinking(t *testing.T) { t.Fatal("the user's profile was rewritten") } } + +// snowFiles is every file under dir, by its path there. +func snowFiles(t *testing.T, dir string) map[string]string { + t.Helper() + out := map[string]string{} + filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error { + if err == nil && !d.IsDir() { + rel, _ := filepath.Rel(dir, p) + out[rel] = readFile(p) + } + return nil + }) + return out +} + +// A model Snow has no profile on, set while on magpie's, is refused and +// changes nothing: `magpie snow --help` took magpie out of Snow (deleted +// profiles/magpie.json, put back the active profile) and wrote "--help" +// as the model of the profile it went back to (#1457, blackrion). An +// unknown model through magpie is refused the same way, on and off it. +func TestSnowUnknownModelChangesNothing(t *testing.T) { + _, dir := snowHome(t) + snowUser(t, dir) + a, _ := Find("snow") + if err := a.Field("model").Set("magpie/nope/x"); err == nil { + t.Error("an unknown model through magpie taken off magpie") + } + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + before := snowFiles(t, dir) + for _, v := range []string{"--help", "-h", "nonsense-model", "magpie/nope/x"} { + if err := a.Field("model").Set(v); err == nil { + t.Errorf("%q taken", v) + } + if got := snowFiles(t, dir); !reflect.DeepEqual(got, before) { + t.Fatalf("%q changed Snow's files:\nbefore %v\nafter %v", v, before, got) + } + } + if got := a.Values()["model"]; got != "magpie/deepseek/pro" { + t.Fatalf("model %q", got) + } + // a model of a profile of theirs still takes Snow there + if err := a.Apply("model", "kimi-k3"); err != nil { + t.Fatal(err) + } + if got := snowActive(dir); got != "work" { + t.Fatalf("active %q, want work", got) + } +} diff --git a/main.go b/main.go index f2b341d66..44b62201b 100644 --- a/main.go +++ b/main.go @@ -49,6 +49,7 @@ const usage = `magpie — one place to pick every agent's model magpie set another field e.g. magpie codex effort high magpie default take magpie out: the agent back on what it had before magpie default that field back to the agent's own default + magpie --help what a command or an agent takes; -h or --help anywhere does nothing else magpie save snapshot every agent's settings as a profile magpie use apply a profile @@ -189,6 +190,12 @@ func runTUI() error { var tuiRun = tui.Run func run(args []string) error { + // before anything is read, moved or started: --help on any command + // prints its usage and does nothing else + if helpAsked(args) { + fmt.Println(strings.TrimRight(helpFor(args), "\n")) + return nil + } if len(args) > 0 && args[0] == "healthcheck" { return healthcheck() // every few seconds in a container: nothing else } @@ -357,6 +364,11 @@ func run(args []string) error { if err != nil { return err } + // no agent form takes a flag: one is never set as a model or a value + // (`magpie snow --verbose` would take magpie out of Snow, #1457) + if f := flagArg(args[1:]); f != "" { + return fmt.Errorf("unknown flag %s: nothing was changed\n\n%s", f, strings.TrimRight(agentHelp(a), "\n")) + } if len(a.Fields) == 0 && a.Import != nil { // `magpie cindy`: it takes magpie through its own link, confirmed there if len(args) > 1 {