diff --git a/docs/subsystems/skill-router.md b/docs/subsystems/skill-router.md index 93b50f68a..596cc1bf2 100644 --- a/docs/subsystems/skill-router.md +++ b/docs/subsystems/skill-router.md @@ -13,6 +13,7 @@ With the Library's switch "Skill router" on, each agent's skills folder is given | Entry | `placeRouter` writes `routerDir(t.Skills)` (`/skill-router//`): its SKILL.md and, under `.skills/`, a link to each listed skill's folder. The folder's entry `magpie-skills` is a link to it (`routerOurs` knows magpie's by where it leads). `Applied.Router` records it; with nothing listed, the entry and its folder go. | `placeRouter`, `writeRouter`, `routerOurs` | | SKILL.md | Front matter `name: magpie-skills` and a description of at most 1024 bytes (`routerDescMax`: Codex refuses a longer one), naming the skills with as much of each description as fits, cut on a whole character (`routerDesc`). The body gives each skill's whole description and the path of its SKILL.md through the agent's own folder (`/magpie-skills/.skills//SKILL.md`). `.skills` is hidden, so the agents that look for skills in every folder under theirs (Codex, OpenCode, Pi) don't find a listed skill twice. | `writeRouter`, `routerDesc` | | Claude Code's Read rules | Claude Code asks before it reads outside its project, its own skills folder too, and checks both the path given and where a link leads (2.1.316). For Claude Code (`claude`, any profile; not a plugin agent) magpie adds `permissions.allow` rules to its settings.json: `Read(///**)` and `Read(///**)`, or one for each listed skill whose folder is elsewhere (`routerRules`; Windows paths as `/c/...`, `claudePath`). `Applied.RouterRules` records magpie's, so it takes out only those and keeps the user's own (`offList`, as for `permissions.deny`). | `routerRules`, `routerAllow` | +| Claude Code's `/name` | A listed skill would be no `/name` of Claude Code's, so for each one `routerCommands` writes a slash command, `/commands/.md` (`routerCommandsDir`, beside the settings.json `routerRules` writes; `claude`, any profile; not a plugin agent or WSL). It has the skill's description and `disable-model-invocation: true`, and its body has the agent read the skill's SKILL.md at the router's path and follow it, with `$ARGUMENTS`. Claude Code 2.1.316 (real runs in a sandbox HOME) lists it under `/` with the description, sends that description in no request, and `/name` reads and follows the skill. It goes in the commands folder, not the skills folder, because Crush, DevEco Code and Kimi Code read `~/.claude/skills` too and take no notice of the flag. `Applied.RouterCommands` records magpie's files with their hash (`syncOwnFiles`): a stub the user changed is theirs. No stub is written where a Library command of that name is given to Claude Code (`syncCommands` takes the stub's file over), or where the user has a command file of that name. The command import (`findCommands`) leaves the stubs out. With the router off, or the skill kept direct, the stub goes. | `routerCommands`, `routerCommand`, `routedAt`; `syncCommands` in [`commands.go`](../../internal/library/commands.go) | | GUI | Under the skill list on the Library's Skills tab: a row "Skill router" with its switch (`.lib-skillrouter`, `.lib-switch`), and with it on, one line for each reason an agent keeps its own links, naming those agents (`.lib-hub-why[data-why]`). `none` is an agent whose folder takes the router but has no skill listed (`AgentView.SkillRouter`, `routerNone`: nothing ticked for it, or each kept direct), and `found` names the agents whose own folder holds skills the library lacks, which the router can't list and each stays in the prompt. Each skill the router may list has a button (`.lib-routedirect`, `aria-pressed`) that keeps it out of the router or lists it again; a skill kept out shows "Not through the router" (`.lib-direct`). | `skillRouterPart` in [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) | | Sessions | A Read of `…/magpie-skills/.skills//SKILL.md` counts as the use of `` (Claude Code, Alma, Droid: `routedSkill`; Codex counts any SKILL.md it reads). Calling up `magpie-skills` itself is counted as a Skill tool call and no skill (`routerSkill`), so a routed use is counted once. | `routedSkill`, `state.tool`, `ccTool` in [`internal/sessions`](../../internal/sessions/sessions.go) | @@ -26,7 +27,7 @@ With the Library's switch "Skill router" on, each agent's skills folder is given ## Constraints and failure behavior - An agent reads its skills when it starts: a change reaches a running agent on its next start. -- A skill listed by the router is not a `/name` command of the agent's. A skill the user types is kept direct, and one with `disable-model-invocation` is never listed. +- A skill listed by the router stays a `/name` of Claude Code's through its stub. In the other agents it is not a `/name` command: a skill the user types there is kept direct. One with `disable-model-invocation` is never listed. - The user's own `magpie-skills`, in the folder or in the Library, is never written over. The agent keeps every link, and the page says why (`own`, `taken`). - Turning the switch off writes every link again, removes the entry, its folder and magpie's Read rules, and leaves the user's own rules. - Alma reads Claude Code's, Codex's and `~/.agents/skills` besides its own `~/.config/alma/skills`, and keeps one skill per name, its own first (personal > Claude Code > Codex > `~/.agents`: `loadSkills` in Alma's `electron/skills/skillsManager.ts`). With the router on for Alma, Alma's `magpie-skills` is the one it keeps, listing Alma's skills. When Alma's folder has no entry (every skill of Alma's kept direct, or none ticked for it), Alma takes Claude Code's (or Codex's) `magpie-skills` and is offered that agent's skills, as it was offered their links before the router; Alma's Settings › Skills turns a folder off. Seen with a real Alma 0.4.738 in a sandbox HOME (#5722). @@ -35,7 +36,7 @@ With the Library's switch "Skill router" on, each agent's skills folder is given ## Verification ```sh -mote-run go test -tags nogui ./internal/library -run 'SkillRouter|RouterDesc|RouterRules' -count=1 +mote-run go test -tags nogui ./internal/library -run 'SkillRouter|RouterDesc|RouterRules|Command' -count=1 mote-run go test -tags nogui ./internal/sessions -run 'Routed' -count=1 mote-run go test -tags nogui ./internal/gateway -run 'SkillBod' -count=1 mote-run node --test internal/gui/tests/skill-router.test.cjs diff --git a/internal/library/command_import.go b/internal/library/command_import.go index adb79496b..8c4d4e935 100644 --- a/internal/library/command_import.go +++ b/internal/library/command_import.go @@ -241,7 +241,8 @@ func (l *Library) findCommands(targets []*Target) *CommandProbe { } var mine []SubagentFile if a := l.Applied[id]; a != nil { - mine = a.Commands + // the skill router's stubs (routerCommands) are magpie's too + mine = slices.Concat(a.Commands, a.RouterCommands) } for _, r := range commandReads(id, sp) { ents, err := os.ReadDir(r[0]) diff --git a/internal/library/commands.go b/internal/library/commands.go index f884b4565..91b220801 100644 --- a/internal/library/commands.go +++ b/internal/library/commands.go @@ -230,7 +230,16 @@ func (l *Library) syncCommands(t *Target, b *backups, res *Result) { } files = append(files, ownFile{name: c.Name, path: path, body: func() []byte { return sp.render(c) }}) } - a.Commands = syncOwnFiles(t, "command", a.Commands, files, b, res) + // a stub the skill router wrote by that name (routerCommands) is + // magpie's to write over: the library's command takes its place + had := a.Commands + for _, f := range files { + if i := slices.IndexFunc(a.RouterCommands, func(r SubagentFile) bool { return r.Path == f.path }); i >= 0 { + had = append(slices.Clip(had), a.RouterCommands[i]) + a.RouterCommands = slices.Delete(a.RouterCommands, i, i+1) + } + } + a.Commands = syncOwnFiles(t, "command", had, files, b, res) } // ---- changes --------------------------------------------------------------- diff --git a/internal/library/library.go b/internal/library/library.go index 385dbcafb..19857c365 100644 --- a/internal/library/library.go +++ b/internal/library/library.go @@ -180,6 +180,9 @@ type Applied struct { // RouterRules are the rules magpie put in Claude Code's // permissions.allow so it reads a listed skill without asking. RouterRules []string `json:"routerRules,omitempty"` + // RouterCommands are the slash commands magpie wrote for the skills + // the router lists (routerCommands), kept as Commands are + RouterCommands []SubagentFile `json:"routerCommands,omitempty"` } // empty is whether a holds nothing magpie wrote: a sync that only looked @@ -189,7 +192,7 @@ type Applied struct { func (a *Applied) empty() bool { return !a.Instructions && a.InstrHash == "" && len(a.MCP) == 0 && len(a.Skills) == 0 && len(a.ToolsOff) == 0 && len(a.ToolRules) == 0 && len(a.Hooks) == 0 && len(a.Env) == 0 && - len(a.Subagents) == 0 && len(a.Commands) == 0 && len(a.Startup) == 0 && len(a.Picked) == 0 && !a.Router && len(a.RouterRules) == 0 + len(a.Subagents) == 0 && len(a.Commands) == 0 && len(a.Startup) == 0 && len(a.Picked) == 0 && !a.Router && len(a.RouterRules) == 0 && len(a.RouterCommands) == 0 } var mu lock // one change at a time, from the page or the CLI's process diff --git a/internal/library/skill_router.go b/internal/library/skill_router.go index e6d75c5f4..11f2b50f3 100644 --- a/internal/library/skill_router.go +++ b/internal/library/skill_router.go @@ -19,7 +19,8 @@ package library // // What stays a link of its own (routedFor): // - a skill the user keeps direct (Skill.Router), to be a /command of -// the agent's, or always in its prompt; +// an agent other than Claude Code, whose routed skills each have a +// slash command (routerCommands), or always in its prompt; // - one whose SKILL.md sets disable-model-invocation: it is for the // user to type, which a listed skill can't be; // - one the agent finds in ~/.agents/skills anyway. @@ -182,6 +183,7 @@ func (l *Library) placeRouter(t *Target, routed map[string]bool, a *Applied, res if len(routed) == 0 { if !a.Router { l.routerAllow(t, nil, a, res) + l.routerCommands(t, nil, a, res) return } if routerOurs(p) { @@ -194,6 +196,7 @@ func (l *Library) placeRouter(t *Target, routed map[string]bool, a *Applied, res os.RemoveAll(dir) a.Router = false l.routerAllow(t, nil, a, res) + l.routerCommands(t, nil, a, res) return } changed, err := writeRouter(dir, t.Skills, routed) @@ -218,6 +221,7 @@ func (l *Library) placeRouter(t *Target, routed map[string]bool, a *Applied, res res.changed(id) } l.routerAllow(t, routerRules(t, routed), a, res) + l.routerCommands(t, routed, a, res) } // routerRules are the rules that let Claude Code read a listed skill's @@ -354,17 +358,15 @@ func writeRouter(dir, skills string, routed map[string]bool) (bool, error) { var list []entry for _, n := range names { q := filepath.Join(links, n) - at := filepath.Join(realDir(skills), RouterSkill, ".skills", n, "SKILL.md") if to, ok := linkTarget(q); !ok || filepath.Clean(to) != filepath.Clean(skillDir(n)) { os.RemoveAll(q) - if err := dirLink(skillDir(n), q); err != nil { - // no link here (Windows without the right to): the library's - // own folder is read instead - at = filepath.Join(skillDir(n), "SKILL.md") - } else { + // no link here (Windows without the right to): the library's + // own folder is read instead (routedAt) + if dirLink(skillDir(n), q) == nil { changed = true } } + at := filepath.Join(routedAt(dir, skills, n), "SKILL.md") m, _ := readMeta(skillDir(n)) list = append(list, entry{n, m.Description, at}) } @@ -396,6 +398,99 @@ func writeRouter(dir, skills string, routed map[string]bool) (bool, error) { return true, os.Rename(tmp, md) } +// routedAt is the folder of the routed skill n the router's SKILL.md +// names: through the agent's own skills folder, where the router's folder +// dir links to it, else the library's own. +func routedAt(dir, skills, n string) string { + if to, ok := linkTarget(filepath.Join(dir, ".skills", n)); ok && filepath.Clean(to) == filepath.Clean(skillDir(n)) { + return filepath.Join(realDir(skills), RouterSkill, ".skills", n) + } + return skillDir(n) +} + +// routerCommands keeps each routed skill a /name of Claude Code's (RoyShen +// on X: with the router on, / no longer picked a skill). For each one it +// writes a slash command, /commands/.md, that has the +// agent read the skill's SKILL.md and follow it. The command says +// disable-model-invocation, so Claude Code lists it under / with the +// skill's description but leaves it out of the model's prompt (Claude +// Code 2.1.316, tried in a sandbox HOME: the description is in no request, +// and /name reads and follows the skill). They go in Claude Code's own +// commands folder, not its skills folder, which Crush, DevEco Code and +// Kimi Code read too, and which would give them every description again. +// What magpie wrote is recorded as a command's is (Applied.RouterCommands, +// syncOwnFiles); a library command or a file of the user's by that name +// stays, and that skill gets none. Other agents: none. +func (l *Library) routerCommands(t *Target, routed map[string]bool, a *Applied, res *Result) { + if len(routed) == 0 && len(a.RouterCommands) == 0 { + return + } + var want []ownFile + if dir := routerCommandsDir(t); dir != "" { + had := map[string]bool{} + for _, f := range a.RouterCommands { + had[f.Path] = true + } + taken := map[string]bool{} + for _, f := range a.Commands { + taken[f.Path] = true + } + rdir := routerDir(t.Skills) + for _, n := range slices.Sorted(maps.Keys(routed)) { + if strings.ContainsAny(n, `:/\`) { + continue + } + if c := l.command(n); c != nil && slices.Contains(c.Agents, t.Agent.ID) { + continue + } + path := filepath.Join(dir, n+".md") + if taken[path] { + continue + } + at := routedAt(rdir, t.Skills, n) + body := routerCommand(n, at) + if _, err := os.Lstat(path); err == nil && !had[path] { + // the user's own command by that name, unless it is what + // magpie would write + if cur, err := os.ReadFile(path); err != nil || !slices.Equal(cur, body) { + continue + } + } + want = append(want, ownFile{name: n, path: path, body: func() []byte { return body }}) + } + } + if l.kept == nil { + l.kept = newBackups() + } + a.RouterCommands = syncOwnFiles(t, "command", a.RouterCommands, want, l.kept, res) +} + +// routerCommandsDir is Claude Code's commands folder, beside the settings +// routerRules writes; "" for any other agent. +func routerCommandsDir(t *Target) string { + if t.Agent == nil || t.Agent.Plugin != "" || t.Settings == "" || t.Agent.WSL != "" { + return "" + } + if id, _, _ := strings.Cut(t.Agent.ID, "@"); id != "claude" { + return "" + } + return filepath.Join(filepath.Dir(t.Settings), "commands") +} + +// routerCommand is the slash command for the routed skill n, whose folder +// is at. +func routerCommand(n, at string) []byte { + m, _ := readMeta(skillDir(n)) + kv := [][2]string{} + if m.Description != "" { + kv = append(kv, [2]string{"description", yamlStr(m.Description)}) + } + kv = append(kv, [2]string{"disable-model-invocation", "true"}) + body := fmt.Sprintf("Use the user's skill %s: read `%s` and follow it. A file or script it names is in `%s`, beside it.\n\n$ARGUMENTS\n", + n, filepath.Join(at, "SKILL.md"), at) + return frontmatter(kv, body) +} + // routerDesc is the router's description: what it is, then each skill's // name with the start of its own description, cut to what Codex takes. func routerDesc(names []string, desc func(int) string) string { diff --git a/internal/library/skill_router_test.go b/internal/library/skill_router_test.go index c644443c1..dce9f4473 100644 --- a/internal/library/skill_router_test.go +++ b/internal/library/skill_router_test.go @@ -269,3 +269,102 @@ func TestRouterRulesLibraryFolder(t *testing.T) { t.Fatalf("windows path: %q", got) } } + +// With the router on, a skill it lists is still a /name of Claude Code's +// (RoyShen on X): a slash command in its commands folder that reads the +// skill's SKILL.md, said disable-model-invocation so it stays out of the +// model's prompt. A skill kept direct, or one of the user's own commands +// by that name, gets none; a library command by that name takes its +// place; router off, they go. +func TestSkillRouterKeepsSlashCommands(t *testing.T) { + h := sandbox(t) + src := filepath.Join(h, "src") + skill(t, filepath.Join(src, "pdf"), "pdf", "Read PDFs. Use for any .pdf file") + skill(t, filepath.Join(src, "xlsx"), "xlsx", "Edit spreadsheets") + skill(t, filepath.Join(src, "docx"), "docx", "Write documents") + write(t, filepath.Join(src, "deploy/SKILL.md"), "---\nname: deploy\ndescription: Ship it\ndisable-model-invocation: true\n---\n") + ok(t)(InstallSkills(src, []string{"pdf", "xlsx", "docx", "deploy"}, []string{"claude", "codex"})) + cmds := filepath.Join(h, ".claude", "commands") + mine := filepath.Join(cmds, "docx.md") + write(t, mine, "my own docx command\n") + r := ok(t)(SetSkillRouter(true)) + for _, p := range r.Problems { + if strings.Contains(p.What, "command") { + t.Fatalf("a problem for a stub: %+v", p) + } + } + stub := filepath.Join(cmds, "pdf.md") + got := read(t, stub) + at := filepath.Join(realDir(filepath.Join(h, ".claude", "skills")), RouterSkill, ".skills", "pdf", "SKILL.md") + for _, w := range []string{"disable-model-invocation: true\n", `description: "Read PDFs. Use for any .pdf file"`, "`" + at + "`", "$ARGUMENTS"} { + if !strings.Contains(got, w) { + t.Fatalf("pdf's stub has no %q:\n%s", w, got) + } + } + if !strings.Contains(read(t, at), "Read PDFs") { + t.Fatal("the stub's path doesn't lead to pdf's SKILL.md") + } + if _, err := os.Stat(filepath.Join(cmds, "xlsx.md")); err != nil { + t.Fatal("xlsx has no stub") + } + if _, err := os.Stat(filepath.Join(cmds, "deploy.md")); err == nil { + t.Fatal("deploy keeps its own link, yet has a stub") + } + if read(t, mine) != "my own docx command\n" { + t.Fatal("the user's own docx command was written over") + } + // Codex has no such folder of magpie's: nothing written for it + if es, _ := os.ReadDir(filepath.Join(h, ".codex", "prompts")); len(es) != 0 { + t.Fatalf("codex was given stubs: %v", es) + } + if r := ok(t)(Sync()); slices.Contains(r.Changed, "claude") { + t.Fatalf("a second sync changed claude: %+v", r.Changed) + } + // the stubs aren't offered as the user's commands to bring in + p, err := ProbeCommands() + if err != nil { + t.Fatal(err) + } + for _, c := range p.Candidates { + if c.Name == "pdf" || c.Name == "xlsx" { + t.Fatalf("a stub is offered to import: %+v", c) + } + } + + // kept direct: its link is the /name, and the stub goes + ok(t)(SkillRouterHow("xlsx", true)) + if _, err := os.Stat(filepath.Join(cmds, "xlsx.md")); err == nil { + t.Fatal("direct, xlsx's stub stays") + } + + // a library command called pdf takes the stub's place + r = ok(t)(SaveCommand("", Command{Name: "pdf", Description: "mine", Prompt: "Do the pdf thing", Agents: []string{"claude"}})) + for _, p := range r.Problems { + if strings.Contains(p.What, "pdf") { + t.Fatalf("a problem: %+v", p) + } + } + if got := read(t, stub); !strings.Contains(got, "Do the pdf thing") { + t.Fatalf("pdf.md isn't the library's command:\n%s", got) + } + a := loaded(t).Applied["claude"] + if slices.ContainsFunc(a.RouterCommands, func(f SubagentFile) bool { return f.Path == stub }) { + t.Fatalf("the command is still on record as a stub: %+v", a.RouterCommands) + } + ok(t)(RemoveCommands([]string{"pdf"})) + if got := read(t, stub); !strings.Contains(got, "disable-model-invocation") { + t.Fatalf("the command gone, pdf has no stub again:\n%s", got) + } + + // off: every stub goes, the user's own stays + ok(t)(SetSkillRouter(false)) + if _, err := os.Stat(stub); err == nil { + t.Fatal("router off, pdf's stub stays") + } + if read(t, mine) != "my own docx command\n" { + t.Fatal("router off took the user's own command") + } + if a := loaded(t).Applied["claude"]; a != nil && len(a.RouterCommands) != 0 { + t.Fatalf("applied after off: %+v", a.RouterCommands) + } +}