library: slash commands, written into each agent's own command folder

miantiao_me on X asked for custom slash commands (prompt templates) kept
once in the Library and given to agents as skills are. Library → Slash
commands keeps a name, a description and a prompt where $ARGUMENTS is
every word typed after /name and $1, $2… the first, second… word. Each
ticked agent gets its own command file, in its own folder and shape
(internal/library/commands.go, from each agent's docs and source):

- Claude Code: <claude dir>/commands/<name>.md; $n becomes $ARGUMENTS[n-1]
  (Claude counts from 0), a literal $0 is escaped.
- OpenCode: <config>/commands/<name>.md, as written.
- Pi: <agent dir>/prompts/<name>.md, as written.
- Gemini CLI: ~/.gemini/commands/<name>.toml, $ARGUMENTS is {{args}}.
- Qwen Code: <qwen home>/commands/<name>.md, {{args}}.
- Factory Droid: ~/.factory/commands/<name>.md, $ARGUMENTS.
- Gemini, Qwen and Droid have no $1…: a command using them is not written
  for those agents, and the row and editor say so.
- Codex is listed greyed: it reads ~/.codex/prompts no more, its skills
  took their place. WSL agents get none yet.

What magpie wrote is recorded per file with its hash (Applied.Commands),
through syncOwnFiles, now shared with subagents: a file the user changed,
or one by that name magpie didn't write, is never overwritten or removed;
one equal to magpie's bytes is adopted. Commands travel with backups and
WebDAV sync (Bundle.Commands; an older bundle keeps this computer's).
docs/subsystems/library.md has the row.

Run (mote was over its load, so mica, then mote at the end):
- At 4119054bb on origin/main 90efddaba: gofmt -l clean; GOOS=linux and
  GOOS=windows go vet -tags nogui ./... ok; go test -timeout 45m ./...
  every package ok but internal/cli's TestEveryRouteHasACommandOrIsNamed
  (POST /api/providers/delete, from 90efddaba, #6677).
- GUI at 5783bf8cb (on 49f49c41c): the 276 files this can reach (every
  library, i18n and sidebar-icon file, new library-commands included),
  both engines, 420 and 1100, en/zh/zh-TW/ja/de: 5218 of 5340 pass. The 15
  red files were run again at 49f49c41c itself and are red the same
  there, test for test.
- At this head (rebased on 217e933dd, which touches only core i18n.js of
  these files): internal/library, gui, davsync ok, cli red as above;
  the 81 library, i18n and nav-sub-icons GUI files pass but library-env
  (#6675).
- Final head (rebased on cd030691a): go test ./internal/library ok; GUI
  library-commands, -plugins, -hooks, -subagents, -groups and i18n-keys,
  both engines: 68 of 68 pass.
- Broken by hand: Claude's $n mapping left as written turns
  TestCommandsWordsByPlace red; the sidebar section missing turned
  library-groups red (my bug, fixed here).
- Real, sandbox HOME: Claude Code 2.1.316 `claude -p "/magpietry alpha
  beta"` expanded first=[alpha] second=[beta]; OpenCode 2.0.25 listed it
  (GET /api/command) and its session command expanded the same. Gemini
  got the $n problem and no file.

Red on origin/main too, not this change: found-skill-pick-remove (#5013),
library-env (#6675), skill-group-shared (#6687), old-webkit (#6030,
#5919), the /api/update/using posts (#6133, #6667, #6668), library-new-skill
(#6539), mobile-web (#5013), phone-no-sideways (#5869), view-no-sideways
(#6669), and skill-where, text-size, usage-ledger and
usage-speed-all-models, each with an open issue. Left alone: a Claude plugin's
commands becoming library commands (#6672).

Not tried: pi, Qwen Code and Droid binaries (their files checked by tests
only), Codex (greyed), a real run on Windows or Linux.
This commit is contained in:
yetone
2026-11-15 00:48:52 +08:00
parent cd030691a3
commit 91d27452b7
20 changed files with 1308 additions and 50 deletions
+7 -4
View File
@@ -1,9 +1,9 @@
# Library: instructions, MCP servers, skills, hooks, subagents, RTK and billion-context
# Library: instructions, MCP servers, skills, hooks, subagents, slash commands, RTK and billion-context
The library keeps what every agent should know in one place: the
instructions each agent reads before a conversation, the MCP servers it can
call, the skills it can load, the hooks it runs at points of its turn, and
the subagents it can hand a task to.
the subagents it can hand a task to, and the slash commands typed into it.
magpie writes these into each agent's own
files in that agent's format, and takes back only what it wrote. Everything
else in those files stays as it was. Package `internal/library` also gives
@@ -37,6 +37,7 @@ Pi's extensions and packages.
| Variables | An `EnvVar` (paopao_baobao on X) is a name, a value and the agents ticked for it (`internal/library/env.go`). Claude Code gets it in `settings.json`'s `env`, Codex in `config.toml`'s `[shell_environment_policy.set]` (`envFile`, `writeEnv`); an agent with no such setting is greyed on the tab, saying why. `syncEnv` records what it wrote in `Applied.Env` and never overrides the user: a name the file already sets to another value is left as it is and reported as a problem on the row (`env:<name>`), and a recorded value the user changed in the file is theirs from then on (the record is dropped, a removal or a turn-off leaves it). Turning an agent off or removing the variable takes out only the recorded, unchanged value. Codex's spelling is respected: a `set` sub-table or an inline `set = {…}` is edited, a dotted spelling is refused with `left as it is`. An unreadable or wrongly typed file is an error, never empty, and nothing is written. Names are `[A-Za-z_][A-Za-z0-9_]*`, at most 128, values at most 8192 bytes. Variables are carried with the library (see below). Tests: `TestEnvWrittenAndTakenOut`, `TestEnvNeverOverridesTheUsers`, `TestEnvValueChanged`, `TestEnvCodexInlineSet`, `TestEnvUnreadableFileLeftAlone`, `TestEnvChecked`, `library-env.test.cjs`. |
| Subagents | A `Subagent` (#2283) is a name (lowercase letters, digits and -), a one-line description, a prompt, and the library's skills and MCP servers it uses, given to the agents ticked for it. `syncSubagents` writes it as a file of its own in each agent's user-level folder, in that agent's format (`subagentSpecOf`): Markdown with YAML front matter in `~/.claude/agents` (with `skills` and `mcpServers`), `~/.factory/droids` (with `mcpServers`), `~/.config/opencode/agents` (`mode: subagent`), `~/.gemini/agents`, `~/.qwen/agents`, `~/.grok/agents`, `~/.cursor/agents` and `~/.copilot/agents` (`<name>.agent.md`); a TOML role (`name`, `description`, `model` when set, `developer_instructions`) in `$CODEX_HOME/agents`. Skills and servers are named only where the agent's file can name them, and only those the library has. A subagent's optional `Model` (a model or routing group of Codex's list, `subagentModels` in `/api/library`) is written only into Codex's role (luckymanjc on Discord): the role file is a config layer, and Codex lays its `model` over the one its lead names in spawn_agent (`apply_spawn_agent_role` after `apply_requested_spawn_agent_model_overrides` in codex-rs `core/src/agent/child_config.rs`), so the subagent's requests carry it and the gateway routes them as any other. Codex's subagent model on the Agents page (`CodexSubagentModel`), when set, still rewrites every subagent's request, and the editor says so. Without one, a Codex subagent runs on the model its lead names, else the lead's own. The page lists, per agent, whether it binds skills, servers and a model (`SubagentAgentView`), names the agents that run a subagent on their own pick, and greys out an agent that takes none. | [`subagents.go`](../../internal/library/subagents.go) |
| Subagents from a repository | The Subagents tab's find line (CHENGJIAHEGOXIS on X: msitarzewski/agency-agents) takes what the skill installer does, owner/repo, a GitHub or GitLab link to the repository, a folder or a file in it, any git address, or a folder here, and fetches it the same way (`fetchSourceRoot`, shared with `resolvePluginRoot`; `tooBig` refuses a whole repository too big to download and asks for its folder's link). `ProbeSubagents` lists each Markdown file with front matter that has a description (`readSubagentAt`): its name is the slug of `name` (`subagentName`), else the file's own name when it sits in an `agents` or `droids` folder; its description is folded to one line of at most 1000 characters; the body is the prompt. Every other key (`color`, `emoji`, `vibe`, `tools`, `author`, `model`, …) is dropped, a Codex TOML role is not read, and a skill's folder (one with a SKILL.md) and `.git`, `.github`, `node_modules` are skipped. Of two files with one name the shallower is taken and the other is listed in `Left` with why, as is one `Subagent.check` refuses (a reserved name). `ImportSubagents` (`POST /api/library/subagents/probe`, then `subagents/import` with `source`, `paths`, `agents`) adds the picked ones for the agents ticked, recording where each came from (`From`, a `Source` with the file's path) and the hash of its description and prompt as imported (`FromHash`). Imported again, from the repository's link or a folder's or a file's, a subagent from the same file is `have` when it is the same, `update` when upstream changed and the library's still matches `FromHash` (its description and prompt are replaced, its agents, skills, servers and model kept), and `edited` when the user changed it here (`SaveSubagent` keeps `From`; it is left as it is). A name the library has for another subagent is never written over: the import takes the next free `name-N`. A carried library carries `From`. The page lists what was found to pick from, with Select all, a filter past eight, a tag for each state and the files left out (`TestSubagentsFromAgencyAgents`, `TestSubagentImportLeavesTheUsersOwn`, `TestSubagentImportAgainUpdates`, `TestSubagentsFromAFolder`, `library-subagents-import.test.cjs`; the fixture is agency-agents' own files in `testdata/agency-agents`). | [`subagent_import.go`](../../internal/library/subagent_import.go), [`plugin.go`](../../internal/library/plugin.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) |
| Slash commands | A `Command` (miantiao_me on X) is a name (lowercase letters, digits, - and _), a one-line description and a prompt, given to the agents ticked for it, and typed as /name there. The prompt says `$ARGUMENTS` for every word typed after the name and `$1`, `$2`… for the first, second… of them. `syncCommands` writes it as a file of its own in each agent's user-level folder, in that agent's shape (`commandSpecOf`): `<claude dir>/commands/<name>.md` (front matter `description`; `$n` becomes Claude Code's `$ARGUMENTS[n-1]`, counted from 0), OpenCode's `commands/<name>.md` beside its config and Pi's `<agent dir>/prompts/<name>.md` (`$ARGUMENTS` and `$n` as magpie's), `~/.gemini/commands/<name>.toml` (`description`, `prompt`, `$ARGUMENTS` as `{{args}}`), Qwen Code's `commands/<name>.md` (`{{args}}`) and `~/.factory/commands/<name>.md` (`$ARGUMENTS`). Gemini CLI, Qwen Code and Droid take no words by place, so a command that uses `$1`… isn't written for them: the agent gets a problem, the editor names them under the prompt while it uses one, and the tab says so under the list. Codex is listed but greyed: Codex 0.165 has no loader of `~/.codex/prompts` any more, its skills took their place. An agent in a WSL distro gets none. The page lists, per agent, its folder and whether it takes `$1`… (`CommandAgentView`). There is no CLI for them yet. | [`commands.go`](../../internal/library/commands.go), `TestCommandsEachAgentsFile`, `TestCommandsWordsByPlace` |
| Claude plugins | A `Plugin` (FakeshadowzZ on X) is a Claude Code plugin kept as one item: `.claude-plugin/plugin.json`, `skills/<name>/SKILL.md`, `agents/*.md`, `hooks/hooks.json` and `.mcp.json`, from a folder, a git address or a marketplace.json (`ProbePlugins`, `InstallPlugins`; a marketplace entry with a relative path, or a github/url/git source, is fetched when installed). Its files are copied to `<library>/plugins/<name>`; `${CLAUDE_PLUGIN_ROOT}` is that folder and `${CLAUDE_PLUGIN_DATA}` is `<library>/plugin-data/<name>`, which an update keeps. No agent sets either variable outside Claude Code's plugin runtime, so every reference is resolved before a part is written out ([`plugin_env.go`](../../internal/library/plugin_env.go)): `${NAME}`/`$NAME` in a hook command, a server's command, args and env, a subagent's prompt and a copied SKILL.md become the folder; a hook program's own read (`process.env.NAME`, `Bun.env`, `Deno.env.get`, Python's `os.environ`/`os.getenv`, Ruby's `ENV`) becomes a quoted string literal of the folder with forward slashes, and PowerShell's `$env:NAME` and cmd's `%NAME%` the folder (ponytail's hooks threw at every start without it, @AXmake110 on X); a command server is given both variables in its env, as Claude Code gives them. Parts a magpie before this wrote with the variables in them are resolved at load (`healPluginRefs`) and written out again at the next sync; a SKILL.md copied before is fixed by Update or a reinstall. Exec-form hooks (`args`) and `CLAUDE_PLUGIN_OPTION_<KEY>` are not carried yet (#6682). Its parts are ordinary library skills, MCP servers, hooks and subagents, each tagged `Bundle: <plugin>`, so every agent gets them through the code of its kind and the old tabs go on working; the plugin holds the names, its agents and `Off`. `PluginAgents` sets every part's agents, `PluginOn` clears them (kept in `Agents` for turning it on again) or gives them back, `RemovePlugin` removes the parts, and `UpdatePlugin` reads the source again. A hook whose Claude event and matcher have a portable event becomes it (Stop turn-end, PostToolUse after-tool, PreToolUse before-tool, UserPromptSubmit prompt, SessionStart session-start; Bash is shell, Edit/Write/MultiEdit is edit); any other event is `claude:<Event>`, for Claude Code only. Subagents go to the agents in `SubagentAgents`. A part whose name the library has gets the prefix `<plugin>-`: the user's own item is never written over or removed. Slash commands, LSP servers and hooks that aren't a command are listed in `Left` and shown, not carried. A backup file carries the parts but not the plugin record or its folder, so on another computer they are ordinary items whose `${CLAUDE_PLUGIN_ROOT}` paths don't exist (`TestPluginImportCarryOnOffRemove`, `TestPluginHookReadsRootFromItsProgram`, `TestPluginHookWrittenBeforeIsResolved`, `TestPluginPartsGetItsFolders`, `TestPluginNameClashKeepsTheUsersOwn`, `TestPluginMarketplaceAndUpdate`, `TestPluginRefusesWhatIsNone`, `library-plugins.test.cjs`). | [`plugin.go`](../../internal/library/plugin.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) |
| Backups | Before a change first writes an agent file, `backups` copies it to `BackupDir`, one folder per change. The last `keepBackups` (30) changes are kept. The Backups button at the top of every tab, beside Library folder, opens that folder (`libHead`; Dade on Discord found it at the foot of a long page). | [`backup.go`](../../internal/library/backup.go) |
| RTK | `SetRTK` runs rtk's own installer (`rtk init -g …`) for an agent being switched on. For one being switched off, it removes exactly what the installer wrote, using magpie's own code, which works even with rtk gone. An rtk.exe in one of winget's folders that winget has no record of (`winget list` says so, or its records name another folder; netube99 on X, 0x8A150014) is upgraded from rtk's own Windows release over the file a `WinGet\Links` link points to, not by `winget upgrade`. `ReadRTK` reads each agent's files to say which have the hook. An agent gone for its CLI (`CLIMissing`, #2254) isn't offered rtk, but one that still has the hook is listed so it can be taken out. `rtkSpec.blocked` stops the installer where it would break an agent. `rtkSpec.env` tells the installer the agent's folder where rtk would pick another: Hermes Agent's is `appdir.HermesHome` (`%LOCALAPPDATA%\hermes` on Windows), which rtk is given as `HERMES_HOME`, since rtk 0.51 knows only `$HERMES_HOME` and `~/.hermes`. Antigravity CLI (`agy`, #2202) gets rtk 0.51's own plugin for Antigravity, `plugins/rtk` in its global customization folder `~/.gemini/config` (`plugin.json`, `hooks.json` with `PreToolUse` → `rtk hook antigravity`, `rules/AGENTS.md`), which `agy plugin list` lists; switching it off takes that one folder out. rtk 0.50 knows Antigravity only per project and fails `rtk init -g --agent antigravity`, so an older rtk is `blocked` (`agyBlocked`) and the row says to update RTK. OpenCode 2 loads only the plugin rtk 0.52 on writes (one default object with `id` and `setup()`, rtk-ai/rtk#4187); an older rtk's plugin is for OpenCode 1 and OpenCode 2 refuses it, so with an OpenCode 2 here an older rtk is `blocked` (`openCodeBlocked`) and the row says to update RTK (#2295). Under OpenCode 2, an old plugin left from before an rtk update counts as off once the rtk here can write the new one (`openCodeHas`), so switching it on writes the new one over it; with an older rtk it counts as on, so it can be switched off. Factory's Droid (lml0664 on Discord) gets rtk's own `rtk init -g --agent droid`, given Droid's folder as `FACTORY_HOME_OVERRIDE`; rtk puts its `Execute` group (`rtk hook droid`) in the root `hooks.json`, or in `settings.json`'s `hooks.PreToolUse` where Droid's hooks already are, so `droidHookFiles` reads and switches off all three places rtk 1.1.0 may use (`hooks.json`, `hooks/hooks.json`, `settings.json`), leaving the user's own hooks. rtk before 0.44 has no Droid agent, so it is `blocked` (`droidBlocked`). A detected agent RTK has no hook for at all is still listed, from `rtkNoHook`, with the reason and a switch that can't be turned on (dsh: its hooks can allow or deny a command but not rewrite it, and `rtk init` has no `--agent dsh`; Grok Build and Grok App: `rtk init` has no Grok or Grok App agent, so both are listed with the switch off; Qoder and Qoder CN: rtk 1.1.0 has no Qoder agent; Cline and Kimi Code: `rtk init --agent cline|kimi` writes only one project's `.clinerules` or `AGENTS.md`, instructions with no hook, and Kimi's refuses `-g`). RTK 1.1.0's Trae, Windsurf, Kilo Code and Mistral Vibe have no magpie agent. The page's No RTK hook tag gives each agent's own reason and rtk-ai/rtk issue (`rtkNoHookWhy` in plugins/library/client.js: dsh #3847, Grok Build and Grok App #2136, Qoder and Qoder CN #1327, Cline #3841), and an agent with no entry gets no link; `TestRTKNoHookIssuesAreEachAgents` fails when the page and `rtkNoHook` cite different issues, or two agents cite the same ones without a reason in `sharedRTKIssues`. | [`rtk.go`](../../internal/library/rtk.go) |
@@ -50,7 +51,7 @@ Pi's extensions and packages.
1. **Edit.** The Library page or `magpie library` calls an exported function such as `SaveServer`, `ServerAgents`, `InstallSkills`, `SkillAgents` or `SetSkillHow`. The skills and servers pages each have Select, Turn all on, Turn all off and Remove all; the heading shows Select (and a busy Checking…, Grouping… or Updating…) and keeps the rest under its ⋯, the app's row menu (`barMore` in plugins/library/client.js). Select's bar calls `SomeSkillsAgents` or `SomeServersAgents` (`/api/library/{skills,servers}/agents-some`), Turn all on or off calls `EverySkillAgents` or `EveryServerAgents` for the agents shown, and Remove all calls `RemoveSkills` or `RemoveServers`. The hooks page has Select and Remove all too (`SomeHooksAgents`, `RemoveHooks`). Each of these is one change that takes every item out as a single removal would (#1027). Select's bar also has Remove… (#1852), which asks first, naming the count, and sends only the picked names to `RemoveSkills`, `RemoveServers` or `RemoveHooks`; ticking a group's or part's header picks all of it. A name that wasn't removed stays picked, with its error in its row's place (`pickErrs`), and the status names it; when every name fails the endpoint answers 400 and the sheet stays open. A row's agent chips start with All (`allChip` in `plugins/library/client.js`), which gives the item to every agent shown that can take it, or takes it from them all; the pickers that choose the agents before an item is added (installing skills from a repository or the market, adding, bringing in or installing a server) have the same All: most start with every agent lit, and one agent alone took a click on each of the others (#1531).
2. **Change.** `change` edits `library.json` under the lock and calls `sync`.
3. **Write.** For each target, `syncInstructions`, `syncMCP`, `syncHooks` and `syncSubagents` write magpie's part in the agent's format and record it in `Applied`. Skills are linked or copied into the agent's skills folder. A copy edited since it was made is taken into the library first.
3. **Write.** For each target, `syncInstructions`, `syncMCP`, `syncHooks`, `syncSubagents` and `syncCommands` write magpie's part in the agent's format and record it in `Applied`. Skills are linked or copied into the agent's skills folder. A copy edited since it was made is taken into the library first.
4. **Result.** The `Result` lists the agents changed, a `Problem` for each thing that couldn't be given, and the backup folder. Each change's folder is its own (`freshBackup`): named by the millisecond, with `-2`, `-3`… after it when another change took that millisecond, so a change's copy is never another's (`TestBackupsInOneMillisecond`).
## Constraints and failure behavior
@@ -109,6 +110,7 @@ Pi's extensions and packages.
- CC Switch's own skills folder is only ever read.
- Reading the page never waits on reading skills through (#541). `Read` compares an agent's own skill with the same name in another agent (`sameTree`) and hashes each library skill given as a copy (`hashFiles`, for `behind`). Both are kept against a stamp of the folders (each file's and link's path, type, size and mtime, `stamper` in [`treememo.go`](../../internal/library/treememo.go)), taken by the same walk that compares or hashes them, before a file is opened; a later read walks the folder without opening a file, and while the stamps match reuses the answer. Only an answer from a whole read of folders untouched for `settleFor` (3s) is kept: a folder that couldn't be walked or read, or was written a moment ago, is read again next time, never taken as unchanged. A rewrite that keeps a file's size and mtime isn't seen. `Glance` (`GET /api/library?glance=1`) is the page without those two, marked `partial`; the page draws it first, then the whole read, which runs `behind` and `foundSkills` after the library's lock is let go, so a change doesn't wait on them either.
- A read of the page (`Read`, `Glance`) follows the links on the way to a few hundred paths, most of them many times over: each agent's skills folder for each skill, CC Switch's and the shared folder for each source. While the read holds the lock, `resolve` looks at each entry on the way once (`lookPart` in [`linkmemo.go`](../../internal/library/linkmemo.go)): one `Lstat`, and a `Readlink` for a link. Nothing is kept past the read, so a link made or moved on disk between two visits shows on the second. An entry that couldn't be looked at for another reason than its not being there is unknown and looked at again. One read had taken ~10,000 looks; on oxyuan's Windows machine that was ~1.3s a visit (#1771).
- A slash command file is recorded as a subagent's is (`Applied.Commands`, through the shared `syncOwnFiles`): magpie writes over or takes away only a file still exactly as it wrote it, an edited one is the user's from then on, a file of the user's own by the name is never written over (the agent gets a problem), one whose bytes are what magpie would write is taken as magpie's, and one of magpie's the user deleted is written again. A carried library carries the commands (`Bundle.Commands`: name, description, prompt, agents ticked), never `Applied.Commands`; nil keeps this computer's, and an empty list hashes as before the field (`TestCommandsLeaveTheUsersFiles`, `TestCommandsCarried`).
- Skills installed together (`InstallSkills`, `InstallMarketSkill`, `AddNewSkills`, through `installFrom` and `installChange`) install each on its own. One the library lists from the same source, or a folder in the library's own skills folder holding exactly that skill's files (left by an install that stopped before the library was saved), is had already and goes in `Result.Had`. Its files are never written, so the user's edits stay. Another skill by that name, listed or only in the folder, is left as it is. One from GitHub or another git repository then goes in beside it under a name of its own (mora1n on Discord: anthropics/skills' and openai/skills' `skill-creator` are two skills): the name with its source's owner added (`skill-creator-openai`), then owner and repository, the repository, then a number, at most 64 bytes (`freeSkillName` in [`skill_beside.go`](../../internal/library/skill_beside.go)). The library's copy of its `SKILL.md` gives that name too (`nameSkill`, only the front matter's top-level `name:` line), so an agent never sees two skills by one name; `Skill.Called` keeps the name its `SKILL.md` gave. Its hash is of the renamed copy, and a check or update compares what it fetches named the same way (`fetchedHash`), so it reads as unchanged and an update keeps the name. Being had is decided by source, not name (`hadSkill`): the same source under any name here, or a skill with no source (taken in from an agent's folder) by that name holding the very same files. A probe's candidate says which (`Candidate.Have`, `Candidate.As`), the page and the TUI show "in the library as …" or "adds as …", the market's had check matches by name only a skill with no repository (`haveSkill`), and the new-skills check no longer drops a skill because its name is taken. A skill already in the library keeps its name, folder and links; nothing is renamed after the fact. A folder of the user's own is linked as it is, so its `SKILL.md` can't be named apart: one by a taken name, or a folder that can't be read, goes in `Result.Skipped` with why (`TestSameNameFromAnotherSourceGoesInBeside`, `TestSameFilesByNameAreHad`, `TestInstallSetPutsAnotherByTheSameNameBeside`, `TestAddFromLibraryFolderKeepsIt`). The rest are installed and named in `Result.Installed`. Only when nothing was installed or had does the change fail, with the first reason.
- A skill the library has from a folder of the user's, or took in from an agent's folder, has nothing to update from, though it often came from GitHub (biubiu8802 on X: downloaded from there, then added from its folder). Installing that skill from GitHub links the two when it is that skill: traced to that repository, or traced nowhere with the same description in its SKILL.md (`followsHere`, `linkSkill` in [`skill_link.go`](../../internal/library/skill_link.go)): the library's skill keeps its name, agents and links, takes GitHub's files and GitHub as its `Source` (`skillUpdate.apply` with `adopt`, as an update of a CC Switch skill does), and a check and an update cover it from then on. The library's link to a folder elsewhere is all that goes; that folder stays as it is. A copy of the library's own whose files aren't GitHub's goes to the backups (`keepReplaced`), as `UpdateSkill` with replace keeps an edited one. One whose files are GitHub's to the file only takes the source, and so does one had by the very same files (`hadSkill`). The install names it in `Result.Linked`, and in `Result.LinkedKept` when its files were kept; a probe's candidate says so first (`Candidate.Links`), and the page tags the row "links to GitHub" and says both after the install (`skill-install-link.test.cjs`), the TUI likewise. A skill traced to another repository (`tracer.repoOf`: `From`, CC Switch's record, the skills CLI's lock, a git checkout) and an untraced one that describes something else are other skills by that name, and the GitHub one goes in beside them as above (`TestInstallSetPutsAnotherByTheSameNameBeside`); a skill from GitHub or git is never taken over (`TestFolderSkillFollowsGitHub`, `TestOwnSkillFollowsGitHubKeepsItsFiles`, `TestSkillFromElsewhereIsNotLinked`). The market's had check is unchanged: it still counts such a skill as had by its name.
@@ -116,6 +118,7 @@ Pi's extensions and packages.
```sh
go test -tags nogui ./internal/library -run 'TestPlugin|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 'TestCommand'
go test -tags nogui ./internal/library -run 'TestSkillOffHere|TestLocalServerNotCarried|TestPutKeepsLocalServer|TestPutSameNameAsLocal|TestServerHere'
go test -tags nogui ./internal/backup -run 'TestRestoreKeepsLocalServer|TestBackupFileCarriesSubagents|TestBackupFileCarriesHooks'
go test -tags nogui ./internal/library -run 'TestHandOver|TestSharedUnderAnotherName|TestSharedAgentsSkills'
@@ -134,7 +137,7 @@ node --test internal/gui/tests/library-rtk-wsl.test.cjs
node --test internal/gui/tests/skill-auto-update.test.cjs
node --test internal/gui/tests/library-wsl-asleep.test.cjs
node --test internal/gui/tests/skill-off-here.test.cjs internal/gui/tests/mcp-local-server.test.cjs internal/gui/tests/mcp-server-here.test.cjs internal/gui/tests/skill-handover.test.cjs
node --test internal/gui/tests/mcp-accounts.test.cjs 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-subagents-import.test.cjs internal/gui/tests/library-plugins.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
node --test internal/gui/tests/mcp-accounts.test.cjs 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-subagents-import.test.cjs internal/gui/tests/library-commands.test.cjs internal/gui/tests/library-plugins.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
```
The package's `TestMain` runs in a home of its own (`testenv`), never the
+3
View File
@@ -75,6 +75,9 @@ func backupCmd(args []string) error {
if l.Subagents != nil && len(*l.Subagents) > 0 {
fmt.Printf(", %d subagents", len(*l.Subagents))
}
if l.Commands != nil && len(*l.Commands) > 0 {
fmt.Printf(", %d slash commands", len(*l.Commands))
}
if l.Hooks != nil && len(*l.Hooks) > 0 {
fmt.Printf(", %d hooks", len(*l.Hooks))
}
+6 -1
View File
@@ -956,6 +956,11 @@ func hashes(b backup.Bundle) map[string]string {
c.Subagents = nil
lib = &c
}
if lib != nil && lib.Commands != nil && len(*lib.Commands) == 0 { // as before them, without one
c := *lib
c.Commands = nil
lib = &c
}
if lib != nil && lib.Hooks != nil && len(*lib.Hooks) == 0 { // as before them, without one
c := *lib
c.Hooks = nil
@@ -1029,7 +1034,7 @@ func unset(b backup.Bundle, p string) bool {
}
}
return len(l.MCP) == 0 && len(l.Skills) == 0 &&
(l.Subagents == nil || len(*l.Subagents) == 0) && (l.Hooks == nil || len(*l.Hooks) == 0) &&
(l.Subagents == nil || len(*l.Subagents) == 0) && (l.Commands == nil || len(*l.Commands) == 0) && (l.Hooks == nil || len(*l.Hooks) == 0) &&
(l.Bili == nil || strings.TrimSpace(*l.Bili) == "")
}
return false
+4
View File
@@ -937,6 +937,7 @@ const I18N = {
"also for small background tasks": "也用于后台小任务",
"the default tier": "默认档位",
"Subagents": "子代理",
"Codex reads custom prompts no more: its skills took their place": "Codex 已不再读取自定义提示词:由它的技能取代",
"Claude models": "Claude 模型",
"Your Claude subscription is in magpie; picking a claude-* model goes through it as before": "已在 magpie 添加 Claude 订阅,claude-* 模型照常走该订阅",
"Add a Claude subscription": "添加 Claude 订阅",
@@ -6244,6 +6245,7 @@ const I18N = {
"also for small background tasks": "也用於後臺小任務",
"the default tier": "預設檔位",
"Subagents": "子代理",
"Codex reads custom prompts no more: its skills took their place": "Codex 已不再讀取自訂提示詞:由它的技能取代",
"Claude models": "Claude 模型",
"Your Claude subscription is in magpie; picking a claude-* model goes through it as before": "已在 magpie 新增 Claude 訂閱,claude-* 模型照常走該訂閱",
"Add a Claude subscription": "新增 Claude 訂閱",
@@ -11515,6 +11517,7 @@ const I18N = {
"also for small background tasks": "小さなバックグラウンドタスクにも使用",
"the default tier": "デフォルトの階層",
"Subagents": "サブエージェント",
"Codex reads custom prompts no more: its skills took their place": "Codex はカスタムプロンプトを読み込まなくなりました:スキルに置き換えられています",
"Claude models": "Claude モデル",
"Your Claude subscription is in magpie; picking a claude-* model goes through it as before": "Claude サブスクリプションは magpie にあります。claude-* モデルを選ぶと、これまでどおりそのサブスクリプションを使います",
"Add a Claude subscription": "Claude サブスクリプションを追加",
@@ -16804,6 +16807,7 @@ const I18N = {
"also for small background tasks": "auch für kleine Hintergrundaufgaben",
"the default tier": "die Standardstufe",
"Subagents": "Subagenten",
"Codex reads custom prompts no more: its skills took their place": "Codex liest keine eigenen Prompts mehr: seine Skills haben sie ersetzt",
"Claude models": "Claude-Modelle",
"Your Claude subscription is in magpie; picking a claude-* model goes through it as before": "Ihr Claude-Abo ist in magpie hinterlegt; ein claude-*-Modell läuft wie bisher darüber",
"Add a Claude subscription": "Claude-Abo hinzufügen",
+3 -1
View File
@@ -5,7 +5,7 @@
// The sections a page's list is cut into, by tab id: a section none of whose
// tabs shows has no name (app.js navSubs), as does a list of one section.
window.NAV_SUB_GROUPS = {
library: { instructions: "Every agent", memory: "Every agent", mcp: "Every agent", skills: "Every agent", hooks: "Every agent", env: "Every agent", subagents: "Every agent", plugins: "One agent", pi: "One agent", rtk: "magpie", bili: "magpie" },
library: { instructions: "Every agent", memory: "Every agent", mcp: "Every agent", skills: "Every agent", hooks: "Every agent", env: "Every agent", subagents: "Every agent", commands: "Every agent", plugins: "One agent", pi: "One agent", rtk: "magpie", bili: "magpie" },
};
// the tabs [tab, its place in the strip, its section's name where one starts],
// in sections in order, each in the strip's order
@@ -27,6 +27,8 @@ window.NAV_SUB_IC = {
hooks: "M10.5 2.5v6.5a3 3 0 0 1-6 0V7.5 M3 9l1.5-1.5L6 9",
env: "M5.5 3.5h-1.5v9h1.5 M10.5 3.5h1.5v9h-1.5 M6.5 8h3",
subagents: "M6 3a2.2 2.2 0 1 0 0 4.4A2.2 2.2 0 0 0 6 3z M2 13c.5-2.2 2-3.4 4-3.4s3.5 1.2 4 3.4 M11.5 7.5a1.5 1.5 0 1 0 0 .01 M10.2 12.5c.3-1.3 1.1-2 2.3-2s1.6.5 1.9 1.4",
// a slash in a key, as a command is typed
commands: "M4.5 3h7A1.5 1.5 0 0 1 13 4.5v7a1.5 1.5 0 0 1-1.5 1.5h-7A1.5 1.5 0 0 1 3 11.5v-7A1.5 1.5 0 0 1 4.5 3z M9.6 5.4l-3.2 5.2",
rtk: "M2.5 3.5h11v9h-11z M5 6.5l1.5 1.5L5 9.5 M8.5 9.5h2.5",
bili: "M8 2v4 M6 4.2 8 6l2-1.8 M8 14v-4 M6 11.8 8 10l2 1.8 M3 8h10",
pi: "M8 2.5l5 2.5v6L8 13.5 3 11V5z M3 5l5 2.5L13 5 M8 7.5v6",
+136 -5
View File
@@ -52,6 +52,8 @@ magpie.plugin("library", (ctx) => {
hook: "M10.5 2.5v6.5a3 3 0 0 1-6 0V7.5 M3 9l1.5-1.5L6 9",
// a person with a second, smaller one it hands work to
subagent: "M6 3a2.2 2.2 0 1 0 0 4.4A2.2 2.2 0 0 0 6 3z M2 13c.5-2.2 2-3.4 4-3.4s3.5 1.2 4 3.4 M11.5 7.5a1.5 1.5 0 1 0 0 .01 M10.2 12.5c.3-1.3 1.1-2 2.3-2s1.6.5 1.9 1.4",
// a slash in a key, as a command is typed
command: "M4.5 3h7A1.5 1.5 0 0 1 13 4.5v7a1.5 1.5 0 0 1-1.5 1.5h-7A1.5 1.5 0 0 1 3 11.5v-7A1.5 1.5 0 0 1 4.5 3z M9.6 5.4l-3.2 5.2",
// a clock with an arrow going back round it, as macOS draws backups
backup: "M3.2 8a4.8 4.8 0 1 0 1.4-3.4 M2.8 2.6v2.4h2.4 M8 5.3V8l1.9 1.2",
power: "M8 2.5v5 M4.7 4.6a4.8 4.8 0 1 0 6.6 0",
@@ -528,7 +530,7 @@ magpie.plugin("library", (ctx) => {
// What All did, said of the item: on for how many of the agents it went
// to, and which of them couldn't be given it, and why.
function reportAll(v, me) {
const what = ({ servers: "mcp:", hooks: "hook:", env: "env:", subagents: "subagent:" }[me.list] || "skill:") + me.name;
const what = ({ servers: "mcp:", hooks: "hook:", env: "env:", subagents: "subagent:", commands: "command:" }[me.list] || "skill:") + me.name;
const shown = [...me.box.children].filter((x) => isChip(x) && !cannot(x)).flatMap((x) => idsOf(x).filter((id) => !x.dataset.fixed?.split("\t").includes(id)));
const n = shown.filter((id) => me.want.includes(id)).length;
const bad = (v.result?.problems || []).filter((p) => p.what === what && shown.includes(p.agent));
@@ -805,7 +807,7 @@ magpie.plugin("library", (ctx) => {
ul.append(li);
}
if (ul.childElementCount) card.append(ul);
const tabNames = { instructions: t("Instructions"), mcp: t("MCP servers"), skills: t("Skills"), hooks: t("Hooks"), env: t("Environment variables"), subagents: t("Subagents"), plugins: t("Claude plugins") };
const tabNames = { instructions: t("Instructions"), mcp: t("MCP servers"), skills: t("Skills"), hooks: t("Hooks"), env: t("Environment variables"), subagents: t("Subagents"), commands: t("Slash commands"), plugins: t("Claude plugins") };
const others = Object.keys(away).filter((k) => k in tabNames);
if (others.length) {
const more = el("div", "lib-problems-away");
@@ -841,7 +843,7 @@ magpie.plugin("library", (ctx) => {
}
// the tab a problem is about; "" is one shown on every tab
function problemTab(what) {
return { instructions: "instructions", mcp: "mcp", skill: "skills", skills: "skills", project: "skills", hook: "hooks", hooks: "hooks", env: "env", subagent: "subagents", plugin: "plugins" }[what.split(":")[0]] || "";
return { instructions: "instructions", mcp: "mcp", skill: "skills", skills: "skills", project: "skills", hook: "hooks", hooks: "hooks", env: "env", subagent: "subagents", command: "commands", plugin: "plugins" }[what.split(":")[0]] || "";
}
function problemWhat(what) {
const [kind, ...rest] = what.split(":");
@@ -851,6 +853,7 @@ magpie.plugin("library", (ctx) => {
if (kind === "skill") return t("Skill {name}", { name });
if (kind === "hook") return t("Hook {name}", { name });
if (kind === "subagent") return t("Subagent {name}", { name });
if (kind === "command") return t("Slash command {name}", { name: "/" + name });
if (kind === "project") return name ? t("Skill {name}", { name }) : t("The project");
return what;
}
@@ -955,6 +958,7 @@ magpie.plugin("library", (ctx) => {
["hooks", t("Hooks") + n("hooks")],
["env", t("Environment variables") + n("env")],
["subagents", t("Subagents") + n("subagents")],
["commands", t("Slash commands") + n("commands")],
["plugins", t("Claude plugins") + n("plugins")],
["rtk", "RTK"],
["bili", "billion-context"],
@@ -1018,7 +1022,7 @@ magpie.plugin("library", (ctx) => {
if (agentless()) tab = "mcp";
// Pi's tab only while a Pi is here; the pick is kept for when one is
else if (tab === "pi" && !hasPi()) tab = "instructions";
const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length, env: (lib.env || []).length, subagents: (lib.subagents || []).length, plugins: (lib.plugins || []).length });
const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length, env: (lib.env || []).length, subagents: (lib.subagents || []).length, commands: (lib.commands || []).length, plugins: (lib.plugins || []).length });
page.append(head);
head.classList.toggle("stuck", top > 0);
// what changed in a tab is drawn in place: only another tab (or the
@@ -1038,6 +1042,7 @@ magpie.plugin("library", (ctx) => {
else if (tab === "hooks") renderHooks(body);
else if (tab === "env") renderEnv(body);
else if (tab === "subagents") renderSubagents(body);
else if (tab === "commands") renderCommands(body);
else if (tab === "plugins") renderPlugins(body);
else renderSkills(body);
page.append(body);
@@ -1074,7 +1079,7 @@ magpie.plugin("library", (ctx) => {
if (JSON.stringify(follow) !== JSON.stringify(was) && lib && page.isConnected) render();
}
function followNote() {
const part = tab === "memory" ? "memory" : ["instructions", "mcp", "skills", "hooks", "env", "subagents", "plugins"].includes(tab) ? "library" : "";
const part = tab === "memory" ? "memory" : ["instructions", "mcp", "skills", "hooks", "env", "subagents", "commands", "plugins"].includes(tab) ? "library" : "";
if (!part || !follow?.[part]) return null;
const p = el("p", "lib-intro lib-follow", t("This computer follows the server: what you change here is replaced by the next sync.") + " ");
const go = button(t("Sync settings"), "link", (e) => openSettingsAt(e, "sync", "#syncList .sync-follows"));
@@ -5071,6 +5076,132 @@ magpie.plugin("library", (ctx) => {
if (!s) requestAnimationFrame(() => name.focus());
}
// ---------- slash commands ----------
// A slash command (miantiao_me on X) is a prompt typed as /name in an
// agent: the words after the name go where it says $ARGUMENTS, and the
// first, second… of them where it says $1, $2…. It is kept once and
// written into each agent picked, as that agent's own command file in
// its own folder and shape (commands.go). Codex is listed, greyed: it
// reads custom prompts no more.
const commandAgentOf = (id) => (lib.commandAgents || []).find((x) => x.id === id);
const commandAgents = () => shownAgents().filter((a) => commandAgentOf(a.id));
// why a can't be given a slash command, or ""
const commandBlocked = (a) => {
const ca = commandAgentOf(a.id);
if (ca && !ca.no) return "";
if (ca?.wsl) return t("magpie gives slash commands only to agents on this computer, not yet to {agent} in WSL", { agent: a.name });
if (a.id === "codex") return t("Codex reads custom prompts no more: its skills took their place");
return t("{agent} reads no slash commands magpie can write", { agent: a.name });
};
// a prompt that takes words by their place ($1, $2…; $0 is none)
const usesArgs = (p) => /\$(?!0(?![0-9]))[0-9]+/.test(p || "");
// the agents of ids that take only $ARGUMENTS
const noArgs = (all, ids) => all.filter((a) => ids.includes(a.id) && !commandBlocked(a) && !commandAgentOf(a.id).args);
function renderCommands(body) {
body.append(intro(t("A slash command is a prompt you type as /name in an agent. Add it once and magpie writes it into each agent you pick, as that agent's own command.")));
const all = commandAgents();
const cmds = lib.commands || [];
if (!cmds.length) {
body.append(empty(t("No slash commands in the library yet"), t("Add one, and pick the agents that get it."), button(t("+ Add a slash command"), "action", () => editCommand(null))));
} else {
const list = el("div", "list lib-list");
list.append(...[...cmds].sort((a, b) => a.name.localeCompare(b.name)).map((c) => commandRow(c, all)));
body.append(list);
const after = el("div", "after-list");
after.append(button(t("+ Add slash command"), "", () => editCommand(null)));
body.append(after);
}
const noPlace = [...new Set(cmds.filter((c) => usesArgs(c.prompt)).flatMap((c) => noArgs(all, c.agents || [])))];
if (noPlace.length) body.append(el("p", "lib-aside lib-commands-noargs", t("{agents} take only $ARGUMENTS, all the words at once: a command that uses $1, $2… isn't written for them.", { agents: noPlace.map((a) => a.name).join(", ") })));
const skip = all.filter((a) => commandAgentOf(a.id).no);
if (skip.length) body.append(el("p", "lib-aside lib-commands-no", t("magpie can't give slash commands to {agents}: their chips are greyed, and say why.", { agents: skip.map((a) => a.name).join(", ") })));
}
function commandRow(c, all) {
const row = el("div", "row lib-row click lib-command");
const who = el("div", "who");
who.append(el("div", "name mono", "/" + c.name));
if (c.description) who.append(el("div", "lib-commanddesc", c.description));
row.append(glyph(GLYPH.command), who,
agentChips(all, c.agents, chipsChange("commands/agents", c.name, "commands", (x) => commandRow(x, all)), { problems: c.problems, blocked: commandBlocked, all: true }));
row.onclick = () => editCommand(c);
row.title = t("Edit {name}", { name: "/" + c.name });
return row;
}
function editCommand(c) {
const all = commandAgents();
const d = c ? { name: c.name, description: c.description || "", prompt: c.prompt, agents: [...(c.agents || [])] }
: { name: "", description: "", prompt: "", agents: all.filter((a) => !commandBlocked(a)).map((a) => a.id) };
const ed = el("div", "editor lib-editor lib-commandedit");
const head = el("div", "ehead");
head.append(glyph(GLYPH.command), el("b", "", c ? "/" + c.name : t("New slash command")));
ed.append(head);
const err = el("div", "editor-error");
const name = field2(d.name, t("e.g. review"), (v) => { d.name = v.trim(); });
name.classList.add("mono");
ed.append(...field(t("Name"), name, t("Typed as /name: lowercase letters, digits, - and _")));
const box = (cls, value, placeholder, rows, max, onEnter) => {
const ta = el("textarea", "lib-text small " + cls);
ta.value = value;
ta.placeholder = placeholder;
ta.spellcheck = false;
ta.rows = rows;
ta.maxLength = max;
ta.onkeydown = (e) => { e.stopPropagation(); if (e.isComposing || e.keyCode === 229) return; if (e.key === "Escape") closeLibModal(); else if (onEnter && e.key === "Enter" && modal?.save) { e.preventDefault(); modal.save(); } };
autosize(ta, rows * 20);
return ta;
};
// one line, as the agents list it (library.SaveCommand joins its
// lines), so Enter saves; the prompt's Enter is a new line
const desc = box("lib-commanddescin", d.description, t("e.g. Review a diff for bugs"), 1, 1000, true);
desc.oninput = () => { d.description = desc.value; };
ed.append(...field(t("Description"), desc));
const prompt = box("lib-commandprompt", d.prompt, t("Review $ARGUMENTS for bugs. Report only what is wrong."), 6, 100000, false);
const argsHint = el("div", "hint lib-commandhint-args");
prompt.oninput = () => { d.prompt = prompt.value; drawHint(); };
const [pl, pw] = field(t("Prompt"), prompt, t("$ARGUMENTS is what you type after the name; $1, $2… its first, second… word"));
pw.append(argsHint);
ed.append(pl, pw);
const agentsBox = el("div");
ed.append(...field(t("Agents"), agentsBox));
ed.append(err);
function drawHint() {
const no = usesArgs(d.prompt) ? noArgs(all, d.agents) : [];
argsHint.textContent = no.length ? t("Not written for {agents} while it uses $1, $2…: they take only $ARGUMENTS", { agents: no.map((a) => a.name).join(", ") }) : "";
}
function drawAgents() {
agentsBox.replaceChildren(agentChips(all, d.agents, (next) => { d.agents = next; drawAgents(); }, { names: true, blocked: commandBlocked, all: true }));
drawHint();
}
drawAgents();
const bar = el("div", "bar");
if (c) bar.append(button(t("Remove from the library"), "danger", async () => {
if (!await confirmRemoval("/" + c.name, "It will be removed from the library and the agents it was given to.")) return;
if (await change("commands/remove", { name: c.name }, t("{name} is out of the library and the agents it was given to", { name: "/" + c.name }))) closeLibModal(true);
}));
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal));
const save = async () => {
err.textContent = "";
try {
const command = { name: d.name.replace(/^\//, ""), description: d.description.trim(), prompt: d.prompt, agents: d.agents.filter((id) => !commandBlocked(agentOf(id) || { id })) };
take(await api("library/commands/save", { old: c ? c.name : "", command }));
report(lib.result, c ? t("{name} saved", { name: "/" + command.name }) : "");
closeLibModal(true);
render();
} catch (e) { err.textContent = e.message; }
};
bar.append(button(c ? t("Save") : t("Add"), "primary", save));
ed.append(bar);
const original = JSON.stringify(d);
modal = { save, dirty: () => JSON.stringify(d) !== original };
openLib(ed);
if (!c) requestAnimationFrame(() => name.focus());
}
// ---------- Claude plugins ----------
// A Claude Code plugin kept as one item (FakeshadowzZ on X): its skills,
@@ -170,6 +170,23 @@ magpie.strings({
"Not bound for {agents}: theirs uses every skill the agent has": "{agents} 不会绑定:其子代理可用该 Agent 的全部技能",
"Skills: {names}": "技能:{names}",
"Subagent {name}": "子代理 {name}",
"Slash commands": "斜杠命令",
"Slash command {name}": "斜杠命令 {name}",
"magpie gives slash commands only to agents on this computer, not yet to {agent} in WSL": "magpie 只给这台电脑上的代理写入斜杠命令,暂不支持 WSL 中的 {agent}",
"{agent} reads no slash commands magpie can write": "{agent} 没有 magpie 能写入的斜杠命令",
"A slash command is a prompt you type as /name in an agent. Add it once and magpie writes it into each agent you pick, as that agent's own command.": "斜杠命令是在代理里以 /名称 输入的一段提示词。在这里添加一次,magpie 会把它写入你选择的每个代理,成为该代理自己的命令。",
"No slash commands in the library yet": "资源库里还没有斜杠命令",
"+ Add a slash command": "+ 添加斜杠命令",
"+ Add slash command": "+ 添加斜杠命令",
"{agents} take only $ARGUMENTS, all the words at once: a command that uses $1, $2… isn't written for them.": "{agents} 只支持 $ARGUMENTS(一次取全部参数):用到 $1、$2… 的命令不会写入它们。",
"magpie can't give slash commands to {agents}: their chips are greyed, and say why.": "magpie 无法给 {agents} 写入斜杠命令:它们的标签为灰色,并说明了原因。",
"New slash command": "新建斜杠命令",
"e.g. review": "例如 review",
"Typed as /name: lowercase letters, digits, - and _": "以 /名称 输入:小写字母、数字、- 和 _",
"e.g. Review a diff for bugs": "例如 检查一个 diff 中的 bug",
"Review $ARGUMENTS for bugs. Report only what is wrong.": "检查 $ARGUMENTS 中的 bug,只报告有问题的地方。",
"$ARGUMENTS is what you type after the name; $1, $2… its first, second… word": "$ARGUMENTS 是名称后输入的内容;$1、$2… 是其中第一个、第二个…词",
"Not written for {agents} while it uses $1, $2…: they take only $ARGUMENTS": "用到 $1、$2… 时不会写入 {agents}:它们只支持 $ARGUMENTS",
"The Cursor app has these subagents; its cursor-agent command reads only a project's own .cursor/agents.": "Cursor 应用会读取这些子代理;它的 cursor-agent 命令只读取项目自己的 .cursor/agents。",
"The library has no MCP servers yet": "资源库里还没有 MCP 服务器",
"The library has no skills yet": "资源库里还没有技能",
@@ -1212,6 +1229,23 @@ magpie.strings({
"Not bound for {agents}: theirs uses every skill the agent has": "{agents} 不會綁定:其子代理可用該 Agent 的全部技能",
"Skills: {names}": "技能:{names}",
"Subagent {name}": "子代理 {name}",
"Slash commands": "斜線命令",
"Slash command {name}": "斜線命令 {name}",
"magpie gives slash commands only to agents on this computer, not yet to {agent} in WSL": "magpie 只給這台電腦上的代理寫入斜線命令,暫不支援 WSL 中的 {agent}",
"{agent} reads no slash commands magpie can write": "{agent} 沒有 magpie 能寫入的斜線命令",
"A slash command is a prompt you type as /name in an agent. Add it once and magpie writes it into each agent you pick, as that agent's own command.": "斜線命令是在代理裡以 /名稱 輸入的一段提示詞。在這裡新增一次,magpie 會把它寫入你選擇的每個代理,成為該代理自己的命令。",
"No slash commands in the library yet": "資源庫裡還沒有斜線命令",
"+ Add a slash command": "+ 新增斜線命令",
"+ Add slash command": "+ 新增斜線命令",
"{agents} take only $ARGUMENTS, all the words at once: a command that uses $1, $2… isn't written for them.": "{agents} 只支援 $ARGUMENTS(一次取全部參數):用到 $1、$2… 的命令不會寫入它們。",
"magpie can't give slash commands to {agents}: their chips are greyed, and say why.": "magpie 無法給 {agents} 寫入斜線命令:它們的標籤為灰色,並說明了原因。",
"New slash command": "新增斜線命令",
"e.g. review": "例如 review",
"Typed as /name: lowercase letters, digits, - and _": "以 /名稱 輸入:小寫字母、數字、- 和 _",
"e.g. Review a diff for bugs": "例如 檢查一個 diff 中的 bug",
"Review $ARGUMENTS for bugs. Report only what is wrong.": "檢查 $ARGUMENTS 中的 bug,只回報有問題的地方。",
"$ARGUMENTS is what you type after the name; $1, $2… its first, second… word": "$ARGUMENTS 是名稱後輸入的內容;$1、$2… 是其中第一個、第二個…詞",
"Not written for {agents} while it uses $1, $2…: they take only $ARGUMENTS": "用到 $1、$2… 時不會寫入 {agents}:它們只支援 $ARGUMENTS",
"The Cursor app has these subagents; its cursor-agent command reads only a project's own .cursor/agents.": "Cursor 應用程式會讀取這些子代理;它的 cursor-agent 命令只讀取專案自己的 .cursor/agents。",
"The library has no MCP servers yet": "資源庫裡還沒有 MCP 伺服器",
"The library has no skills yet": "資源庫裡還沒有技能",
@@ -2254,6 +2288,23 @@ magpie.strings({
"Not bound for {agents}: theirs uses every skill the agent has": "{agents} では割り当てられません。エージェントのすべてのスキルを使います",
"Skills: {names}": "スキル: {names}",
"Subagent {name}": "サブエージェント {name}",
"Slash commands": "スラッシュコマンド",
"Slash command {name}": "スラッシュコマンド {name}",
"magpie gives slash commands only to agents on this computer, not yet to {agent} in WSL": "magpie がスラッシュコマンドを書き込めるのはこのコンピューター上のエージェントだけで、WSL の {agent} にはまだ対応していません",
"{agent} reads no slash commands magpie can write": "{agent} には magpie が書き込めるスラッシュコマンドがありません",
"A slash command is a prompt you type as /name in an agent. Add it once and magpie writes it into each agent you pick, as that agent's own command.": "スラッシュコマンドは、エージェントで /名前 と入力して使うプロンプトです。ここで一度追加すると、magpie が選んだ各エージェントにそのエージェント独自のコマンドとして書き込みます。",
"No slash commands in the library yet": "ライブラリにスラッシュコマンドはまだありません",
"+ Add a slash command": "+ スラッシュコマンドを追加",
"+ Add slash command": "+ スラッシュコマンドを追加",
"{agents} take only $ARGUMENTS, all the words at once: a command that uses $1, $2… isn't written for them.": "{agents} は $ARGUMENTS(すべての引数をまとめて)のみ対応です:$1、$2… を使うコマンドは書き込まれません。",
"magpie can't give slash commands to {agents}: their chips are greyed, and say why.": "magpie は {agents} にスラッシュコマンドを書き込めません:チップはグレー表示で、理由が表示されます。",
"New slash command": "新しいスラッシュコマンド",
"e.g. review": "例:review",
"Typed as /name: lowercase letters, digits, - and _": "/名前 で入力:小文字、数字、- と _",
"e.g. Review a diff for bugs": "例:diff のバグを確認する",
"Review $ARGUMENTS for bugs. Report only what is wrong.": "$ARGUMENTS のバグを確認し、問題のある箇所だけを報告してください。",
"$ARGUMENTS is what you type after the name; $1, $2… its first, second… word": "$ARGUMENTS は名前の後に入力した内容、$1、$2… はその 1 番目、2 番目…の語です",
"Not written for {agents} while it uses $1, $2…: they take only $ARGUMENTS": "$1、$2… を使う間は {agents} に書き込まれません:$ARGUMENTS のみ対応です",
"The Cursor app has these subagents; its cursor-agent command reads only a project's own .cursor/agents.": "Cursor アプリはこれらのサブエージェントを読み込みます。cursor-agent コマンドが読むのはプロジェクト自身の .cursor/agents だけです。",
"The library has no MCP servers yet": "ライブラリにはまだ MCP サーバーがありません",
"The library has no skills yet": "ライブラリにはまだスキルがありません",
@@ -3296,6 +3347,23 @@ magpie.strings({
"Not bound for {agents}: theirs uses every skill the agent has": "Für {agents} nicht zugewiesen: Dort nutzt er jeden Skill, den der Agent hat",
"Skills: {names}": "Skills: {names}",
"Subagent {name}": "Subagent {name}",
"Slash commands": "Slash-Befehle",
"Slash command {name}": "Slash-Befehl {name}",
"magpie gives slash commands only to agents on this computer, not yet to {agent} in WSL": "magpie gibt Slash-Befehle nur Agenten auf diesem Computer, noch nicht {agent} in WSL",
"{agent} reads no slash commands magpie can write": "{agent} liest keine Slash-Befehle, die magpie schreiben kann",
"A slash command is a prompt you type as /name in an agent. Add it once and magpie writes it into each agent you pick, as that agent's own command.": "Ein Slash-Befehl ist ein Prompt, den du in einem Agenten als /Name eingibst. Füge ihn einmal hinzu, und magpie schreibt ihn in jeden gewählten Agenten als dessen eigenen Befehl.",
"No slash commands in the library yet": "Noch keine Slash-Befehle in der Bibliothek",
"+ Add a slash command": "+ Slash-Befehl hinzufügen",
"+ Add slash command": "+ Slash-Befehl hinzufügen",
"{agents} take only $ARGUMENTS, all the words at once: a command that uses $1, $2… isn't written for them.": "{agents} kennen nur $ARGUMENTS, alle Wörter auf einmal: ein Befehl mit $1, $2… wird für sie nicht geschrieben.",
"magpie can't give slash commands to {agents}: their chips are greyed, and say why.": "magpie kann {agents} keine Slash-Befehle geben: ihre Chips sind ausgegraut und sagen, warum.",
"New slash command": "Neuer Slash-Befehl",
"e.g. review": "z. B. review",
"Typed as /name: lowercase letters, digits, - and _": "Eingegeben als /Name: Kleinbuchstaben, Ziffern, - und _",
"e.g. Review a diff for bugs": "z. B. Einen Diff auf Fehler prüfen",
"Review $ARGUMENTS for bugs. Report only what is wrong.": "Prüfe $ARGUMENTS auf Fehler. Melde nur, was falsch ist.",
"$ARGUMENTS is what you type after the name; $1, $2… its first, second… word": "$ARGUMENTS ist, was du nach dem Namen eingibst; $1, $2… sein erstes, zweites… Wort",
"Not written for {agents} while it uses $1, $2…: they take only $ARGUMENTS": "Nicht für {agents} geschrieben, solange er $1, $2… nutzt: sie kennen nur $ARGUMENTS",
"The Cursor app has these subagents; its cursor-agent command reads only a project's own .cursor/agents.": "Die Cursor-App liest diese Subagenten; ihr Befehl cursor-agent liest nur das eigene .cursor/agents eines Projekts.",
"The library has no MCP servers yet": "Die Bibliothek hat noch keine MCP-Server",
"The library has no skills yet": "Die Bibliothek hat noch keine Skills",
@@ -810,6 +810,13 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col
.lib-subagentedit .lib-subagentdescin, .lib-subagentedit .lib-subagentprompt { width: 100%; box-sizing: border-box; resize: none; font: inherit; font-size: 12.5px; line-height: 1.45; }
.lib-subagentedit .lib-subagentprompt { max-height: 40vh; overflow-y: auto; }
.lib-subagentedit .hint:empty { display: none; }
/* a slash command's row: its /name in mono, its description under it;
its editor's prompt a box that grows */
.lib-command > .who { flex-basis: 240px; }
.lib-command .lib-commanddesc { font-size: 12px; line-height: 1.45; color: var(--fg); white-space: normal; overflow-wrap: anywhere; margin-top: 1px; }
.lib-commandedit .lib-commanddescin, .lib-commandedit .lib-commandprompt { width: 100%; box-sizing: border-box; resize: none; font: inherit; font-size: 12.5px; line-height: 1.45; }
.lib-commandedit .lib-commandprompt { max-height: 40vh; overflow-y: auto; }
.lib-commandedit .hint:empty { display: none; }
/* a chip whose agent has the item whatever is ticked (it reads
~/.agents/skills itself, #595): lit, as it has it, with a lock on its
+7
View File
@@ -702,6 +702,7 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
Env library.EnvVar // a variable saved
// a subagent saved (#2283)
Subagent library.Subagent
Command library.Command
Agent string // the agent whose own skill is in the library's way
App string // the app the MCP hub is added to (servers/hub-open)
Note string // what the MCP router says of itself (servers/hub-note), or a skill's note (skills/note)
@@ -810,6 +811,12 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
res, err = library.SubagentAgentsSet(in.Name, in.Agents)
case "subagents/remove":
res, err = library.RemoveSubagents([]string{in.Name})
case "commands/save":
res, err = library.SaveCommand(in.Old, in.Command)
case "commands/agents":
res, err = library.CommandAgentsSet(in.Name, in.Agents)
case "commands/remove":
res, err = library.RemoveCommands([]string{in.Name})
case "subagents/import":
res, err = library.ImportSubagents(in.Source, in.Paths, in.Agents)
case "skills/install":
@@ -0,0 +1,263 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// miantiao_me on X: Slash commands, a Library tab after Subagents. A slash
// command (a name, a description, a prompt with $ARGUMENTS and $1, $2…)
// is kept once and given to agents with the chips every other tab has.
// Its row shows /name and what it is for, wrapped. Asides say which
// agents it is given to take only $ARGUMENTS (so a command using $1 isn't
// written for them) and which agents magpie can't write one for: Codex,
// which reads custom prompts no more, and an agent in WSL. Their chips
// are greyed, say why, and post nothing. A row's chip posts
// commands/agents. Add opens the editor with every agent that can take
// one picked: the prompt's Enter is a new line, not a save; an input
// method's Enter saves nothing; a hint names the agents picked that take
// only $ARGUMENTS while the prompt uses $1; a leading / on the name is
// dropped; Save posts commands/save. A row opens it again, and Remove
// asks first, then posts commands/remove.
// At 420 and 1100 wide in en, zh, zh-TW, ja and de: no sideways scroll,
// and what each click pressed stays where it was on the screen.
// 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 { strings } = require("./strings.cjs");
const assets = path.resolve(__dirname, "../assets");
const HOME = "/Users/mian";
const agent = (id, name, more = {}) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json`, ...more });
const LONG = "审阅指定文件或目录里改动过的代码,只报告真正的 bug:逻辑错误、边界条件、并发问题和资源泄漏;不评论代码风格,也不提出与本次改动无关的重构建议。";
const cmd = (name, description, prompt, agents) => ({ name, description, prompt, agents });
const WSL = "claude@wsl:Ubuntu";
const COMMAND_AGENTS = [
{ id: "claude", dir: `${HOME}/.claude/commands`, args: true },
{ id: "codex", no: "Codex reads custom prompts no more: its skills took their place" },
{ id: "gemini", dir: `${HOME}/.gemini/commands` },
{ id: "opencode", dir: `${HOME}/.config/opencode/commands`, args: true },
{ id: WSL, wsl: true, no: "magpie gives no slash commands to an agent in WSL yet" },
];
const lib = (commands) => ({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [agent("claude", "Claude Code"), agent("codex", "Codex"), agent("gemini", "Gemini CLI"), agent("opencode", "OpenCode"), agent(WSL, "Claude Code (Ubuntu)")],
instructions: { agents: [] }, servers: [], skills: [], foundServers: [], projects: [], foundSkills: [], problems: [],
hooks: [], hookAgents: [], subagents: [], subagentAgents: [], commands, commandAgents: COMMAND_AGENTS,
});
let I18N;
// the words the page says in lang; a string missing from a language fails
function tr(lang, key, vars = {}) {
let s = key;
if (lang !== "en") {
assert.equal(typeof I18N[lang][key], "string", `${lang} has no ${JSON.stringify(key)}`);
s = I18N[lang][key];
}
return s.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m));
}
function server(lang, state, posts) {
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
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 json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/library") return json(lib(state.commands));
if (url.pathname.startsWith("/api/library/") && req.method() === "POST" && !url.pathname.endsWith("/reveal")) {
const body = req.postDataJSON(), what = url.pathname.replace("/api/library/", "");
posts.push({ what, body });
if (what === "commands/agents") state.commands = state.commands.map((x) => (x.name === body.name ? { ...x, agents: body.agents } : x));
if (what === "commands/save") state.commands = [...state.commands.filter((x) => x.name !== body.old), body.command];
if (what === "commands/remove") state.commands = state.commands.filter((x) => x.name !== body.name);
return json({ ...lib(state.commands), result: { changed: ["claude"] } });
}
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true } });
if (url.pathname.startsWith("/api/")) return json({});
if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" });
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
// a click where the button is, as the reader's, and what was clicked stays
// where it was on the screen while the click redraws around it
const press = async (page, loc) => {
await page.waitForFunction(() => !document.querySelector("#view-library").getAnimations({ subtree: true }).some((a) => a.effect?.getComputedTiming().endTime !== Infinity));
const b = await loc.boundingBox();
const sel = String(loc);
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
await page.waitForTimeout(250);
if (!(await loc.count())) return;
const a = await loc.boundingBox();
if (a && a.width) assert(Math.abs(a.y - b.y) <= 1, `${sel} moved on the screen from ${Math.round(b.y)} to ${Math.round(a.y)}`);
};
const settled = (page) => page.waitForFunction(() => !document.querySelector("#modal").getAnimations({ subtree: true }).length);
// nothing wider than the window: the page, the Library, its rows and dialog
const sideways = (page) => page.evaluate(() => {
const over = [];
const w = document.documentElement.clientWidth;
if (document.documentElement.scrollWidth > w) over.push("page " + document.documentElement.scrollWidth);
const v = document.querySelector("#view-library");
if (v.scrollWidth > v.clientWidth + 1) over.push("library " + v.scrollWidth + ">" + v.clientWidth);
for (const e of document.querySelectorAll("#view-library .lib-command, #view-library .lib-aside, #view-library .lib-tabs, #modal .lib-commandedit *")) {
const r = e.getBoundingClientRect();
if (r.width && (r.right > w + 0.5 || r.left < -0.5)) over.push((e.className || e.tagName) + " " + Math.round(r.left) + "–" + Math.round(r.right));
}
return over;
});
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": the Library's Slash commands tab", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
I18N = strings().I18N; // i18n.js's and the plugins'
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
t.after(() => browser.close());
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
await t.test(lang, async () => {
const w = (key, vars) => tr(lang, key, vars);
const state = { commands: [cmd("review", LONG, "Review $1 for bugs.\n\nFocus: $ARGUMENTS", ["claude", "gemini"])] };
const posts = [], errors = [];
const open = async (width) => {
const ctx = await browser.newContext({ viewport: { width, height: 1000 }, reducedMotion: "reduce" });
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "commands"); } catch {} });
const page = await ctx.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
page.on("dialog", (d) => { errors.push("a browser dialog: " + d.message()); d.dismiss(); });
await page.route("**/*", server(lang, state, posts));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
await page.locator("#view-library .lib-command").first().waitFor();
return { ctx, page };
};
const wrapped = async (page, width) => {
const r = page.locator("#view-library .lib-command").first();
const fit = await r.locator(".lib-commanddesc").evaluate((e) => ({ clipped: e.scrollWidth > e.clientWidth + 1 || e.scrollHeight > e.clientHeight + 1, lines: Math.round(e.getBoundingClientRect().height / parseFloat(getComputedStyle(e).lineHeight)) }));
assert.equal(fit.clipped, false, `the description is cut off at ${width}`);
assert(fit.lines >= 2, `the description isn't wrapped at ${width}: ${fit.lines} line`);
const gap = await r.evaluate((x) => Math.abs(x.firstElementChild.getBoundingClientRect().top - x.querySelector(".name").getBoundingClientRect().top));
assert(gap < 12, `the name is ${Math.round(gap)}px off its glyph at ${width}`);
assert.deepEqual(await sideways(page), [], `sideways scroll with the list at ${width}`);
};
// 1100 wide in a window of its own: the list, and the editor
{
const { ctx, page } = await open(1100);
await wrapped(page, 1100);
await press(page, page.locator("#view-library .lib-command").first());
await page.locator("#modal .lib-commandedit").waitFor();
await settled(page);
assert.deepEqual(await sideways(page), [], "sideways scroll in the editor at 1100");
await ctx.close();
}
const { ctx, page } = await open(420);
const v = page.locator("#view-library");
const row = (name) => v.locator(".lib-command").filter({ has: page.locator(".name", { hasText: new RegExp("^/" + name + "$") }) });
const agentsOf = (name) => state.commands.find((s) => s.name === name)?.agents;
// the tab, with its count, between Subagents and Claude plugins
const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim());
const at = tabs.indexOf(w("Slash commands") + " · 1");
assert(at > 0, tabs.join("|"));
assert.deepEqual(tabs.slice(at - 1, at + 2), [w("Subagents"), w("Slash commands") + " · 1", w("Claude plugins")]);
assert.equal((await row("review").locator(".lib-commanddesc").textContent()).trim(), LONG);
await wrapped(page, 420);
// Gemini takes only $ARGUMENTS, and review uses $1
await v.locator(".lib-commands-noargs").filter({ hasText: w("{agents} take only $ARGUMENTS, all the words at once: a command that uses $1, $2… isn't written for them.", { agents: "Gemini CLI" }) }).waitFor();
await v.locator(".lib-commands-no").filter({ hasText: w("magpie can't give slash commands to {agents}: their chips are greyed, and say why.", { agents: "Codex, Claude Code (Ubuntu)" }) }).waitFor();
// Codex and the agent in WSL: greyed, say why, and a click posts nothing
const codex = row("review").locator('.lib-ag[data-agent="codex"]');
assert.equal(await codex.getAttribute("aria-disabled"), "true");
assert.equal(await codex.getAttribute("title"), w("Codex reads custom prompts no more: its skills took their place"));
const wsl = row("review").locator(`.lib-ag[data-agent="${WSL}"]`);
assert.equal(await wsl.getAttribute("aria-disabled"), "true");
assert.equal(await wsl.getAttribute("title"), w("magpie gives slash commands only to agents on this computer, not yet to {agent} in WSL", { agent: "Claude Code (Ubuntu)" }));
await press(page, codex);
await press(page, wsl);
await page.waitForTimeout(150);
assert.deepEqual(posts, [], "a greyed chip posted");
// a row's chip gives it to OpenCode
await press(page, row("review").locator('.lib-ag[data-agent="opencode"]'));
await page.waitForFunction(() => document.querySelector('#view-library .lib-command .lib-ag[data-agent="opencode"][aria-pressed="true"]'));
await page.waitForTimeout(200);
assert.deepEqual(posts.shift(), { what: "commands/agents", body: { name: "review", agents: ["claude", "gemini", "opencode"] } });
assert.deepEqual(agentsOf("review"), ["claude", "gemini", "opencode"]);
// Add: the editor, every agent that can take it picked
await press(page, v.locator(".after-list button"));
const ed = page.locator("#modal .lib-commandedit");
await ed.waitFor();
await settled(page);
assert.equal(await page.locator("#modal select").count(), 0, "a native <select>");
assert.equal((await ed.locator(".ehead b").textContent()).trim(), w("New slash command"));
const edChip = (id) => ed.locator(`.lib-ag[data-agent="${id}"]`);
for (const id of ["claude", "gemini", "opencode"]) assert.equal(await edChip(id).getAttribute("aria-pressed"), "true", id);
for (const id of ["codex", WSL]) assert.equal(await edChip(id).getAttribute("aria-pressed"), "false", id);
await ed.locator("input").first().fill("/explain");
const desc = ed.locator(".lib-commanddescin");
assert.equal(await desc.getAttribute("placeholder"), w("e.g. Review a diff for bugs"));
await desc.fill("讲解代码");
// Enter choosing an input method's word is the IME's: nothing saved
await desc.evaluate((i) => i.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", isComposing: true, keyCode: 229, bubbles: true })));
await page.waitForTimeout(150);
assert.deepEqual(posts, [], "an IME's Enter saved the command");
// the prompt's Enter is a new line, not a save
const prompt = ed.locator(".lib-commandprompt");
const hint = ed.locator(".lib-commandhint-args");
await prompt.click();
await page.keyboard.type("Explain $ARGUMENTS.");
assert.equal((await hint.textContent()).trim(), "", "a hint with no $1");
await page.keyboard.press("Enter");
await page.keyboard.type("Start with $1.");
await page.waitForTimeout(150);
assert.deepEqual(posts, [], "the prompt's Enter saved");
assert.equal(await prompt.inputValue(), "Explain $ARGUMENTS.\nStart with $1.");
// the hint names the agents picked that take only $ARGUMENTS
assert.equal((await hint.textContent()).trim(), w("Not written for {agents} while it uses $1, $2…: they take only $ARGUMENTS", { agents: "Gemini CLI" }));
await edChip("gemini").click();
assert.equal((await hint.textContent()).trim(), "");
assert.deepEqual(await sideways(page), [], "sideways scroll in the editor");
await ed.locator(".bar button.primary").click();
await ed.waitFor({ state: "detached" });
assert.deepEqual(posts.shift(), { what: "commands/save", body: { old: "", command: { name: "explain", description: "讲解代码", prompt: "Explain $ARGUMENTS.\nStart with $1.", agents: ["claude", "opencode"] } } });
await row("explain").waitFor();
// a row opens it again; Remove asks first, Cancel posts nothing
await press(page, row("review"));
await ed.waitFor();
await settled(page);
assert.equal((await ed.locator(".ehead b").textContent()).trim(), "/review");
assert.equal(await ed.locator(".lib-commandprompt").inputValue(), "Review $1 for bugs.\n\nFocus: $ARGUMENTS");
assert.equal((await hint.textContent()).trim(), w("Not written for {agents} while it uses $1, $2…: they take only $ARGUMENTS", { agents: "Gemini CLI" }));
await ed.locator(".bar button.danger").click();
const sheet = page.locator("dialog.action-confirm");
await sheet.waitFor();
await sheet.locator("button", { hasText: w("Cancel") }).click();
await sheet.waitFor({ state: "detached" });
await page.waitForTimeout(150);
assert.deepEqual(posts, [], "Cancel posts nothing");
await ed.locator(".bar button.danger").click();
await sheet.waitFor();
await sheet.locator("button.danger-fill").click();
await ed.waitFor({ state: "detached" });
assert.deepEqual(posts.shift(), { what: "commands/remove", body: { name: "review" } });
assert.equal(await row("review").count(), 0);
await row("explain").waitFor();
// with no command given to Gemini using $1, its aside is gone
assert.equal(await v.locator(".lib-commands-noargs").count(), 0);
assert.deepEqual(posts, []);
assert.deepEqual(errors, []);
await ctx.close();
});
}
});
}
+7 -7
View File
@@ -79,14 +79,14 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
t.after(() => context.close());
await page.waitForFunction(() => document.querySelector("#side .nav-sub .nav-sl"));
const rows = await order(page);
assert.equal(rows.length, 14, rows.join(","));
assert.equal(rows.length, 15, rows.join(","));
assert.deepEqual(rows.filter((x) => x[0] === "#"), ["#" + a, "#" + b, "#" + c]);
// the order inside each: the shared seven, then Claude's and Pi's, then magpie's
// the order inside each: the shared eight, then Claude's and Pi's, then magpie's
assert.equal(rows[0], "#" + a);
assert.equal(rows[8], "#" + b);
assert.equal(rows[11], "#" + c);
assert.equal(rows[9], "#" + b);
assert.equal(rows[12], "#" + c);
// a name is no tab: picking by keyboard skips it, the rows are still the tabs
assert.equal(await page.locator("#side .nav-sub .nav-s").count(), 11);
assert.equal(await page.locator("#side .nav-sub .nav-s").count(), 12);
// the page's own strip is as it was: no names in it
assert.equal(await page.locator("#view-library .lib-tabs .nav-sl").count(), 0);
// the name is quiet: the muted ink, no left border, no ground
@@ -105,11 +105,11 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await page.waitForFunction(() => document.querySelector("#side .nav-sub .nav-sl"));
// Claude plugins and Pi packages hidden: "One agent" has nothing to list
await page.evaluate(() => { for (const b of document.querySelectorAll("#view-library .lib-tabs button")) if (["plugins", "pi"].includes(b.dataset.seg)) b.hidden = true; navSubs(); });
await page.waitForFunction(() => !document.querySelector("#side .nav-sub .nav-s[data-of]") || document.querySelectorAll("#side .nav-sub .nav-s").length === 9);
await page.waitForFunction(() => !document.querySelector("#side .nav-sub .nav-s[data-of]") || document.querySelectorAll("#side .nav-sub .nav-s").length === 10);
assert.deepEqual(await heads(page), ["Every agent", "magpie"]);
// one section left: no names at all
await page.evaluate(() => { for (const b of document.querySelectorAll("#view-library .lib-tabs button")) if (["rtk", "bili"].includes(b.dataset.seg)) b.hidden = true; navSubs(); });
await page.waitForFunction(() => document.querySelectorAll("#side .nav-sub .nav-s").length === 7);
await page.waitForFunction(() => document.querySelectorAll("#side .nav-sub .nav-s").length === 8);
assert.deepEqual(await heads(page), []);
});
+1 -1
View File
@@ -152,7 +152,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// the tab, with its count, between Skills and Subagents
const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim());
assert.deepEqual(tabs.slice(3, 9), [w("Skills"), w("Hooks") + " · 2", w("Environment variables"), w("Subagents"), w("Claude plugins"), "RTK"]);
assert.deepEqual(tabs.slice(3, 10), [w("Skills"), w("Hooks") + " · 2", w("Environment variables"), w("Subagents"), w("Slash commands"), w("Claude plugins"), "RTK"]);
// each hook says when it runs, in words, and what it runs
assert.equal((await row("fmt").locator(".lib-hookev").textContent()).trim(), w("After a tool runs") + " · " + w("File edits"));
assert.equal((await row("bark").locator(".lib-hookev").textContent()).trim(), w("When a turn ends"));
+2 -2
View File
@@ -73,7 +73,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(await skel.getAttribute("aria-busy"), "true");
const tabs = v.locator(".lib-head .lib-tabs .opt");
assert.deepEqual(await tabs.allTextContents(), ["Instructions", "Memory", "MCP servers", "Skills", "Hooks", "Environment variables", "Subagents", "Claude plugins", "RTK", "billion-context"]);
assert.deepEqual(await tabs.allTextContents(), ["Instructions", "Memory", "MCP servers", "Skills", "Hooks", "Environment variables", "Subagents", "Slash commands", "Claude plugins", "RTK", "billion-context"]);
assert.equal(await v.locator(".lib-tabs .opt.on").textContent(), "Skills");
assert.ok(await v.locator(".lib-head .lib-more").isDisabled(), "the folder waits for the library");
// Skills in outline: rows with a switch, no section heading
@@ -90,7 +90,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
open();
await v.locator(".lib-head .lib-more:not([disabled])").waitFor();
assert.equal(await v.locator(".lib-skel").count(), 0, "the outline goes");
assert.deepEqual(await v.locator(".lib-tabs .opt").allTextContents(), ["Instructions", "Memory", "MCP servers · 1", "Skills · 1", "Hooks", "Environment variables", "Subagents", "Claude plugins", "RTK", "billion-context", "Pi packages"]);
assert.deepEqual(await v.locator(".lib-tabs .opt").allTextContents(), ["Instructions", "Memory", "MCP servers · 1", "Skills · 1", "Hooks", "Environment variables", "Subagents", "Slash commands", "Claude plugins", "RTK", "billion-context", "Pi packages"]);
assert.equal(await v.locator(".lib-tabs .opt.on").textContent(), "Instructions");
assert.equal(await v.locator(".lib-head .lib-more").getAttribute("title"), "~/.magpie/library");
const after = await v.locator(".lib-tabs").boundingBox();
@@ -172,7 +172,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// the tab, with its count, between Hooks and RTK
const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim());
assert.deepEqual(tabs.slice(4, 9), [w("Hooks"), w("Environment variables"), w("Subagents") + " · 1", w("Claude plugins"), "RTK"]);
assert.deepEqual(tabs.slice(4, 10), [w("Hooks"), w("Environment variables"), w("Subagents") + " · 1", w("Slash commands"), w("Claude plugins"), "RTK"]);
// the row: what it is for, and what it binds
assert.equal((await row("reviewer").locator(".lib-subagentdesc").textContent()).trim(), LONG);
assert.equal((await row("reviewer").locator(".lib-subagentuses").textContent()).trim(), w("Skills: {names}", { names: "tdd" }) + " · " + w("MCP servers: {names}", { names: "github" }));
+36
View File
@@ -33,6 +33,9 @@ type Bundle struct {
// carried, which knew nothing of this computer's: Put keeps them. Collect
// always sets it, empty too, so taking the last one out is carried.
Subagents *[]*Subagent `json:"subagents,omitempty"`
// Commands are nil in a bundle from a magpie before slash commands,
// as Subagents are: Put keeps this computer's.
Commands *[]*Command `json:"commands,omitempty"`
// Hooks are nil in a bundle from a magpie before they were carried,
// as Subagents are: Put keeps this computer's. Applied.Hooks, the
// entries magpie wrote into each agent here, stays out.
@@ -146,6 +149,13 @@ func Collect() (*Bundle, error) {
subs = append(subs, &c)
}
b.Subagents = &subs
cmds := []*Command{}
for _, c := range sorted(l.Commands, func(c *Command) string { return c.Name }) {
x := *c
x.Agents = orNone(slices.Sorted(slices.Values(c.Agents)))
cmds = append(cmds, &x)
}
b.Commands = &cmds
hooks := []*Hook{}
for _, h := range sorted(l.Hooks, func(h *Hook) string { return h.Name }) {
c := *h
@@ -311,6 +321,22 @@ func (b *Bundle) check() error {
seen[s.Name] = true
}
}
if b.Commands != nil {
seen := map[string]bool{}
for _, c := range *b.Commands {
if c == nil {
return fmt.Errorf("an empty slash command")
}
// the agents are left as they come, as a subagent's are
if !commandNameRe.MatchString(c.Name) {
return fmt.Errorf("the slash command name %q", c.Name)
}
if seen[c.Name] {
return fmt.Errorf("the slash command %s twice", c.Name)
}
seen[c.Name] = true
}
}
if b.Env != nil {
seen := map[string]bool{}
for _, e := range *b.Env {
@@ -637,6 +663,16 @@ func Put(b *Bundle) (*Result, error) {
}
l.Subagents = subs
}
// slash commands the same way: Applied.Commands decides
if b.Commands != nil {
cmds := []*Command{}
for _, c := range *b.Commands {
x := *c
x.Agents = slices.Clone(orNone(c.Agents))
cmds = append(cmds, &x)
}
l.Commands = cmds
}
// the same for hooks: Applied.Hooks decides, entry by entry,
// what magpie takes out of each agent's file here
if b.Hooks != nil {
+364
View File
@@ -0,0 +1,364 @@
package library
import (
"errors"
"fmt"
"path/filepath"
"slices"
"strconv"
"strings"
"unicode/utf8"
"github.com/pelletier/go-toml/v2"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/lazyre"
)
// Slash commands are prompts kept once and typed as /name in the agents
// ticked for each (miantiao_me on X): a name, what it is for, and the
// prompt the agent is sent, with the words typed after the name put in
// where it says $ARGUMENTS, and the first, second… of them where it says
// $1, $2… Each is written into the agent's own folder of commands, in its
// own shape (each read from the agent's docs and source):
//
// Claude Code <claude dir>/commands/<name>.md description; $n is $ARGUMENTS[n-1] there, counted from 0
// OpenCode <config>/commands/<name>.md description; $ARGUMENTS and $1… as magpie's
// Pi <agent dir>/prompts/<name>.md description; $ARGUMENTS and $1… as magpie's
// Gemini CLI ~/.gemini/commands/<name>.toml description, prompt; $ARGUMENTS is {{args}}, no $1…
// Qwen Code <qwen home>/commands/<name>.md description; $ARGUMENTS is {{args}}, no $1…
// Factory Droid ~/.factory/commands/<name>.md description; $ARGUMENTS, no $1…
//
// A command that uses $1… isn't written for an agent that has no such
// thing: the page says why. Codex's custom prompts (~/.codex/prompts) are
// listed but greyed: Codex reads them no more, its skills having taken
// their place. What magpie wrote is recorded file by file with its hash
// (Applied.Commands), as subagents' are (syncOwnFiles): a file still as
// magpie wrote it is magpie's to rewrite or remove, one the user changed
// is theirs from then on, and a file by that name magpie didn't write is
// never touched.
// Command is a slash command the agents ticked for it are given.
type Command struct {
Name string `json:"name"`
Description string `json:"description"`
Prompt string `json:"prompt"`
Agents []string `json:"agents"`
}
// commandNameRe is a name each agent takes as one command of its folder:
// a file's name, no / (a folder there makes a namespace) and no :
// (Gemini CLI's namespace mark).
var commandNameRe = lazyre.New(`^[a-z0-9](?:[a-z0-9_-]{0,62}[a-z0-9])?$`)
const (
maxCommandDescription = 1000
maxCommandPrompt = 100_000
)
// CommandAgents are the agents a slash command can be given, in the order
// the page lists them.
var CommandAgents = []string{"claude", "codex", "opencode", "pi", "gemini", "qwen", "droid"}
// commandSpec is where an agent keeps its slash commands and how it reads
// one.
type commandSpec struct {
dir string
ext string
// args: it puts the first, second… word typed in for $1, $2…
args bool
render func(c *Command) []byte
}
func (sp *commandSpec) path(name string) string { return filepath.Join(sp.dir, name+sp.ext) }
const (
// wslNoCommands is why an agent in WSL is given no slash commands,
// its distro running or not.
wslNoCommands = "magpie gives no slash commands to an agent in WSL yet"
// codexNoCommands is why Codex is given none: custom prompts were
// deprecated for skills, and Codex no longer reads ~/.codex/prompts.
codexNoCommands = "Codex reads custom prompts no more: its skills took their place"
)
// argRe is a word typed in, by its place: $1, $2…
var argRe = lazyre.New(`\$([0-9]+)`)
// usesArgs says whether a prompt takes words typed in by their place.
func usesArgs(prompt string) bool {
for _, m := range argRe.FindAllStringSubmatch(prompt, -1) {
if m[1] != "0" {
return true
}
}
return false
}
func commandSpecOf(t *Target) (*commandSpec, string) {
a := t.Agent
if a.WSL != "" {
return nil, wslNoCommands
}
md := func(dir string, body func(string) string) *commandSpec {
return &commandSpec{dir: dir, ext: ".md", render: func(c *Command) []byte {
if c.Description == "" {
// each takes the prompt's first line for what it is for
return []byte(strings.TrimRight(body(c.Prompt), "\n") + "\n")
}
return frontmatter([][2]string{{"description", yamlStr(c.Description)}}, body(c.Prompt))
}}
}
same := func(p string) string { return p }
args := func(p string) string { return strings.ReplaceAll(p, "$ARGUMENTS", "{{args}}") }
switch a.ID {
case "claude":
// Claude Code counts $0 as the first word, and reads \$ as a $
sp := md(filepath.Join(claudeDir(), "commands"), claudeArgs)
sp.args = true
return sp, ""
case "codex":
return nil, codexNoCommands
case "opencode":
// it reads command/ and commands/; commands/ is the one its docs name
sp := md(filepath.Join(filepath.Dir(a.Path), "commands"), same)
sp.args = true
return sp, ""
case "pi":
sp := md(filepath.Join(a.Dir, "prompts"), same)
sp.args = true
return sp, ""
case "gemini":
return &commandSpec{dir: filepath.Join(home(), ".gemini", "commands"), ext: ".toml", render: func(c *Command) []byte {
b, _ := toml.Marshal(struct {
Description string `toml:"description,omitempty"`
Prompt string `toml:"prompt,multiline"`
}{c.Description, strings.TrimRight(args(c.Prompt), "\n") + "\n"})
return b
}}, ""
case "qwen":
return md(filepath.Join(a.Dir, "commands"), args), ""
case "droid":
return md(filepath.Join(a.Dir, "commands"), same), ""
}
return nil, "magpie can't give " + a.Name + " slash commands: it reads none from a folder of its own"
}
// claudeArgs is a prompt as Claude Code reads one: $n is $ARGUMENTS[n-1],
// and a $0 that is no word typed in is written \$0, as its docs have it.
func claudeArgs(p string) string {
return argRe.ReplaceAllStringFunc(p, func(m string) string {
n, err := strconv.Atoi(m[1:])
if err != nil || n == 0 {
return `\` + m
}
return "$ARGUMENTS[" + strconv.Itoa(n-1) + "]"
})
}
func (c *Command) check() error {
if !commandNameRe.MatchString(c.Name) {
return fmt.Errorf("slash command name %q: use lowercase letters, digits, - and _, at most 64, not starting or ending with - or _", c.Name)
}
if utf8.RuneCountInString(c.Description) > maxCommandDescription {
return fmt.Errorf("a slash command's description is at most %d characters", maxCommandDescription)
}
if strings.TrimSpace(c.Prompt) == "" {
return errors.New("a slash command needs a prompt")
}
if len(c.Prompt) > maxCommandPrompt {
return fmt.Errorf("a slash command's prompt is at most %d bytes", maxCommandPrompt)
}
for _, a := range c.Agents {
if base, _, _ := strings.Cut(a, "@wsl:"); !slices.Contains(CommandAgents, base) {
return fmt.Errorf("%s can't be given slash commands", a)
}
}
return nil
}
func (l *Library) command(name string) *Command {
for _, c := range l.Commands {
if c.Name == name {
return c
}
}
return nil
}
// noArgs is why an agent that has no $1… isn't given a command that uses
// them.
func noArgs(name string) error {
return fmt.Errorf("%s takes no words by their place ($1, $2…): only $ARGUMENTS, all of them", name)
}
func (l *Library) syncCommands(t *Target, b *backups, res *Result) {
id := t.Agent.ID
a := l.applied(id)
var want []*Command
for _, c := range l.Commands {
if slices.Contains(c.Agents, id) {
want = append(want, c)
}
}
if len(a.Commands) == 0 && len(want) == 0 {
return
}
sp, why := commandSpecOf(t)
if sp == nil {
for _, c := range want {
res.fail(id, "command:"+c.Name, errors.New(why))
}
return
}
var files []ownFile
for _, c := range want {
if !sp.args && usesArgs(c.Prompt) {
// not written: what magpie wrote of it before goes
res.fail(id, "command:"+c.Name, noArgs(t.Agent.Name))
continue
}
files = append(files, ownFile{name: c.Name, path: sp.path(c.Name), body: func() []byte { return sp.render(c) }})
}
a.Commands = syncOwnFiles(t, "command", a.Commands, files, b, res)
}
// ---- changes ---------------------------------------------------------------
// SaveCommand adds a slash command, or replaces the one called old
// (renaming it: the files magpie wrote by the old name go).
func SaveCommand(old string, c Command) (*Result, error) {
c.Name = strings.TrimSpace(c.Name)
c.Description = strings.Join(strings.Fields(c.Description), " ")
c.Prompt = strings.TrimRight(strings.ReplaceAll(c.Prompt, "\r\n", "\n"), " \n\t")
if err := c.check(); err != nil {
return nil, err
}
return change(func(l *Library) error {
if c.Name != old && l.command(c.Name) != nil {
return fmt.Errorf("the library already has a slash command called %s", c.Name)
}
if old != "" {
i := slices.IndexFunc(l.Commands, func(x *Command) bool { return x.Name == old })
if i < 0 {
return fmt.Errorf("no slash command called %s", old)
}
l.Commands = slices.Delete(l.Commands, i, i+1)
}
c.Agents = orNone(slices.Compact(slices.Sorted(slices.Values(c.Agents))))
l.Commands = append(l.Commands, &c)
return nil
})
}
// CommandAgentsSet sets which agents get a slash command.
func CommandAgentsSet(name string, agents []string) (*Result, error) {
return change(func(l *Library) error {
c := l.command(name)
if c == nil {
return fmt.Errorf("no slash command called %s", name)
}
x := *c
x.Agents = agents
if err := x.check(); err != nil {
return err
}
c.Agents = orNone(slices.Compact(slices.Sorted(slices.Values(agents))))
return nil
})
}
// RemoveCommands takes the slash commands named out of the library, and
// the files magpie wrote of them, still as it wrote them, out of every
// agent.
func RemoveCommands(names []string) (*Result, error) {
if len(names) == 0 {
return nil, errors.New("no slash commands to remove")
}
return change(func(l *Library) error {
for _, n := range names {
if l.command(n) == nil {
return fmt.Errorf("no slash command called %s", n)
}
}
l.Commands = slices.DeleteFunc(l.Commands, func(c *Command) bool { return slices.Contains(names, c.Name) })
return nil
})
}
// ---- the page --------------------------------------------------------------
// CommandView is a library slash command, and where each agent has it.
type CommandView struct {
*Command
// Files are, for each agent it was written to, the file
Files map[string]string `json:"files,omitempty"`
// Problems are the agents it couldn't be given to, and why
Problems map[string]string `json:"problems,omitempty"`
}
// CommandAgentView is an agent the Slash commands tab lists.
type CommandAgentView struct {
ID string `json:"id"`
// Dir is where its commands are; No is why magpie can't give it any
Dir string `json:"dir,omitempty"`
No string `json:"no,omitempty"`
WSL bool `json:"wsl,omitempty"`
// Args: it takes $1, $2…; one without takes only $ARGUMENTS
Args bool `json:"args,omitempty"`
}
// commandsView is the Slash commands page for these agents, and those in
// stopped WSL distros (asleep), greyed as while their distro runs.
func (l *Library) commandsView(targets []*Target, asleep []*agent.Agent, of func(string) map[string]string) ([]CommandView, []CommandAgentView) {
agents := []CommandAgentView{}
names := map[string]string{}
for _, t := range targets {
names[t.Agent.ID] = t.Agent.Name
if base, _, _ := strings.Cut(t.Agent.ID, "@wsl:"); !slices.Contains(CommandAgents, base) {
continue
}
sp, why := commandSpecOf(t)
av := CommandAgentView{ID: t.Agent.ID, No: why, WSL: t.Agent.WSL != ""}
if sp != nil {
av.Dir, av.Args = sp.dir, sp.args
}
agents = append(agents, av)
}
for _, a := range asleep {
if base, _, _ := strings.Cut(a.ID, "@wsl:"); slices.Contains(CommandAgents, base) && shapeOf(a) != nil {
agents = append(agents, CommandAgentView{ID: a.ID, No: wslNoCommands, WSL: true})
}
}
views := []CommandView{}
for _, c := range l.Commands {
x := *c
x.Agents = orNone(x.Agents)
cv := CommandView{Command: &x, Problems: of("command:" + c.Name)}
for id, a := range l.Applied {
for _, f := range a.Commands {
if f.Name == c.Name && slices.Contains(c.Agents, id) {
if cv.Files == nil {
cv.Files = map[string]string{}
}
cv.Files[id] = f.Path
}
}
}
for _, av := range agents {
if slices.Contains(c.Agents, av.ID) && cv.Problems[av.ID] == "" {
why := av.No
if why == "" && !av.Args && usesArgs(c.Prompt) {
why = noArgs(names[av.ID]).Error()
}
if why == "" {
continue
}
if cv.Problems == nil {
cv.Problems = map[string]string{}
}
cv.Problems[av.ID] = why
}
}
views = append(views, cv)
}
return views, agents
}
+324
View File
@@ -0,0 +1,324 @@
package library
import (
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/pelletier/go-toml/v2"
)
// commandAgents puts every agent that takes slash commands in the
// sandbox, and says where each keeps one called name.
func commandAgents(t *testing.T, h, name string) map[string]string {
t.Helper()
write(t, filepath.Join(h, ".qwen/settings.json"), "{}\n")
write(t, filepath.Join(h, ".factory/settings.json"), "")
return map[string]string{
"claude": filepath.Join(h, ".claude/commands", name+".md"),
"opencode": filepath.Join(h, ".config/opencode/commands", name+".md"),
"pi": filepath.Join(h, ".pi/agent/prompts", name+".md"),
"gemini": filepath.Join(h, ".gemini/commands", name+".toml"),
"qwen": filepath.Join(h, ".qwen/commands", name+".md"),
"droid": filepath.Join(h, ".factory/commands", name+".md"),
}
}
func commandProblems(res *Result) map[string]string {
m := map[string]string{}
for _, p := range res.Problems {
if strings.HasPrefix(p.What, "command:") {
m[p.Agent] = p.Error
}
}
return m
}
// Each agent gets the command as a file of its own, in its own folder
// and shape, $ARGUMENTS as it says it.
func TestCommandsEachAgentsFile(t *testing.T) {
h := sandbox(t)
files := commandAgents(t, h, "review")
c := Command{Name: "review", Description: "Review \"the\" diff.\n Bugs only.", Prompt: "Review $ARGUMENTS.\r\n\r\nBugs only.\n\n"}
for id := range files {
c.Agents = append(c.Agents, id)
}
c.Agents = append(c.Agents, "codex")
res, err := SaveCommand("", c)
if err != nil {
t.Fatal(err)
}
desc := `"Review \"the\" diff. Bugs only."`
md := func(body string) string { return "---\ndescription: " + desc + "\n---\n\n" + body }
want := map[string]string{
"claude": md("Review $ARGUMENTS.\n\nBugs only.\n"),
"opencode": md("Review $ARGUMENTS.\n\nBugs only.\n"),
"pi": md("Review $ARGUMENTS.\n\nBugs only.\n"),
"qwen": md("Review {{args}}.\n\nBugs only.\n"),
"droid": md("Review $ARGUMENTS.\n\nBugs only.\n"),
}
for id, f := range files {
got := read(t, f)
if id == "gemini" {
var cmd map[string]any
if err := toml.Unmarshal([]byte(got), &cmd); err != nil {
t.Fatalf("gemini command: %v\n%s", err, got)
}
if cmd["description"] != `Review "the" diff. Bugs only.` || cmd["prompt"] != "Review {{args}}.\n\nBugs only.\n" || len(cmd) != 2 {
t.Errorf("gemini command: %#v", cmd)
}
continue
}
if got != want[id] {
t.Errorf("%s's %s:\n%s\nwant:\n%s", id, f, got, want[id])
}
}
// Codex reads no custom prompts: nothing written, and why
if p := commandProblems(res); len(p) != 1 || p["codex"] != codexNoCommands {
t.Errorf("problems: %+v", res.Problems)
}
if _, err := os.Stat(filepath.Join(h, ".codex/prompts")); !os.IsNotExist(err) {
t.Errorf("a Codex prompts folder: %v", err)
}
v, err := Read(nil)
if err != nil {
t.Fatal(err)
}
if len(v.Commands) != 1 || len(v.Commands[0].Files) != len(files) || v.Commands[0].Problems["codex"] != codexNoCommands {
t.Errorf("view: %+v", v.Commands)
}
var listed []string
for _, av := range v.CommandAgents {
listed = append(listed, av.ID)
if av.Args != slices.Contains([]string{"claude", "opencode", "pi"}, av.ID) || (av.No != "") != (av.ID == "codex") {
t.Errorf("agent view %+v", av)
}
}
slices.Sort(listed)
if !slices.Equal(listed, []string{"claude", "codex", "droid", "gemini", "opencode", "pi", "qwen"}) {
t.Errorf("agents listed: %v", listed)
}
// taken from one agent: its file goes, the others stay
ok(t)(CommandAgentsSet("review", []string{"claude", "opencode"}))
for id, f := range files {
_, err := os.Stat(f)
if gone := os.IsNotExist(err); gone != (id != "claude" && id != "opencode") {
t.Errorf("%s's file after untick: %v", id, err)
}
}
// renamed: the old name's files go, the new one's come
c.Name, c.Agents = "check", []string{"claude", "opencode"}
ok(t)(SaveCommand("review", c))
if read(t, files["claude"]) != "" || read(t, files["opencode"]) != "" {
t.Error("the old name's files stayed")
}
if !strings.Contains(read(t, filepath.Join(h, ".claude/commands/check.md")), "Review $ARGUMENTS.") {
t.Error("no check.md")
}
// a file the user deleted comes back on the next sync
os.Remove(filepath.Join(h, ".claude/commands/check.md"))
ok(t)(Sync())
if read(t, filepath.Join(h, ".claude/commands/check.md")) == "" {
t.Error("the deleted file wasn't written again")
}
ok(t)(RemoveCommands([]string{"check"}))
for _, f := range []string{".claude/commands/check.md", ".config/opencode/commands/check.md"} {
if _, err := os.Stat(filepath.Join(h, f)); !os.IsNotExist(err) {
t.Errorf("%s after remove: %v", f, err)
}
}
}
// Words by their place: $1 is the first. Claude Code counts from 0, so
// it is $ARGUMENTS[0] there; OpenCode and Pi count from 1 as magpie does.
// An agent with no such thing gets no file, and says why; one with no
// description gets none in its file.
func TestCommandsWordsByPlace(t *testing.T) {
h := sandbox(t)
files := commandAgents(t, h, "fix")
c := Command{Name: "fix", Prompt: "Fix issue #$1 with $2, costs $0 ($ARGUMENTS).", Agents: []string{"claude", "opencode", "pi", "gemini", "qwen", "droid"}}
res, err := SaveCommand("", c)
if err != nil {
t.Fatal(err)
}
if got := read(t, files["claude"]); got != "Fix issue #$ARGUMENTS[0] with $ARGUMENTS[1], costs \\$0 ($ARGUMENTS).\n" {
t.Errorf("claude: %q", got)
}
for _, id := range []string{"opencode", "pi"} {
if got := read(t, files[id]); got != "Fix issue #$1 with $2, costs $0 ($ARGUMENTS).\n" {
t.Errorf("%s: %q", id, got)
}
}
p := commandProblems(res)
for _, id := range []string{"gemini", "qwen", "droid"} {
if _, err := os.Stat(files[id]); !os.IsNotExist(err) {
t.Errorf("%s was given a command it can't read: %v", id, err)
}
if !strings.Contains(p[id], "$1") {
t.Errorf("%s's problem: %q", id, p[id])
}
}
if len(p) != 3 {
t.Errorf("problems: %+v", p)
}
// the page says so before a sync, too
v, err := Read(nil)
if err != nil {
t.Fatal(err)
}
for _, id := range []string{"gemini", "qwen", "droid"} {
if !strings.Contains(v.Commands[0].Problems[id], "$1") {
t.Errorf("view's %s problem: %+v", id, v.Commands[0].Problems)
}
}
// no $1 any more: written for them all, and the problems are gone
c.Prompt = "Fix $ARGUMENTS."
res, err = SaveCommand("fix", c)
if err != nil {
t.Fatal(err)
}
if p := commandProblems(res); len(p) != 0 {
t.Errorf("problems: %+v", p)
}
if got := read(t, files["qwen"]); got != "Fix {{args}}.\n" {
t.Errorf("qwen: %q", got)
}
// $1 again: magpie's Gemini file goes, for it would say the wrong thing
c.Prompt = "Fix $1."
if _, err := SaveCommand("fix", c); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(files["gemini"]); !os.IsNotExist(err) {
t.Errorf("gemini's stale file stayed: %v", err)
}
}
// A command file of the user's own by the same name is never written
// over, nor taken away; one magpie wrote that the user edited is theirs
// from then on; one that says what magpie would write is taken as
// magpie's.
func TestCommandsLeaveTheUsersFiles(t *testing.T) {
h := sandbox(t)
files := commandAgents(t, h, "review")
mine := "---\ndescription: mine\n---\nMy own review.\n"
write(t, files["claude"], mine)
same := "Review $ARGUMENTS.\n"
write(t, files["pi"], same)
c := Command{Name: "review", Prompt: "Review $ARGUMENTS.", Agents: []string{"claude", "opencode", "pi", "droid"}}
res, err := SaveCommand("", c)
if err != nil {
t.Fatal(err)
}
if p := commandProblems(res); len(p) != 1 || !strings.Contains(p["claude"], "has a slash command of its own at "+files["claude"]) {
t.Fatalf("problems: %+v", res.Problems)
}
if read(t, files["claude"]) != mine {
t.Fatalf("the user's own file was written over:\n%s", read(t, files["claude"]))
}
// the user edits magpie's Droid file, then the command changes: the
// edit stays, and the page is told why
edited := read(t, files["droid"]) + "And style.\n"
write(t, files["droid"], edited)
c.Prompt = "Review $ARGUMENTS, twice."
res, err = SaveCommand("review", c)
if err != nil {
t.Fatal(err)
}
if read(t, files["droid"]) != edited {
t.Errorf("the user's edit was written over:\n%s", read(t, files["droid"]))
}
if !strings.Contains(commandProblems(res)["droid"], "of its own") {
t.Errorf("problems: %+v", res.Problems)
}
if read(t, files["opencode"]) != "Review $ARGUMENTS, twice.\n" || read(t, files["pi"]) != "Review $ARGUMENTS, twice.\n" {
t.Errorf("magpie's files weren't updated: %q %q", read(t, files["opencode"]), read(t, files["pi"]))
}
// removed: magpie's own files go, the user's stay
ok(t)(RemoveCommands([]string{"review"}))
for _, id := range []string{"opencode", "pi"} {
if _, err := os.Stat(files[id]); !os.IsNotExist(err) {
t.Errorf("magpie's %s file stayed: %v", id, err)
}
}
if read(t, files["droid"]) != edited || read(t, files["claude"]) != mine {
t.Error("removing took the user's files")
}
l, _ := load()
for id, a := range l.Applied {
if len(a.Commands) != 0 {
t.Errorf("%s still records %+v", id, a.Commands)
}
}
}
func TestCommandCheck(t *testing.T) {
sandbox(t)
for _, c := range []Command{
{Name: "", Prompt: "x"},
{Name: "Review", Prompt: "x"},
{Name: "-review", Prompt: "x"},
{Name: "re/view", Prompt: "x"},
{Name: "re:view", Prompt: "x"},
{Name: strings.Repeat("a", 65), Prompt: "x"},
{Name: "review", Prompt: " \n"},
{Name: "review", Prompt: "x", Agents: []string{"cursor"}},
{Name: "review", Prompt: "x", Description: strings.Repeat("字", maxCommandDescription+1)},
} {
if _, err := SaveCommand("", c); err == nil {
t.Errorf("%+v was taken", c)
}
}
for _, n := range []string{"r", "pr_review", "fix-2"} {
if _, err := SaveCommand("", Command{Name: n, Prompt: "x"}); err != nil {
t.Errorf("%s: %v", n, err)
}
}
if _, err := SaveCommand("", Command{Name: "r", Prompt: "y"}); err == nil {
t.Error("a second command called r")
}
}
// Carried to another computer (a backup, WebDAV sync), the commands come
// along; a bundle from a magpie before them keeps this computer's.
func TestCommandsCarried(t *testing.T) {
h := sandbox(t)
commandAgents(t, h, "review")
ok(t)(SaveCommand("", Command{Name: "review", Description: "d", Prompt: "Review $ARGUMENTS.", Agents: []string{"claude"}}))
b, err := Collect()
if err != nil {
t.Fatal(err)
}
if b.Commands == nil || len(*b.Commands) != 1 || (*b.Commands)[0].Name != "review" {
t.Fatalf("collected: %+v", b.Commands)
}
old := *b
old.Commands = nil
ok(t)(RemoveCommands([]string{"review"}))
ok(t)(SaveCommand("", Command{Name: "here", Prompt: "x", Agents: []string{"claude"}}))
if _, err := Put(&old); err != nil {
t.Fatal(err)
}
l, _ := load()
if len(l.Commands) != 1 || l.Commands[0].Name != "here" {
t.Errorf("an older bundle took this computer's commands: %+v", l.Commands)
}
if _, err := Put(b); err != nil {
t.Fatal(err)
}
l, _ = load()
if len(l.Commands) != 1 || l.Commands[0].Name != "review" {
t.Errorf("after put: %+v", l.Commands)
}
if got := read(t, filepath.Join(h, ".claude/commands/review.md")); got != "---\ndescription: \"d\"\n---\n\nReview $ARGUMENTS.\n" {
t.Errorf("claude's file after put: %q", got)
}
if _, err := os.Stat(filepath.Join(h, ".claude/commands/here.md")); !os.IsNotExist(err) {
t.Errorf("here.md stayed: %v", err)
}
}
+11 -1
View File
@@ -35,6 +35,9 @@ type Library struct {
// Subagents are agents of their own the agents ticked for each can
// hand a task to (subagents.go, #2283)
Subagents []*Subagent `json:"subagents,omitempty"`
// Commands are slash commands the agents ticked for each are given
// (commands.go)
Commands []*Command `json:"commands,omitempty"`
// Plugins are the Claude Code plugins kept as one item each: its
// skills, servers, hooks and subagents are the items above marked
// with its name (plugin.go)
@@ -160,6 +163,9 @@ type Applied struct {
// Subagents are the files magpie wrote for the subagents, each with
// the hash of what it wrote: one changed since is the user's
Subagents []SubagentFile `json:"subagents,omitempty"`
// Commands are the files magpie wrote for the slash commands, kept as
// Subagents are
Commands []SubagentFile `json:"commands,omitempty"`
// Startup is, for each server, the startup timeout magpie wrote in its
// entry (Codex's startup_timeout_sec): one there other than this is
// the user's
@@ -183,7 +189,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.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
}
var mu lock // one change at a time, from the page or the CLI's process
@@ -247,6 +253,10 @@ func (l *Library) save() error {
for _, s := range l.Subagents {
s.Agents = orNone(s.Agents)
}
sort.Slice(l.Commands, func(i, j int) bool { return l.Commands[i].Name < l.Commands[j].Name })
for _, c := range l.Commands {
c.Agents = orNone(c.Agents)
}
// an entry with nothing in it is no record of what magpie wrote, and
// is not kept: a sync that only looked at an agent used to leave one
// behind, one per agent, and the write its save brought into a file
+51 -26
View File
@@ -305,29 +305,52 @@ func (l *Library) syncSubagents(t *Target, b *backups, res *Result) {
}
return
}
wanted := map[string]*Subagent{} // path → the subagent written there
for _, s := range want {
wanted[sp.path(s.Name)] = s
files := make([]ownFile, len(want))
for i, s := range want {
files[i] = ownFile{name: s.Name, path: sp.path(s.Name), body: func() []byte { return l.renderSubagent(sp, s) }}
}
a.Subagents = syncOwnFiles(t, "subagent", a.Subagents, files, b, res)
}
// ownFile is a file of its own magpie wants an agent to have, for the
// library's item called name: at path, with what body renders.
type ownFile struct {
name, path string
body func() []byte
}
// syncOwnFiles writes each file wanted, and takes out every one magpie
// wrote before (had) that is wanted no more, for subagents and slash
// commands alike. A file still as magpie wrote it (its hash) is magpie's
// to rewrite or remove; one the user changed is theirs from then on; one
// by that name magpie didn't write is never touched, and is a problem
// under noun:name, unless it says what magpie would write, when it is
// taken as magpie's. It returns what magpie wrote, sorted by path.
func syncOwnFiles(t *Target, noun string, had []SubagentFile, want []ownFile, b *backups, res *Result) []SubagentFile {
id := t.Agent.ID
wanted := map[string]*ownFile{} // path → the file wanted there
for i := range want {
wanted[want[i].path] = &want[i]
}
done := map[string]bool{}
var kept []SubagentFile
write := func(s *Subagent, path string, body []byte) bool {
write := func(name, path string, body []byte) bool {
if err := b.keep(id, path); err != nil {
res.fail(id, "subagent:"+s.Name, err)
res.fail(id, noun+":"+name, err)
return false
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
res.fail(id, "subagent:"+s.Name, err)
res.fail(id, noun+":"+name, err)
return false
}
if err := edit.WriteAtomic(path, body); err != nil {
res.fail(id, "subagent:"+s.Name, err)
res.fail(id, noun+":"+name, err)
return false
}
res.changed(id)
return true
}
for _, f := range a.Subagents {
for _, f := range had {
cur, err := os.ReadFile(f.Path)
switch {
case os.IsNotExist(err):
@@ -336,7 +359,7 @@ func (l *Library) syncSubagents(t *Target, b *backups, res *Result) {
case err != nil:
// can't tell whether it is still magpie's: left, and kept on
// record, untouched
res.fail(id, "subagent:"+f.Name, err)
res.fail(id, noun+":"+f.Name, err)
kept = append(kept, f)
done[f.Path] = true
continue
@@ -345,15 +368,15 @@ func (l *Library) syncSubagents(t *Target, b *backups, res *Result) {
// the loop below says if the library still wants that name
continue
}
s := wanted[f.Path]
if s == nil {
w := wanted[f.Path]
if w == nil {
if err := b.keep(id, f.Path); err != nil {
res.fail(id, "subagent:"+f.Name, err)
res.fail(id, noun+":"+f.Name, err)
kept = append(kept, f)
continue
}
if err := os.Remove(f.Path); err != nil && !os.IsNotExist(err) {
res.fail(id, "subagent:"+f.Name, err)
res.fail(id, noun+":"+f.Name, err)
kept = append(kept, f)
continue
}
@@ -361,40 +384,42 @@ func (l *Library) syncSubagents(t *Target, b *backups, res *Result) {
continue
}
done[f.Path] = true
body := l.renderSubagent(sp, s)
if !bytes.Equal(cur, body) && !write(s, f.Path, body) {
body := w.body()
if !bytes.Equal(cur, body) && !write(w.name, f.Path, body) {
kept = append(kept, f)
continue
}
kept = append(kept, SubagentFile{Name: s.Name, Path: f.Path, Hash: subagentHash(body)})
kept = append(kept, SubagentFile{Name: w.name, Path: f.Path, Hash: subagentHash(body)})
}
for _, s := range want {
path := sp.path(s.Name)
if done[path] {
for _, w := range want {
if done[w.path] {
continue
}
body := l.renderSubagent(sp, s)
cur, err := os.ReadFile(path)
body := w.body()
cur, err := os.ReadFile(w.path)
switch {
case err == nil && bytes.Equal(cur, body):
// the same as magpie would write: taken as magpie's
case err == nil:
res.fail(id, "subagent:"+s.Name, fmt.Errorf("%s has a subagent of its own at %s, which magpie leaves as it is", t.Agent.Name, path))
res.fail(id, noun+":"+w.name, fmt.Errorf("%s has a %s of its own at %s, which magpie leaves as it is", t.Agent.Name, ownNoun[noun], w.path))
continue
case !os.IsNotExist(err):
res.fail(id, "subagent:"+s.Name, err)
res.fail(id, noun+":"+w.name, err)
continue
default:
if !write(s, path, body) {
if !write(w.name, w.path, body) {
continue
}
}
kept = append(kept, SubagentFile{Name: s.Name, Path: path, Hash: subagentHash(body)})
kept = append(kept, SubagentFile{Name: w.name, Path: w.path, Hash: subagentHash(body)})
}
slices.SortFunc(kept, func(x, y SubagentFile) int { return strings.Compare(x.Path, y.Path) })
a.Subagents = kept
return kept
}
// ownNoun is how a problem names what is in the agent's way.
var ownNoun = map[string]string{"subagent": "subagent", "command": "slash command"}
// ---- changes ---------------------------------------------------------------
// SaveSubagent adds a subagent, or replaces the one called old (renaming
+7 -1
View File
@@ -116,6 +116,7 @@ func syncSteps(all, gone []*Target, b *backups, res *Result) []func(*Library) {
l.syncHooks(t, b, res)
l.syncEnv(t, b, res)
l.syncSubagents(t, b, res)
l.syncCommands(t, b, res)
})
}
// an edit made in an agent's copy of a skill goes to the library first,
@@ -526,7 +527,11 @@ type View struct {
// each agent on this computer makes of them (subagents.go)
Subagents []SubagentView `json:"subagents"`
SubagentAgents []SubagentAgentView `json:"subagentAgents"`
FoundServers []Found `json:"foundServers"`
// Commands are the library's slash commands, and CommandAgents what
// the agents that can take them do with them
Commands []CommandView `json:"commands"`
CommandAgents []CommandAgentView `json:"commandAgents"`
FoundServers []Found `json:"foundServers"`
// Plugins are the plugins kept as one item each (plugin.go)
Plugins []PluginView `json:"plugins"`
Skills []SkillView `json:"skills"`
@@ -730,6 +735,7 @@ func readView(problems []Problem, glance bool) (*View, error) {
v.Hooks, v.HookAgents = l.hooksView(append(slices.Clone(targets), gone...), asleep, of)
v.Env, v.EnvAgents = l.envView(append(slices.Clone(targets), gone...), of)
v.Subagents, v.SubagentAgents = l.subagentsView(targets, asleep, of)
v.Commands, v.CommandAgents = l.commandsView(targets, asleep, of)
v.Plugins = l.pluginsView()
tr := &tracer{}
for _, s := range l.Skills {