diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 64f10b0bf..2371297b4 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -2,7 +2,9 @@ package agent import ( "encoding/json" + "errors" "fmt" + "io/fs" "os" "os/exec" "path/filepath" @@ -146,6 +148,37 @@ func pairGet(get func(string) (string, bool), pKey, mKey string) func() string { } } +// magpieEffort is the reasoning_effort of the models. object obj in +// Crush's data file when magpie set it: the object names magpie's provider +// and has no field but provider, model and reasoning_effort, which is all +// magpie ever writes there. An object Crush's picker saved is not magpie's. +func magpieEffort(data, obj, magpieID string) (string, bool) { + raw, ok := edit.GetJSON(data, obj) + if !ok { + return "", false + } + var cur map[string]json.RawMessage + if json.Unmarshal([]byte(raw), &cur) != nil { + return "", false + } + var prov, effort string + for k, v := range cur { + switch k { + case "provider": + json.Unmarshal(v, &prov) + case "model": + case "reasoning_effort": + json.Unmarshal(v, &effort) + default: + return "", false + } + } + if prov != magpieID || effort == "" { + return "", false + } + return effort, true +} + func pairSet(set func(...edit.KV) error, pKey, mKey string) func(string) error { return func(v string) error { p, m, ok := strings.Cut(v, "/") @@ -967,25 +1000,64 @@ func copilot(home string) *Agent { func crush(home, cfg string) *Agent { path := filepath.Join(cfg, "crush", "crush.json") + // Crush saves the models its own picker chooses to its data file, and + // reads that after crush.json, so a pick there wins over one in path. + // The picks are read as Crush merges the two files and written where + // Crush writes them; magpie's provider stays in path, beside the + // library's MCP servers. + data := filepath.Join(home, ".local", "share", "crush", "crush.json") + if dir := os.Getenv("XDG_DATA_HOME"); dir != "" { + data = filepath.Join(dir, "crush", "crush.json") + } if runtime.GOOS == "windows" { if app := os.Getenv("LOCALAPPDATA"); app != "" { path = filepath.Join(app, "crush", "crush.json") } + // %LOCALAPPDATA%\crush is Crush's data folder there + data = path } - return crushAt(here(home), path) + return crushAt(here(home), path, data) } // crushIn is Crush in a WSL distro: ~/.config/crush/crush.json, Linux's // place for it. func crushIn(at place) *Agent { - return crushAt(at, filepath.Join(at.home, ".config", "crush", "crush.json")) + // Crush's data file is in Linux's place there too + return crushAt(at, filepath.Join(at.home, ".config", "crush", "crush.json"), + filepath.Join(at.home, ".local", "share", "crush", "crush.json")) } -// crushAt is Crush with its config at path, reaching the gateway as at does. -func crushAt(at place, path string) *Agent { +// crushAt is Crush with its config at path and its data file at data, +// reaching the gateway as at does. +func crushAt(at place, path, data string) *Agent { provider := func() any { return magpieProviderJSONAt("crush", "crush", at.gw()) } get := func(k string) (string, bool) { return edit.GetJSON(path, k) } set := func(kvs ...edit.KV) error { return edit.SetJSON(path, kvs...) } + pick := func(k string) (string, bool) { + if v, ok := edit.GetJSON(data, k); ok { + return v, true + } + return get(k) + } + setPick := func(kvs ...edit.KV) error { + // Crush keeps API keys in its data file, so one magpie is first to + // make is made readable by its owner only + if _, err := os.Lstat(data); errors.Is(err, fs.ErrNotExist) { + if err := os.MkdirAll(filepath.Dir(data), 0o755); err != nil { + return err + } + if err := os.WriteFile(data, []byte("{}\n"), 0o600); err != nil { + return err + } + } + return edit.SetJSON(data, kvs...) + } + delPick := func(k string) error { + if err := edit.DelJSON(data, k); err != nil { + return err + } + return edit.DelJSON(path, k) + } opts := func(key string) func(map[string]string) []Option { return func(cur map[string]string) []Option { var extra []string @@ -1004,15 +1076,38 @@ func crushAt(at place, path string) *Agent { return append(ownOptions("", cur[key], extra...), viaMagpie("crush", magpieID+"/")...) } } + // replacePick puts v in place of the whole models. object in the + // data file. Crush's own picker saves its per-model settings there + // (max_tokens, think, reasoning_effort, sampling, provider_options), + // and Crush applies them to whatever model the object names, so they + // must not stay attached to the model magpie picks: a max_tokens meant + // for another model can go upstream as an over-limit request. Only an + // effort magpie set itself is kept: one on the large pick when that pick + // is already magpie's and carries nothing Crush adds. + replacePick := func(obj string) func(string) error { + return func(v string) error { + p, m, ok := strings.Cut(v, "/") + if !ok || p == "" || m == "" { + return fmt.Errorf("expected provider/model, got %q", v) + } + next := map[string]any{"provider": p, "model": m} + if obj == "models.large" { + if e, ok := magpieEffort(data, obj, magpieID); ok { + next["reasoning_effort"] = e + } + } + return setPick(edit.KV{Path: obj, Value: next}) + } + } setter := func(pKey, mKey string) func(string) error { - pair := pairSet(set, pKey, mKey) + pair := replacePick(strings.TrimSuffix(pKey, ".provider")) return func(v string) error { if v == "" { - if err := edit.DelJSON(path, strings.TrimSuffix(pKey, ".provider")); err != nil { + if err := delPick(strings.TrimSuffix(pKey, ".provider")); err != nil { return err } - large := pairGet(get, "models.large.provider", "models.large.model")() - small := pairGet(get, "models.small.provider", "models.small.model")() + large := pairGet(pick, "models.large.provider", "models.large.model")() + small := pairGet(pick, "models.small.provider", "models.small.model")() if usesMagpie(large, small) { return nil } @@ -1030,8 +1125,8 @@ func crushAt(at place, path string) *Agent { ID: "crush", Name: "Crush", Icon: "crush", Bin: "crush", Dir: filepath.Dir(path), Path: path, UA: []string{"crush"}, Check: func() string { - large, _ := get("models.large.provider") - small, _ := get("models.small.provider") + large, _ := pick("models.large.provider") + small, _ := pick("models.small.provider") if large != magpieID && small != magpieID { return "" } @@ -1042,21 +1137,21 @@ func crushAt(at place, path string) *Agent { return syncJSON(path, "providers."+magpieID, provider) }, Fields: []Field{ - {Key: "model", Label: "large", Get: pairGet(get, "models.large.provider", "models.large.model"), Set: setter("models.large.provider", "models.large.model"), Options: opts("model")}, - {Key: "small", Label: "small", Get: pairGet(get, "models.small.provider", "models.small.model"), Set: setter("models.small.provider", "models.small.model"), Options: opts("small")}, + {Key: "model", Label: "large", Get: pairGet(pick, "models.large.provider", "models.large.model"), Set: setter("models.large.provider", "models.large.model"), Options: opts("model")}, + {Key: "small", Label: "small", Get: pairGet(pick, "models.small.provider", "models.small.model"), Set: setter("models.small.provider", "models.small.model"), Options: opts("small")}, { // the large model's reasoning_effort, which Crush's schema // takes as low, medium or high (for OpenAI-style models) Key: "effort", Label: "effort", - Get: func() string { v, _ := get("models.large.reasoning_effort"); return v }, + Get: func() string { v, _ := pick("models.large.reasoning_effort"); return v }, Set: func(v string) error { if v == "" { - return edit.DelJSON(path, "models.large.reasoning_effort") + return delPick("models.large.reasoning_effort") } - if m, _ := get("models.large.model"); m == "" { + if m, _ := pick("models.large.model"); m == "" { return fmt.Errorf("pick Crush's large model first; the effort is kept with it") } - return set(edit.KV{Path: "models.large.reasoning_effort", Value: v}) + return setPick(edit.KV{Path: "models.large.reasoning_effort", Value: v}) }, Options: func(map[string]string) []Option { return static("low", "medium", "high") }, }, diff --git a/internal/agent/crush_test.go b/internal/agent/crush_test.go new file mode 100644 index 000000000..f4aa8ed7d --- /dev/null +++ b/internal/agent/crush_test.go @@ -0,0 +1,244 @@ +package agent + +import ( + "encoding/json" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/yetone/magpie/internal/edit" +) + +// crushHome is effortHome with Crush's data folder in the sandbox too, and +// the path of the data file Crush reads there: its GlobalConfigData, which +// is ~/.local/share/crush/crush.json, or %LOCALAPPDATA%\crush\crush.json on +// Windows. +func crushHome(t *testing.T) (home, data string) { + t.Helper() + home = effortHome(t) + t.Setenv("XDG_DATA_HOME", "") + t.Setenv("LOCALAPPDATA", filepath.Join(home, "AppData", "Local")) + data = filepath.Join(home, ".local", "share", "crush", "crush.json") + if runtime.GOOS == "windows" { + data = filepath.Join(home, "AppData", "Local", "crush", "crush.json") + } + return home, data +} + +// Crush saves what its own model picker chooses to its data file, and reads +// that after crush.json, so a pick there wins over one in crush.json. Once +// somebody has picked a model in Crush (its first run asks for one), the +// model magpie sets has to go where Crush reads it last, and what magpie +// shows has to be what Crush will use. +func TestCrushPickWhereCrushReadsIt(t *testing.T) { + home, data := crushHome(t) + cr := crush(home, filepath.Join(home, ".config")) + writeFile(t, data, `{"models":{"large":{"model":"m-mine","provider":"mine"}}}`) + + large := cr.Field("model") + if got := large.Get(); got != "mine/m-mine" { + t.Fatalf("large reads %q, not the pick Crush uses", got) + } + if err := large.Set("magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + if p, _ := edit.GetJSON(data, "models.large.provider"); p != "magpie" { + t.Fatalf("Crush still picks %q from its data file:\n%s", p, readFile(data)) + } + if m, _ := edit.GetJSON(data, "models.large.model"); m != "deepseek/pro" { + t.Fatalf("data file model %q:\n%s", m, readFile(data)) + } + if got := large.Get(); got != "magpie/deepseek/pro" { + t.Fatalf("large reads %q", got) + } + // the provider stays where it was, with the library's MCP servers + if _, ok := edit.GetJSON(cr.Path, "providers.magpie.base_url"); !ok { + t.Fatalf("no magpie provider in %s:\n%s", cr.Path, readFile(cr.Path)) + } + if cr.Check() != "" { + t.Fatalf("check: %s", cr.Check()) + } + + // the effort is kept with the pick + effort := cr.Field("effort") + if err := effort.Set("high"); err != nil { + t.Fatal(err) + } + if e, _ := edit.GetJSON(data, "models.large.reasoning_effort"); e != "high" || effort.Get() != "high" { + t.Fatalf("effort %q:\n%s", effort.Get(), readFile(data)) + } + + small := cr.Field("small") + if err := small.Set("magpie/deepseek/flash"); err != nil { + t.Fatal(err) + } + // unset, a pick is gone from both files, and the provider goes with + // the last pick on it + if err := large.Set(""); err != nil { + t.Fatal(err) + } + if large.Get() != "" || effort.Get() != "" { + t.Fatalf("large %q, effort %q after unset:\n%s", large.Get(), effort.Get(), readFile(data)) + } + if _, ok := edit.GetJSON(cr.Path, "providers.magpie"); !ok { + t.Fatal("the provider went while small still uses it") + } + if err := small.Set(""); err != nil { + t.Fatal(err) + } + for _, f := range []string{cr.Path, data} { + if _, ok := edit.GetJSON(f, "models.small"); ok { + t.Fatalf("a small pick is left in %s:\n%s", f, readFile(f)) + } + } + if _, ok := edit.GetJSON(cr.Path, "providers.magpie"); ok { + t.Fatalf("the provider is left with no pick on it:\n%s", readFile(cr.Path)) + } +} + +// A pick magpie wrote to crush.json before it wrote Crush's data file still +// reads as set where Crush has picked nothing itself, and one Crush's own +// pick hides reads as that pick, since it is the one Crush uses. +func TestCrushPickInCrushJSON(t *testing.T) { + home, data := crushHome(t) + cr := crush(home, filepath.Join(home, ".config")) + if cr.Path == data { + t.Skip("crush.json is Crush's data file here") + } + writeFile(t, cr.Path, `{"providers":{"magpie":{"base_url":"x"}},"models":{"large":{"provider":"magpie","model":"deepseek/pro"}}}`) + if got := cr.Field("model").Get(); got != "magpie/deepseek/pro" { + t.Fatalf("large reads %q", got) + } + writeFile(t, data, `{"models":{"large":{"model":"m-mine","provider":"mine"}}}`) + if got := cr.Field("model").Get(); got != "mine/m-mine" { + t.Fatalf("large reads %q, not the pick Crush uses", got) + } +} + +// Crush's picker saves the whole model object in its data file: the model +// and the settings it picked for that model. A model magpie picks takes the +// whole object's place, so none of those settings ride along to it (a +// max_tokens meant for another model would go upstream with magpie's), and +// magpie's effort row doesn't show an effort magpie never set. +func TestCrushPickReplacesCrushsModelObject(t *testing.T) { + home, data := crushHome(t) + cr := crush(home, filepath.Join(home, ".config")) + writeFile(t, data, `{ + "models": { + "large": {"model":"gpt-5","provider":"openai","reasoning_effort":"medium","max_tokens":128000,"think":true,"temperature":0.2,"top_p":0.9,"provider_options":{"x":1}}, + "small": {"model":"gpt-5-mini","provider":"openai","max_tokens":4096,"think":true} + }, + "providers": {"openai": {"api_key": "sk-keep"}}, + "recent_models": {"large": [{"model":"gpt-5","provider":"openai"}]} +}`) + + if err := cr.Field("model").Set("magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + if err := cr.Field("small").Set("magpie/deepseek/flash"); err != nil { + t.Fatal(err) + } + for _, typ := range []string{"large", "small"} { + raw, _ := edit.GetJSON(data, "models."+typ) + var obj map[string]any + if err := json.Unmarshal([]byte(raw), &obj); err != nil { + t.Fatalf("models.%s: %v\n%s", typ, err, readFile(data)) + } + if len(obj) != 2 || obj["provider"] != "magpie" { + t.Fatalf("models.%s after magpie's pick: %s", typ, raw) + } + } + if e := cr.Field("effort").Get(); e != "" { + t.Fatalf("effort row shows %q, which magpie never set", e) + } + // the rest of the data file is Crush's and stays + if k, _ := edit.GetJSON(data, "providers.openai.api_key"); k != "sk-keep" { + t.Fatalf("api key gone:\n%s", readFile(data)) + } + if _, ok := edit.GetJSON(data, "recent_models.large"); !ok { + t.Fatalf("recent_models gone:\n%s", readFile(data)) + } + + // an effort magpie set stays with its next pick on magpie + if err := cr.Field("effort").Set("high"); err != nil { + t.Fatal(err) + } + if err := cr.Field("model").Set("magpie/deepseek/max"); err != nil { + t.Fatal(err) + } + if e := cr.Field("effort").Get(); e != "high" { + t.Fatalf("magpie's own effort %q after a new pick:\n%s", e, readFile(data)) + } + + // once Crush's picker has saved its own object again, magpie's next pick + // drops all of it, the effort Crush saved too + writeFile(t, data, `{"models":{"large":{"model":"deepseek/pro","provider":"magpie","reasoning_effort":"low","max_tokens":64000}}}`) + if err := cr.Field("model").Set("magpie/deepseek/max"); err != nil { + t.Fatal(err) + } + if raw, _ := edit.GetJSON(data, "models.large"); strings.Contains(raw, "max_tokens") || strings.Contains(raw, "reasoning_effort") { + t.Fatalf("Crush's settings ride along: %s", raw) + } +} + +// Crush keeps API keys in its data file, so when magpie is first to make it +// the file is readable by its owner only. +func TestCrushDataFileMadePrivate(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("no unix permission bits") + } + home, data := crushHome(t) + cr := crush(home, filepath.Join(home, ".config")) + if err := cr.Field("model").Set("magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + st, err := os.Stat(data) + if err != nil { + t.Fatal(err) + } + if st.Mode().Perm() != 0o600 { + t.Fatalf("data file mode %v", st.Mode().Perm()) + } +} + +// Crush in a WSL distro has the same data file over its crush.json, in the +// distro's home: /.local/share/crush/crush.json, whatever +// Windows' own XDG_DATA_HOME or LOCALAPPDATA say. A pick made in magpie goes +// there and is read back from there. +func TestCrushInWSLPicksInTheDistrosDataFile(t *testing.T) { + home, _ := crushHome(t) + t.Setenv("XDG_DATA_HOME", filepath.Join(home, "windows-data")) + root := t.TempDir() + d := distro{Name: "Ubuntu", Home: "/home/me", Root: root, Running: true, Mirrored: true} + cr := crushIn(d.place("crush@wsl:Ubuntu")) + data := d.local("/home/me/.local/share/crush/crush.json") + if want := d.local("/home/me/.config/crush/crush.json"); cr.Path != want { + t.Fatalf("config %s, want %s", cr.Path, want) + } + writeFile(t, data, `{"models":{"large":{"model":"m-mine","provider":"mine"}}}`) + + large := cr.Field("model") + if got := large.Get(); got != "mine/m-mine" { + t.Fatalf("large reads %q, not the pick in the distro's data file", got) + } + if err := large.Set("magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + if p, _ := edit.GetJSON(data, "models.large.provider"); p != "magpie" { + t.Fatalf("the distro's Crush still picks %q:\n%s", p, readFile(data)) + } + if got := large.Get(); got != "magpie/deepseek/pro" { + t.Fatalf("large reads %q", got) + } + for _, other := range []string{ + filepath.Join(home, "windows-data", "crush", "crush.json"), + filepath.Join(home, ".local", "share", "crush", "crush.json"), + filepath.Join(home, "AppData", "Local", "crush", "crush.json"), + } { + if _, err := os.Stat(other); err == nil { + t.Fatalf("the distro's pick went to this machine's %s", other) + } + } +} diff --git a/internal/agent/effort_test.go b/internal/agent/effort_test.go index a0270b905..d3d0a4a85 100644 --- a/internal/agent/effort_test.go +++ b/internal/agent/effort_test.go @@ -19,6 +19,8 @@ func effortHome(t *testing.T) string { t.Setenv("USERPROFILE", home) t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + // Crush's data file, the sandbox's rather than the package's shared one + t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share")) // where Windows keeps Goose's, Crush's and Devin's: the sandbox's, never the machine's t.Setenv("APPDATA", filepath.Join(home, "AppData", "Roaming")) t.Setenv("LOCALAPPDATA", filepath.Join(home, "AppData", "Local"))