Files
magpie/internal/appdir/env.go
T
yetone 3c6b7d585f agent: OpenClaw is wired up like the other agents
arthur041691 (Discord #help) runs OpenClaw for WhatsApp and asked for it in
Agents. Connecting writes magpie as a custom provider of OpenClaw's own, in
openclaw.json, and makes the picked model agents.defaults.model's primary.

What is written, from OpenClaw's source at 5bab0c14 (npm 2026.10.8, dc2523e):
- the file: OPENCLAW_CONFIG_PATH, else $OPENCLAW_STATE_DIR/openclaw.json,
  else ~/.openclaw-<profile> for a named OPENCLAW_PROFILE, else
  ~/.openclaw; ~ is OPENCLAW_HOME when set (src/config/paths.ts,
  src/config/state-dir.ts, src/cli/profile-utils.ts). OPENCLAW_PROFILE is
  a name, not a path (agentenv.NotPaths); the other three expand a
  leading ~, as resolveUserPath does (appdir.usable).
- models.providers.magpie: baseUrl (the gateway's /v1), apiKey (the
  OpenClaw-named gateway key), api "openai-completions", and every model
  magpie serves with id, name, input, reasoning and contextWindow
  (src/config/zod-schema.core.ts, docs/gateway/config-tools/custom-providers.md).
  A user's own keys on a model entry (headers, maxTokens…) stay on Sync.
- agents.defaults.model keeps its shape (string or {primary, fallbacks});
  agents.defaults.models gets the ref's {} entry as `openclaw models set`
  adds it (src/commands/models/shared.ts), only when that map exists; a
  non-empty modelPolicy.allow gets "magpie/*" when nothing there lets
  magpie's models in (src/agents/model-selection-normalize.ts).
- Model changes are hot-reloaded (docs/gateway/configuration/hot-reload.md);
  a chat that already has a model keeps it (docs/concepts/models.md), so
  the notice says to send /model default there. Translated in every
  language.
- The file is written through temp-and-rename; a new one is 0600 in a
  0700 folder, as OpenClaw makes it (src/config/io.write.ts). A file that
  isn't JSON after comments are blanked (JSON5's bare keys) is left alone
  with an error, never read as empty.
- Disconnect puts back the model there was, removes magpie's provider,
  its {} entries, the allow entry and any object magpie made, and the
  file itself if magpie made it.

Icon: a mask drawn from OpenClaw's ui/public/favicon.svg (MIT).

Run, on mote at this tree:
- go test -tags nogui ./internal/agent -run OpenClaw plus the every-agent
  tests (drift, port move, sync on another machine, reverse proxy, LAN,
  pinned key per writer, notices translated), ./internal/appdir,
  ./internal/agentenv: ok.
- Broken by hand, each red then green again: no stash restore
  (TestOpenClaw, Shapes, AllowList), user keys dropped
  (SyncKeepsTheirs), no allow entry (AllowList), no JSON5 guard
  (JSON5LeftAlone), profile ignored (Paths), OPENCLAW_PROFILE back as a
  path variable (Paths).
- Real OpenClaw 2026.10.8 from npm, Node 24.22.2, sandbox HOME on mote:
  onboard --non-interactive made the file (its bytes are the test
  fixture); magpie's code connected it; `openclaw config validate` ok;
  `openclaw models list` shows magpie/kimi/k2 as default; `openclaw agent
  --local` sent POST /v1/chat/completions with Bearer magpie-openclaw and
  model kimi/k2 to a fake gateway on 3425 and showed its reply; no
  agents/*/models.json override was written; Disconnect gave the file
  back byte for byte and it validates.
- GUI: i18n-keys, agent-notice-lang, icon-tile, about-notices,
  agent-connect (Chromium and WebKit): 53/53.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok.
- Full suite, go test -tags nogui -timeout 45m ./... at fe05f0a72 + this
  change: 76 packages ok; internal/provider red on
  TestClaudeAccountServesModelsListedSinceItsFetch only, green alone
  -count=5: the known #3174 (untouched here).
- Rebased on b2d005bf3 (grok.go, i18n.js changed there): internal/agent,
  appdir, agentenv, gui and the five GUI files above again, all ok.

Not tried: per-agent model overrides (agents.list[].model), a config
split with $include, a chat already pinned to a model, Windows and Linux
OpenClaw installs, a real WhatsApp channel.
2026-10-29 05:06:50 +08:00

128 lines
4.0 KiB
Go

package appdir
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"github.com/yetone/magpie/internal/agentenv"
)
// homeVar is the variable Go's os.UserHomeDir reads the home folder from.
func homeVar() string {
if runtime.GOOS == "windows" {
return "USERPROFILE"
}
return "HOME"
}
// rooted says whether p names the same place whatever the working folder
// is: absolute, or on Windows rooted on the current drive, as \Users\x or
// /x is. A Git Bash path such as /c/x is one too, though Go takes it as
// \c\x on the current drive, not C:\x: it kept that meaning before, and it
// still doesn't depend on the working folder.
func rooted(p string) bool {
if filepath.IsAbs(p) {
return true
}
return runtime.GOOS == "windows" && (strings.HasPrefix(p, `\`) || strings.HasPrefix(p, "/"))
}
// Home is the user's home folder, or an error when its variable is unset,
// empty or relative. os.UserHomeDir hands back "" there, which
// filepath.Join turns into a path under the folder magpie was started in,
// and on Android it falls back to the shared /sdcard.
func Home() (string, error) {
v := homeVar()
switch h := os.Getenv(v); {
case h == "":
return "", fmt.Errorf("%s is not set: magpie needs the home folder to find its own files and the agents'", v)
case !rooted(h):
return "", fmt.Errorf("%s is %q, not an absolute path", v, h)
default:
return h, nil
}
}
// mustHome is Home for paths built once main has checked it; reached with
// an unusable home anyway (a test made one), it stops rather than write
// under the working folder.
func mustHome() string {
h, err := Home()
if err != nil {
panic("appdir: " + err.Error())
}
return h
}
// pathVars are the variables folders and files are built from: the XDG
// folders, Windows' application data folders, magpie's own and every
// agent's.
var pathVars = sync.OnceValue(func() map[string]bool {
vs := map[string]bool{}
for _, v := range []string{
"XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_RUNTIME_DIR",
"APPDATA", "LOCALAPPDATA",
"MAGPIE_BIN_DIR", "OMARCHY_PATH", "OPENCODE_CONFIG",
} {
vs[v] = true
}
for _, v := range agentenv.Vars {
if !agentenv.NotPaths[v] {
vs[v] = true
}
}
return vs
})
// usable accepts rooted paths, and a home-relative path only for variables
// whose readers expand it. Most agent paths, like the XDG and Windows
// folders, are used as given and would put a literal ~ under the working folder.
func usable(name, v string) bool {
if rooted(v) {
return true
}
switch name {
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 false
}
// LookupEnv is os.LookupEnv for what magpie itself reads: a folder variable
// (pathVars) holding a relative path reads as unset, as the XDG spec asks of
// one, so no file of magpie's or an agent's is written under the working
// folder. The environment is left as it is: the programs magpie starts get
// the variable as the user set it. The variables a login shell lends the
// desktop app (proc.UserPath) are read through here too.
func LookupEnv(name string) (string, bool) {
v, ok := os.LookupEnv(name)
if ok && v != "" && pathVars()[name] && !usable(name, v) {
return "", false
}
return v, ok
}
// Getenv is LookupEnv's value, "" for a variable unset or ignored.
func Getenv(name string) string {
v, _ := LookupEnv(name)
return v
}
// CheckEnv is what main checks before anything is read or written: an
// unusable home folder is the error, and ignored names the folder
// variables holding a relative path, which LookupEnv passes over.
func CheckEnv() (ignored []string, err error) {
for v := range pathVars() {
if x := os.Getenv(v); x != "" && !usable(v, x) {
ignored = append(ignored, v)
}
}
_, err = Home()
return ignored, err
}