diff --git a/docs/reference.md b/docs/reference.md index 1fb97b518..a74b6008d 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -117,6 +117,7 @@ line; agents connected to magpie lose it when it quits. | Muse Code | `~/.config/muse/settings.json` (`$XDG_CONFIG_HOME`) | model (endpoint_transport to the gateway, auth none; magpie's models in Muse's list) | | Empryo | `~/.empryo/config.json` | defaultModel (a `magpie` provider at the gateway in `providers`) | | Ante | `~/.ante/catalog.json` and `settings.json` (`$ANTE_HOME`) | provider, model (a `magpie` provider on OpenAiCompatible, with no auth of magpie's: the gateway lets this machine in with any token and Ante counts a provider with none as authenticated; magpie's models in Ante's model picker, and Ante started on magpie, which is what its settings' `provider` decides) | +| AstrBot | `data/cmd_config.json` under `$ASTRBOT_ROOT`, else `~/.astrbot` (the desktop app's) | model (a `magpie` entry in `provider_sources` and magpie's models in `provider`, the user's own entries kept; the default chat model in `agent_runner.config.model.provider_id`, or `provider_settings.default_provider_id` on AstrBot before 4.28's agent runner; restart AstrBot after connecting; Docker installs aren't reached) | | MiniMax Code (mcode) | `~/.minimax/config.yaml` (`$MINIMAX_DATA_DIR`) | model (a `magpie` custom provider; magpie's models in its /model) | | Droid (Factory) | `~/.factory/settings.json` (`$FACTORY_HOME_OVERRIDE`) | model (magpie's models as BYOK `customModels`, in Droid's /model) | | Cline (CLI) | `~/.cline/data/settings/providers.json` (`$CLINE_DIR`) | model, effort (magpie takes its openai-compatible provider) | diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index cb44dc35c..87b85b3eb 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -40,6 +40,7 @@ something else shows up as drift. - 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. - 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. - 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. +- AstrBot keeps its providers in `data/cmd_config.json` under its root (`$ASTRBOT_ROOT`, else `~/.astrbot`, the desktop app's, else `~/astrbot`), written with a UTF-8 BOM, which magpie keeps (`astrbot` in [`astrbot.go`](../../internal/agent/astrbot.go)). magpie adds a `magpie` entry to `provider_sources` and one `magpie/` entry per model to `provider`, keeps the user's own entries byte for byte and keeps what the user changes in magpie's (timeout, proxy, enable), and sets the default chat model (`agent_runner.config.model.provider_id`, or `provider_settings.default_provider_id` before the agent runner), putting back what it found there. A pick the user makes while magpie is wired is theirs and stands. The first connect copies the file to `cmd_config.json.before-magpie`. AstrBot reads the file only at start-up and its WebUI writes it back whole on save, so the agent's notice says to restart AstrBot before saving in the WebUI. A Docker install's root is inside its container, which magpie doesn't reach. - JSON/JSONC config edits and their previews reject malformed input rather than editing a partially parsed document. Object edits and VS Code's model-group array edits leave the original file untouched on a parse error; valid comments and trailing commas remain supported (`internal/edit`). - Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (`codex.out` marks the move, and Sync undoes it once the account has room). - Moving a field from one of magpie's models to another (the agent's own picker) is not drift. Moving it off magpie is. @@ -70,6 +71,7 @@ go test -tags nogui ./internal/agent -run 'TestConnect|TestDisconnect|Drift|Test go test -tags nogui ./internal/agent go test -tags nogui ./internal/agent -run '^TestAir' go test -tags nogui ./internal/agent -run '^TestAnte' +go test -tags nogui ./internal/agent -run '^TestAstrBot' go test -tags nogui ./internal/agent -run '^TestPlugged' go test -tags nogui ./internal/agent -run 'TestCodexFailoverOnlyKeepsOwnModels|TestCodexOwnModelThroughMagpieWhileAccountsOn|TestCodexHandWrittenBaseURLStays' go test -tags nogui ./internal/agent -run 'TestDisconnectStaysThroughSync|TestCodexDisconnectStaysWithAccountsOn|TestCodexAPIDisconnectStays' diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 992b6ece4..1dac8d9b6 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -113,6 +113,7 @@ func builtins(home, cfg string) []*Agent { muse(cfg), empryo(home), ante(home), + astrbot(home), miniMax(home), droid(home), cline(home), diff --git a/internal/agent/applied_test.go b/internal/agent/applied_test.go index fe140fe00..359745fb7 100644 --- a/internal/agent/applied_test.go +++ b/internal/agent/applied_test.go @@ -155,6 +155,9 @@ func TestDriftUnwiredEveryAgent(t *testing.T) { // OpenHanako gives the model to an agent of its own os.MkdirAll(filepath.Join(home, ".hanako", "agents", "hana"), 0o755) os.WriteFile(filepath.Join(home, ".hanako", "agents", "hana", "config.yaml"), []byte("agent:\n name: Hana\n"), 0o644) + // AstrBot is connected once it has written its settings + os.MkdirAll(filepath.Join(home, ".astrbot", "data"), 0o755) + os.WriteFile(filepath.Join(home, ".astrbot", "data", "cmd_config.json"), []byte(astrbotConfig), 0o644) for _, a := range All() { // agy's gateway is in the command that starts it, in no file (its // Check is TestAgy's) diff --git a/internal/agent/astrbot.go b/internal/agent/astrbot.go new file mode 100644 index 000000000..7a0ae4c42 --- /dev/null +++ b/internal/agent/astrbot.go @@ -0,0 +1,490 @@ +package agent + +// AstrBot (AstrBotDevs/AstrBot, a chatbot framework for QQ, Telegram, +// Discord, Lark and the rest) keeps every setting in one file, +// /data/cmd_config.json, where the root is ASTRBOT_ROOT, else ~/.astrbot +// for the desktop app (AstrBot-desktop's runtime_paths.rs, and +// astrbot_path.get_astrbot_root for a packaged desktop runtime), else the +// folder it was started in: `astrbot init` marks one with a .astrbot file, +// and `astrbot run` there sets ASTRBOT_ROOT to it (cli/commands/cmd_run.py). +// +// Since 4.10 the file splits a chat provider into two lists (default.py, +// the dashboard's buildModelProviderConfig): +// +// "provider_sources": [{"id":…,"provider":"openai", +// "type":"openai_chat_completion","provider_type":"chat_completion", +// "enable":true,"key":["…"],"api_base":"…/v1","timeout":120, +// "proxy":"","custom_headers":{}}], +// "provider": [{"id":"/","enable":true, +// "provider_source_id":"","model":"…", +// "modalities":["text","image","tool_use"],"custom_extra_body":{}, +// "max_context_tokens":0}] +// +// — a source is an endpoint and its keys, each entry of provider one model +// of a source, and what AstrBot runs is the two merged, the model's keys +// winning (ProviderManager.get_merged_provider_config). The types are +// config_service.validate_config's, from default.py's schema: key a list of +// strings, timeout and max_context_tokens ints (0: AstrBot looks the window +// up itself), custom_headers and custom_extra_body objects, modalities a +// list of text/image/audio/tool_use. +// +// magpie adds a source "magpie", OpenAI Compatible at the gateway's /v1 with +// a key naming AstrBot (its requests carry no User-Agent of its own), and an +// entry "magpie//" for every model of magpie's, and makes +// the one picked AstrBot's default chat model: agent_runner.config.model. +// provider_id, which AstrBot reads when agent_runner.runner_type is "local" +// (4.28's ProviderManager._resolve_using_provider), or +// provider_settings.default_provider_id in a file from before agent_runner, +// which AstrBot's migration (migra_helper.py) carries over. The user's own +// sources and models are left where they are, byte for byte, and so is +// what they changed in magpie's own entries in AstrBot's WebUI (a source's +// timeout or proxy, a model switched off, its extra body). A model picked +// for one chat with /provider, which AstrBot keeps in its own database, is +// the user's and stands. The file is copied to cmd_config.json.before-magpie +// before magpie first writes it. +// +// AstrBot reads the file once, at start, and keeps it in memory: its WebUI +// writes the whole of it back on every save. So magpie's change needs +// AstrBot restarted, and a WebUI save made before that restart writes over +// it (Check then says so). AstrBot writes the file with a UTF-8 BOM +// (astrbot_config.py, encoding utf-8-sig), which magpie keeps. +// +// AstrBot in Docker is not one magpie wires: its data folder is a volume +// magpie can't know, and the gateway on this machine's loopback is not the +// container's. + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "reflect" + "slices" + "strings" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/edit" +) + +const ( + astrbotSources = "provider_sources" + astrbotModels = "provider" + // astrbotRunner and astrbotLegacy are where AstrBot's default chat model + // is named, from 4.28 and before it + astrbotRunner = "agent_runner.config.model.provider_id" + astrbotLegacy = "provider_settings.default_provider_id" +) + +// astrbotBOM is the byte order mark AstrBot writes its config with. +var astrbotBOM = []byte("\xef\xbb\xbf") + +// astrbotRoot is the folder AstrBot keeps data/ in: ASTRBOT_ROOT, else the +// desktop app's ~/.astrbot, else a folder `astrbot init` was run in that +// magpie can know of — the home itself (a .astrbot file there), or ~/astrbot +// or ~/AstrBot, where its README and a clone of its source put it. A root +// none of these is reaches magpie through ASTRBOT_ROOT. With none found it is +// the desktop app's, which then isn't there. +func astrbotRoot(at place) string { + if d := strings.TrimSpace(at.getenv("ASTRBOT_ROOT")); d != "" { + return d + } + desktop := filepath.Join(at.home, ".astrbot") + if isFile(filepath.Join(desktop, "data", "cmd_config.json")) { + return desktop + } + if isFile(desktop) { + return at.home + } + for _, d := range []string{"astrbot", "AstrBot"} { + root := filepath.Join(at.home, d) + if isFile(filepath.Join(root, "data", "cmd_config.json")) || isFile(filepath.Join(root, ".astrbot")) { + return root + } + } + return desktop +} + +func astrbot(home string) *Agent { return astrbotAt(here(home)) } + +func astrbotAt(at place) *Agent { + root := astrbotRoot(at) + data := filepath.Join(root, "data") + path := filepath.Join(data, "cmd_config.json") + backup := path + ".before-magpie" + // keyPick is the default chat model AstrBot was on before magpie's + keyPick := at.key("astrbot.provider_id") + key := func() string { return agentKeyAt("astrbot", at.gw()) } + // read is the file without its BOM, and whether it had one + read := func() ([]byte, bool, error) { + raw, err := os.ReadFile(path) + if err != nil { + return nil, false, err + } + if b, ok := bytes.CutPrefix(raw, astrbotBOM); ok { + return b, true, nil + } + return raw, false, nil + } + write := func(raw []byte, bom bool) error { + if bom { + raw = append(append([]byte(nil), astrbotBOM...), raw...) + } + return edit.WriteAtomic(path, raw) + } + get := func(k string) (gjson.Result, bool) { + raw, _, err := read() + if err != nil || !json.Valid(raw) { + return gjson.Result{}, false + } + return gjson.GetBytes(raw, k), true + } + // pickKey is where this file names AstrBot's default chat model + pickKey := func() string { + if r, _ := get("agent_runner"); r.Exists() { + return astrbotRunner + } + return astrbotLegacy + } + pick := func() string { r, _ := get(pickKey()); return r.String() } + // source is magpie's entry in provider_sources + source := func() (gjson.Result, bool) { + r, _ := get(astrbotSources) + for _, e := range r.Array() { + if e.Get("id").String() == magpieID { + return e, true + } + } + return gjson.Result{}, false + } + wired := func() bool { _, ok := source(); return ok } + ours := func() bool { return prefixed(pick()) } + // setPick names AstrBot's default chat model + setPick := func(v string) error { + raw, bom, err := read() + if err != nil { + return err + } + out, err := edit.PatchJSON(raw, []edit.KV{{Path: pickKey(), Value: v}}, nil) + if err != nil { + return err + } + if bytes.Equal(out, raw) { + return nil + } + return write(out, bom) + } + // lists rewrites provider_sources and provider: the user's entries as + // they are, magpie's — when on — after them, as astrbotWired makes them + // from what is there + lists := func(on bool) error { + raw, bom, err := read() + if err != nil { + return err + } + out, err := astrbotWired(raw, on, at.v1(), key()) + if err != nil { + return fmt.Errorf("AstrBot's %s: %w", path, err) + } + if bytes.Equal(out, raw) { + return nil + } + return write(out, bom) + } + // unwire takes magpie's source and models out, and AstrBot back to the + // default chat model it was on — when it is still on one of magpie's: a + // pick the user made in AstrBot since is theirs and stands + unwire := func() error { + if !isFile(path) { + forget(keyPick) + return nil + } + if ours() { + if err := setPick(unstash(keyPick)); err != nil { + return err + } + } else { + forget(keyPick) + } + return lists(false) + } + // put is magpie's source and models in, and AstrBot's default chat model + // the one picked (magpie//). What AstrBot was on is + // saved before it is written over, and only then. + put := func(v string) error { + raw, _, err := read() + if errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("AstrBot has no %s yet: start AstrBot once so it writes its settings (or start magpie with ASTRBOT_ROOT set to the folder AstrBot runs in), then connect it", path) + } + if err != nil { + return err + } + if !json.Valid(raw) { + return fmt.Errorf("AstrBot's %s isn't JSON magpie can read; it was left as it is", path) + } + if !gjson.GetBytes(raw, astrbotSources).Exists() { + return fmt.Errorf("this AstrBot keeps no provider_sources in %s: update AstrBot to 4.10 or later, start it once, then connect it", path) + } + if !wired() { + b, _ := os.ReadFile(path) + if err := os.WriteFile(backup, b, 0o600); err != nil { + return err + } + } + if !ours() { + stash(map[string]string{keyPick: pick()}) + } + if err := lists(true); err != nil { + return err + } + return setPick(v) + } + return atomic(&Agent{ + ID: "astrbot", Name: "AstrBot", Icon: "astrbot", Spelled: prefixed, + Bin: "astrbot", Dir: data, Path: path, + Notice: func() string { + return "AstrBot reads cmd_config.json at start-up and writes it back whole when its WebUI saves settings — restart AstrBot to use this, before saving anything in its WebUI." + }, + Joined: wired, + Unwire: func() error { + if !wired() { + return nil + } + return unwire() + }, + Check: func() string { + if !ours() { + return "" + } + if r, _ := get("agent_runner.runner_type"); pickKey() == astrbotRunner && r.String() != "local" { + return "AstrBot's agent runner (cmd_config.json) is " + orDefault(r.String()) + ", which doesn't ask its chat model, so it no longer asks magpie" + } + e, ok := source() + if !ok { + return "magpie's provider source is gone from AstrBot's " + path + " (a save in AstrBot's WebUI writes its settings back whole) — connect it again" + } + return wiringOff("AstrBot", path, func(k string) (string, bool) { + r := e.Get(k) + return r.String(), r.Exists() + }, "api_base", at.v1(), "key.0", key()) + }, + Sync: func() error { + if !wired() { + return nil + } + return lists(true) + }, + Fields: []Field{{ + // AstrBot's default chat model, by its provider id: one of + // magpie's is magpie//, the id magpie gives + // its entry in provider, which is "/" as + // AstrBot's own WebUI names them + Key: "model", Label: "model", + Get: pick, + Set: func(v string) error { + if v == "" { + if ours() { + return unwire() + } + return setPick("") + } + if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) { + return put(v) + } + // one of the user's own: AstrBot goes onto it, magpie's + // models left beside it in its list until Disconnect + if ours() { + forget(keyPick) + } + return setPick(v) + }, + Options: func(cur map[string]string) []Option { + return append(astrbotOwn(path, cur["model"]), viaMagpie("astrbot", magpieID+"/")...) + }, + }}, + }, path) +} + +// astrbotOwn is the user's own chat models in AstrBot's file, by the +// provider id AstrBot names them with, for the picker. +func astrbotOwn(path, cur string) []Option { + var out []Option + raw, err := os.ReadFile(path) + if err != nil { + return nil + } + raw = bytes.TrimPrefix(raw, astrbotBOM) + seen := map[string]bool{} + for _, e := range gjson.GetBytes(raw, astrbotModels).Array() { + id := e.Get("id").String() + if id == "" || prefixed(id) || seen[id] { + continue + } + if t := e.Get("provider_type").String(); t != "" && t != "chat_completion" { + continue + } + seen[id] = true + out = append(out, Option{Value: id, Label: id, Note: "AstrBot's own"}) + } + if cur != "" && !prefixed(cur) && !seen[cur] { + out = append(out, Option{Value: cur, Label: cur, Note: "AstrBot's own"}) + } + return out +} + +// astrbotWired is raw, AstrBot's config, with provider_sources and provider +// holding the user's entries as they are and, when on, magpie's after them: +// its source at gw (the gateway's /v1) with key, and one entry for each of +// magpie's models. What the user changed in magpie's entries is kept +// (astrbotKeep). +func astrbotWired(raw []byte, on bool, gw, key string) ([]byte, error) { + var wantSource map[string]any + var wantModels []map[string]any + if on { + wantSource = astrbotSourceJSON(gw, key) + for _, m := range magpieModels("astrbot") { + wantModels = append(wantModels, astrbotModelJSON(m)) + } + } + var err error + raw, err = astrbotList(raw, astrbotSources, func(e gjson.Result) bool { return e.Get("id").String() == magpieID }, + astrbotKeep(raw, astrbotSources, []map[string]any{wantSource}, astrbotSourceOwned)) + if err != nil { + return nil, err + } + return astrbotList(raw, astrbotModels, func(e gjson.Result) bool { return e.Get("provider_source_id").String() == magpieID }, + astrbotKeep(raw, astrbotModels, wantModels, astrbotModelOwned)) +} + +// astrbotSourceOwned and astrbotModelOwned are the keys of magpie's entries +// that are magpie's to say; every other key of one is the user's to change +// in AstrBot's WebUI, and stays as they left it. +var ( + astrbotSourceOwned = []string{"id", "provider", "type", "provider_type", "key", "api_base"} + astrbotModelOwned = []string{"id", "provider_source_id", "model", "modalities", "max_context_tokens"} +) + +// astrbotKeep is want, magpie's entries for the list at k, each with the +// keys of the entry of the same id already in raw that aren't magpie's to +// say (owned) kept as they are. +func astrbotKeep(raw []byte, k string, want []map[string]any, owned []string) []map[string]any { + have := map[string]map[string]json.RawMessage{} + for _, e := range gjson.GetBytes(raw, k).Array() { + var m map[string]json.RawMessage + if json.Unmarshal([]byte(e.Raw), &m) == nil { + have[e.Get("id").String()] = m + } + } + var out []map[string]any + for _, w := range want { + if w == nil { + continue + } + id, _ := w["id"].(string) + for hk, hv := range have[id] { + if !slices.Contains(owned, hk) { + w[hk] = hv + } + } + out = append(out, w) + } + return out +} + +// astrbotList is raw with the top-level list at k rewritten: its entries +// that aren't magpie's (mine) as they are, byte for byte, then add. Nothing +// else of the file changes. +func astrbotList(raw []byte, k string, mine func(gjson.Result) bool, add []map[string]any) ([]byte, error) { + r := gjson.GetBytes(raw, k) + if !r.Exists() { + if len(add) == 0 { + return raw, nil + } + return nil, fmt.Errorf("no %s list", k) + } + if !r.IsArray() { + return nil, fmt.Errorf("%s is not a list", k) + } + base := "" + if start := bytes.LastIndexByte(raw[:r.Index], '\n') + 1; start < r.Index { + for i := start; i < r.Index && (raw[i] == ' ' || raw[i] == '\t'); i++ { + base += string(raw[i]) + } + } + in := base + " " + var items []string + for _, e := range r.Array() { + if !mine(e) { + items = append(items, e.Raw) + } + } + for _, a := range add { + var b bytes.Buffer + enc := json.NewEncoder(&b) + // AstrBot writes with ensure_ascii off: a model's name stays as it is + enc.SetEscapeHTML(false) + enc.SetIndent(in, " ") + if err := enc.Encode(a); err != nil { + return nil, err + } + items = append(items, strings.TrimRight(b.String(), "\n")) + } + list := "[]" + if len(items) > 0 { + list = "[\n" + in + strings.Join(items, ",\n"+in) + "\n" + base + "]" + } + // the same entries, though AstrBot wrote them in another order of + // keys, are no change: a file that says the same isn't written again + var was, now any + if list == r.Raw || json.Unmarshal([]byte(r.Raw), &was) == nil && json.Unmarshal([]byte(list), &now) == nil && reflect.DeepEqual(was, now) { + return raw, nil + } + out := make([]byte, 0, len(raw)+len(list)) + out = append(out, raw[:r.Index]...) + out = append(out, list...) + return append(out, raw[r.Index+len(r.Raw):]...), nil +} + +// astrbotSourceJSON is magpie's provider source: AstrBot's OpenAI Compatible +// template (default.py's "OpenAI" in CONFIG_METADATA_2's provider templates) +// at the gateway's /v1, with a key naming AstrBot. +func astrbotSourceJSON(gw, key string) map[string]any { + return map[string]any{ + "id": magpieID, + "provider": "openai", + "type": "openai_chat_completion", + "provider_type": "chat_completion", + "enable": true, + "key": []string{key}, + "api_base": gw, + "timeout": 120, + "proxy": "", + "custom_headers": map[string]any{}, + } +} + +// astrbotModelJSON is one of magpie's models as an entry of AstrBot's +// provider list. Every one is said to take tools: AstrBot drops a model's +// tools when tool_use isn't in its modalities (modalities.py), and the +// gateway hands a tool call on whatever the model. Images are what magpie +// knows the model sees, or describes to it. A window magpie doesn't know is +// 0, which has AstrBot look it up itself. +func astrbotModelJSON(m catalog.Model) map[string]any { + mods := []string{"text"} + if m.Images { + mods = append(mods, "image") + } + mods = append(mods, "tool_use") + return map[string]any{ + "id": magpieID + "/" + m.ID, + "enable": true, + "provider_source_id": magpieID, + "model": m.ID, + "modalities": mods, + "custom_extra_body": map[string]any{}, + "max_context_tokens": m.Context, + } +} diff --git a/internal/agent/astrbot_test.go b/internal/agent/astrbot_test.go new file mode 100644 index 000000000..0323ec9b5 --- /dev/null +++ b/internal/agent/astrbot_test.go @@ -0,0 +1,466 @@ +package agent + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// astrbotConfig is a cmd_config.json as AstrBot 4.28.2 writes it (json.dump, +// indent 2, ensure_ascii off, utf-8-sig) with the user's own DeepSeek source +// and one model of it — the shape its WebUI's buildModelProviderConfig makes +// — picked as the default chat model. The rest of the file is cut to a few +// of its keys. +const astrbotConfig = "\xef\xbb\xbf" + `{ + "config_version": 3, + "provider_sources": [ + { + "id": "deepseek", + "provider": "deepseek", + "type": "openai_chat_completion", + "provider_type": "chat_completion", + "enable": true, + "key": [ + "sk-user" + ], + "api_base": "https://api.deepseek.com/v1", + "timeout": 120, + "proxy": "", + "custom_headers": {} + } + ], + "provider": [ + { + "id": "deepseek/deepseek-chat", + "enable": true, + "provider_source_id": "deepseek", + "model": "deepseek-chat", + "modalities": [ + "text", + "tool_use" + ], + "custom_extra_body": {}, + "max_context_tokens": 0 + } + ], + "provider_settings": { + "enable": true, + "wake_prefix": "", + "web_search": false + }, + "agent_runner": { + "runner_type": "local", + "config": { + "model": { + "provider_id": "deepseek/deepseek-chat", + "fallback_provider_ids": [], + "request_max_retries": 5 + } + } + }, + "dashboard": { + "enable": true, + "username": "astrbot", + "port": 6185 + }, + "timezone": "Asia/Shanghai" +}` + +// astrbotHome is a HOME with the AstrBot desktop app's ~/.astrbot holding +// body as its cmd_config.json, and magpie with a provider of two models. +func astrbotHome(t *testing.T, body string) (home, path string) { + t.Helper() + 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")) + t.Setenv("ASTRBOT_ROOT", "") + if err := provider.Save(provider.Provider{ID: "kimi", Name: "Kimi", Key: "k", + Chat: "https://api.moonshot.cn/v1", Models: []string{"k2", "k2-vision"}}); err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive("kimi", "https://api.moonshot.cn/v1", []catalog.Model{ + {ID: "k2", Context: 262144}, + {ID: "k2-vision", Images: true}, + }); err != nil { + t.Fatal(err) + } + path = filepath.Join(home, ".astrbot", "data", "cmd_config.json") + if body != "" { + writeFile(t, path, body) + } + return home, path +} + +func astrbotRead(t *testing.T, path string) map[string]any { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !bytes.HasPrefix(b, astrbotBOM) { + t.Fatalf("%s lost AstrBot's BOM:\n%.40q", path, b) + } + var m map[string]any + if err := json.Unmarshal(bytes.TrimPrefix(b, astrbotBOM), &m); err != nil { + t.Fatalf("%s is not JSON: %v\n%s", path, err, b) + } + return m +} + +// astrbotByID is the entries of the list at k, by id. +func astrbotByID(t *testing.T, m map[string]any, k string) map[string]map[string]any { + t.Helper() + out := map[string]map[string]any{} + for _, x := range m[k].([]any) { + e := x.(map[string]any) + out[e["id"].(string)] = e + } + return out +} + +// astrbotReversed is r indented as AstrBot writes it, every object's keys in +// the reverse of their order: the same settings, in an order magpie doesn't +// write them in. +func astrbotReversed(r gjson.Result, in string) string { + switch { + case r.IsObject(): + var kv []string + r.ForEach(func(k, v gjson.Result) bool { + kv = append([]string{in + " " + k.Raw + ": " + astrbotReversed(v, in+" ")}, kv...) + return true + }) + if len(kv) == 0 { + return "{}" + } + return "{\n" + strings.Join(kv, ",\n") + "\n" + in + "}" + case r.IsArray(): + var vs []string + for _, v := range r.Array() { + vs = append(vs, in+" "+astrbotReversed(v, in+" ")) + } + if len(vs) == 0 { + return "[]" + } + return "[\n" + strings.Join(vs, ",\n") + "\n" + in + "]" + } + return r.Raw +} + +// astrbotEdit changes AstrBot's settings as its WebUI does: the whole file +// written again from what it holds, keys in an order of its own. +func astrbotEdit(t *testing.T, path string, change func(m map[string]any)) { + t.Helper() + m := astrbotRead(t, path) + change(m) + var b bytes.Buffer + b.Write(astrbotBOM) + enc := json.NewEncoder(&b) + enc.SetIndent("", " ") + enc.SetEscapeHTML(false) + if err := enc.Encode(m); err != nil { + t.Fatal(err) + } + writeFile(t, path, b.String()) +} + +func astrbotPick(m map[string]any) any { + return m["agent_runner"].(map[string]any)["config"].(map[string]any)["model"].(map[string]any)["provider_id"] +} + +// Connecting AstrBot adds magpie's provider source and one model entry for +// each of magpie's models, typed as AstrBot's validator types them, and +// makes the one picked AstrBot's default chat model. The user's own source +// and model stay as they were, the file keeps its BOM, a copy of it is kept +// before magpie writes, and Disconnect gives back the file byte for byte. +func TestAstrBot(t *testing.T) { + home, path := astrbotHome(t, astrbotConfig) + a := astrbot(home) + if a.Path != path || !a.Detected() { + t.Fatalf("path %q, detected %v", a.Path, a.Detected()) + } + f := a.Field("model") + if got := f.Get(); got != "deepseek/deepseek-chat" || a.Wired() || a.Check() != "" { + t.Fatalf("before: %q wired %v check %q", got, a.Wired(), a.Check()) + } + var own, ours bool + for _, o := range f.Options(a.Values()) { + own = own || o.Value == "deepseek/deepseek-chat" + ours = ours || o.Value == "magpie/kimi/k2" + } + if !own || !ours { + t.Fatalf("options: own %v magpie %v", own, ours) + } + + if err := a.Pick("model", "magpie/kimi/k2"); err != nil { + t.Fatal(err) + } + m := astrbotRead(t, path) + if got := astrbotPick(m); got != "magpie/kimi/k2" { + t.Fatalf("default chat model %v", got) + } + if !a.Wired() || f.Get() != "magpie/kimi/k2" { + t.Fatalf("wired %v, model %q", a.Wired(), f.Get()) + } + if c := a.Check(); c != "" { + t.Fatalf("check: %s", c) + } + sources := astrbotByID(t, m, "provider_sources") + src := sources["magpie"] + if src == nil || src["type"] != "openai_chat_completion" || src["provider_type"] != "chat_completion" || + !strings.HasSuffix(src["api_base"].(string), "/v1") || src["timeout"] != float64(120) { + t.Fatalf("magpie's source: %v", src) + } + if k, _ := src["key"].([]any); len(k) != 1 || k[0] != agentKeyAt("astrbot", here(home).gw()) { + t.Fatalf("magpie's key must be a list of the key naming AstrBot: %v", src["key"]) + } + if !reflect.DeepEqual(sources["deepseek"]["key"], []any{"sk-user"}) { + t.Fatalf("the user's source: %v", sources["deepseek"]) + } + models := astrbotByID(t, m, "provider") + k2, vision := models["magpie/kimi/k2"], models["magpie/kimi/k2-vision"] + if k2 == nil || vision == nil || models["deepseek/deepseek-chat"] == nil { + t.Fatalf("models: %v", models) + } + // k2 takes images only when magpie describes them to it + k2mods := []any{"text", "tool_use"} + if provider.Described != nil && provider.Described() { + k2mods = []any{"text", "image", "tool_use"} + } + if k2["provider_source_id"] != "magpie" || k2["model"] != "kimi/k2" || k2["max_context_tokens"] != float64(262144) || + !reflect.DeepEqual(k2["modalities"], k2mods) || !reflect.DeepEqual(k2["custom_extra_body"], map[string]any{}) { + t.Fatalf("k2: %v", k2) + } + if !reflect.DeepEqual(vision["modalities"], []any{"text", "image", "tool_use"}) || vision["max_context_tokens"] != float64(0) { + t.Fatalf("k2-vision: %v", vision) + } + // the user's own entries are as they were, byte for byte, in front of + // magpie's + b, _ := os.ReadFile(path) + for _, own := range []string{ + astrbotConfig[strings.Index(astrbotConfig, " {\n \"id\": \"deepseek\",") : strings.Index(astrbotConfig, " ],\n \"provider\": [")-1], + astrbotConfig[strings.Index(astrbotConfig, " {\n \"id\": \"deepseek/deepseek-chat\"") : strings.Index(astrbotConfig, " ],\n \"provider_settings\"")-1], + } { + if !bytes.Contains(b, []byte(own+",\n {\n \"")) { + t.Fatalf("the user's entry changed or moved:\n%s\nin\n%s", own, b) + } + } + if bk, err := os.ReadFile(path + ".before-magpie"); err != nil || string(bk) != astrbotConfig { + t.Fatalf("backup: %v\n%s", err, bk) + } + + // switching between magpie's models keeps what AstrBot was on before + // magpie, and leaves the backup as it was + if err := a.Pick("model", "magpie/kimi/k2-vision"); err != nil { + t.Fatal(err) + } + if bk, _ := os.ReadFile(path + ".before-magpie"); string(bk) != astrbotConfig { + t.Fatalf("the backup was written over:\n%s", bk) + } + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(path); string(got) != astrbotConfig { + t.Fatalf("Disconnect left:\n%s", got) + } + if a.Wired() { + t.Fatal("still wired") + } +} + +// What the user changes in magpie's entries in AstrBot's WebUI — a timeout, +// a proxy, a model switched off — is theirs: a catalog sync rewrites the +// list of models and the endpoint, not those. A sync that has nothing to +// change doesn't write, though AstrBot wrote the entries' keys in an order +// of its own. +func TestAstrBotSyncKeepsTheirs(t *testing.T) { + home, path := astrbotHome(t, astrbotConfig) + a := astrbot(home) + if err := a.Pick("model", "magpie/kimi/k2"); err != nil { + t.Fatal(err) + } + // as AstrBot's WebUI saves it: the whole file, from what it holds + astrbotEdit(t, path, func(m map[string]any) { + src := astrbotByID(t, m, "provider_sources")["magpie"] + src["timeout"], src["proxy"] = 300, "http://127.0.0.1:7890" + astrbotByID(t, m, "provider")["magpie/kimi/k2-vision"]["enable"] = false + }) + // a model magpie lists no more leaves AstrBot's list; one it lists + // now comes in + if err := catalog.SaveLive("kimi", "https://api.moonshot.cn/v1", []catalog.Model{ + {ID: "k2", Context: 262144}, {ID: "k2-vision", Images: true}, {ID: "k3"}, + }); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "kimi", Name: "Kimi", Key: "k", + Chat: "https://api.moonshot.cn/v1", Models: []string{"k2", "k2-vision", "k3"}}); err != nil { + t.Fatal(err) + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + m := astrbotRead(t, path) + src := astrbotByID(t, m, "provider_sources")["magpie"] + if src["timeout"] != float64(300) || src["proxy"] != "http://127.0.0.1:7890" { + t.Fatalf("the user's timeout and proxy were written over: %v", src) + } + models := astrbotByID(t, m, "provider") + if models["magpie/kimi/k2-vision"]["enable"] != false { + t.Fatalf("a model the user switched off came back on: %v", models["magpie/kimi/k2-vision"]) + } + if models["magpie/kimi/k3"] == nil { + t.Fatalf("a model magpie lists now isn't in AstrBot's list: %v", models) + } + + // AstrBot's WebUI writes every key back in an order of its own; the + // same entries again are no change + b, _ := os.ReadFile(path) + saved := append(append([]byte(nil), astrbotBOM...), astrbotReversed(gjson.ParseBytes(bytes.TrimPrefix(b, astrbotBOM)), "")...) + writeFile(t, path, string(saved)) + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(path); !bytes.Equal(got, saved) { + t.Fatalf("a sync with nothing to change wrote the file:\n%s", got) + } +} + +// Picking no model of magpie's in the picker puts AstrBot back on the one it +// was on before magpie, and takes magpie's source and models out. +func TestAstrBotNoModelPutsTheirsBack(t *testing.T) { + home, path := astrbotHome(t, astrbotConfig) + a := astrbot(home) + if err := a.Pick("model", "magpie/kimi/k2"); err != nil { + t.Fatal(err) + } + if err := a.Field("model").Set(""); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(path); string(got) != astrbotConfig { + t.Fatalf("left:\n%s", got) + } +} + +// A default chat model the user picks in AstrBot while magpie is wired is +// theirs: Disconnect takes magpie's source and models out and leaves the +// pick as it is. +func TestAstrBotTheirPickStands(t *testing.T) { + home, path := astrbotHome(t, astrbotConfig) + a := astrbot(home) + if err := a.Pick("model", "magpie/kimi/k2"); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(path) + writeFile(t, path, strings.Replace(string(b), `"provider_id": "magpie/kimi/k2"`, `"provider_id": "openai/gpt-5"`, 1)) + if !a.Wired() { + t.Fatal("magpie's models are still in AstrBot's list: it is connected") + } + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + m := astrbotRead(t, path) + if got := astrbotPick(m); got != "openai/gpt-5" { + t.Fatalf("the user's pick became %v", got) + } + if _, ok := astrbotByID(t, m, "provider_sources")["magpie"]; ok { + t.Fatal("magpie's source stayed") + } + for id := range astrbotByID(t, m, "provider") { + if strings.HasPrefix(id, "magpie/") { + t.Fatalf("magpie's model %s stayed", id) + } + } +} + +// Before 4.28 AstrBot named its default chat model in +// provider_settings.default_provider_id, with no agent_runner; magpie sets +// that one there, and puts it back. +func TestAstrBotBeforeAgentRunner(t *testing.T) { + old := strings.Replace(astrbotConfig, `"web_search": false`, `"web_search": false, + "default_provider_id": "deepseek/deepseek-chat"`, 1) + old = old[:strings.Index(old, ` "agent_runner"`)] + old[strings.Index(old, ` "dashboard"`):] + home, path := astrbotHome(t, old) + a := astrbot(home) + if got := a.Field("model").Get(); got != "deepseek/deepseek-chat" { + t.Fatalf("model %q", got) + } + if err := a.Pick("model", "magpie/kimi/k2"); err != nil { + t.Fatal(err) + } + m := astrbotRead(t, path) + if _, ok := m["agent_runner"]; ok { + t.Fatal("magpie made an agent_runner of its own") + } + if got := m["provider_settings"].(map[string]any)["default_provider_id"]; got != "magpie/kimi/k2" { + t.Fatalf("default_provider_id %v", got) + } + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(path); string(got) != old { + t.Fatalf("Disconnect left:\n%s", got) + } +} + +// magpie writes no AstrBot settings of its own: with no cmd_config.json yet +// (AstrBot never started) or one from before provider_sources (older than +// 4.10), it says what to do and leaves the folder as it is. +func TestAstrBotRefusesWithoutItsSettings(t *testing.T) { + home, path := astrbotHome(t, "") + os.MkdirAll(filepath.Join(home, ".astrbot"), 0o755) + a := astrbot(home) + if err := a.Pick("model", "magpie/kimi/k2"); err == nil || !strings.Contains(err.Error(), "start AstrBot once") { + t.Fatalf("no settings: %v", err) + } + if isFile(path) { + t.Fatal("magpie made AstrBot's settings") + } + old := `{"provider": [{"id": "openai", "type": "openai_chat_completion", "key": ["sk"]}], "provider_settings": {"default_provider_id": "openai"}}` + writeFile(t, path, old) + if err := astrbot(home).Pick("model", "magpie/kimi/k2"); err == nil || !strings.Contains(err.Error(), "4.10") { + t.Fatalf("before provider_sources: %v", err) + } + if got, _ := os.ReadFile(path); string(got) != old { + t.Fatalf("the file changed:\n%s", got) + } +} + +// AstrBot's root: ASTRBOT_ROOT, the desktop app's ~/.astrbot, or a folder +// `astrbot init` was run in that magpie can know of. +func TestAstrBotRoot(t *testing.T) { + home, _ := astrbotHome(t, "") + at := here(home) + if got := astrbotRoot(at); got != filepath.Join(home, ".astrbot") { + t.Fatalf("nothing there: %s", got) + } + writeFile(t, filepath.Join(home, "AstrBot", ".astrbot"), "") + if got := astrbotRoot(at); !sameDir(got, filepath.Join(home, "AstrBot")) { + t.Fatalf("~/AstrBot: %s", got) + } + writeFile(t, filepath.Join(home, ".astrbot"), "") + if got := astrbotRoot(at); got != home { + t.Fatalf("init in the home: %s", got) + } + t.Setenv("ASTRBOT_ROOT", filepath.Join(home, "bots", "mine")) + if got := astrbotRoot(here(home)); got != filepath.Join(home, "bots", "mine") { + t.Fatalf("ASTRBOT_ROOT: %s", got) + } +} + +// sameDir says a and b are one folder, on a file system that may not tell +// names' cases apart (macOS's, where ~/astrbot is ~/AstrBot). +func sameDir(a, b string) bool { + sa, err1 := os.Stat(a) + sb, err2 := os.Stat(b) + return err1 == nil && err2 == nil && os.SameFile(sa, sb) +} diff --git a/internal/agent/rewire_test.go b/internal/agent/rewire_test.go index a1d43fc5c..64938e6aa 100644 --- a/internal/agent/rewire_test.go +++ b/internal/agent/rewire_test.go @@ -49,6 +49,9 @@ func TestPortMovesEveryAgent(t *testing.T) { almaApp := startAlma(t) os.MkdirAll(filepath.Join(home, ".hanako", "agents", "hana"), 0o755) os.WriteFile(filepath.Join(home, ".hanako", "agents", "hana", "config.yaml"), []byte("agent:\n name: Hana\n"), 0o644) + // AstrBot is connected once it has written its settings + os.MkdirAll(filepath.Join(home, ".astrbot", "data"), 0o755) + os.WriteFile(filepath.Join(home, ".astrbot", "data", "cmd_config.json"), []byte(astrbotConfig), 0o644) setPort(t, 3591) if gateway.URL() != "http://127.0.0.1:3591" { t.Fatalf("Settings' port isn't the gateway's: %s", gateway.URL()) diff --git a/internal/agentenv/agentenv.go b/internal/agentenv/agentenv.go index bc25acf02..9d9969274 100644 --- a/internal/agentenv/agentenv.go +++ b/internal/agentenv/agentenv.go @@ -55,6 +55,8 @@ var Vars = []string{ "QWEN_HOME", // Ante "ANTE_HOME", + // AstrBot's root, the folder holding its data/ (else ~/.astrbot, the desktop app's) + "ASTRBOT_ROOT", // MiMo Code, MiniMax Code, OpenHanako, Hermes, dsh, WorkBuddy, CodeBuddy Code "MIMOCODE_HOME", "MINIMAX_DATA_DIR", "HANA_HOME", "HERMES_HOME", "DSH_HOME", "WORKBUDDY_CONFIG_DIR", "CODEBUDDY_CONFIG_DIR", diff --git a/internal/gui/assets/icons/astrbot.svg b/internal/gui/assets/icons/astrbot.svg new file mode 100644 index 000000000..b898aab00 --- /dev/null +++ b/internal/gui/assets/icons/astrbot.svg @@ -0,0 +1 @@ +AstrBot