From dd70a4055a2a317a69e444a8bb7df626b9680353 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 2 Oct 2026 14:15:13 +0800 Subject: [PATCH] =?UTF-8?q?wsl:=20OpenCode,=20Kimi=20Code,=20omp=20and=20t?= =?UTF-8?q?he=20other=20CLIs=20magpie=20sets=20up=20through=20a=20file=20i?= =?UTF-8?q?n=20the=20home=20are=20set=20up=20in=20WSL=20distros=20too=20(#?= =?UTF-8?q?515:=20on=20Windows=20only=20Codex,=20Pi,=20OmO=20and=20Claude?= =?UTF-8?q?=20Code=20were=20found=20in=20a=20distro)=20=E2=80=94=20fourtee?= =?UTF-8?q?n=20agents=20join=20wslKinds,=20each=20found=20by=20its=20folde?= =?UTF-8?q?r=20under=20the=20distro's=20$HOME=20or=20its=20command=20on=20?= =?UTF-8?q?the=20distro's=20own=20PATH,=20and=20listed=20as=20=20?= =?UTF-8?q?=C2=B7=20WSL=20=20(opencode@wsl:Ubuntu=E2=80=A6):=20Ope?= =?UTF-8?q?nCode=20(~/.config/opencode,=20opencode),=20MiMo=20Code=20(~/.c?= =?UTF-8?q?onfig/mimocode,=20mimo),=20Kimi=20Code=20(~/.kimi-code,=20kimi;?= =?UTF-8?q?=20the=20old=20kimi-cli's=20~/.kimi=20where=20that=20is=20all?= =?UTF-8?q?=20there=20is,=20found=20by=20the=20command),=20omp=20(~/.omp/a?= =?UTF-8?q?gent,=20omp),=20Crush=20(~/.config/crush/crush.json,=20Linux's?= =?UTF-8?q?=20place,=20not=20Windows'=20LOCALAPPDATA),=20Hermes=20Agent=20?= =?UTF-8?q?(~/.hermes),=20Grok=20Build=20(~/.grok,=20by=20its=20folder=20a?= =?UTF-8?q?lone,=20as=20on=20this=20machine),=20Droid=20(~/.factory),=20fx?= =?UTF-8?q?=20(~/.fx,=20by=20its=20folder=20alone:=20fx=20is=20also=20the?= =?UTF-8?q?=20JSON=20viewer),=20Command=20Code=20(~/.commandcode),=20MiniM?= =?UTF-8?q?ax=20Code's=20mcode=20(~/.minimax),=20Muse=20Code=20(~/.config/?= =?UTF-8?q?muse),=20Qoder=20and=20Qoder=20CN=20(~/.qoder,=20~/.qoder-cn).?= =?UTF-8?q?=20Each=20is=20its=20host=20constructor=20at=20a=20place=20(ope?= =?UTF-8?q?ncodeIn,=20kimiIn,=20ompIn,=20crushIn,=20hermesIn,=20grokIn,=20?= =?UTF-8?q?droidIn,=20fxIn,=20commandCodeIn,=20miniMaxIn,=20museIn,=20qode?= =?UTF-8?q?rIn/qoderCNIn;=20the=20host's=20opencode(home,=20cfg)=20and=20t?= =?UTF-8?q?he=20rest=20wrap=20them),=20so=20it=20writes=20the=20same=20key?= =?UTF-8?q?s=20and=20schema=20as=20on=20this=20machine,=20but=20the=20gate?= =?UTF-8?q?way=20as=20the=20distro=20reaches=20it=20(place.gw/v1:=20127.0.?= =?UTF-8?q?0.1=20when=20mirrored,=20Windows'=20address=20under=20NAT)=20in?= =?UTF-8?q?=20its=20provider,=20its=20Check=20and=20its=20Sync,=20and=20it?= =?UTF-8?q?s=20folder=20at=20the=20default,=20as=20the=20distro's=20variab?= =?UTF-8?q?les=20(OPENCODE=5FCONFIG=5FDIR,=20KIMI=5FCODE=5FHOME,=20HERMES?= =?UTF-8?q?=5FHOME,=20FACTORY=5FHOME=5FOVERRIDE,=20MINIMAX=5FDATA=5FDIR,?= =?UTF-8?q?=20QODER=5FCONFIG=5FDIR=E2=80=A6)=20aren't=20read=20(place.gete?= =?UTF-8?q?nv=20is=20""=20there);=20OpenChamber,=20a=20Windows=20app,=20is?= =?UTF-8?q?n't=20looked=20at=20for=20a=20distro's=20OpenCode,=20and=20omp?= =?UTF-8?q?=20there,=20whose=20version=20isn't=20known,=20gets=20xhigh=20r?= =?UTF-8?q?ather=20than=20a=20max=20an=20older=20omp=20refuses.=20Their=20?= =?UTF-8?q?notices=20are=20the=20restart=20advice=20of=20their=20own,=20as?= =?UTF-8?q?=20for=20Codex.=20A=20stopped=20distro's=20agent=20is=20built?= =?UTF-8?q?=20without=20looking=20at=20its=20files=20(place.cold:=20exists?= =?UTF-8?q?/isDir=20are=20false,=20so=20the=20defaults=20are=20taken),=20i?= =?UTF-8?q?ts=20options=20read=20none=20(wslOwnAsleep,=20kimiOwnOptions/om?= =?UTF-8?q?pOwnOptions/miniMaxOwnOptions=20without=20a=20file),=20and=20a?= =?UTF-8?q?=20pick,=20once=20the=20distro=20is=20started,=20builds=20the?= =?UTF-8?q?=20agent=20again=20warm,=20so=20it=20writes=20the=20file=20the?= =?UTF-8?q?=20agent=20reads=20=E2=80=94=20an=20opencode.jsonc=20already=20?= =?UTF-8?q?there,=20~/.kimi=20for=20kimi-cli=20=E2=80=94=20not=20the=20def?= =?UTF-8?q?ault.=20Left=20out:=20Gemini=20CLI=20and=20Antigravity=20(a=20k?= =?UTF-8?q?ey=20lent=20through=20.env,=20a=20launch=20command),=20dsh=20(p?= =?UTF-8?q?rofiles=20and=20.env),=20Devin=20(no=20gateway;=20its=20model?= =?UTF-8?q?=20list=20from=20the=20devin=20command=20on=20this=20machine),?= =?UTF-8?q?=20Goose=20(no=20magpie=20routing;=20its=20name=20is=20pressly'?= =?UTF-8?q?s=20goose=20too),=20Cursor=20and=20Copilot=20(no=20magpie=20rou?= =?UTF-8?q?ting),=20and=20the=20apps=20(Cline,=20Hanako,=20WorkBuddy,=20ZC?= =?UTF-8?q?ode,=20Claude=20Desktop,=20OpenChamber,=20Alma,=20Cindy);=20and?= =?UTF-8?q?=20the=20library's=20skills,=20MCP=20and=20instructions=20for?= =?UTF-8?q?=20the=20new=20WSL=20agents,=20which=20wslTargetOf=20still=20gi?= =?UTF-8?q?ves=20only=20Claude=20Code,=20Codex,=20Pi=20and=20OmO.=20Nothin?= =?UTF-8?q?g=20ran=20on=20Windows=20or=20in=20a=20real=20WSL.=20wsl=5Fmore?= =?UTF-8?q?=5Ftest.go,=20on=20fake=20distro=20roots=20under=20temp=20dirs?= =?UTF-8?q?=20with=20the=20host's=20variables=20pointed=20elsewhere:=20Tes?= =?UTF-8?q?tWSLProbeFindsMoreAgents=20(each=20folder=20and=20command=20in?= =?UTF-8?q?=20the=20probe,=20none=20for=20grok=20and=20fx,=20kimi-cli=20by?= =?UTF-8?q?=20its=20command),=20TestWSLMoreAgentsDiscovered=20(all=20fourt?= =?UTF-8?q?een=20listed,=20no=20command,=20UA=20or=20aliases),=20TestWSLMo?= =?UTF-8?q?reAgentsPick=20(each=20agent,=20mirrored=20and=20NAT:=20its=20f?= =?UTF-8?q?ile=20in=20the=20distro=20names=20the=20distro's=20gateway,=20n?= =?UTF-8?q?o=20127.0.0.1=20under=20NAT,=20Check=20passes,=20Sync=20keeps?= =?UTF-8?q?=20it,=20the=20notice;=20this=20machine's=20home=20and=20the=20?= =?UTF-8?q?folders=20its=20variables=20name=20untouched),=20TestWSLMoreAge?= =?UTF-8?q?ntsStopped=20(nothing=20asked=20nor=20opened,=20the=20last=20va?= =?UTF-8?q?lue=20shown,=20options,=20a=20pick=20starts=20the=20distro=20an?= =?UTF-8?q?d=20writes=20there)=20fail=20without=20the=20change;=20TestWSLS?= =?UTF-8?q?toppedPickFindsItsFiles=20fails=20without=20the=20warm=20rebuil?= =?UTF-8?q?d=20(the=20pick=20wrote=20a=20second=20opencode.json=20beside?= =?UTF-8?q?=20the=20.jsonc).=20go=20vet=20./internal/...,=20go=20build=20-?= =?UTF-8?q?tags=20nogui=20(darwin,=20GOOS=3Dlinux),=20GOOS=3Dwindows=20go?= =?UTF-8?q?=20build=20and=20vet=20./internal/...,=20GOOS=3Dwindows=20go=20?= =?UTF-8?q?test=20-c=20./internal/agent/=20./internal/library/,=20and=20go?= =?UTF-8?q?=20test=20-tags=20nogui=20-count=3D1=20./...=20under=20a=20temp?= =?UTF-8?q?=20HOME=20pass=20(TestFXInState=20failed=20once=20on=20its=20Te?= =?UTF-8?q?mpDir=20cleanup=20race,=20passes=20on=20the=20rerun;=20untouche?= =?UTF-8?q?d).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/agent/agents.go | 81 +++++++--- internal/agent/commandcode.go | 20 ++- internal/agent/droid.go | 25 ++- internal/agent/fx.go | 18 ++- internal/agent/grok.go | 22 ++- internal/agent/hermes.go | 22 ++- internal/agent/kimi.go | 29 ++-- internal/agent/minimax.go | 22 ++- internal/agent/muse.go | 11 +- internal/agent/omp.go | 36 +++-- internal/agent/qoder.go | 27 +++- internal/agent/wsl.go | 143 ++++++++++++++++- internal/agent/wsl_more_test.go | 273 ++++++++++++++++++++++++++++++++ 13 files changed, 634 insertions(+), 95 deletions(-) create mode 100644 internal/agent/wsl_more_test.go diff --git a/internal/agent/agents.go b/internal/agent/agents.go index c96904fb4..b5b60b9a7 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -370,17 +370,19 @@ func piThinkingLevels(efforts []string, anthropic bool) map[string]any { // openCodeLike is OpenCode and the forks that keep its config shape // (mimocode): a provider block with npm/@ai-sdk/openai-compatible, model and // small_model fields, and its own auth file beside its config. -func openCodeLike(id, name, icon, bin, dir, auth string, ua []string, aliases ...string) *Agent { +// at is where it lives: this machine, or a WSL distro (see wsl.go), whose +// gateway address its provider names. +func openCodeLike(at place, id, name, icon, bin, dir, auth string, ua []string, aliases ...string) *Agent { // the first of its files there is, as the agent looks for them; with // none, a new .json path := filepath.Join(dir, id+".json") for _, name := range []string{id + ".jsonc", id + ".json", "config.json"} { - if _, err := os.Stat(filepath.Join(dir, name)); err == nil { + if at.exists(filepath.Join(dir, name)) { path = filepath.Join(dir, name) break } } - provider := func() any { return magpieProviderJSONFor("opencode", id) } + provider := func() any { return magpieProviderJSONAt("opencode", id, at.gw()) } opts := func(key string) func(map[string]string) []Option { return func(cur map[string]string) []Option { return append(ownOptions(auth, cur[key]), viaMagpie(id, magpieID+"/")...) @@ -391,7 +393,7 @@ func openCodeLike(id, name, icon, bin, dir, auth string, ua []string, aliases .. // OpenCode it runs on this config, is one of magpie's: magpie's // provider has to stay onMagpie := func() bool { - return usesMagpie(get("model"), get("small_model")) || id == "opencode" && openChamberOnMagpie() + return usesMagpie(get("model"), get("small_model")) || id == "opencode" && at.spell == nil && openChamberOnMagpie() } set := func(key string) func(string) error { return func(v string) error { @@ -404,7 +406,7 @@ func openCodeLike(id, name, icon, bin, dir, auth string, ua []string, aliases .. } return edit.DelJSON(path, "provider."+magpieID) } - v, err := openCodeRef(path, id, v) + v, err := openCodeRefAt(at, path, id, v) if err != nil { return err } @@ -420,7 +422,7 @@ func openCodeLike(id, name, icon, bin, dir, auth string, ua []string, aliases .. return "" } return wiringOff(name, path, func(k string) (string, bool) { return edit.GetJSON(path, "provider."+magpieID+".options."+k) }, - "baseURL", gatewayV1(), "apiKey", gateway.Token) + "baseURL", at.v1(), "apiKey", gateway.Token) }, Sync: func() error { // a model of magpie's chosen, but its provider gone from the @@ -443,21 +445,27 @@ func openCodeLike(id, name, icon, bin, dir, auth string, ua []string, aliases .. // magpie, named there rather than in a second list of the same models, else // to magpie's provider, put in the file; any other is v as it is. func openCodeRef(path, id, v string) (string, error) { + return openCodeRefAt(here(""), path, id, v) +} + +// openCodeRefAt is openCodeRef for the agent at a place, which reaches the +// gateway at its own address. +func openCodeRefAt(at place, path, id, v string) (string, error) { ref, ok := strings.CutPrefix(v, magpieID+"/") if !ok || !isMagpie(ref) { return v, nil } - if own := ownGatewayProvider(path, ref); own != "" { + if own := ownGatewayProvider(path, ref, at.v1()); own != "" { return own + "/" + ref, nil } - return v, edit.SetJSON(path, edit.KV{Path: "provider." + magpieID, Value: magpieProviderJSONFor("opencode", id)}) + return v, edit.SetJSON(path, edit.KV{Path: "provider." + magpieID, Value: magpieProviderJSONAt("opencode", id, at.gw())}) } // ownGatewayProvider is the provider in an OpenCode config, other than -// magpie's own, whose baseURL is magpie's gateway and that lists the model -// ref, as a layout of one provider per family of magpie's models has; "" -// when there is none. -func ownGatewayProvider(path, ref string) string { +// magpie's own, whose baseURL is magpie's gateway (v1, as the agent reaches +// it) and that lists the model ref, as a layout of one provider per family +// of magpie's models has; "" when there is none. +func ownGatewayProvider(path, ref, v1 string) string { raw, ok := edit.GetJSON(path, "provider") if !ok { return "" @@ -478,29 +486,46 @@ func ownGatewayProvider(path, ref string) string { sort.Strings(names) for _, name := range names { p := ps[name] - if _, has := p.Models[ref]; name != magpieID && has && sameGateway(p.Options.BaseURL) { + if _, has := p.Models[ref]; name != magpieID && has && sameGateway(p.Options.BaseURL, v1) { return name } } return "" } -// sameGateway reports whether a base URL is magpie's gateway's, its host -// spelled 127.0.0.1 or localhost. -func sameGateway(base string) bool { +// sameGateway reports whether a base URL is magpie's gateway's (v1), its +// host spelled 127.0.0.1 or localhost. +func sameGateway(base, v1 string) bool { norm := func(u string) string { u = strings.TrimRight(strings.TrimSpace(u), "/") return strings.Replace(u, "://localhost:", "://127.0.0.1:", 1) } - return base != "" && norm(base) == norm(gatewayV1()) + return base != "" && norm(base) == norm(v1) } func opencode(home, cfg string) *Agent { - return openCodeLike("opencode", "OpenCode", "opencode", "opencode", + return openCodeLike(here(home), "opencode", "OpenCode", "opencode", "opencode", openCodeDir(cfg), filepath.Join(home, ".local", "share", "opencode", "auth.json"), []string{"opencode"}, "oc") } +// opencodeIn is OpenCode in a WSL distro (see wsl.go): its config in +// ~/.config/opencode, as XDG_CONFIG_HOME and OPENCODE_CONFIG_DIR, the +// distro's variables, aren't read; OpenChamber, a Windows app, isn't there. +func opencodeIn(at place) *Agent { + return openCodeLike(at, "opencode", "OpenCode", "opencode", "opencode", + filepath.Join(at.home, ".config", "opencode"), filepath.Join(at.home, ".local", "share", "opencode", "auth.json"), + []string{"opencode"}, "oc") +} + +// mimocodeIn is MiMo Code in a WSL distro: ~/.config/mimocode, as +// MIMOCODE_HOME isn't read there. +func mimocodeIn(at place) *Agent { + return openCodeLike(at, "mimocode", "MiMo Code", "mimocode", "mimo", + filepath.Join(at.home, ".config", "mimocode"), filepath.Join(at.home, ".local", "share", "mimocode", "auth.json"), + []string{"mimocode"}, "mimo") +} + // openCodeDir is the folder OpenCode reads its user config from: // $OPENCODE_CONFIG_DIR when set, else $XDG_CONFIG_HOME/opencode (cfg). // OpenCode 2, the one OpenChamber bundles (#321), reads that folder in place @@ -523,7 +548,7 @@ func mimocode(home, cfg string) *Agent { if h := os.Getenv("MIMOCODE_HOME"); filepath.IsAbs(h) { dir = filepath.Join(h, "config") } - return openCodeLike("mimocode", "MiMo Code", "mimocode", "mimo", + return openCodeLike(here(home), "mimocode", "MiMo Code", "mimocode", "mimo", dir, filepath.Join(home, ".local", "share", "mimocode", "auth.json"), []string{"mimocode"}, "mimo") } @@ -772,6 +797,18 @@ func crush(home, cfg string) *Agent { path = filepath.Join(app, "crush", "crush.json") } } + return crushAt(here(home), path) +} + +// crushIn is Crush in a WSL distro: ~/.config/crush/crush.json, Linux's +// place for it. +func crushIn(at place) *Agent { + return crushAt(at, filepath.Join(at.home, ".config", "crush", "crush.json")) +} + +// crushAt is Crush with its config at path, reaching the gateway as at does. +func crushAt(at place, path string) *Agent { + provider := func() any { return magpieProviderJSONAt("crush", "crush", at.gw()) } get := func(k string) (string, bool) { return edit.GetJSON(path, k) } set := func(kvs ...edit.KV) error { return edit.SetJSON(path, kvs...) } opts := func(key string) func(map[string]string) []Option { @@ -807,7 +844,7 @@ func crush(home, cfg string) *Agent { return edit.DelJSON(path, "providers."+magpieID) } if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) { - if err := set(edit.KV{Path: "providers." + magpieID, Value: magpieProviderJSON("crush")}); err != nil { + if err := set(edit.KV{Path: "providers." + magpieID, Value: provider()}); err != nil { return err } } @@ -824,10 +861,10 @@ func crush(home, cfg string) *Agent { return "" } return wiringOff("Crush", path, func(k string) (string, bool) { return get("providers." + magpieID + "." + k) }, - "base_url", gatewayV1(), "api_key", gateway.Token) + "base_url", at.v1(), "api_key", gateway.Token) }, Sync: func() error { - return syncJSON(path, "providers."+magpieID, func() any { return magpieProviderJSON("crush") }) + return syncJSON(path, "providers."+magpieID, provider) }, Fields: []Field{ {Key: "model", Label: "large", Get: pairGet(get, "models.large.provider", "models.large.model"), Set: setter("models.large.provider", "models.large.model"), Options: opts("model")}, diff --git a/internal/agent/commandcode.go b/internal/agent/commandcode.go index 75b221c4e..ef27565a3 100644 --- a/internal/agent/commandcode.go +++ b/internal/agent/commandcode.go @@ -21,8 +21,14 @@ import ( // ccEfforts are the reasoning levels Command Code knows. var ccEfforts = []string{"low", "medium", "high", "xhigh", "max"} -func commandCode(home string) *Agent { - dir := filepath.Join(home, ".commandcode") +func commandCode(home string) *Agent { return commandCodeIn(here(home)) } + +// commandCodeIn is Command Code at a place: this machine's home, or a WSL +// distro's (see wsl.go), its provider naming the gateway as the distro +// reaches it. +func commandCodeIn(at place) *Agent { + ccProviderJSON := func() any { return ccProviderJSONAt(at.v1()) } + dir := filepath.Join(at.home, ".commandcode") path := filepath.Join(dir, "settings.json") providers := filepath.Join(dir, "providers.json") get := func(k string) string { v, _ := edit.GetJSON(path, k); return v } @@ -54,7 +60,7 @@ func commandCode(home string) *Agent { return "Command Code's modelProvider (settings.json) is " + orDefault(p) + ", so it no longer asks magpie" } return wiringOff("Command Code", providers, func(k string) (string, bool) { return edit.GetJSON(providers, "provider."+magpieID+"."+k) }, - "baseURL", gatewayV1()) + "baseURL", at.v1()) }, Fields: []Field{{ Key: "model", Label: "model", @@ -140,7 +146,11 @@ func commandCode(home string) *Agent { // ccProviderJSON is magpie's entry in providers.json. The key is false: // the gateway takes any, and Command Code refuses one written out. -func ccProviderJSON() any { +func ccProviderJSON() any { return ccProviderJSONAt(gatewayV1()) } + +// ccProviderJSONAt is ccProviderJSON for a Command Code reaching the +// gateway's /v1 at v1. +func ccProviderJSONAt(v1 string) any { ms := map[string]any{} for _, m := range magpieModels("commandcode") { e := map[string]any{"name": m.Name} @@ -156,7 +166,7 @@ func ccProviderJSON() any { } ms[m.ID] = e } - return map[string]any{"name": "magpie", "api": "openai-completions", "baseURL": gatewayV1(), "apiKey": false, "models": ms} + return map[string]any{"name": "magpie", "api": "openai-completions", "baseURL": v1, "apiKey": false, "models": ms} } // ccEffortMap is settings.json's reasoningEffort, model id to effort. diff --git a/internal/agent/droid.go b/internal/agent/droid.go index 298e4c969..93dd3bf04 100644 --- a/internal/agent/droid.go +++ b/internal/agent/droid.go @@ -22,7 +22,6 @@ package agent import ( "encoding/json" - "os" "path/filepath" "slices" "strconv" @@ -60,17 +59,20 @@ type droidEntry struct { } // droidEntries are magpie's custom models as the catalog is now. -func droidEntries() []droidEntry { +func droidEntries() []droidEntry { return droidEntriesAt(gateway.URL()) } + +// droidEntriesAt are droidEntries for a droid reaching the gateway at gw. +func droidEntriesAt(gw string) []droidEntry { var out []droidEntry for _, m := range magpieModels("droid") { - e := droidEntry{Model: m.ID, ID: droidID + m.ID, BaseURL: gatewayV1(), APIKey: gateway.Token, + e := droidEntry{Model: m.ID, ID: droidID + m.ID, BaseURL: gw + "/v1", APIKey: gateway.Token, Provider: "generic-chat-completion-api", MaxContextLimit: m.Context, MaxOutputTokens: maxTokens(m), NoImageSupport: !m.Images} switch { case slices.Contains(m.APIs, string(provider.Responses)): e.Provider = "openai" case slices.Contains(m.APIs, string(provider.Anthropic)): // Anthropic's SDK adds the /v1 itself - e.Provider, e.BaseURL = "anthropic", gateway.URL() + e.Provider, e.BaseURL = "anthropic", gw } // the catalog's own label ("pro · DeepSeek") is what the picker // shows; droid finds the model by its id, whatever its name @@ -124,10 +126,17 @@ func droidCustoms(path, key string) []droidCustom { return out } -func droid(home string) *Agent { - if h := os.Getenv("FACTORY_HOME_OVERRIDE"); h != "" { +func droid(home string) *Agent { return droidIn(here(home)) } + +// droidIn is Droid at a place: this machine's home, or a WSL distro's (see +// wsl.go), where FACTORY_HOME_OVERRIDE isn't read and its custom models +// name the gateway as the distro reaches it. +func droidIn(at place) *Agent { + home := at.home + if h := at.getenv("FACTORY_HOME_OVERRIDE"); h != "" { home = h } + droidEntries := func() []droidEntry { return droidEntriesAt(at.gw()) } dir := filepath.Join(home, ".factory") path := filepath.Join(dir, "settings.json") legacy := filepath.Join(dir, "config.json") @@ -224,9 +233,9 @@ func droid(home string) *Agent { return "Droid's custom model " + v + " (settings.json) is gone, so it no longer reaches magpie" } r := gjson.ParseBytes(c.raw) - base := gatewayV1() + base := at.v1() if r.Get("provider").String() == "anthropic" { - base = gateway.URL() + base = at.gw() } return wiringOff("Droid", path, func(k string) (string, bool) { g := r.Get(k); return g.String(), g.Exists() }, "baseUrl", base, "apiKey", gateway.Token) diff --git a/internal/agent/fx.go b/internal/agent/fx.go index e3a2bc0f3..48aef621b 100644 --- a/internal/agent/fx.go +++ b/internal/agent/fx.go @@ -25,8 +25,13 @@ import ( // past it fx refuses the whole settings file. const fxMaxModels = 256 -func fx(home string) *Agent { - dir := filepath.Join(home, ".fx") +func fx(home string) *Agent { return fxIn(here(home)) } + +// fxIn is fx at a place: this machine's home, or a WSL distro's (see +// wsl.go), its provider naming the gateway as the distro reaches it. +func fxIn(at place) *Agent { + fxProvider := func(cur string) any { return fxProviderAt(cur, at.v1()) } + dir := filepath.Join(at.home, ".fx") path := filepath.Join(dir, "settings.json") get := func(k string) string { v, _ := edit.GetJSON(path, k); return v } // the provider fx talks to; unset, it is Vercel's AI Gateway @@ -68,7 +73,7 @@ func fx(home string) *Agent { return "" } return wiringOff("fx", path, func(k string) (string, bool) { return edit.GetJSON(path, "providers."+magpieID+"."+k) }, - "base_url", gatewayV1()) + "base_url", at.v1()) }, Fields: []Field{{ Key: "model", Label: "model", @@ -138,7 +143,10 @@ func fxModels(path string) map[string]string { // fxProvider is magpie's entry in settings.json's providers. Its // model_metadata is what fx's model picker lists: the catalog, the model // in use first so it is never the one cut at fx's limit. -func fxProvider(cur string) any { +func fxProvider(cur string) any { return fxProviderAt(cur, gatewayV1()) } + +// fxProviderAt is fxProvider for an fx reaching the gateway's /v1 at v1. +func fxProviderAt(cur, v1 string) any { all := magpieModels("fx") slices.SortStableFunc(all, func(a, b catalog.Model) int { switch { @@ -165,7 +173,7 @@ func fxProvider(cur string) any { ms[m.ID] = e } return map[string]any{ - "protocol": "openai-chat-completions", "base_url": gatewayV1(), "auth": map[string]any{"type": "none"}, + "protocol": "openai-chat-completions", "base_url": v1, "auth": map[string]any{"type": "none"}, "tool_choice_mode": "send", "model_metadata": ms, } } diff --git a/internal/agent/grok.go b/internal/agent/grok.go index 6ae2ff4a5..e3dfa9caa 100644 --- a/internal/agent/grok.go +++ b/internal/agent/grok.go @@ -16,7 +16,6 @@ package agent // gives them back. import ( - "os" "path/filepath" "strconv" "strings" @@ -32,13 +31,15 @@ var grokEfforts = []string{"none", "minimal", "low", "medium", "high", "xhigh", // grokModelTable is the header prefix of every table magpie writes. var grokModelTable = `model."` + magpieID + "/" -func grokModelTables() []edit.Table { +// grokModelTables are magpie's model tables, for a Grok that reaches the +// gateway's /v1 at v1. +func grokModelTables(v1 string) []edit.Table { var out []edit.Table for _, m := range magpieModels("grok") { kvs := []edit.KV{ {Path: "model", Value: m.ID}, {Path: "name", Value: m.Name}, - {Path: "base_url", Value: gatewayV1()}, + {Path: "base_url", Value: v1}, {Path: "api_key", Value: gateway.Token}, {Path: "api_backend", Value: "chat_completions"}, } @@ -59,10 +60,15 @@ func grokModelTables() []edit.Table { return out } -func grok(home string) *Agent { - dir := os.Getenv("GROK_HOME") +func grok(home string) *Agent { return grokIn(here(home)) } + +// grokIn is Grok Build at a place: this machine's home, or a WSL distro's +// (see wsl.go), where GROK_HOME isn't read and its models name the gateway +// as the distro reaches it. +func grokIn(at place) *Agent { + dir := at.getenv("GROK_HOME") if dir == "" { - dir = filepath.Join(home, ".grok") + dir = filepath.Join(at.home, ".grok") } path := filepath.Join(dir, "config.toml") get := func(k string) (string, error) { @@ -81,7 +87,7 @@ func grok(home string) *Agent { } return false, nil } - writeMagpie := func() error { return edit.SetTOMLTables(path, []string{grokModelTable}, grokModelTables()) } + writeMagpie := func() error { return edit.SetTOMLTables(path, []string{grokModelTable}, grokModelTables(at.v1())) } dropMagpie := func() error { return edit.SetTOMLTables(path, []string{grokModelTable}, nil) } // the default model is the user's, not a campaign's ownDefault := func(features map[string]string) error { @@ -144,7 +150,7 @@ func grok(home string) *Agent { return "Grok Build's [model." + strconv.Quote(v) + "] (config.toml) is gone, so it no longer reaches magpie" } return wiringOff("Grok Build", path, func(k string) (string, bool) { v, ok := t[k]; return v, ok }, - "base_url", gatewayV1(), "api_key", gateway.Token) + "base_url", at.v1(), "api_key", gateway.Token) }, Fields: []Field{ { diff --git a/internal/agent/hermes.go b/internal/agent/hermes.go index 2c208f3cf..9852ebd6d 100644 --- a/internal/agent/hermes.go +++ b/internal/agent/hermes.go @@ -10,7 +10,6 @@ package agent // put back when magpie steps out. import ( - "os" "path/filepath" "strings" @@ -18,12 +17,18 @@ import ( "github.com/yetone/magpie/internal/gateway" ) -func hermes(home string) *Agent { - dir := os.Getenv("HERMES_HOME") +func hermes(home string) *Agent { return hermesIn(here(home)) } + +// hermesIn is Hermes at a place: this machine's home, or a WSL distro's +// (see wsl.go), where HERMES_HOME isn't read and its provider names the +// gateway as the distro reaches it. +func hermesIn(at place) *Agent { + dir := at.getenv("HERMES_HOME") if dir == "" { - dir = filepath.Join(home, ".hermes") + dir = filepath.Join(at.home, ".hermes") } path := filepath.Join(dir, "config.yaml") + hermesProvider := func() hermesProviderEntry { return hermesProviderAt(at.gw()) } key := "hermes:" + path + ":" getKey := func(k string) string { v, _ := edit.GetYAML(path, k); return v } onMagpie := func() bool { return getKey("model.provider") == magpieID } @@ -64,7 +69,7 @@ func hermes(home string) *Agent { return "" } return wiringOff("Hermes", path, func(k string) (string, bool) { return edit.GetYAML(path, "providers."+magpieID+"."+k) }, - "base_url", gatewayV1(), "api_key", gateway.Token) + "base_url", at.v1(), "api_key", gateway.Token) }, Fields: []Field{{ Key: "model", Label: "model", @@ -138,13 +143,16 @@ type hermesProviderEntry struct { // hermesProvider is magpie's entry under providers. Hermes sends its own // User-Agent only from a recent release on, so the header names it for the // gateway's usage view. -func hermesProvider() hermesProviderEntry { +func hermesProvider() hermesProviderEntry { return hermesProviderAt(gateway.URL()) } + +// hermesProviderAt is hermesProvider for a Hermes reaching the gateway at gw. +func hermesProviderAt(gw string) hermesProviderEntry { ms := []string{} for _, m := range magpieModels("hermes") { ms = append(ms, m.ID) } return hermesProviderEntry{ - Name: magpieID, BaseURL: gatewayV1(), APIKey: gateway.Token, APIMode: "chat_completions", + Name: magpieID, BaseURL: gw + "/v1", APIKey: gateway.Token, APIMode: "chat_completions", Headers: map[string]string{"User-Agent": "hermes-agent"}, Models: ms, } } diff --git a/internal/agent/kimi.go b/internal/agent/kimi.go index 78436c238..9856f5c19 100644 --- a/internal/agent/kimi.go +++ b/internal/agent/kimi.go @@ -15,7 +15,6 @@ package agent // and out the other way round. import ( - "os" "path/filepath" "slices" "strconv" @@ -38,18 +37,22 @@ const kimiContext = 128000 // when it first starts, and once that's done never reads ~/.kimi again, so a // model written there is one it never sees (#290). ~/.kimi is kimi-cli's only where // the new one isn't: no ~/.kimi-code, nor $KIMI_CODE_HOME. -func KimiDir(home string) (dir string, legacy bool) { - if d := os.Getenv("KIMI_CODE_HOME"); d != "" { +func KimiDir(home string) (dir string, legacy bool) { return kimiDir(here(home)) } + +// kimiDir is KimiDir at a place: in a WSL distro its variables aren't +// read, and a stopped one's is ~/.kimi-code until it is looked at. +func kimiDir(at place) (dir string, legacy bool) { + if d := at.getenv("KIMI_CODE_HOME"); d != "" { return d, false } - code := filepath.Join(home, ".kimi-code") - if isDir(code) { + code := filepath.Join(at.home, ".kimi-code") + if at.isDir(code) { return code, false } - if d := os.Getenv("KIMI_SHARE_DIR"); d != "" { + if d := at.getenv("KIMI_SHARE_DIR"); d != "" { return d, true } - if d := filepath.Join(home, ".kimi"); isDir(d) { + if d := filepath.Join(at.home, ".kimi"); at.isDir(d) { return d, true } return code, false @@ -113,8 +116,12 @@ func kimiEfforts(efforts []string) []edit.KV { return kvs } -func kimi(home string) *Agent { - dir, legacy := KimiDir(home) +func kimi(home string) *Agent { return kimiIn(here(home)) } + +// kimiIn is Kimi Code at a place: this machine's home, or a WSL distro's +// (see wsl.go), its provider naming the gateway as it reaches it from there. +func kimiIn(at place) *Agent { + dir, legacy := kimiDir(at) path := filepath.Join(dir, "config.toml") key := "kimi:" + path + ":default_model" get := func() string { v, _ := edit.GetTOMLTop(path, "default_model"); return v } @@ -122,7 +129,7 @@ func kimi(home string) *Agent { writeMagpie := func() error { if err := edit.SetTOMLTable(path, providerTable, edit.KV{Path: "type", Value: "kimi"}, - edit.KV{Path: "base_url", Value: gatewayV1()}, + edit.KV{Path: "base_url", Value: at.v1()}, edit.KV{Path: "api_key", Value: gateway.Token}, ); err != nil { return err @@ -184,7 +191,7 @@ func kimi(home string) *Agent { return "Kimi Code's [" + providerTable + "] (config.toml) is gone, so it no longer reaches magpie" } return wiringOff("Kimi Code", path, func(k string) (string, bool) { v, ok := t[k]; return v, ok }, - "base_url", gatewayV1(), "api_key", gateway.Token) + "base_url", at.v1(), "api_key", gateway.Token) }, Fields: []Field{{ Key: "model", Label: "model", diff --git a/internal/agent/minimax.go b/internal/agent/minimax.go index 31f63f68d..78356a058 100644 --- a/internal/agent/minimax.go +++ b/internal/agent/minimax.go @@ -45,8 +45,16 @@ func MiniMaxDir(home string) string { return filepath.Join(home, ".minimax") } -func miniMax(home string) *Agent { - dir := MiniMaxDir(home) +func miniMax(home string) *Agent { return miniMaxAt(here(home), MiniMaxDir(home)) } + +// miniMaxIn is MiniMax Code's mcode in a WSL distro (see wsl.go): ~/.minimax, +// as MINIMAX_DATA_DIR there isn't read. +func miniMaxIn(at place) *Agent { return miniMaxAt(at, filepath.Join(at.home, ".minimax")) } + +// miniMaxAt is MiniMax Code with its data folder at dir, reaching the +// gateway as at does. +func miniMaxAt(at place, dir string) *Agent { + writeMiniMaxEntry := func(path string) error { return writeMiniMaxEntryAt(path, at.gw()) } path := filepath.Join(dir, "config.yaml") key := "minimax-code:" + path + ":" get := func(k string) string { v, _ := edit.GetYAML(path, k); return v } @@ -94,7 +102,7 @@ func miniMax(home string) *Agent { return "MiniMax Code's " + mcodeEntry + " (config.yaml) is turned off, so it no longer reaches magpie" } return wiringOff("MiniMax Code", path, func(k string) (string, bool) { return edit.GetYAML(path, mcodeEntry+".options."+k) }, - "baseURL", gateway.URL(), "apiKey", gateway.Token) + "baseURL", at.gw(), "apiKey", gateway.Token) }, Fields: []Field{{ Key: "model", Label: "model", @@ -155,7 +163,11 @@ func miniMax(home string) *Agent { // catalog is now, over the one there: what magpie sets is set, a model gone // from the catalog goes, and every other key — the user's, MiniMax Code's — // stays with its comments. The file is written only when this changes it. -func writeMiniMaxEntry(path string) error { +func writeMiniMaxEntry(path string) error { return writeMiniMaxEntryAt(path, gateway.URL()) } + +// writeMiniMaxEntryAt is writeMiniMaxEntry for a MiniMax Code reaching the +// gateway at gw. +func writeMiniMaxEntryAt(path, gw string) error { cur, _ := edit.GetYAMLText(path, mcodeEntry) entry := &yaml.Node{Kind: yaml.MappingNode} if cur != "" { @@ -172,7 +184,7 @@ func writeMiniMaxEntry(path string) error { yamlSet(entry, "api", "anthropic-messages") opts := yamlMap(entry, "options") yamlSet(opts, "apiKey", gateway.Token) - yamlSet(opts, "baseURL", gateway.URL()) + yamlSet(opts, "baseURL", gw) yamlSet(opts, "authMode", "api-key") yamlSet(yamlMap(opts, "headers"), "User-Agent", mcodeUA) diff --git a/internal/agent/muse.go b/internal/agent/muse.go index 521da6876..37c2ccf07 100644 --- a/internal/agent/muse.go +++ b/internal/agent/muse.go @@ -30,7 +30,16 @@ const ( museModel = "model" ) -func muse(cfg string) *Agent { +func muse(cfg string) *Agent { return museAt(here(""), cfg) } + +// museIn is Muse Code in a WSL distro (see wsl.go): ~/.config/muse, as +// XDG_CONFIG_HOME there isn't read. +func museIn(at place) *Agent { return museAt(at, filepath.Join(at.home, ".config")) } + +// museAt is Muse Code with its config under cfg, reaching the gateway as +// at does. +func museAt(at place, cfg string) *Agent { + gatewayV1 := at.v1 dir := filepath.Join(cfg, "muse") path := filepath.Join(dir, "settings.json") keyTransport := "muse:" + path + ":" + museTransport diff --git a/internal/agent/omp.go b/internal/agent/omp.go index 851abb14d..8c5e442d6 100644 --- a/internal/agent/omp.go +++ b/internal/agent/omp.go @@ -112,14 +112,26 @@ func ompDir(home string) string { } func omp(home string) *Agent { - dir := ompDir(home) + return ompAt(here(home), ompDir(home), func() ompProviderEntry { return ompProvider() }) +} + +// ompIn is omp in a WSL distro (see wsl.go): ~/.omp/agent, as the +// distro's variables that move it aren't read. The omp there isn't the one +// on Windows' PATH, so its version isn't known, and its models offer xhigh +// rather than a max an older omp would refuse. +func ompIn(at place) *Agent { + return ompAt(at, filepath.Join(at.home, ".omp", "agent"), func() ompProviderEntry { return ompProviderAt(at.gw(), "") }) +} + +// ompAt is omp with its agent folder at dir, magpie's entry in its +// models.yml being entry's. +func ompAt(at place, dir string, entry func() ompProviderEntry) *Agent { + ompProvider := entry // omp reads the .yml and falls back to the .yaml pick := func(name string) string { yml := filepath.Join(dir, name+".yml") - if _, err := os.Stat(yml); err != nil { - if _, err := os.Stat(filepath.Join(dir, name+".yaml")); err == nil { - return filepath.Join(dir, name+".yaml") - } + if !at.exists(yml) && at.exists(filepath.Join(dir, name+".yaml")) { + return filepath.Join(dir, name+".yaml") } return yml } @@ -316,7 +328,7 @@ func omp(home string) *Agent { } models := pick("models") return wiringOff("omp", models, func(k string) (string, bool) { return edit.GetYAML(models, "providers."+magpieID+"."+k) }, - "baseUrl", gatewayV1()) + "baseUrl", at.v1()) }, Fields: []Field{ role("model", "model", "default", false), @@ -408,8 +420,12 @@ func ompTakesMax(v string) bool { // /v1/messages (omp adds the /v1). That one thinks adaptively when it takes // nothing else, else on a budget: omp's anthropic-budget-effort would also // send output_config.effort, which Sonnet 4.5 and Haiku 4.5 refuse. -func ompProvider() ompProviderEntry { - takesMax := ompTakesMax(ompVersion()) +func ompProvider() ompProviderEntry { return ompProviderAt(gateway.URL(), ompVersion()) } + +// ompProviderAt is ompProvider for an omp of version (as ompVersion) that +// reaches the gateway at gw. +func ompProviderAt(gw, version string) ompProviderEntry { + takesMax := ompTakesMax(version) ms := []ompModel{} for _, m := range magpieModels("omp") { e := ompModel{ID: m.ID, Name: m.Name, Context: m.Context, MaxTokens: maxTokens(m)} @@ -418,7 +434,7 @@ func ompProvider() ompProviderEntry { case slices.Contains(m.APIs, string(provider.Responses)): e.API = "openai-responses" case slices.Contains(m.APIs, string(provider.Anthropic)): - e.API, e.BaseURL = "anthropic-messages", gateway.URL() + e.API, e.BaseURL = "anthropic-messages", gw mode = "budget" if gateway.AdaptiveThinking(m.ID) { mode = "anthropic-adaptive" @@ -452,7 +468,7 @@ func ompProvider() ompProviderEntry { } ms = append(ms, e) } - return ompProviderEntry{BaseURL: gatewayV1(), API: "openai-completions", Auth: "none", + return ompProviderEntry{BaseURL: gw + "/v1", API: "openai-completions", Auth: "none", Headers: map[string]string{"User-Agent": "omp"}, Models: ms} } diff --git a/internal/agent/qoder.go b/internal/agent/qoder.go index dbe79b01a..a030d8520 100644 --- a/internal/agent/qoder.go +++ b/internal/agent/qoder.go @@ -29,7 +29,6 @@ package agent import ( "encoding/json" - "os" "path/filepath" "slices" @@ -58,10 +57,20 @@ var ( aliases: []string{"qoderclicn", "qodercn", "qodercn-cli"}, procs: []string{`(^|/)qoderclicn( |$)`, `(^|/)qodercn( |$)`}} ) -func qoderSite(home string, b qoderBuild) *Agent { - dir := os.Getenv(b.env) +// qoderIn and qoderCNIn are Qoder's two builds in a WSL distro (see +// wsl.go): at their default folders, as the distro's variables aren't read. +func qoderIn(at place) *Agent { return qoderAt(at, qoderGlobal) } +func qoderCNIn(at place) *Agent { return qoderAt(at, qoderChina) } + +func qoderSite(home string, b qoderBuild) *Agent { return qoderAt(here(home), b) } + +// qoderAt is a build of Qoder at a place, its provider naming the gateway +// as it reaches it from there. +func qoderAt(at place, b qoderBuild) *Agent { + qoderProvider := func(agent, model string) map[string]any { return qoderProviderAt(agent, model, at.v1()) } + dir := at.getenv(b.env) if dir == "" { - dir = filepath.Join(home, b.dir) + dir = filepath.Join(at.home, b.dir) } path := filepath.Join(dir, "settings.json") key := b.id + ":" + path + ":" @@ -124,7 +133,7 @@ func qoderSite(home string, b qoderBuild) *Agent { return "" } return wiringOff(b.name, path, func(k string) (string, bool) { return edit.GetJSON(path, slot+"."+k) }, - "baseUrl", gatewayV1()) + "baseUrl", at.v1()) }, Fields: []Field{{ Key: "model", Label: "model", @@ -250,6 +259,12 @@ var qoderLevels = []string{"low", "medium", "high", "xhigh", "max"} // qoderProvider is magpie's entry in Qoder's providers, every magpie model // in it, model the one it starts on. func qoderProvider(agent, model string) map[string]any { + return qoderProviderAt(agent, model, gatewayV1()) +} + +// qoderProviderAt is qoderProvider for a Qoder reaching the gateway's /v1 +// at v1. +func qoderProviderAt(agent, model, v1 string) map[string]any { var ms []map[string]any for _, m := range magpieModels(agent) { caps := map[string]any{"tools": true, "vision": m.Images} @@ -272,7 +287,7 @@ func qoderProvider(agent, model string) map[string]any { } ms = append(ms, e) } - return map[string]any{"displayName": "magpie", "protocol": "openai", "baseUrl": gatewayV1(), + return map[string]any{"displayName": "magpie", "protocol": "openai", "baseUrl": v1, "apiKey": gateway.TokenFor(agent), "model": model, "models": ms} } diff --git a/internal/agent/wsl.go b/internal/agent/wsl.go index 4271d3d3b..07aef1a44 100644 --- a/internal/agent/wsl.go +++ b/internal/agent/wsl.go @@ -9,6 +9,7 @@ import ( "os" "path/filepath" "runtime" + "slices" "strings" "sync" "time" @@ -41,10 +42,35 @@ type place struct { spell func(string) string // a path under home as the agent names it; nil: as is sys func(string) string // a path of the agent's system (/etc/…) as magpie opens it; nil: as is base func() string // the gateway's URL from the agent; nil: gateway.URL + // cold: a stopped distro's, whose files can't be looked at without + // starting it — an agent built there takes its files at their defaults + cold bool } func here(home string) place { return place{home: home} } +// getenv is this machine's variable for this machine's agent; "" for one +// in a distro, whose variables magpie can't read. +func (p place) getenv(k string) string { + if p.spell != nil { + return "" + } + return os.Getenv(k) +} + +// exists is whether there is a file or folder at path, as an agent looks +// for the one it reads; false at a cold place. +func (p place) exists(path string) bool { + if p.cold { + return false + } + _, err := os.Stat(path) + return err == nil +} + +// isDir is isDir at the place; false at a cold one. +func (p place) isDir(path string) bool { return !p.cold && isDir(path) } + func (p place) gw() string { if p.base != nil { return p.base() @@ -125,7 +151,7 @@ func (d distro) base() string { } func (d distro) place(id string) place { - return place{home: d.local(d.Home), id: id, spell: d.native, sys: d.local, base: d.base} + return place{home: d.local(d.Home), id: id, spell: d.native, sys: d.local, base: d.base, cold: !d.Running} } // wslKind is an agent magpie looks for in a distro: what the probe finds @@ -201,10 +227,101 @@ var wslKinds = []wslKind{ return claudeViaMagpie(false) } }}, + // The CLIs below keep a plain file in the distro's home, written as on + // this machine, at their default folders: the distro's variables that + // move them (OPENCODE_CONFIG_DIR, KIMI_CODE_HOME, HERMES_HOME, …) + // aren't read. Each one's restart advice is its own Notice's. + {id: "opencode", name: "OpenCode", dir: ".config/opencode", bin: "opencode", in: opencodeIn, + restart: "reads its config at start-up — restart open opencode sessions to use this.", + asleep: wslOwnAsleep("opencode", "model", "small")}, + {id: "mimocode", name: "MiMo Code", dir: ".config/mimocode", bin: "mimo", in: mimocodeIn, + restart: "reads its config at start-up — restart open mimo sessions to use this.", + asleep: wslOwnAsleep("mimocode", "model", "small")}, + // Kimi Code's ~/.kimi-code, or the old kimi-cli's ~/.kimi where that is + // all there is; a stopped distro's is looked at once it is started + {id: "kimi", name: "Kimi Code", dir: ".kimi-code", bin: "kimi", in: kimiIn, + restart: "reads its settings at start-up — restart open kimi sessions to use this.", + asleep: func(key string) func(map[string]string) []Option { + if key != "model" { + return nil + } + return func(cur map[string]string) []Option { + return append(kimiOwnOptions("", cur["model"]), viaMagpie("kimi", magpieID+"/")...) + } + }}, + {id: "omp", name: "omp", dir: ".omp", bin: "omp", in: ompIn, + restart: "reads its settings at start-up — restart open omp sessions to use this.", + asleep: func(key string) func(map[string]string) []Option { + if key == "effort" { + return nil + } + return func(cur map[string]string) []Option { + return append(ompOwnOptions("", cur[key]), viaMagpie("omp", magpieID+"/")...) + } + }}, + {id: "crush", name: "Crush", dir: ".config/crush", bin: "crush", in: crushIn, + restart: "reads its settings at start-up — restart open crush sessions to use this.", + asleep: wslOwnAsleep("crush", "model", "small")}, + {id: "hermes", name: "Hermes Agent", dir: ".hermes", bin: "hermes", in: hermesIn, + restart: "reads its settings at start-up — restart open Hermes sessions to use this."}, + // no bin: grok is also other tools' name, as on this machine + {id: "grok", name: "Grok Build", dir: ".grok", in: grokIn, + restart: "reads its settings at start-up — restart open grok sessions to use this."}, + {id: "droid", name: "Droid", dir: ".factory", bin: "droid", in: droidIn, + restart: "reads its settings at start-up — restart open droid sessions to use this.", + asleep: func(key string) func(map[string]string) []Option { + if key != "model" { + return nil + } + return func(cur map[string]string) []Option { + var own []Option + if c := cur["model"]; c != "" && !usesMagpie(c) { + own = append(own, Option{Value: c, Icon: modelIcon("", c)}) + } + return append(group("Droid", own), viaMagpie("droid", magpieID+"/")...) + } + }}, + // no bin: fx is also the JSON viewer's name + {id: "fx", name: "fx", dir: ".fx", in: fxIn, + restart: "reads its settings at start-up — restart open fx sessions to use this."}, + {id: "commandcode", name: "Command Code", dir: ".commandcode", bin: "command-code", in: commandCodeIn, + restart: "wants its own sign-in there (cmd login) even for models through magpie, and reads its settings at start-up — restart open Command Code sessions to use this."}, + {id: "minimax-code", name: "MiniMax Code", dir: ".minimax", bin: "mcode", in: miniMaxIn, + restart: "reads its settings at start-up — restart open mcode sessions to use this.", + asleep: func(key string) func(map[string]string) []Option { + if key != "model" { + return nil + } + return func(cur map[string]string) []Option { + return append(miniMaxOwnOptions("", cur["model"]), viaMagpie("minimax-code", magpieID+"/")...) + } + }}, + {id: "muse", name: "Muse Code", dir: ".config/muse", bin: "muse", in: museIn, + restart: "reads its settings at start-up — restart open muse sessions to use this."}, + {id: "qoder", name: "Qoder", dir: ".qoder", bin: "qodercli", in: qoderIn, + restart: "reads its settings as a session starts — open sessions keep the model they have; new ones use this."}, + {id: "qoder-cn", name: "Qoder CN", dir: ".qoder-cn", bin: "qoderclicn", in: qoderCNIn, + restart: "reads its settings as a session starts — open sessions keep the model they have; new ones use this."}, +} + +// wslOwnAsleep is a stopped distro's options for an agent's model fields +// (keys) whose live ones read its files: the providers of the value last +// seen, and magpie's. +func wslOwnAsleep(id string, keys ...string) func(string) func(map[string]string) []Option { + return func(key string) func(map[string]string) []Option { + if !slices.Contains(keys, key) { + return nil + } + return func(cur map[string]string) []Option { + return append(ownOptions("", cur[key]), viaMagpie(id, magpieID+"/")...) + } + } } // found reports whether the probe found the agent in d. -func (k wslKind) found(d distro) bool { return d.Has["dir:"+k.dir] || d.Has["bin:"+k.bin] } +func (k wslKind) found(d distro) bool { + return d.Has["dir:"+k.dir] || k.bin != "" && d.Has["bin:"+k.bin] +} // memo is the key a field of the agent is kept under in distro.Values: // Codex's as they are, as wsl.json has always had them. @@ -315,7 +432,7 @@ func asleep(live *Agent, k wslKind, d distro) *Agent { return "WSL " + d.Name + " isn't running: magpie shows what it last saw there, and starts it only to change something." }} for _, lf := range live.Fields { - key, set := lf.Key, lf.Set + key := lf.Key f := Field{Key: key, Label: lf.Label, Quiet: lf.Quiet, Options: lf.Options, Get: func() string { return wslLastSeen(d.Name, k.memo(key)) }, Set: func(v string) error { @@ -325,9 +442,19 @@ func asleep(live *Agent, k wslKind, d distro) *Agent { return fmt.Errorf("start WSL %s: %w", d.Name, err) } started = true - err := set(v) + // the agent again, now its files can be looked at: which of + // them it reads (opencode.jsonc or .json, ~/.kimi-code or + // ~/.kimi) is theirs to say, not the defaults it was built on + w := d + w.Running = true + warm := k.in(w.place(live.ID)) + wf := warm.Field(key) + if wf == nil || wf.Set == nil { + return fmt.Errorf("%s has no %s", live.Name, key) + } + err := wf.Set(v) // a model settles the effort too - for _, f := range live.Fields { + for _, f := range warm.Fields { wslRemember(d.Name, k.memo(f.Key), f.Get()) } wslSave() @@ -575,8 +702,10 @@ const wslProbeVersion = 2 var wslProbeScript = func() string { s := `echo "home:$HOME"; ` for _, k := range wslKinds { - s += `[ -d "$HOME/` + k.dir + `" ] && echo dir:` + k.dir + `; ` + - `p=$(command -v ` + k.bin + ` 2>/dev/null) && echo "bin:` + k.bin + ` $p"; ` + s += `[ -d "$HOME/` + k.dir + `" ] && echo dir:` + k.dir + `; ` + if k.bin != "" { + s += `p=$(command -v ` + k.bin + ` 2>/dev/null) && echo "bin:` + k.bin + ` $p"; ` + } } // a drive's source in /proc/mounts is C:\ (written C:\134), under any automount root s += `awk '$1 ~ /^[A-Za-z]:/ {print "win:" $2}' /proc/mounts 2>/dev/null; ` diff --git a/internal/agent/wsl_more_test.go b/internal/agent/wsl_more_test.go new file mode 100644 index 000000000..93959960d --- /dev/null +++ b/internal/agent/wsl_more_test.go @@ -0,0 +1,273 @@ +package agent + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/gateway" +) + +// wslMore is each CLI #515 brings into WSL distros: the file under the +// distro's home that carries magpie's provider once one of magpie's models +// is picked, and what of the gateway's address it names (its /v1, or the +// bare address for one spoken to as Anthropic messages). +var wslMore = []struct { + id, file, suffix string +}{ + {"opencode", ".config/opencode/opencode.json", "/v1"}, + {"mimocode", ".config/mimocode/mimocode.json", "/v1"}, + {"kimi", ".kimi-code/config.toml", "/v1"}, + {"omp", ".omp/agent/models.yml", "/v1"}, + {"crush", ".config/crush/crush.json", "/v1"}, + {"hermes", ".hermes/config.yaml", "/v1"}, + {"grok", ".grok/config.toml", "/v1"}, + {"droid", ".factory/settings.json", "/v1"}, + {"fx", ".fx/settings.json", "/v1"}, + {"commandcode", ".commandcode/providers.json", "/v1"}, + {"minimax-code", ".minimax/config.yaml", ""}, + {"muse", ".config/muse/settings.json", "/v1"}, + {"qoder", ".qoder/settings.json", "/v1"}, + {"qoder-cn", ".qoder-cn/settings.json", "/v1"}, +} + +// moveHostDirs points the variables that move these agents' folders on +// this machine at a folder of its own, which a distro's agent must leave +// alone: a distro's variables are its own, not Windows'. +func moveHostDirs(t *testing.T) string { + t.Helper() + moved := t.TempDir() + for _, v := range []string{"OPENCODE_CONFIG_DIR", "MIMOCODE_HOME", "KIMI_CODE_HOME", "KIMI_SHARE_DIR", "PI_CODING_AGENT_DIR", + "HERMES_HOME", "GROK_HOME", "FACTORY_HOME_OVERRIDE", "MINIMAX_DATA_DIR", "QODER_CONFIG_DIR", "QODERCN_CONFIG_DIR"} { + t.Setenv(v, filepath.Join(moved, v)) + } + return moved +} + +// The probe asks after each of them by its folder and, but for grok and +// fx, whose names other tools have too, its command; and finds each by +// either. +func TestWSLProbeFindsMoreAgents(t *testing.T) { + for _, c := range wslMore { + k := wslKindOf(c.id) + if !strings.Contains(wslProbeScript, `[ -d "$HOME/`+k.dir+`" ] && echo dir:`+k.dir+`; `) { + t.Errorf("%s: probe lacks its folder %s", c.id, k.dir) + } + if !strings.HasPrefix(c.file, k.dir+"/") { + t.Errorf("%s: its file %s isn't under %s", c.id, c.file, k.dir) + } + if k.bin != "" && !strings.Contains(wslProbeScript, `command -v `+k.bin+` `) { + t.Errorf("%s: probe lacks its command %s", c.id, k.bin) + } + if d := parseProbe("U", "home:/home/me\ndir:"+k.dir+"\n"); d == nil || !k.found(*d) { + t.Errorf("%s: not found by its folder", c.id) + } + if k.bin != "" { + if d := parseProbe("U", "home:/home/me\nbin:"+k.bin+" /usr/bin/"+k.bin+"\n"); d == nil || !k.found(*d) { + t.Errorf("%s: not found by its command", c.id) + } + } + } + for _, bin := range []string{"fx", "grok"} { + if strings.Contains(wslProbeScript, `command -v `+bin+` `) { + t.Errorf("probe takes any %s command for the agent", bin) + } + } + // Kimi Code's old kimi-cli, in ~/.kimi, is found by its command + if d := parseProbe("U", "home:/home/me\nbin:kimi /home/me/.local/bin/kimi\n"); d == nil || !wslKindOf("kimi").found(*d) { + t.Error("kimi by its command") + } +} + +// A running distro with them lists each as · WSL , with no +// command, User-Agent or aliases of its own (those are its Windows twin's). +func TestWSLMoreAgentsDiscovered(t *testing.T) { + syncHome(t) + root := t.TempDir() + probe := "home:/home/me\nroute:default via 172.20.0.1 dev eth0\n" + var want []string + for _, c := range wslMore { + probe += "dir:" + wslKindOf(c.id).dir + "\n" + want = append(want, c.id+"@wsl:Ubuntu") + } + _, opened := fakeWSL(t, "Ubuntu\r\n", "Ubuntu\r\n", map[string]string{"Ubuntu": probe}, map[string]string{"Ubuntu": root}) + ds := wslDistros() + if len(ds) != 1 || strings.Join(*opened, ",") != "Ubuntu" { + t.Fatalf("%+v %v", ds, *opened) + } + var ids []string + for _, a := range wslAgentsOf(ds) { + ids = append(ids, a.ID) + k := wslKindOf(strings.TrimSuffix(a.ID, "@wsl:Ubuntu")) + if a.Name != k.name+" · WSL Ubuntu" || a.WSL != "Ubuntu" || a.Bin != "" || a.UA != nil || a.Aliases != nil || + !strings.HasPrefix(a.Path, filepath.Join(root, "home", "me")+string(filepath.Separator)) { + t.Errorf("%+v", a) + } + } + if got := strings.Join(ids, ","); got != strings.Join(want, ",") { + t.Fatalf("agents %s\nwant %s", got, strings.Join(want, ",")) + } +} + +// Picking one of magpie's models writes each one's own file in the +// distro's home, as on this machine but naming the gateway as the distro +// reaches it: Windows' address under NAT, 127.0.0.1 when mirrored. Its +// wiring checks out against that address, a sync keeps it, and nothing of +// this machine's — its home, or the folders its variables name — is +// touched. +func TestWSLMoreAgentsPick(t *testing.T) { + for _, c := range wslMore { + for _, mirrored := range []bool{false, true} { + home := syncHome(t) + moved := moveHostDirs(t) + root := t.TempDir() + dhome := filepath.Join(root, "home", "me") + k := wslKindOf(c.id) + os.MkdirAll(filepath.Join(dhome, filepath.FromSlash(k.dir)), 0o755) + d := distro{Name: "Ubuntu", Root: root, Home: "/home/me", Has: map[string]bool{"dir:" + k.dir: true}, + Gateway: "172.20.0.1", Mirrored: mirrored, Running: true} + a := wslAgent(k, d) + if err := a.Field("model").Set("magpie/relay/glm-4.6"); err != nil { + t.Fatalf("%s: %v", c.id, err) + } + path := filepath.Join(dhome, filepath.FromSlash(c.file)) + gw := gateway.URL() + if !mirrored { + gw = "http://172.20.0.1:" + gateway.Port() + } + body := readFile(path) + if !strings.Contains(body, gw+c.suffix) || !strings.Contains(body, "glm-4.6") { + t.Fatalf("%s mirrored %v: %s lacks %s:\n%s", c.id, mirrored, c.file, gw+c.suffix, body) + } + if !mirrored && strings.Contains(body, "127.0.0.1") { + t.Fatalf("%s: this machine's address under NAT:\n%s", c.id, body) + } + if v := a.Field("model").Get(); !usesMagpie(v) { + t.Fatalf("%s: model %q", c.id, v) + } + if msg := a.Check(); msg != "" { + t.Fatalf("%s mirrored %v: %s", c.id, mirrored, msg) + } + if a.Sync != nil { + if err := a.Sync(); err != nil || !strings.Contains(readFile(path), gw+c.suffix) { + t.Fatalf("%s sync %v:\n%s", c.id, err, readFile(path)) + } + } + if !mirrored && !strings.Contains(a.Notice(), "mirrored") { + t.Errorf("%s: %s", c.id, a.Notice()) + } + if mirrored && !strings.HasPrefix(a.Notice(), k.name+" in WSL Ubuntu ") { + t.Errorf("%s: %s", c.id, a.Notice()) + } + for _, dir := range []string{filepath.Join(home, filepath.FromSlash(k.dir)), moved} { + if es, _ := os.ReadDir(dir); len(es) > 0 { + t.Fatalf("%s: this machine's %s was touched", c.id, dir) + } + } + } + } +} + +// A stopped distro's agents are never asked anything nor opened: each is +// listed as magpie last saw it, its options come from magpie alone, and a +// pick starts the distro, then writes its file there. +func TestWSLMoreAgentsStopped(t *testing.T) { + for _, c := range wslMore { + syncHome(t) + root := t.TempDir() + k := wslKindOf(c.id) + b, _ := json.Marshal(map[string]*distro{ + "Stopped": {Name: "Stopped", Home: "/home/me", Root: root, Has: map[string]bool{"dir:" + k.dir: true}, + Values: map[string]string{k.memo("model"): "own/last-seen"}}, + }) + os.MkdirAll(filepath.Dir(wslStatePath()), 0o755) + os.WriteFile(wslStatePath(), b, 0o600) + asked, opened := fakeWSL(t, "Stopped\r\n", "", nil, nil) + var a *Agent + for _, x := range wslAgentsOf(wslDistros()) { + if x.ID == c.id+"@wsl:Stopped" { + a = x + } + } + if a == nil || a.Path != "" || a.Dir != "" || a.Check != nil || a.Sync != nil { + t.Fatalf("%s: %+v", c.id, a) + } + if v := a.Values(); v["model"] != "own/last-seen" { + t.Fatalf("%s: values %v", c.id, v) + } + for _, f := range a.Fields { + if f.Options != nil { + f.Options(a.Values()) + } + } + if !strings.Contains(a.Notice(), "isn't running") || len(*asked) != 0 || len(*opened) != 0 { + t.Fatalf("%s: %s, asked %v opened %v", c.id, a.Notice(), *asked, *opened) + } + if es, _ := os.ReadDir(root); len(es) > 0 { + t.Fatalf("%s: a stopped distro was opened", c.id) + } + if err := a.Field("model").Set("magpie/relay/glm-4.6"); err != nil { + t.Fatalf("%s: %v", c.id, err) + } + if strings.Join(*asked, ",") != "Stopped" { + t.Fatalf("%s: not started first: %v", c.id, *asked) + } + if body := readFile(filepath.Join(root, "home", "me", filepath.FromSlash(c.file))); !strings.Contains(body, "glm-4.6") { + t.Fatalf("%s: nothing written to %s", c.id, c.file) + } + if v := a.Field("model").Get(); !usesMagpie(v) { + t.Fatalf("%s: last seen %q", c.id, v) + } + } +} + +// A stopped distro's agent is built on its default files, as they can't +// be looked at; a pick, once it has started the distro, writes the ones +// the agent reads: an opencode.jsonc already there, the old kimi-cli's +// ~/.kimi where there is no ~/.kimi-code. +func TestWSLStoppedPickFindsItsFiles(t *testing.T) { + syncHome(t) + root := t.TempDir() + dhome := filepath.Join(root, "home", "me") + jsonc := filepath.Join(dhome, ".config", "opencode", "opencode.jsonc") + legacy := filepath.Join(dhome, ".kimi", "config.toml") + os.MkdirAll(filepath.Dir(jsonc), 0o755) + os.MkdirAll(filepath.Dir(legacy), 0o755) + os.WriteFile(jsonc, []byte("{\n // mine\n \"model\": \"anthropic/claude-sonnet-5\"\n}\n"), 0o644) + os.WriteFile(legacy, []byte("default_model = \"kimi-k3\"\n"), 0o644) + b, _ := json.Marshal(map[string]*distro{ + "Stopped": {Name: "Stopped", Home: "/home/me", Root: root, Has: map[string]bool{"dir:.config/opencode": true, "bin:kimi": true}, Probe: wslProbeVersion}, + }) + os.MkdirAll(filepath.Dir(wslStatePath()), 0o755) + os.WriteFile(wslStatePath(), b, 0o600) + fakeWSL(t, "Stopped\r\n", "", nil, nil) + byID := map[string]*Agent{} + for _, a := range wslAgentsOf(wslDistros()) { + byID[a.ID] = a + } + oc, ki := byID["opencode@wsl:Stopped"], byID["kimi@wsl:Stopped"] + if oc == nil || ki == nil { + t.Fatalf("%v", byID) + } + if err := oc.Field("model").Set("magpie/relay/glm-4.6"); err != nil { + t.Fatal(err) + } + if m, _ := edit.GetJSON(jsonc, "model"); m != "magpie/relay/glm-4.6" || !strings.Contains(readFile(jsonc), "// mine") { + t.Fatalf("opencode.jsonc:\n%s", readFile(jsonc)) + } + if _, err := os.Stat(filepath.Join(dhome, ".config", "opencode", "opencode.json")); !os.IsNotExist(err) { + t.Fatal("a second opencode.json beside the .jsonc") + } + if err := ki.Field("model").Set("magpie/relay/glm-4.6"); err != nil { + t.Fatal(err) + } + if v, _ := edit.GetTOMLTop(legacy, "default_model"); v != "magpie/relay/glm-4.6" { + t.Fatalf("~/.kimi/config.toml:\n%s", readFile(legacy)) + } + if _, err := os.Stat(filepath.Join(dhome, ".kimi-code")); !os.IsNotExist(err) { + t.Fatal("a ~/.kimi-code the old kimi-cli never reads") + } +}