diff --git a/docs/reference.md b/docs/reference.md index 48f93fce2..13da7b0eb 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1870,6 +1870,51 @@ Termux uses the Android terminal build: the installer puts it in `go build` or `go install`, pass `-tags nogui`; use `magpie web` or `magpie tui` for the interface. `magpie autostart on` requires Termux:Boot. +### As a background service + +`magpie daemon install` runs `magpie serve` as a service of your own, with +no window and no desktop session: a server, or a machine you reach over +SSH. The system starts it at login (and at boot, see below) and starts it +again when it stops with a failure. + +```sh +magpie daemon install # write the service and start it; again, to take a new PATH or proxy +magpie daemon status # running or not, its pid, file and logs, whether the gateway answers +magpie daemon restart # after updating magpie +magpie daemon stop|start +magpie daemon uninstall # stop it and remove the file +``` + +- **Linux:** a systemd user unit, `~/.config/systemd/user/magpie.service` + (`$XDG_CONFIG_HOME/systemd/user` when set), run with `systemctl --user`, + no root. Its log: `journalctl --user -u magpie -f`. systemd starts a + user's units at their first login and stops them at their last, so for + the gateway to run from boot with no one logged in, run + `sudo loginctl enable-linger $USER` once; `magpie daemon status` says so + when it isn't on. From `su` or `sudo -u`, `systemctl --user` can't reach + your session: log in as the user, or set + `XDG_RUNTIME_DIR=/run/user/$(id -u)`. On WSL, turn systemd on first + (`[boot] systemd=true` in `/etc/wsl.conf`). A system without systemd is + told so; run `magpie serve` under the manager it has. +- **macOS:** a launch agent, `~/Library/LaunchAgents/com.yetone.magpie.serve.plist`, + loaded with `launchctl bootstrap gui/$UID`. Its log: + `~/Library/Logs/magpie/serve.log`. +- **Windows:** not a service; `magpie autostart on` opens magpie, which + serves the gateway, when you log in. Inside WSL, `magpie daemon` works as + on Linux. + +The service gets the environment `magpie daemon install` ran in: `PATH` +(where it finds the agents' CLIs and bun), the proxy variables, `MAGPIE_*` +settings such as `MAGPIE_ADDR`, the XDG folders and the agents' own folder +variables (`CODEX_HOME`, `CLAUDE_CONFIG_DIR`…). The file is readable by you +alone, since a proxy's address can hold a password. Run the install again +after changing any of them. It runs magpie by the name it has on `PATH` +when that is the same file (Homebrew's link stays right across updates), +and refuses a `go run` build. It is refused while `magpie autostart` is on: +the app opened at login serves the gateway too, and the two would take +turns failing on the port. The app opened by hand while the service runs +uses the service's gateway. + ### Docker `docker build` makes a server image: the terminal-only binary on diff --git a/internal/cli/daemon_cli.go b/internal/cli/daemon_cli.go new file mode 100644 index 000000000..98009d014 --- /dev/null +++ b/internal/cli/daemon_cli.go @@ -0,0 +1,127 @@ +package cli + +import ( + "errors" + "fmt" + "strconv" + "time" + + "github.com/yetone/magpie/internal/daemon" + "github.com/yetone/magpie/internal/gateway" +) + +const daemonUsage = "usage: magpie daemon [install|uninstall|start|stop|restart|status]" + +// daemonWait is how long install, start and restart wait for the gateway +// to answer before saying where its log is; a var for the tests. +var daemonWait = 5 * time.Second + +// magpie daemon …: `magpie serve` as a service of the user's, started at +// boot or login and again when it stops (systemd --user, launchd). +func daemonCmd(args []string) error { + if len(args) > 1 { + return errors.New(daemonUsage) + } + cmd := "status" + if len(args) == 1 { + cmd = args[0] + } + var err error + switch cmd { + case "status": + return daemonStatus() + case "install": + err = daemon.Install() + case "uninstall", "remove": + if err := daemon.Uninstall(); err != nil { + return err + } + fmt.Println(green.Render("✓"), "the magpie service is removed") + return nil + case "start": + err = daemon.Start() + case "stop": + if err := daemon.Stop(); err != nil { + return err + } + fmt.Println(green.Render("✓"), "the magpie service is stopped") + return nil + case "restart": + err = daemon.Restart() + default: + return errors.New(daemonUsage) + } + if err != nil { + return err + } + st, _ := daemon.Get() + switch cmd { + case "install": + fmt.Println(green.Render("✓"), "magpie serves the gateway as a service, from boot or login, started again when it stops") + fmt.Println(muted.Render(" file "), st.File) + if a := daemon.Linger(); a != "" { + fmt.Println(amber.Render("!"), a) + } + default: + fmt.Println(green.Render("✓"), "the magpie service is "+cmd+"ed") + } + deadline := time.Now().Add(daemonWait) + for { + if o := gateway.ServedBy(); o.Running { + fmt.Println(green.Render("●"), "the gateway answers on", bold.Render(gateway.URL())) + return nil + } + if !time.Now().Before(deadline) { + break + } + time.Sleep(250 * time.Millisecond) + } + fmt.Println(amber.Render("!"), "the gateway doesn't answer on", gateway.URL(), "yet ·", st.Logs) + return nil +} + +func daemonStatus() error { + st, err := daemon.Get() + if err != nil { + return err + } + served := gateway.ServedBy() + if !st.Installed { + fmt.Println("the magpie service isn't installed ·", muted.Render("magpie daemon install")) + if served.Running { + fmt.Println(muted.Render(" another magpie (the app, magpie serve) answers on"), gateway.URL()) + } + return nil + } + mark, word := amber.Render("○"), "not running" + if st.Running { + mark, word = green.Render("●"), "running" + } + line := "the magpie service is " + word + if st.PID > 0 { + line += " · pid " + strconv.Itoa(st.PID) + } + fmt.Println(mark, line) + if st.State != "" { + fmt.Println(muted.Render(" state "), st.State) + } + if st.LastExit != "" { + fmt.Println(muted.Render(" last exit"), st.LastExit) + } + start := "at boot or login" + if !st.Enabled { + start = "only when started" + } + fmt.Println(muted.Render(" start "), start) + fmt.Println(muted.Render(" file "), st.File) + fmt.Println(muted.Render(" logs "), st.Logs) + if served.Running { + fmt.Println(muted.Render(" gateway"), "answers on", gateway.URL(), muted.Render(served.Version)) + } else { + fmt.Println(muted.Render(" gateway"), "doesn't answer on", gateway.URL()) + } + for _, a := range st.Advice { + fmt.Println(amber.Render("!"), a) + } + return nil +} diff --git a/internal/cli/daemon_cli_test.go b/internal/cli/daemon_cli_test.go new file mode 100644 index 000000000..3a05da043 --- /dev/null +++ b/internal/cli/daemon_cli_test.go @@ -0,0 +1,47 @@ +package cli + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/yetone/magpie/internal/testenv" +) + +// magpie daemon: status before an install says how to install; start +// says to install first; a word it doesn't take prints its usage; and a +// `go test` or `go run` build, which Go deletes, is never installed as the +// service. None of them runs the system's service tool. +func TestDaemonCmd(t *testing.T) { + if runtime.GOOS != "linux" && runtime.GOOS != "darwin" { + t.Skip("systemd and launchd only") + } + helpHome(t) + dir := t.TempDir() + calls := filepath.Join(dir, "calls") + for _, name := range []string{"systemctl", "launchctl", "loginctl"} { + testenv.Program(t, filepath.Join(dir, name), "#!/bin/sh\necho \""+name+" $*\" >> '"+calls+"'\n") + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + prev := daemonWait + daemonWait = 0 + t.Cleanup(func() { daemonWait = prev }) + out, err := runOut(t, "daemon") + if err != nil || !strings.Contains(out, "isn't installed") || !strings.Contains(out, "magpie daemon install") { + t.Errorf("status: %q, %v", out, err) + } + if _, err := runOut(t, "daemon", "start"); err == nil || !strings.Contains(err.Error(), "isn't installed") { + t.Errorf("start: %v", err) + } + if _, err := runOut(t, "daemon", "bogus"); err == nil || !strings.Contains(err.Error(), "usage: magpie daemon") { + t.Errorf("bogus: %v", err) + } + if _, err := runOut(t, "daemon", "install"); err == nil || !strings.Contains(err.Error(), "go run") { + t.Errorf("install from a test build: %v", err) + } + if b, _ := os.ReadFile(calls); len(b) > 0 { + t.Errorf("ran %s", b) + } +} diff --git a/internal/cli/main.go b/internal/cli/main.go index 6e572f87e..4e68a82c7 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -104,6 +104,8 @@ const usage = `magpie — one place to pick every agent's model magpie plugin move-back|unmigrate go back to the built-in, with its accounts magpie serve run the gateway alone (the app runs it too) + magpie daemon [install|uninstall|start|stop|restart|status] + magpie serve as a service of yours, from boot or login and started again when it stops (systemd --user on Linux, launchd on the Mac) magpie healthcheck exit 0 when the gateway answers (a container's HEALTHCHECK) magpie gateway-key list|add |rotate |remove manage the keys clients use to call a shared gateway magpie gateway-key limit [off|reset|day|week|month|d --tokens N --cost USD --cache-reads] a key's own limit, and what it used @@ -301,6 +303,8 @@ func run(args []string) error { return runPanel() case "autostart": return autostartCmd(args[1:]) + case "daemon": + return daemonCmd(args[1:]) case "-h", "--help", "help": fmt.Print(usage) return nil diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go new file mode 100644 index 000000000..85e46d85a --- /dev/null +++ b/internal/daemon/daemon.go @@ -0,0 +1,251 @@ +// Package daemon runs `magpie serve` as a service of the user's own: a +// systemd user unit on Linux, a launch agent on the Mac. The system starts +// it at boot or login and starts it again when it stops, with no window +// and no desktop session, for a server or a machine reached over SSH. +// Whether it is installed and running is the system's own record, read +// each time, never a setting of magpie's. +package daemon + +import ( + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + + "github.com/yetone/magpie/internal/agentenv" + "github.com/yetone/magpie/internal/autostart" + "github.com/yetone/magpie/internal/edit" +) + +// Name is the service's name: magpie.service, com.yetone.magpie.serve. +const Name = "magpie" + +// Status is what the system says of the service. +type Status struct { + Installed bool // the unit or launch agent is on disk + Enabled bool // started at boot or login + Running bool // its process is up + PID int // that process, when the system says + State string // the system's own word for it: active, failed, running… + LastExit string // how its last run ended, when the system says + File string // the unit or launch agent's file + Logs string // how to read what it printed + Advice []string +} + +// manager is one system's way of running a service. +type manager interface { + file() string + logs() string + install(exe string, env []string) error + uninstall() error + start() error + stop() error + restart() error + status() (Status, error) +} + +// goos picks the manager; a var so that the tests run both on any unix. +var goos = runtime.GOOS + +// ErrUnsupported is for a system with no service manager magpie writes for. +var ErrUnsupported = errors.New("unsupported") + +func current() (manager, error) { + switch goos { + case "linux": + return systemd{}, nil + case "darwin": + return launchd{}, nil + case "windows": + return nil, fmt.Errorf("%w on Windows: `magpie autostart on` opens magpie, with its gateway, when you log in; or run `magpie daemon install` inside WSL", ErrUnsupported) + case "android": + return nil, fmt.Errorf("%w on Android: `magpie autostart on` starts the gateway at boot through Termux:Boot", ErrUnsupported) + } + return nil, fmt.Errorf("%w on %s: run `magpie serve` under the system's own service manager", ErrUnsupported, goos) +} + +// Install writes the service for this copy of magpie, with the +// environment it was installed from, and starts it; again, it writes the +// service anew (a moved magpie, a new PATH or proxy) and restarts it. +func Install() error { + m, err := current() + if err != nil { + return err + } + // the app opened at login serves the gateway too: the two would take + // turns failing on the port + if autostartEnabled() { + return errors.New("magpie already opens at login and serves the gateway: run `magpie autostart off` first, or keep that instead") + } + exe, err := self() + if err != nil { + return err + } + return m.install(exe, environ()) +} + +// Uninstall stops the service and removes it. One not installed is left +// as it is. +func Uninstall() error { return with(manager.uninstall) } + +// Start starts the installed service. +func Start() error { return installed(manager.start) } + +// Stop stops it, until the next boot or login, or Start. +func Stop() error { return installed(manager.stop) } + +// Restart stops it and starts it again: a magpie updated in place serves +// as the new version. +func Restart() error { return installed(manager.restart) } + +// Get is what the system says of the service. +func Get() (Status, error) { + m, err := current() + if err != nil { + return Status{}, err + } + st := Status{File: m.file(), Logs: m.logs()} + if _, err := os.Stat(st.File); err != nil { + return st, nil + } + got, err := m.status() + got.Installed, got.File, got.Logs = true, st.File, st.Logs + return got, err +} + +// ErrNotInstalled is Start, Stop or Restart before Install. +var ErrNotInstalled = errors.New("the magpie service isn't installed: `magpie daemon install`") + +func with(f func(manager) error) error { + m, err := current() + if err != nil { + return err + } + return f(m) +} + +func installed(f func(manager) error) error { + return with(func(m manager) error { + if _, err := os.Stat(m.file()); err != nil { + return ErrNotInstalled + } + return f(m) + }) +} + +// autostartEnabled is a var for the tests. +var autostartEnabled = autostart.Enabled + +// self is the program the service runs: this one, by the name on PATH +// when that is this same file, so a package manager's link (Homebrew's +// /opt/homebrew/bin/magpie) still leads to the version it updates to. A +// var for the tests, whose binary is a build Go deletes. +var self = func() (string, error) { + if p := os.Getenv("APPIMAGE"); p != "" { + return p, nil + } + exe, err := os.Executable() + if err != nil { + return "", err + } + real := exe + if p, err := filepath.EvalSymlinks(exe); err == nil { + real = p + } + return pick(real, exe) +} + +// pick is self past os.Executable: real is the running file, exe the +// name it was started by. +func pick(real, exe string) (string, error) { + if strings.Contains(real, "/AppTranslocation/") { + return "", errors.New("move magpie to Applications first, then install the service") + } + if strings.Contains(real, string(filepath.Separator)+"go-build") { + return "", errors.New("this magpie is a build `go run` deletes when it ends: install magpie, then run `magpie daemon install` from it") + } + if p, err := exec.LookPath(Name); err == nil { + if abs, err := filepath.Abs(p); err == nil { + if r, err := filepath.EvalSymlinks(abs); err == nil && sameFile(r, real) { + return abs, nil + } + } + } + if filepath.IsAbs(exe) && sameFile(exe, real) { + return exe, nil + } + return real, nil +} + +func sameFile(a, b string) bool { + x, err := os.Stat(a) + if err != nil { + return false + } + y, err := os.Stat(b) + return err == nil && os.SameFile(x, y) +} + +// carried are the variables the service gets from the shell it was +// installed from: the PATH that finds the agents' CLIs and bun, the proxy, +// magpie's own settings, and where each agent keeps its files. A service +// starts with the system's bare environment otherwise. +var carried = []string{ + "PATH", + "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", + "http_proxy", "https_proxy", "all_proxy", "no_proxy", + "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME", + "MAGPIE_ADDR", "MAGPIE_TRUST_PROXY", "MAGPIE_BUN", "MAGPIE_WEB_URL", +} + +// environ is carried's variables that are set, as KEY=value, in order. +func environ() []string { + var out []string + seen := map[string]bool{} + for _, k := range append(append([]string{}, carried...), agentenv.Vars...) { + if seen[k] { + continue + } + seen[k] = true + if v, ok := os.LookupEnv(k); ok && v != "" { + out = append(out, k+"="+v) + } + } + return out +} + +// run runs a service manager's tool, from PATH, and gives what it printed. +// A failure carries that text, which is what the user needs to read. +func run(name string, args ...string) (string, error) { + out, err := exec.Command(name, args...).CombinedOutput() + text := strings.TrimSpace(string(out)) + if err != nil { + if errors.Is(err, exec.ErrNotFound) { + return text, err + } + if text != "" { + return text, fmt.Errorf("%s %s: %s", name, strings.Join(args, " "), text) + } + return text, fmt.Errorf("%s %s: %w", name, strings.Join(args, " "), err) + } + return text, nil +} + +// private writes a service's file, readable by the user alone from its +// first byte: it holds the environment, and a proxy's can carry a +// password. +func private(path string, data []byte) error { + if _, err := os.Lstat(path); os.IsNotExist(err) { + if err := os.WriteFile(path, nil, 0o600); err != nil { + return err + } + } + if err := edit.WriteAtomic(path, data); err != nil { + return err + } + return os.Chmod(path, 0o600) +} diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go new file mode 100644 index 000000000..eca2213dd --- /dev/null +++ b/internal/daemon/daemon_test.go @@ -0,0 +1,380 @@ +package daemon + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" + + "github.com/yetone/magpie/internal/testenv" +) + +// The tests run in a home of their own, with a fake systemctl, launchctl +// and loginctl first on PATH: nothing is ever installed in the system. +func TestMain(m *testing.M) { testenv.Main(m) } + +// fakes puts a systemctl, launchctl and loginctl on PATH, alone, that log +// each call to the file it gives and answer from the files the test +// writes: .out is printed, and .fail, when there, makes the +// call fail with its text. A file named after the first argument, such as +// launchctl.print.fail, is for that call alone. +func fakes(t *testing.T, os_ string) (log, dir string) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("the fakes are shell scripts") + } + prev, prevSelf, prevAuto := goos, self, autostartEnabled + t.Cleanup(func() { goos, self, autostartEnabled = prev, prevSelf, prevAuto }) + goos = os_ + self = func() (string, error) { return "/opt/my magpie/magpie%1", nil } + autostartEnabled = func() bool { return false } + dir = t.TempDir() + // a home of the test's own: nothing one test installs is the next's + testenv.SetHome(t, filepath.Join(dir, "home")) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "home", ".config")) + bin := filepath.Join(dir, "bin") + log = filepath.Join(dir, "calls") + for _, name := range []string{"systemctl", "launchctl", "loginctl"} { + testenv.Program(t, filepath.Join(bin, name), `#!/bin/sh +d='`+dir+`' +echo "`+name+` $*" >> "$d/calls" +for f in "$d/`+name+`.$1" "$d/`+name+`.$2"; do + if [ -f "$f.fail" ]; then /bin/cat "$f.fail"; exit 1; fi + if [ -f "$f.out" ]; then /bin/cat "$f.out"; exit 0; fi +done +if [ -f "$d/`+name+`.fail" ]; then /bin/cat "$d/`+name+`.fail"; exit 1; fi +[ -f "$d/`+name+`.out" ] && /bin/cat "$d/`+name+`.out" +exit 0 +`) + } + t.Setenv("PATH", bin) + return log, dir +} + +func calls(t *testing.T, log string) []string { + t.Helper() + b, err := os.ReadFile(log) + if err != nil && !os.IsNotExist(err) { + t.Fatal(err) + } + return strings.Split(strings.TrimSpace(string(b)), "\n") +} + +func write(t *testing.T, path, text string) { + t.Helper() + if err := os.WriteFile(path, []byte(text), 0o644); err != nil { + t.Fatal(err) + } +} + +// On Linux, install writes a user unit that runs `magpie serve` with the +// shell's PATH, proxy and agents' folders, readable by the user alone, +// then enables and starts it through systemctl --user; uninstall stops, +// disables and removes it (HuanCheng on Discord). +func TestSystemdInstallAndUninstall(t *testing.T) { + log, _ := fakes(t, "linux") + t.Setenv("HTTPS_PROXY", "http://me:p%ss@proxy:8080") + t.Setenv("CODEX_HOME", "/srv/codex") + if err := Install(); err != nil { + t.Fatal(err) + } + file := filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "systemd", "user", "magpie.service") + b, err := os.ReadFile(file) + if err != nil { + t.Fatal(err) + } + unit := string(b) + for _, want := range []string{ + "ExecStart=\"/opt/my magpie/magpie%%1\" serve\n", + "Restart=on-failure\n", + "Environment=\"PATH=" + os.Getenv("PATH") + "\"\n", + "Environment=\"HTTPS_PROXY=http://me:p%%ss@proxy:8080\"\n", + "Environment=\"CODEX_HOME=/srv/codex\"\n", + "WantedBy=default.target\n", + } { + if !strings.Contains(unit, want) { + t.Errorf("the unit has no %q:\n%s", want, unit) + } + } + if st, _ := os.Stat(file); st.Mode().Perm() != 0o600 { + t.Errorf("the unit, which holds the proxy's password, is %v", st.Mode().Perm()) + } + // one left readable by others, written over, is the user's alone too + os.Chmod(file, 0o644) + if err := Install(); err != nil { + t.Fatal(err) + } + if st, _ := os.Stat(file); st.Mode().Perm() != 0o600 { + t.Errorf("the unit written again is %v", st.Mode().Perm()) + } + os.Remove(log) + if err := Install(); err != nil { + t.Fatal(err) + } + got := strings.Join(calls(t, log), "\n") + want := "systemctl --user is-system-running\nsystemctl --user daemon-reload\nsystemctl --user enable magpie.service\nsystemctl --user restart magpie.service" + if got != want { + t.Errorf("install ran\n%s\nwant\n%s", got, want) + } + + os.Remove(log) + if err := Uninstall(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(file); !os.IsNotExist(err) { + t.Errorf("the unit is still there: %v", err) + } + got = strings.Join(calls(t, log), "\n") + want = "systemctl --user is-system-running\nsystemctl --user disable --now magpie.service\nsystemctl --user daemon-reload" + if got != want { + t.Errorf("uninstall ran\n%s\nwant\n%s", got, want) + } + // none left: nothing to do, and no failure + os.Remove(log) + if err := Uninstall(); err != nil { + t.Fatal(err) + } + if c := calls(t, log); c[0] != "" { + t.Errorf("uninstall with none installed ran %v", c) + } +} + +// Start, stop and restart before an install say to install, and run +// nothing. +func TestNotInstalled(t *testing.T) { + for _, os_ := range []string{"linux", "darwin"} { + t.Run(os_, func(t *testing.T) { + log, _ := fakes(t, os_) + for _, f := range []func() error{Start, Stop, Restart} { + if err := f(); !errors.Is(err, ErrNotInstalled) { + t.Errorf("got %v, want ErrNotInstalled", err) + } + } + if c := calls(t, log); c[0] != "" { + t.Errorf("ran %v", c) + } + st, err := Get() + if err != nil || st.Installed { + t.Errorf("status %+v, %v", st, err) + } + }) + } +} + +// Status reads systemctl show; a user who doesn't linger is told the +// service stops at logout and how to keep it from boot. +func TestSystemdStatus(t *testing.T) { + _, dir := fakes(t, "linux") + if err := Install(); err != nil { + t.Fatal(err) + } + write(t, filepath.Join(dir, "systemctl.show.out"), "ActiveState=active\nSubState=running\nMainPID=4242\nUnitFileState=enabled\nExecMainStatus=0\n") + write(t, filepath.Join(dir, "loginctl.out"), "no\n") + st, err := Get() + if err != nil { + t.Fatal(err) + } + if !st.Installed || !st.Enabled || !st.Running || st.PID != 4242 || st.State != "active (running)" || st.LastExit != "" { + t.Errorf("status %+v", st) + } + if len(st.Advice) != 1 || !strings.Contains(st.Advice[0], "sudo loginctl enable-linger ") { + t.Errorf("advice %q, want enable-linger", st.Advice) + } + if !strings.HasPrefix(st.Logs, "journalctl --user -u magpie") { + t.Errorf("logs %q", st.Logs) + } + // stopped by hand: SIGTERM's 15 is no failure to show + write(t, filepath.Join(dir, "systemctl.show.out"), "ActiveState=inactive\nSubState=dead\nMainPID=0\nUnitFileState=enabled\nExecMainStatus=15\n") + if st, _ = Get(); st.Running || st.LastExit != "" || st.State != "inactive (dead)" { + t.Errorf("a stopped service's status %+v", st) + } + write(t, filepath.Join(dir, "systemctl.show.out"), "ActiveState=activating\nSubState=auto-restart\nMainPID=0\nUnitFileState=enabled\nExecMainStatus=1\n") + write(t, filepath.Join(dir, "loginctl.out"), "yes\n") + st, _ = Get() + if st.Running || st.PID != 0 || st.LastExit != "1" || len(st.Advice) != 0 { + t.Errorf("a failing service's status %+v", st) + } +} + +// A shell without the user's bus (su, sudo) or with no systemd says +// what to do instead, and writes nothing. +func TestSystemdUnreachable(t *testing.T) { + _, dir := fakes(t, "linux") + write(t, filepath.Join(dir, "systemctl.fail"), "Failed to connect to bus: No medium found") + err := Install() + if err == nil || !strings.Contains(err.Error(), "XDG_RUNTIME_DIR") { + t.Errorf("got %v, want the bus advice", err) + } + if _, err := os.Stat(systemd{}.file()); !os.IsNotExist(err) { + t.Errorf("a unit was written: %v", err) + } + t.Setenv("PATH", t.TempDir()) + if err := Install(); err == nil || !strings.Contains(err.Error(), "no systemd") { + t.Errorf("got %v, want no systemd", err) + } +} + +// The app opened at login serves the gateway too: an install beside it is +// refused before anything is written. +func TestRefusedBesideAutostart(t *testing.T) { + for _, os_ := range []string{"linux", "darwin"} { + t.Run(os_, func(t *testing.T) { + log, _ := fakes(t, os_) + autostartEnabled = func() bool { return true } + if err := Install(); err == nil || !strings.Contains(err.Error(), "magpie autostart off") { + t.Errorf("got %v", err) + } + if c := calls(t, log); c[0] != "" { + t.Errorf("ran %v", c) + } + }) + } +} + +// On the Mac, install writes a launch agent that runs `magpie serve` at +// login and again when it fails, and loads it; an install over one loaded +// takes the old one out first. +func TestLaunchdInstall(t *testing.T) { + log, dir := fakes(t, "darwin") + t.Setenv("HTTP_PROXY", "http://a&b@proxy") + // not loaded yet + write(t, filepath.Join(dir, "launchctl.print.fail"), "Could not find service") + if err := Install(); err != nil { + t.Fatal(err) + } + file := filepath.Join(os.Getenv("HOME"), "Library", "LaunchAgents", "com.yetone.magpie.serve.plist") + b, err := os.ReadFile(file) + if err != nil { + t.Fatal(err) + } + p := string(b) + for _, want := range []string{ + "Labelcom.yetone.magpie.serve", + "/opt/my magpie/magpie%1serve", + "SuccessfulExit", + "HTTP_PROXYhttp://a&b<c>@proxy", + "PATH" + os.Getenv("PATH") + "", + } { + if !strings.Contains(p, want) { + t.Errorf("the plist has no %q:\n%s", want, p) + } + } + if lint := "/usr/bin/plutil"; runtime.GOOS == "darwin" { + if out, err := exec.Command(lint, "-lint", file).CombinedOutput(); err != nil { + t.Errorf("plutil: %s", out) + } + } + if st, _ := os.Stat(file); st.Mode().Perm() != 0o600 { + t.Errorf("the plist is %v", st.Mode().Perm()) + } + uid := strconv.Itoa(os.Getuid()) + got := strings.Join(calls(t, log), "\n") + want := "launchctl print gui/" + uid + "/com.yetone.magpie.serve\nlaunchctl bootstrap gui/" + uid + " " + file + if got != want { + t.Errorf("install ran\n%s\nwant\n%s", got, want) + } + + // loaded: install again takes it out first; restart kills and starts + os.Remove(filepath.Join(dir, "launchctl.print.fail")) + write(t, filepath.Join(dir, "launchctl.print.out"), "gui/501/com.yetone.magpie.serve = {\n\tactive count = 1\n\tstate = running\n\tprogram = /opt/magpie\n\tpid = 777\n\tlast exit code = (never exited)\n\tendpoints = {\n\t\tstate = active\n\t}\n}\n") + os.Remove(log) + if err := Install(); err != nil { + t.Fatal(err) + } + if err := Restart(); err != nil { + t.Fatal(err) + } + got = strings.Join(calls(t, log), "\n") + svc := "gui/" + uid + "/com.yetone.magpie.serve" + want = "launchctl print " + svc + "\nlaunchctl bootout " + svc + "\nlaunchctl bootstrap gui/" + uid + " " + file + "\nlaunchctl print " + svc + "\nlaunchctl kickstart -k " + svc + if got != want { + t.Errorf("reinstall and restart ran\n%s\nwant\n%s", got, want) + } + st, err := Get() + if err != nil || !st.Running || st.PID != 777 || st.State != "running" || st.LastExit != "" { + t.Errorf("status %+v, %v", st, err) + } + if !strings.Contains(st.Logs, filepath.Join("Library", "Logs", "magpie", "serve.log")) { + t.Errorf("logs %q", st.Logs) + } + + os.Remove(log) + if err := Uninstall(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(file); !os.IsNotExist(err) { + t.Errorf("the plist is still there: %v", err) + } + if got := strings.Join(calls(t, log), "\n"); got != "launchctl print "+svc+"\nlaunchctl bootout "+svc { + t.Errorf("uninstall ran\n%s", got) + } +} + +// Windows and Android have no service of this kind: the error points to +// what they have. +func TestUnsupported(t *testing.T) { + prev := goos + t.Cleanup(func() { goos = prev }) + for os_, want := range map[string]string{"windows": "magpie autostart on", "android": "Termux:Boot"} { + goos = os_ + if err := Install(); !errors.Is(err, ErrUnsupported) || !strings.Contains(err.Error(), want) { + t.Errorf("%s: %v", os_, err) + } + } +} + +// The service runs magpie by the name on PATH when that is this same file +// (a package manager's link survives an update), never a build `go run` +// deletes, nor a copy macOS runs from a random place. +func TestPick(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("links") + } + dir := t.TempDir() + real := filepath.Join(dir, "Cellar", "magpie", "1.0", "magpie") + os.MkdirAll(filepath.Dir(real), 0o755) + write(t, real, "x") + os.Chmod(real, 0o755) + bin := filepath.Join(dir, "bin") + os.MkdirAll(bin, 0o755) + if err := os.Symlink(real, filepath.Join(bin, "magpie")); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", bin) + if got, err := pick(real, real); err != nil || got != filepath.Join(bin, "magpie") { + t.Errorf("got %q, %v; want the link on PATH", got, err) + } + // another magpie on PATH: this one + other := filepath.Join(dir, "other") + write(t, other, "y") + t.Setenv("PATH", t.TempDir()) + if got, _ := pick(other, other); got != other { + t.Errorf("got %q", got) + } + for _, p := range []string{ + filepath.Join(os.TempDir(), "go-build123", "b001", "exe", "magpie"), + "/private/var/folders/x/T/AppTranslocation/ABC/d/magpie.app/Contents/MacOS/magpie", + } { + if _, err := pick(p, p); err == nil { + t.Errorf("%s was taken", p) + } + } +} + +// The environment carried is the set variables of the list, once each. +func TestEnviron(t *testing.T) { + t.Setenv("PATH", "/a:/b") + t.Setenv("no_proxy", "localhost") + t.Setenv("MAGPIE_ADDR", "") + got := strings.Join(environ(), "\n") + if !strings.Contains(got, "PATH=/a:/b") || !strings.Contains(got, "no_proxy=localhost") || strings.Contains(got, "MAGPIE_ADDR") { + t.Errorf("environ:\n%s", got) + } + if strings.Count(got, "PATH=/a:/b") != 1 { + t.Errorf("PATH twice:\n%s", got) + } +} diff --git a/internal/daemon/launchd.go b/internal/daemon/launchd.go new file mode 100644 index 000000000..b25f7142e --- /dev/null +++ b/internal/daemon/launchd.go @@ -0,0 +1,166 @@ +package daemon + +import ( + "html" + "os" + "path/filepath" + "strconv" + "strings" +) + +// launchd runs the service as a launch agent of the user's: started at +// login, and again when it stops with a failure. +type launchd struct{} + +// Label is the launch agent's; the tray's at login is com.yetone.magpie. +const Label = "com.yetone.magpie.serve" + +func home() string { + h, _ := os.UserHomeDir() + return h +} + +func (launchd) file() string { + return filepath.Join(home(), "Library", "LaunchAgents", Label+".plist") +} + +func logFile() string { return filepath.Join(home(), "Library", "Logs", "magpie", "serve.log") } + +func (launchd) logs() string { return "tail -f " + strconv.Quote(logFile()) } + +func domain() string { return "gui/" + strconv.Itoa(os.Getuid()) } +func service() string { return domain() + "/" + Label } + +// plist is the launch agent for exe, with env set in it. +func plist(exe string, env []string) string { + s := func(v string) string { return "" + html.EscapeString(v) + "" } + var b strings.Builder + b.WriteString(` + + + + + Label` + s(Label) + ` + ProgramArguments + ` + s(exe) + s("serve") + ` + RunAtLoad + KeepAlive + SuccessfulExit + ThrottleInterval5 + ProcessTypeBackground + StandardOutPath` + s(logFile()) + ` + StandardErrorPath` + s(logFile()) + ` +`) + if len(env) > 0 { + b.WriteString("\tEnvironmentVariables\n\t\n") + for _, kv := range env { + k, v, _ := strings.Cut(kv, "=") + b.WriteString("\t\t" + html.EscapeString(k) + "" + s(v) + "\n") + } + b.WriteString("\t\n") + } + b.WriteString("\n\n") + return b.String() +} + +func (l launchd) install(exe string, env []string) error { + if err := os.MkdirAll(filepath.Dir(l.file()), 0o755); err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(logFile()), 0o755); err != nil { + return err + } + if err := private(l.file(), []byte(plist(exe, env))); err != nil { + return err + } + // one loaded before runs the old plist until it is taken out + l.unload() + _, err := launchctl("bootstrap", domain(), l.file()) + return err +} + +func (l launchd) uninstall() error { + if _, err := os.Stat(l.file()); err != nil { + return nil + } + l.unload() + if err := os.Remove(l.file()); err != nil && !os.IsNotExist(err) { + return err + } + return nil +} + +// loaded reports whether launchd has the agent, running or not. +func (launchd) loaded() bool { + _, err := launchctl("print", service()) + return err == nil +} + +// unload takes the agent out of launchd, stopping it; one not loaded is +// no failure. +func (l launchd) unload() { + if l.loaded() { + launchctl("bootout", service()) + } +} + +func (l launchd) start() error { + if !l.loaded() { + _, err := launchctl("bootstrap", domain(), l.file()) + return err + } + _, err := launchctl("kickstart", service()) + return err +} + +// stop takes it out of launchd: stopped alone, KeepAlive would have it +// back. The next login, or start, loads it again. +func (l launchd) stop() error { + if !l.loaded() { + return nil + } + _, err := launchctl("bootout", service()) + return err +} + +func (l launchd) restart() error { + if !l.loaded() { + return l.start() + } + _, err := launchctl("kickstart", "-k", service()) + return err +} + +func (l launchd) status() (Status, error) { + // a plist in LaunchAgents is loaded at every login + st := Status{Enabled: true} + out, err := launchctl("print", service()) + if err != nil { + st.State = "not loaded" + return st, nil + } + for _, line := range strings.Split(out, "\n") { + k, v, ok := strings.Cut(strings.TrimSpace(line), " = ") + if !ok { + continue + } + switch k { + case "state": + if st.State == "" { + st.State = v + } + case "pid": + if n, err := strconv.Atoi(v); err == nil && n > 0 { + st.PID = n + } + case "last exit code": + if v != "0" && !strings.HasPrefix(v, "(never") { + st.LastExit = v + } + } + } + st.Running = st.State == "running" + return st, nil +} + +func launchctl(args ...string) (string, error) { return run("launchctl", args...) } diff --git a/internal/daemon/systemd.go b/internal/daemon/systemd.go new file mode 100644 index 000000000..aadddaefc --- /dev/null +++ b/internal/daemon/systemd.go @@ -0,0 +1,187 @@ +package daemon + +import ( + "errors" + "fmt" + "os" + "os/exec" + "os/user" + "path/filepath" + "strconv" + "strings" +) + +// systemd runs the service as a user unit: systemctl --user, no root. +type systemd struct{} + +const unit = Name + ".service" + +func (systemd) file() string { + dir := os.Getenv("XDG_CONFIG_HOME") + if dir == "" { + home, _ := os.UserHomeDir() + dir = filepath.Join(home, ".config") + } + return filepath.Join(dir, "systemd", "user", unit) +} + +func (systemd) logs() string { return "journalctl --user -u " + Name + " -f" } + +// unitText is the unit for exe, with env set in it. +func unitText(exe string, env []string) string { + var b strings.Builder + b.WriteString("# Written by `magpie daemon install`; `magpie daemon uninstall` removes it.\n") + b.WriteString("[Unit]\nDescription=magpie gateway\nWants=network-online.target\nAfter=network-online.target\n\n") + b.WriteString("[Service]\nType=simple\n") + b.WriteString("ExecStart=" + unitQuote(exe) + " serve\n") + b.WriteString("Restart=on-failure\nRestartSec=5\n") + for _, kv := range env { + b.WriteString("Environment=" + unitQuote(kv) + "\n") + } + b.WriteString("\n[Install]\nWantedBy=default.target\n") + return b.String() +} + +// unitQuote quotes s as one word of a unit file: systemd reads \ and " +// escaped inside quotes, and % as the start of a specifier. +func unitQuote(s string) string { + s = strings.NewReplacer(`\`, `\\`, `"`, `\"`, "%", "%%", "\n", " ").Replace(s) + return `"` + s + `"` +} + +func (s systemd) install(exe string, env []string) error { + if err := s.reachable(); err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(s.file()), 0o755); err != nil { + return err + } + if err := private(s.file(), []byte(unitText(exe, env))); err != nil { + return err + } + if _, err := systemctl("daemon-reload"); err != nil { + return err + } + if _, err := systemctl("enable", unit); err != nil { + return err + } + // restart, not start: an install over one running takes the new unit + _, err := systemctl("restart", unit) + return err +} + +func (s systemd) uninstall() error { + if _, err := os.Stat(s.file()); err != nil { + return nil + } + if err := s.reachable(); err != nil { + return err + } + if _, err := systemctl("disable", "--now", unit); err != nil { + return err + } + if err := os.Remove(s.file()); err != nil && !os.IsNotExist(err) { + return err + } + _, err := systemctl("daemon-reload") + return err +} + +func (systemd) start() error { _, err := systemctl("start", unit); return err } +func (systemd) stop() error { _, err := systemctl("stop", unit); return err } +func (systemd) restart() error { _, err := systemctl("restart", unit); return err } + +func (s systemd) status() (Status, error) { + if err := s.reachable(); err != nil { + return Status{}, err + } + out, err := systemctl("show", unit, "--property=ActiveState,SubState,MainPID,UnitFileState,ExecMainStatus") + if err != nil { + return Status{}, err + } + v := map[string]string{} + for _, line := range strings.Split(out, "\n") { + if k, val, ok := strings.Cut(strings.TrimSpace(line), "="); ok { + v[k] = val + } + } + st := Status{ + Enabled: v["UnitFileState"] == "enabled", + Running: v["ActiveState"] == "active", + State: v["ActiveState"], + } + if sub := v["SubState"]; sub != "" && sub != st.State { + st.State += " (" + sub + ")" + } + if pid, err := strconv.Atoi(v["MainPID"]); err == nil && pid > 0 { + st.PID = pid + } + // a stop ends it with SIGTERM's 15: only a run that failed is news + failing := st.State != "" && (v["ActiveState"] == "failed" || v["ActiveState"] == "activating") + if code := v["ExecMainStatus"]; failing && code != "" && code != "0" { + st.LastExit = code + } + if a := lingerAdvice(); a != "" { + st.Advice = append(st.Advice, a) + } + return st, nil +} + +// reachable says what to do when systemctl --user can't be used: no +// systemd, or a session without the user's bus (su, sudo, some SSH). +func (systemd) reachable() error { + _, err := systemctl("is-system-running") + if err == nil { + return nil + } + if errors.Is(err, exec.ErrNotFound) { + advice := "this system has no systemd (systemctl isn't on PATH): run `magpie serve` under the service manager it has" + if wsl() { + advice += "; on WSL, turn systemd on with [boot] systemd=true in /etc/wsl.conf, then `wsl --shutdown`" + } + return errors.New(advice) + } + msg := err.Error() + if strings.Contains(msg, "bus") || strings.Contains(msg, "XDG_RUNTIME_DIR") { + return fmt.Errorf("systemctl --user can't reach your session's service manager: log in as this user directly (not through su or sudo), or set XDG_RUNTIME_DIR=/run/user/%d (%s)", os.Getuid(), msg) + } + // is-system-running exits non-zero for "degraded" too, which still + // runs user units + return nil +} + +func wsl() bool { + b, _ := os.ReadFile("/proc/version") + return strings.Contains(strings.ToLower(string(b)), "microsoft") +} + +// lingerAdvice is what to run so the service starts at boot and keeps +// running after logging out, when it doesn't: systemd starts a user's +// units with their first login and stops them with their last, unless the +// user lingers. Empty when it does, or when loginctl can't tell. +func lingerAdvice() string { + name := os.Getenv("USER") + if u, err := user.Current(); err == nil && u.Username != "" { + name = u.Username + } + if name == "" { + return "" + } + out, err := run("loginctl", "show-user", name, "--property=Linger", "--value") + if err != nil || strings.TrimSpace(out) != "no" { + return "" + } + return "it starts when you log in and stops when you log out; to run it from boot, with no one logged in: sudo loginctl enable-linger " + name +} + +// Linger is lingerAdvice, for after an install. +func Linger() string { + if goos != "linux" { + return "" + } + return lingerAdvice() +} + +func systemctl(args ...string) (string, error) { + return run("systemctl", append([]string{"--user"}, args...)...) +} diff --git a/site/public/docs/ja/start.html b/site/public/docs/ja/start.html index dcedd2ba6..e10a87c06 100644 --- a/site/public/docs/ja/start.html +++ b/site/public/docs/ja/start.html @@ -266,7 +266,7 @@ magpie claude group/opus-anywhere # これを使う

OPENAI_BASE_URL や ANTHROPIC_BASE_URL を export する必要はありますか?

いいえ。magpie が一覧に表示するエージェントについては、ゲートウェイのアドレスとトークンをエージェント自身の設定ファイルに書き込みます。これらの変数は、ベース URL を設定できる他のツール向けです。Gateway タブの Connect セクションに、コピーボタンとスニペットとして用意されています。

magpie は起動しておく必要がありますか?

-

magpie 経由のモデルを使うなら必要です。ゲートウェイはアプリと一緒に動きます。ウィンドウを閉じてもメニューバーやトレイで動き続けます。magpie tray はアイコンだけで起動し(ログイン項目に入れておくと便利です)、magpie serve はゲートウェイだけを動かします。エージェント自身のモデルと自身のサインインで動くエージェントは、magpie を通りません。

+

magpie 経由のモデルを使うなら必要です。ゲートウェイはアプリと一緒に動きます。ウィンドウを閉じてもメニューバーやトレイで動き続けます。magpie tray はアイコンだけで起動し(ログイン項目に入れておくと便利です)、magpie serve はゲートウェイだけを動かし、magpie daemon install はそれをサービス(Linux は systemd、Mac は launchd)として登録し、ログインや起動時からウィンドウなしで動かし続けます。エージェント自身のモデルと自身のサインインで動くエージェントは、magpie を通りません。

エージェントを元の状態に戻すには?

ピッカーでエージェント自身のモデルを選ぶか、magpie <agent> default を実行します。magpie は自分が書き込んだものを取り除き、以前に設定していた ANTHROPIC_BASE_URL など、置き換えた値を元に戻します。

モデルを切り替えたのに、エージェントが古いモデルを使い続けます。

diff --git a/site/public/docs/start.html b/site/public/docs/start.html index 7f8def4b2..47f622cd7 100644 --- a/site/public/docs/start.html +++ b/site/public/docs/start.html @@ -266,7 +266,7 @@ magpie claude group/opus-anywhere # use it

Do I need to export OPENAI_BASE_URL or ANTHROPIC_BASE_URL?

No. For the agents magpie lists, it writes the gateway’s address and token into the agent’s own config file. Those variables are only for other tools with a base-URL setting: the Gateway tab’s Connect section has them as copy buttons and snippets.

Does magpie have to be running?

-

For a model through magpie, yes: the gateway runs with the app. Closing the window leaves it running in the menu bar or tray; magpie tray starts the icon alone (put it in your login items), and magpie serve runs just the gateway. An agent on its own model and its own sign-in doesn’t go through magpie.

+

For a model through magpie, yes: the gateway runs with the app. Closing the window leaves it running in the menu bar or tray; magpie tray starts the icon alone (put it in your login items), and magpie serve runs just the gateway, and magpie daemon install keeps it running as a service (systemd on Linux, launchd on the Mac), from login or boot, with no window. An agent on its own model and its own sign-in doesn’t go through magpie.

How do I put an agent back the way it was?

Pick one of the agent’s own models in the picker, or run magpie <agent> default. magpie removes what it wrote and restores the values it replaced, such as an ANTHROPIC_BASE_URL you had before.

I switched models, but my agent still uses the old one.

diff --git a/site/public/docs/zh/start.html b/site/public/docs/zh/start.html index efe767b00..171cdbe63 100644 --- a/site/public/docs/zh/start.html +++ b/site/public/docs/zh/start.html @@ -266,7 +266,7 @@ magpie claude group/opus-anywhere # 使用它

需要自己 export OPENAI_BASE_URL 或 ANTHROPIC_BASE_URL 吗?

不需要。对 magpie 列出的 Agent,它会把网关地址和令牌直接写进 Agent 自己的配置文件。这些环境变量只用于 magpie 不管理的、带 base URL 设置的其他工具:网关 标签页的 接入 部分有一键复制和示例代码。

magpie 必须一直开着吗?

-

通过 magpie 使用的模型需要:网关随应用一起运行。关掉窗口后它仍留在菜单栏或托盘里;magpie tray 只启动图标(可以放进登录项),magpie serve 只运行网关。Agent 用它自己的模型和自己的登录时,不经过 magpie。

+

通过 magpie 使用的模型需要:网关随应用一起运行。关掉窗口后它仍留在菜单栏或托盘里;magpie tray 只启动图标(可以放进登录项),magpie serve 只运行网关,magpie daemon install 把它装成服务(Linux 上是 systemd,Mac 上是 launchd),登录或开机就启动,不需要窗口。Agent 用它自己的模型和自己的登录时,不经过 magpie。

怎么把 Agent 恢复原样?

在选择列表里选 Agent 自带的模型,或运行 magpie <agent> default。magpie 会删掉它写入的内容,并恢复被它替换掉的值,比如你原来的 ANTHROPIC_BASE_URL。

换了模型,Agent 还在用旧的?