diff --git a/internal/agent/hermes.go b/internal/agent/hermes.go index 47e15cc5a..d9bd1fd24 100644 --- a/internal/agent/hermes.go +++ b/internal/agent/hermes.go @@ -13,9 +13,19 @@ package agent // magpie's models beside its own (lijiho96940561 on X: Hermes went to Not // connected and magpie's models left its picker), and only Disconnect // takes the provider out. +// +// Each of Hermes's bots is a profile with its own config.yaml (see +// hermesProfiles), which doesn't read the main one's: magpie's provider goes +// into every profile's too, so magpie is offered in every bot's picker, not +// the main one's alone (lijiho96940561 on X). A profile's own model and +// provider are left as its user set them, and Disconnect takes the provider +// out of each. import ( + "errors" + "os" "path/filepath" + "regexp" "strings" "github.com/yetone/magpie/internal/edit" @@ -33,6 +43,19 @@ func hermesIn(at place) *Agent { } path := filepath.Join(dir, "config.yaml") hermesProvider := func() hermesProviderEntry { return hermesProviderAt(at.gw()) } + // spread puts magpie's provider, as it is now, into every other + // profile's config beside the one magpie connects + spread := func() error { + var errs []error + for _, p := range hermesOthers(at, dir) { + if edit.GetYAMLMap(p, "providers."+magpieID) != nil { + errs = append(errs, syncYAML(p, "providers."+magpieID, func() any { return hermesProvider() })) + } else { + errs = append(errs, edit.SetYAML(p, edit.KV{Path: "providers." + magpieID, Value: hermesProvider()})) + } + } + return errors.Join(errs...) + } key := "hermes:" + path + ":" getKey := func(k string) string { v, _ := edit.GetYAML(path, k); return v } onMagpie := func() bool { return getKey("model.provider") == magpieID } @@ -66,7 +89,10 @@ func hermesIn(at place) *Agent { UA: []string{"hermes-agent"}, Bin: "hermes", Dir: dir, Path: path, Sync: func() error { - return syncYAML(path, "providers."+magpieID, func() any { return hermesProvider() }) + if err := syncYAML(path, "providers."+magpieID, func() any { return hermesProvider() }); err != nil || !joined() { + return err + } + return spread() }, Notice: func() string { if Running(`(^|/)hermes( |$)`) { @@ -78,10 +104,14 @@ func hermesIn(at place) *Agent { // Disconnect takes magpie's provider out; the model, when it is // magpie's, goes back by the field Unwire: func() error { - if !joined() { - return nil + var errs []error + if joined() { + errs = append(errs, edit.DelYAML(path, "providers."+magpieID)) } - return edit.DelYAML(path, "providers."+magpieID) + for _, p := range hermesOthers(at, dir) { + errs = append(errs, hermesUnwireProfile(p)) + } + return errors.Join(errs...) }, Check: func() string { if !onMagpie() { @@ -116,11 +146,14 @@ func hermesIn(at place) *Agent { key + "model.default": getKey("model.default"), }) } - return edit.SetYAML(path, + if err := edit.SetYAML(path, edit.KV{Path: "providers." + magpieID, Value: hermesProvider()}, edit.KV{Path: "model.provider", Value: magpieID}, edit.KV{Path: "model.default", Value: ref}, - ) + ); err != nil { + return err + } + return spread() } if onMagpie() { if err := restore(); err != nil { @@ -150,6 +183,78 @@ func hermesIn(at place) *Agent { } } +// hermesProfileID is the name a Hermes profile may have +// (hermes_constants.PROFILE_ID_RE). +var hermesProfileID = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,63}$`) + +// hermesProfiles is the config.yaml of each of Hermes's own profiles (its +// bots), as Hermes lists them (hermes_cli/profiles.py): the root's own, and +// /profiles/'s for each name Hermes allows that holds a file +// only a profile has and isn't deleted (a tombstone at +// profiles/.deleted/). The root is ~/.hermes, which HERMES_HOME under +// it is a profile of; a HERMES_HOME elsewhere is the root itself, or, as +// /profiles/, a profile of (get_default_hermes_root). +// A profile with no config.yaml yet is left out: magpie doesn't make one. +func hermesProfiles(at place) []string { + root := filepath.Join(at.home, ".hermes") + if env := at.getenv("HERMES_HOME"); env != "" { + if rel, err := filepath.Rel(root, env); err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + root = env + if filepath.Base(filepath.Dir(env)) == "profiles" { + root = filepath.Dir(filepath.Dir(env)) + } + } + } + paths := []string{filepath.Join(root, "config.yaml")} + ps := filepath.Join(root, "profiles") + es, _ := os.ReadDir(ps) + for _, e := range es { + name := e.Name() + if !e.IsDir() || name == "default" || !hermesProfileID.MatchString(name) { + continue + } + if _, err := os.Stat(filepath.Join(ps, ".deleted", name)); err == nil { + continue + } + if st, err := os.Stat(filepath.Join(ps, name, "config.yaml")); err == nil && st.Mode().IsRegular() { + paths = append(paths, filepath.Join(ps, name, "config.yaml")) + } + } + return paths +} + +// hermesOthers is every profile's config but the one at dir, which magpie +// connects +func hermesOthers(at place, dir string) []string { + var out []string + for _, p := range hermesProfiles(at) { + if filepath.Clean(filepath.Dir(p)) == filepath.Clean(dir) { + continue + } + if _, err := os.Stat(p); err != nil { + continue + } + out = append(out, p) + } + return out +} + +// hermesUnwireProfile takes magpie's provider out of a profile's config. A +// profile whose model is on magpie (one cloned from a connected main +// config, or picked in that bot) would be left naming a provider that is +// gone, so its provider and model go too, and Hermes takes its own +// defaults, as the main config does with nothing stashed. +func hermesUnwireProfile(p string) error { + if edit.GetYAMLMap(p, "providers."+magpieID) == nil { + return nil + } + del := []string{"providers." + magpieID} + if v, _ := edit.GetYAML(p, "model.provider"); v == magpieID { + del = append(del, "model.provider", "model.default") + } + return edit.DelYAML(p, del...) +} + type hermesProviderEntry struct { Name string `yaml:"name"` BaseURL string `yaml:"base_url"` diff --git a/internal/agent/hermes_test.go b/internal/agent/hermes_test.go index 00e73330a..ead7e9370 100644 --- a/internal/agent/hermes_test.go +++ b/internal/agent/hermes_test.go @@ -120,3 +120,125 @@ func TestHermes(t *testing.T) { t.Fatalf("disconnect, no provider:\n%s", raw) } } + +// Each of Hermes's bots is a profile under ~/.hermes/profiles/ with a +// config.yaml of its own, which doesn't read the main one's: connected, +// magpie is offered in every bot's picker, each keeps its own model, and +// Disconnect takes magpie out of each (lijiho96940561 on X: only the main +// bot had magpie). +func TestHermesProfiles(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("HERMES_HOME", "") + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro"}}); err != nil { + t.Fatal(err) + } + root := filepath.Join(home, ".hermes") + write := func(rel, s string) string { + p := filepath.Join(root, rel) + os.MkdirAll(filepath.Dir(p), 0o755) + os.WriteFile(p, []byte(s), 0o644) + return p + } + write("config.yaml", "model:\n default: anthropic/claude-opus-5\n provider: openrouter\n") + // as `hermes profile create` leaves them: config.yaml, .env, SOUL.md + bot := write("profiles/coder/config.yaml", "# coder bot\nmodel:\n default: kimi-k3\n provider: moonshot\nproviders:\n mine:\n base_url: https://x\n") + write("profiles/coder/SOUL.md", "coder\n") + // cloned from a main config already on magpie + clone := write("profiles/writer/config.yaml", "model:\n default: deepseek/pro\n provider: magpie\n") + // deleted (a tombstone beside it), and a name Hermes doesn't allow + gone := write("profiles/old/config.yaml", "model:\n default: x\n") + write("profiles/.deleted/old", "") + bad := write("profiles/Bad/config.yaml", "model:\n default: x\n") + read := func(p string) (map[string]any, string) { + var c map[string]any + b, _ := os.ReadFile(p) + yaml.Unmarshal(b, &c) + return c, string(b) + } + has := func(p string) bool { + c, _ := read(p) + ps, _ := c["providers"].(map[string]any) + return ps["magpie"] != nil + } + + a := hermes(home) + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + c, raw := read(bot) + m, _ := c["model"].(map[string]any) + if !has(bot) || !has(clone) || m["default"] != "kimi-k3" || m["provider"] != "moonshot" || !strings.Contains(raw, "# coder bot") || + c["providers"].(map[string]any)["mine"] == nil { + t.Fatalf("coder after connect:\n%s", raw) + } + if has(gone) || has(bad) { + t.Fatal("a deleted or invalid profile got magpie") + } + + // a profile made later gets it at the next sync + later := write("profiles/later/config.yaml", "model:\n default: x\n") + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if !has(later) { + t.Fatal("sync left a new profile out") + } + + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + c, raw = read(bot) + m, _ = c["model"].(map[string]any) + if has(bot) || has(later) || m["default"] != "kimi-k3" || m["provider"] != "moonshot" || c["providers"].(map[string]any)["mine"] == nil { + t.Fatalf("coder after disconnect:\n%s", raw) + } + // the clone isn't left naming a provider that is gone + c, raw = read(clone) + m, _ = c["model"].(map[string]any) + if has(clone) || m["provider"] != nil || m["default"] != nil { + t.Fatalf("writer after disconnect:\n%s", raw) + } + // disconnected: a sync doesn't put it back + if err := a.Sync(); err != nil || has(bot) { + t.Fatalf("sync after disconnect: %v", err) + } +} + +// HERMES_HOME set to a profile outside ~/.hermes (Docker): magpie connects +// that profile, and the root's config and its other profiles get the +// provider too +func TestHermesProfilesOfCustomRoot(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro"}}); err != nil { + t.Fatal(err) + } + root := filepath.Join(home, "data") + for _, p := range []string{"config.yaml", "profiles/a/config.yaml", "profiles/b/config.yaml"} { + os.MkdirAll(filepath.Dir(filepath.Join(root, p)), 0o755) + os.WriteFile(filepath.Join(root, p), []byte("model:\n default: x\n"), 0o644) + } + t.Setenv("HERMES_HOME", filepath.Join(root, "profiles", "a")) + if got := hermesProfiles(here(home)); len(got) != 3 { + t.Fatalf("profiles: %v", got) + } + if err := hermes(home).Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + for _, p := range []string{"config.yaml", "profiles/b/config.yaml"} { + v, ok := edit.GetYAML(filepath.Join(root, p), "providers.magpie.base_url") + if !ok || !strings.HasSuffix(v, "/v1") { + t.Fatalf("%s: %q", p, v) + } + } + if v, _ := edit.GetYAML(filepath.Join(root, "config.yaml"), "model.default"); v != "x" { + t.Fatalf("root model: %q", v) + } +}