Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

library: skills kept in ~/.agents/skills can be handed over to the library, and then turned off per agent

yetoneda8039368fdb
diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md
index 619faa731..95140f255 100644
--- a/docs/subsystems/library.md
+++ b/docs/subsystems/library.md
@@ -61,7 +61,8 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
- With the MCP hub on (`MCPHub`), an agent that takes a Streamable HTTP server is given magpie's one `magpie` entry in place of the Library servers ticked for it, and each server's own entry again when it is turned off. One that can't, or has an entry called magpie of its own, or whose library has a server called magpie, keeps each server's own entry, and the page says why ([MCP hub](mcp-hub.md)).
- magpie's own MCP server (`magpie-image`, and any `mcp …` run by a program named magpie) runs this computer's magpie (#1439). `InstallServer` gives it magpie by full path (`update.Program`: the AppImage, not its mount; Homebrew's opt link, not the Cellar), and that path is right only on this computer. When the library is read, and after every change, `heal` points such a server whose program isn't on this computer (another system's path, a magpie moved out of Downloads, a bare `magpie`) at this magpie, so the agents and `CheckServers` get it; a magpie program that is here (another build) and a server run by any other program stay as they are. A carried library (`Collect`, for a backup or a WebDAV or S3 sync) names it as plain `magpie`, so two computers carry the same bundle and a sync doesn't write one's path over the other's; `Put` then reads it as that computer's magpie. [`self_here.go`](../../internal/library/self_here.go)
- A carried library (`Collect`) has every file of each skill, its templates and other binaries included, up to `maxCarried` (16 MiB) a file and `maxCarriedAll` (32 MiB) in all, chosen smallest first across the skills (`readSkills`), so every skill's text goes before any big file. The total keeps a sealed backup under the 64 MiB a sync reads: the files are base64 twice in it. What is left out is named in `Left`, and `Put` keeps this computer's copy of such a file in the skill it puts (`keepLeft`). [`carry.go`](../../internal/library/carry.go)
-- A skill can be turned off on this computer alone (`OffHere`, `SkillHere`; the row's power button, `magpie library skill off-here <name>` and `on-here`; hanslin1666 on Discord). No agent here gets it, whatever its `Agents` say (`gives`, which every reader of `Agents` for giving goes through: `syncSkills`, `desktop_skills.go`, `skill_changed.go`, `skill_edits.go`, `behind`, `Targets`). `Agents` stays what a sync carries, and the page leaves its chips as they are, faded. `Collect` never carries `OffHere`, so turning it off changes no part a sync uploads, and `Put` keeps this computer's `OffHere` for a skill it puts, so a sync from a computer that has it on, or gives it to more agents, never turns it on here. A library.json from before has no `offHere` and every skill stays on. Not covered: a project's skills; a library skill whose own folder is inside `~/.agents/skills`, which agents read in place; and a skill another computer removes, which takes the flag with it. [`skills.go`](../../internal/library/skills.go), [`carry.go`](../../internal/library/carry.go)
+- A skill can be turned off on this computer alone (`OffHere`, `SkillHere`; the row's power button, `magpie library skill off-here <name>` and `on-here`; hanslin1666 on Discord). No agent here gets it, whatever its `Agents` say (`gives`, which every reader of `Agents` for giving goes through: `syncSkills`, `desktop_skills.go`, `skill_changed.go`, `skill_edits.go`, `behind`, `Targets`). `Agents` stays what a sync carries, and the page leaves its chips as they are, faded. `Collect` never carries `OffHere`, so turning it off changes no part a sync uploads, and `Put` keeps this computer's `OffHere` for a skill it puts, so a sync from a computer that has it on, or gives it to more agents, never turns it on here. A library.json from before has no `offHere` and every skill stays on. Not covered: a project's skills; a library skill kept in `~/.agents/skills`, which agents read in place, until it is handed over (below); and a skill another computer removes, which takes the flag with it. [`skills.go`](../../internal/library/skills.go), [`carry.go`](../../internal/library/carry.go)
+- A skill kept in `~/.agents/skills` is handed over to the library on the user's click (`HandOverSkills`, `POST /api/library/skills/hand-over` with `names`; the row's Manage in magpie in its source line, Manage {n} in magpie in the skills' heading, each asking first; `magpie library skill hand-over <name…>|--all`; tnt1223 on Discord). "Kept there" is `sharedEntry`: the entry in that folder that is the library skill's own folder, by its name or, for a library link into it under another folder's name, by that folder's (`SkillView.Shared`; `SharedElsewhere` when the entry only links to a folder kept elsewhere). Every reader of `sharedHas`/`sharedEntry` follows: `Always`, `syncSkills`' `inShared`, and the shared folder's own target (Goose, Kimi Code, Cindy), which is given no second link beside such an entry (`TestSharedUnderAnotherName`). Handed over, a folder in `~/.agents/skills` moves into the library's skills folder (`moveIn`: renamed, or copied, read back the same with `sameTree` and only then set aside with the backups; a failure leaves it where it was and the library's link as it was, `TestHandOverFailureKeepsOriginal`), and an entry that only links elsewhere is taken away while the library links past it to that folder. The user's own links to it in agents' folders, which would point at nothing, go too. Every agent here that read it (`readsSharedHere`, and the agent of each such link) is ticked, so each keeps it, now from the library, till it is unticked or turned off here. A skill found there and not in the library yet is brought in first. One that can't be handed over is left as it was, in `Result.Unmoved`, and the others are handed over all the same. `HandBackSkill` (`magpie library skill hand-back <name>`, CLI only; the sheet names it) moves the folder back and links the library to it, its ticks as they are. Not covered: another computer whose skill is still in its own `~/.agents/skills` gets the library's copy from a sync beside its own, until it is handed over there too; and the skills CLI's lock (`npx skills update`) may put the entry back (`TestHandOverSharedFolder`, `TestHandOverSharedLink`, `TestHandOverFound`, `TestHandOverWithGoose`, `TestLibrarySkillHandOver`, `skill-handover.test.cjs`). [`skill_handover.go`](../../internal/library/skill_handover.go)
- WorkBuddy's servers go in `$WORKBUDDY_CONFIG_DIR/mcp.json` (default `~/.workbuddy`; WorkBuddy AI, the international build, keeps its own in `~/.workbuddy-ai`, #1494), and CodeBuddy Code's go in the first of `.mcp.json`, `mcp.json` and `~/.codebuddy.json` that exists, as `resolveMcpFilePath` reads them (#1266). WorkBuddy connects a server only after the user has switched it on once in its own MCP settings. It keeps that approval in `mcp-approvals.json`, keyed by the command, args and env names or the URL's origin, so changing those asks again. magpie never writes the approval, and the servers page says so, by the build's name, when a server is given to WorkBuddy or WorkBuddy AI.
- Alma's servers go in `~/.config/alma/mcp.json` on every system (its home, not its data folder), as its own MCP settings write them: `command`/`args`/`env`, or `url`/`headers` with `transport: "sse"` only for SSE (#1292). Alma reads the file as it starts and when its MCP settings refresh, so a server given to it while it runs reaches it after one of those.
- Grok App's independent home (Use on a custom provider, `GROK_HOME` at `agent-home` under its data folder) gets instructions in `AGENTS.md`, MCP servers in `[mcp_servers]` of the same `config.toml` magpie's channel is in, skills in `skills/`, and hooks as `[[hooks.<Event>]]` tables in that config, and it also reads `~/.agents/skills`. Shared mode stays on Grok Build's `~/.grok` row. RTK lists Grok App, and Grok Build, with the switch off: `rtk init` has no Grok agent.
@@ -81,11 +82,12 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
```sh
go test -tags nogui ./internal/library -run 'TestGit|TestInstallFromGitRepo|TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestWSLPiMCP|TestWSLMCPSiblings|TestServer|TestHub|TestImportServer|TestCheck|TestInstructions|TestInstructionsSetLinkedToAgentsFile|TestInstructionSets|TestTakesAlma|TestAlma|TestLinkedSet|TestLinkRefused|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList|TestHooks|TestSubagent|TestCheckRenewsMagpiesSignIn|TestCheckWSLOnlyServerInItsDistro|TestCheckWindowsServerHere|TestCheckMixedServerEachSide|TestCheckSaysSignInRanOut|TestCheckNamesAgentsSignedInThemselves|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut|TestUpdateFindsSkillsRemovedUpstream|TestGoneFromNeedsTheSourceRead'
go test -tags nogui ./internal/library -run 'TestSkillOffHere'
+go test -tags nogui ./internal/library -run 'TestHandOver|TestSharedUnderAnotherName|TestSharedAgentsSkills'
go test -tags nogui ./internal/davsync -run 'TestSkillOffHereThroughSync'
-go test -tags nogui ./internal/cli -run 'TestLibrarySkillRm'
+go test -tags nogui ./internal/cli -run 'TestLibrarySkillRm|TestLibrarySkillHandOver'
go test -race ./internal/mcpauth
go test -tags nogui ./internal/library
-node --test internal/gui/tests/skill-off-here.test.cjs
+node --test internal/gui/tests/skill-off-here.test.cjs internal/gui/tests/skill-handover.test.cjs
node --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-mcp-hub.test.cjs internal/gui/tests/library-alma-profile.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-pick-remove.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/skill-gone.test.cjs internal/gui/tests/skill-git-source.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/found-skill-pick-remove.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs internal/gui/tests/library-hooks.test.cjs internal/gui/tests/library-subagents.test.cjs internal/gui/tests/library-mcp-health.test.cjs internal/gui/tests/library-mcp-health-wsl.test.cjs internal/gui/tests/mcp-signin-health.test.cjs internal/gui/tests/mcp-signin.test.cjs internal/gui/tests/mcp-editor-cancel.test.cjs internal/gui/tests/mcp-oauth-app.test.cjs internal/gui/tests/library-ime-scroll.test.cjs
```
diff --git a/internal/cli/library_cli.go b/internal/cli/library_cli.go
index 8e6851143..22f2b8039 100644
--- a/internal/cli/library_cli.go
+++ b/internal/cli/library_cli.go
@@ -26,6 +26,9 @@ const libraryUsage = `magpie library what the library gives
magpie library skill agents <name> <a,b…|none>
magpie library skill off-here <name> turn it off on this computer only: a sync neither carries that nor turns it back on
magpie library skill on-here <name> …and on again here
+ magpie library skill hand-over <name…>|--all move skills kept in ~/.agents/skills into the library's folder: the agents that read them
+ there keep them, ticked, and you can turn each off
+ magpie library skill hand-back <name> …and back into ~/.agents/skills, where those agents read it whatever is ticked
magpie library skill rm <name> (skills are installed from the app's Library page)
magpie library skill rm --all [--yes] every skill out of the library and the agents (asks first; --yes doesn't)
magpie library skill rm --gone [--yes] every skill an update found removed from its source (asks first; --yes doesn't)
@@ -142,6 +145,14 @@ func libraryCmd(args []string) error {
}
case len(rest) == 2 && (rest[0] == "off-here" || rest[0] == "on-here") && !strings.HasPrefix(rest[1], "-"):
res, err = library.SkillHere(rest[1], rest[0] == "on-here")
+ case len(rest) >= 2 && rest[0] == "hand-over":
+ if res, err = handOverSkills(rest[1:]); res == nil && err == nil {
+ return nil
+ }
+ case len(rest) == 2 && rest[0] == "hand-back" && !strings.HasPrefix(rest[1], "-"):
+ if res, err = library.HandBackSkill(rest[1]); err == nil {
+ fmt.Println(green.Render("✓"), rest[1], "is back in", filepath.Join("~", ".agents", "skills", rest[1]))
+ }
case len(rest) == 2 && rest[0] == "rm":
res, err = library.RemoveSkill(rest[1])
case len(rest) == 3 && rest[0] == "use-library":
@@ -583,3 +594,39 @@ func rtkCmd(args []string) error {
}
return nil
}
+
+// handOverSkills is magpie library skill hand-over: the skills named, or
+// with --all every one the library keeps in ~/.agents/skills, moved into
+// the library's folder. Each moved is said, and where it went.
+func handOverSkills(args []string) (*library.Result, error) {
+ names := args
+ if slices.Contains(args, "--all") {
+ if len(args) != 1 {
+ return nil, fmt.Errorf("usage:\n %s", libraryUsage)
+ }
+ var err error
+ if names, err = library.SharedSkills(); err != nil {
+ return nil, err
+ }
+ if len(names) == 0 {
+ fmt.Println(muted.Render("No skill of the library's is kept in ~/.agents/skills."))
+ return nil, nil
+ }
+ } else if slices.ContainsFunc(args, func(a string) bool { return strings.HasPrefix(a, "-") }) {
+ return nil, fmt.Errorf("usage:\n %s", libraryUsage)
+ }
+ res, err := library.HandOverSkills(names)
+ if err != nil {
+ return nil, err
+ }
+ for _, n := range names {
+ if slices.ContainsFunc(res.Unmoved, func(p library.Problem) bool { return p.What == "skill:"+n }) {
+ continue
+ }
+ fmt.Println(green.Render("✓"), n, "is in the library's folder:", library.SkillPath(n))
+ }
+ for _, p := range res.Unmoved {
+ fmt.Println(amber.Render("!"), strings.TrimPrefix(p.What, "skill:"), "stays where it was:", p.Error)
+ }
+ return res, nil
+}
diff --git a/internal/cli/library_handover_test.go b/internal/cli/library_handover_test.go
new file mode 100644
index 000000000..d01e84bd3
--- /dev/null
+++ b/internal/cli/library_handover_test.go
@@ -0,0 +1,57 @@
+package cli
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/yetone/magpie/internal/library"
+)
+
+// magpie library skill hand-over / hand-back (tnt1223): a skill kept in
+// ~/.agents/skills moves into the library's folder and back again; --all
+// takes the library's skills kept there, and nothing else.
+func TestLibrarySkillHandOver(t *testing.T) {
+ h := t.TempDir()
+ for k, v := range map[string]string{"HOME": h, "USERPROFILE": h, "XDG_CONFIG_HOME": filepath.Join(h, ".config"), "CLAUDE_CONFIG_DIR": "", "CODEX_HOME": "", "APPDATA": "", "LOCALAPPDATA": "", "PATH": filepath.Join(h, "bin")} {
+ t.Setenv(k, v)
+ }
+ shared := filepath.Join(h, ".agents/skills", "orca")
+ if err := os.MkdirAll(shared, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(shared, "SKILL.md"), []byte("---\nname: orca\ndescription: Orca\n---\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ // found, not brought in: --all is the library's alone
+ if err := libraryCmd([]string{"library", "skill", "hand-over", "--all"}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(filepath.Join(shared, "SKILL.md")); err != nil {
+ t.Fatal("--all moved a skill the library doesn't have")
+ }
+ if err := libraryCmd([]string{"library", "skill", "hand-over", "--all", "--yes"}); err == nil {
+ t.Error("an unknown flag was taken")
+ }
+ if _, err := library.ImportSkill("orca"); err != nil {
+ t.Fatal(err)
+ }
+ if err := libraryCmd([]string{"library", "skill", "hand-over", "--all"}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Lstat(shared); !os.IsNotExist(err) {
+ t.Fatalf("still in ~/.agents/skills: %v", err)
+ }
+ if fi, err := os.Lstat(library.SkillPath("orca")); err != nil || !fi.IsDir() {
+ t.Fatalf("not a folder in the library: %v", err)
+ }
+ if err := libraryCmd([]string{"library", "skill", "hand-back", "orca"}); err != nil {
+ t.Fatal(err)
+ }
+ if fi, err := os.Lstat(shared); err != nil || !fi.IsDir() {
+ t.Fatalf("not back in ~/.agents/skills: %v", err)
+ }
+ if err := libraryCmd([]string{"library", "skill", "hand-over", "nope"}); err == nil {
+ t.Error("a skill that isn't there was handed over")
+ }
+}
diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js
index 72f5f15a5..882e6a18b 100644
--- a/internal/gui/assets/plugins/library/client.js
+++ b/internal/gui/assets/plugins/library/client.js
@@ -3056,6 +3056,10 @@ magpie.plugin("library", (ctx) => {
}
if (lib.skills.length > 1 && all.length) rh.append(pickButton("skills"), ...everyButtons("skills", all));
if (byAgentRows("skills").length) rh.append(byAgentButton("skills"));
+ // every one kept in ~/.agents/skills, moved into the library at once
+ // (tnt1223); a row moves its own
+ const kept = lib.skills.filter((s) => s.shared);
+ if (kept.length > 1) rh.append(handOverButton(kept));
if (lib.skills.length > 1) rh.append(removeEveryButton("skills"));
if (lib.skills.some((s) => s.kind === "github" || s.kind === "git")) {
const c = button(checking ? t("Checking…") : t("Check for updates"), "lib-updall", () => checkSkills());
@@ -5007,6 +5011,9 @@ magpie.plugin("library", (ctx) => {
} else {
src.append(el("span", "", t("linked from")), pathLink(s.source));
}
+ // kept in ~/.agents/skills, which some agents read themselves: moved
+ // into the library, each of them can be turned off (tnt1223)
+ if (s.shared) src.append(handOverButton([s]));
who.append(src);
}
const acts = el("div", "lib-rowacts");
@@ -5132,6 +5139,83 @@ magpie.plugin("library", (ctx) => {
openLib(ed);
}
+ // Skills kept in ~/.agents/skills (tnt1223 on Discord): agents that read
+ // that folder themselves have each whatever is ticked, so none can be
+ // turned off for one of them. Manage in magpie moves them into the
+ // library's own folder, asking first and saying where they go; the
+ // agents that read them there are ticked, and keep them till unticked.
+ function handOverButton(skills) {
+ const one = skills.length === 1;
+ const b = button(one ? t("Manage in magpie") : t("Manage {n} in magpie", { n: skills.length }), one ? "lib-handover" : "action lib-updall lib-handover", (e) => {
+ e.stopPropagation();
+ confirmHandOver(skills);
+ });
+ b.title = one ? t("Move it out of ~/.agents/skills into magpie's library, so you choose which agents get it")
+ : t("Move these {n} from ~/.agents/skills into magpie's library, so you choose which agents get them", { n: skills.length });
+ return b;
+ }
+
+ function confirmHandOver(skills) {
+ const one = skills.length === 1, s = skills[0];
+ const ed = el("div", "editor lib-editor lib-handover-ask");
+ const head = el("div", "ehead");
+ head.append(glyph(GLYPH.skill), el("b", "", one ? t("Manage {name} in magpie?", { name: s.name }) : t("Manage {n} skills in magpie?", { n: skills.length })));
+ ed.append(head);
+ const readers = [...new Set(skills.flatMap((x) => x.always || []))].map(nameOf).filter(Boolean).join(", ");
+ // the entry only links to a folder elsewhere: only the link goes
+ ed.append(el("p", "lib-confirm", one
+ ? (s.sharedElsewhere ? t("Its entry in ~/.agents/skills, a link to {path}, is taken away. The folder stays where it is, and the library links to it.", { path: tilde(s.source) })
+ : t("Its folder moves from {from} into magpie's library folder, {to}.", { from: tilde(s.shared), to: tilde(libSkillPath(s.name)) }))
+ : t("Their folders move from ~/.agents/skills into magpie's library folder, {to}. One that only links there to a folder elsewhere keeps that folder; only the link goes.", { to: tilde(libSkillPath("")) })));
+ if (readers) ed.append(el("p", "lib-confirm", one
+ ? t("{agents} read ~/.agents/skills themselves. They keep it, ticked here, and you can turn it off for any of them, or on this computer only.", { agents: readers })
+ : t("{agents} read ~/.agents/skills themselves. They keep them, ticked here, and you can turn each off for any of them, or on this computer only.", { agents: readers })));
+ ed.append(el("p", "lib-confirm lib-muted", one
+ ? t("To put it back: {cmd}", { cmd: "magpie library skill hand-back " + s.name })
+ : t("To put one back: {cmd}", { cmd: "magpie library skill hand-back <name>" })));
+ const bar = el("div", "bar");
+ const go = button(t("Move into the library"), "primary", async () => {
+ go.disabled = true;
+ if (await handOverSkills(skills.map((x) => x.name))) closeLibModal(true);
+ else go.disabled = false;
+ });
+ bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal), go);
+ ed.append(bar);
+ modal = { save: () => go.click() };
+ openLib(ed);
+ }
+
+ // where the library keeps a skill's folder: skills/<name> in its own
+ function libSkillPath(name) {
+ const dir = lib.dir || "", sep = dir.includes("\\") ? "\\" : "/";
+ return dir + sep + "skills" + (name ? sep + name : "");
+ }
+
+ async function handOverSkills(names) {
+ if (changing) return false;
+ changing = true;
+ page.setAttribute("aria-busy", "true");
+ status(t("Saving…"), "", 120000);
+ try {
+ const v = await api("library/skills/hand-over", { names });
+ take(v);
+ status("");
+ const res = v.result || {}, no = res.unmoved || [];
+ const moved = names.filter((x) => !no.some((p) => p.what === "skill:" + x));
+ const done = moved.length === 1 ? t("{name} is in magpie's library now", { name: moved[0] }) : t("{n} skills are in magpie's library now", { n: moved.length });
+ if (no.length) status((moved.length ? done + " · " : "") + t("{name} wasn't moved: {error}", { name: no[0].what.replace(/^skill:/, ""), error: no[0].error }) + (no.length > 1 ? " " + t("(and {n} more)", { n: no.length - 1 }) : ""), "warn", 10000);
+ else report(res, done);
+ return true;
+ } catch (e) {
+ status(e.message, "err", 6000);
+ return false;
+ } finally {
+ changing = false;
+ page.removeAttribute("aria-busy");
+ render();
+ }
+ }
+
function confirmRemoveSkill(s) {
const ed = el("div", "editor lib-editor");
const head = el("div", "ehead");
diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js
index 35c68f59b..c604d14cf 100644
--- a/internal/gui/assets/plugins/library/i18n.js
+++ b/internal/gui/assets/plugins/library/i18n.js
@@ -2,6 +2,23 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
+ "Move into the library": "移入资源库",
+ "Manage in magpie": "交给 magpie 管理",
+ "Manage {n} in magpie": "将 {n} 个交给 magpie 管理",
+ "Move it out of ~/.agents/skills into magpie's library, so you choose which agents get it": "从 ~/.agents/skills 移入 magpie 的资源库,由你决定哪些 Agent 使用它",
+ "Move these {n} from ~/.agents/skills into magpie's library, so you choose which agents get them": "将这 {n} 个从 ~/.agents/skills 移入 magpie 的资源库,由你决定哪些 Agent 使用它们",
+ "Manage {name} in magpie?": "将 {name} 交给 magpie 管理?",
+ "Manage {n} skills in magpie?": "将 {n} 个技能交给 magpie 管理?",
+ "Its entry in ~/.agents/skills, a link to {path}, is taken away. The folder stays where it is, and the library links to it.": "它在 ~/.agents/skills 里的条目(指向 {path} 的链接)会被移除。文件夹留在原处,资源库链接到它。",
+ "Its folder moves from {from} into magpie's library folder, {to}.": "它的文件夹会从 {from} 移入 magpie 的资源库文件夹 {to}。",
+ "Their folders move from ~/.agents/skills into magpie's library folder, {to}. One that only links there to a folder elsewhere keeps that folder; only the link goes.": "它们的文件夹会从 ~/.agents/skills 移入 magpie 的资源库文件夹 {to}。只是链接到别处文件夹的,文件夹留在原处,只移除链接。",
+ "{agents} read ~/.agents/skills themselves. They keep it, ticked here, and you can turn it off for any of them, or on this computer only.": "{agents} 会自己读取 ~/.agents/skills。它们会继续使用它,在这里保持勾选;你可以为其中任意一个关闭它,或只在本机关闭。",
+ "{agents} read ~/.agents/skills themselves. They keep them, ticked here, and you can turn each off for any of them, or on this computer only.": "{agents} 会自己读取 ~/.agents/skills。它们会继续使用这些技能,在这里保持勾选;你可以为其中任意一个分别关闭,或只在本机关闭。",
+ "To put it back: {cmd}": "放回原处:{cmd}",
+ "To put one back: {cmd}": "放回某一个:{cmd}",
+ "{name} is in magpie's library now": "{name} 已交给 magpie 的资源库管理",
+ "{n} skills are in magpie's library now": "{n} 个技能已交给 magpie 的资源库管理",
+ "{name} wasn't moved: {error}": "{name} 未移动:{error}",
"Off on this computer": "本机已关闭",
"No agent on this computer gets it. Your other computers keep their own choice, and a sync doesn't turn it on here. Click to turn it on here.": "这台电脑上的 Agent 都不会用到它。其他电脑保持各自的设置,同步也不会在这里把它重新打开。点一下在本机打开。",
"{name} is on on this computer": "{name} 已在本机打开",
@@ -687,6 +704,23 @@ magpie.strings({
"Not installed here: it isn't given anything new, and what it has can be taken out here": "本机没有安装:不会再分配新的内容,已有的可以在这里移除",
},
"zh-TW": {
+ "Move into the library": "移入資源庫",
+ "Manage in magpie": "交給 magpie 管理",
+ "Manage {n} in magpie": "將 {n} 個交給 magpie 管理",
+ "Move it out of ~/.agents/skills into magpie's library, so you choose which agents get it": "從 ~/.agents/skills 移入 magpie 的資源庫,由你決定哪些 Agent 使用它",
+ "Move these {n} from ~/.agents/skills into magpie's library, so you choose which agents get them": "將這 {n} 個從 ~/.agents/skills 移入 magpie 的資源庫,由你決定哪些 Agent 使用它們",
+ "Manage {name} in magpie?": "將 {name} 交給 magpie 管理?",
+ "Manage {n} skills in magpie?": "將 {n} 個技能交給 magpie 管理?",
+ "Its entry in ~/.agents/skills, a link to {path}, is taken away. The folder stays where it is, and the library links to it.": "它在 ~/.agents/skills 裡的項目(指向 {path} 的連結)會被移除。資料夾留在原處,資源庫連結到它。",
+ "Its folder moves from {from} into magpie's library folder, {to}.": "它的資料夾會從 {from} 移入 magpie 的資源庫資料夾 {to}。",
+ "Their folders move from ~/.agents/skills into magpie's library folder, {to}. One that only links there to a folder elsewhere keeps that folder; only the link goes.": "它們的資料夾會從 ~/.agents/skills 移入 magpie 的資源庫資料夾 {to}。只是連結到別處資料夾的,資料夾留在原處,只移除連結。",
+ "{agents} read ~/.agents/skills themselves. They keep it, ticked here, and you can turn it off for any of them, or on this computer only.": "{agents} 會自己讀取 ~/.agents/skills。它們會繼續使用它,在這裡保持勾選;你可以為其中任一個關閉它,或只在本機關閉。",
+ "{agents} read ~/.agents/skills themselves. They keep them, ticked here, and you can turn each off for any of them, or on this computer only.": "{agents} 會自己讀取 ~/.agents/skills。它們會繼續使用這些技能,在這裡保持勾選;你可以為其中任一個分別關閉,或只在本機關閉。",
+ "To put it back: {cmd}": "放回原處:{cmd}",
+ "To put one back: {cmd}": "放回某一個:{cmd}",
+ "{name} is in magpie's library now": "{name} 已交給 magpie 的資源庫管理",
+ "{n} skills are in magpie's library now": "{n} 個技能已交給 magpie 的資源庫管理",
+ "{name} wasn't moved: {error}": "{name} 未移動:{error}",
"Off on this computer": "本機已關閉",
"No agent on this computer gets it. Your other computers keep their own choice, and a sync doesn't turn it on here. Click to turn it on here.": "這台電腦上的 Agent 都不會用到它。其他電腦保持各自的設定,同步也不會在這裡把它重新開啟。點一下在本機開啟。",
"{name} is on on this computer": "{name} 已在本機開啟",
@@ -1372,6 +1406,23 @@ magpie.strings({
"Not installed here: it isn't given anything new, and what it has can be taken out here": "本機沒有安裝:不會再分配新的內容,已有的可以在這裡移除",
},
ja: {
+ "Move into the library": "ライブラリへ移す",
+ "Manage in magpie": "magpie で管理",
+ "Manage {n} in magpie": "{n} 件を magpie で管理",
+ "Move it out of ~/.agents/skills into magpie's library, so you choose which agents get it": "~/.agents/skills から magpie のライブラリへ移し、どのエージェントが使うかを選べるようにします",
+ "Move these {n} from ~/.agents/skills into magpie's library, so you choose which agents get them": "この {n} 件を ~/.agents/skills から magpie のライブラリへ移し、どのエージェントが使うかを選べるようにします",
+ "Manage {name} in magpie?": "{name} を magpie で管理しますか?",
+ "Manage {n} skills in magpie?": "{n} 件のスキルを magpie で管理しますか?",
+ "Its entry in ~/.agents/skills, a link to {path}, is taken away. The folder stays where it is, and the library links to it.": "~/.agents/skills にある項目({path} へのリンク)を取り除きます。フォルダーはそのまま残り、ライブラリがそこにリンクします。",
+ "Its folder moves from {from} into magpie's library folder, {to}.": "フォルダーを {from} から magpie のライブラリのフォルダー {to} へ移します。",
+ "Their folders move from ~/.agents/skills into magpie's library folder, {to}. One that only links there to a folder elsewhere keeps that folder; only the link goes.": "フォルダーを ~/.agents/skills から magpie のライブラリのフォルダー {to} へ移します。別の場所のフォルダーへのリンクだけのものは、フォルダーを残してリンクだけ取り除きます。",
+ "{agents} read ~/.agents/skills themselves. They keep it, ticked here, and you can turn it off for any of them, or on this computer only.": "{agents} は ~/.agents/skills を自分で読み込みます。引き続き使えるようここでチェックされたままになり、どれか一つだけ、またはこのコンピューターだけでオフにできます。",
+ "{agents} read ~/.agents/skills themselves. They keep them, ticked here, and you can turn each off for any of them, or on this computer only.": "{agents} は ~/.agents/skills を自分で読み込みます。引き続き使えるようここでチェックされたままになり、それぞれどれか一つだけ、またはこのコンピューターだけでオフにできます。",
+ "To put it back: {cmd}": "元に戻すには:{cmd}",
+ "To put one back: {cmd}": "一つを元に戻すには:{cmd}",
+ "{name} is in magpie's library now": "{name} は magpie のライブラリで管理されています",
+ "{n} skills are in magpie's library now": "{n} 件のスキルが magpie のライブラリで管理されています",
+ "{name} wasn't moved: {error}": "{name} は移動されませんでした:{error}",
"Off on this computer": "このコンピュータでオフ",
"No agent on this computer gets it. Your other computers keep their own choice, and a sync doesn't turn it on here. Click to turn it on here.": "このコンピュータのエージェントには渡されません。ほかのコンピュータはそれぞれの設定のままで、同期してもここでオンに戻りません。クリックするとここでオンにします。",
"{name} is on on this computer": "{name} をこのコンピュータでオンにしました",
@@ -2057,6 +2108,23 @@ magpie.strings({
"Not installed here: it isn't given anything new, and what it has can be taken out here": "このコンピューターにはインストールされていません:新しいものは割り当てられず、すでにあるものはここで外せます",
},
de: {
+ "Move into the library": "In die Bibliothek verschieben",
+ "Manage in magpie": "In magpie verwalten",
+ "Manage {n} in magpie": "{n} in magpie verwalten",
+ "Move it out of ~/.agents/skills into magpie's library, so you choose which agents get it": "Aus ~/.agents/skills in die Bibliothek von magpie verschieben, damit du wählst, welche Agents ihn bekommen",
+ "Move these {n} from ~/.agents/skills into magpie's library, so you choose which agents get them": "Diese {n} aus ~/.agents/skills in die Bibliothek von magpie verschieben, damit du wählst, welche Agents sie bekommen",
+ "Manage {name} in magpie?": "{name} in magpie verwalten?",
+ "Manage {n} skills in magpie?": "{n} Skills in magpie verwalten?",
+ "Its entry in ~/.agents/skills, a link to {path}, is taken away. The folder stays where it is, and the library links to it.": "Sein Eintrag in ~/.agents/skills, ein Link auf {path}, wird entfernt. Der Ordner bleibt, wo er ist, und die Bibliothek verlinkt ihn.",
+ "Its folder moves from {from} into magpie's library folder, {to}.": "Sein Ordner wird von {from} in den Bibliotheksordner von magpie verschoben, {to}.",
+ "Their folders move from ~/.agents/skills into magpie's library folder, {to}. One that only links there to a folder elsewhere keeps that folder; only the link goes.": "Ihre Ordner werden aus ~/.agents/skills in den Bibliotheksordner von magpie verschoben, {to}. Ist einer dort nur ein Link auf einen Ordner anderswo, bleibt dieser Ordner; nur der Link wird entfernt.",
+ "{agents} read ~/.agents/skills themselves. They keep it, ticked here, and you can turn it off for any of them, or on this computer only.": "{agents} lesen ~/.agents/skills selbst. Sie behalten ihn, hier angehakt, und du kannst ihn für jeden einzeln ausschalten oder nur auf diesem Computer.",
+ "{agents} read ~/.agents/skills themselves. They keep them, ticked here, and you can turn each off for any of them, or on this computer only.": "{agents} lesen ~/.agents/skills selbst. Sie behalten sie, hier angehakt, und du kannst jeden für jeden Agent einzeln ausschalten oder nur auf diesem Computer.",
+ "To put it back: {cmd}": "Zum Zurücklegen: {cmd}",
+ "To put one back: {cmd}": "Um einen zurückzulegen: {cmd}",
+ "{name} is in magpie's library now": "{name} wird jetzt in der Bibliothek von magpie verwaltet",
+ "{n} skills are in magpie's library now": "{n} Skills werden jetzt in der Bibliothek von magpie verwaltet",
+ "{name} wasn't moved: {error}": "{name} wurde nicht verschoben: {error}",
"Off on this computer": "Auf diesem Computer aus",
"No agent on this computer gets it. Your other computers keep their own choice, and a sync doesn't turn it on here. Click to turn it on here.": "Kein Agent auf diesem Computer bekommt ihn. Deine anderen Computer behalten ihre Wahl, und ein Sync schaltet ihn hier nicht wieder ein. Klicken, um ihn hier einzuschalten.",
"{name} is on on this computer": "{name} ist auf diesem Computer an",
diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css
index 253a58a26..9fe883a4e 100644
--- a/internal/gui/assets/plugins/library/library.css
+++ b/internal/gui/assets/plugins/library/library.css
@@ -198,6 +198,10 @@ button.row.lib-hubfolded:hover { background: var(--pill); }
.lib-src > .lib-path, .lib-src > .lib-srclink { flex: 0 1 auto; min-width: 0; }
.lib-srclink { font: var(--code-style, normal) var(--code-weight, 400) 11px var(--code-font, var(--code)); font-stretch: var(--code-stretch, 100%); color: var(--muted); text-decoration: none; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.lib-srclink:hover { color: var(--fg); text-decoration: underline; text-underline-offset: 2px; }
+/* kept in ~/.agents/skills: moved into the library on a click (tnt1223) */
+.lib-src > .lib-handover { flex: 0 2 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; height: auto; border: 0; background: none; font-size: 11px; color: var(--accent); padding: 0 2px; margin-left: 4px; border-radius: 3px; white-space: nowrap; }
+.lib-src > .lib-handover:hover { text-decoration: underline; text-underline-offset: 2px; }
+.lib-confirm.lib-muted { color: var(--muted); }
/* a path: shown in the file manager on a click */
.lib-path { font: var(--code-style, normal) var(--code-weight, 400) 11px var(--code-font, var(--code)); font-stretch: var(--code-stretch, 100%); color: var(--muted); padding: 0; max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: left; border-radius: 3px; }
diff --git a/internal/gui/library.go b/internal/gui/library.go
index 7d34fa3a6..9bae365d1 100644
--- a/internal/gui/library.go
+++ b/internal/gui/library.go
@@ -550,6 +550,9 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
res, err = library.RemoveFoundSkill(in.Name)
case "skills/remove-found-some":
res, err = library.RemoveFoundSkills(in.Names)
+ case "skills/hand-over":
+ // out of ~/.agents/skills, into the library's own folder (tnt1223)
+ res, err = library.HandOverSkills(oneOrMore(in.Name, in.Names))
case "skills/use-library":
res, err = library.UseLibrarySkills(oneOrMore(in.Name, in.Names), in.Agent)
case "skills/how":
diff --git a/internal/gui/tests/skill-handover.test.cjs b/internal/gui/tests/skill-handover.test.cjs
new file mode 100644
index 000000000..434286e30
--- /dev/null
+++ b/internal/gui/tests/skill-handover.test.cjs
@@ -0,0 +1,172 @@
+// Run with Node's test runner and Playwright on the module path; see README.md.
+// tnt1223 on Discord: skills kept in ~/.agents/skills, which some agents
+// read themselves whatever is ticked, are handed over to the library. A
+// row of one says "Manage in magpie" in its source line; the skills'
+// heading moves all of them at once. Each asks first, in the page, saying
+// where the folder goes (or that only a link goes), who keeps it and how
+// to put it back; Cancel posts nothing; the move posts
+// skills/hand-over once with the names. A row not kept there has no
+// button, and no click scrolls the page. Five languages, Chromium and
+// WebKit, wide and narrow. No backend: the API is faked here.
+const assert = require("node:assert/strict");
+const fs = require("node:fs/promises");
+const path = require("node:path");
+const { test } = require("node:test");
+const { chromium, webkit } = require("playwright");
+
+const assets = path.resolve(__dirname, "../assets");
+const HOME = "/Users/tnt";
+const SH = `${HOME}/.agents/skills`;
+const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills` });
+const lib = (st) => ({
+ dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
+ agents: [agent("claude", "Claude Code"), agent("codex", "Codex"), agent("gemini", "Gemini CLI")],
+ instructions: { agents: [] }, servers: [], foundServers: [], projects: [], foundSkills: [], newSkills: [],
+ checkDue: false,
+ skills: [
+ st.moved.includes("orca")
+ ? { name: "orca", description: "Orca", agents: ["claude", "codex", "gemini"] }
+ : { name: "orca", description: "Orca", kind: "folder", source: `${SH}/orca`, shared: `${SH}/orca`, always: ["codex", "gemini"], agents: ["claude"] },
+ st.moved.includes("grill")
+ ? { name: "grill", description: "Grill", kind: "folder", source: `${HOME}/aimer/grill`, agents: ["codex", "gemini"] }
+ : { name: "grill", description: "Grill", kind: "folder", source: `${HOME}/aimer/grill`, shared: `${SH}/grill`, sharedElsewhere: true, always: ["codex", "gemini"], agents: [] },
+ { name: "pdf", description: "PDF", kind: "folder", source: `${HOME}/skills/pdf`, agents: ["claude"] },
+ ],
+});
+
+function server(lang, posts, st) {
+ return async (route) => {
+ const req = route.request(), url = new URL(req.url());
+ if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
+ if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } });
+ if (url.pathname === "/api/library") return route.fulfill({ json: lib(st) });
+ if (url.pathname.startsWith("/api/library/skills/")) {
+ const what = url.pathname.split("/").pop(), body = req.postDataJSON();
+ posts.push({ what, body });
+ if (what === "hand-over") st.moved.push(...body.names);
+ return route.fulfill({ json: { ...lib(st), result: { changed: ["codex", "gemini"] } } });
+ }
+ if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
+ if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
+ if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
+ if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
+ if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} });
+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
+ await route.fulfill({ body: await fs.readFile(file), contentType });
+ };
+}
+
+const scrolls = (page) => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => (e.id || e.className) + ":" + e.scrollTop).concat("doc:" + document.scrollingElement.scrollTop).join(" "));
+
+const words = {
+ en: { one: "Manage in magpie", all: "Manage 2 in magpie", ask: "Manage orca in magpie?", askAll: "Manage 2 skills in magpie?", go: "Move into the library", cancel: "Cancel",
+ where: "~/.agents/skills/orca", lib: "~/.magpie/library/skills/orca", link: "~/aimer/grill", done: "orca is in magpie's library now", doneAll: "2 skills are in magpie's library now" },
+ zh: { one: "交给 magpie 管理", all: "将 2 个交给 magpie 管理", ask: "将 orca 交给 magpie 管理?", askAll: "将 2 个技能交给 magpie 管理?", go: "移入资源库", cancel: "取消",
+ where: "~/.agents/skills/orca", lib: "~/.magpie/library/skills/orca", link: "~/aimer/grill", done: "orca 已交给 magpie 的资源库管理", doneAll: "2 个技能已交给 magpie 的资源库管理" },
+ "zh-TW": { one: "交給 magpie 管理", all: "將 2 個交給 magpie 管理", ask: "將 orca 交給 magpie 管理?", askAll: "將 2 個技能交給 magpie 管理?", go: "移入資源庫", cancel: "取消",
+ where: "~/.agents/skills/orca", lib: "~/.magpie/library/skills/orca", link: "~/aimer/grill", done: "orca 已交給 magpie 的資源庫管理", doneAll: "2 個技能已交給 magpie 的資源庫管理" },
+ ja: { one: "magpie で管理", all: "2 件を magpie で管理", ask: "orca を magpie で管理しますか?", askAll: "2 件のスキルを magpie で管理しますか?", go: "ライブラリへ移す", cancel: "キャンセル",
+ where: "~/.agents/skills/orca", lib: "~/.magpie/library/skills/orca", link: "~/aimer/grill", done: "orca は magpie のライブラリで管理されています", doneAll: "2 件のスキルが magpie のライブラリで管理されています" },
+ de: { one: "In magpie verwalten", all: "2 in magpie verwalten", ask: "orca in magpie verwalten?", askAll: "2 Skills in magpie verwalten?", go: "In die Bibliothek verschieben", cancel: "Abbrechen",
+ where: "~/.agents/skills/orca", lib: "~/.magpie/library/skills/orca", link: "~/aimer/grill", done: "orca wird jetzt in der Bibliothek von magpie verwaltet", doneAll: "2 Skills werden jetzt in der Bibliothek von magpie verwaltet" },
+};
+
+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
+ test(engine + ": skills in ~/.agents/skills are handed over to the library", async (t) => {
+ assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
+ const errors = [];
+ t.after(async () => {
+ await browser.close();
+ });
+ for (const width of [860, 400]) for (const lang of Object.keys(words)) {
+ await t.test(`${lang} at ${width}px`, async () => {
+ const w = words[lang], posts = [], st = { moved: [] };
+ const ctx = await browser.newContext({ viewport: { width, height: 900 } });
+ await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} });
+ const page = await ctx.newPage();
+ page.setDefaultTimeout(5000);
+ page.on("pageerror", (e) => errors.push(e.message));
+ await page.route("**/*", server(lang, posts, st));
+ await page.goto("http://magpie.test/");
+ await page.locator('button[data-view="library"]').click();
+ const v = page.locator("#view-library");
+ const row = (n) => v.locator(".lib-skill", { has: page.locator(".name", { hasText: new RegExp("^" + n) }) });
+ await row("orca").waitFor();
+
+ // only the rows kept in ~/.agents/skills have it, in their source line
+ const one = row("orca").locator(".lib-src button.lib-handover");
+ assert.equal((await one.textContent()).trim(), w.one);
+ assert.equal(await row("grill").locator(".lib-src button.lib-handover").count(), 1);
+ assert.equal(await row("pdf").locator(".lib-handover").count(), 0, "a skill not kept there has the button");
+ // it stays inside its row, at every width
+ const rb = await row("orca").boundingBox(), bb = await one.boundingBox();
+ assert(bb.x >= rb.x && bb.x + bb.width <= rb.x + rb.width + 1, `the button overflows its row at ${width}px`);
+ // and the path beside it still shows
+ const pb = await row("orca").locator(".lib-src .lib-path").boundingBox();
+ assert(pb.width > 40, `the path gave way to the button at ${width}px: ${pb.width}px`);
+ const before = await scrolls(page);
+
+ // it asks first, saying where it goes and how to put it back
+ await one.click();
+ const sheet = page.locator("#modal .lib-editor");
+ await sheet.waitFor();
+ assert.equal((await sheet.locator(".ehead b").textContent()).trim(), w.ask);
+ const said = (await sheet.locator(".lib-confirm").allTextContents()).join(" ");
+ for (const x of [w.where, w.lib, "Codex", "Gemini CLI", "magpie library skill hand-back orca"]) assert(said.includes(x), `the sheet doesn't say ${x}: ${said}`);
+ await sheet.locator(".bar button", { hasText: w.cancel }).click();
+ await sheet.waitFor({ state: "detached" });
+ assert.deepEqual(posts, [], "Cancel posts nothing");
+
+ // the link-only one says the folder stays
+ await row("grill").locator(".lib-handover").click();
+ await sheet.waitFor();
+ assert((await sheet.locator(".lib-confirm").first().textContent()).includes(w.link), "the link's folder isn't named");
+ await sheet.locator(".bar button", { hasText: w.cancel }).click();
+ await sheet.waitFor({ state: "detached" });
+
+ // moved: one post, the row's button gone, and said
+ await one.click();
+ await sheet.waitFor();
+ const go = sheet.locator(".bar button.primary");
+ assert.equal((await go.textContent()).trim(), w.go);
+ await go.click();
+ await sheet.waitFor({ state: "detached" });
+ assert.deepEqual(posts, [{ what: "hand-over", body: { names: ["orca"] } }]);
+ await row("orca").locator(".lib-handover").waitFor({ state: "detached" });
+ assert.equal((await page.locator("#status").textContent()).trim(), w.done);
+ assert.equal(await scrolls(page), before, "the clicks scrolled the page");
+ await ctx.close();
+ });
+ }
+ // the skills' heading moves every one at once
+ await t.test("all at once", async () => {
+ const w = words.en, posts = [], st = { moved: [] };
+ const ctx = await browser.newContext({ viewport: { width: 860, height: 900 } });
+ await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} });
+ const page = await ctx.newPage();
+ page.setDefaultTimeout(5000);
+ page.on("pageerror", (e) => errors.push(e.message));
+ await page.route("**/*", server("en", posts, st));
+ await page.goto("http://magpie.test/");
+ await page.locator('button[data-view="library"]').click();
+ const all = page.locator("#view-library .lib-skillshead button.lib-handover");
+ await all.waitFor();
+ assert.equal((await all.textContent()).trim(), w.all);
+ await all.click();
+ const sheet = page.locator("#modal .lib-editor");
+ await sheet.waitFor();
+ assert.equal((await sheet.locator(".ehead b").textContent()).trim(), w.askAll);
+ assert.equal(posts.length, 0, "the heading's click posted before asking");
+ await sheet.locator(".bar button.primary").click();
+ await sheet.waitFor({ state: "detached" });
+ assert.deepEqual(posts, [{ what: "hand-over", body: { names: ["orca", "grill"] } }]);
+ await all.waitFor({ state: "detached" });
+ assert.equal((await page.locator("#status").textContent()).trim(), w.doneAll);
+ await ctx.close();
+ });
+ assert.deepEqual(errors, []);
+ });
+}
diff --git a/internal/library/skill_handover.go b/internal/library/skill_handover.go
new file mode 100644
index 000000000..28f485a5f
--- /dev/null
+++ b/internal/library/skill_handover.go
@@ -0,0 +1,294 @@
+package library
+
+import (
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "slices"
+ "time"
+)
+
+// HandOverSkills gives skills kept in ~/.agents/skills to the library to
+// manage (tnt1223 on Discord, "统一移入 magpie 的资源库文件夹,交给 magpie
+// 管理"). Several agents read that folder themselves, so a skill there is
+// on for each of them whatever the library ticks, and turning it off for
+// one, or on this computer alone (OffHere), can't work. Handed over:
+// - a folder kept in ~/.agents/skills moves into the library's own folder
+// (renamed, or copied, checked the same and only then set aside with
+// the backups), and its entry there is gone;
+// - an entry there that only links to a folder elsewhere is taken away,
+// and the library links to that folder past it;
+// - the user's own links to it in the agents' folders, which would point
+// at nothing, are taken away too.
+//
+// Every agent that read it there, or through such a link, is ticked for
+// it, so each goes on having it, now from the library, till it's unticked.
+// A skill not in the library yet (found in ~/.agents/skills) is brought in
+// first. One that can't be handed over stays as it was, in Unmoved, and
+// the others are handed over all the same. HandBackSkill undoes it.
+func HandOverSkills(names []string) (*Result, error) {
+ if len(names) == 0 {
+ return nil, fmt.Errorf("no skills to hand over")
+ }
+ names = slices.Compact(slices.Sorted(slices.Values(names)))
+ var failed, partly []Problem
+ res, err := change(func(l *Library) error {
+ var found []FoundSkill
+ ts := Targets()
+ for _, name := range names {
+ left, err := handOver(l, &found, ts, name)
+ if err != nil {
+ failed = append(failed, Problem{What: "skill:" + name, Error: err.Error()})
+ } else if left != "" {
+ partly = append(partly, Problem{Agent: "agents", What: "skill:" + name, Error: left})
+ }
+ }
+ if len(failed) == len(names) {
+ return errors.New(failed[0].Error)
+ }
+ return nil
+ })
+ if res != nil {
+ res.Unmoved = failed
+ res.Problems = append(res.Problems, partly...)
+ }
+ return res, err
+}
+
+// SharedSkills are the names of the library's skills kept in
+// ~/.agents/skills, which HandOverSkills can move into the library.
+func SharedSkills() ([]string, error) {
+ mu.Lock()
+ defer mu.Unlock()
+ l, err := load()
+ if err != nil {
+ return nil, err
+ }
+ var out []string
+ for _, s := range l.Skills {
+ if sharedHas(s.Name) {
+ out = append(out, s.Name)
+ }
+ }
+ return out, nil
+}
+
+// readsSharedHere are the agents here that read ~/.agents/skills: those
+// that read it besides their own folder, and those whose folder it is.
+func readsSharedHere(ts []*Target) []string {
+ sh := realDir(sharedSkillsDir())
+ var out []string
+ for _, t := range ts {
+ if t.Skills != "" && !t.Gone && t.Desktop == nil && (slices.Contains(readsShared, t.Agent.ID) || realDir(t.Skills) == sh) {
+ out = append(out, t.Agent.ID)
+ }
+ }
+ return out
+}
+
+// handOver hands one skill over (HandOverSkills). left says what of the
+// original couldn't be taken away after a whole copy was made.
+func handOver(l *Library, found *[]FoundSkill, ts []*Target, name string) (left string, err error) {
+ sh := realDir(sharedSkillsDir())
+ if l.skill(name) == nil {
+ if *found == nil {
+ *found = foundSkills(l)
+ }
+ i := slices.IndexFunc(*found, func(f FoundSkill) bool { return f.Name == name })
+ if i < 0 || (*found)[i].Shared == "" && !within((*found)[i].real, sh) {
+ return "", fmt.Errorf("no skill called %s in %s", name, sharedSkillsDir())
+ }
+ if err := importSkill(l, *found, name); err != nil {
+ return "", err
+ }
+ }
+ s := l.skill(name)
+ entry := sharedEntry(name)
+ if entry == "" {
+ return "", fmt.Errorf("%s isn't kept in %s", name, sharedSkillsDir())
+ }
+ lib := skillDir(name)
+ r := realDir(lib)
+ agents := readsSharedHere(ts)
+ // the user's own links to it in the agents' folders: they'd point at
+ // nothing once it moves, and the library gives the agent its own
+ var strays []string
+ for _, t := range ts {
+ if t.Skills == "" || t.Desktop != nil || realDir(t.Skills) == sh {
+ continue
+ }
+ q := filepath.Join(t.Skills, name)
+ if linked(q) && !ours(q, name) && realDir(q) == r {
+ strays = append(strays, q)
+ agents = append(agents, t.Agent.ID)
+ }
+ }
+ if within(r, sh) {
+ // the folder itself is in the shared one: it moves in
+ if !linked(lib) {
+ return "", fmt.Errorf("%s is in the library's folder and in %s at once", name, sharedSkillsDir())
+ }
+ if left, err = moveIn(r, lib); err != nil {
+ return "", err
+ }
+ if e := filepath.Clean(entry); e != r && linked(e) {
+ // a link in the shared folder to it there, by its name
+ if err := os.Remove(e); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ left = err.Error()
+ }
+ }
+ s.Source = nil
+ } else {
+ // the entry only links to a folder elsewhere (or to the library's
+ // own): the library links past it, and only the link goes
+ if !linked(entry) {
+ return "", fmt.Errorf("%s in %s is a folder of its own", name, sharedSkillsDir())
+ }
+ if linked(lib) {
+ via := linkVia(lib, r)
+ old, _ := os.Readlink(lib)
+ if filepath.Clean(old) != filepath.Clean(via) {
+ if err := os.Remove(lib); err != nil {
+ return "", err
+ }
+ if err := dirLink(via, lib); err != nil {
+ if rerr := dirLink(old, lib); rerr != nil {
+ return "", fmt.Errorf("%w; and the library's link to %s couldn't be made again: %v", err, old, rerr)
+ }
+ return "", err
+ }
+ }
+ s.Source = &Source{Kind: "folder", Dir: via}
+ }
+ if err := os.Remove(entry); err != nil {
+ return "", err
+ }
+ }
+ for _, q := range strays {
+ os.Remove(q) // a link: what it pointed at is the library's now
+ }
+ s.Agents = slices.Compact(slices.Sorted(slices.Values(append(s.Agents, agents...))))
+ return left, nil
+}
+
+// moveIn puts the folder from in the place of the library's link lib to
+// it: renamed, or where that can't be (another disk), copied, checked to
+// hold the very same files, and only then set aside with the backups. On
+// a failure the folder stays where it was and lib links to it as before.
+// left is what of from couldn't be taken away after its whole copy was
+// in (a file in it held open, on Windows).
+func moveIn(from, lib string) (left string, err error) {
+ tmp := filepath.Join(filepath.Dir(lib), "."+filepath.Base(lib)+".magpie-in-"+time.Now().Format("20060102150405.000"))
+ renamed := os.Rename(from, tmp) == nil
+ if !renamed {
+ if err := copyDir(from, tmp); err != nil {
+ os.RemoveAll(tmp)
+ return "", err
+ }
+ // a copy that can't be read back the same is no copy: the
+ // original stays where it is
+ if !sameTree(from, tmp) {
+ os.RemoveAll(tmp)
+ return "", fmt.Errorf("the copy of %s didn't read back the same; it stays where it is", from)
+ }
+ }
+ back := func() {
+ if renamed {
+ os.Rename(tmp, from)
+ } else {
+ os.RemoveAll(tmp)
+ }
+ }
+ old, err := os.Readlink(lib)
+ if err != nil {
+ back()
+ return "", err
+ }
+ if err := os.Remove(lib); err != nil {
+ back()
+ return "", err
+ }
+ if err := os.Rename(tmp, lib); err != nil {
+ dirLink(old, lib)
+ back()
+ return "", err
+ }
+ if renamed {
+ return "", nil
+ }
+ if _, err := setAside("agents", from); err != nil {
+ var lb *leftBehind
+ if errors.As(err, &lb) {
+ // whole in the library and in the backups; what is left of
+ // it where it was is said
+ return fmt.Sprintf("moved into the library, but part of %s couldn't be taken away: %v", from, err), nil
+ }
+ // nothing of it moved: as it was before
+ os.RemoveAll(lib)
+ dirLink(old, lib)
+ return "", err
+ }
+ return "", nil
+}
+
+// HandBackSkill puts a skill handed over (HandOverSkills) back into
+// ~/.agents/skills: its folder moves there, and the library links to it,
+// as it did before. Which agents it's ticked for stays as it is; those
+// that read ~/.agents/skills have it again whatever is ticked.
+func HandBackSkill(name string) (*Result, error) {
+ return change(func(l *Library) error {
+ s := l.skill(name)
+ if s == nil {
+ return fmt.Errorf("no skill called %s", name)
+ }
+ lib := skillDir(name)
+ if linked(lib) {
+ return fmt.Errorf("%s isn't kept in the library's folder: it links to %s", name, realDir(lib))
+ }
+ if fi, err := os.Stat(lib); err != nil || !fi.IsDir() {
+ return fmt.Errorf("%s has no folder in the library: %v", name, err)
+ }
+ p := filepath.Join(sharedSkillsDir(), name)
+ if _, err := os.Lstat(p); err == nil {
+ if !ours(p, name) {
+ return fmt.Errorf("%s has a %s of its own", sharedSkillsDir(), name)
+ }
+ // magpie's own link there (for Goose, Kimi Code or Cindy)
+ if err := unlink(p); err != nil {
+ return err
+ }
+ } else if !errors.Is(err, fs.ErrNotExist) {
+ return err
+ }
+ if err := os.MkdirAll(sharedSkillsDir(), 0o755); err != nil {
+ return err
+ }
+ if err := os.Rename(lib, p); err != nil {
+ if err := copyDir(lib, p); err != nil {
+ os.RemoveAll(p)
+ return err
+ }
+ if !sameTree(lib, p) {
+ os.RemoveAll(p)
+ return fmt.Errorf("the copy of %s didn't read back the same; it stays in the library", name)
+ }
+ if _, err := setAside("library", lib); err != nil {
+ var lb *leftBehind
+ if !errors.As(err, &lb) {
+ os.RemoveAll(p)
+ }
+ return err
+ }
+ }
+ if err := dirLink(p, lib); err != nil {
+ if rerr := move(p, lib); rerr != nil {
+ return fmt.Errorf("%w; the skill is at %s", err, p)
+ }
+ return err
+ }
+ s.Source = &Source{Kind: "folder", Dir: p}
+ return nil
+ })
+}
diff --git a/internal/library/skill_handover_test.go b/internal/library/skill_handover_test.go
new file mode 100644
index 000000000..364616ea2
--- /dev/null
+++ b/internal/library/skill_handover_test.go
@@ -0,0 +1,264 @@
+package library
+
+import (
+ "os"
+ "path/filepath"
+ "slices"
+ "testing"
+)
+
+// noGoose takes Goose, whose own folder is ~/.agents/skills, out of the
+// sandbox, so the shared folder holds only what a test puts there.
+func noGoose(t *testing.T, h string) {
+ t.Helper()
+ os.RemoveAll(filepath.Join(h, ".config/goose"))
+ os.Remove(filepath.Join(h, "bin/goose"))
+ os.Remove(filepath.Join(h, "bin/goose.exe"))
+}
+
+// realFolder: p is a folder, not a link to one
+func realFolder(p string) bool {
+ fi, err := os.Lstat(p)
+ return err == nil && fi.IsDir()
+}
+
+// tnt1223 on Discord: a skill kept in ~/.agents/skills is on for every
+// agent that reads that folder, whatever is ticked. Handed over, its
+// folder is the library's own, the agents that read it there are ticked
+// and keep it, and each can then be turned off, here alone too.
+func TestHandOverSharedFolder(t *testing.T) {
+ h := sandbox(t)
+ noGoose(t, h)
+ shared := filepath.Join(h, ".agents/skills")
+ skill(t, filepath.Join(shared, "orchestration"), "orchestration", "Orchestrate")
+ symlink(t, filepath.Join(shared, "orchestration"), filepath.Join(h, ".pi/agent/skills/orchestration"))
+ ok(t)(ImportSkill("orchestration"))
+ if v := offView(t, "orchestration"); v.Shared != filepath.Join(shared, "orchestration") || v.SharedElsewhere || !slices.Contains(v.Always, "codex") {
+ t.Fatalf("before: %+v", v)
+ }
+ if n, err := SharedSkills(); err != nil || !slices.Equal(n, []string{"orchestration"}) {
+ t.Fatalf("shared skills: %v %v", n, err)
+ }
+
+ ok(t)(HandOverSkills([]string{"orchestration"}))
+ if _, err := os.Lstat(filepath.Join(shared, "orchestration")); !os.IsNotExist(err) {
+ t.Fatalf("still in ~/.agents/skills: %v", err)
+ }
+ lib := skillDir("orchestration")
+ if linked(lib) || !realFolder(lib) {
+ t.Fatal("the library's isn't a folder of its own")
+ }
+ if read(t, filepath.Join(lib, "scripts/run.sh")) != "echo hi\n" {
+ t.Fatal("its files didn't come along")
+ }
+ v := offView(t, "orchestration")
+ if v.Shared != "" || len(v.Always) != 0 || v.Kind != "" {
+ t.Errorf("after: %+v", v)
+ }
+ // the readers and pi, which linked to it, keep it, ticked now
+ for _, id := range []string{"codex", "gemini", "pi"} {
+ if !slices.Contains(v.Agents, id) {
+ t.Errorf("%s isn't ticked: %v", id, v.Agents)
+ }
+ }
+ if slices.Contains(v.Agents, "claude") {
+ t.Errorf("claude never had it: %v", v.Agents)
+ }
+ for _, d := range []string{".codex/skills/orchestration", ".gemini/skills/orchestration", ".pi/agent/skills/orchestration"} {
+ if p := filepath.Join(h, d); !ours(p, "orchestration") {
+ t.Errorf("%s isn't the library's", d)
+ }
+ }
+ // and now one agent can be without it
+ var rest []string
+ for _, id := range v.Agents {
+ if id != "codex" {
+ rest = append(rest, id)
+ }
+ }
+ ok(t)(SkillAgents("orchestration", rest))
+ if given(h, ".codex", "orchestration") {
+ t.Error("unticked, codex still has it")
+ }
+ if !given(h, ".gemini", "orchestration") {
+ t.Error("gemini lost it")
+ }
+ // or this computer
+ ok(t)(SkillHere("orchestration", false))
+ if given(h, ".gemini", "orchestration") || given(h, ".pi/agent", "orchestration") {
+ t.Error("off here, an agent still has it")
+ }
+ if _, err := os.Lstat(filepath.Join(shared, "orchestration")); !os.IsNotExist(err) {
+ t.Error("off here, it came back to ~/.agents/skills")
+ }
+
+ // handed back: in ~/.agents/skills again, the library linking to it
+ ok(t)(SkillHere("orchestration", true))
+ ok(t)(HandBackSkill("orchestration"))
+ if !realFolder(filepath.Join(shared, "orchestration")) || read(t, filepath.Join(shared, "orchestration/scripts/run.sh")) != "echo hi\n" {
+ t.Fatal("not back in ~/.agents/skills")
+ }
+ if !linked(lib) || realDir(lib) != realDir(filepath.Join(shared, "orchestration")) {
+ t.Fatal("the library doesn't link to it")
+ }
+ if v := offView(t, "orchestration"); v.Shared == "" {
+ t.Errorf("handed back: %+v", v)
+ }
+}
+
+// An entry in ~/.agents/skills that only links to a folder elsewhere: the
+// link goes, the folder stays, and the library links to the folder.
+func TestHandOverSharedLink(t *testing.T) {
+ h := sandbox(t)
+ noGoose(t, h)
+ shared := filepath.Join(h, ".agents/skills")
+ ext := filepath.Join(h, "aimer-skills/grilling")
+ skill(t, ext, "grilling", "Grill")
+ symlink(t, ext, filepath.Join(shared, "grilling"))
+ ok(t)(ImportSkill("grilling"))
+ if v := offView(t, "grilling"); v.Shared == "" || !v.SharedElsewhere {
+ t.Fatalf("before: %+v", v)
+ }
+ ok(t)(HandOverSkills([]string{"grilling"}))
+ if _, err := os.Lstat(filepath.Join(shared, "grilling")); !os.IsNotExist(err) {
+ t.Fatalf("the shared link is still there: %v", err)
+ }
+ if read(t, filepath.Join(ext, "SKILL.md")) == "" {
+ t.Fatal("the folder elsewhere went")
+ }
+ lib := skillDir("grilling")
+ if !linked(lib) || realDir(lib) != realDir(ext) {
+ t.Fatal("the library doesn't link to the folder")
+ }
+ v := offView(t, "grilling")
+ if v.Shared != "" || v.Kind != "folder" || realDir(v.Source) != realDir(ext) || !slices.Contains(v.Agents, "codex") {
+ t.Errorf("after: %+v", v)
+ }
+ if !ours(filepath.Join(h, ".codex/skills/grilling"), "grilling") {
+ t.Error("codex didn't get the library's")
+ }
+}
+
+// A skill found in ~/.agents/skills, never brought in, is brought in and
+// handed over at once; a name that isn't there is said, and the other is
+// handed over all the same.
+func TestHandOverFound(t *testing.T) {
+ h := sandbox(t)
+ noGoose(t, h)
+ shared := filepath.Join(h, ".agents/skills")
+ skill(t, filepath.Join(shared, "orca-cli"), "orca-cli", "Orca")
+ // a user's own link to it in Claude Code's folder
+ symlink(t, filepath.Join(shared, "orca-cli"), filepath.Join(h, ".claude/skills/orca-cli"))
+ res, err := HandOverSkills([]string{"orca-cli", "nope"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(res.Unmoved) != 1 || res.Unmoved[0].What != "skill:nope" {
+ t.Fatalf("unmoved: %+v", res.Unmoved)
+ }
+ if _, err := os.Lstat(filepath.Join(shared, "orca-cli")); !os.IsNotExist(err) {
+ t.Fatalf("still in ~/.agents/skills: %v", err)
+ }
+ if lib := skillDir("orca-cli"); linked(lib) || !realFolder(lib) {
+ t.Fatal("not in the library's folder")
+ }
+ v := offView(t, "orca-cli")
+ for _, id := range []string{"claude", "codex", "gemini"} {
+ if !slices.Contains(v.Agents, id) {
+ t.Errorf("%s isn't ticked: %v", id, v.Agents)
+ }
+ }
+ if !ours(filepath.Join(h, ".claude/skills/orca-cli"), "orca-cli") {
+ t.Error("claude's link isn't the library's")
+ }
+ // none at all: an error, and nothing changes
+ if _, err := HandOverSkills([]string{"nope"}); err == nil {
+ t.Error("handing over nothing there said nothing")
+ }
+}
+
+// A copy that can't be made leaves the skill where it was: the rename
+// fails (another disk), and the copy fails too.
+func TestHandOverFailureKeepsOriginal(t *testing.T) {
+ h := sandbox(t)
+ noGoose(t, h)
+ shared := filepath.Join(h, ".agents/skills")
+ skill(t, filepath.Join(shared, "orchestration"), "orchestration", "Orchestrate")
+ ok(t)(ImportSkill("orchestration"))
+ lib := skillDir("orchestration")
+ // a file in the way of the folder the move makes in the library's
+ // skills folder: neither a rename nor a copy can get there
+ skills := filepath.Dir(lib)
+ if err := os.Chmod(skills, 0o555); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.Chmod(skills, 0o755) })
+ if f, err := os.Create(filepath.Join(skills, ".probe")); err == nil {
+ f.Close()
+ t.Skip("a read-only folder can be written here (root, or Windows)")
+ }
+ res, err := HandOverSkills([]string{"orchestration"})
+ if err == nil {
+ t.Fatalf("moved into a read-only folder: %+v", res)
+ }
+ os.Chmod(skills, 0o755)
+ if !realFolder(filepath.Join(shared, "orchestration")) || read(t, filepath.Join(shared, "orchestration/scripts/run.sh")) != "echo hi\n" {
+ t.Fatal("the original isn't where it was")
+ }
+ if !linked(lib) || realDir(lib) != realDir(filepath.Join(shared, "orchestration")) {
+ t.Fatal("the library no longer links to it")
+ }
+ if v := offView(t, "orchestration"); v.Shared == "" {
+ t.Errorf("after the failure: %+v", v)
+ }
+}
+
+// Goose reads ~/.agents/skills as its own folder: handed over, the
+// library gives it a link there, and the skill's folder is the library's.
+func TestHandOverWithGoose(t *testing.T) {
+ h := sandbox(t)
+ shared := filepath.Join(h, ".agents/skills")
+ skill(t, filepath.Join(shared, "orchestration"), "orchestration", "Orchestrate")
+ ok(t)(ImportSkill("orchestration"))
+ ok(t)(HandOverSkills([]string{"orchestration"}))
+ lib := skillDir("orchestration")
+ if linked(lib) || !realFolder(lib) {
+ t.Fatal("not in the library's folder")
+ }
+ if !ours(filepath.Join(shared, "orchestration"), "orchestration") {
+ t.Fatal("goose's isn't the library's")
+ }
+ if v := offView(t, "orchestration"); !slices.Contains(v.Agents, "goose") || v.Shared != "" {
+ t.Errorf("after: %+v", v)
+ }
+}
+
+// A skill kept in ~/.agents/skills under another folder's name is still
+// the shared folder's: Goose, whose folder that is, isn't given a second
+// one beside it, and handed over, the folder moves in by the skill's name.
+func TestSharedUnderAnotherName(t *testing.T) {
+ h := sandbox(t)
+ shared := filepath.Join(h, ".agents/skills")
+ skill(t, filepath.Join(shared, "orchestration-v2"), "orchestration", "Orchestrate")
+ // linked into the library's folder by hand, and brought in from there
+ symlink(t, filepath.Join(shared, "orchestration-v2"), skillDir("orchestration"))
+ ok(t)(ImportSkill("orchestration"))
+ ok(t)(SkillAgents("orchestration", []string{"claude", "goose"}))
+ if _, err := os.Lstat(filepath.Join(shared, "orchestration")); !os.IsNotExist(err) {
+ t.Fatalf("goose was given it twice: %v", err)
+ }
+ v := offView(t, "orchestration")
+ if v.Shared != filepath.Join(shared, "orchestration-v2") || !slices.Contains(v.Always, "codex") {
+ t.Fatalf("before: %+v", v)
+ }
+ ok(t)(HandOverSkills([]string{"orchestration"}))
+ if _, err := os.Lstat(filepath.Join(shared, "orchestration-v2")); !os.IsNotExist(err) {
+ t.Fatalf("still in ~/.agents/skills: %v", err)
+ }
+ if lib := skillDir("orchestration"); linked(lib) || !realFolder(lib) {
+ t.Fatal("not in the library's folder")
+ }
+ if !ours(filepath.Join(shared, "orchestration"), "orchestration") {
+ t.Error("goose isn't given the library's")
+ }
+}
diff --git a/internal/library/skills.go b/internal/library/skills.go
index bfc509b1d..21ff11a57 100644
--- a/internal/library/skills.go
+++ b/internal/library/skills.go
@@ -499,18 +499,33 @@ func linked(p string) bool {
func sharedSkillsDir() string { return filepath.Join(home(), ".agents", "skills") }
// sharedHas is whether the library's skill by that name is kept in
-// ~/.agents/skills: the user's own entry there (not a link magpie made)
-// is the very folder the library's is or links to, so every agent that
-// reads the shared folder has it, whatever the library gives.
-func sharedHas(name string) bool {
- p, lib := filepath.Join(sharedSkillsDir(), name), skillDir(name)
- if _, err := os.Lstat(p); err != nil || ours(p, name) {
- return false
- }
+// ~/.agents/skills, so every agent that reads the shared folder has it,
+// whatever the library gives (sharedEntry).
+func sharedHas(name string) bool { return sharedEntry(name) != "" }
+
+// sharedEntry is the user's own entry in ~/.agents/skills (not a link
+// magpie made) by which the agents reading that folder find the library's
+// skill by that name: the very folder the library's is or links to. That
+// is the entry by its name, or, for a library skill linked to a folder
+// right in the shared one under another name, that entry. "" when none.
+// HandOverSkills moves such a skill out of it (skill_handover.go).
+func sharedEntry(name string) string {
+ lib := skillDir(name)
if _, err := os.Stat(lib); err != nil {
- return false
+ return ""
+ }
+ r := realDir(lib)
+ p := filepath.Join(sharedSkillsDir(), name)
+ if _, err := os.Lstat(p); err == nil && !ours(p, name) && realDir(p) == r {
+ return p
}
- return realDir(p) == realDir(lib)
+ sh := realDir(sharedSkillsDir())
+ if rel, err := filepath.Rel(sh, r); err == nil && within(r, sh) && rel != "." && !strings.ContainsRune(rel, filepath.Separator) {
+ if q := filepath.Join(sharedSkillsDir(), rel); !ours(q, rel) && realDir(q) == r {
+ return q
+ }
+ }
+ return ""
}
// within is whether p is dir or inside it.
@@ -544,6 +559,7 @@ func (l *Library) syncSkills(t *Target, res *Result, all []*Target) {
// a skill magpie put there for another (Kimi Code) already: a link in
// its own too would be the skill twice
shared := realDir(sharedSkillsDir())
+ isShared := realDir(t.Skills) == shared
inShared := func(s *Skill) bool {
if s == nil || !slices.Contains(readsShared, id) || realDir(t.Skills) == shared {
return false
@@ -596,6 +612,14 @@ func (l *Library) syncSkills(t *Target, res *Result, all []*Target) {
}
continue
}
+ // kept in ~/.agents/skills under another name (sharedEntry): the
+ // agent whose folder that is has it there already, and a link by
+ // this name too would be the skill twice for every reader of it
+ if isShared && !ours(p, s.Name) {
+ if e := sharedEntry(s.Name); e != "" && e != p {
+ continue
+ }
+ }
if inShared(s) {
// a copy of its own of the very same files would be the skill
// twice as much as a link: kept aside, as it would be for one
diff --git a/internal/library/sync.go b/internal/library/sync.go
index 3faed9993..334b0652d 100644
--- a/internal/library/sync.go
+++ b/internal/library/sync.go
@@ -31,6 +31,9 @@ type Result struct {
// Unremoved are, for skills or servers taken out together, the ones
// that couldn't be (What is skill:<name> or mcp:<name>)
Unremoved []Problem `json:"unremoved,omitempty"`
+ // Unmoved are, for skills handed over from ~/.agents/skills, the ones
+ // that couldn't be moved and stay where they were (What is skill:<name>)
+ Unmoved []Problem `json:"unmoved,omitempty"`
// Installed, Had and Skipped are, for skills installed together, the
// ones added, the ones the library had already from the same source,
// and the ones left out with why: another skill by that name, the
@@ -429,6 +432,12 @@ type SkillView struct {
// Always are the agents that have it whatever the library gives them:
// it is kept in ~/.agents/skills, which they read themselves (#595)
Always []string `json:"always,omitempty"`
+ // Shared is its entry in ~/.agents/skills when it is kept there:
+ // HandOverSkills moves it into the library's own folder
+ Shared string `json:"shared,omitempty"`
+ // SharedElsewhere: that entry only links to a folder kept elsewhere,
+ // which stays there when it's handed over; only the link goes
+ SharedElsewhere bool `json:"sharedElsewhere,omitempty"`
// Behind are the agents given it as a copy whose copy differs from it,
// till the next sync makes it again
Behind []string `json:"behind,omitempty"`
@@ -610,7 +619,8 @@ func readView(problems []Problem, glance bool) (*View, error) {
} else if _, err := os.Lstat(p); err == nil && sv.Kind == "folder" {
sv.Kind, sv.Source = "", ""
}
- if sharedHas(s.Name) {
+ if sv.Shared = sharedEntry(s.Name); sv.Shared != "" {
+ sv.SharedElsewhere = !within(realDir(skillDir(s.Name)), realDir(sharedSkillsDir()))
for _, t := range targets {
if t.Skills != "" && (slices.Contains(readsShared, t.Agent.ID) || realDir(t.Skills) == realDir(sharedSkillsDir())) {
sv.Always = append(sv.Always, t.Agent.ID)