Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
agent: OpenClaw is wired up like the other agents
yetone3c6b7d585f4b
diff --git a/README.md b/README.mdindex be33a2699..89009f492 100644--- a/README.md+++ b/README.md@@ -79,7 +79,7 @@ magpie finds the subscriptions your agents are signed in to by reading their sig<table><tr><td>-Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · 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 · Pencil · OpenPencil · NewMax · Raycast · Kiro Crew · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy · Lody · AionUi · Ante · AstrBot+Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · 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 · Pencil · OpenPencil · NewMax · Raycast · Kiro Crew · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy · Lody · AionUi · Ante · AstrBot · OpenClaw</td></tr></table>diff --git a/README.zh-CN.md b/README.zh-CN.mdindex ba42c23fd..57e91c878 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -79,7 +79,7 @@ magpie 通过读取智能体的登录信息(Claude Code 和 Codex 的文件、<table><tr><td>-Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · 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 · Pencil · OpenPencil · NewMax · Raycast · Kiro Crew · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy · Lody · AionUi · Ante · AstrBot+Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · 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 · Pencil · OpenPencil · NewMax · Raycast · Kiro Crew · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy · Lody · AionUi · Ante · AstrBot · OpenClaw</td></tr></table>diff --git a/docs/reference.md b/docs/reference.mdindex 0657f7e9c..a737d38ec 100644--- a/docs/reference.md+++ b/docs/reference.md@@ -129,6 +129,7 @@ line; agents connected to magpie lose it when it quits.| 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) |+| OpenClaw | `openclaw.json` in `~/.openclaw` (`$OPENCLAW_CONFIG_PATH`, `$OPENCLAW_STATE_DIR`, `~/.openclaw-<profile>` for `$OPENCLAW_PROFILE`, `~` as `$OPENCLAW_HOME`) | model (a `magpie` provider in `models.providers`, `openai-completions`, with magpie's models in it; `agents.defaults.model`'s primary set to it, what was there put back on Disconnect; `magpie/*` added to a `modelPolicy.allow` that would refuse it; the user's own keys in the provider and its models kept; a chat already on a model keeps it until `/model default`) || jcode | `config.toml` in `$JCODE_HOME`, else `~/.jcode` | model (a `[providers.magpie]` profile, `openai-compatible`, with magpie's models in it; `[provider] default_provider`/`default_model` set to it, what was there put back on Disconnect; the user's own keys in the profile, such as `headers` and a model's `reasoning_effort`, kept; restart open jcode sessions after connecting) || 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) |diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.mdindex ce6da5d31..908bae68a 100644--- a/docs/subsystems/agent-wiring.md+++ b/docs/subsystems/agent-wiring.md@@ -70,6 +70,7 @@ something else shows up as drift.- DeepSeek Harness Desktop (macOS arm64 and Windows x64; no Linux build) reads the same `$DSH_HOME` or `~/.dsh` as the CLI, as its own profile `profiles/desktop` (`resolveDshHome` and `resolveDesktopPaths` in the app's `lib/main.js`; `defaultDshHome` in github.com/deepseek-ai/deepseek-harness's `packages/util/home-paths/src/index.ts` and `apps/desktop/src/paths.ts`), so it takes magpie's routes with no wiring of its own (#2279, liangjinyuan-sihan). Only that app, from deepseek-ai/deepseek-harness (bundle id `com.deepseek.dsh`, productName DeepSeek Harness in `apps/desktop/scripts/electron-builder-config.mjs`), is dsh's: the community "DeepSeek Hermes" (motongv/deepseek-hermes-desktop) v0.1.1337 took for it is not listed or written for (WuSix on Discord, `TestDshOnlyTheOfficialApp`). It is found by `/Applications/DeepSeek Harness.app`, by `%LOCALAPPDATA%\Programs\DeepSeek Harness`, or by the folder its current-user installer records under `HKCU\Software\1bf39983-50d0-5fe0-9ef4-cece76f67c5e` (`InstallLocation`), whose Uninstall key gives the version (`registered` in [`desktopapp.go`](../../internal/agent/desktopapp.go)), so a user who picked another folder is found. With the app installed but never opened there is no `~/.dsh`: the row is still listed, and connecting writes `profiles/desktop/cordis.patch.yml` from dsh's own template (`dshProfileTemplate`) with magpie's routes, which the app keeps on its first start, since it writes only the files that are missing. The notice says the app starts on it the first time it opens (`noticeDsh5`). Disconnect before that first start removes the profile magpie made when nothing else is in it (`dshTidyUnopened`); once the app has opened it, the profile stays and only magpie's entries go (`TestDshDesktopNeverOpened`, `TestDshDesktopRegisteredFolder`; the registry as 0.2.1-rc.2's installer writes it, `TestDshWindowsAsTheInstallerRegistersIt`).- 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/<model>` 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.+- OpenClaw keeps its settings in `openclaw.json` (`openClaw` in [`openclaw.go`](../../internal/agent/openclaw.go)), found as OpenClaw's own `resolveConfigPath` and `resolveStateDir` find it: `$OPENCLAW_CONFIG_PATH`, else in `$OPENCLAW_STATE_DIR`, else in `~/.openclaw-<profile>` for a named `$OPENCLAW_PROFILE`, else in `~/.openclaw`, `~` being `$OPENCLAW_HOME` when set. magpie adds the provider `models.providers.magpie` as OpenClaw's schema has one (`zod-schema.core.ts`, strict, so only keys it knows): `baseUrl` at the gateway's `/v1`, `apiKey` naming OpenClaw, `api: openai-completions`, and one model per catalog model with `id`, `name`, `input` (`image` for a model that takes images), `reasoning` for a model with effort levels, and `contextWindow`. The model OpenClaw runs on is `agents.defaults.model`: a string stays a string, an object gets its `primary` set and keeps its `fallbacks`, and the ref is added to `agents.defaults.models` as `openclaw models set` adds it. A non-empty `agents.defaults.modelPolicy.allow` with nothing of magpie's gets `magpie/*`. What the model was is stashed and put back on Disconnect, while magpie's is still the primary; the `magpie/*` and the `{}` entries magpie added go, and so do objects magpie made and the file if magpie made it. The user's own keys stay, in magpie's provider and in a model entry of the same id too, and a sync with nothing to change doesn't write. The file is read as JSON with comments; a JSON5 file (bare keys), which OpenClaw also reads, is left alone and Check says so. A new file is made 0600 in a 0700 folder, as OpenClaw makes its own. OpenClaw's gateway takes the change without a restart, but a chat already on a model keeps it, so the notice says to send `/model default` there. A per-agent model (`agents.entries.*.model`) and a config split with `$include` are left to the user.- 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.- Raycast AI reads Custom Providers from `~/.config/raycast/ai/providers.yaml` in the user's folder, on Mac and Windows alike (`raycast` in [`raycast.go`](../../internal/agent/raycast.go); manual.raycast.com/ai/custom-providers). magpie adds one entry to its `providers` list, `id: magpie`, at the gateway's `/v1` with an `api_keys` alias holding a key that names Raycast (its User-Agent isn't known), and one model per catalog model with `context` and all five `abilities` said, since Raycast assumes tools and vision off when one isn't. The list is edited as a node (`EditYAMLNode`), so the user's other entries, the `tools` block (anchors too) and comments stay. A key the user adds to magpie's entry or to one of its models (`include_user_email`, a `description`) is kept on a sync (`mergeYAMLKept`), and a sync with nothing to change doesn't write. Disconnect takes the entry out, the list when it was the only one, and a file left with nothing in it. Raycast watches the file, so there is no restart notice. The model is picked in Raycast, so the field is whether magpie is in its picker (`ListsModels`). Detected by `Raycast.app` on a Mac or the `~/.config/raycast` folder.- Kiro Crew (AWS's persistent agent: KiroCrew.app, the `kirocrew` CLI, its Gateway on :5476) has no model setting of its own: it runs every session on a harness over ACP, chosen by `agent.acp_backend` in `$KIROCREW_HOME/config.json` (default `~/.kiro/crew`; `""` is kiro-cli), and dispatched members by `agent.member_acp_backend` (`kirocrew` in [`kirocrew.go`](../../internal/agent/kirocrew.go); github.com/kirodotdev/KiroCrew v0.9.0, `src/kiro_crew/` `config/paths.py`, `config/loader.py`, `config/sections.py`, `agent_sdk/backends.py`). Connecting it sets both to an agent already connected to magpie (Codex, Claude Code, OpenCode, Pi or Goose; Pi can't take dispatch, so only the first key for it), preferring the one whose ACP adapter is installed (codex-acp, claude-agent-acp, pi-acp; looked for, never installed, and named in the notice when missing). When `agent.acp_backend` already names one of those five and that agent is installed but not connected, connecting Kiro Crew connects that agent too, in the same action, and runs Crew on it (wuping9525 on Windows: Crew on Claude Code, Claude Code not connected); the stash's `kirocrew.joined` records it, and Kiro Crew's Disconnect disconnects it again, unless the user disconnected it themselves since (`kiroCrewUserLeft` in `Agent.Disconnect`), and a disconnect the user had made before stays theirs. Otherwise, with none connected it refuses and says which to connect. On Windows the app is found by `~\.kirocrew-app\.venv\Scripts\kirocrew.exe` and an adapter also by npm's `.cmd`/`.exe` shim names. `config.local.json` is merged over `config.json` and wins, so a harness set there is the user's: magpie neither writes nor reads past it, and the row says so. The previous values are stashed and put back on Disconnect, only while each key still holds what magpie wrote; a file magpie made is removed when it is left empty. The row reads as connected only while the harness it names is still wired to magpie. Open sessions keep their harness; new ones take it.@@ -153,6 +154,7 @@ go test -tags nogui ./internal/gui -run 'TestAionUiImportRow|TestImportStatusUnrnode --test internal/gui/tests/import-row.test.cjsgo test -tags nogui ./internal/agent -run '^TestAstrBot'go test -tags nogui ./internal/agent -run '^TestJcode'+go test -tags nogui ./internal/agent -run '^TestOpenClaw'go test -tags nogui ./internal/agent -run '^TestRaycast'go test -tags nogui ./internal/agent -run '^TestKiroCrew'go test -tags nogui ./internal/agent -run '^TestOpenPencil'diff --git a/internal/agent/agents.go b/internal/agent/agents.goindex d16716920..7be56d7dc 100644--- a/internal/agent/agents.go+++ b/internal/agent/agents.go@@ -199,6 +199,7 @@ func onMachine(home, cfg string) []*Agent {empryo(home),ante(home),astrbot(home),+ openClaw(home),jcode(home),miniMax(home),droid(home),diff --git a/internal/agent/gatewaykey_test.go b/internal/agent/gatewaykey_test.goindex cd94e3d42..2e2b60ba3 100644--- a/internal/agent/gatewaykey_test.go+++ b/internal/agent/gatewaykey_test.go@@ -226,6 +226,7 @@ func TestPinnedGatewayKeyForEveryWriter(t *testing.T) {"cursor": cursorLocalEnv(gw)[cursorLocalVars[1]],"hanako": hanakoProvider().APIKey,"newmax": newMaxEntryFor(gw).APIKey,+ "openclaw": openClawProviderAt(gw)["apiKey"],"openpencil": openPencilEntry(gw).APIKey,"pencil": pencilProviderJSON(gw)["apiKey"].(string),"vscode": vscodeStable.token(),diff --git a/internal/agent/openclaw.go b/internal/agent/openclaw.gonew file mode 100644index 000000000..8c58fdfd1--- /dev/null+++ b/internal/agent/openclaw.go@@ -0,0 +1,501 @@+package agent++// OpenClaw (openclaw/openclaw, a personal assistant that answers on+// WhatsApp, Telegram, Discord and the rest) keeps its settings in one file,+// openclaw.json. Where it is follows OpenClaw's own resolveConfigPath+// (src/config/paths.ts) and resolveStateDir (src/config/state-dir.ts):+// $OPENCLAW_CONFIG_PATH, else openclaw.json in $OPENCLAW_STATE_DIR, else in+// ~/.openclaw-<profile> for a named $OPENCLAW_PROFILE, else in ~/.openclaw,+// where ~ is $OPENCLAW_HOME when it is set.+//+// A provider of the user's own is an entry of models.providers+// (src/config/zod-schema.core.ts, ModelProviderSchema): a baseUrl, an+// apiKey, an api (openai-completions is OpenAI's chat completions) and its+// models, each an id and a name, with input, reasoning and contextWindow+// (ModelDefinitionSchema). The schema is strict: a key OpenClaw doesn't+// know makes the file invalid, so magpie writes only those. A model is+// named provider/model, split at the first slash+// (src/agents/model-selection-normalize.ts), so magpie's+// magpie/<provider>/<model> is OpenClaw's ref as it is. The model OpenClaw+// runs on is agents.defaults.model, a ref or {primary, fallbacks}+// (docs/concepts/models.md); `openclaw models set` sets primary and keeps+// the fallbacks, and adds the ref to agents.defaults.models+// (src/commands/models/shared.ts), which a config from before 2026.8.1+// still reads as the models allowed. A non-empty+// agents.defaults.modelPolicy.allow is the models allowed: magpie adds+// "magpie/*" to it when nothing of magpie's is in it.+//+// magpie adds itself as the provider "magpie", the gateway's /v1 with a key+// naming OpenClaw and one model entry per catalog model, and makes the model+// picked the primary. What was the primary is stashed and put back on+// Disconnect, while magpie's is still the primary. The user's own keys stay+// as written, in magpie's provider and its model entries too (headers,+// timeoutSeconds, a model's maxTokens). OpenClaw writes the file as JSON+// (src/config/io.write.ts) but reads JSON5; a file that isn't JSON magpie+// can read is left alone. OpenClaw's gateway takes a change to models and+// the default model without a restart (docs/gateway/configuration/+// hot-reload.md), but a chat already pinned to a model keeps it until+// /model default.+//+// Not wired: a per-agent model (agents.entries.*.model) stays the user's,+// and so does a config split with $include.++import (+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "regexp"+ "slices"+ "strings"++ "github.com/tidwall/gjson"+ "github.com/tidwall/jsonc"++ "github.com/yetone/magpie/internal/edit"+)++// what OpenClaw says after a change (notice.go)+var noticeOpenClaw = newNotice("OpenClaw takes this up without a restart. A chat that already has a model keeps it: send /model default in that chat to move it onto this one.")++// openClawContext is what OpenClaw is told of a model whose context magpie+// doesn't know.+const openClawContext = 128000++// the key paths magpie writes in openclaw.json+const (+ openClawProvider = "models.providers." + magpieID+ openClawModel = "agents.defaults.model"+ openClawModels = "agents.defaults.models"+ openClawAllow = "agents.defaults.modelPolicy.allow"+ openClawAll = magpieID + "/*"+)++// openClawProfile is a profile name OpenClaw takes (profile-utils.ts).+var openClawProfile = regexp.MustCompile(`(?i)^[a-z0-9][a-z0-9_-]{0,63}$`)++// openClawHome is OpenClaw's ~: $OPENCLAW_HOME, a leading ~ in it the+// system's home (resolveEffectiveHomeDir).+func openClawHome(at place) string {+ h := strings.TrimSpace(at.getenv("OPENCLAW_HOME"))+ if h == "" || h == "undefined" || h == "null" {+ return at.home+ }+ return openClawTilde(h, at.home)+}++// openClawTilde is p with a leading ~ as home.+func openClawTilde(p, home string) string {+ if p == "~" {+ return home+ }+ if rest, ok := strings.CutPrefix(p, "~/"); ok {+ return filepath.Join(home, rest)+ }+ if rest, ok := strings.CutPrefix(p, `~\`); ok {+ return filepath.Join(home, rest)+ }+ return p+}++// openClawPaths are OpenClaw's state folder and its openclaw.json.+func openClawPaths(at place) (dir, path string) {+ home := openClawHome(at)+ dir = filepath.Join(home, ".openclaw")+ if p := strings.TrimSpace(at.getenv("OPENCLAW_PROFILE")); p != "" && !strings.EqualFold(p, "default") && openClawProfile.MatchString(p) {+ dir = filepath.Join(home, ".openclaw-"+p)+ }+ if d := strings.TrimSpace(at.getenv("OPENCLAW_STATE_DIR")); d != "" {+ dir = openClawTilde(d, home)+ }+ path = filepath.Join(dir, "openclaw.json")+ if p := strings.TrimSpace(at.getenv("OPENCLAW_CONFIG_PATH")); p != "" {+ path = openClawTilde(p, home)+ }+ return dir, path+}++// openClawRead is openclaw.json as JSON with its comments blanked out, nil+// for a missing file; one that isn't JSON (JSON5's bare keys) is an error,+// never taken as empty.+func openClawRead(path string) ([]byte, error) {+ b, err := edit.Read(path)+ if err != nil {+ return nil, err+ }+ if len(strings.TrimSpace(string(b))) == 0 {+ return nil, nil+ }+ s := jsonc.ToJSONInPlace(append([]byte(nil), b...))+ if !json.Valid(s) || !gjson.ParseBytes(s).IsObject() {+ return nil, fmt.Errorf("OpenClaw's %s isn't JSON magpie can read (JSON5?); it was left as it is", path)+ }+ return s, nil+}++// openClawKey is a key as one part of a key path.+func openClawKey(k string) string { return strings.ReplaceAll(k, ".", `\.`) }++// openClawEntry is one of magpie's models as OpenClaw is told it.+type openClawEntry struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Reasoning bool `json:"reasoning"`+ Input []string `json:"input"`+ ContextWindow int `json:"contextWindow"`+}++// openClawWant is magpie's models as OpenClaw is told them, each laid over+// the entry of the same id there was (raw), so the user's own keys in it+// stay.+func openClawWant(raw gjson.Result) []any {+ was := map[string]map[string]any{}+ for _, m := range raw.Array() {+ var e map[string]any+ if json.Unmarshal([]byte(m.Raw), &e) == nil {+ if id, _ := e["id"].(string); id != "" {+ was[id] = e+ }+ }+ }+ out := []any{}+ for _, m := range magpieModels("openclaw") {+ ctx := m.Context+ if ctx <= 0 {+ ctx = openClawContext+ }+ e := openClawEntry{ID: m.ID, Name: m.ID, Input: []string{"text"}, ContextWindow: ctx}+ if m.Images {+ e.Input = append(e.Input, "image")+ }+ e.Reasoning = slices.ContainsFunc(m.Efforts, func(l string) bool { return l != "none" })+ var mine map[string]any+ b, _ := json.Marshal(e)+ json.Unmarshal(b, &mine)+ kept := was[m.ID]+ if kept == nil {+ out = append(out, mine)+ continue+ }+ for k, v := range mine {+ kept[k] = v+ }+ out = append(out, kept)+ }+ return out+}++// openClawPrimary is the model a value of agents.defaults.model names: the+// string, or an object's primary.+func openClawPrimary(r gjson.Result) string {+ if r.IsObject() {+ return r.Get("primary").String()+ }+ if r.Type == gjson.String {+ return r.String()+ }+ return ""+}++// openClawWas is what agents.defaults.model was before magpie, as written,+// and which of the objects holding magpie's keys magpie made.+type openClawWas struct {+ Had bool `json:"had,omitempty"`+ Model json.RawMessage `json:"model,omitempty"`+ // Made are the key paths of objects that weren't there before magpie+ Made []string `json:"made,omitempty"`+ // File: the file wasn't there before magpie+ File bool `json:"file,omitempty"`+}++// openClawProviderAt is magpie's provider entry for a gateway at gw, as+// it is written (models aside).+func openClawProviderAt(gw string) map[string]string {+ return map[string]string{"baseUrl": gw + "/v1", "apiKey": agentKeyAt("openclaw", gw), "api": "openai-completions"}+}++func openClaw(home string) *Agent { return openClawAt(here(home)) }++func openClawAt(at place) *Agent {+ dir, path := openClawPaths(at)+ keyWas := at.key("openclaw:" + path + ":model")+ read := func() gjson.Result {+ s, _ := openClawRead(path)+ return gjson.ParseBytes(s)+ }+ ours := func(c gjson.Result) bool { return prefixed(openClawPrimary(c.Get(openClawModel))) }+ // patch applies sets and deletes to the file as it is, in one write+ patch := func(set []edit.KV, del []string) error {+ raw, err := edit.Read(path)+ if err != nil {+ return err+ }+ out, err := edit.PatchJSON(raw, set, del)+ if err != nil {+ return fmt.Errorf("%s: %w", path, err)+ }+ if raw == nil {+ // OpenClaw keeps its folder to its user (io.write.ts), and the+ // file holds keys+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+ return err+ }+ if err := os.WriteFile(path, nil, 0o600); err != nil {+ return err+ }+ }+ return edit.WriteAtomic(path, out)+ }+ // wire writes magpie's provider and its models, the user's own keys in+ // it left as they are, and with model, if given, makes it the primary;+ // it writes nothing when the file has it all already+ wire := func(c gjson.Result, model string) ([]edit.KV, []string) {+ var set []edit.KV+ var del []string+ p := c.Get(openClawProvider)+ for k, v := range openClawProviderAt(at.gw()) {+ if p.Get(k).String() != v || p.Get(k).Type != gjson.String {+ set = append(set, edit.KV{Path: openClawProvider + "." + k, Value: v})+ }+ }+ want := openClawWant(p.Get("models"))+ if !sameJSON(p.Get("models").Raw, want) {+ set = append(set, edit.KV{Path: openClawProvider + ".models", Value: want})+ }+ if model == "" {+ return set, del+ }+ ref := magpieID + "/" + model+ m := c.Get(openClawModel)+ if m.IsObject() {+ if m.Get("primary").String() != ref {+ set = append(set, edit.KV{Path: openClawModel + ".primary", Value: ref})+ }+ } else if m.String() != ref || m.Type != gjson.String {+ set = append(set, edit.KV{Path: openClawModel, Value: ref})+ }+ // as `openclaw models set` does; the ref of a model magpie put+ // there before goes, as it had nothing of the user's in it+ if ms := c.Get(openClawModels); ms.IsObject() {+ ms.ForEach(func(k, v gjson.Result) bool {+ if prefixed(k.String()) && k.String() != ref && v.IsObject() && len(v.Map()) == 0 {+ del = append(del, openClawModels+"."+openClawKey(k.String()))+ }+ return true+ })+ if !ms.Get(openClawKey(ref)).Exists() {+ set = append(set, edit.KV{Path: openClawModels + "." + openClawKey(ref), Value: map[string]any{}})+ }+ }+ if allow := c.Get(openClawAllow); allow.IsArray() && len(allow.Array()) > 0 && !slices.ContainsFunc(allow.Array(), func(a gjson.Result) bool {+ s := a.String()+ return s == "*" || s == ref || s == openClawAll || s == magpieID+"/"+strings.SplitN(model, "/", 2)[0]+"/*"+ }) {+ var list []any+ json.Unmarshal([]byte(allow.Raw), &list)+ set = append(set, edit.KV{Path: openClawAllow, Value: append(list, openClawAll)})+ }+ return set, del+ }+ // unwire takes magpie's provider out, and OpenClaw back to the model it+ // ran on before — when it still runs on magpie's: a pick the user made+ // since is theirs and stands. own, if given, is the model to run on.+ unwire := func(own string) error {+ s, err := openClawRead(path)+ if err != nil {+ return err+ }+ c := gjson.ParseBytes(s)+ var was openClawWas+ json.Unmarshal([]byte(unstash(keyWas)), &was)+ var set []edit.KV+ del := []string{openClawProvider}+ m := c.Get(openClawModel)+ switch {+ case own != "":+ if m.IsObject() {+ set = append(set, edit.KV{Path: openClawModel + ".primary", Value: own})+ } else {+ set = append(set, edit.KV{Path: openClawModel, Value: own})+ }+ case !ours(c):+ case !was.Had:+ if m.IsObject() && len(m.Map()) > 1 {+ del = append(del, openClawModel+".primary")+ } else {+ del = append(del, openClawModel)+ }+ case m.IsObject():+ if p := openClawPrimary(gjson.ParseBytes(was.Model)); p != "" {+ set = append(set, edit.KV{Path: openClawModel + ".primary", Value: p})+ } else {+ del = append(del, openClawModel+".primary")+ }+ default:+ set = append(set, edit.KV{Path: openClawModel, Value: was.Model})+ }+ if ms := c.Get(openClawModels); ms.IsObject() {+ ms.ForEach(func(k, v gjson.Result) bool {+ if prefixed(k.String()) && v.IsObject() && len(v.Map()) == 0 {+ del = append(del, openClawModels+"."+openClawKey(k.String()))+ }+ return true+ })+ }+ if allow := c.Get(openClawAllow); allow.IsArray() && slices.Contains(was.Made, openClawAllow+"[]") {+ var list []any+ for _, a := range allow.Array() {+ if a.String() != openClawAll {+ list = append(list, a.Value())+ }+ }+ if len(list) < len(allow.Array()) {+ if list == nil {+ list = []any{}+ }+ set = append(set, edit.KV{Path: openClawAllow, Value: list})+ }+ }+ if err := patch(set, del); err != nil {+ return err+ }+ // the objects magpie made, where nothing else is in them now,+ // deepest first; and the file, where magpie made it and it is+ // left empty+ for i := len(was.Made) - 1; i >= 0; i-- {+ k := was.Made[i]+ if strings.HasSuffix(k, "[]") {+ continue+ }+ if r := read().Get(k); r.IsObject() && len(r.Map()) == 0 {+ if err := edit.DelJSON(path, k); err != nil {+ return err+ }+ }+ }+ if was.File {+ if r := read(); r.IsObject() && len(r.Map()) == 0 {+ return os.Remove(path)+ }+ }+ return nil+ }+ // connect makes model, one of magpie's, the primary, stashing what was+ // there first+ connect := func(model string) error {+ s, err := openClawRead(path)+ if err != nil {+ return err+ }+ c := gjson.ParseBytes(s)+ var was openClawWas+ if b := stashLoad()[keyWas]; b != "" {+ json.Unmarshal([]byte(b), &was)+ } else if !ours(c) {+ m := c.Get(openClawModel)+ was = openClawWas{Had: m.Exists(), File: s == nil}+ if m.Exists() {+ was.Model = json.RawMessage(m.Raw)+ }+ }+ for _, k := range []string{"models", "models.providers", "agents", "agents.defaults"} {+ if !c.Get(k).Exists() && !slices.Contains(was.Made, k) {+ was.Made = append(was.Made, k)+ }+ }+ set, del := wire(c, model)+ for _, kv := range set {+ if kv.Path == openClawAllow && !slices.Contains(was.Made, openClawAllow+"[]") {+ was.Made = append(was.Made, openClawAllow+"[]")+ }+ }+ b, _ := json.Marshal(was)+ stash(map[string]string{keyWas: string(b)})+ return patch(set, del)+ }+ return atomic(&Agent{+ ID: "openclaw", Name: "OpenClaw", Icon: "openclaw", Spelled: prefixed, NoNames: true,+ Bin: "openclaw", Dir: dir, Path: path,+ Notice: func() string { return noticeOpenClaw.String() },+ Sync: func() error {+ s, err := openClawRead(path)+ if err != nil {+ return err+ }+ c := gjson.ParseBytes(s)+ if !c.Get(openClawProvider).Exists() {+ return nil+ }+ set, del := wire(c, "")+ if len(set) == 0 && len(del) == 0 {+ return nil+ }+ return patch(set, del)+ },+ Check: func() string {+ s, err := openClawRead(path)+ if err != nil {+ return err.Error()+ }+ c := gjson.ParseBytes(s)+ if !ours(c) {+ return ""+ }+ p := c.Get(openClawProvider)+ if !p.Exists() {+ return "OpenClaw's " + openClawProvider + " (openclaw.json) is gone, so it no longer reaches magpie"+ }+ want := openClawProviderAt(at.gw())+ return wiringOff("OpenClaw", path, func(k string) (string, bool) {+ v := p.Get(k)+ return v.String(), v.Exists()+ }, "baseUrl", want["baseUrl"], "apiKey", want["apiKey"])+ },+ Fields: []Field{{+ // the model OpenClaw runs on: one of magpie's is+ // magpie/<provider>/<model>, OpenClaw's ref for it as it is+ Key: "model", Label: "model",+ Get: func() string { return openClawPrimary(read().Get(openClawModel)) },+ Set: func(v string) error {+ s, err := openClawRead(path)+ if err != nil {+ return err+ }+ c := gjson.ParseBytes(s)+ if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) {+ return connect(ref)+ }+ if c.Get(openClawProvider).Exists() || ours(c) {+ return unwire(v)+ }+ if v == "" {+ return nil+ }+ if m := c.Get(openClawModel); m.IsObject() {+ return patch([]edit.KV{{Path: openClawModel + ".primary", Value: v}}, nil)+ }+ return patch([]edit.KV{{Path: openClawModel, Value: v}}, nil)+ },+ Options: func(cur map[string]string) []Option {+ return append(openClawOwn(keyWas, cur["model"]), viaMagpie("openclaw", magpieID+"/")...)+ },+ }},+ }, path)+}++// openClawOwn is the model OpenClaw ran on before magpie, or runs on now,+// for the picker: OpenClaw's own providers are its sign-ins and plugins,+// which magpie can't list.+func openClawOwn(keyWas, cur string) []Option {+ var was openClawWas+ json.Unmarshal([]byte(stashLoad()[keyWas]), &was)+ var out []Option+ for _, m := range []string{openClawPrimary(gjson.ParseBytes(was.Model)), cur} {+ if m == "" || prefixed(m) || slices.ContainsFunc(out, func(o Option) bool { return o.Value == m }) {+ continue+ }+ p, id, _ := strings.Cut(m, "/")+ out = append(out, Option{Value: m, Icon: modelIcon(p, id), Note: "OpenClaw's own"})+ }+ return group("openclaw", out)+}diff --git a/internal/agent/openclaw_test.go b/internal/agent/openclaw_test.gonew file mode 100644index 000000000..3c72432ad--- /dev/null+++ b/internal/agent/openclaw_test.go@@ -0,0 +1,458 @@+package agent++import (+ "encoding/json"+ "os"+ "path/filepath"+ "reflect"+ "runtime"+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/catalog"+ "github.com/yetone/magpie/internal/provider"+)++// openClawConfig is openclaw.json as OpenClaw 2026.10.8 writes it after+// `openclaw onboard --non-interactive --accept-risk --auth-choice+// deepseek-api-key …` (the folder and the gateway token changed).+const openClawConfig = `{+ "agents": {+ "entries": {+ "main": {+ "name": "main",+ "workspace": "/Users/u/.openclaw/workspace",+ "agentDir": "/Users/u/.openclaw/agents/main/agent",+ "identity": {+ "name": "main"+ }+ }+ },+ "defaults": {+ "workspace": "/Users/u/.openclaw/workspace",+ "models": {+ "deepseek/deepseek-v4-pro": {+ "alias": "DeepSeek"+ }+ },+ "model": {+ "primary": "deepseek/deepseek-v4-pro"+ }+ }+ },+ "plugins": {+ "entries": {+ "anthropic": {+ "config": {+ "sessionCatalog": {+ "enabled": false+ }+ }+ },+ "codex": {+ "config": {+ "sessionCatalog": {+ "enabled": false+ }+ }+ },+ "deepseek": {+ "enabled": true+ }+ }+ },+ "meta": {+ "migrations": {+ "modelPolicyAllowlist": true,+ "utilityModelSeparation": true+ },+ "lastTouchedVersion": "2026.10.8"+ },+ "gateway": {+ "mode": "local",+ "auth": {+ "mode": "token",+ "token": "gateway-token"+ },+ "port": 18799,+ "bind": "loopback",+ "tailscale": {+ "mode": "off"+ }+ },+ "tools": {+ "profile": "full"+ },+ "auth": {+ "profiles": {+ "deepseek:default": {+ "provider": "deepseek",+ "mode": "api_key"+ }+ }+ },+ "models": {+ "mode": "merge",+ "providers": {+ "deepseek": {+ "baseUrl": "https://api.deepseek.com",+ "api": "openai-completions",+ "models": []+ }+ }+ },+ "wizard": {+ "lastRunAt": "2026-10-28T20:43:15.671Z",+ "lastRunVersion": "2026.10.8",+ "lastRunCommand": "onboard",+ "lastRunMode": "local"+ }+}+`++// openClawHomeWith is a HOME with OpenClaw's ~/.openclaw holding body as+// its openclaw.json ("" for none), and magpie with a provider of two+// models, one of them with effort levels.+func openClawHomeWith(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"))+ for _, k := range []string{"OPENCLAW_CONFIG_PATH", "OPENCLAW_STATE_DIR", "OPENCLAW_PROFILE", "OPENCLAW_HOME"} {+ t.Setenv(k, "")+ }+ if err := provider.Save(provider.Provider{ID: "kimi", Name: "Kimi", Key: "k",+ Chat: "https://api.moonshot.cn/v1", Models: []string{"k2", "k2.5-vision"}}); err != nil {+ t.Fatal(err)+ }+ if err := catalog.SaveLive("kimi", "https://api.moonshot.cn/v1", []catalog.Model{+ {ID: "k2", Context: 262144, Efforts: []string{"low", "medium", "high"}},+ {ID: "k2.5-vision", Images: true},+ }); err != nil {+ t.Fatal(err)+ }+ path = filepath.Join(home, ".openclaw", "openclaw.json")+ if body != "" {+ writeFile(t, path, body)+ }+ return home, path+}++func openClawParse(t *testing.T, path string) map[string]any {+ t.Helper()+ b, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ var m map[string]any+ if err := json.Unmarshal(b, &m); err != nil {+ t.Fatalf("%s is not JSON: %v\n%s", path, err, b)+ }+ return m+}++func openClawAt_(m map[string]any, keys ...string) any {+ var v any = m+ for _, k := range keys {+ o, _ := v.(map[string]any)+ v = o[k]+ }+ return v+}++// Connecting OpenClaw adds magpie as a provider of its own — the gateway,+// with a key naming OpenClaw, and every one of magpie's models — and makes+// the model picked the primary. The rest of OpenClaw's file stays, and+// Disconnect gives it back byte for byte.+func TestOpenClaw(t *testing.T) {+ home, path := openClawHomeWith(t, openClawConfig)+ a := openClaw(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-v4-pro" || 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-v4-pro"+ 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 := openClawParse(t, path)+ if p := openClawAt_(m, "agents", "defaults", "model"); !reflect.DeepEqual(p, map[string]any{"primary": "magpie/kimi/k2"}) {+ t.Fatalf("agents.defaults.model: %v", p)+ }+ 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)+ }+ p, _ := openClawAt_(m, "models", "providers", "magpie").(map[string]any)+ if p["baseUrl"] != here(home).v1() || p["api"] != "openai-completions" || p["apiKey"] != agentKeyAt("openclaw", here(home).gw()) {+ t.Fatalf("magpie's provider: %v", p)+ }+ models := map[string]map[string]any{}+ for _, x := range p["models"].([]any) {+ e := x.(map[string]any)+ models[e["id"].(string)] = e+ }+ k2, vision := models["kimi/k2"], models["kimi/k2.5-vision"]+ if len(models) != 2 || k2 == nil || vision == nil {+ t.Fatalf("models: %v", models)+ }+ if k2["name"] != "kimi/k2" || k2["contextWindow"] != float64(262144) || k2["reasoning"] != true {+ t.Fatalf("k2: %v", k2)+ }+ if vision["contextWindow"] != float64(openClawContext) || !reflect.DeepEqual(vision["input"], []any{"text", "image"}) || vision["reasoning"] != false {+ t.Fatalf("k2.5-vision: %v", vision)+ }+ // as `openclaw models set` does, beside the user's own entry+ if ms := openClawAt_(m, "agents", "defaults", "models"); !reflect.DeepEqual(ms, map[string]any{+ "deepseek/deepseek-v4-pro": map[string]any{"alias": "DeepSeek"}, "magpie/kimi/k2": map[string]any{}}) {+ t.Fatalf("agents.defaults.models: %v", ms)+ }+ for _, k := range []string{"plugins", "meta", "gateway", "tools", "auth", "wizard"} {+ var want map[string]any+ json.Unmarshal([]byte(openClawConfig), &want)+ if !reflect.DeepEqual(m[k], want[k]) {+ t.Fatalf("%s changed: %v", k, m[k])+ }+ }+ if d := openClawAt_(m, "models", "providers", "deepseek"); d == nil {+ t.Fatal("the user's own provider is gone")+ }++ // switching between magpie's models keeps what OpenClaw was on before;+ // a model ref with a dot is one key+ if err := a.Pick("model", "magpie/kimi/k2.5-vision"); err != nil {+ t.Fatal(err)+ }+ if got := f.Get(); got != "magpie/kimi/k2.5-vision" {+ t.Fatalf("model %q", got)+ }+ ms, _ := openClawAt_(openClawParse(t, path), "agents", "defaults", "models").(map[string]any)+ if _, on := ms["magpie/kimi/k2.5-vision"]; !on || len(ms) != 2 {+ t.Fatalf("agents.defaults.models after a switch: %v", ms)+ }+ if err := a.Disconnect(); err != nil {+ t.Fatal(err)+ }+ if got, _ := os.ReadFile(path); string(got) != openClawConfig {+ t.Fatalf("Disconnect left:\n%s", got)+ }+ if a.Wired() {+ t.Fatal("still wired")+ }+}++// A model OpenClaw names as a bare string stays a string, and one with no+// model at all, or no file at all, is given back as it was.+func TestOpenClawShapes(t *testing.T) {+ for name, body := range map[string]string{+ "string": "{\n \"agents\": {\n \"defaults\": {\n \"model\": \"anthropic/claude-opus-4-6\"\n }\n }\n}\n",+ "fallback": "{\n \"agents\": {\n \"defaults\": {\n \"model\": {\n \"primary\": \"anthropic/claude-opus-4-6\",\n \"fallbacks\": [\"openai/gpt-5.5\"]\n }\n }\n }\n}\n",+ "no model": "{\n \"gateway\": {\n \"port\": 18789\n }\n}\n",+ "no file": "",+ } {+ t.Run(name, func(t *testing.T) {+ home, path := openClawHomeWith(t, body)+ if body == "" {+ os.MkdirAll(filepath.Dir(path), 0o700) // detected+ }+ a := openClaw(home)+ if err := a.Pick("model", "magpie/kimi/k2"); err != nil {+ t.Fatal(err)+ }+ m := openClawParse(t, path)+ got := openClawAt_(m, "agents", "defaults", "model")+ switch name {+ case "fallback":+ if !reflect.DeepEqual(got, map[string]any{"primary": "magpie/kimi/k2", "fallbacks": []any{"openai/gpt-5.5"}}) {+ t.Fatalf("model: %v", got)+ }+ default:+ if got != "magpie/kimi/k2" {+ t.Fatalf("model: %v", got)+ }+ }+ if body == "" && runtime.GOOS != "windows" {+ if st, err := os.Stat(path); err != nil || st.Mode().Perm() != 0o600 {+ t.Fatalf("a new openclaw.json holding a key: %v %v", st.Mode(), err)+ }+ }+ if err := a.Disconnect(); err != nil {+ t.Fatal(err)+ }+ b, err := os.ReadFile(path)+ if body == "" {+ if !os.IsNotExist(err) {+ t.Fatalf("magpie's own file is left: %v\n%s", err, b)+ }+ return+ }+ if string(b) != body {+ t.Fatalf("Disconnect left:\n%s\nwant:\n%s", b, body)+ }+ })+ }+}++// A model allow-list that has nothing of magpie's gets magpie's models+// in, or OpenClaw refuses them; Disconnect takes them out again.+func TestOpenClawAllowList(t *testing.T) {+ body := "{\n \"agents\": {\n \"defaults\": {\n \"model\": \"deepseek/deepseek-v4-pro\",\n \"modelPolicy\": {\n \"allow\": [\n \"deepseek/*\"\n ]\n }\n }\n }\n}\n"+ home, path := openClawHomeWith(t, body)+ a := openClaw(home)+ if err := a.Pick("model", "magpie/kimi/k2"); err != nil {+ t.Fatal(err)+ }+ allow := openClawAt_(openClawParse(t, path), "agents", "defaults", "modelPolicy", "allow")+ if !reflect.DeepEqual(allow, []any{"deepseek/*", "magpie/*"}) {+ t.Fatalf("allow: %v", allow)+ }+ if err := a.Disconnect(); err != nil {+ t.Fatal(err)+ }+ m := openClawParse(t, path)+ if allow := openClawAt_(m, "agents", "defaults", "modelPolicy", "allow"); !reflect.DeepEqual(allow, []any{"deepseek/*"}) {+ t.Fatalf("allow after Disconnect: %v", allow)+ }+ if got := openClawAt_(m, "agents", "defaults", "model"); got != "deepseek/deepseek-v4-pro" {+ t.Fatalf("model after Disconnect: %v", got)+ }+}++// A model of OpenClaw's own picked while it is on magpie takes magpie+// out, and keeps the fallbacks.+func TestOpenClawOwnModelTakesMagpieOut(t *testing.T) {+ home, path := openClawHomeWith(t, openClawConfig)+ a := openClaw(home)+ if err := a.Pick("model", "magpie/kimi/k2"); err != nil {+ t.Fatal(err)+ }+ if err := a.Pick("model", "deepseek/deepseek-v4-flash"); err != nil {+ t.Fatal(err)+ }+ want := strings.Replace(openClawConfig, `"primary": "deepseek/deepseek-v4-pro"`, `"primary": "deepseek/deepseek-v4-flash"`, 1)+ if got, _ := os.ReadFile(path); string(got) != want {+ t.Fatalf("got:\n%s\nwant:\n%s", got, want)+ }+ if a.Wired() {+ t.Fatal("still wired")+ }+}++// What the user sets in magpie's provider — a header, a timeout, a+// model's maxTokens — is theirs: a catalog sync rewrites the endpoint and+// the models, not those. A sync with nothing to change doesn't write.+func TestOpenClawSyncKeepsTheirs(t *testing.T) {+ home, path := openClawHomeWith(t, openClawConfig)+ a := openClaw(home)+ if err := a.Pick("model", "magpie/kimi/k2"); err != nil {+ t.Fatal(err)+ }+ m := openClawParse(t, path)+ p := openClawAt_(m, "models", "providers", "magpie").(map[string]any)+ p["headers"] = map[string]any{"X-Mine": "1"}+ p["timeoutSeconds"] = 600+ p["baseUrl"] = "http://127.0.0.1:1/v1"+ for _, x := range p["models"].([]any) {+ if e := x.(map[string]any); e["id"] == "kimi/k2" {+ e["maxTokens"] = 32000+ e["reasoning"] = false+ }+ }+ b, _ := json.MarshalIndent(m, "", " ")+ writeFile(t, path, string(b)+"\n")+ if c := a.Check(); !strings.Contains(c, "baseUrl") {+ t.Fatalf("check with the URL changed: %q", c)+ }+ if err := a.Sync(); err != nil {+ t.Fatal(err)+ }+ p = openClawAt_(openClawParse(t, path), "models", "providers", "magpie").(map[string]any)+ if p["baseUrl"] != here(home).v1() || p["timeoutSeconds"] != float64(600) || !reflect.DeepEqual(p["headers"], map[string]any{"X-Mine": "1"}) {+ t.Fatalf("after a sync: %v", p)+ }+ for _, x := range p["models"].([]any) {+ if e := x.(map[string]any); e["id"] == "kimi/k2" && (e["maxTokens"] != float64(32000) || e["reasoning"] != true) {+ t.Fatalf("k2 after a sync: %v", e)+ }+ }+ if a.Check() != "" {+ t.Fatalf("check: %s", a.Check())+ }+ st, _ := os.Stat(path)+ before, _ := os.ReadFile(path)+ if err := a.Sync(); err != nil {+ t.Fatal(err)+ }+ st2, _ := os.Stat(path)+ if after, _ := os.ReadFile(path); string(after) != string(before) || !st2.ModTime().Equal(st.ModTime()) {+ t.Fatal("a sync with nothing to change wrote the file")+ }+}++// openclaw.json in JSON5, which OpenClaw reads and magpie can't, is left+// as it is, and said so.+func TestOpenClawJSON5LeftAlone(t *testing.T) {+ body := "// mine\n{\n agents: { defaults: { model: 'deepseek/deepseek-v4-pro' } },\n}\n"+ home, path := openClawHomeWith(t, body)+ a := openClaw(home)+ if err := a.Pick("model", "magpie/kimi/k2"); err == nil {+ t.Fatal("a JSON5 file was written")+ }+ if got, _ := os.ReadFile(path); string(got) != body {+ t.Fatalf("changed:\n%s", got)+ }+ if c := a.Check(); !strings.Contains(c, "JSON5") {+ t.Fatalf("check: %q", c)+ }+}++// openclaw.json is where OpenClaw itself looks: $OPENCLAW_CONFIG_PATH, its+// state folder, a named profile's folder, ~ as $OPENCLAW_HOME.+func TestOpenClawPaths(t *testing.T) {+ home := t.TempDir()+ at := here(home)+ env := map[string]string{}+ set := func(k, v string) { env[k] = v; t.Setenv(k, v) }+ for _, k := range []string{"OPENCLAW_CONFIG_PATH", "OPENCLAW_STATE_DIR", "OPENCLAW_PROFILE", "OPENCLAW_HOME"} {+ set(k, "")+ }+ check := func(wantDir, wantPath string) {+ t.Helper()+ dir, path := openClawPaths(at)+ if dir != wantDir || path != wantPath {+ t.Fatalf("%v: %s %s, want %s %s", env, dir, path, wantDir, wantPath)+ }+ }+ def := filepath.Join(home, ".openclaw")+ check(def, filepath.Join(def, "openclaw.json"))+ set("OPENCLAW_PROFILE", "default")+ check(def, filepath.Join(def, "openclaw.json"))+ set("OPENCLAW_PROFILE", "../x")+ check(def, filepath.Join(def, "openclaw.json"))+ set("OPENCLAW_PROFILE", "Work")+ w := filepath.Join(home, ".openclaw-Work")+ check(w, filepath.Join(w, "openclaw.json"))+ set("OPENCLAW_HOME", "~/oc")+ w = filepath.Join(home, "oc", ".openclaw-Work")+ check(w, filepath.Join(w, "openclaw.json"))+ set("OPENCLAW_STATE_DIR", "~/state")+ s := filepath.Join(home, "oc", "state")+ check(s, filepath.Join(s, "openclaw.json"))+ set("OPENCLAW_CONFIG_PATH", filepath.Join(home, "cfg", "my.json"))+ check(s, filepath.Join(home, "cfg", "my.json"))+}diff --git a/internal/agentenv/agentenv.go b/internal/agentenv/agentenv.goindex 8d796cd66..05d59da96 100644--- a/internal/agentenv/agentenv.go+++ b/internal/agentenv/agentenv.go@@ -71,6 +71,9 @@ var Vars = []string{"ASTRBOT_ROOT",// jcode's folder, ~/.jcode without it"JCODE_HOME",+ // OpenClaw: its config file, its state folder (openclaw.json in it), a+ // named profile's folder (~/.openclaw-<profile>) and its own ~+ "OPENCLAW_CONFIG_PATH", "OPENCLAW_STATE_DIR", "OPENCLAW_PROFILE", "OPENCLAW_HOME",// 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",@@ -131,6 +134,7 @@ var NotPaths = map[string]bool{"STEPCODE_CONFIG_DIR": true,"MAGPIE_ZED_BIN": true, "MAGPIE_ZED_PROCESS_NAMES": true,"PENGUIN_PROJECT_ID": true,+ "OPENCLAW_PROFILE": true,}// ClaudeProviders are Claude Code's switches that send its requests to adiff --git a/internal/appdir/env.go b/internal/appdir/env.goindex 94438ab85..78e09829c 100644--- a/internal/appdir/env.go+++ b/internal/appdir/env.go@@ -86,7 +86,8 @@ func usable(name, v string) bool {return true}switch name {- case "PI_CODING_AGENT_DIR", "PI_CODING_AGENT_SESSION_DIR", "PRIME_AGENT_CODING_AGENT_DIR", "HANA_HOME", "T3CODE_HOME":+ case "PI_CODING_AGENT_DIR", "PI_CODING_AGENT_SESSION_DIR", "PRIME_AGENT_CODING_AGENT_DIR", "HANA_HOME", "T3CODE_HOME",+ "OPENCLAW_HOME", "OPENCLAW_STATE_DIR", "OPENCLAW_CONFIG_PATH":return v == "~" || strings.HasPrefix(v, "~/") || (runtime.GOOS == "windows" && strings.HasPrefix(v, `~\`))}return falsediff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex bc3c7b620..0309482c7 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -3852,6 +3852,7 @@ const I18N = {"MothX reads its settings at start-up — restart open mothx sessions to use this.": "MothX 启动时读取设置,需重启已打开的 mothx 会话才会生效。","Zoo Code reads magpie's profile when it starts — run Developer: Reload Window in VS Code to use this.": "Zoo Code 启动时读取 magpie 的配置档,需在 VS Code 中运行 Developer: Reload Window 才会生效。","jcode reads its settings at start-up — restart open jcode sessions to use this.": "jcode 启动时读取设置,需重启已打开的 jcode 会话才会生效。",+ "OpenClaw takes this up without a restart. A chat that already has a model keeps it: send /model default in that chat to move it onto this one.": "OpenClaw 无需重启即可生效。已在进行的对话会保留原来的模型:在该对话中发送 /model default 即可换到这个模型。","Magpie is a custom provider in Grok App's Settings › Account. A chat can pick magpie's models in its model picker, and Grok App stays on its current route until you press Use on magpie there.": "Magpie 是 Grok App「设置 › 账户」里的一个自定义供应商。对话可以在模型选择器里选 magpie 的模型;在你于该处对 magpie 点「使用」之前,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 对话需重启才会生效。",@@ -7895,6 +7896,7 @@ const I18N = {"MothX reads its settings at start-up — restart open mothx sessions to use this.": "MothX 啟動時讀取設定,需重啟已打開的 mothx 會話才會生效。","Zoo Code reads magpie's profile when it starts — run Developer: Reload Window in VS Code to use this.": "Zoo Code 啟動時讀取 magpie 的設定檔,需在 VS Code 中執行 Developer: Reload Window 才會生效。","jcode reads its settings at start-up — restart open jcode sessions to use this.": "jcode 啟動時讀取設定,需重啟已打開的 jcode 會話才會生效。",+ "OpenClaw takes this up without a restart. A chat that already has a model keeps it: send /model default in that chat to move it onto this one.": "OpenClaw 無需重啟即可生效。已在進行的對話會保留原來的模型:在該對話中傳送 /model default 即可換到這個模型。","Magpie is a custom provider in Grok App's Settings › Account. A chat can pick magpie's models in its model picker, and Grok App stays on its current route until you press Use on magpie there.": "Magpie 是 Grok App「設定 › 帳戶」裡的一個自訂供應商。對話可以在模型選擇器裡選 magpie 的模型;在你於該處對 magpie 按「使用」之前,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 對話需重啟才會生效。",@@ -11940,6 +11942,7 @@ const I18N = {"MothX reads its settings at start-up — restart open mothx sessions to use this.": "MothX は起動時に設定を読み込みます。反映するには開いている mothx セッションを再起動してください。","Zoo Code reads magpie's profile when it starts — run Developer: Reload Window in VS Code to use this.": "Zoo Code は起動時に magpie のプロファイルを読み込みます。反映するには VS Code で Developer: Reload Window を実行してください。","jcode reads its settings at start-up — restart open jcode sessions to use this.": "jcode は起動時に設定を読み込みます。反映するには開いている jcode セッションを再起動してください。",+ "OpenClaw takes this up without a restart. A chat that already has a model keeps it: send /model default in that chat to move it onto this one.": "OpenClaw は再起動なしで反映します。すでにモデルが決まっている会話はそのままです。その会話で /model default を送るとこのモデルに切り替わります。","Magpie is a custom provider in Grok App's Settings › Account. A chat can pick magpie's models in its model picker, and Grok App stays on its current route until you press Use on magpie there.": "Magpie は Grok App の「設定 › アカウント」にあるカスタムプロバイダーです。チャットはモデル選択から magpie のモデルを選べます。そこで magpie の「使う」を押すまで、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 チャットに反映するには再起動してください。",@@ -15985,6 +15988,7 @@ const I18N = {"MothX reads its settings at start-up — restart open mothx sessions to use this.": "MothX liest seine Einstellungen beim Start – offene mothx-Sitzungen neu starten, damit es gilt.","Zoo Code reads magpie's profile when it starts — run Developer: Reload Window in VS Code to use this.": "Zoo Code liest das Profil von magpie beim Start – in VS Code Developer: Reload Window ausführen, 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.",+ "OpenClaw takes this up without a restart. A chat that already has a model keeps it: send /model default in that chat to move it onto this one.": "OpenClaw übernimmt das ohne Neustart. Ein Chat, der schon ein Modell hat, behält es: Sende in diesem Chat /model default, um ihn auf dieses umzustellen.","Magpie is a custom provider in Grok App's Settings › Account. A chat can pick magpie's models in its model picker, and Grok App stays on its current route until you press Use on magpie there.": "Magpie ist ein eigener Anbieter unter Einstellungen › Konto in Grok App. Ein Chat kann magpies Modelle in seiner Modellauswahl wählen, und Grok App bleibt auf seiner aktuellen Route, bis du dort bei magpie auf Verwenden drückst.","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.",@@ -16229,6 +16233,7 @@ const NOTICES = ["MothX reads its settings at start-up — restart open mothx sessions to use this.","Zoo Code reads magpie's profile when it starts — run Developer: Reload Window in VS Code to use this.","jcode reads its settings at start-up — restart open jcode sessions to use this.",+ "OpenClaw takes this up without a restart. A chat that already has a model keeps it: send /model default in that chat to move it onto this one.","Magpie is a custom provider in Grok App's Settings › Account. A chat can pick magpie's models in its model picker, and Grok App stays on its current route until you press Use on magpie there.","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.",diff --git a/internal/gui/assets/icons/openclaw.svg b/internal/gui/assets/icons/openclaw.svgnew file mode 100644index 000000000..3c1241b55--- /dev/null+++ b/internal/gui/assets/icons/openclaw.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 120"><title>OpenClaw</title><g fill="#000"><path fill-rule="evenodd" d="M60 10C30 10 15 35 15 55C15 75 30 95 45 100L45 110L55 110L55 100C55 100 60 102 65 100L65 110L75 110L75 100C90 95 105 75 105 55C105 35 90 10 60 10ZM39 35a6 6 0 1 0 12 0a6 6 0 1 0-12 0ZM69 35a6 6 0 1 0 12 0a6 6 0 1 0-12 0Z"/><path d="M20 45C5 40 0 50 5 60C10 70 20 65 25 55C28 48 25 45 20 45Z"/><path d="M100 45C115 40 120 50 115 60C110 70 100 65 95 55C92 48 95 45 100 45Z"/></g><g fill="none" stroke="#000" stroke-width="3" stroke-linecap="round"><path d="M45 15Q35 5 30 8"/><path d="M75 15Q85 5 90 8"/></g></svg>