daemon: magpie daemon install --web serves the browser page from the service, with a link that lasts (HuanCheng Bai)
HuanCheng Bai on Discord runs `magpie daemon` on a Linux server and asked
for the daemon to serve the web page too, or for an option to turn it on.
`magpie web` run beside it is a second process, and he read it as not
seeing the daemon's state.
- `magpie serve --web[=host:port]` serves the gateway and `magpie web`'s
page from one process (stats, StartWeb, Wait). The default page address
is 127.0.0.1:3430. Any other argument is refused, where before it was
ignored.
- `magpie daemon install --web | --lan | --addr host:port | --no-web` and
`magpie daemon web [on|off] [--lan] [--addr host:port]`. The unit's
ExecStart and the plist's ProgramArguments become `serve --web=<addr>`,
and the key goes into the 0600 file's environment as MAGPIE_WEB_KEY. The
key is made once. A reinstall with no flags keeps the page and its key
(read back from the file by daemon.Web), so the link survives restarts
and reinstalls. `web off` drops it. MAGPIE_WEB_KEY in the shell, when
set, is used and checked like magpie web's. The page defaults to
loopback; --lan or a non-loopback --addr prints the network links and
magpie web --lan's warning.
- `magpie daemon status`, install and `daemon web` print the page's link.
- `magpie web` while the service serves a page prints that page's link and
exits. Beside a gateway another magpie serves, it says so and points to
`magpie daemon web on`.
- docs/reference.md (the service section and the Use list), and the
site's start page (en, zh, ja). The READMEs don't cover the daemon.
Run:
- Tests: TestInstallWithWeb (systemd and launchd, plutil lint, read back,
reinstall without the page, the shell's key not carried, no key
refused), TestWebNotInstalled, TestParseDaemon, TestWebOptions,
TestDaemonStatusPrintsPage and TestServeArgs. Each of these went red
with its line reverted by hand: withKey, prevKey in webOptions, and the
status page line.
- Sandbox HOME with a fake launchctl:
- `daemon install --web --lan` wrote a 0600 plist with
`serve --web=0.0.0.0:3430` and the key. plutil said OK, and it printed
the link, the network links and the warning.
- Reinstalling with no flags kept the key. `daemon status` showed the
link.
- `daemon web off` / `daemon web` / `daemon web on` behaved as above,
with a new key after off.
- `daemon web bogus` and `serve --lan` gave the usage errors.
- `serve --web=127.0.0.1:3462` served the gateway (3461) and the page in
one process. The page answered 200 with the key and 401 without, and the
page and /v1/models both showed 3 models. `magpie web --no-open` beside
it printed the service's link and exited 0.
- gofmt -l; go vet (gui), and go vet -tags nogui for darwin, linux and
windows; go test -tags nogui ./... in a sandbox HOME.
Not tried: a real systemd on Linux. The unit text is checked by test only.
This commit is contained in:
@@ -1930,8 +1930,28 @@ magpie daemon status # running or not, its pid, file and logs, whether the g
|
||||
magpie daemon restart # after updating magpie
|
||||
magpie daemon stop|start
|
||||
magpie daemon uninstall # stop it and remove the file
|
||||
magpie daemon web on # the service serves the browser page too; off stops it, no word shows it
|
||||
```
|
||||
|
||||
The service serves only the gateway unless asked for the page:
|
||||
`magpie daemon install --web` (or `magpie daemon web on` once installed)
|
||||
runs `magpie serve --web`, which serves the gateway and `magpie web`'s
|
||||
page from one process, so the page shows the service's own gateway,
|
||||
providers and accounts. It listens on `127.0.0.1:3430`; `--lan` puts it on
|
||||
`0.0.0.0:3430` and `--addr host:port` anywhere, with the same warning as
|
||||
`magpie web --lan`: anyone with the link can change your settings. Its key
|
||||
is made once and kept in the service file (as `MAGPIE_WEB_KEY`, readable by
|
||||
you alone), so the link stays the same across restarts and reinstalls;
|
||||
`daemon web off` drops it, and the next `on` makes a new one.
|
||||
`magpie daemon status` prints the link. `--no-web` installs without it.
|
||||
|
||||
`magpie web` beside a running service doesn't take the gateway's port:
|
||||
when the service serves the page it prints that page's link and exits, and
|
||||
otherwise its own page uses the service's gateway and says so. A magpie
|
||||
holding the port but slow to answer (a busy server, or one still starting)
|
||||
is waited for, not raced: the new one serves the gateway only once the
|
||||
port is free.
|
||||
|
||||
- **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
|
||||
@@ -2116,6 +2136,8 @@ magpie tui # the same thing, in the terminal; serves the ga
|
||||
magpie web # the app's window in a browser (WSL, a server over SSH); --lan, --addr, --no-open, --gateway
|
||||
# (a new key each run; MAGPIE_WEB_KEY keeps one, for a page run as a service)
|
||||
# (behind a reverse proxy, MAGPIE_WEB_URL=https://<the page there> prints the link through it)
|
||||
magpie serve # the gateway alone, no window; --web[=host:port] serves the page too, from the same process
|
||||
magpie daemon install # run magpie serve as a service (systemd, launchd); --web, --lan, --addr serve the page too
|
||||
magpie ls # list every agent and its current settings
|
||||
magpie claude opus # set a model (agent names accept prefixes: cc, oc, gem …)
|
||||
magpie codex gpt-5.6-sol
|
||||
|
||||
+172
-10
@@ -3,35 +3,144 @@ package cli
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/daemon"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/gui"
|
||||
)
|
||||
|
||||
const daemonUsage = "usage: magpie daemon [install|uninstall|start|stop|restart|status]"
|
||||
const daemonUsage = "usage: magpie daemon [install|uninstall|start|stop|restart|status] · magpie daemon install [--web] [--lan] [--addr host:port] [--no-web] · magpie daemon web [on|off] [--lan] [--addr host:port]"
|
||||
|
||||
// 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
|
||||
|
||||
// daemonWeb is what a daemon command says of the page the service serves
|
||||
// beside the gateway (`magpie serve --web`, HuanCheng on Discord).
|
||||
type daemonWeb struct {
|
||||
set bool // the command says whether it is served; not set, it stays as it is
|
||||
on bool // served
|
||||
addr string // where, "" for the default
|
||||
}
|
||||
|
||||
// parseDaemon reads magpie daemon's arguments: the command, and what it
|
||||
// says of the page.
|
||||
func parseDaemon(args []string) (cmd string, w daemonWeb, err error) {
|
||||
cmd = "status"
|
||||
if len(args) > 0 {
|
||||
cmd, args = args[0], args[1:]
|
||||
}
|
||||
if cmd == "web" && len(args) > 0 && !strings.HasPrefix(args[0], "-") {
|
||||
switch args[0] {
|
||||
case "on":
|
||||
w.set, w.on = true, true
|
||||
case "off":
|
||||
w.set = true
|
||||
case "status":
|
||||
default:
|
||||
return "", w, errors.New(daemonUsage)
|
||||
}
|
||||
args = args[1:]
|
||||
}
|
||||
if len(args) > 0 && cmd != "install" && cmd != "web" {
|
||||
return "", w, errors.New(daemonUsage)
|
||||
}
|
||||
lan, off := false, false
|
||||
for i := 0; i < len(args); i++ {
|
||||
switch a := args[i]; {
|
||||
case a == "--web" && cmd == "install":
|
||||
w.set, w.on = true, true
|
||||
case a == "--no-web" && cmd == "install":
|
||||
off = true
|
||||
case a == "--lan":
|
||||
lan = true
|
||||
case a == "--addr" && i+1 < len(args):
|
||||
i++
|
||||
w.addr = args[i]
|
||||
case strings.HasPrefix(a, "--addr="):
|
||||
w.addr = strings.TrimPrefix(a, "--addr=")
|
||||
default:
|
||||
return "", w, fmt.Errorf("magpie daemon %s: unknown %q · %s", cmd, a, daemonUsage)
|
||||
}
|
||||
}
|
||||
if w.addr != "" {
|
||||
if _, _, err := net.SplitHostPort(w.addr); err != nil {
|
||||
return "", w, fmt.Errorf("magpie daemon %s: --addr %s isn't host:port", cmd, w.addr)
|
||||
}
|
||||
}
|
||||
// --lan and --addr say where the page is: it is served
|
||||
if lan || w.addr != "" {
|
||||
if cmd == "web" && w.set && !w.on || off {
|
||||
return "", w, fmt.Errorf("magpie daemon %s: --lan and --addr are for a page that is served", cmd)
|
||||
}
|
||||
w.set, w.on = true, true
|
||||
}
|
||||
if off {
|
||||
if w.on {
|
||||
return "", w, errors.New("magpie daemon install: --web and --no-web both")
|
||||
}
|
||||
w.set = true
|
||||
}
|
||||
if w.on && w.addr == "" {
|
||||
w.addr = webAddr
|
||||
if lan {
|
||||
_, port, _ := net.SplitHostPort(webAddr)
|
||||
w.addr = "0.0.0.0:" + port
|
||||
}
|
||||
}
|
||||
return cmd, w, nil
|
||||
}
|
||||
|
||||
// webOptions is what the service is to serve: what w asks, or what it
|
||||
// serves now (prevAddr, prevKey) when w says nothing. The page keeps its
|
||||
// key across installs, so a browser stays signed in: MAGPIE_WEB_KEY
|
||||
// (envKey) when set, else the key the service has, else a new one.
|
||||
func webOptions(w daemonWeb, prevAddr, prevKey, envKey string) (daemon.Options, error) {
|
||||
if !w.set {
|
||||
return daemon.Options{Web: prevAddr, Key: prevKey}, nil
|
||||
}
|
||||
if !w.on {
|
||||
return daemon.Options{}, nil
|
||||
}
|
||||
key := envKey
|
||||
if key == "" {
|
||||
key = prevKey
|
||||
}
|
||||
if key == "" {
|
||||
key = gui.NewWebKey()
|
||||
}
|
||||
if err := gui.CheckWebKey(key); err != nil {
|
||||
return daemon.Options{}, err
|
||||
}
|
||||
return daemon.Options{Web: w.addr, Key: key}, nil
|
||||
}
|
||||
|
||||
// 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, web, err := parseDaemon(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := "status"
|
||||
if len(args) == 1 {
|
||||
cmd = args[0]
|
||||
}
|
||||
var err error
|
||||
switch cmd {
|
||||
case "status":
|
||||
return daemonStatus()
|
||||
case "install":
|
||||
err = daemon.Install()
|
||||
err = daemonInstall(web)
|
||||
case "web":
|
||||
if !web.set {
|
||||
return daemonWebStatus()
|
||||
}
|
||||
if st, _ := daemon.Get(); !st.Installed && !web.on {
|
||||
fmt.Println("the magpie service isn't installed ·", muted.Render("magpie daemon install"))
|
||||
return nil
|
||||
}
|
||||
err = daemonInstall(web)
|
||||
case "uninstall", "remove":
|
||||
if err := daemon.Uninstall(); err != nil {
|
||||
return err
|
||||
@@ -56,9 +165,14 @@ func daemonCmd(args []string) error {
|
||||
}
|
||||
st, _ := daemon.Get()
|
||||
switch cmd {
|
||||
case "install":
|
||||
case "install", "web":
|
||||
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, k := daemon.Web(); a != "" {
|
||||
printDaemonWeb(a, k)
|
||||
} else if cmd == "web" {
|
||||
fmt.Println(muted.Render(" page not served"))
|
||||
}
|
||||
if a := daemon.Linger(); a != "" {
|
||||
fmt.Println(amber.Render("!"), a)
|
||||
}
|
||||
@@ -83,6 +197,51 @@ func daemonCmd(args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// daemonInstall installs the service, serving the page as w says.
|
||||
func daemonInstall(w daemonWeb) error {
|
||||
a, k := daemon.Web()
|
||||
o, err := webOptions(w, a, k, os.Getenv("MAGPIE_WEB_KEY"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return daemon.Install(o)
|
||||
}
|
||||
|
||||
// printDaemonWeb prints the service's page: its link, and on the network
|
||||
// its links there and what that lets anyone with one do.
|
||||
func printDaemonWeb(addr, key string) {
|
||||
fmt.Println(muted.Render(" page "), webLink(addr, key))
|
||||
host, port, _ := net.SplitHostPort(addr)
|
||||
q := "/?k=" + key
|
||||
if ip := net.ParseIP(host); host == "" || ip != nil && !ip.IsLoopback() {
|
||||
for _, l := range gui.NetworkLinks(port, q) {
|
||||
fmt.Println(muted.Render(" on the network"), l)
|
||||
}
|
||||
fmt.Println(amber.Render("!"), lanWarning)
|
||||
} else if l := proxyLink(q); l != "" {
|
||||
fmt.Println(muted.Render(" through your proxy"), l)
|
||||
}
|
||||
}
|
||||
|
||||
// daemonWebStatus: magpie daemon web — the page the service serves.
|
||||
func daemonWebStatus() error {
|
||||
st, err := daemon.Get()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !st.Installed {
|
||||
fmt.Println("the magpie service isn't installed ·", muted.Render("magpie daemon install --web"))
|
||||
return nil
|
||||
}
|
||||
a, k := daemon.Web()
|
||||
if a == "" {
|
||||
fmt.Println("the magpie service serves no page ·", muted.Render("magpie daemon web on"))
|
||||
return nil
|
||||
}
|
||||
printDaemonWeb(a, k)
|
||||
return nil
|
||||
}
|
||||
|
||||
func daemonStatus() error {
|
||||
st, err := daemon.Get()
|
||||
if err != nil {
|
||||
@@ -118,6 +277,9 @@ func daemonStatus() error {
|
||||
fmt.Println(muted.Render(" start "), start)
|
||||
fmt.Println(muted.Render(" file "), st.File)
|
||||
fmt.Println(muted.Render(" logs "), st.Logs)
|
||||
if a, k := daemon.Web(); a != "" {
|
||||
printDaemonWeb(a, k)
|
||||
}
|
||||
if served.Running {
|
||||
fmt.Println(muted.Render(" gateway"), "answers on", gateway.URL(), muted.Render(served.Version))
|
||||
} else {
|
||||
|
||||
@@ -45,3 +45,127 @@ func TestDaemonCmd(t *testing.T) {
|
||||
t.Errorf("ran %s", b)
|
||||
}
|
||||
}
|
||||
|
||||
// magpie daemon's words for the page the service serves beside the
|
||||
// gateway (HuanCheng on Discord): --web on loopback by default, --lan on
|
||||
// every interface, --addr where told; a command that says nothing of it
|
||||
// leaves it as it is, and one that contradicts itself is refused.
|
||||
func TestParseDaemon(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
args []string
|
||||
cmd string
|
||||
w daemonWeb
|
||||
wantErr string
|
||||
}{
|
||||
{nil, "status", daemonWeb{}, ""},
|
||||
{[]string{"install"}, "install", daemonWeb{}, ""},
|
||||
{[]string{"install", "--web"}, "install", daemonWeb{true, true, "127.0.0.1:3430"}, ""},
|
||||
{[]string{"install", "--web", "--lan"}, "install", daemonWeb{true, true, "0.0.0.0:3430"}, ""},
|
||||
{[]string{"install", "--lan"}, "install", daemonWeb{true, true, "0.0.0.0:3430"}, ""},
|
||||
{[]string{"install", "--addr", "10.0.0.5:8080"}, "install", daemonWeb{true, true, "10.0.0.5:8080"}, ""},
|
||||
{[]string{"install", "--web", "--addr=[::1]:3431", "--lan"}, "install", daemonWeb{true, true, "[::1]:3431"}, ""},
|
||||
{[]string{"install", "--no-web"}, "install", daemonWeb{true, false, ""}, ""},
|
||||
{[]string{"install", "--no-web", "--web"}, "", daemonWeb{}, "both"},
|
||||
{[]string{"install", "--no-web", "--lan"}, "", daemonWeb{}, "served"},
|
||||
{[]string{"install", "--addr", "3430"}, "", daemonWeb{}, "host:port"},
|
||||
{[]string{"install", "--addr"}, "", daemonWeb{}, "unknown"},
|
||||
{[]string{"install", "--bogus"}, "", daemonWeb{}, "unknown"},
|
||||
{[]string{"web"}, "web", daemonWeb{}, ""},
|
||||
{[]string{"web", "status"}, "web", daemonWeb{}, ""},
|
||||
{[]string{"web", "on"}, "web", daemonWeb{true, true, "127.0.0.1:3430"}, ""},
|
||||
{[]string{"web", "on", "--lan"}, "web", daemonWeb{true, true, "0.0.0.0:3430"}, ""},
|
||||
{[]string{"web", "--lan"}, "web", daemonWeb{true, true, "0.0.0.0:3430"}, ""},
|
||||
{[]string{"web", "off"}, "web", daemonWeb{true, false, ""}, ""},
|
||||
{[]string{"web", "off", "--lan"}, "", daemonWeb{}, "served"},
|
||||
{[]string{"web", "maybe"}, "", daemonWeb{}, "usage"},
|
||||
{[]string{"web", "on", "--web"}, "", daemonWeb{}, "unknown"},
|
||||
{[]string{"start", "--web"}, "", daemonWeb{}, "usage"},
|
||||
{[]string{"status", "x"}, "", daemonWeb{}, "usage"},
|
||||
} {
|
||||
cmd, w, err := parseDaemon(c.args)
|
||||
if c.wantErr != "" {
|
||||
if err == nil || !strings.Contains(err.Error(), c.wantErr) {
|
||||
t.Errorf("%q: %v, want an error with %q", c.args, err, c.wantErr)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil || cmd != c.cmd || w != c.w {
|
||||
t.Errorf("%q: %q %+v %v, want %q %+v", c.args, cmd, w, err, c.cmd, c.w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The page's key stays what it was across installs, so a browser stays
|
||||
// signed in: MAGPIE_WEB_KEY when the shell has one, else the service's
|
||||
// own, else a new one; installed again with nothing said, the service
|
||||
// keeps its page and key; turned off, neither is kept.
|
||||
func TestWebOptions(t *testing.T) {
|
||||
const prev = "0123456789abcdef0123456789abcdef"
|
||||
on := daemonWeb{true, true, "127.0.0.1:3430"}
|
||||
if o, err := webOptions(daemonWeb{}, "0.0.0.0:3430", prev, ""); err != nil || o.Web != "0.0.0.0:3430" || o.Key != prev {
|
||||
t.Errorf("kept: %+v %v", o, err)
|
||||
}
|
||||
if o, err := webOptions(daemonWeb{}, "", "", ""); err != nil || o.Web != "" {
|
||||
t.Errorf("none kept: %+v %v", o, err)
|
||||
}
|
||||
if o, err := webOptions(on, "0.0.0.0:3430", prev, ""); err != nil || o.Web != "127.0.0.1:3430" || o.Key != prev {
|
||||
t.Errorf("on again: %+v %v", o, err)
|
||||
}
|
||||
if o, err := webOptions(on, "", "", "my-own-key-0123456789"); err != nil || o.Key != "my-own-key-0123456789" {
|
||||
t.Errorf("the shell's key: %+v %v", o, err)
|
||||
}
|
||||
o, err := webOptions(on, "", "", "")
|
||||
if err != nil || len(o.Key) != 32 || o.Web != "127.0.0.1:3430" {
|
||||
t.Errorf("new: %+v %v", o, err)
|
||||
}
|
||||
if o, err := webOptions(daemonWeb{set: true}, "127.0.0.1:3430", prev, ""); err != nil || o.Web != "" || o.Key != "" {
|
||||
t.Errorf("off: %+v %v", o, err)
|
||||
}
|
||||
if _, err := webOptions(on, "", "", "short"); err == nil {
|
||||
t.Error("a MAGPIE_WEB_KEY too short to stand between the network and the keys was taken")
|
||||
}
|
||||
}
|
||||
|
||||
// magpie daemon status and magpie daemon web print the page's link, with
|
||||
// the key, read from the service's file, and say the page is open to
|
||||
// anyone with the link when it is served on the network.
|
||||
func TestDaemonStatusPrintsPage(t *testing.T) {
|
||||
if runtime.GOOS != "linux" && runtime.GOOS != "darwin" {
|
||||
t.Skip("systemd and launchd only")
|
||||
}
|
||||
home := helpHome(t)
|
||||
dir := t.TempDir()
|
||||
for _, name := range []string{"systemctl", "launchctl", "loginctl"} {
|
||||
testenv.Program(t, filepath.Join(dir, name), "#!/bin/sh\nexit 0\n")
|
||||
}
|
||||
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
t.Setenv("MAGPIE_ADDR", "127.0.0.1:1") // no gateway answers
|
||||
const key = "0123456789abcdef0123456789abcdef"
|
||||
file := filepath.Join(home, ".config", "systemd", "user", "magpie.service")
|
||||
text := "ExecStart=\"/usr/bin/magpie\" serve \"--web=0.0.0.0:3430\"\nEnvironment=\"MAGPIE_WEB_KEY=" + key + "\"\n"
|
||||
if runtime.GOOS == "darwin" {
|
||||
file = filepath.Join(home, "Library", "LaunchAgents", "com.yetone.magpie.serve.plist")
|
||||
text = "<array><string>/usr/bin/magpie</string><string>serve</string><string>--web=0.0.0.0:3430</string></array>\n<key>MAGPIE_WEB_KEY</key><string>" + key + "</string>\n"
|
||||
}
|
||||
os.MkdirAll(filepath.Dir(file), 0o755)
|
||||
if err := os.WriteFile(file, []byte(text), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, args := range [][]string{{"daemon", "status"}, {"daemon", "web"}} {
|
||||
out, err := runOut(t, args...)
|
||||
if err != nil || !strings.Contains(out, "http://127.0.0.1:3430/?k="+key) || !strings.Contains(out, "anyone with the link") {
|
||||
t.Errorf("%q: %q, %v", args, out, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// magpie serve takes --web and --web=host:port alone; anything else is
|
||||
// refused before a gateway is started.
|
||||
func TestServeArgs(t *testing.T) {
|
||||
helpHome(t)
|
||||
for _, args := range [][]string{{"serve", "--lan"}, {"serve", "--web=3430"}, {"serve", "web"}} {
|
||||
if _, err := runOut(t, args...); err == nil || !strings.Contains(err.Error(), "magpie serve") {
|
||||
t.Errorf("%q: %v", args, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,9 +103,14 @@ const usage = `magpie — one place to pick every agent's model
|
||||
magpie plugin move|migrate <subscription> run a built-in subscription's accounts on its community plugin
|
||||
magpie plugin move-back|unmigrate <subscription> go back to the built-in, with its accounts
|
||||
|
||||
magpie serve run the gateway alone (the app runs it too)
|
||||
magpie serve [--web[=host:port]]
|
||||
run the gateway alone (the app runs it too); --web serves magpie web's page too, from the same process (127.0.0.1:3430 unless told)
|
||||
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 daemon install [--web] [--lan] [--addr host:port] [--no-web]
|
||||
--web: the service serves magpie web's page too, with a key kept across restarts; installed again, it keeps what it served
|
||||
magpie daemon web [on|off] [--lan] [--addr host:port]
|
||||
the service's page: its link, or turn it on or off
|
||||
magpie healthcheck exit 0 when the gateway answers (a container's HEALTHCHECK)
|
||||
magpie gateway-key list|add <name>|rotate <id>|remove <id> manage the keys clients use to call a shared gateway
|
||||
magpie gateway-key limit <id> [off|reset|day|week|month|<N>d --tokens N --cost USD --cache-reads] a key's own limit, and what it used
|
||||
@@ -350,7 +355,7 @@ func run(args []string) error {
|
||||
case "group":
|
||||
return groupCmd(args)
|
||||
case "serve":
|
||||
return serve()
|
||||
return serveCmd(args[1:])
|
||||
case "gateway-key":
|
||||
return gatewayKeys(args)
|
||||
case "accounts", "account":
|
||||
|
||||
+90
-4
@@ -7,8 +7,10 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/daemon"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/gui"
|
||||
"github.com/yetone/magpie/internal/stats"
|
||||
)
|
||||
|
||||
// webAddr is where `magpie web` listens unless told: beside the gateway.
|
||||
@@ -41,10 +43,44 @@ func webCmd(args []string) error {
|
||||
_, port, _ := net.SplitHostPort(webAddr)
|
||||
addr = "0.0.0.0:" + port
|
||||
}
|
||||
// the service serves the page already: its own, beside the gateway
|
||||
// it serves, is the one to open
|
||||
if a, k := daemon.Web(); a != "" && gateway.ServedBy().Running {
|
||||
link := webLink(a, k)
|
||||
fmt.Println(green.Render("●"), "the magpie service serves this page:", bold.Render(link))
|
||||
fmt.Println(muted.Render(" magpie daemon web off turns it off"))
|
||||
if open {
|
||||
openInBrowser(link)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
w, err := gui.StartWeb(addr, version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !w.ServesGateway() {
|
||||
// another magpie has the gateway (the service, magpie serve, the
|
||||
// app): this page shows its settings and accounts, read from the
|
||||
// same files, and takes the gateway up when that one stops
|
||||
o := gateway.ServedBy()
|
||||
who := "another magpie"
|
||||
if o.Version != "" {
|
||||
who += " (" + o.Version + ")"
|
||||
}
|
||||
fmt.Println(muted.Render(" the gateway on " + gateway.URL() + " is served by " + who + "; this page shows the same settings and accounts, and serves the gateway once that one stops"))
|
||||
if st, err := daemon.Get(); err == nil && st.Running {
|
||||
fmt.Println(muted.Render(" to have the service serve this page itself: magpie daemon web on"))
|
||||
}
|
||||
}
|
||||
printWeb(w)
|
||||
if open {
|
||||
openInBrowser(w.Link)
|
||||
}
|
||||
return w.Wait()
|
||||
}
|
||||
|
||||
// printWeb prints where a started page is, and what its link carries.
|
||||
func printWeb(w *gui.Web) {
|
||||
fmt.Println(green.Render("●"), "magpie web on", bold.Render(w.Link))
|
||||
host, port, _ := net.SplitHostPort(w.Addr)
|
||||
key := w.Link[strings.Index(w.Link, "/?k="):]
|
||||
@@ -55,7 +91,7 @@ func webCmd(args []string) error {
|
||||
if gateway.ContainerAddrs() {
|
||||
fmt.Println(muted.Render(" " + containerNote))
|
||||
}
|
||||
fmt.Println(amber.Render("!"), "anyone with the link can change magpie and see its keys, and the network carries it unencrypted")
|
||||
fmt.Println(amber.Render("!"), lanWarning)
|
||||
} else if l := proxyLink(key); l != "" {
|
||||
fmt.Println(muted.Render(" through your proxy"), l)
|
||||
}
|
||||
@@ -64,10 +100,22 @@ func webCmd(args []string) error {
|
||||
carries = "MAGPIE_WEB_KEY"
|
||||
}
|
||||
fmt.Println(muted.Render(" the link carries " + carries + " · gateway " + advertisedURL() + " · Ctrl-C to stop"))
|
||||
if open {
|
||||
openInBrowser(w.Link)
|
||||
}
|
||||
|
||||
// lanWarning is said wherever the page is served on the network.
|
||||
const lanWarning = "anyone with the link can change magpie and see its keys, and the network carries it unencrypted"
|
||||
|
||||
// webLink is the link to a page served on addr with key, from this
|
||||
// computer.
|
||||
func webLink(addr, key string) string {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return "http://" + addr + "/?k=" + url.QueryEscape(key)
|
||||
}
|
||||
return w.Wait()
|
||||
if ip := net.ParseIP(host); host == "" || ip != nil && ip.IsUnspecified() {
|
||||
host = "127.0.0.1"
|
||||
}
|
||||
return "http://" + net.JoinHostPort(host, port) + "/?k=" + url.QueryEscape(key)
|
||||
}
|
||||
|
||||
// proxyLink is the page's link through a reverse proxy in front of a page
|
||||
@@ -93,3 +141,41 @@ func proxyLink(key string) string {
|
||||
}
|
||||
return strings.TrimRight(u.String(), "/") + key
|
||||
}
|
||||
|
||||
// serveCmd: magpie serve [--web[=host:port]] — the gateway, and with
|
||||
// --web magpie web's page from the same process: what the service runs
|
||||
// (`magpie daemon install --web`), so the page shows the gateway that
|
||||
// serves the agents, its routing included (HuanCheng on Discord).
|
||||
func serveCmd(args []string) error {
|
||||
web := ""
|
||||
for _, a := range args {
|
||||
switch {
|
||||
case a == "--web":
|
||||
web = webAddr
|
||||
case strings.HasPrefix(a, "--web="):
|
||||
web = strings.TrimPrefix(a, "--web=")
|
||||
if _, _, err := net.SplitHostPort(web); err != nil {
|
||||
return fmt.Errorf("magpie serve: --web=%s isn't host:port", web)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("magpie serve: unknown %q · magpie serve [--web[=host:port]]", a)
|
||||
}
|
||||
}
|
||||
if web == "" {
|
||||
return serve()
|
||||
}
|
||||
go stats.Run(version, "serve")
|
||||
w, err := gui.StartWeb(web, version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
public := advertisedURL()
|
||||
fmt.Println(green.Render("●"), "magpie gateway on", bold.Render(gateway.URL()))
|
||||
fmt.Println(muted.Render(" OpenAI "), public+"/v1/chat/completions", muted.Render("·"), public+"/v1/responses")
|
||||
fmt.Println(muted.Render(" Anthropic"), public+"/v1/messages")
|
||||
if !w.ServesGateway() {
|
||||
fmt.Println(amber.Render("!"), "another magpie serves the gateway there: this one serves it once that one stops")
|
||||
}
|
||||
printWeb(w)
|
||||
return w.Wait()
|
||||
}
|
||||
|
||||
@@ -9,9 +9,11 @@ package daemon
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -42,7 +44,7 @@ type Status struct {
|
||||
type manager interface {
|
||||
file() string
|
||||
logs() string
|
||||
install(exe string, env []string) error
|
||||
install(exe string, args, env []string) error
|
||||
uninstall() error
|
||||
start() error
|
||||
stop() error
|
||||
@@ -70,10 +72,20 @@ func current() (manager, error) {
|
||||
return nil, fmt.Errorf("%w on %s: run `magpie serve` under the system's own service manager", ErrUnsupported, goos)
|
||||
}
|
||||
|
||||
// Options are what the service serves besides the gateway.
|
||||
type Options struct {
|
||||
// Web is the address the app's page is served on (`magpie serve
|
||||
// --web=…`), "" for none.
|
||||
Web string
|
||||
// Key is the page's MAGPIE_WEB_KEY, written into the service so its
|
||||
// link stays the same across restarts; needed with Web.
|
||||
Key string
|
||||
}
|
||||
|
||||
// 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 {
|
||||
func Install(o Options) error {
|
||||
m, err := current()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -83,12 +95,73 @@ func Install() error {
|
||||
if autostartEnabled() {
|
||||
return errors.New("magpie already opens at login and serves the gateway: run `magpie autostart off` first, or keep that instead")
|
||||
}
|
||||
if o.Web != "" && o.Key == "" {
|
||||
return errors.New("the page needs a key")
|
||||
}
|
||||
exe, err := self()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
widenPath()
|
||||
return m.install(exe, environ())
|
||||
return m.install(exe, serveArgs(o), withKey(environ(), o))
|
||||
}
|
||||
|
||||
// serveArgs is what the service runs magpie with.
|
||||
func serveArgs(o Options) []string {
|
||||
if o.Web == "" {
|
||||
return []string{"serve"}
|
||||
}
|
||||
return []string{"serve", webFlag + o.Web}
|
||||
}
|
||||
|
||||
// webFlag is `magpie serve`'s, naming the page's address.
|
||||
const webFlag = "--web="
|
||||
|
||||
// webKeyVar is the page's key in the service's environment.
|
||||
const webKeyVar = "MAGPIE_WEB_KEY"
|
||||
|
||||
// withKey is env with the page's key, when it has a page: a key in the
|
||||
// shell's environment is never carried otherwise.
|
||||
func withKey(env []string, o Options) []string {
|
||||
if o.Web == "" {
|
||||
return env
|
||||
}
|
||||
return append(env, webKeyVar+"="+o.Key)
|
||||
}
|
||||
|
||||
// Web is the page the installed service serves: its address and key, ""
|
||||
// when it serves none or isn't installed. Read from the service's own
|
||||
// file, which is the user's alone.
|
||||
func Web() (addr, key string) {
|
||||
m, err := current()
|
||||
if err != nil {
|
||||
return "", ""
|
||||
}
|
||||
b, err := os.ReadFile(m.file())
|
||||
if err != nil {
|
||||
return "", ""
|
||||
}
|
||||
return webOf(string(b))
|
||||
}
|
||||
|
||||
var (
|
||||
webArgRe = regexp.MustCompile(`(?:"|<string>)` + regexp.QuoteMeta(webFlag) + `([^"<\s]+)(?:"|</string>)`)
|
||||
// a unit's Environment="MAGPIE_WEB_KEY=…", a plist's
|
||||
// <key>MAGPIE_WEB_KEY</key><string>…</string>
|
||||
webKeyRe = regexp.MustCompile(webKeyVar + `(?:=|</key><string>)([A-Za-z0-9._~-]+)`)
|
||||
)
|
||||
|
||||
// webOf is Web from a unit's or a launch agent's text.
|
||||
func webOf(text string) (addr, key string) {
|
||||
m := webArgRe.FindStringSubmatch(text)
|
||||
if m == nil {
|
||||
return "", ""
|
||||
}
|
||||
k := webKeyRe.FindStringSubmatch(text)
|
||||
if k == nil {
|
||||
return "", ""
|
||||
}
|
||||
return html.UnescapeString(m[1]), k[1]
|
||||
}
|
||||
|
||||
// widenPath gives PATH, before it is written into the service, the
|
||||
|
||||
@@ -81,7 +81,7 @@ 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 {
|
||||
if err := Install(Options{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file := filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "systemd", "user", "magpie.service")
|
||||
@@ -107,14 +107,14 @@ func TestSystemdInstallAndUninstall(t *testing.T) {
|
||||
}
|
||||
// one left readable by others, written over, is the user's alone too
|
||||
os.Chmod(file, 0o644)
|
||||
if err := Install(); err != nil {
|
||||
if err := Install(Options{}); 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 {
|
||||
if err := Install(Options{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := strings.Join(calls(t, log), "\n")
|
||||
@@ -171,7 +171,7 @@ func TestNotInstalled(t *testing.T) {
|
||||
// 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 {
|
||||
if err := Install(Options{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
write(t, filepath.Join(dir, "systemctl.show.out"), "ActiveState=active\nSubState=running\nMainPID=4242\nUnitFileState=enabled\nExecMainStatus=0\n")
|
||||
@@ -207,7 +207,7 @@ func TestSystemdStatus(t *testing.T) {
|
||||
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()
|
||||
err := Install(Options{})
|
||||
if err == nil || !strings.Contains(err.Error(), "XDG_RUNTIME_DIR") {
|
||||
t.Errorf("got %v, want the bus advice", err)
|
||||
}
|
||||
@@ -215,7 +215,7 @@ func TestSystemdUnreachable(t *testing.T) {
|
||||
t.Errorf("a unit was written: %v", err)
|
||||
}
|
||||
t.Setenv("PATH", t.TempDir())
|
||||
if err := Install(); err == nil || !strings.Contains(err.Error(), "no systemd") {
|
||||
if err := Install(Options{}); err == nil || !strings.Contains(err.Error(), "no systemd") {
|
||||
t.Errorf("got %v, want no systemd", err)
|
||||
}
|
||||
}
|
||||
@@ -227,7 +227,7 @@ func TestRefusedBesideAutostart(t *testing.T) {
|
||||
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") {
|
||||
if err := Install(Options{}); err == nil || !strings.Contains(err.Error(), "magpie autostart off") {
|
||||
t.Errorf("got %v", err)
|
||||
}
|
||||
if c := calls(t, log); c[0] != "" {
|
||||
@@ -245,7 +245,7 @@ func TestLaunchdInstall(t *testing.T) {
|
||||
t.Setenv("HTTP_PROXY", "http://a&b<c>@proxy")
|
||||
// not loaded yet
|
||||
write(t, filepath.Join(dir, "launchctl.print.fail"), "Could not find service")
|
||||
if err := Install(); err != nil {
|
||||
if err := Install(Options{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file := filepath.Join(os.Getenv("HOME"), "Library", "LaunchAgents", "com.yetone.magpie.serve.plist")
|
||||
@@ -284,7 +284,7 @@ func TestLaunchdInstall(t *testing.T) {
|
||||
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 {
|
||||
if err := Install(Options{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Restart(); err != nil {
|
||||
@@ -323,7 +323,7 @@ func TestUnsupported(t *testing.T) {
|
||||
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) {
|
||||
if err := Install(Options{}); !errors.Is(err, ErrUnsupported) || !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("%s: %v", os_, err)
|
||||
}
|
||||
}
|
||||
@@ -401,7 +401,7 @@ func TestInstallFindsNvmNode(t *testing.T) {
|
||||
if Node() != "" {
|
||||
t.Fatal("the test's PATH has a node already")
|
||||
}
|
||||
if err := Install(); err != nil {
|
||||
if err := Install(Options{}); err != nil {
|
||||
t.Fatal(err, calls(t, log))
|
||||
}
|
||||
b, err := os.ReadFile(systemd{}.file())
|
||||
@@ -427,3 +427,74 @@ func TestInstallFindsNvmNode(t *testing.T) {
|
||||
}
|
||||
|
||||
var realWiden = widenPath
|
||||
|
||||
// Installed with the page, the service runs `magpie serve --web=<addr>`
|
||||
// with the page's key in its environment, on both systems, and Web reads
|
||||
// both back from the service's own file: the key stays the same across
|
||||
// restarts and is what `magpie daemon status` prints the link with
|
||||
// (HuanCheng on Discord). Installed again without, both are gone, and a
|
||||
// MAGPIE_WEB_KEY in the shell is never carried into a service with no page.
|
||||
func TestInstallWithWeb(t *testing.T) {
|
||||
const key = "0123456789abcdef0123456789abcdef"
|
||||
for _, c := range []struct {
|
||||
goos string
|
||||
file func() string
|
||||
arg, keyIn string
|
||||
}{
|
||||
{"linux", func() string {
|
||||
return filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "systemd", "user", "magpie.service")
|
||||
}, "ExecStart=\"/opt/my magpie/magpie%%1\" serve \"--web=0.0.0.0:3430\"\n", "Environment=\"MAGPIE_WEB_KEY=" + key + "\"\n"},
|
||||
{"darwin", func() string {
|
||||
return filepath.Join(os.Getenv("HOME"), "Library", "LaunchAgents", "com.yetone.magpie.serve.plist")
|
||||
}, "<array><string>/opt/my magpie/magpie%1</string><string>serve</string><string>--web=0.0.0.0:3430</string></array>", "<key>MAGPIE_WEB_KEY</key><string>" + key + "</string>"},
|
||||
} {
|
||||
t.Run(c.goos, func(t *testing.T) {
|
||||
fakes(t, c.goos)
|
||||
t.Setenv("MAGPIE_WEB_KEY", "from-the-shell-0123456789")
|
||||
if err := Install(Options{Web: "0.0.0.0:3430", Key: key}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := os.ReadFile(c.file())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, want := range []string{c.arg, c.keyIn} {
|
||||
if !strings.Contains(string(b), want) {
|
||||
t.Errorf("the service has no %q:\n%s", want, b)
|
||||
}
|
||||
}
|
||||
if strings.Contains(string(b), "from-the-shell") {
|
||||
t.Errorf("the shell's key was carried beside the page's:\n%s", b)
|
||||
}
|
||||
if c.goos == "darwin" && runtime.GOOS == "darwin" {
|
||||
if out, err := exec.Command("/usr/bin/plutil", "-lint", c.file()).CombinedOutput(); err != nil {
|
||||
t.Errorf("plutil: %s", out)
|
||||
}
|
||||
}
|
||||
if a, k := Web(); a != "0.0.0.0:3430" || k != key {
|
||||
t.Errorf("Web: %q %q", a, k)
|
||||
}
|
||||
if err := Install(Options{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ = os.ReadFile(c.file())
|
||||
if strings.Contains(string(b), "--web") || strings.Contains(string(b), "MAGPIE_WEB_KEY") {
|
||||
t.Errorf("installed without the page, the service still has it:\n%s", b)
|
||||
}
|
||||
if a, k := Web(); a != "" || k != "" {
|
||||
t.Errorf("Web without the page: %q %q", a, k)
|
||||
}
|
||||
if err := Install(Options{Web: "127.0.0.1:3430"}); err == nil {
|
||||
t.Error("a page with no key was installed")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Web is "" with no service installed.
|
||||
func TestWebNotInstalled(t *testing.T) {
|
||||
fakes(t, "linux")
|
||||
if a, k := Web(); a != "" || k != "" {
|
||||
t.Errorf("%q %q", a, k)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,8 +31,8 @@ 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 {
|
||||
// plist is the launch agent running exe with args, with env set in it.
|
||||
func plist(exe string, args, env []string) string {
|
||||
s := func(v string) string { return "<string>" + html.EscapeString(v) + "</string>" }
|
||||
var b strings.Builder
|
||||
b.WriteString(`<?xml version="1.0" encoding="UTF-8"?>
|
||||
@@ -42,7 +42,7 @@ func plist(exe string, env []string) string {
|
||||
<dict>
|
||||
<key>Label</key>` + s(Label) + `
|
||||
<key>ProgramArguments</key>
|
||||
<array>` + s(exe) + s("serve") + `</array>
|
||||
<array>` + s(exe) + strings.Join(mapped(args, s), "") + `</array>
|
||||
<key>RunAtLoad</key><true/>
|
||||
<key>KeepAlive</key>
|
||||
<dict><key>SuccessfulExit</key><false/></dict>
|
||||
@@ -63,14 +63,14 @@ func plist(exe string, env []string) string {
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (l launchd) install(exe string, env []string) error {
|
||||
func (l launchd) install(exe string, args, 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 {
|
||||
if err := private(l.file(), []byte(plist(exe, args, env))); err != nil {
|
||||
return err
|
||||
}
|
||||
// one loaded before runs the old plist until it is taken out
|
||||
@@ -163,4 +163,12 @@ func (l launchd) status() (Status, error) {
|
||||
return st, nil
|
||||
}
|
||||
|
||||
func mapped(xs []string, f func(string) string) []string {
|
||||
out := make([]string, len(xs))
|
||||
for i, x := range xs {
|
||||
out[i] = f(x)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func launchctl(args ...string) (string, error) { return run("launchctl", args...) }
|
||||
|
||||
@@ -27,13 +27,21 @@ func (systemd) file() string {
|
||||
|
||||
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 {
|
||||
// unitText is the unit running exe with args, with env set in it.
|
||||
func unitText(exe string, args, 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("ExecStart=" + unitQuote(exe))
|
||||
for _, a := range args {
|
||||
if a == "serve" {
|
||||
b.WriteString(" serve")
|
||||
} else {
|
||||
b.WriteString(" " + unitQuote(a))
|
||||
}
|
||||
}
|
||||
b.WriteString("\n")
|
||||
b.WriteString("Restart=on-failure\nRestartSec=5\n")
|
||||
for _, kv := range env {
|
||||
b.WriteString("Environment=" + unitQuote(kv) + "\n")
|
||||
@@ -49,14 +57,14 @@ func unitQuote(s string) string {
|
||||
return `"` + s + `"`
|
||||
}
|
||||
|
||||
func (s systemd) install(exe string, env []string) error {
|
||||
func (s systemd) install(exe string, args, 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 {
|
||||
if err := private(s.file(), []byte(unitText(exe, args, env))); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := systemctl("daemon-reload"); err != nil {
|
||||
|
||||
+28
-8
@@ -101,6 +101,12 @@ func StartWeb(addr, version string) (*Web, error) {
|
||||
return w, nil
|
||||
}
|
||||
|
||||
// ServesGateway says whether this process serves the gateway, which it
|
||||
// doesn't while another magpie (the service, the app, magpie serve) has
|
||||
// it: the page then shows that one's settings and accounts, read from the
|
||||
// same files, and this one takes the gateway up once that one is gone.
|
||||
func (w *Web) ServesGateway() bool { return served.Load() != nil }
|
||||
|
||||
// Wait returns once the page's Quit is used. After a restart to update it
|
||||
// runs the new version in this one's place, with the same arguments and
|
||||
// key, so the page open in the browser finds it where it was.
|
||||
@@ -138,19 +144,33 @@ func webKey() (key string, fixed bool, err error) {
|
||||
}
|
||||
}
|
||||
if k := os.Getenv("MAGPIE_WEB_KEY"); k != "" {
|
||||
if len(k) < webKeyMin {
|
||||
return "", false, fmt.Errorf("MAGPIE_WEB_KEY is %d characters; it needs at least %d", len(k), webKeyMin)
|
||||
}
|
||||
// a cookie can't hold a space, ; " \ or a comma: the browser would
|
||||
// be sent one that isn't the key, and turned away
|
||||
if strings.Trim(k, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") != "" {
|
||||
return "", false, errors.New("MAGPIE_WEB_KEY takes letters, digits and - . _ ~ only (openssl rand -hex 16 makes one)")
|
||||
if err := CheckWebKey(k); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return k, true, nil
|
||||
}
|
||||
return NewWebKey(), false, nil
|
||||
}
|
||||
|
||||
// NewWebKey is a new random key for the page.
|
||||
func NewWebKey() string {
|
||||
b := make([]byte, 16)
|
||||
rand.Read(b)
|
||||
return hex.EncodeToString(b), false, nil
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// CheckWebKey says what is wrong with k as a MAGPIE_WEB_KEY, nil when
|
||||
// nothing is.
|
||||
func CheckWebKey(k string) error {
|
||||
if len(k) < webKeyMin {
|
||||
return fmt.Errorf("MAGPIE_WEB_KEY is %d characters; it needs at least %d", len(k), webKeyMin)
|
||||
}
|
||||
// a cookie can't hold a space, ; " \ or a comma: the browser would
|
||||
// be sent one that isn't the key, and turned away
|
||||
if strings.Trim(k, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") != "" {
|
||||
return errors.New("MAGPIE_WEB_KEY takes letters, digits and - . _ ~ only (openssl rand -hex 16 makes one)")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// webGuard lets through requests with the key: in the link's k, which it
|
||||
|
||||
@@ -267,7 +267,7 @@ magpie claude group/opus-anywhere <span class="c"># これを使う</span></p
|
||||
<h3><code>OPENAI_BASE_URL</code> や <code>ANTHROPIC_BASE_URL</code> を export する必要はありますか?</h3>
|
||||
<p>いいえ。magpie が一覧に表示するエージェントについては、ゲートウェイのアドレスとトークンをエージェント自身の設定ファイルに書き込みます。これらの変数は、ベース URL を設定できる他のツール向けです。<span class="ui">Gateway</span> タブの <span class="ui">Connect</span> セクションに、コピーボタンとスニペットとして用意されています。</p>
|
||||
<h3>magpie は起動しておく必要がありますか?</h3>
|
||||
<p>magpie 経由のモデルを使うなら必要です。ゲートウェイはアプリと一緒に動きます。ウィンドウを閉じてもメニューバーやトレイで動き続けます。<code>magpie tray</code> はアイコンだけで起動し(ログイン項目に入れておくと便利です)、<code>magpie serve</code> はゲートウェイだけを動かし、<code>magpie daemon install</code> はそれをサービス(Linux は systemd、Mac は launchd)として登録し、ログインや起動時からウィンドウなしで動かし続けます。エージェント自身のモデルと自身のサインインで動くエージェントは、magpie を通りません。</p>
|
||||
<p>magpie 経由のモデルを使うなら必要です。ゲートウェイはアプリと一緒に動きます。ウィンドウを閉じてもメニューバーやトレイで動き続けます。<code>magpie tray</code> はアイコンだけで起動し(ログイン項目に入れておくと便利です)、<code>magpie serve</code> はゲートウェイだけを動かし、<code>magpie daemon install</code> はそれをサービス(Linux は systemd、Mac は launchd)として登録し、ログインや起動時からウィンドウなしで動かし続けます。<code>magpie daemon install --web</code> ならブラウザのページも同じサービスが提供し、<code>magpie daemon status</code> がページのリンクを表示します。エージェント自身のモデルと自身のサインインで動くエージェントは、magpie を通りません。</p>
|
||||
<h3>エージェントを元の状態に戻すには?</h3>
|
||||
<p>ピッカーでエージェント自身のモデルを選ぶか、<code>magpie <agent> default</code> を実行します。magpie は自分が書き込んだものを取り除き、以前に設定していた <code>ANTHROPIC_BASE_URL</code> など、置き換えた値を元に戻します。</p>
|
||||
<h3>モデルを切り替えたのに、エージェントが古いモデルを使い続けます。</h3>
|
||||
|
||||
@@ -267,7 +267,7 @@ magpie claude group/opus-anywhere <span class="c"># use it</span></pre>
|
||||
<h3>Do I need to export <code>OPENAI_BASE_URL</code> or <code>ANTHROPIC_BASE_URL</code>?</h3>
|
||||
<p>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 <span class="ui">Gateway</span> tab’s <span class="ui">Connect</span> section has them as copy buttons and snippets.</p>
|
||||
<h3>Does magpie have to be running?</h3>
|
||||
<p>For a model through magpie, yes: the gateway runs with the app. Closing the window leaves it running in the menu bar or tray; <code>magpie tray</code> starts the icon alone (put it in your login items), and <code>magpie serve</code> runs just the gateway, and <code>magpie daemon install</code> 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.</p>
|
||||
<p>For a model through magpie, yes: the gateway runs with the app. Closing the window leaves it running in the menu bar or tray; <code>magpie tray</code> starts the icon alone (put it in your login items), and <code>magpie serve</code> runs just the gateway, and <code>magpie daemon install</code> keeps it running as a service (systemd on Linux, launchd on the Mac), from login or boot, with no window; <code>magpie daemon install --web</code> has it serve the browser page too, and <code>magpie daemon status</code> prints the page’s link. An agent on its own model and its own sign-in doesn’t go through magpie.</p>
|
||||
<h3>How do I put an agent back the way it was?</h3>
|
||||
<p>Pick one of the agent’s own models in the picker, or run <code>magpie <agent> default</code>. magpie removes what it wrote and restores the values it replaced, such as an <code>ANTHROPIC_BASE_URL</code> you had before.</p>
|
||||
<h3>I switched models, but my agent still uses the old one.</h3>
|
||||
|
||||
@@ -267,7 +267,7 @@ magpie claude group/opus-anywhere <span class="c"># 使用它</span></pre>
|
||||
<h3>需要自己 export <code>OPENAI_BASE_URL</code> 或 <code>ANTHROPIC_BASE_URL</code> 吗?</h3>
|
||||
<p>不需要。对 magpie 列出的 Agent,它会把网关地址和令牌直接写进 Agent 自己的配置文件。这些环境变量只用于 magpie 不管理的、带 base URL 设置的其他工具:<span class="ui">网关</span> 标签页的 <span class="ui">接入</span> 部分有一键复制和示例代码。</p>
|
||||
<h3>magpie 必须一直开着吗?</h3>
|
||||
<p>通过 magpie 使用的模型需要:网关随应用一起运行。关掉窗口后它仍留在菜单栏或托盘里;<code>magpie tray</code> 只启动图标(可以放进登录项),<code>magpie serve</code> 只运行网关,<code>magpie daemon install</code> 把它装成服务(Linux 上是 systemd,Mac 上是 launchd),登录或开机就启动,不需要窗口。Agent 用它自己的模型和自己的登录时,不经过 magpie。</p>
|
||||
<p>通过 magpie 使用的模型需要:网关随应用一起运行。关掉窗口后它仍留在菜单栏或托盘里;<code>magpie tray</code> 只启动图标(可以放进登录项),<code>magpie serve</code> 只运行网关,<code>magpie daemon install</code> 把它装成服务(Linux 上是 systemd,Mac 上是 launchd),登录或开机就启动,不需要窗口;<code>magpie daemon install --web</code> 让服务同时提供浏览器页面,<code>magpie daemon status</code> 会打印页面的链接。Agent 用它自己的模型和自己的登录时,不经过 magpie。</p>
|
||||
<h3>怎么把 Agent 恢复原样?</h3>
|
||||
<p>在选择列表里选 Agent 自带的模型,或运行 <code>magpie <agent> default</code>。magpie 会删掉它写入的内容,并恢复被它替换掉的值,比如你原来的 <code>ANTHROPIC_BASE_URL</code>。</p>
|
||||
<h3>换了模型,Agent 还在用旧的?</h3>
|
||||
|
||||
Reference in New Issue
Block a user