JonahFu asked on X (tweet 2123236872940073039) for each subagent's local path in Library > Subagents, to edit it with an LLM, or to keep a subagent in a git repository. Each subagent of the library (not a plugin's) is now kept on this computer in <library>/subagents/<name>.md as well, in Claude Code's shape (name, description, model, skills, mcpServers, the prompt), or in a file of the user's own set under the editor's Advanced (folded unless one is set), in a repository say: - FileHash is what the file said when magpie last wrote or took it in. An edit there (by hand, by an agent, a git pull) is taken in at the next sync and before a change made on the page, and every ticked agent gets it. While magpie runs, KeepLinked's loop syncs when a file's hash differs, once per edit. - An edit that can't be read as a subagent (no front matter, another name, no prompt) is left as it is, the agents keep what it said before, and the editor says why. magpie writes a file only when it is missing, or still as magpie left it; never the user's edit. - A file of the user's own that is there already is what the subagent says (a bad one refuses the save). It must be an absolute .md path, not a folder, not inside the library, not one another subagent uses, and not a file magpie writes for an agent. - Rename and remove take the library's own file only while it is as magpie wrote it; the user's own file always stays. - File and FileHash are this computer's: Collect leaves them out, Put keeps this computer's. The editor shows the path (click reveals it, Copy copies it), a line that edits there reach the agents, and the error when one wasn't taken in. i18n in zh, zh-TW, ja and de. docs/subsystems/library.md: a row for the subagent's own file and its tests. Run at the tree before2051dfc23(a Pi market change in pimarket.go and plugin/market.go only) came onto origin/main: - mote-run: gofmt -l none; GOOS=linux and GOOS=windows go vet -tags nogui ./... and go vet ./...: ok. go test -timeout 45m ./...: every package ok, internal/library 504s, except known reds not touched here: internal/cli TestHealthcheckFindsTheRunningGatewayWithoutMagpieAddr, TestUpdateRestartsTheGatewayItFindsWithoutMagpieAddr and TestUpdateFindsAMagpieThatWroteNoRecord (#6471, #6223: a real gateway on mote's 127.0.0.1:3425), internal/gateway TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes (#7117). mote and mica were both over their cores; the suite went to mote. - mica-run: node --test library-subagents, library-rules, library-commands, i18n-keys, i18n-en-no-cjk (Chromium and WebKit, 420 and 1100 wide, en zh zh-TW ja de): 44 of 44. Before that, every library-*, lib-*, nav-* and i18n* file (95 files, 2071 tests): red only in library-commands (its tab-order assert, fixed in the previous commit) and library-open-again's 1100px cases, red the same alone at base14b6b9555(#6751). - Red on the old code: TestSubagentFileFollowed and TestSubagentFileUnreadable went red with the follow step skipped and the hash check dropped; library-subagents.test.cjs is red against the previous commit's client.js. - Real use: a sandbox HOME magpie on mica (fake claude on PATH) wrote ~/.config/magpie/library/subagents/reviewer.md; an edit there with a new description and prompt reached ~/.claude/agents/reviewer.md and library.json on the next `library sync`; an edit with no front matter was left as written and Claude Code's file kept the old text. - After rebasing on2051dfc23, mica-run: go vet ./internal/library ./internal/plugin and go test -timeout 45m ./internal/library: ok. Not tried: a real Claude Code or other agent editing the file, a real git pull into a repository file while magpie runs (KeepLinked's loop is covered by TestSubagentOwnFile only), Windows and Linux.
1018 lines
32 KiB
Go
1018 lines
32 KiB
Go
package library
|
|
|
|
import (
|
|
"bytes"
|
|
"cmp"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"io/fs"
|
|
"maps"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// Bundle is the library as a backup carries it to another computer: the
|
|
// instruction sets and the one on, what each agent gets besides, the MCP
|
|
// servers, the skills with their files and the subagents. What magpie
|
|
// wrote into each agent (Applied, the subagents' files among it) is this
|
|
// computer's own and stays out. It is made the
|
|
// same way every time — no times, everything in order — so two computers
|
|
// with the same library carry the same bundle.
|
|
type Bundle struct {
|
|
Instructions Instructions `json:"instructions"`
|
|
Texts map[string]string `json:"texts,omitempty"` // set → its text
|
|
Extra map[string]string `json:"extra,omitempty"` // agent → what it gets besides
|
|
MCP []*Server `json:"mcp"`
|
|
Skills []*CarriedSkill `json:"skills"`
|
|
Icons map[string]string `json:"icons,omitempty"`
|
|
// Subagents are nil in a bundle from a magpie before they were
|
|
// carried, which knew nothing of this computer's: Put keeps them. Collect
|
|
// always sets it, empty too, so taking the last one out is carried.
|
|
Subagents *[]*Subagent `json:"subagents,omitempty"`
|
|
// Commands are nil in a bundle from a magpie before slash commands,
|
|
// as Subagents are: Put keeps this computer's.
|
|
Commands *[]*Command `json:"commands,omitempty"`
|
|
// Rules are nil in a bundle from a magpie before rules, as Subagents
|
|
// are: Put keeps this computer's.
|
|
Rules *[]*Rule `json:"rules,omitempty"`
|
|
// Hooks are nil in a bundle from a magpie before they were carried,
|
|
// as Subagents are: Put keeps this computer's. Applied.Hooks, the
|
|
// entries magpie wrote into each agent here, stays out.
|
|
Hooks *[]*Hook `json:"hooks,omitempty"`
|
|
// Env is nil in a bundle from a magpie before variables were carried:
|
|
// Put keeps this computer's. Applied.Env stays out. A backup made
|
|
// without keys carries the names with empty values (WithoutSecrets).
|
|
Env *[]*EnvVar `json:"env,omitempty"`
|
|
// Bili is billion-context's own billion-context.json, with magpie's
|
|
// recipe at the default gateway address (carriedBili). It is nil when
|
|
// this computer has none or it can't be read, and in a bundle from a
|
|
// magpie before it was carried: Put keeps this computer's then.
|
|
Bili *string `json:"bili,omitempty"`
|
|
// ClaudePlugins are the marketplaces and plugins installed in Claude
|
|
// Code itself (claude_plugins.go). nil when there are none, or they
|
|
// can't be read, and in a bundle from a magpie before them: Put adds
|
|
// nothing then. Put only adds, so one computer's never takes away
|
|
// another's.
|
|
ClaudePlugins *ClaudePlugins `json:"claudePlugins,omitempty"`
|
|
// Plugins are the library's own Claude plugins (plugin.go), each as a
|
|
// whole: its parts aren't among the skills, servers, hooks and
|
|
// subagents above, and each computer makes them again from it
|
|
// (plugin_carry.go). nil in a bundle from a magpie before they were
|
|
// carried: Put keeps this computer's then.
|
|
Plugins *[]*CarriedPlugin `json:"plugins,omitempty"`
|
|
// NoAgents says the Library was told by a magpie whose page shows no
|
|
// agent (a container, a NAS, gateway mode; Shared): its skills and
|
|
// prompts are ticked for none there, and a magpie that takes them
|
|
// gives one ticked for none to the agents a new one goes to (Borrow).
|
|
NoAgents bool `json:"noAgents,omitempty"`
|
|
}
|
|
|
|
// CarriedSkill is a skill with its folder's files.
|
|
type CarriedSkill struct {
|
|
Name string `json:"name"`
|
|
Source *Source `json:"source,omitempty"`
|
|
Agents []string `json:"agents"`
|
|
Files map[string][]byte `json:"files"` // by path in the folder, with /
|
|
Exec []string `json:"exec,omitempty"` // the files that run
|
|
Left []string `json:"left,omitempty"` // files too big to carry
|
|
// Called is the name its SKILL.md gives, when that isn't Name
|
|
Called string `json:"called,omitempty"`
|
|
// Note is the user's note on it (Skill.Note)
|
|
Note string `json:"note,omitempty"`
|
|
// Router is Skill.Router: direct, kept out of the skill router
|
|
Router string `json:"router,omitempty"`
|
|
// From is the repository the skill was traced to on the computer that
|
|
// made the bundle (Skill.From, skill_from.go), when it isn't a source
|
|
// the skill carries itself: the lock, a checkout, CC Switch's record or
|
|
// an install-again there. What traced it is that computer's own files,
|
|
// so without this the other computer groups the skill under "this
|
|
// computer". Bundles from before this have none.
|
|
From string `json:"from,omitempty"`
|
|
// Fetch is a skill carried as its source (skill_carry.go): the other
|
|
// computer fetches it from there, at the version Hash names (Commit
|
|
// too, for a git repository's), and Files are only what fit, standing
|
|
// in until then. A magpie from before this leaves it out and writes
|
|
// the files, as it did.
|
|
Fetch bool `json:"fetch,omitempty"`
|
|
Hash string `json:"hash,omitempty"`
|
|
Commit string `json:"commit,omitempty"`
|
|
}
|
|
|
|
// A skill's file bigger than maxCarried is left out, and so are the
|
|
// biggest once the skills come to maxCarriedAll. A skill's own files go
|
|
// with it, its scripts and its templates (a PowerPoint template with its
|
|
// pictures is several MB), but a sync reads at most 64 MiB of a backup
|
|
// (davsync), and a skill's bytes are base64 twice in one (the bundle's
|
|
// JSON, then the sealed envelope's): 32 MiB of files is about 57 MiB.
|
|
const (
|
|
maxCarried = 16 << 20
|
|
maxCarriedAll = 32 << 20
|
|
)
|
|
|
|
// Collect is the library as it is now; nil when there is none yet.
|
|
func Collect() (*Bundle, error) {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
if _, err := os.Stat(path()); errors.Is(err, fs.ErrNotExist) {
|
|
return nil, nil
|
|
} else if err != nil { // there, but unknown: never carried as no library (#2269)
|
|
return nil, err
|
|
}
|
|
l, err := load()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
b := &Bundle{Instructions: l.Instructions, Texts: map[string]string{}, Extra: extras(), MCP: []*Server{}, Skills: []*CarriedSkill{}, Icons: l.Icons}
|
|
b.Instructions.Agents = orNone(b.Instructions.Agents)
|
|
// a set's own file is this computer's: its text goes, where it is
|
|
// doesn't
|
|
b.Instructions.Sets = slices.Clone(b.Instructions.Sets)
|
|
for i := range b.Instructions.Sets {
|
|
b.Instructions.Sets[i].File = ""
|
|
}
|
|
for _, s := range l.sets() {
|
|
if text := setText(l.textPath(s.ID)); text != "" {
|
|
b.Texts[s.ID] = text
|
|
}
|
|
}
|
|
if len(b.Texts) == 0 {
|
|
b.Texts = nil
|
|
}
|
|
if len(b.Extra) == 0 {
|
|
b.Extra = nil
|
|
}
|
|
// a server kept to this computer stays out; another computer's by its
|
|
// name, which a sync brought, goes on as it came (mcp_local.go)
|
|
for _, s := range sorted(l.carriedServers(), func(s *Server) string { return s.Name }) {
|
|
if l.ownedPart(s.Bundle) { // with its plugin (plugin_carry.go)
|
|
continue
|
|
}
|
|
// magpie's own by name, each computer's own binary; a server
|
|
// started its own way here goes with the synced start (mcp_here.go)
|
|
c := *carried(carriedStart(s))
|
|
c.Agents = orNone(slices.Sorted(slices.Values(s.Agents)))
|
|
b.MCP = append(b.MCP, &c)
|
|
}
|
|
skills := sorted(slices.DeleteFunc(slices.Clone(l.Skills), func(s *Skill) bool { return l.ownedPart(s.Bundle) }),
|
|
func(s *Skill) string { return s.Name })
|
|
// a skill carried as its source (skill_carry.go) takes only the room
|
|
// the ones carried as their files leave
|
|
var asFiles, asSource []*Skill
|
|
dirs, sdirs := []string{}, []string{}
|
|
for _, s := range skills {
|
|
if l.bySource(s) {
|
|
asSource, sdirs = append(asSource, s), append(sdirs, realDir(skillDir(s.Name)))
|
|
} else {
|
|
asFiles, dirs = append(asFiles, s), append(dirs, realDir(skillDir(s.Name)))
|
|
}
|
|
}
|
|
// a plugin's files from a folder are read with the skills', in one
|
|
// budget
|
|
plugins, pdirs, at := l.carriedPlugins()
|
|
read := readSkills(append(dirs, pdirs...))
|
|
for i, f := range read[len(asFiles):] {
|
|
c := plugins[at[i]]
|
|
c.Files, c.Exec, c.Left = f.Files, f.Exec, f.Left
|
|
}
|
|
b.Plugins = &plugins
|
|
used := int64(0)
|
|
for _, c := range read {
|
|
for _, f := range c.Files {
|
|
used += int64(len(f))
|
|
}
|
|
}
|
|
carried := map[string]*CarriedSkill{}
|
|
for i, c := range readSkillsMax(sdirs, maxCarried, max(maxCarriedAll-used, 0)) {
|
|
s := asSource[i]
|
|
c.Fetch, c.Hash, c.Commit = true, s.Hash, s.Commit
|
|
carried[s.Name] = c
|
|
}
|
|
for i, c := range read[:len(asFiles)] {
|
|
carried[asFiles[i].Name] = c
|
|
}
|
|
for _, s := range skills {
|
|
missing(carried[s.Name], s)
|
|
}
|
|
tr := &tracer{}
|
|
for _, s := range skills {
|
|
c := carried[s.Name]
|
|
if s.Source == nil || s.Source.Kind == "folder" {
|
|
c.From = tr.repoOf(s)
|
|
}
|
|
c.Name, c.Source, c.Agents, c.Called, c.Note, c.Router = s.Name, s.Source, orNone(slices.Sorted(slices.Values(s.Agents))), s.Called, s.Note, s.Router
|
|
b.Skills = append(b.Skills, c)
|
|
}
|
|
subs := []*Subagent{}
|
|
for _, s := range sorted(l.Subagents, func(s *Subagent) string { return s.Name }) {
|
|
if l.ownedPart(s.Bundle) {
|
|
continue
|
|
}
|
|
c := *s
|
|
c.Skills, c.MCP = slices.Sorted(slices.Values(s.Skills)), slices.Sorted(slices.Values(s.MCP))
|
|
c.Agents = orNone(slices.Sorted(slices.Values(s.Agents)))
|
|
c.From = s.From.clone()
|
|
c.File, c.FileHash = "", "" // this computer's
|
|
subs = append(subs, &c)
|
|
}
|
|
b.Subagents = &subs
|
|
cmds := []*Command{}
|
|
for _, c := range sorted(l.Commands, func(c *Command) string { return c.Name }) {
|
|
x := *c
|
|
x.Agents = orNone(slices.Sorted(slices.Values(c.Agents)))
|
|
x.Taken = nil // files here, this computer's own
|
|
cmds = append(cmds, &x)
|
|
}
|
|
b.Commands = &cmds
|
|
rules := []*Rule{}
|
|
for _, r := range sorted(l.Rules, func(r *Rule) string { return r.Name }) {
|
|
x := *r
|
|
x.Paths = slices.Clone(r.Paths)
|
|
x.Agents = orNone(slices.Sorted(slices.Values(r.Agents)))
|
|
rules = append(rules, &x)
|
|
}
|
|
b.Rules = &rules
|
|
hooks := []*Hook{}
|
|
for _, h := range sorted(l.Hooks, func(h *Hook) string { return h.Name }) {
|
|
if l.ownedPart(h.Bundle) {
|
|
continue
|
|
}
|
|
c := *h
|
|
c.Agents = orNone(slices.Sorted(slices.Values(h.Agents)))
|
|
hooks = append(hooks, &c)
|
|
}
|
|
b.Hooks = &hooks
|
|
envs := []*EnvVar{}
|
|
for _, e := range sorted(l.Env, func(e *EnvVar) string { return e.Name }) {
|
|
c := *e
|
|
c.Agents = orNone(slices.Sorted(slices.Values(e.Agents)))
|
|
envs = append(envs, &c)
|
|
}
|
|
b.Env = &envs
|
|
b.Bili = carriedBili()
|
|
b.ClaudePlugins = carriedClaudePlugins()
|
|
return b, nil
|
|
}
|
|
|
|
func sorted[T any](xs []T, key func(T) string) []T {
|
|
return slices.SortedFunc(slices.Values(xs), func(a, b T) int { return strings.Compare(key(a), key(b)) })
|
|
}
|
|
|
|
func orNone(xs []string) []string {
|
|
if xs == nil {
|
|
return []string{}
|
|
}
|
|
return xs
|
|
}
|
|
|
|
// readSkills is each skill folder's files. Links in it, .git and what
|
|
// isn't a plain file stay out. What goes is chosen smallest first across
|
|
// every skill, so the text of them all comes before any big file.
|
|
func readSkills(dirs []string) []*CarriedSkill { return readSkillsMax(dirs, maxCarried, maxCarriedAll) }
|
|
|
|
// readSkillsMax is readSkills with a file's and the whole's budget given.
|
|
func readSkillsMax(dirs []string, perFile, all int64) []*CarriedSkill {
|
|
type file struct {
|
|
skill int
|
|
rel, p string
|
|
size int64
|
|
runs bool
|
|
}
|
|
var files []file
|
|
out := make([]*CarriedSkill, len(dirs))
|
|
for i, dir := range dirs {
|
|
out[i] = &CarriedSkill{Files: map[string][]byte{}}
|
|
filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
if d.IsDir() {
|
|
if p != dir && (d.Name() == ".git" || d.Name() == marker) {
|
|
return filepath.SkipDir
|
|
}
|
|
return nil
|
|
}
|
|
if !d.Type().IsRegular() || d.Name() == marker {
|
|
return nil
|
|
}
|
|
rel, err := filepath.Rel(dir, p)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
fi, err := d.Info()
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
files = append(files, file{i, filepath.ToSlash(rel), p, fi.Size(), fi.Mode().Perm()&0o111 != 0})
|
|
return nil
|
|
})
|
|
}
|
|
// smallest first, and the same order for the same files every time
|
|
slices.SortFunc(files, func(a, b file) int {
|
|
return cmp.Or(cmp.Compare(a.size, b.size), cmp.Compare(a.skill, b.skill), strings.Compare(a.rel, b.rel))
|
|
})
|
|
budget := all
|
|
for _, f := range files {
|
|
c := out[f.skill]
|
|
if f.size > perFile || f.size > budget {
|
|
c.Left = append(c.Left, f.rel)
|
|
continue
|
|
}
|
|
data, err := os.ReadFile(f.p)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
if n := int64(len(data)); n > perFile || n > budget { // grew since
|
|
c.Left = append(c.Left, f.rel)
|
|
continue
|
|
}
|
|
budget -= int64(len(data))
|
|
c.Files[f.rel] = data
|
|
if f.runs {
|
|
c.Exec = append(c.Exec, f.rel)
|
|
}
|
|
}
|
|
for _, c := range out {
|
|
slices.Sort(c.Exec)
|
|
slices.Sort(c.Left)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// check refuses a bundle that would write outside the library: a name
|
|
// that isn't one, a file's path that climbs out of its skill.
|
|
func (b *Bundle) check() error {
|
|
for _, s := range b.Instructions.Sets {
|
|
if err := checkName("set", s.ID); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
for id := range b.Texts {
|
|
if id != defaultSet && !slices.ContainsFunc(b.Instructions.Sets, func(s InstrSet) bool { return s.ID == id }) {
|
|
return fmt.Errorf("a text for no set, %q", id)
|
|
}
|
|
}
|
|
for id := range b.Extra {
|
|
if err := checkAgent(id); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
for _, s := range b.MCP {
|
|
if s == nil {
|
|
return fmt.Errorf("an empty server")
|
|
}
|
|
if err := s.check(); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
seen := map[string]bool{}
|
|
for _, s := range b.Skills {
|
|
if s == nil {
|
|
return fmt.Errorf("an empty skill")
|
|
}
|
|
if err := checkName("skill", s.Name); err != nil {
|
|
return err
|
|
}
|
|
if seen[s.Name] {
|
|
return fmt.Errorf("the skill %s twice", s.Name)
|
|
}
|
|
seen[s.Name] = true
|
|
for _, rel := range slices.Concat(slices.Collect(maps.Keys(s.Files)), s.Left) {
|
|
if !localFile(rel) {
|
|
return fmt.Errorf("skill %s: %q is not a file in its folder", s.Name, rel)
|
|
}
|
|
}
|
|
}
|
|
if b.Subagents != nil {
|
|
seen := map[string]bool{}
|
|
for _, s := range *b.Subagents {
|
|
if s == nil {
|
|
return fmt.Errorf("an empty subagent")
|
|
}
|
|
// the name is the file's in every agent's folder; the agents
|
|
// are left as they come, as a skill's are: one a newer magpie
|
|
// gives subagents to is no target here and gets nothing
|
|
if !subagentNameRe.MatchString(s.Name) || slices.Contains(reservedSubagents, s.Name) {
|
|
return fmt.Errorf("the subagent name %q", s.Name)
|
|
}
|
|
if seen[s.Name] {
|
|
return fmt.Errorf("the subagent %s twice", s.Name)
|
|
}
|
|
seen[s.Name] = true
|
|
}
|
|
}
|
|
if b.Commands != nil {
|
|
seen := map[string]bool{}
|
|
for _, c := range *b.Commands {
|
|
if c == nil {
|
|
return fmt.Errorf("an empty slash command")
|
|
}
|
|
// the agents are left as they come, as a subagent's are
|
|
if !commandNameRe.MatchString(c.Name) {
|
|
return fmt.Errorf("the slash command name %q", c.Name)
|
|
}
|
|
if seen[c.Name] {
|
|
return fmt.Errorf("the slash command %s twice", c.Name)
|
|
}
|
|
seen[c.Name] = true
|
|
}
|
|
}
|
|
if b.Rules != nil {
|
|
seen := map[string]bool{}
|
|
for _, r := range *b.Rules {
|
|
if r == nil {
|
|
return fmt.Errorf("an empty rule")
|
|
}
|
|
// the agents are left as they come, as a subagent's are
|
|
if !commandNameRe.MatchString(r.Name) {
|
|
return fmt.Errorf("the rule name %q", r.Name)
|
|
}
|
|
if seen[r.Name] {
|
|
return fmt.Errorf("the rule %s twice", r.Name)
|
|
}
|
|
seen[r.Name] = true
|
|
}
|
|
}
|
|
if b.Env != nil {
|
|
seen := map[string]bool{}
|
|
for _, e := range *b.Env {
|
|
if e == nil {
|
|
return fmt.Errorf("an empty variable")
|
|
}
|
|
if err := e.check(); err != nil {
|
|
return err
|
|
}
|
|
if seen[e.Name] {
|
|
return fmt.Errorf("the variable %s twice", e.Name)
|
|
}
|
|
seen[e.Name] = true
|
|
}
|
|
}
|
|
if b.Plugins != nil {
|
|
seen := map[string]bool{}
|
|
for _, p := range *b.Plugins {
|
|
if p == nil {
|
|
return fmt.Errorf("an empty plugin")
|
|
}
|
|
// its folder's name in the library
|
|
if p.Name == "" || pluginSlug(p.Name) != p.Name {
|
|
return fmt.Errorf("the plugin name %q", p.Name)
|
|
}
|
|
if seen[p.Name] {
|
|
return fmt.Errorf("the plugin %s twice", p.Name)
|
|
}
|
|
seen[p.Name] = true
|
|
for _, rel := range slices.Concat(slices.Collect(maps.Keys(p.Files)), p.Left) {
|
|
if !localFile(rel) {
|
|
return fmt.Errorf("plugin %s: %q is not a file in its folder", p.Name, rel)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if b.Hooks != nil {
|
|
seen := map[string]bool{}
|
|
for _, h := range *b.Hooks {
|
|
if h == nil {
|
|
return fmt.Errorf("an empty hook")
|
|
}
|
|
// the event and agents are left as they come: one a newer
|
|
// magpie knows and this one doesn't is a problem on the
|
|
// agent it is given to (syncHooks), not a refused library
|
|
if err := checkName("hook", h.Name); err != nil {
|
|
return err
|
|
}
|
|
if strings.TrimSpace(h.Command) == "" {
|
|
return fmt.Errorf("the hook %s has no command", h.Name)
|
|
}
|
|
if seen[h.Name] {
|
|
return fmt.Errorf("the hook %s twice", h.Name)
|
|
}
|
|
seen[h.Name] = true
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// localFile reports whether rel, with /, names a file inside a folder:
|
|
// not absolute, no .., no \ to be read as a separator elsewhere.
|
|
func localFile(rel string) bool {
|
|
return rel != "" && !strings.ContainsAny(rel, "\\:\x00") && filepath.IsLocal(filepath.FromSlash(rel)) &&
|
|
!slices.Contains(strings.Split(rel, "/"), "..")
|
|
}
|
|
|
|
// WithoutSecrets empties the values of the servers' environment variables
|
|
// and headers that secret says hold one; their names stay, to be filled in.
|
|
func (b *Bundle) WithoutSecrets(secret func(string) bool) {
|
|
// billion-context.json holds no keys (bili takes a key's variable or
|
|
// its own store's name), except a storage DSN's password: a file
|
|
// naming one stays out, kept on each computer as it is
|
|
if b.Bili != nil && strings.Contains(strings.ToLower(*b.Bili), "dsn") {
|
|
b.Bili = nil
|
|
}
|
|
// a variable's name says nothing of what its value is: every value
|
|
// goes, the names stay
|
|
if b.Env != nil {
|
|
envs := []*EnvVar{}
|
|
for _, e := range *b.Env {
|
|
c := *e
|
|
c.Value = ""
|
|
envs = append(envs, &c)
|
|
}
|
|
b.Env = &envs
|
|
}
|
|
for i, s := range b.MCP {
|
|
c := *s
|
|
c.Env, c.Headers = blank(s.Env, secret), blank(s.Headers, secret)
|
|
c.Accounts = nil
|
|
for _, a := range s.Accounts {
|
|
a.Headers = blank(a.Headers, secret)
|
|
c.Accounts = append(c.Accounts, a)
|
|
}
|
|
// an OAuth app's secret is a key too; its client ID isn't
|
|
if s.OAuth != nil && s.OAuth.ClientSecret != "" {
|
|
a := *s.OAuth
|
|
a.ClientSecret = ""
|
|
c.OAuth = &a
|
|
}
|
|
b.MCP[i] = &c
|
|
}
|
|
}
|
|
|
|
func blank(m map[string]string, secret func(string) bool) map[string]string {
|
|
if m == nil {
|
|
return nil
|
|
}
|
|
out := map[string]string{}
|
|
for k, v := range m {
|
|
if secret(k) {
|
|
v = ""
|
|
}
|
|
out[k] = v
|
|
}
|
|
return out
|
|
}
|
|
|
|
// WithSecrets is b with the values WithoutSecrets emptied filled from the
|
|
// servers of the same name in have, so a bundle made without keys doesn't
|
|
// take away the ones kept here.
|
|
func (b *Bundle) WithSecrets(have *Bundle, secret func(string) bool) *Bundle {
|
|
if have == nil {
|
|
return b
|
|
}
|
|
out := *b
|
|
out.MCP = nil
|
|
if b.Env != nil && have.Env != nil {
|
|
envs := []*EnvVar{}
|
|
for _, e := range *b.Env {
|
|
c := *e
|
|
if i := slices.IndexFunc(*have.Env, func(h *EnvVar) bool { return h.Name == e.Name }); i >= 0 && c.Value == "" {
|
|
c.Value = (*have.Env)[i].Value
|
|
}
|
|
envs = append(envs, &c)
|
|
}
|
|
out.Env = &envs
|
|
}
|
|
for _, s := range b.MCP {
|
|
c := *s
|
|
i := slices.IndexFunc(have.MCP, func(h *Server) bool { return h.Name == s.Name })
|
|
if i >= 0 {
|
|
c.Env, c.Headers = filled(s.Env, have.MCP[i].Env, secret), filled(s.Headers, have.MCP[i].Headers, secret)
|
|
c.Accounts = nil
|
|
for _, a := range s.Accounts {
|
|
if j := slices.IndexFunc(have.MCP[i].Accounts, func(h Account) bool { return h.ID == a.ID }); j >= 0 {
|
|
a.Headers = filled(a.Headers, have.MCP[i].Accounts[j].Headers, secret)
|
|
}
|
|
c.Accounts = append(c.Accounts, a)
|
|
}
|
|
// the same app's secret, kept here
|
|
if h := have.MCP[i].OAuth; s.OAuth != nil && s.OAuth.ClientSecret == "" && h != nil && h.ClientID == s.OAuth.ClientID {
|
|
a := *s.OAuth
|
|
a.ClientSecret = h.ClientSecret
|
|
c.OAuth = &a
|
|
}
|
|
}
|
|
out.MCP = append(out.MCP, &c)
|
|
}
|
|
return &out
|
|
}
|
|
|
|
func filled(m, have map[string]string, secret func(string) bool) map[string]string {
|
|
if m == nil {
|
|
return nil
|
|
}
|
|
out := maps.Clone(m)
|
|
for k, v := range m {
|
|
if v == "" && secret(k) && have[k] != "" {
|
|
out[k] = have[k]
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Put makes the library what b says — its instructions, servers and
|
|
// skills in place of the ones here — and writes it into the agents, which
|
|
// keep whatever of theirs isn't magpie's. The skills are written aside
|
|
// first, and only once all of them are there does any go in; a skill
|
|
// replaced or taken out is kept with the backups, and so is an
|
|
// instructions file that changes. A skill that comes linked to a folder
|
|
// this computer has too is linked to it; else it comes as its files. A
|
|
// skill whose files are as they are here is left alone. The subagents
|
|
// replace the ones here too, unless b is from a magpie that didn't carry
|
|
// them.
|
|
func Put(b *Bundle) (*Result, error) {
|
|
if err := b.check(); err != nil {
|
|
return nil, err
|
|
}
|
|
biliWrote := false
|
|
var fetch []*CarriedPlugin
|
|
var gone, fetchS []string
|
|
var plProblems, skProblems []Problem
|
|
res, err := change(func(l *Library) error {
|
|
fetch, gone, fetchS, plProblems, skProblems = nil, nil, nil, nil, nil
|
|
if err := os.MkdirAll(skillsDir(), 0o755); err != nil {
|
|
return err
|
|
}
|
|
stage, err := os.MkdirTemp(Dir(), ".incoming-") // beside skills, to be renamed in
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer os.RemoveAll(stage)
|
|
// this computer's plugins' parts stand aside while the items are
|
|
// replaced, the bundle carrying none of them, and the plugins
|
|
// are put after (plugin_carry.go). A bundle from a magpie before
|
|
// plugins were carried has their parts as its own items, naming
|
|
// the other computer's folder: this computer's stay instead
|
|
held := l.holdPluginParts()
|
|
b := b
|
|
if b.Plugins == nil {
|
|
b = held.without(b)
|
|
}
|
|
|
|
keep, link := map[string]bool{}, map[string]string{}
|
|
// a skill carried as its source (skill_carry.go)
|
|
bySrc := map[string]*fromSource{}
|
|
for _, s := range b.Skills {
|
|
p := l.fromSourceHere(s)
|
|
if p != nil {
|
|
bySrc[s.Name] = p
|
|
if p.keep {
|
|
keep[s.Name] = true
|
|
continue
|
|
}
|
|
}
|
|
if cur := l.skill(s.Name); cur != nil && sameSource(cur.Source, s.Source) {
|
|
if have := readSkills([]string{realDir(skillDir(s.Name))})[0]; sameFiles(have, s) {
|
|
keep[s.Name] = true
|
|
continue
|
|
}
|
|
}
|
|
if src := s.Source; src != nil && src.Kind == "folder" && src.Dir != "" && isDir(src.Dir) {
|
|
if to, err := os.Readlink(skillDir(s.Name)); err == nil && filepath.Clean(to) == filepath.Clean(src.Dir) {
|
|
keep[s.Name] = true
|
|
} else {
|
|
link[s.Name] = src.Dir
|
|
}
|
|
continue
|
|
}
|
|
if err := writeSkill(filepath.Join(stage, s.Name), s); err != nil {
|
|
return fmt.Errorf("skill %s: %w", s.Name, err)
|
|
}
|
|
if err := keepLeft(filepath.Join(stage, s.Name), realDir(skillDir(s.Name)), s); err != nil {
|
|
return fmt.Errorf("skill %s: %w", s.Name, err)
|
|
}
|
|
if p != nil {
|
|
p.whole(filepath.Join(stage, s.Name), s)
|
|
}
|
|
}
|
|
|
|
// every skill's files are ready: out with the old ones
|
|
aside := filepath.Join(BackupDir(), time.Now().Format("2006-01-02_15-04-05.000"), "skills")
|
|
out := func(name string) error {
|
|
p := skillDir(name)
|
|
fi, err := os.Lstat(p)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
if linkEntry(fi) {
|
|
return os.Remove(p) // a folder of the user's: only the link goes
|
|
}
|
|
if err := os.MkdirAll(aside, 0o700); err != nil {
|
|
return err
|
|
}
|
|
return move(p, filepath.Join(aside, name))
|
|
}
|
|
for _, s := range l.Skills {
|
|
if !keep[s.Name] {
|
|
if err := out(s.Name); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
skills := []*Skill{}
|
|
for _, s := range b.Skills {
|
|
// turned off here stays off here: that is this computer's own
|
|
off := l.skill(s.Name) != nil && l.skill(s.Name).OffHere
|
|
n := &Skill{Name: s.Name, Source: s.Source, Agents: slices.Clone(orNone(s.Agents)), OffHere: off, Called: s.Called, Note: s.Note, Router: s.Router}
|
|
// where it came from: the other computer's trace, else what
|
|
// this one has found itself (Group again) for the same skill,
|
|
// which a bundle from before From was carried says nothing of
|
|
n.From = s.From
|
|
if cur := l.skill(s.Name); cur != nil && sameSource(cur.Source, s.Source) {
|
|
if n.From == "" {
|
|
n.From = cur.From
|
|
}
|
|
n.Gone = cur.Gone // kept on this computer only
|
|
n.Home = cur.Home // where it was in this computer's agents
|
|
if keep[s.Name] {
|
|
// the same files: what was fetched is still known
|
|
n.Hash, n.Own, n.Commit = cur.Hash, cur.Own, cur.Commit
|
|
}
|
|
}
|
|
if len(s.Left) > 0 {
|
|
dir := filepath.Join(stage, s.Name)
|
|
if keep[s.Name] {
|
|
dir = realDir(skillDir(s.Name))
|
|
}
|
|
n.Missing = notIn(dir, s.Left)
|
|
}
|
|
if p := bySrc[s.Name]; p != nil {
|
|
n.Hash, n.Own, n.Commit, n.Pending = p.hash, p.own, p.commit, p.pending
|
|
if p.fetch {
|
|
fetchS = append(fetchS, s.Name)
|
|
}
|
|
if p.changed {
|
|
skProblems = append(skProblems, changedHere(s.Name))
|
|
}
|
|
}
|
|
skills = append(skills, n)
|
|
if keep[s.Name] {
|
|
continue
|
|
}
|
|
if err := out(s.Name); err != nil { // one of no skill's, in the way
|
|
return err
|
|
}
|
|
if dir, ok := link[s.Name]; ok {
|
|
if err := dirLink(dir, skillDir(s.Name)); err != nil {
|
|
if err := copyDir(dir, skillDir(s.Name)); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
continue
|
|
}
|
|
if err := os.Rename(filepath.Join(stage, s.Name), skillDir(s.Name)); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
l.Skills = skills
|
|
|
|
// the instructions: every text here that b hasn't goes, kept first
|
|
kept := newBackups()
|
|
l.kept = kept
|
|
texts := map[string]string{}
|
|
// a set linked here to a file of the user's keeps it: the file is
|
|
// given the text b has for the set, and never emptied for a text
|
|
// b hasn't
|
|
files := map[string]string{}
|
|
for _, s := range l.sets() {
|
|
if s.File != "" {
|
|
files[s.ID] = s.File
|
|
} else {
|
|
texts[setPath(s.ID)] = ""
|
|
}
|
|
}
|
|
for id := range extras() {
|
|
texts[extraPath(id)] = ""
|
|
}
|
|
for id, text := range b.Texts {
|
|
if files[id] == "" {
|
|
texts[setPath(id)] = text
|
|
}
|
|
}
|
|
for id, text := range b.Extra {
|
|
texts[extraPath(id)] = text
|
|
}
|
|
for _, p := range slices.Sorted(maps.Keys(texts)) {
|
|
if readText(p) == strings.TrimSpace(texts[p]) {
|
|
continue
|
|
}
|
|
if err := kept.keep("library", p); err != nil {
|
|
return err
|
|
}
|
|
if err := writeText(p, texts[p]); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
l.Instructions = Instructions{Agents: slices.Sorted(slices.Values(orNone(b.Instructions.Agents))),
|
|
Sets: slices.Clone(b.Instructions.Sets), Active: b.Instructions.Active}
|
|
for i := range l.Instructions.Sets {
|
|
s := &l.Instructions.Sets[i]
|
|
s.File = files[s.ID]
|
|
if text := strings.TrimSpace(b.Texts[s.ID]); s.File != "" && text != "" {
|
|
if err := l.putText(s.File, text); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
l.putServers(b.MCP)
|
|
l.Icons = maps.Clone(b.Icons)
|
|
// the agents are written on the sync change runs: what magpie
|
|
// wrote here (Applied) decides, file by file, what is its own
|
|
if b.Subagents != nil {
|
|
subs := []*Subagent{}
|
|
for _, s := range *b.Subagents {
|
|
c := *s
|
|
c.Skills, c.MCP, c.Agents = slices.Clone(s.Skills), slices.Clone(s.MCP), slices.Clone(orNone(s.Agents))
|
|
c.From = s.From.clone()
|
|
// the file it is kept in here stays this computer's
|
|
c.File, c.FileHash = "", ""
|
|
if here := l.subagent(s.Name); here != nil {
|
|
c.File, c.FileHash = here.File, here.FileHash
|
|
}
|
|
subs = append(subs, &c)
|
|
}
|
|
for _, s := range l.Subagents {
|
|
if !slices.ContainsFunc(subs, func(c *Subagent) bool { return c.Name == s.Name }) {
|
|
dropSubagentFile(s)
|
|
}
|
|
}
|
|
l.Subagents = subs
|
|
}
|
|
// slash commands the same way: Applied.Commands decides
|
|
if b.Commands != nil {
|
|
cmds := []*Command{}
|
|
for _, c := range *b.Commands {
|
|
x := *c
|
|
x.Agents = slices.Clone(orNone(c.Agents))
|
|
// the files this computer's was imported from stay its
|
|
// own: written as they were while it says the same
|
|
x.Taken = nil
|
|
if have := l.command(c.Name); have != nil {
|
|
x.Taken = have.Taken
|
|
}
|
|
cmds = append(cmds, &x)
|
|
}
|
|
l.Commands = cmds
|
|
}
|
|
// rules the same way: Applied.Rules decides
|
|
if b.Rules != nil {
|
|
rules := []*Rule{}
|
|
for _, r := range *b.Rules {
|
|
x := *r
|
|
x.Paths, x.Agents = slices.Clone(r.Paths), slices.Clone(orNone(r.Agents))
|
|
rules = append(rules, &x)
|
|
}
|
|
l.Rules = rules
|
|
}
|
|
// the same for hooks: Applied.Hooks decides, entry by entry,
|
|
// what magpie takes out of each agent's file here
|
|
if b.Hooks != nil {
|
|
hooks := []*Hook{}
|
|
for _, h := range *b.Hooks {
|
|
c := *h
|
|
c.Agents = slices.Clone(orNone(h.Agents))
|
|
hooks = append(hooks, &c)
|
|
}
|
|
l.Hooks = hooks
|
|
}
|
|
// variables the same way: Applied.Env decides what is taken out
|
|
if b.Env != nil {
|
|
envs := []*EnvVar{}
|
|
for _, e := range *b.Env {
|
|
c := *e
|
|
c.Agents = slices.Clone(orNone(e.Agents))
|
|
envs = append(envs, &c)
|
|
}
|
|
l.Env = envs
|
|
}
|
|
l.putBack(held)
|
|
if b.Plugins != nil {
|
|
fetch, gone, plProblems = l.putPlugins(*b.Plugins, stage)
|
|
}
|
|
if b.Bili != nil {
|
|
wrote, err := putBili(*b.Bili, kept)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
biliWrote = wrote
|
|
}
|
|
if b.ClaudePlugins != nil {
|
|
if err := putClaudePlugins(b.ClaudePlugins, kept); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
if err == nil && biliWrote {
|
|
// the running bilis read their settings again (best effort: one
|
|
// started later reads the file anyway)
|
|
biliReload()
|
|
}
|
|
if err == nil {
|
|
removePluginDirs(gone)
|
|
res.Problems = append(res.Problems, plProblems...)
|
|
res.Problems = append(res.Problems, skProblems...)
|
|
fetchPlugins(fetch, res)
|
|
fetchSkills(fetchS, res)
|
|
}
|
|
return res, err
|
|
}
|
|
|
|
func sameSource(a, b *Source) bool {
|
|
return (a == nil) == (b == nil) && (a == nil || *a == *b)
|
|
}
|
|
|
|
// sameFiles reports whether a folder here has what c carries.
|
|
func sameFiles(have, c *CarriedSkill) bool {
|
|
return maps.EqualFunc(have.Files, c.Files, bytes.Equal) && slices.Equal(have.Exec, sorted(c.Exec, func(s string) string { return s }))
|
|
}
|
|
|
|
// writeSkill writes a carried skill's files into a new folder.
|
|
func writeSkill(dir string, s *CarriedSkill) error {
|
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
return err
|
|
}
|
|
for _, rel := range slices.Sorted(maps.Keys(s.Files)) {
|
|
p := filepath.Join(dir, filepath.FromSlash(rel))
|
|
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
|
return err
|
|
}
|
|
mode := fs.FileMode(0o644)
|
|
if slices.Contains(s.Exec, rel) {
|
|
mode = 0o755
|
|
}
|
|
if err := os.WriteFile(p, s.Files[rel], mode); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// keepLeft copies into a skill being put (at dir) the files the other
|
|
// computer left out as too big to carry that the skill here has, so it
|
|
// is put with them, not without.
|
|
func keepLeft(dir, here string, s *CarriedSkill) error {
|
|
for _, rel := range s.Left {
|
|
if _, ok := s.Files[rel]; ok {
|
|
continue
|
|
}
|
|
from := filepath.Join(here, filepath.FromSlash(rel))
|
|
fi, err := os.Lstat(from)
|
|
if err != nil || !fi.Mode().IsRegular() {
|
|
continue
|
|
}
|
|
to := filepath.Join(dir, filepath.FromSlash(rel))
|
|
if err := os.MkdirAll(filepath.Dir(to), 0o755); err != nil {
|
|
return err
|
|
}
|
|
in, err := os.Open(from)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
out, err := os.OpenFile(to, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, fi.Mode().Perm())
|
|
if err == nil {
|
|
_, err = io.Copy(out, in)
|
|
err = errors.Join(err, out.Close())
|
|
}
|
|
in.Close()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func isDir(p string) bool {
|
|
fi, err := os.Stat(p)
|
|
return err == nil && fi.IsDir()
|
|
}
|
|
|
|
// Changed is when the library was last changed: library.json, or a file
|
|
// of its own (links not followed), or billion-context.json or Claude
|
|
// Code's plugin records, which a sync carries with it.
|
|
func Changed() time.Time {
|
|
var t time.Time
|
|
if fi, err := os.Stat(path()); err == nil {
|
|
t = fi.ModTime()
|
|
}
|
|
if b := biliChanged(); b.After(t) {
|
|
t = b
|
|
}
|
|
if c := claudePluginsChanged(); c.After(t) {
|
|
t = c
|
|
}
|
|
filepath.WalkDir(Dir(), func(p string, d fs.DirEntry, err error) error {
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
if fi, err := d.Info(); err == nil && fi.ModTime().After(t) {
|
|
t = fi.ModTime()
|
|
}
|
|
return nil
|
|
})
|
|
return t
|
|
}
|