diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 81325db53..41a1fc75f 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -710,9 +710,25 @@ func goose(home, cfg string) *Agent { } get := func(k string) (string, bool) { return edit.GetYAMLTop(path, k) } set := func(kvs ...edit.KV) error { return edit.SetYAMLTop(path, kvs...) } + provider := gooseProviderPath(path) return &Agent{ ID: "goose", Name: "Goose", Icon: "goose", Bin: "goose", Dir: filepath.Dir(path), Path: path, UA: []string{"goose"}, + Check: func() string { + if p, _ := get("GOOSE_PROVIDER"); p != gooseProviderID { + return "" + } + return wiringOff("Goose", provider, func(k string) (string, bool) { return edit.GetJSON(provider, k) }, + "base_url", gatewayV1(), "headers.Authorization", "Bearer "+gateway.Token) + }, + Sync: func() error { return syncGooseProvider(provider) }, + // goose loads custom_providers when it starts + Notice: func() string { + if p, _ := get("GOOSE_PROVIDER"); p == gooseProviderID && Running(`Goose\.app/`, `(^|/)goose( |$)`) { + return "Goose loads its providers at start-up — quit and reopen Goose (and open goose sessions) to use magpie's models." + } + return "" + }, // a goose on PATH may be pressly's database migration tool, a Go // program; Block's goose is Rust, so a Go goose is not the agent detect: func() bool { @@ -727,12 +743,23 @@ func goose(home, cfg string) *Agent { Get: pairGet(get, "GOOSE_PROVIDER", "GOOSE_MODEL"), Set: func(v string) error { if v == "" { - return edit.DelYAMLTop(path, "GOOSE_PROVIDER", "GOOSE_MODEL") + if err := edit.DelYAMLTop(path, "GOOSE_PROVIDER", "GOOSE_MODEL"); err != nil { + return err + } + return removeGooseProvider(provider) + } + // a model of magpie's: magpie as a custom provider of + // Goose's, each model with its window and whether Goose + // can send it a thinking level (see goose.go) + if ref, ok := strings.CutPrefix(v, gooseProviderID+"/"); ok && isMagpie(ref) { + if err := writeGooseProvider(provider); err != nil { + return err + } } return pairSet(set, "GOOSE_PROVIDER", "GOOSE_MODEL")(v) }, Options: func(cur map[string]string) []Option { - return ownOptions("", cur["model"], "anthropic", "openai", "google", "openrouter") + return append(ownOptions("", cur["model"], "anthropic", "openai", "google", "openrouter"), viaMagpie("goose", gooseProviderID+"/")...) }, }, { // GOOSE_THINKING_EFFORT, the effort goose asks of a model that diff --git a/internal/agent/goose.go b/internal/agent/goose.go new file mode 100644 index 000000000..e8951ce46 --- /dev/null +++ b/internal/agent/goose.go @@ -0,0 +1,117 @@ +package agent + +import ( + "encoding/json" + "errors" + "io/fs" + "os" + "path/filepath" + "regexp" + + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/gateway" +) + +// Goose (Block's goose, its CLI and desktop app alike) reaches magpie as a +// custom provider: a JSON file of its own in custom_providers beside +// config.yaml, named by the provider's id, which goose loads at start-up +// (crates/goose/src/config/declarative_providers.rs). Its schema is +// DeclarativeProviderConfig (crates/goose-providers/src/declarative.rs), and +// each of its models a ModelInfo (crates/goose-provider-types/src/base.rs): +// +// - context_limit is the window goose's ContextLimitResolver takes for the +// model before anything else but GOOSE_CONTEXT_LIMIT +// (crates/goose-provider-types/src/context_limit.rs). Without it goose +// guesses from its own registry by the model's name, or 128K. +// - reasoning is what the desktop app's model picker asks before it shows +// its Thinking Level (fetchModelReasoning, ui/desktop/src/components/ +// settings/models/modelInterface.ts); a model declared without it is +// taken for one that doesn't think. +// +// dynamic_models false keeps goose to this list rather than the gateway's +// /v1/models (every model, none of their windows), and +// skip_canonical_filtering keeps magpie's order and models goose's registry +// doesn't know. + +// gooseProviderID is magpie's file in Goose's custom_providers and the +// provider GOOSE_PROVIDER names. +const gooseProviderID = magpieID + +// gooseThinks matches the model names goose sends its thinking level for on +// an OpenAI-compatible provider: OpenAI's reasoning models, as goose's +// is_openai_responses_model tells them (crates/goose-provider-types/src/ +// formats/openai.rs). For any other model goose keeps the level to itself — +// thinking_effort is one of its own request params, never sent — so a +// level offered for it would change nothing; it is declared without +// reasoning rather than shown a picker that does nothing. +var gooseThinks = regexp.MustCompile(`(?i)(?:^|[-/])(?:o\d+(?:$|-)|gpt-(?:5|6)(?:$|[-.]))`) + +// gooseProviderPath is magpie's custom provider file for the Goose whose +// config.yaml is at cfg. +func gooseProviderPath(cfg string) string { + return filepath.Join(filepath.Dir(cfg), "custom_providers", gooseProviderID+".json") +} + +// gooseProviderJSON is magpie as a Goose custom provider, its models the +// catalog as Goose is shown it. +func gooseProviderJSON() map[string]any { + models := []map[string]any{} + for _, m := range magpieModels("goose") { + e := map[string]any{"name": m.ID, "reasoning": gooseThinks.MatchString(m.ID)} + if m.Context > 0 { + e["context_limit"] = m.Context + } + models = append(models, e) + } + p := map[string]any{ + "name": gooseProviderID, + "engine": "openai", + "display_name": "magpie", + "description": "Every model magpie has, through its local gateway", + "api_key_env": "", + "base_url": gatewayV1(), + "headers": map[string]any{"Authorization": "Bearer " + gateway.Token}, + "requires_auth": false, + "skip_canonical_filtering": true, + "models": models, + } + // goose refuses a provider whose static list is empty + if len(models) > 0 { + p["dynamic_models"] = false + } + return p +} + +// writeGooseProvider writes magpie's custom provider file for Goose. +func writeGooseProvider(path string) error { + b, err := json.MarshalIndent(gooseProviderJSON(), "", " ") + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + return edit.WriteAtomic(path, append(b, '\n')) +} + +// syncGooseProvider rewrites magpie's custom provider file for Goose with +// the catalog as it is now, where magpie wrote one and it differs. +func syncGooseProvider(path string) error { + raw, err := edit.Read(path) + if err != nil || raw == nil { + return nil + } + if sameJSON(string(raw), gooseProviderJSON()) { + return nil + } + return writeGooseProvider(path) +} + +// removeGooseProvider takes magpie's custom provider file away once Goose's +// model is no longer one of magpie's. +func removeGooseProvider(path string) error { + if err := edit.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) { + return err + } + return nil +} diff --git a/internal/agent/goose_test.go b/internal/agent/goose_test.go index 34ddc7626..f0cd993b6 100644 --- a/internal/agent/goose_test.go +++ b/internal/agent/goose_test.go @@ -1,11 +1,19 @@ package agent import ( + "encoding/json" "os" "os/exec" "path/filepath" "runtime" + "slices" + "strings" "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/provider" ) // A goose on PATH that is pressly's migration tool (a Go program) is not the @@ -49,3 +57,98 @@ func TestGooseDetectSkipsGoGoose(t *testing.T) { t.Fatal("goose's config dir not detected") } } + +// Goose is offered magpie's models, and picking one makes magpie a custom +// provider of Goose's that hands it each model's window and says which +// models Goose can send a thinking level (wani on Discord: Goose's GUI +// offered no thinking level and had the context wrong). A model Goose sends +// no level for (GLM, on an OpenAI-compatible provider) is not said to think. +func TestGooseRunsOnMagpie(t *testing.T) { + home := syncHome(t) + t.Setenv("APPDATA", filepath.Join(home, "AppData", "Roaming")) + if err := provider.Save(provider.Provider{ID: "oa", Name: "OA", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"gpt-5.5"}}); err != nil { + t.Fatal(err) + } + a := goose(home, filepath.Join(home, ".config")) + f := a.Fields[0] + var vals []string + for _, o := range f.Options(map[string]string{}) { + vals = append(vals, o.Value) + } + if !slices.Contains(vals, "magpie/relay/glm-4.6") || !slices.Contains(vals, "magpie/oa/gpt-5.5") { + t.Fatalf("magpie's models not offered: %v", vals) + } + if err := f.Set("magpie/relay/glm-4.6"); err != nil { + t.Fatal(err) + } + if got := f.Get(); got != "magpie/relay/glm-4.6" { + t.Fatalf("model = %q", got) + } + file := gooseProviderPath(a.Path) + if filepath.Dir(filepath.Dir(file)) != filepath.Dir(a.Path) { + t.Fatalf("custom provider at %s, config at %s", file, a.Path) + } + var p struct { + Name string `json:"name"` + Engine string `json:"engine"` + BaseURL string `json:"base_url"` + APIKeyEnv *string `json:"api_key_env"` + RequiresAuth *bool `json:"requires_auth"` + DynamicModels *bool `json:"dynamic_models"` + Skip bool `json:"skip_canonical_filtering"` + Headers map[string]string `json:"headers"` + Models []struct { + Name string `json:"name"` + Context int `json:"context_limit"` + Reasoning bool `json:"reasoning"` + } `json:"models"` + } + if err := json.Unmarshal([]byte(readFile(file)), &p); err != nil { + t.Fatalf("%v: %s", err, readFile(file)) + } + if p.Name != "magpie" || p.Engine != "openai" || p.BaseURL != gatewayV1() || + p.Headers["Authorization"] != "Bearer "+gateway.Token || p.APIKeyEnv == nil || *p.APIKeyEnv != "" || + p.RequiresAuth == nil || *p.RequiresAuth || p.DynamicModels == nil || *p.DynamicModels || !p.Skip { + t.Fatalf("provider: %s", readFile(file)) + } + think := map[string]bool{} + window := map[string]int{} + for _, m := range p.Models { + think[m.Name], window[m.Name] = m.Reasoning, m.Context + } + if window["relay/glm-4.6"] != 204800 { + t.Fatalf("glm window = %d: %s", window["relay/glm-4.6"], readFile(file)) + } + if think["relay/glm-4.6"] || !think["oa/gpt-5.5"] { + t.Fatalf("reasoning: %v", think) + } + if c := a.Check(); c != "" { + t.Fatalf("check: %s", c) + } + if err := edit.SetJSON(file, edit.KV{Path: "base_url", Value: "http://elsewhere/v1"}); err != nil { + t.Fatal(err) + } + if a.Check() == "" { + t.Fatal("a rewritten base_url not noticed") + } + + // the catalog as it is now reaches the file + writeFile(t, catalog.CachePath(), `{"zai":{"models":{"glm-4.6":{"id":"glm-4.6","name":"GLM-4.6","limit":{"context":131072}}}}}`) + catalog.Reset() + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if !strings.Contains(readFile(file), `"context_limit": 131072`) || a.Check() != "" { + t.Fatalf("not synced: %s", readFile(file)) + } + + if err := f.Set(""); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(file); !os.IsNotExist(err) { + t.Fatalf("custom provider left behind: %v", err) + } + if f.Get() != "" { + t.Fatalf("model left: %q", f.Get()) + } +}