diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 81dfc637a..194e23127 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -39,6 +39,16 @@ something else shows up as drift. - magpie only removes what it wrote. Anything else in an agent's config stays as it was. - A sync brings magpie's models up to date, not where the agent reaches magpie. Every `Sync` that `SyncCatalog` runs (each start and update of magpie, a provider added) goes through `synced`, which passes each file written through `keptAway` (`edit.Filtered`, [`keptaway.go`](../../internal/agent/keptaway.go)). In a file without the gateway's own address, whose magpie the user pointed at an address on another machine (a NAS's, or this machine's LAN address), and with no address a WSL distro was seen at, that address stays in place of `gateway.URL()`, with the path before magpie's every URL at it had (`awayPath`: a reverse proxy's `/magpie`; on loopback, a local proxy's route where magpie answered or hasn't been asked), and so does the key that went with it in place of magpie's own (coeo91 on Discord: the base URL went back to 127.0.0.1 after an update or restart). An address on this machine's loopback follows the gateway; with more than one address or key gone, the write is left as it is. Picking a model in magpie still points the agent at this magpie, but for Claude Code at a proxy to it (above). ZCode and WorkBuddy keep such an address in their own writers too (`zcodeAddress`, `buddyWriteAt`). - JetBrains Air's `magpie-opencode.json` keeps user-added fields in `provider.magpie`, including nested options, on sync and model picks (`air` in [`air.go`](../../internal/agent/air.go), using `theirsKept` in [`sync.go`](../../internal/agent/sync.go)). The gateway fields and complete model list are still replaced, so removed models leave the list. +- Every sync and pick that writes magpie's own block into an agent's config lays it over what is there, so keys magpie doesn't write stay (#2030, then its siblings). Each block was checked against the app's own schema or source. magpie's parts are named; a key it no longer writes goes with them. + - Qoder's `providers.magpie` keeps `routing`, the timeouts, `type`, `authType`, `anthropic` and a non-empty `displayName` (`qoderKept`). + - fx keeps `reviewer_model` and a `tool_choice_mode` of `omit`. Its `auth` is magpie's whole, since fx refuses an `env` beside `type: none` (`fxKept`). + - Hermes keeps the `default_model` that `hermes model` writes there, `key_cmd`, the timeouts, `extra_body`, a name and headers beside magpie's (`hermesKept`). This holds in every profile. + - omp's `models.yml` keeps `modelOverrides`, `discovery`, `disableStrictTools`, headers and compat flags (`ompKept`). Its `auth` and `apiKey` are magpie's, or gone. + - Kimi Code's `[providers.magpie]` has magpie's three keys set in place, so `custom_headers`, `env` and `default_model` stay (`kimiProvider`). + - Cline's `models.json` keeps the provider's other keys, and on each model magpie lists what magpie doesn't write, such as a VS Code override (`clineKept`). + - Goose's custom provider file keeps a name, `timeout_seconds`, `toolshim`, headers and the like (`gooseProviderKept`). + - ZCode's provider rule keeps its name, logo, visibility, API headers and the key's management link (`zcodeRules`). + - The YAML ones go through `yamlKept` and `mergeKept` in [`sync.go`](../../internal/agent/sync.go). Each is tested by a `TestKeepsTheUsersSettings`. - Copilot in JetBrains IDEs keeps its Bring Your Own Key providers in the Copilot language server's `byok.json`, shared with Xcode's and Eclipse's Copilot (`copilotJetBrains` in [`copilotjetbrains.go`](../../internal/agent/copilotjetbrains.go)). magpie writes its own three keys there, `magpie-provider-config`, `magpie-api-key` and `magpie-models-config`, in the bytes the server itself writes, and only when they differ; the user's providers and keys stay. A magpie model the user hid in Manage Models (`isRegistered: false`) stays hidden through a sync. A new file is made 0600 in a 0700 folder, as the server makes it. - dsh (DeepSeek Harness) sets one API per llm-pi-ai route, so magpie writes a route per protocol (`dshKinds` in [`dsh.go`](../../internal/agent/dsh.go); 01huadalang on Discord): `magpie` (Chat Completions) for most models, `magpie-responses` (`openai-responses`) for a model served on Responses, `magpie-anthropic` (`anthropic-messages`, the gateway root, `forceAdaptiveThinking` where `AdaptiveThinking`) for one served on Messages, by the model's `APIs` (`dshRouteOf`). A model's `APIs` is the one its provider serves it on best (`Provider.Native`, in `magpieModels`, [`route.go`](../../internal/agent/route.go)), and Pi, omp and droid read it the same way. A routing group has `responses` when every member is best on Responses (`allResponses`, #1594), so its tool-call arguments are relayed as they stream; any other group has none and stays on Chat, a Messages-only group too, as a Claude member's thinking is known by its own model. A route with no models is taken out. An api the user picked for a route in dsh's Models page is kept, and so are keys they added there. The start (`agent-default-model`) names its model's route, and Sync moves a start on one of magpie's routes to the route its model is now on (`dshStartOnItsRoute`), its effort and marks kept. Check asks the route the start names to list its model. A dsh session resumed on a model that has since moved routes asks for the model to be picked again, since dsh finds a model by route and id. - Ante's `catalog.json` keeps user-added fields in `providers.magpie` the same way (`ante` in [`ante.go`](../../internal/agent/ante.go)); its `auth`, `http_headers`, `extra_body` and `stream_idle_timeout_secs` are what a gateway shared on the local network or reached from WSL needs to send a key. Ante starts a session on the `provider` and `model` of `settings.json`, not on what its catalog holds (#1210), so magpie sets that pair and puts back what it found there; a pick the user makes in Ante while magpie is wired is theirs and stands. diff --git a/internal/agent/cline.go b/internal/agent/cline.go index 797987b79..310a8e4f1 100644 --- a/internal/agent/cline.go +++ b/internal/agent/cline.go @@ -177,7 +177,7 @@ func clineIn(at place) *Agent { return err } } - return syncJSON(models, "providers."+clineSlot, func() any { return clineModelsAt(get(slot+".settings.model"), at.v1()) }) + return syncJSON(models, "providers."+clineSlot, func() any { return clineKept(models, clineModelsAt(get(slot+".settings.model"), at.v1())) }) }, Notice: func() string { if runtime.GOOS == "windows" { @@ -233,7 +233,7 @@ func clineIn(at place) *Agent { }) } if err := clineWrite(models, `{"version":1,"providers":{}}`, - edit.KV{Path: "providers." + clineSlot, Value: clineModelsAt(ref, at.v1())}); err != nil { + edit.KV{Path: "providers." + clineSlot, Value: clineKept(models, clineModelsAt(ref, at.v1()))}); err != nil { return err } if err := wireState(ref); err != nil { @@ -398,6 +398,39 @@ func clineModelsAt(model, v1 string) map[string]any { } } +// clineKept is magpie's entry want laid over the one in Cline's models.json +// at path. What the user set there stays (#2030): a key of the provider's +// beside its name, address and default model (protocol, client, +// capabilities, modelsSourceUrl), and on each of magpie's models what +// magpie doesn't write, such as an override from the VS Code extension's +// model editor (temperature, prices, apiFormat, supportsVision; +// sdk/packages/core/src/services/providers/local-provider-registry.ts). A +// model magpie no longer lists goes, with what was set on it. +func clineKept(path string, want map[string]any) any { + cur, ok := edit.GetJSON(path, "providers."+clineSlot) + if !ok { + return want + } + var have map[string]any + if json.Unmarshal([]byte(cur), &have) != nil || have == nil { + return want + } + hm, _ := have["models"].(map[string]any) + wm, _ := want["models"].(map[string]any) + ms := make(map[string]any, len(wm)) + for id, w := range wm { + h, _ := hm[id].(map[string]any) + if h == nil { + ms[id] = w + continue + } + ms[id] = mergeKept(h, w.(map[string]any), nil) + } + out := mergeKept(have, want, []string{"models"}) + out["models"] = ms + return out +} + // providersEmpty is a providers.json with nothing in it. const providersEmpty = `{"version":1,"modes":{},"providers":{}}` diff --git a/internal/agent/cline_test.go b/internal/agent/cline_test.go index 9802c2498..5392668b3 100644 --- a/internal/agent/cline_test.go +++ b/internal/agent/cline_test.go @@ -201,3 +201,64 @@ func TestCline(t *testing.T) { t.Fatalf("CLINE_DATA_DIR: %q", p) } } + +// What the user set on magpie's entry in Cline's models.json stays through +// every sync and pick (#2030's siblings): a key of the provider's, and on a +// model magpie lists what magpie doesn't write (an override from the VS Code +// extension's model editor). The address, default model and model list stay +// magpie's. +func TestClineKeepsTheUsersSettings(t *testing.T) { + home := syncHome(t) + t.Setenv("CLINE_DIR", "") + t.Setenv("CLINE_DATA_DIR", "") + mpath := filepath.Join(home, ".cline", "data", "settings", "models.json") + a := cline(home) + f := a.Field("model") + if err := f.Set("magpie/relay/glm-4.6"); err != nil { + t.Fatal(err) + } + slot := "providers." + clineSlot + if err := edit.SetJSON(mpath, + edit.KV{Path: slot + ".provider.modelsSourceUrl", Value: "https://x/models"}, + edit.KV{Path: slot + ".provider.protocol", Value: "openai-chat"}, + edit.KV{Path: slot + ".provider.baseUrl", Value: "http://127.0.0.1:1/v1"}, + edit.KV{Path: slot + ".models.relay/glm-4\\.6.temperature", Value: 0.3}, + edit.KV{Path: slot + ".models.gone/old", Value: map[string]any{"id": "gone/old", "temperature": 0.1}}, + ); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"pro"}}); err != nil { + t.Fatal(err) + } + for range 3 { + if err := a.Sync(); err != nil { + t.Fatal(err) + } + } + check := func(when string) { + t.Helper() + var c struct { + Providers map[string]struct { + Provider map[string]any `json:"provider"` + Models map[string]map[string]any `json:"models"` + } `json:"providers"` + } + raw := readFile(mpath) + if err := json.Unmarshal([]byte(raw), &c); err != nil { + t.Fatalf("%v\n%s", err, raw) + } + e := c.Providers[clineSlot] + if e.Provider["modelsSourceUrl"] != "https://x/models" || e.Provider["protocol"] != "openai-chat" || e.Models["relay/glm-4.6"]["temperature"] != 0.3 { + t.Errorf("%s: the user's settings not kept:\n%s", when, raw) + } + if e.Provider["baseUrl"] == "http://127.0.0.1:1/v1" || e.Provider["name"] != "magpie" || e.Models["gone/old"] != nil || + e.Models["deepseek/pro"] == nil || e.Models["relay/glm-4.6"]["name"] == nil { + t.Errorf("%s: magpie's own parts not written:\n%s", when, raw) + } + } + check("sync") + if err := f.Set("magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + check("pick") +} diff --git a/internal/agent/fx.go b/internal/agent/fx.go index 4169976c7..b789b6916 100644 --- a/internal/agent/fx.go +++ b/internal/agent/fx.go @@ -30,9 +30,10 @@ func fx(home string) *Agent { return fxIn(here(home)) } // fxIn is fx at a place: this machine's home, or a WSL distro's (see // wsl.go), its provider naming the gateway as the distro reaches it. func fxIn(at place) *Agent { - fxProvider := func(cur string) any { return fxProviderAt(cur, at.v1()) } dir := filepath.Join(at.home, ".fx") path := filepath.Join(dir, "settings.json") + // magpie's provider, with what the user set on it in fx kept + fxProvider := func(cur string) any { return fxKept(path, fxProviderAt(cur, at.v1())) } get := func(k string) string { v, _ := edit.GetJSON(path, k); return v } // the provider fx talks to; unset, it is Vercel's AI Gateway prov := func() string { @@ -147,7 +148,7 @@ func fxModels(path string) map[string]string { // reaching the gateway's /v1 at v1. Its model_metadata is what fx's model // picker lists: the catalog, the model in use first so it is never the one // cut at fx's limit. -func fxProviderAt(cur, v1 string) any { +func fxProviderAt(cur, v1 string) map[string]any { all := magpieModels("fx") slices.SortStableFunc(all, func(a, b catalog.Model) int { switch { @@ -179,6 +180,22 @@ func fxProviderAt(cur, v1 string) any { } } +// fxKept is want, magpie's provider in fx's settings.json at path, with +// what the user set on the one there kept: fx takes a reviewer_model on a +// provider (the model its auto permission mode asks), which magpie doesn't +// write, and a tool_choice_mode, which magpie writes "send" and the user +// may turn to "omit" (src/core/config/configured_provider.zig); a sync wrote +// both away on every start, as T3 Code's did (#2030). Its protocol, +// address, auth and model_metadata are magpie's; auth is written whole, as +// fx refuses an env beside type none. +func fxKept(path string, want map[string]any) any { + key := "providers." + magpieID + if mode, ok := edit.GetJSON(path, key+".tool_choice_mode"); ok && (mode == "omit" || mode == "send") { + want["tool_choice_mode"] = mode + } + return theirsKept(path, key, func() any { return want }, "model_metadata", "auth")() +} + // what fx says after a change (notice.go) var ( noticeFx = newNotice("fx reads its settings at start-up — restart open fx sessions to use this.") diff --git a/internal/agent/fx_test.go b/internal/agent/fx_test.go index d9712b828..9ae6da3ae 100644 --- a/internal/agent/fx_test.go +++ b/internal/agent/fx_test.go @@ -6,6 +6,7 @@ import ( "path/filepath" "testing" + "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/testenv" ) @@ -104,3 +105,69 @@ func TestFxDetected(t *testing.T) { t.Error("~/.fx is not taken for the agent") } } + +// What the user set on magpie's provider in fx's settings stays through +// every sync and pick, as T3 Code's did after #2030: the reviewer model fx's +// auto permission mode asks, and a tool_choice_mode turned to omit. The +// address, auth and model list stay magpie's; an auth the user changed goes +// back whole, as fx refuses an env beside type none. +func TestFxKeepsTheUsersSettings(t *testing.T) { + home := syncHome(t) + path := filepath.Join(home, ".fx", "settings.json") + os.MkdirAll(filepath.Dir(path), 0o755) + os.WriteFile(path, []byte(`{"theme":"dark","providers":{"local":{"protocol":"openai-chat-completions","base_url":"http://localhost:11434/v1","auth":{"type":"none"}}}}`), 0o644) + a := fx(home) + f := a.Field("model") + if err := f.Set("magpie/relay/glm-4.6"); err != nil { + t.Fatal(err) + } + if err := edit.SetJSON(path, + edit.KV{Path: "providers.magpie.reviewer_model", Value: "relay/glm-4.6"}, + edit.KV{Path: "providers.magpie.tool_choice_mode", Value: "omit"}, + edit.KV{Path: "providers.magpie.auth", Value: map[string]any{"type": "bearer", "env": "MY_KEY"}}, + edit.KV{Path: "providers.magpie.base_url", Value: "http://127.0.0.1:1/v1"}, + edit.KV{Path: "providers.magpie.model_metadata", Value: map[string]any{"gone/old": map[string]any{}}}, + ); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"pro"}}); err != nil { + t.Fatal(err) + } + for range 3 { + if err := a.Sync(); err != nil { + t.Fatal(err) + } + } + check := func(when string) { + t.Helper() + var s struct { + Theme string `json:"theme"` + Providers map[string]struct { + ReviewerModel string `json:"reviewer_model"` + ToolChoiceMode string `json:"tool_choice_mode"` + BaseURL string `json:"base_url"` + Auth map[string]any `json:"auth"` + ModelMetadata map[string]any `json:"model_metadata"` + } `json:"providers"` + } + raw := readFile(path) + if err := json.Unmarshal([]byte(raw), &s); err != nil { + t.Fatalf("%v\n%s", err, raw) + } + p := s.Providers[magpieID] + if p.ReviewerModel != "relay/glm-4.6" || p.ToolChoiceMode != "omit" { + t.Errorf("%s: the user's settings not kept:\n%s", when, raw) + } + if p.BaseURL == "http://127.0.0.1:1/v1" || p.BaseURL == "" || len(p.Auth) != 1 || p.Auth["type"] != "none" || p.ModelMetadata["gone/old"] != nil || p.ModelMetadata["deepseek/pro"] == nil { + t.Errorf("%s: magpie's own parts not written:\n%s", when, raw) + } + if s.Theme != "dark" || s.Providers["local"].BaseURL == "" { + t.Errorf("%s: the user's other settings changed:\n%s", when, raw) + } + } + check("sync") + if err := f.Set("magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + check("pick") +} diff --git a/internal/agent/goose.go b/internal/agent/goose.go index 884f64ed7..ded08ca31 100644 --- a/internal/agent/goose.go +++ b/internal/agent/goose.go @@ -151,9 +151,36 @@ func gooseProviderJSON(at place) map[string]any { // in Usage (#1083). func gooseKey(at place) string { return agentKeyAt("goose", at.gw()) } +// gooseProviderKept is magpie's custom provider laid over the file at path. +// Goose's own editor (update_custom_provider, crates/goose/src/config/ +// declarative_providers.rs) carries the keys it doesn't show into the file it +// writes, and the user sets timeout_seconds, toolshim, supports_streaming, +// preserves_thinking, a header or a name there (DeclarativeProviderConfig). +// Each stays (#2030); what reaches the gateway, its key and the model list +// are magpie's. +func gooseProviderKept(path string, at place) map[string]any { + want := gooseProviderJSON(at) + raw, err := edit.Read(path) + if err != nil || raw == nil { + return want + } + var have map[string]any + if json.Unmarshal(raw, &have) != nil || have == nil { + return want + } + if name, _ := have["display_name"].(string); strings.TrimSpace(name) != "" { + want["display_name"] = name + } + if h, _ := have["headers"].(map[string]any); h != nil { + // a header of the user's, beside magpie's Authorization + want["headers"] = mergeKept(h, want["headers"].(map[string]any), nil) + } + return mergeKept(have, want, []string{"name", "engine", "api_key_env", "base_url", "requires_auth", "dynamic_models", "models", "headers"}) +} + // writeGooseProvider writes magpie's custom provider file for Goose. func writeGooseProvider(path string, at place) error { - b, err := json.MarshalIndent(gooseProviderJSON(at), "", " ") + b, err := json.MarshalIndent(gooseProviderKept(path, at), "", " ") if err != nil { return err } @@ -170,7 +197,7 @@ func syncGooseProvider(path string, at place) error { if err != nil || raw == nil { return nil } - if sameJSON(string(raw), gooseProviderJSON(at)) { + if sameJSON(string(raw), gooseProviderKept(path, at)) { return nil } return writeGooseProvider(path, at) diff --git a/internal/agent/goose_test.go b/internal/agent/goose_test.go index 0d9d29df7..21f0a4f73 100644 --- a/internal/agent/goose_test.go +++ b/internal/agent/goose_test.go @@ -388,3 +388,72 @@ func TestGooseModelInEitherLayout(t *testing.T) { t.Fatalf("goose uses %q", got) } } + +// What the user set on magpie's custom provider in Goose stays through every +// sync and pick (#2030's siblings): a name, a timeout, the tool shim, a +// header beside magpie's key. The engine, address, key and model list stay +// magpie's. +func TestGooseKeepsTheUsersSettings(t *testing.T) { + home := syncHome(t) + t.Setenv("APPDATA", filepath.Join(home, "AppData", "Roaming")) + a := goose(home, filepath.Join(home, ".config")) + f := a.Fields[0] + if err := f.Set("magpie/relay/glm-4.6"); err != nil { + t.Fatal(err) + } + file := gooseProviderPath(a.Path) + var p map[string]any + if err := json.Unmarshal([]byte(readFile(file)), &p); err != nil { + t.Fatal(err) + } + p["display_name"] = "My GW" + p["timeout_seconds"] = 900 + p["toolshim"] = true + p["headers"].(map[string]any)["X-Mine"] = "1" + p["base_url"] = "http://127.0.0.1:1/v1" + p["models"] = []any{map[string]any{"name": "gone/old"}} + b, _ := json.Marshal(p) + os.WriteFile(file, b, 0o644) + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"pro"}}); err != nil { + t.Fatal(err) + } + for range 3 { + if err := a.Sync(); err != nil { + t.Fatal(err) + } + } + check := func(when string) { + t.Helper() + var got struct { + DisplayName string `json:"display_name"` + Timeout int `json:"timeout_seconds"` + Toolshim bool `json:"toolshim"` + Headers map[string]string `json:"headers"` + BaseURL string `json:"base_url"` + Engine string `json:"engine"` + Models []struct { + Name string `json:"name"` + } `json:"models"` + } + raw := readFile(file) + if err := json.Unmarshal([]byte(raw), &got); err != nil { + t.Fatalf("%v\n%s", err, raw) + } + if got.DisplayName != "My GW" || got.Timeout != 900 || !got.Toolshim || got.Headers["X-Mine"] != "1" { + t.Errorf("%s: the user's settings not kept:\n%s", when, raw) + } + var ids []string + for _, m := range got.Models { + ids = append(ids, m.Name) + } + if got.BaseURL != gatewayV1() || got.Engine != "openai" || got.Headers["Authorization"] != "Bearer "+gateway.TokenFor("goose") || + slices.Contains(ids, "gone/old") || !slices.Contains(ids, "deepseek/pro") { + t.Errorf("%s: magpie's own parts not written:\n%s", when, raw) + } + } + check("sync") + if err := f.Set("magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + check("pick") +} diff --git a/internal/agent/hermes.go b/internal/agent/hermes.go index 4133be886..aa295180d 100644 --- a/internal/agent/hermes.go +++ b/internal/agent/hermes.go @@ -40,16 +40,16 @@ func hermes(home string) *Agent { return hermesIn(here(home)) } func hermesIn(at place) *Agent { dir := at.hermesHome() path := filepath.Join(dir, "config.yaml") - hermesProvider := func() hermesProviderEntry { return hermesProviderAt(at.gw()) } + hermesProvider := func(p string) any { return hermesKept(p, hermesProviderAt(at.gw())) } // spread puts magpie's provider, as it is now, into every other // profile's config beside the one magpie connects spread := func() error { var errs []error for _, p := range hermesOthers(at, dir) { if edit.GetYAMLMap(p, "providers."+magpieID) != nil { - errs = append(errs, syncYAML(p, "providers."+magpieID, func() any { return hermesProvider() })) + errs = append(errs, syncYAML(p, "providers."+magpieID, func() any { return hermesProvider(p) })) } else { - errs = append(errs, edit.SetYAML(p, edit.KV{Path: "providers." + magpieID, Value: hermesProvider()})) + errs = append(errs, edit.SetYAML(p, edit.KV{Path: "providers." + magpieID, Value: hermesProvider(p)})) } } return errors.Join(errs...) @@ -87,7 +87,7 @@ func hermesIn(at place) *Agent { UA: []string{"hermes-agent"}, Bin: "hermes", Dir: dir, Path: path, Sync: func() error { - if err := syncYAML(path, "providers."+magpieID, func() any { return hermesProvider() }); err != nil || !joined() { + if err := syncYAML(path, "providers."+magpieID, func() any { return hermesProvider(path) }); err != nil || !joined() { return err } return spread() @@ -145,7 +145,7 @@ func hermesIn(at place) *Agent { }) } if err := edit.SetYAML(path, - edit.KV{Path: "providers." + magpieID, Value: hermesProvider()}, + edit.KV{Path: "providers." + magpieID, Value: hermesProvider(path)}, edit.KV{Path: "model.provider", Value: magpieID}, edit.KV{Path: "model.default", Value: ref}, ); err != nil { @@ -277,6 +277,20 @@ func hermesProviderAt(gw string) hermesProviderEntry { } } +// hermesKept is magpie's entry e laid over the one in the config at path. +// Hermes keeps keys it doesn't know and writes into the entry itself: `hermes +// model` sets default_model there, the dashboard key_env, and a user adds +// key_cmd, request_timeout_seconds, extra_body, context_length, enabled or +// ssl_* (hermes_cli/config_providers.py _KNOWN_PROVIDER_KEYS). Each stays, +// as does a name of their own and a header beside magpie's User-Agent; the +// address, key, API mode and model list are magpie's (#2030). +func hermesKept(path string, e hermesProviderEntry) any { + if name, ok := edit.GetYAML(path, "providers."+magpieID+".name"); ok && strings.TrimSpace(name) != "" { + e.Name = name + } + return yamlKept(path, "providers."+magpieID, e, "base_url", "api_key", "api_mode", "models") +} + // what hermes says after a change (notice.go) var ( noticeHermes = newNotice("Hermes reads its settings at start-up — restart open Hermes sessions to use this.") diff --git a/internal/agent/hermes_test.go b/internal/agent/hermes_test.go index 8c30b98f3..b0fa27229 100644 --- a/internal/agent/hermes_test.go +++ b/internal/agent/hermes_test.go @@ -4,6 +4,7 @@ import ( "os" "path/filepath" "runtime" + "slices" "strings" "testing" @@ -272,3 +273,87 @@ func TestHermesFolder(t *testing.T) { t.Fatalf("Hermes in WSL at %s, want ~/.hermes", a.Dir) } } + +// What the user, or Hermes itself, set on magpie's provider stays through +// every sync and pick, in the connected config and in each profile's +// (#2030's siblings): the default_model `hermes model` writes there, a name, +// a timeout, a key command, a header beside magpie's. The address, key, API +// mode and model list stay magpie's. +func TestHermesKeepsTheUsersSettings(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("HERMES_HOME", "") + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro"}}); err != nil { + t.Fatal(err) + } + root := appdir.HermesHomeIn(home) + path := filepath.Join(root, "config.yaml") + bot := filepath.Join(root, "profiles", "coder", "config.yaml") + os.MkdirAll(filepath.Dir(bot), 0o755) + os.WriteFile(path, []byte("model:\n default: anthropic/claude-opus-5\n provider: openrouter\n"), 0o644) + os.WriteFile(bot, []byte("model:\n default: kimi-k3\n provider: moonshot\n"), 0o644) + a := hermes(home) + f := a.Field("model") + if err := f.Set("magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + for _, p := range []string{path, bot} { + if err := edit.SetYAML(p, + edit.KV{Path: "providers.magpie.name", Value: "My GW"}, + edit.KV{Path: "providers.magpie.default_model", Value: "deepseek/pro"}, + edit.KV{Path: "providers.magpie.request_timeout_seconds", Value: 900}, + edit.KV{Path: "providers.magpie.key_cmd", Value: "cat ~/.gw-key"}, + edit.KV{Path: "providers.magpie.extra_headers.X-Mine", Value: "1"}, + edit.KV{Path: "providers.magpie.base_url", Value: "http://127.0.0.1:1/v1"}, + edit.KV{Path: "providers.magpie.models", Value: []string{"gone/old"}}, + ); err != nil { + t.Fatal(err) + } + } + if err := provider.Save(provider.Provider{ID: "kimi", Name: "Kimi", Chat: "https://api.moonshot.ai/v1", Key: "k", Models: []string{"k3"}}); err != nil { + t.Fatal(err) + } + for range 3 { + if err := a.Sync(); err != nil { + t.Fatal(err) + } + } + check := func(when string) { + t.Helper() + for _, p := range []string{path, bot} { + var c struct { + Providers map[string]struct { + Name string `yaml:"name"` + Default string `yaml:"default_model"` + Timeout int `yaml:"request_timeout_seconds"` + KeyCmd string `yaml:"key_cmd"` + Headers map[string]string `yaml:"extra_headers"` + BaseURL string `yaml:"base_url"` + APIKey string `yaml:"api_key"` + APIMode string `yaml:"api_mode"` + Models []string `yaml:"models"` + } `yaml:"providers"` + } + raw := readFile(p) + if err := yaml.Unmarshal([]byte(raw), &c); err != nil { + t.Fatalf("%v\n%s", err, raw) + } + mp := c.Providers[magpieID] + if mp.Name != "My GW" || mp.Default != "deepseek/pro" || mp.Timeout != 900 || mp.KeyCmd != "cat ~/.gw-key" || mp.Headers["X-Mine"] != "1" { + t.Errorf("%s: the user's settings not kept in %s:\n%s", when, p, raw) + } + if mp.BaseURL == "http://127.0.0.1:1/v1" || mp.APIKey == "" || mp.APIMode != "chat_completions" || mp.Headers["User-Agent"] != "hermes-agent" || + slices.Contains(mp.Models, "gone/old") || !slices.Contains(mp.Models, "kimi/k3") { + t.Errorf("%s: magpie's own parts not written in %s:\n%s", when, p, raw) + } + } + } + check("sync") + if err := f.Set("magpie/kimi/k3"); err != nil { + t.Fatal(err) + } + check("pick") +} diff --git a/internal/agent/kimi.go b/internal/agent/kimi.go index d66a9cd59..9f9c3a7ce 100644 --- a/internal/agent/kimi.go +++ b/internal/agent/kimi.go @@ -197,6 +197,23 @@ func kimiEfforts(efforts []string, was string) []edit.KV { func kimi(home string) *Agent { return kimiIn(here(home)) } +// kimiProvider writes magpie's keys into its provider table, each in place +// when the table is there, so the rest of it stays: custom_headers, env or a +// default_model the user set on it (Kimi Code's ProviderConfig, +// packages/agent-core-v2/src/app/kosongConfig/configSection.ts), which a +// table written afresh dropped on every sync (#2030). +func kimiProvider(path, table string, kvs ...edit.KV) error { + if t, err := edit.GetTOMLTable(path, table); err != nil || t == nil { + return edit.SetTOMLTable(path, table, kvs...) + } + for _, kv := range kvs { + if err := edit.SetTOMLKey(path, table, kv.Path, kv.Value); err != nil { + return err + } + } + return nil +} + // kimiIn is Kimi Code at a place: this machine's home, or a WSL distro's // (see wsl.go), its provider naming the gateway as it reaches it from there. func kimiIn(at place) *Agent { @@ -206,7 +223,7 @@ func kimiIn(at place) *Agent { get := func() string { v, _ := edit.GetTOMLTop(path, "default_model"); return v } providerTable := "providers." + magpieID writeMagpie := func() error { - if err := edit.SetTOMLTable(path, providerTable, + if err := kimiProvider(path, providerTable, edit.KV{Path: "type", Value: "kimi"}, edit.KV{Path: "base_url", Value: at.v1()}, edit.KV{Path: "api_key", Value: at.gwKey()}, diff --git a/internal/agent/kimi_test.go b/internal/agent/kimi_test.go index 7d0ec932f..104005834 100644 --- a/internal/agent/kimi_test.go +++ b/internal/agent/kimi_test.go @@ -188,3 +188,63 @@ func TestKimiNoConfig(t *testing.T) { t.Fatalf("reset:\n%s", b) } } + +// What the user set on magpie's provider table in Kimi Code's config.toml +// stays through every sync and pick (#2030's siblings): headers, env and a +// default model of its own. The type, address and key stay magpie's. +func TestKimiKeepsTheUsersSettings(t *testing.T) { + home := syncHome(t) + t.Setenv("KIMI_SHARE_DIR", "") + path := filepath.Join(home, ".kimi", "config.toml") + os.MkdirAll(filepath.Dir(path), 0o755) + os.WriteFile(path, []byte("default_model = \"x\"\n"), 0o644) + a := kimi(home) + f := a.Field("model") + if err := f.Set("magpie/relay/glm-4.6"); err != nil { + t.Fatal(err) + } + raw := readFile(path) + if !strings.Contains(raw, "[providers.magpie]\n") { + t.Fatalf("no table:\n%s", raw) + } + raw = strings.Replace(raw, "[providers.magpie]\n", "[providers.magpie]\ndefault_model = \"relay/glm-4.6\"\ncustom_headers = { X-Mine = \"1\" }\nenv = { HTTPS_PROXY = \"http://proxy:8080\" }\n", 1) + os.WriteFile(path, []byte(raw), 0o644) + edit.SetTOMLKey(path, "providers.magpie", "base_url", "http://127.0.0.1:1/v1") + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"pro"}}); err != nil { + t.Fatal(err) + } + for range 3 { + if err := a.Sync(); err != nil { + t.Fatal(err) + } + } + check := func(when string) { + t.Helper() + var c struct { + Providers map[string]struct { + Type string `toml:"type"` + BaseURL string `toml:"base_url"` + APIKey string `toml:"api_key"` + Default string `toml:"default_model"` + Headers map[string]string `toml:"custom_headers"` + Env map[string]string `toml:"env"` + } `toml:"providers"` + } + raw := readFile(path) + if err := toml.Unmarshal([]byte(raw), &c); err != nil { + t.Fatalf("%v\n%s", err, raw) + } + p := c.Providers[magpieID] + if p.Default != "relay/glm-4.6" || p.Headers["X-Mine"] != "1" || p.Env["HTTPS_PROXY"] != "http://proxy:8080" { + t.Errorf("%s: the user's settings not kept:\n%s", when, raw) + } + if p.Type != "kimi" || p.BaseURL == "http://127.0.0.1:1/v1" || p.BaseURL == "" || p.APIKey == "" { + t.Errorf("%s: magpie's own parts not written:\n%s", when, raw) + } + } + check("sync") + if err := f.Set("magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + check("pick") +} diff --git a/internal/agent/omp.go b/internal/agent/omp.go index 36ebe022f..cb9018fdb 100644 --- a/internal/agent/omp.go +++ b/internal/agent/omp.go @@ -198,7 +198,8 @@ func ompIn(at place) *Agent { // ompAt is omp with its agent folder at dir, magpie's entry in its // models.yml being entry's. func ompAt(at place, dir string, entry func() ompProviderEntry) *Agent { - ompProvider := entry + // magpie's entry laid over the one in the models file at path (ompKept) + ompProvider := func(path string) any { return ompKept(path, entry()) } // omp reads the .yml and falls back to the .yaml pick := func(name string) string { yml := filepath.Join(dir, name+".yml") @@ -238,7 +239,7 @@ func ompAt(at place, dir string, entry func() ompProviderEntry) *Agent { return err } } - return edit.SetYAML(models, edit.KV{Path: "providers." + magpieID, Value: ompProvider()}) + return edit.SetYAML(models, edit.KV{Path: "providers." + magpieID, Value: ompProvider(models)}) } // dropMagpie takes magpie's provider out of models.yml once nothing in // the config is on magpie; while something is (a fallback chain, another @@ -451,7 +452,8 @@ func ompAt(at place, dir string, entry func() ompProviderEntry) *Agent { // a list of models is the user's own SplitSuffix: ompSplit, Sync: func() error { - return syncYAML(pick("models"), "providers."+magpieID, func() any { return ompProvider() }) + models := pick("models") + return syncYAML(models, "providers."+magpieID, func() any { return ompProvider(models) }) }, // a provider renamed takes its models' ids in models.yml with it; a // name left on the old one omp would pass over, with a warning. So @@ -672,6 +674,18 @@ func ompProviderAt(gw, version string) ompProviderEntry { return e } +// ompKept is magpie's entry e laid over the one in the models.yml at path. +// omp keeps keys its schema doesn't name and never writes the file itself, +// so what is there beside magpie's is the user's: modelOverrides (a model's +// context or cost), discovery, disableStrictTools, remoteCompaction, a +// header or compat flag of their own (models-config-schema-bundle.ts +// ProviderConfigSchema). Each stays; the address, API, auth, key and model +// list are magpie's, an auth or key it no longer writes gone with it, so a +// loopback's auth: none never sits beside the key a WSL omp needs (#2030). +func ompKept(path string, e ompProviderEntry) any { + return yamlKept(path, "providers."+magpieID, e, "baseUrl", "api", "auth", "apiKey", "models") +} + // ompOwnOptions lists the models of the providers the user added to omp's // models.yml, then the ones models.dev knows for the current value's // provider, spelled as ownOptions spells them (the model's name as the diff --git a/internal/agent/omp_test.go b/internal/agent/omp_test.go index 3720abc65..84868b4f1 100644 --- a/internal/agent/omp_test.go +++ b/internal/agent/omp_test.go @@ -710,3 +710,88 @@ func TestOmpOwnModels(t *testing.T) { t.Fatalf("the subagents' picker lacks models.yml's models: %+v", sub) } } + +// What the user set on magpie's provider in omp's models.yml stays through +// every sync and pick (#2030's siblings): a model's override, discovery's +// timeouts, strict tools turned off, a header or compat flag beside +// magpie's. The address, API, auth and model list stay magpie's, and a key +// magpie doesn't write goes. +func TestOmpKeepsTheUsersSettings(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + for _, k := range []string{"PI_CODING_AGENT_DIR", "PI_CONFIG_DIR", "OMP_PROFILE", "PI_PROFILE"} { + t.Setenv(k, "") + } + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro"}}); err != nil { + t.Fatal(err) + } + dir := filepath.Join(home, ".omp", "agent") + modelsPath := filepath.Join(dir, "models.yml") + os.MkdirAll(dir, 0o755) + os.WriteFile(filepath.Join(dir, "config.yml"), []byte("modelRoles:\n default: anthropic/claude-opus-5\n"), 0o644) + a := omp(home) + f := a.Field("model") + if err := f.Set("magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + if err := edit.SetYAML(modelsPath, + edit.KV{Path: "providers.magpie.modelOverrides", Value: map[string]any{"deepseek/pro": map[string]any{"contextWindow": 64000}}}, + edit.KV{Path: "providers.magpie.disableStrictTools", Value: true}, + edit.KV{Path: "providers.magpie.headers.X-Mine", Value: "1"}, + edit.KV{Path: "providers.magpie.compat.supportsStore", Value: false}, + edit.KV{Path: "providers.magpie.baseUrl", Value: "http://127.0.0.1:1/v1"}, + edit.KV{Path: "providers.magpie.apiKey", Value: "stale"}, + edit.KV{Path: "providers.magpie.models", Value: []any{map[string]any{"id": "gone/old"}}}, + ); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "kimi", Name: "Kimi", Chat: "https://api.moonshot.ai/v1", Key: "k", Models: []string{"k3"}}); err != nil { + t.Fatal(err) + } + for range 3 { + if err := a.Sync(); err != nil { + t.Fatal(err) + } + } + check := func(when string) { + t.Helper() + var c struct { + Providers map[string]struct { + Overrides map[string]map[string]any `yaml:"modelOverrides"` + NoStrict bool `yaml:"disableStrictTools"` + Headers map[string]string `yaml:"headers"` + Compat map[string]any `yaml:"compat"` + BaseURL string `yaml:"baseUrl"` + Auth string `yaml:"auth"` + APIKey *string `yaml:"apiKey"` + Models []struct { + ID string `yaml:"id"` + } `yaml:"models"` + } `yaml:"providers"` + } + raw := readFile(modelsPath) + if err := yaml.Unmarshal([]byte(raw), &c); err != nil { + t.Fatalf("%v\n%s", err, raw) + } + mp := c.Providers[magpieID] + if mp.Overrides["deepseek/pro"]["contextWindow"] != 64000 || !mp.NoStrict || mp.Headers["X-Mine"] != "1" || mp.Compat["supportsStore"] != false { + t.Errorf("%s: the user's settings not kept:\n%s", when, raw) + } + var ids []string + for _, m := range mp.Models { + ids = append(ids, m.ID) + } + if mp.BaseURL == "http://127.0.0.1:1/v1" || mp.Auth != "none" || mp.APIKey != nil || mp.Headers["User-Agent"] != "omp" || + slices.Contains(ids, "gone/old") || !slices.Contains(ids, "kimi/k3") { + t.Errorf("%s: magpie's own parts not written:\n%s", when, raw) + } + } + check("sync") + if err := f.Set("magpie/kimi/k3"); err != nil { + t.Fatal(err) + } + check("pick") +} diff --git a/internal/agent/qoder.go b/internal/agent/qoder.go index 44e6b9255..7357472ce 100644 --- a/internal/agent/qoder.go +++ b/internal/agent/qoder.go @@ -32,6 +32,7 @@ import ( "os" "path/filepath" "slices" + "strings" "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/gateway" @@ -68,7 +69,6 @@ func qoderSite(home string, b qoderBuild) *Agent { return qoderAt(here(home), b) // qoderAt is a build of Qoder at a place, its provider naming the gateway // as it reaches it from there. func qoderAt(at place, b qoderBuild) *Agent { - qoderProvider := func(agent, model string) map[string]any { return qoderProviderAt(agent, model, at.v1()) } dir := at.getenv(b.env) if dir == "" { dir = filepath.Join(at.home, b.dir) @@ -76,6 +76,10 @@ func qoderAt(at place, b qoderBuild) *Agent { path := filepath.Join(dir, "settings.json") key := b.id + ":" + path + ":" slot := "providers." + magpieID + // magpie's provider, with what the user set on it in Qoder kept + qoderProvider := func(agent, model string) any { + return qoderKept(path, slot, qoderProviderAt(agent, model, at.v1())) + } get := func(k string) string { v, _ := edit.GetJSON(path, k); return v } // effort is what the model in use asks for: its preference, else // reasoningEffort @@ -260,6 +264,20 @@ func qoderPreferences(prefs, model, effort string) (out map[string]any, drop boo return out, len(out) == 0 } +// qoderKept is want, magpie's provider in Qoder's settings.json at path, +// with what the user set on the one at slot kept: Qoder (1.1.70) reads a +// provider's routing (the model for compact, summary, subagent …), its +// firstPayloadTimeoutMs and streamIdleTimeoutMs, type, authType and +// anthropic block, none of which magpie writes, and a sync wrote them away +// on every start, as T3 Code's did (#2030). A name the user gave it is +// theirs too. Its address, key, model and model list are magpie's. +func qoderKept(path, slot string, want map[string]any) any { + if name, ok := edit.GetJSON(path, slot+".displayName"); ok && strings.TrimSpace(name) != "" { + want["displayName"] = name + } + return theirsKept(path, slot, func() any { return want }, "models")() +} + // qoderLevels are the efforts Qoder can ask for. var qoderLevels = []string{"low", "medium", "high", "xhigh", "max"} diff --git a/internal/agent/qoder_test.go b/internal/agent/qoder_test.go index 07d72fffb..4107d044d 100644 --- a/internal/agent/qoder_test.go +++ b/internal/agent/qoder_test.go @@ -4,6 +4,7 @@ import ( "encoding/json" "os" "path/filepath" + "slices" "strings" "testing" @@ -172,3 +173,90 @@ func testQoder(t *testing.T, mk func(string) *Agent, rel string) { t.Fatalf("new file:\n%s", raw) } } + +// What the user set on magpie's provider in Qoder's settings stays through +// every sync and pick, as T3 Code's did after #2030: its name, the model +// routing that picks compact's and subagents' models, its timeouts and auth +// type. The address, key, model and model list stay magpie's. +func TestQoderKeepsTheUsersSettings(t *testing.T) { + for _, b := range []struct { + mk func(string) *Agent + rel string + }{{qoder, filepath.Join(".qoder", "settings.json")}, {qoderCN, filepath.Join(".qoder-cn", "settings.json")}} { + t.Run(b.rel, func(t *testing.T) { + home := syncHome(t) + t.Setenv("QODER_CONFIG_DIR", "") + t.Setenv("QODERCN_CONFIG_DIR", "") + path := filepath.Join(home, b.rel) + os.MkdirAll(filepath.Dir(path), 0o700) + os.WriteFile(path, []byte(`{"providers":{"mine":{"baseUrl":"https://x/v1","apiKey":"sk-m","model":"m1"}},"model":{"name":"m1"}}`), 0o600) + a := b.mk(home) + f := a.Field("model") + if err := f.Set("magpie/relay/glm-4.6"); err != nil { + t.Fatal(err) + } + // the user edits magpie's provider, as they would Qoder's settings + if err := edit.SetJSON(path, + edit.KV{Path: "providers.magpie.displayName", Value: "Magpie GW"}, + edit.KV{Path: "providers.magpie.routing", Value: map[string]any{"compact": "relay/glm-4.6", "subagent": "relay/glm-4.6"}}, + edit.KV{Path: "providers.magpie.streamIdleTimeoutMs", Value: 600000}, + edit.KV{Path: "providers.magpie.firstPayloadTimeoutMs", Value: 120000}, + edit.KV{Path: "providers.magpie.authType", Value: "bearer"}, + edit.KV{Path: "providers.magpie.baseUrl", Value: "http://127.0.0.1:1/v1"}, + edit.KV{Path: "providers.magpie.models", Value: []any{map[string]any{"model": "gone/old"}}}, + ); err != nil { + t.Fatal(err) + } + // a provider added since, so the sync has a model list to change + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"pro"}}); err != nil { + t.Fatal(err) + } + for range 3 { + if err := a.Sync(); err != nil { + t.Fatal(err) + } + } + check := func(when string) { + t.Helper() + var c struct { + Providers map[string]struct { + DisplayName string `json:"displayName"` + Routing map[string]string `json:"routing"` + StreamIdleTimeoutMs int `json:"streamIdleTimeoutMs"` + FirstPayloadTimeoutMs int `json:"firstPayloadTimeoutMs"` + AuthType string `json:"authType"` + BaseURL string `json:"baseUrl"` + APIKey string `json:"apiKey"` + Models []struct { + Model string `json:"model"` + } `json:"models"` + } `json:"providers"` + } + raw := readFile(path) + if err := json.Unmarshal([]byte(raw), &c); err != nil { + t.Fatalf("%v\n%s", err, raw) + } + p := c.Providers[magpieID] + if p.DisplayName != "Magpie GW" || p.Routing["compact"] != "relay/glm-4.6" || p.Routing["subagent"] != "relay/glm-4.6" || + p.StreamIdleTimeoutMs != 600000 || p.FirstPayloadTimeoutMs != 120000 || p.AuthType != "bearer" { + t.Errorf("%s: the user's settings not kept:\n%s", when, raw) + } + var ids []string + for _, m := range p.Models { + ids = append(ids, m.Model) + } + if p.BaseURL == "http://127.0.0.1:1/v1" || p.BaseURL == "" || p.APIKey == "" || slices.Contains(ids, "gone/old") || !slices.Contains(ids, "deepseek/pro") { + t.Errorf("%s: magpie's own parts not written: %s %s %v", when, p.BaseURL, p.APIKey, ids) + } + if c.Providers["mine"].APIKey != "sk-m" { + t.Errorf("%s: the user's own provider changed:\n%s", when, raw) + } + } + check("sync") + if err := f.Set("magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + check("pick") + }) + } +} diff --git a/internal/agent/sync.go b/internal/agent/sync.go index e92f936cb..32f252216 100644 --- a/internal/agent/sync.go +++ b/internal/agent/sync.go @@ -178,6 +178,65 @@ func sameJSON(raw string, v any) bool { return reflect.DeepEqual(x, y) } +// yamlKept is value laid over the mapping at key in a YAML file, as +// theirsKept does for JSON: a key magpie doesn't write stays as the user, or +// the app itself, left it, and mappings in both are merged alike. The keys +// named in own are magpie's: its value, or none when it writes none (#2030's +// siblings: Hermes writes default_model into magpie's entry itself, and a +// whole rewrite dropped it). +func yamlKept(path, key string, value any, own ...string) any { + raw, err := edit.Read(path) + if err != nil || raw == nil { + return value + } + var doc any + if yaml.Unmarshal(raw, &doc) != nil { + return value + } + for _, k := range strings.Split(key, ".") { + m, _ := doc.(map[string]any) + if doc = m[k]; doc == nil { + return value + } + } + have, ok := doc.(map[string]any) + if !ok { + return value + } + var want map[string]any + b, err := yaml.Marshal(value) + if err != nil || yaml.Unmarshal(b, &want) != nil || want == nil { + return value + } + return mergeKept(have, want, own) +} + +// mergeKept is want with each key of have that want lacks, mappings in both +// merged alike; a key named in own is want's, or gone. have and want are +// decoded JSON or YAML. +func mergeKept(have, want map[string]any, own []string) map[string]any { + out := make(map[string]any, len(have)+len(want)) + for k, w := range want { + out[k] = w + } + for k, h := range have { + if slices.Contains(own, k) { + continue + } + w, ok := want[k] + if !ok { + out[k] = h + continue + } + hm, hok := h.(map[string]any) + wm, wok := w.(map[string]any) + if hok && wok { + out[k] = mergeKept(hm, wm, nil) + } + } + return out +} + // syncYAML is syncJSON for a YAML file. func syncYAML(path, key string, value func() any) error { raw, err := edit.Read(path) diff --git a/internal/agent/zcode.go b/internal/agent/zcode.go index 6cd24a556..7e6f343f7 100644 --- a/internal/agent/zcode.go +++ b/internal/agent/zcode.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "slices" + "strings" "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/edit" @@ -463,6 +464,20 @@ func zcodeRules(path string, on, keep bool) error { if e, ok := old["enabled"].(bool); ok { rule["enabled"] = e } + // What the user set on it in ZCode stays (#2030): its name, logo, + // visibility, a header or the key's management link + // (packages/provider/src/config/provider-data-schema.ts). ZCode + // checks the file strictly, so only keys it already took are kept; + // the address, key, format and model lists are magpie's. + if old != nil { + if name, _ := old["providerName"].(string); strings.TrimSpace(name) != "" { + rule["providerName"] = name + } + if oc, _ := old["config"].(map[string]any); oc != nil { + rule["config"] = mergeKept(oc, rule["config"].(map[string]any), []string{"group", "personalModelIds", "modelOrder"}) + } + rule = mergeKept(old, rule, nil) + } if at >= 0 { providers = slices.Insert(providers, at, any(rule)) } else { diff --git a/internal/agent/zcode_test.go b/internal/agent/zcode_test.go index f05b31cb2..16211235f 100644 --- a/internal/agent/zcode_test.go +++ b/internal/agent/zcode_test.go @@ -4,6 +4,7 @@ import ( "encoding/json" "os" "path/filepath" + "slices" "strings" "testing" "time" @@ -546,3 +547,74 @@ func TestZCodeMovedDataFolder(t *testing.T) { } } } + +// What the user set on magpie's provider rule in ZCode's provider_config.json +// stays through every sync and pick (#2030's siblings): its name, logo, +// visibility, a header, the key's management link. The address, key, format +// and model lists stay magpie's. +func TestZCodeKeepsTheUsersSettings(t *testing.T) { + home := syncHome(t) + rules := filepath.Join(home, ".zcode", "v2", "provider_config.json") + os.MkdirAll(filepath.Dir(rules), 0o755) + os.WriteFile(filepath.Join(filepath.Dir(rules), "config.json"), []byte(`{}`), 0o644) + a := zcode(home) + f := a.Field("provider") + if err := f.Set("magpie"); err != nil { + t.Fatal(err) + } + type rule = map[string]any + load := func() (map[string]any, rule) { + var d map[string]any + raw := readFile(rules) + if err := json.Unmarshal([]byte(raw), &d); err != nil { + t.Fatalf("%v\n%s", err, raw) + } + for _, r := range zcodeList(zcodeObj(zcodeObj(d, "config"), "providerConfigRules"), "providerRules") { + if m := r.(map[string]any); m["providerId"] == magpieID { + return d, m + } + } + t.Fatalf("no rule:\n%s", raw) + return nil, nil + } + d, r := load() + cfg := r["config"].(map[string]any) + r["providerName"] = "My GW" + cfg["logo"] = map[string]any{"type": "builtin", "key": "openai"} + cfg["visibility"] = "visible" + cfg["api"].(map[string]any)["headers"] = map[string]any{"X-Mine": "1"} + cfg["api"].(map[string]any)["baseUrl"] = "http://127.0.0.1:1/v1" + cfg["access"].(map[string]any)["apiKeyManagementUrl"] = "https://x/keys" + cfg["personalModelIds"] = []any{"gone/old"} + b, _ := json.Marshal(d) + os.WriteFile(rules, b, 0o600) + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"pro"}}); err != nil { + t.Fatal(err) + } + for range 3 { + if err := a.Sync(); err != nil { + t.Fatal(err) + } + } + check := func(when string) { + t.Helper() + _, r := load() + cfg := r["config"].(map[string]any) + api, access := cfg["api"].(map[string]any), cfg["access"].(map[string]any) + headers, _ := api["headers"].(map[string]any) + logo, _ := cfg["logo"].(map[string]any) + if r["providerName"] != "My GW" || logo["key"] != "openai" || cfg["visibility"] != "visible" || headers["X-Mine"] != "1" || + access["apiKeyManagementUrl"] != "https://x/keys" { + t.Errorf("%s: the user's settings not kept:\n%s", when, readFile(rules)) + } + ids, _ := cfg["personalModelIds"].([]any) + if api["baseUrl"] == "http://127.0.0.1:1/v1" || access["apiKey"] == "" || slices.Contains(ids, any("gone/old")) || !slices.Contains(ids, any("deepseek/pro")) { + t.Errorf("%s: magpie's own parts not written:\n%s", when, readFile(rules)) + } + } + check("sync") + if err := f.Set("magpie"); err != nil { + t.Fatal(err) + } + check("pick") +}