diff --git a/README.md b/README.md index 99c07849a..80be947c1 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ magpie finds the subscriptions your agents are signed in to by reading their sig
-Claude Code · Claude Desktop · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · Pi · oh-my-pi · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy +Claude Code · Claude Desktop · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · Pi · oh-my-pi · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy
diff --git a/README.zh-CN.md b/README.zh-CN.md index a8787b6ac..fbd56be07 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -72,7 +72,7 @@ magpie 通过读取智能体的登录信息(Claude Code 和 Codex 的文件、
-Claude Code · Claude Desktop · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · Pi · oh-my-pi · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy +Claude Code · Claude Desktop · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · Pi · oh-my-pi · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy
diff --git a/docs/reference.md b/docs/reference.md index 5faa9336c..f59661dc1 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -127,6 +127,7 @@ line; agents connected to magpie lose it when it quits. | Qoder (CLI) | `~/.qoder/settings.json` (`$QODER_CONFIG_DIR`) | model, effort (a `magpie` custom provider; needs a Qoder plan with BYOK) | | Qoder CN (CLI) | `~/.qoder-cn/settings.json` (`$QODERCN_CONFIG_DIR`) | model, effort (as Qoder; its own accounts, a Qoder CN plan with BYOK) | | Grok Build | `~/.grok/config.toml` (`$GROK_HOME`) | model, effort | +| Grok App | `agent-home/config.toml` in its data folder (`$GROK_APP_HOME`, else `~/Library/Application Support/com.grokapp.grok-app`, `%APPDATA%\grokapp\grok-app\data`, `$XDG_DATA_HOME/grok-app`, or `~/.grok-app`) | model (a `[model.magpie]` provider channel as the App's Providers page writes one, with magpie's models and their effort levels in `app_models`; `[models] default = "magpie"`, what was there put back on Disconnect; a model or default effort picked in the App kept; effort is picked in the App's composer; MCP servers and skills reach it through Grok Build's row) | | ZCode | `~/.zcode/v2/config.json` | provider (magpie's models in ZCode's picker) | | WorkBuddy | `~/.workbuddy/models.json` (`$WORKBUDDY_CONFIG_DIR`) | provider (magpie's models in WorkBuddy's picker) | | WorkBuddy AI | `~/.workbuddy-ai/models.json` (the international build) | provider (magpie's models in WorkBuddy AI's picker) | diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 3b3afc244..97e1cd79e 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -44,6 +44,7 @@ something else shows up as drift. - 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. - jcode keeps its settings in `config.toml` in `$JCODE_HOME`, else `~/.jcode` (`jcode` in [`jcode.go`](../../internal/agent/jcode.go)). magpie adds a named profile, `[providers.magpie]`, as `jcode provider add` writes one: `type = "openai-compatible"`, the gateway's `/v1`, an inline `api_key` naming jcode (jcode sends nothing else that tells it apart) and `requires_api_key = true`, since jcode sends no key to a loopback URL without it. Its `models` list has one entry per model, with `context_window`, `input` and `reasoning` for a model with effort levels. A `reasoning_effort` the user set on one stays while the model has that level. The model jcode starts on is `[provider] default_provider = "magpie"` and `default_model`. What was there is stashed and put back on Disconnect. A model of jcode's own picked while it is on magpie takes magpie out. Each key is set alone, so the user's other keys and tables stay, and the `[[providers.magpie.models]]` tables jcode writes when it saves the file itself are replaced by the one list. A sync with nothing to change doesn't write. Disconnect drops the profile whole, its sub-tables included. jcode reads the file when it starts, so the notice says to restart open sessions. +- Grok App (RongleCat/grok-app, a desktop front end that starts Grok Build over ACP) keeps its provider channels in `agent-home/config.toml` under its data folder: `$GROK_APP_HOME`, else where its `directories` crate puts it, or its `~/.grok-app` fallback when that is the one there (`grokApp` in [`grokapp.go`](../../internal/agent/grokapp.go)). Its composer lists only Grok Build's official catalog, never the `[model."magpie/…"]` tables of Grok Build's row, so magpie adds itself as a channel, `[model.magpie]`, with the keys the App's Providers page writes: the gateway's `/v1`, a key naming Grok App, `api_backend = "chat_completions"`, `app_provider_mode = "generic"`, and `app_models`, a JSON list of magpie's models with `contextWindow`, `supportsVision` and their effort levels (no `none`; a default the user marks in the App stays, else medium). The picked model's `context_window` (a bare integer) and `supports_reasoning_effort` (a bare bool, Grok Build's gate for `--reasoning-effort`) are on the channel, as the App puts them there when a model is picked in its composer. `[models] default = "magpie"` makes it the route; what was there is stashed and put back on Disconnect, which drops the channel. A model picked in the App's composer since is the user's and stays through a sync, and a sync with nothing to change doesn't write. The App switches itself to its independent mode when a channel is the route, so Grok Build then runs with `GROK_HOME` at agent-home; MCP servers still reach it, since the App reads `~/.grok/config.toml`'s `[mcp_servers]` in both modes and hands them to each session, and skills are Grok Build's `~/.agents/skills`. The notice, while the App runs, says to start a new chat or restart it. - 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`). - A config that starts with a UTF-8 byte order mark (a Windows `settings.json` or `config.toml` saved by PowerShell, Notepad or a channel switcher, #1534) is read without it (`edit.Read`), and a write keeps it (`keepBOM` in `WriteAtomic`): the user's file keeps the encoding it was saved in. That covers every format `internal/edit` writes (JSON/JSONC and its arrays, TOML, YAML, env); Codex reads a TOML file through a BOM too, so magpie no longer refuses one. A file read some other way trims it with `edit.TrimBOM` (the Claude Code and CC Switch imports). A line an edit takes out of a CRLF file goes with its `\r\n`. - 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). @@ -83,6 +84,7 @@ go test -tags nogui ./internal/edit -run 'BOM|CRLF' go test -tags nogui ./internal/agent -run '^TestAnte' go test -tags nogui ./internal/agent -run '^TestAstrBot' go test -tags nogui ./internal/agent -run '^TestJcode' +go test -tags nogui ./internal/agent -run '^TestGrokApp' go test -tags nogui ./internal/agent -run '^TestPlugged' go test -tags nogui ./internal/agent -run 'TestCodexFailoverOnlyKeepsOwnModels|TestCodexOwnModelThroughMagpieWhileAccountsOn|TestCodexHandWrittenBaseURLStays|TestCodexProxyFor|TestRealProxyProbe|TestCodexFailoverHeldWhileProxyDoesNotPassOn|TestCodexProxiedDrift|TestCodexFailoverEndsWithMagpie|TestCodexMirrorFailoverHeldAndEndsWithMagpie' go test -tags nogui ./internal/agent -run 'TestDisconnectStaysThroughSync|TestCodexDisconnectStaysWithAccountsOn|TestCodexAPIDisconnectStays' diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 8ff60cf97..4a5dd6767 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -128,6 +128,7 @@ func builtins(home, cfg string) []*Agent { qoder(home), qoderCN(home), grok(home), + grokApp(home), zcode(home), workbuddy(home), workbuddyAI(home), diff --git a/internal/agent/grokapp.go b/internal/agent/grokapp.go new file mode 100644 index 000000000..22b4e718f --- /dev/null +++ b/internal/agent/grokapp.go @@ -0,0 +1,399 @@ +package agent + +// Grok App (RongleCat/grok-app, Tauri) is a desktop front end for the grok +// CLI, which it starts over ACP. Most of what the CLI reads it reads where +// Grok Build's own row writes it: MCP servers from ~/.grok/config.toml, +// which the App reads and hands each session itself in either of its modes, +// skills from ~/.agents/skills, instructions from AGENTS.md. Its models are +// its own, though: its composer lists only Grok Build's official catalog +// (models_cache.json), never a [model.""] table of config.toml, and a +// model of the user's choosing is a "provider channel" of its Settings › +// Providers page, a [model.] table with the App's own keys in +// agent-home/config.toml under its data folder. That file is the CLI's +// config.toml while a channel is on: [models] default naming a channel is +// what the App takes as the route, and it then starts the CLI with +// GROK_HOME at agent-home, switching itself to its independent mode +// (grok-app's providers.rs, ensure_independent_for_custom_route). +// +// So magpie adds itself as the channel "magpie", written as the App writes +// one (upsert_custom_provider): the gateway as base_url with Grok App's own +// key, chat completions, app_models a JSON list of magpie's models with each +// one's context window, images and effort levels, so the composer offers +// them and their efforts. The model picked is the channel's model and +// [models] default is "magpie"; what default was before is stashed and put +// back on Disconnect. A model the user picks in the App's composer since is +// theirs and stays through a sync. + +import ( + "encoding/json" + "os" + "path/filepath" + "runtime" + "slices" + "strconv" + "strings" + + "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/edit" +) + +// grokAppChannel is magpie's channel's table in the App's config.toml. +const grokAppChannel = "model." + magpieID + +// what Grok App says after a change (notice.go) +var noticeGrokApp = newNotice("Grok App reads its providers when it starts an agent — start a new chat in Grok App, or restart it, to use this.") + +// grokAppOS is the system grokAppDir looks for the App's data on; a test +// sets it. +var grokAppOS = runtime.GOOS + +// grokAppDir is the App's data folder: $GROK_APP_HOME, else where the +// directories crate's ProjectDirs("com", "grokapp", "grok-app") puts its +// data (grok-app's paths.rs app_data_root) — on a Mac ~/Library/Application +// Support/com.grokapp.grok-app, on Windows %APPDATA%\grokapp\grok-app\data, +// on Linux $XDG_DATA_HOME/grok-app. The App's README names ~/.grok-app on +// Linux and %APPDATA%\grokapp\grok-app on Windows, and the App falls back to +// ~/.grok-app (%APPDATA%\grok-app) itself, so those are looked for too; the +// first that is there wins, else the App's own default. +func grokAppDir(home, goos string) string { + if d := strings.TrimSpace(appdir.Getenv("GROK_APP_HOME")); d != "" { + return d + } + var dirs []string + switch goos { + case "darwin": + dirs = []string{filepath.Join(home, "Library", "Application Support", "com.grokapp.grok-app"), filepath.Join(home, ".grok-app")} + case "windows": + app := appdir.Getenv("APPDATA") + if app == "" { + app = filepath.Join(home, "AppData", "Roaming") + } + dirs = []string{filepath.Join(app, "grokapp", "grok-app", "data"), filepath.Join(app, "grokapp", "grok-app"), filepath.Join(app, "grok-app")} + default: + data := appdir.Getenv("XDG_DATA_HOME") + if data == "" { + data = filepath.Join(home, ".local", "share") + } + dirs = []string{filepath.Join(data, "grok-app"), filepath.Join(home, ".grok-app")} + } + for _, d := range dirs { + if isDir(d) { + return d + } + } + return dirs[0] +} + +// grokAppEffort is one effort level of a channel's model, as the App's +// ProviderEffortEntry reads it. +type grokAppEffort struct { + ID string `json:"id"` + Name string `json:"name"` + IsDefault bool `json:"isDefault"` +} + +// grokAppModel is one entry of a channel's app_models, as the App's +// ProviderModelEntry reads it. +type grokAppModel struct { + ID string `json:"id"` + Name string `json:"name"` + ContextWindow int `json:"contextWindow,omitempty"` + SupportsVision *bool `json:"supportsVision,omitempty"` + Efforts []grokAppEffort `json:"efforts,omitempty"` +} + +// grokAppWant is magpie's models as the App is told them, was the +// app_models the channel has now. Grok Build has no effort "none" of a +// channel's: the levels are the model's others, and the one the composer +// starts on is the default the user marked in the App's Providers page +// while the model has it, else medium (the middle one without it). +func grokAppWant(was string) []grokAppModel { + var before []grokAppModel + _ = json.Unmarshal([]byte(was), &before) // a list not there or not the App's: no defaults kept + kept := map[string]string{} + for _, m := range before { + for _, e := range m.Efforts { + if e.IsDefault { + kept[m.ID] = e.ID + } + } + } + var out []grokAppModel + for _, m := range magpieModels("grok-app") { + e := grokAppModel{ID: m.ID, Name: m.Name, ContextWindow: m.Context} + if e.Name == "" { + e.Name = m.ID + } + if m.Images { + yes := true + e.SupportsVision = &yes + } + var levels []string + for _, l := range m.Efforts { + if l != "none" { + levels = append(levels, l) + } + } + if len(levels) > 0 { + def := keptEffort(kept[m.ID], levels, zcodeDefaultLevel(levels)) + for _, l := range levels { + e.Efforts = append(e.Efforts, grokAppEffort{ID: l, Name: l, IsDefault: l == def}) + } + } + out = append(out, e) + } + return out +} + +// grokAppRead is the App's config.toml's [models] default and magpie's +// channel's keys, nil when there is none. A file that doesn't parse is an +// error, never taken as empty. +func grokAppRead(path string) (def string, ch map[string]string, err error) { + models, err := edit.GetTOMLTable(path, "models") + if err != nil { + return "", nil, err + } + ch, err = edit.GetTOMLTable(path, grokAppChannel) + return models["default"], ch, err +} + +func grokApp(home string) *Agent { + dir := grokAppDir(home, grokAppOS) + path := filepath.Join(dir, "agent-home", "config.toml") + keyDefault := "grok-app:" + path + ":default" + at := here(home) + key := func() string { return agentKeyAt("grok-app", at.gw()) } + get := func() string { + def, ch, _ := grokAppRead(path) + if def == magpieID && ch != nil && ch["model"] != "" { + return magpieID + "/" + ch["model"] + } + return def + } + // wire writes magpie's channel, model, if given, its model, and + // nothing when the file has it all already. The channel's own extras + // (context window, images, efforts) are the model's, as the App copies + // them onto the channel when a model is picked in its composer. + wire := func(model string) error { + _, ch, err := grokAppRead(path) + if err != nil { + return err + } + want := grokAppWant(ch["app_models"]) + if len(want) == 0 { + return nil + } + if model == "" { + model = ch["model"] + } + i := slices.IndexFunc(want, func(m grokAppModel) bool { return m.ID == model }) + if i < 0 { + // a model magpie no longer has: the channel moves to its first + i = 0 + } + picked := want[i] + list, _ := json.Marshal(want) + efforts := "[]" + if len(picked.Efforts) > 0 { + b, _ := json.Marshal(picked.Efforts) + efforts = string(b) + } + // key, value, and whether it is written bare (a TOML bool or + // integer, as the App and Grok Build read it) rather than a string + type kv struct { + k, v string + bare bool + } + kvs := []kv{ + {"model", picked.ID, false}, + {"base_url", at.v1(), false}, + {"name", "magpie", false}, + {"api_key", key(), false}, + {"api_backend", "chat_completions", false}, + {"app_provider_mode", "generic", false}, + {"app_models", string(list), false}, + {"app_efforts", efforts, false}, + {"supports_reasoning_effort", strconv.FormatBool(len(picked.Efforts) > 0), true}, + } + var gone []string + if picked.SupportsVision != nil && *picked.SupportsVision { + kvs = append(kvs, kv{"app_supports_vision", "true", false}) + } else { + gone = append(gone, "app_supports_vision") + } + if picked.ContextWindow > 0 { + kvs = append(kvs, kv{"context_window", strconv.Itoa(picked.ContextWindow), true}) + } else { + gone = append(gone, "context_window") + } + same := ch != nil + for _, x := range kvs { + if v, ok := ch[x.k]; !ok || v != x.v { + same = false + } + } + for _, k := range gone { + if _, ok := ch[k]; ok { + same = false + } + } + if same { + return nil + } + for _, x := range kvs { + var v any = x.v + if x.bare { + v = edit.Raw(x.v) + } + if err := edit.SetTOMLKey(path, grokAppChannel, x.k, v); err != nil { + return err + } + } + for _, k := range gone { + if err := edit.DelTOMLKey(path, grokAppChannel, k); err != nil { + return err + } + } + return nil + } + // setDefault names the route the App starts on, the key taken out for "" + setDefault := func(v string) error { + if v == "" { + return edit.DelTOMLKey(path, "models", "default") + } + return edit.SetTOMLKey(path, "models", "default", v) + } + // unwire takes magpie's channel out, and the App back to the route it + // was on before — when it is still on magpie: a route picked in the App + // since is the user's and stands + unwire := func(own string) error { + def, _, err := grokAppRead(path) + if err != nil { + return err + } + if def == magpieID { + was := unstash(keyDefault) + if own != "" { + was = own + } + if err := setDefault(was); err != nil { + return err + } + } else { + forget(keyDefault) + if own != "" { + if err := setDefault(own); err != nil { + return err + } + } + } + return edit.SetTOMLTablesMatching(path, []string{grokAppChannel}, []string{grokAppChannel + "."}, nil) + } + return atomic(&Agent{ + ID: "grok-app", Name: "Grok App", Icon: "grok", Aliases: []string{"grokapp"}, Spelled: prefixed, + Dir: dir, Path: path, + Notice: func() string { + if Running(`(^|/)grok-app( |$)`) { + return noticeGrokApp.String() + } + return "" + }, + Sync: func() error { + _, ch, err := grokAppRead(path) + if err != nil || ch == nil { + return err + } + return wire("") + }, + Check: func() string { + def, ch, err := grokAppRead(path) + if err != nil { + return err.Error() + } + if def != magpieID { + return "" + } + if ch == nil { + return "Grok App's [" + grokAppChannel + "] (config.toml) is gone, so it no longer reaches magpie" + } + return wiringOff("Grok App", path, func(k string) (string, bool) { v, ok := ch[k]; return v, ok }, + "base_url", at.v1(), "api_key", key()) + }, + Fields: []Field{{ + // the route the App starts on: one of magpie's models is + // magpie//, magpie's channel with the model in + // it; anything else is the App's own route ("grok", or a + // channel of the user's) + Key: "model", Label: "model", + Get: get, + Set: func(v string) error { + def, ch, err := grokAppRead(path) + if err != nil { + return err + } + if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) { + if def != magpieID { + stash(map[string]string{keyDefault: def}) + } + if err := wire(ref); err != nil { + return err + } + return setDefault(magpieID) + } + if ch != nil || def == magpieID { + return unwire(v) + } + return setDefault(v) + }, + Options: func(cur map[string]string) []Option { + return append(grokAppOwn(path, keyDefault, cur["model"]), viaMagpie("grok-app", magpieID+"/")...) + }, + }}, + }, path) +} + +// grokAppOwn is the App's own routes for the picker: its official one +// ("grok", Grok Build's sign-in), the channels the user added, and the one +// it was on before magpie. +func grokAppOwn(path, keyDefault, cur string) []Option { + var out []Option + add := func(v, label, direct string) { + if v == "" || v == magpieID || prefixed(v) || slices.ContainsFunc(out, func(o Option) bool { return o.Value == v }) { + return + } + o := Option{Value: v, Icon: "xai", Direct: direct} + if label != "" && label != v { + o.Label = label + } + out = append(out, o) + } + add("grok", "Grok (official)", "xAI") + if tables, err := edit.TOMLTables(path); err == nil { + for _, t := range tables { + id, ok := strings.CutPrefix(t, "model.") + if !ok { + continue + } + if u, err := unquoteTOML(id); err == nil { + id = u + } + kv, _ := edit.GetTOMLTable(path, t) + if kv["base_url"] == "" { + continue + } + direct := hostOf(kv["base_url"]) + add(id, kv["name"], direct) + } + } + add(stashLoad()[keyDefault], "", "") + add(cur, "", "") + return group("Grok App", out) +} + +// unquoteTOML is a table name's quoted part without its quotes. +func unquoteTOML(s string) (string, error) { + if len(s) >= 2 && (s[0] == '"' || s[0] == '\'') && s[len(s)-1] == s[0] { + return s[1 : len(s)-1], nil + } + return s, os.ErrInvalid +} diff --git a/internal/agent/grokapp_test.go b/internal/agent/grokapp_test.go new file mode 100644 index 000000000..c92a9ad2e --- /dev/null +++ b/internal/agent/grokapp_test.go @@ -0,0 +1,361 @@ +package agent + +import ( + "encoding/json" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + toml "github.com/pelletier/go-toml/v2" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// grokAppConfig is agent-home/config.toml as Grok App 0.2.39 writes it +// after a DeepSeek channel is added on its Settings › Providers page and +// made the route (upsert_custom_provider, set_default_model_id), with the +// [models] max_retries it pins itself and a comment the user added by hand. +const grokAppConfig = `[models] +default = "deepseek" +max_retries = 3 + +# my own channel +[model.deepseek] +model = "deepseek-v4-flash" +base_url = "https://api.deepseek.com/v1" +name = "DeepSeek" +api_key = "sk-test" +api_backend = "chat_completions" +app_provider_mode = "generic" +app_models = "[{\"id\":\"deepseek-v4-flash\",\"name\":\"Flash\"}]" +app_efforts = "[]" +supports_reasoning_effort = false +context_window = 1000000 +` + +// grokAppHome is a HOME with Grok App's data folder under GROK_APP_HOME, +// its agent-home/config.toml holding body, and magpie with a provider of +// two models, one of them with effort levels. +func grokAppHome(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("GROK_APP_HOME", filepath.Join(home, "grok-app-data")) + // images only where the model takes them itself, not where magpie's + // vision model describes them + was := provider.Described + provider.Described = func() bool { return false } + t.Cleanup(func() { provider.Described = was }) + 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, Efforts: []string{"none", "low", "medium", "high"}}, + {ID: "k2-vision", Images: true}, + }); err != nil { + t.Fatal(err) + } + path = filepath.Join(home, "grok-app-data", "agent-home", "config.toml") + if body != "" { + writeFile(t, path, body) + } else if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + return home, path +} + +// grokAppSections reads config.toml the way Grok App itself does +// (providers.rs parse_model_sections and unquote): line by line, a +// [model.] header starting a section, each `key = value` taken with a +// quoted value decoded as a JSON string — so what magpie writes has to be +// what that reader takes, not only valid TOML. +func grokAppSections(t *testing.T, path string) map[string]map[string]string { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + unquote := func(v string) string { + v = strings.TrimSpace(v) + if len(v) >= 2 && v[0] == '"' && v[len(v)-1] == '"' { + var s string + if json.Unmarshal([]byte(v), &s) == nil { + return s + } + return v[1 : len(v)-1] + } + return v + } + out := map[string]map[string]string{} + var cur map[string]string + for _, line := range strings.Split(string(b), "\n") { + l := strings.TrimSpace(line) + if rest, ok := strings.CutPrefix(l, "[model."); ok && strings.HasSuffix(rest, "]") { + cur = map[string]string{} + out[unquote(strings.TrimSuffix(rest, "]"))] = cur + continue + } + if strings.HasPrefix(l, "[") { + cur = nil + continue + } + if cur == nil || l == "" || strings.HasPrefix(l, "#") { + continue + } + if k, v, ok := strings.Cut(l, "="); ok { + cur[strings.TrimSpace(k)] = unquote(v) + } + } + return out +} + +// Connecting Grok App adds magpie as one of its provider channels — the +// gateway, with a key naming Grok App, and every one of magpie's models in +// the App's own app_models form — and makes it the route. The App's own +// channel stays in the file, and Disconnect gives the file back byte for +// byte. +func TestGrokApp(t *testing.T) { + home, path := grokAppHome(t, grokAppConfig) + a := grokApp(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" || a.Wired() || a.Check() != "" { + t.Fatalf("before: %q wired %v check %q", got, a.Wired(), a.Check()) + } + opts := map[string]Option{} + for _, o := range f.Options(a.Values()) { + opts[o.Value] = o + } + if opts["deepseek"].Direct != "api.deepseek.com" || opts["deepseek"].Label != "DeepSeek" || + opts["grok"].Value == "" || opts["magpie/kimi/k2"].Value == "" { + t.Fatalf("options: %v", opts) + } + + if err := a.Pick("model", "magpie/kimi/k2"); err != nil { + t.Fatal(err) + } + var m map[string]any + b, _ := os.ReadFile(path) + if err := toml.Unmarshal(b, &m); err != nil { + t.Fatalf("not TOML (Grok Build reads it as TOML): %v\n%s", err, b) + } + if d := m["models"].(map[string]any); d["default"] != "magpie" || d["max_retries"] != int64(3) { + t.Fatalf("[models]: %v", d) + } + ch := m["model"].(map[string]any)["magpie"].(map[string]any) + // Grok Build reads these two bare: a quoted context window is what the + // App heals as broken (#538 of its own), and the effort gate a bool + if ch["context_window"] != int64(262144) || ch["supports_reasoning_effort"] != true { + t.Fatalf("bare keys: %v", ch) + } + 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) + } + + secs := grokAppSections(t, path) + s := secs["magpie"] + if s["model"] != "kimi/k2" || s["base_url"] != here(home).v1() || s["name"] != "magpie" || + s["api_key"] != agentKeyAt("grok-app", here(home).gw()) || s["api_backend"] != "chat_completions" || + s["app_provider_mode"] != "generic" || s["context_window"] != "262144" || s["supports_reasoning_effort"] != "true" { + t.Fatalf("magpie's channel as the App reads it: %v", s) + } + if _, ok := s["app_supports_vision"]; ok { + t.Fatalf("k2 takes no images: %v", s) + } + // app_models decodes as the App's Vec (camelCase) + var models []struct { + ID string `json:"id"` + Name string `json:"name"` + ContextWindow *int `json:"contextWindow"` + SupportsVision *bool `json:"supportsVision"` + Efforts []struct { + ID string `json:"id"` + Name string `json:"name"` + IsDefault bool `json:"isDefault"` + } `json:"efforts"` + } + if err := json.Unmarshal([]byte(s["app_models"]), &models); err != nil || len(models) != 2 { + t.Fatalf("app_models %q: %v", s["app_models"], err) + } + k2, vision := models[0], models[1] + if k2.ID != "kimi/k2" || k2.ContextWindow == nil || *k2.ContextWindow != 262144 || k2.SupportsVision != nil { + t.Fatalf("k2: %+v", k2) + } + var levels, defs []string + for _, e := range k2.Efforts { + levels = append(levels, e.ID) + if e.IsDefault { + defs = append(defs, e.ID) + } + } + // no "none" (Grok Build's channel effort is a level), one default + if !reflect.DeepEqual(levels, []string{"low", "medium", "high"}) || !reflect.DeepEqual(defs, []string{"medium"}) { + t.Fatalf("k2's efforts %v, default %v", levels, defs) + } + if vision.ID != "kimi/k2-vision" || vision.SupportsVision == nil || !*vision.SupportsVision || len(vision.Efforts) != 0 { + t.Fatalf("k2-vision: %+v", vision) + } + if !strings.Contains(s["app_efforts"], `"id":"medium","name":"medium","isDefault":true`) { + t.Fatalf("app_efforts: %s", s["app_efforts"]) + } + if !reflect.DeepEqual(secs["deepseek"], grokAppSectionsOf(t, grokAppConfig)["deepseek"]) { + t.Fatalf("the user's own channel changed: %v", secs["deepseek"]) + } + if !strings.Contains(string(b), "# my own channel\n[model.deepseek]") { + t.Fatalf("the user's comment went:\n%s", b) + } + + // another of magpie's models: the channel's extras are that one's + if err := a.Pick("model", "magpie/kimi/k2-vision"); err != nil { + t.Fatal(err) + } + s = grokAppSections(t, path)["magpie"] + if s["model"] != "kimi/k2-vision" || s["app_supports_vision"] != "true" || s["supports_reasoning_effort"] != "false" || + s["app_efforts"] != "[]" { + t.Fatalf("k2-vision's channel: %v", s) + } + if _, ok := s["context_window"]; ok { + t.Fatalf("k2-vision has no context window of its own: %v", s) + } + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(path); string(got) != grokAppConfig { + t.Fatalf("Disconnect left:\n%s", got) + } + if a.Wired() { + t.Fatal("still wired") + } +} + +func grokAppSectionsOf(t *testing.T, body string) map[string]map[string]string { + t.Helper() + p := filepath.Join(t.TempDir(), "config.toml") + writeFile(t, p, body) + return grokAppSections(t, p) +} + +// A model picked in the App's own composer since, and an effort the user +// made the default on its Providers page, are theirs: a sync keeps both, +// and a sync with nothing changed writes nothing. +func TestGrokAppSyncKeepsTheirs(t *testing.T) { + home, path := grokAppHome(t, grokAppConfig) + a := grokApp(home) + if err := a.Pick("model", "magpie/kimi/k2"); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(path) + // the App's composer switching to k2-vision rewrites model =, and the + // user marked high k2's default + edited := strings.Replace(string(b), `model = "kimi/k2"`, `model = "kimi/k2-vision"`, 1) + edited = strings.Replace(edited, `{\"id\":\"medium\",\"name\":\"medium\",\"isDefault\":true},{\"id\":\"high\",\"name\":\"high\",\"isDefault\":false}`, + `{\"id\":\"medium\",\"name\":\"medium\",\"isDefault\":false},{\"id\":\"high\",\"name\":\"high\",\"isDefault\":true}`, 1) + if edited == string(b) || !strings.Contains(edited, `{\"id\":\"high\",\"name\":\"high\",\"isDefault\":true}]}`) { + t.Fatalf("fixture edit didn't take:\n%s", edited) + } + writeFile(t, path, edited) + if err := a.Sync(); err != nil { + t.Fatal(err) + } + s := grokAppSections(t, path)["magpie"] + if s["model"] != "kimi/k2-vision" || s["app_supports_vision"] != "true" { + t.Fatalf("the App's pick went: %v", s) + } + if !strings.Contains(s["app_models"], `{"id":"high","name":"high","isDefault":true}`) { + t.Fatalf("the user's default effort went: %s", s["app_models"]) + } + before, _ := os.ReadFile(path) + st, _ := os.Stat(path) + if err := a.Sync(); err != nil { + t.Fatal(err) + } + after, _ := os.ReadFile(path) + st2, _ := os.Stat(path) + if string(after) != string(before) || !st2.ModTime().Equal(st.ModTime()) { + t.Fatalf("a sync with nothing changed wrote:\n%s", after) + } +} + +// A route of the App's own picked while it is on magpie takes magpie out: +// the channel goes, and the App is on the route picked. +func TestGrokAppOwnRouteTakesMagpieOut(t *testing.T) { + home, path := grokAppHome(t, grokAppConfig) + a := grokApp(home) + if err := a.Pick("model", "magpie/kimi/k2"); err != nil { + t.Fatal(err) + } + if err := a.Pick("model", "grok"); err != nil { + t.Fatal(err) + } + secs := grokAppSections(t, path) + if _, on := secs["magpie"]; on || a.Field("model").Get() != "grok" || a.Wired() { + t.Fatalf("magpie still in:\n%v", secs) + } + if secs["deepseek"]["api_key"] != "sk-test" { + t.Fatalf("the user's channel went: %v", secs) + } +} + +// With no channel of the user's and no route set (a fresh install, Grok's +// own sign-in), Disconnect leaves no route either: the App is back on +// Grok's official one. +func TestGrokAppFresh(t *testing.T) { + home, path := grokAppHome(t, "") + a := grokApp(home) + if !a.Detected() { + t.Fatal("not detected") + } + if err := a.Pick("model", "magpie/kimi/k2-vision"); err != nil { + t.Fatal(err) + } + if s := grokAppSections(t, path)["magpie"]; s["model"] != "kimi/k2-vision" { + t.Fatalf("channel: %v", s) + } + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + def, ch, err := grokAppRead(path) + if err != nil || def != "" || ch != nil { + t.Fatalf("after Disconnect: default %q channel %v err %v", def, ch, err) + } +} + +// The data folder is where the App's directories crate puts it on each +// system, else one of its fallbacks when that is the one there. +func TestGrokAppDir(t *testing.T) { + home := t.TempDir() + t.Setenv("GROK_APP_HOME", "") + t.Setenv("XDG_DATA_HOME", "") + t.Setenv("APPDATA", filepath.Join(home, "Roaming")) + for goos, want := range map[string]string{ + "darwin": filepath.Join(home, "Library", "Application Support", "com.grokapp.grok-app"), + "linux": filepath.Join(home, ".local", "share", "grok-app"), + "windows": filepath.Join(home, "Roaming", "grokapp", "grok-app", "data"), + } { + if got := grokAppDir(home, goos); got != want { + t.Errorf("%s: %s, want %s", goos, got, want) + } + } + if err := os.MkdirAll(filepath.Join(home, ".grok-app"), 0o755); err != nil { + t.Fatal(err) + } + if got := grokAppDir(home, "linux"); got != filepath.Join(home, ".grok-app") { + t.Errorf("linux fallback: %s", got) + } + t.Setenv("GROK_APP_HOME", filepath.Join(home, "x")) + if got := grokAppDir(home, "darwin"); got != filepath.Join(home, "x") { + t.Errorf("GROK_APP_HOME: %s", got) + } +} diff --git a/internal/agentenv/agentenv.go b/internal/agentenv/agentenv.go index eff28341d..6f3ae5413 100644 --- a/internal/agentenv/agentenv.go +++ b/internal/agentenv/agentenv.go @@ -52,6 +52,8 @@ var Vars = []string{ "QODER_CONFIG_DIR", "QODERCN_CONFIG_DIR", // Grok: its home, and where its CLI is installed "GROK_HOME", "GROK_BIN_DIR", + // Grok App's data folder (its agent-home/config.toml), else the OS's app-data one + "GROK_APP_HOME", // Kimi Code and its shared folder "KIMI_CODE_HOME", "KIMI_SHARE_DIR", // Qwen Code's home, ~/.qwen without it diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 280af4c2e..58fc57c04 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4285,6 +4285,7 @@ const I18N = { "It reads its settings at start-up — restart open Command Code sessions to use this.": "它启动时读取设置,需重启已打开的 Command Code 会话才会生效。", "Kimi Code reads its settings at start-up — restart open kimi sessions to use this.": "Kimi Code 启动时读取设置,需重启已打开的 kimi 会话才会生效。", "jcode reads its settings at start-up — restart open jcode sessions to use this.": "jcode 启动时读取设置,需重启已打开的 jcode 会话才会生效。", + "Grok App reads its providers when it starts an agent — start a new chat in Grok App, or restart it, to use this.": "Grok App 在启动 agent 时读取供应商设置,需在 Grok App 中新建对话或重启它才会生效。", "MiniMax Code reads its settings at start-up — restart open mcode sessions to use this.": "MiniMax Code 启动时读取设置,需重启已打开的 mcode 会话才会生效。", "Mister Morph's Console uses this for new tasks; restart open morph chats to use it there.": "Mister Morph 的 Console 会在新任务中使用这项设置;已打开的 morph 对话需重启才会生效。", "Muse Code reads its settings at start-up — restart open muse sessions to use this.": "Muse Code 启动时读取设置,需重启已打开的 muse 会话才会生效。", @@ -8607,6 +8608,7 @@ const I18N = { "It reads its settings at start-up — restart open Command Code sessions to use this.": "它啟動時讀取設定,需重啟已打開的 Command Code 會話才會生效。", "Kimi Code reads its settings at start-up — restart open kimi sessions to use this.": "Kimi Code 啟動時讀取設定,需重啟已打開的 kimi 會話才會生效。", "jcode reads its settings at start-up — restart open jcode sessions to use this.": "jcode 啟動時讀取設定,需重啟已打開的 jcode 會話才會生效。", + "Grok App reads its providers when it starts an agent — start a new chat in Grok App, or restart it, to use this.": "Grok App 在啟動 agent 時讀取供應商設定,需在 Grok App 中新建對話或重啟它才會生效。", "MiniMax Code reads its settings at start-up — restart open mcode sessions to use this.": "MiniMax Code 啟動時讀取設定,需重啟已打開的 mcode 會話才會生效。", "Mister Morph's Console uses this for new tasks; restart open morph chats to use it there.": "Mister Morph 的 Console 會在新任務中使用這項設定;已打開的 morph 對話需重啟才會生效。", "Muse Code reads its settings at start-up — restart open muse sessions to use this.": "Muse Code 啟動時讀取設定,需重啟已打開的 muse 會話才會生效。", @@ -12931,6 +12933,7 @@ const I18N = { "It reads its settings at start-up — restart open Command Code sessions to use this.": "起動時に設定を読み込むため、反映するには開いている Command Code セッションを再起動してください。", "Kimi Code reads its settings at start-up — restart open kimi sessions to use this.": "Kimi Code は起動時に設定を読み込みます。反映するには開いている kimi セッションを再起動してください。", "jcode reads its settings at start-up — restart open jcode sessions to use this.": "jcode は起動時に設定を読み込みます。反映するには開いている jcode セッションを再起動してください。", + "Grok App reads its providers when it starts an agent — start a new chat in Grok App, or restart it, to use this.": "Grok App は agent の起動時にプロバイダーを読み込みます。反映するには Grok App で新しいチャットを開始するか、再起動してください。", "MiniMax Code reads its settings at start-up — restart open mcode sessions to use this.": "MiniMax Code は起動時に設定を読み込みます。反映するには開いている mcode セッションを再起動してください。", "Mister Morph's Console uses this for new tasks; restart open morph chats to use it there.": "Mister Morph の Console は新しいタスクでこれを使います。開いている morph チャットに反映するには再起動してください。", "Muse Code reads its settings at start-up — restart open muse sessions to use this.": "Muse Code は起動時に設定を読み込みます。反映するには開いている muse セッションを再起動してください。", @@ -17255,6 +17258,7 @@ const I18N = { "It reads its settings at start-up — restart open Command Code sessions to use this.": "Es liest seine Einstellungen beim Start – offene Command-Code-Sitzungen neu starten, damit es gilt.", "Kimi Code reads its settings at start-up — restart open kimi sessions to use this.": "Kimi Code liest seine Einstellungen beim Start – offene kimi-Sitzungen neu starten, damit es gilt.", "jcode reads its settings at start-up — restart open jcode sessions to use this.": "jcode liest seine Einstellungen beim Start – offene jcode-Sitzungen neu starten, damit es gilt.", + "Grok App reads its providers when it starts an agent — start a new chat in Grok App, or restart it, to use this.": "Grok App liest seine Anbieter beim Start eines Agenten – in Grok App einen neuen Chat beginnen oder es neu starten, damit es gilt.", "MiniMax Code reads its settings at start-up — restart open mcode sessions to use this.": "MiniMax Code liest seine Einstellungen beim Start – offene mcode-Sitzungen neu starten, damit es gilt.", "Mister Morph's Console uses this for new tasks; restart open morph chats to use it there.": "Die Console von Mister Morph nutzt dies für neue Aufgaben; offene morph-Chats neu starten, damit es dort gilt.", "Muse Code reads its settings at start-up — restart open muse sessions to use this.": "Muse Code liest seine Einstellungen beim Start – offene muse-Sitzungen neu starten, damit es gilt.", @@ -17343,6 +17347,7 @@ const NOTICES = [ "It reads its settings at start-up — restart open Command Code sessions to use this.", "Kimi Code reads its settings at start-up — restart open kimi sessions to use this.", "jcode reads its settings at start-up — restart open jcode sessions to use this.", + "Grok App reads its providers when it starts an agent — start a new chat in Grok App, or restart it, to use this.", "MiniMax Code reads its settings at start-up — restart open mcode sessions to use this.", "Mister Morph's Console uses this for new tasks; restart open morph chats to use it there.", "Muse Code reads its settings at start-up — restart open muse sessions to use this.",