library: each subagent is kept in a Markdown file to edit, or one of the user's own in a git repo (JonahFu on X)

JonahFu asked on X (tweet 2123236872940073039) for each subagent's
local path in Library > Subagents, to edit it with an LLM, or to keep a
subagent in a git repository.

Each subagent of the library (not a plugin's) is now kept on this
computer in <library>/subagents/<name>.md as well, in Claude Code's
shape (name, description, model, skills, mcpServers, the prompt), or in
a file of the user's own set under the editor's Advanced (folded unless
one is set), in a repository say:

- FileHash is what the file said when magpie last wrote or took it in.
  An edit there (by hand, by an agent, a git pull) is taken in at the
  next sync and before a change made on the page, and every ticked
  agent gets it. While magpie runs, KeepLinked's loop syncs when a
  file's hash differs, once per edit.
- An edit that can't be read as a subagent (no front matter, another
  name, no prompt) is left as it is, the agents keep what it said
  before, and the editor says why. magpie writes a file only when it is
  missing, or still as magpie left it; never the user's edit.
- A file of the user's own that is there already is what the subagent
  says (a bad one refuses the save). It must be an absolute .md path,
  not a folder, not inside the library, not one another subagent uses,
  and not a file magpie writes for an agent.
- Rename and remove take the library's own file only while it is as
  magpie wrote it; the user's own file always stays.
- File and FileHash are this computer's: Collect leaves them out, Put
  keeps this computer's.

The editor shows the path (click reveals it, Copy copies it), a line
that edits there reach the agents, and the error when one wasn't taken
in. i18n in zh, zh-TW, ja and de.

docs/subsystems/library.md: a row for the subagent's own file and its
tests.

Run at the tree before 2051dfc23 (a Pi market change in
pimarket.go and plugin/market.go only) came onto origin/main:
- mote-run: gofmt -l none; GOOS=linux and GOOS=windows go vet -tags
  nogui ./... and go vet ./...: ok. go test -timeout 45m ./...: every
  package ok, internal/library 504s, except known reds not touched here:
  internal/cli TestHealthcheckFindsTheRunningGatewayWithoutMagpieAddr,
  TestUpdateRestartsTheGatewayItFindsWithoutMagpieAddr and
  TestUpdateFindsAMagpieThatWroteNoRecord (#6471, #6223: a real gateway
  on mote's 127.0.0.1:3425), internal/gateway
  TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes (#7117).
  mote and mica were both over their cores; the suite went to mote.
- mica-run: node --test library-subagents, library-rules,
  library-commands, i18n-keys, i18n-en-no-cjk (Chromium and WebKit,
  420 and 1100 wide, en zh zh-TW ja de): 44 of 44. Before that, every
  library-*, lib-*, nav-* and i18n* file (95 files, 2071 tests): red
  only in library-commands (its tab-order assert, fixed in the previous
  commit) and library-open-again's 1100px cases, red the same alone at
  base 14b6b9555 (#6751).
- Red on the old code: TestSubagentFileFollowed and
  TestSubagentFileUnreadable went red with the follow step skipped and
  the hash check dropped; library-subagents.test.cjs is red against the
  previous commit's client.js.
- Real use: a sandbox HOME magpie on mica (fake claude on PATH) wrote
  ~/.config/magpie/library/subagents/reviewer.md; an edit there with a
  new description and prompt reached ~/.claude/agents/reviewer.md and
  library.json on the next `library sync`; an edit with no front matter
  was left as written and Claude Code's file kept the old text.
- After rebasing on 2051dfc23, mica-run: go vet ./internal/library
  ./internal/plugin and go test -timeout 45m ./internal/library: ok.
Not tried: a real Claude Code or other agent editing the file, a real
git pull into a repository file while magpie runs (KeepLinked's loop is
covered by TestSubagentOwnFile only), Windows and Linux.
This commit is contained in:
yetone
2026-11-19 12:20:02 +08:00
parent 3132fa1cd9
commit 426a707a19
12 changed files with 663 additions and 17 deletions
+2
View File
@@ -39,6 +39,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) |
| A subagent's own file | Each subagent of the library (not a plugin's) is kept in a Markdown file on this computer as well (JonahFu on X: to edit it with an LLM, or keep it in git), in Claude Code's shape with its model: `<library>/subagents/<name>.md`, or `Subagent.File`, a file of the user's own set under the editor's Advanced, in a repository say (`subagent_file.go`). `FileHash` is what the file said when magpie last wrote or took it in. `followSubagentFiles` (the first sync step, and in `change` before its edit) takes in a file that says anything else and reads as a subagent of that name; one that doesn't is left as it is, the agents keep what it said before, and the view says why (`SubagentView.FileError`, beside `Path`). `writeSubagentFiles` (the last sync step) writes one missing, or one still as magpie left it that says other than the library; never the user's edit. A file of the user's own that is there already when it is set is what the subagent says (a bad one refuses the save). Rename and remove take the library's own file only while it is as magpie wrote it; the user's own always stays. `KeepLinked`'s loop syncs when a file's hash differs from `FileHash` (a git pull, an agent's edit), once per edit. File and FileHash are this computer's: `Collect` leaves them out and `Put` keeps this computer's. The editor shows `Path` (reveal, Copy) and the error.
| 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` |
| Slash commands from the agents | The Slash commands tab's "Find in agents" (miantiao_me on X: "can the ones I defined in Pi be imported?") lists the commands the user already made in each agent here (`ProbeCommands`), read where that agent reads them, at the folder's top only: Pi's `prompts/*.md`, Claude Code's `commands/*.md`, OpenCode's `commands/*.md` and `command/*.md`, Gemini CLI's `commands/*.toml`, Qwen Code's `commands/*.md` and `*.toml` (its FileCommandLoader reads both) and Droid's `commands/*.md`. The file's name is the command's; the description is the front matter's (a TOML's `description`), the prompt the body (a TOML's `prompt`), and each agent's way of saying the words typed in reads back as magpie's: Claude Code's `$ARGUMENTS[n]` and `$n`, counted from 0, as `$n+1` (the `\$0` magpie writes as `$0`), Pi's `$@` and Gemini's and Qwen's `{{args}}` as `$ARGUMENTS`; Pi's `${@:N}` is left as written. A name magpie can't take, a file over 1 MB or one with no prompt is listed as left out, with why. A file magpie wrote, still as it wrote it (`Applied.Commands`), isn't listed. One name saying the same in several agents is one candidate for all of them; saying different things, each is listed, tagged, and only one can be picked. A name the library has saying the same is tagged and joins (the import ticks these agents too); one the library has for another command can't be picked, and the user's file stays as it is. `ImportCommands` takes the paths picked, reads them again, and ticks the agents each was found in. Each command keeps the files it came from (`Command.Taken`, per agent: path, bytes, and a hash of what they said): while the command says the same, `syncCommands` writes those bytes at that path, so `syncOwnFiles` takes the user's own file as magpie's byte for byte, and nothing is doubled or written over (OpenCode's `command/` file stays there). After an edit here, the command is written in the agent's shape at the same path when its extension is the one magpie writes, else at magpie's own path. A rename drops `Taken`. Unticking or removing an imported command takes its file away, into the backups, as with any file of magpie's. `Taken` is this computer's: never in `Bundle.Commands` or the page's view, and a bundle put here keeps it for a command of the same name. | [`command_import.go`](../../internal/library/command_import.go), `TestCommandImportPiPrompts` (Pi's own `.pi/prompts` files in `testdata/pi-prompts`), `TestCommandImportArgs`, `TestCommandImportByName`, `TestCommandImportNotCarried`, `library-commands-import.test.cjs` |
| Rules | A `Rule` (JonahFu on X) is a name (as a slash command's), a Markdown body and, if wanted, `Paths`: globs, one a line in the editor, that keep it to the files they match. `syncRules` writes it as `<name>.md` in each ticked agent's own folder of rules (`ruleSpecOf`), through the shared `syncOwnFiles`: Claude Code's `<claude dir>/rules` (front matter `paths`, the only key it reads; checked against the memory docs and v2.1.327, which reads every .md under the folder, loads one without `paths` at launch and one with them when Read/Write/Edit touches a match), Cline's `<cline dir>/rules` (CLINE_DIR, else ~/.cline; Cline 3.0.70 reads every rule always and has no paths key, so a rule with paths isn't written for it: the agent gets a problem (`noPaths`), and the editor names it under the paths) and Kiro CLI's steering folder beside its AGENTS.md (`inclusion: fileMatch` and `fileMatchPattern` for paths, else always; a rule called `agents` is refused there, as it would be AGENTS.md on a disk that ignores case). A body starting with `---` gets an empty front matter first, so it isn't read as one. Cursor (user rules live in its settings, `.cursor/rules` is per project), Codex (its rules are execpolicy) and Droid (command permissions) read no such folder and aren't listed; nor are Gemini CLI, Qwen Code and OpenCode, which read only their instructions file. An agent in a WSL distro gets none. The editor lists each agent's file as a path to show (`revealable`). Bundles carry them as slash commands; there is no CLI yet. | [`rules.go`](../../internal/library/rules.go), `TestRulesEachAgentsFile`, `TestRulesKeptToTheirPaths`, `TestRulesLeaveTheUsersFiles`, `TestRulesCarried`, `library-rules.test.cjs` |
@@ -127,6 +128,7 @@ Pi's extensions and packages.
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 'TestRule'
go test -tags nogui ./internal/library -run 'TestSubagentFile|TestSubagentOwnFile'
node --test internal/gui/tests/library-rules.test.cjs
go test -tags nogui ./internal/library -run 'TestSkillOffHere|TestLocalServerNotCarried|TestPutKeepsLocalServer|TestPutSameNameAsLocal|TestServerHere'
go test -tags nogui ./internal/backup -run 'TestRestoreKeepsLocalServer|TestBackupFileCarriesSubagents|TestBackupFileCarriesHooks'
+29 -4
View File
@@ -5138,14 +5138,17 @@ magpie.plugin("library", (ctx) => {
function editSubagent(s) {
const all = subagentAgents();
const d = s ? { name: s.name, description: s.description, prompt: s.prompt, model: s.model || "", skills: [...(s.skills || [])], mcp: [...(s.mcp || [])], agents: [...(s.agents || [])] }
: { name: "", description: "", prompt: "", model: "", skills: [], mcp: [], agents: all.filter((a) => !subagentBlocked(a)).map((a) => a.id) };
const d = s ? { name: s.name, description: s.description, prompt: s.prompt, model: s.model || "", skills: [...(s.skills || [])], mcp: [...(s.mcp || [])], agents: [...(s.agents || [])], file: s.file || "" }
: { name: "", description: "", prompt: "", model: "", skills: [], mcp: [], agents: all.filter((a) => !subagentBlocked(a)).map((a) => a.id), file: "" };
const ed = el("div", "editor lib-editor lib-subagentedit");
const head = el("div", "ehead");
head.append(glyph(GLYPH.subagent), el("b", "", s ? s.name : t("New subagent")));
ed.append(head);
const err = el("div", "editor-error");
const name = field2(d.name, t("e.g. code-reviewer"), (v) => { d.name = v.trim(); });
// a file of the user's own's example follows the name
let own = null;
const ownExample = () => "~/code/agents/" + (d.name || "reviewer") + ".md";
const name = field2(d.name, t("e.g. code-reviewer"), (v) => { d.name = v.trim(); if (own) own.placeholder = ownExample(); });
name.classList.add("mono");
ed.append(...field(t("Name"), name, t("Lowercase letters, digits and -; it is the file's name in each agent")));
const box = (cls, value, placeholder, rows, max, onEnter) => {
@@ -5179,6 +5182,28 @@ magpie.plugin("library", (ctx) => {
ed.append(...withHint(field(t("MCP servers"), servers), mcpHint));
const agentsBox = el("div");
ed.append(...field(t("Agents"), agentsBox));
// the file it is kept in on this computer (JonahFu on X): to open, or
// to hand an agent to edit; magpie takes an edit there in
if (s?.path) {
const where = el("div", "lib-rulefile lib-subagentfile");
where.append(pathLink(s.path), copyBtn(s.path, t("Path")));
const [fl, fw] = field(t("Kept in"), where, t("Edit it in any editor or agent: magpie takes the change in and gives it to the agents"));
if (s.fileError) fw.append(el("div", "lib-signin-err lib-subagentfile-err", s.fileError));
ed.append(fl, fw);
}
// a file of the user's own, in a git repository say: rarely, so under
// Advanced, open while it is
if (!s?.bundle) {
const more = el("details", "more advanced lib-subagentmore");
more.open = !!d.file;
more.append(el("summary", "", t("Advanced")));
const inner = el("div", "inner");
own = field2(d.file, ownExample(), (v) => { d.file = v; });
own.classList.add("mono", "lib-subagentownfile");
inner.append(...field(t("Keep in a file of your own"), own, t("A Markdown file anywhere, in a git repository say. One there already is what the subagent says.")));
more.append(inner);
ed.append(more);
}
ed.append(err);
function drawHints() {
const sk = unbound(all, d.agents, "skills"), mc = unbound(all, d.agents, "mcp");
@@ -5207,7 +5232,7 @@ magpie.plugin("library", (ctx) => {
const save = async () => {
err.textContent = "";
try {
const subagent = { name: d.name, description: d.description.trim(), prompt: d.prompt, model: d.model, skills: d.skills, mcp: d.mcp, agents: d.agents.filter((id) => !subagentBlocked(agentOf(id) || { id })) };
const subagent = { name: d.name, description: d.description.trim(), prompt: d.prompt, model: d.model, skills: d.skills, mcp: d.mcp, agents: d.agents.filter((id) => !subagentBlocked(agentOf(id) || { id })), file: d.file.trim() };
take(await api("library/subagents/save", { old: s ? s.name : "", subagent }));
report(lib.result, s ? t("{name} saved", { name: d.name }) : "");
closeLibModal(true);
@@ -204,6 +204,9 @@ magpie.strings({
"The file's name: lowercase letters, digits, - and _": "文件名:小写字母、数字、- 和 _",
"e.g. Run the tests before saying a change works.": "例如:说改动可用之前先跑测试。",
"Only for files": "仅用于这些文件",
"Edit it in any editor or agent: magpie takes the change in and gives it to the agents": "编辑器或 Agent 都能直接改它:magpie 会读入改动并同步给各个 Agent",
"Keep in a file of your own": "保存在你自己的文件里",
"A Markdown file anywhere, in a git repository say. One there already is what the subagent says.": "任意位置的 Markdown 文件,比如 git 仓库里。文件已存在时,以文件内容为准。",
"One glob a line. Empty: read in every conversation": "每行一个 glob。留空:每次对话都读取",
"Not written for {agents}: they read every rule in every conversation": "不会写给 {agents}:它们每次对话都会读取所有规则",
"e.g. review": "例如 review",
@@ -1331,6 +1334,9 @@ magpie.strings({
"The file's name: lowercase letters, digits, - and _": "檔名:小寫字母、數字、- 和 _",
"e.g. Run the tests before saying a change works.": "例如:說改動可用之前先跑測試。",
"Only for files": "僅用於這些檔案",
"Edit it in any editor or agent: magpie takes the change in and gives it to the agents": "用編輯器或 Agent 直接改它:magpie 會讀入改動並同步給各個 Agent",
"Keep in a file of your own": "存放在你自己的檔案裡",
"A Markdown file anywhere, in a git repository say. One there already is what the subagent says.": "任意位置的 Markdown 檔案,例如 git 儲存庫裡。檔案已存在時,以檔案內容為準。",
"One glob a line. Empty: read in every conversation": "每行一個 glob。留空:每次對話都讀取",
"Not written for {agents}: they read every rule in every conversation": "不會寫給 {agents}:它們每次對話都會讀取所有規則",
"e.g. review": "例如 review",
@@ -2458,6 +2464,9 @@ magpie.strings({
"The file's name: lowercase letters, digits, - and _": "ファイル名:英小文字、数字、- と _",
"e.g. Run the tests before saying a change works.": "例:変更が動くと言う前にテストを実行する。",
"Only for files": "対象のファイル",
"Edit it in any editor or agent: magpie takes the change in and gives it to the agents": "エディタやエージェントで直接編集できます:magpie が変更を読み込み、各エージェントに反映します",
"Keep in a file of your own": "自分のファイルに保存",
"A Markdown file anywhere, in a git repository say. One there already is what the subagent says.": "どこにある Markdown ファイルでも構いません(git リポジトリ内など)。既にあるファイルは、その内容がサブエージェントになります。",
"One glob a line. Empty: read in every conversation": "1 行に 1 つの glob。空なら毎回の会話で読まれます",
"Not written for {agents}: they read every rule in every conversation": "{agents} には書かれません。毎回の会話ですべてのルールを読むためです",
"e.g. review": "例:review",
@@ -3585,6 +3594,9 @@ magpie.strings({
"The file's name: lowercase letters, digits, - and _": "Der Dateiname: Kleinbuchstaben, Ziffern, - und _",
"e.g. Run the tests before saying a change works.": "z. B. Führe die Tests aus, bevor du sagst, dass eine Änderung funktioniert.",
"Only for files": "Nur für Dateien",
"Edit it in any editor or agent: magpie takes the change in and gives it to the agents": "Bearbeite sie in einem beliebigen Editor oder Agenten: magpie übernimmt die Änderung und gibt sie an die Agenten weiter",
"Keep in a file of your own": "In einer eigenen Datei speichern",
"A Markdown file anywhere, in a git repository say. One there already is what the subagent says.": "Eine Markdown-Datei an beliebiger Stelle, etwa in einem Git-Repository. Liegt dort schon eine, gilt, was sie sagt.",
"One glob a line. Empty: read in every conversation": "Ein Glob pro Zeile. Leer: in jedem Gespräch gelesen",
"Not written for {agents}: they read every rule in every conversation": "Nicht für {agents} geschrieben: Sie lesen jede Regel in jedem Gespräch",
"e.g. review": "z. B. review",
+6
View File
@@ -161,6 +161,12 @@ func revealable(v *library.View) []string {
for _, s := range v.FoundSkills {
out = append(out, s.Link, s.Shared)
}
for _, s := range v.Subagents {
// the file it is kept in, to edit it in
if s.Path != "" {
out = append(out, s.Path)
}
}
for _, r := range v.Rules {
for _, f := range r.Files {
out = append(out, f)
+43 -7
View File
@@ -18,6 +18,11 @@
// one, so the hint and an aside name the agents that run it on their own
// pick, and the hint says when Codex's subagent model on the Agents page
// takes its place.
// Each is kept in a file of its own on this computer (JonahFu on X): the
// editor shows where, a click shows it in the file manager, and Copy puts
// the path on the clipboard; an edit there magpie couldn't read says why.
// A file of the user's own, in a git repository say, is under Advanced,
// folded until one is set, and Save posts it.
// 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.
@@ -63,7 +68,10 @@ function tr(lang, key, vars = {}) {
return s.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m));
}
function server(lang, state, posts) {
const FILE = `${HOME}/.magpie/library/subagents/reviewer.md`, OWN = `${HOME}/code/agents/test-writer.md`;
const BAD = `magpie can't read ${FILE}: it has no front matter. The agents keep what it said before.`;
function server(lang, state, posts, reveals = []) {
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
@@ -71,11 +79,12 @@ function server(lang, state, posts) {
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.subagents, state.held));
if (url.pathname.startsWith("/api/library/") && req.method() === "POST" && !url.pathname.endsWith("/reveal")) {
if (url.pathname === "/api/library/reveal") { reveals.push(req.postDataJSON().path); return json({}); }
if (url.pathname.startsWith("/api/library/") && req.method() === "POST") {
const body = req.postDataJSON(), what = url.pathname.replace("/api/library/", "");
posts.push({ what, body });
if (what === "subagents/agents") state.subagents = state.subagents.map((x) => (x.name === body.name ? { ...x, agents: body.agents.filter((a) => a !== WSL) } : x));
if (what === "subagents/save") state.subagents = [...state.subagents.filter((x) => x.name !== body.old), body.subagent];
if (what === "subagents/save") state.subagents = [...state.subagents.filter((x) => x.name !== body.old), { ...body.subagent, path: body.subagent.file || `${HOME}/.magpie/library/subagents/${body.subagent.name}.md` }];
if (what === "subagents/remove") state.subagents = state.subagents.filter((x) => x.name !== body.name);
return json({ ...lib(state.subagents, state.held), result: { changed: ["claude"] } });
}
@@ -128,8 +137,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
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 = { subagents: [sa("reviewer", LONG, "You review code.\n\nReport bugs only.", ["tdd"], ["github"], ["claude", "codex"])] };
const posts = [], errors = [];
const state = { subagents: [{ ...sa("reviewer", LONG, "You review code.\n\nReport bugs only.", ["tdd"], ["github"], ["claude", "codex"]), path: FILE, fileError: BAD }] };
const posts = [], errors = [], reveals = [];
const open = async (width) => {
const ctx = await browser.newContext({ viewport: { width, height: 1000 }, reducedMotion: "reduce" });
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "subagents"); } catch {} });
@@ -138,7 +147,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
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.route("**/*", server(lang, state, posts, reveals));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
await page.locator("#view-library .lib-subagent").first().waitFor();
@@ -211,6 +220,12 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
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 subagent"));
// a new one has no file yet; one of the user's own is under
// Advanced, folded
assert.equal(await ed.locator(".lib-subagentfile").count(), 0, "a file line for a subagent not saved yet");
const more = ed.locator(".lib-subagentmore");
assert.equal(await more.evaluate((d) => d.open), false, "Advanced open at first");
assert.equal((await more.locator("summary").textContent()).trim(), w("Advanced"));
const edChip = (id) => ed.locator(`.lib-ag[data-agent="${id}"]`);
for (const id of ["claude", "codex", "cursor", "droid", "opencode"]) assert.equal(await edChip(id).getAttribute("aria-pressed"), "true", id);
assert.equal(await edChip(WSL).getAttribute("aria-pressed"), "false");
@@ -263,10 +278,15 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await menu.waitFor({ state: "detached" });
assert.equal((await ed.locator(".lib-subagentskills").textContent()).trim(), "tdd");
await ed.waitFor();
// kept in a file of the user's own, in a repository
await more.locator("summary").click();
await ed.locator(".lib-subagentownfile").fill(" " + OWN + " ");
assert.equal(await ed.locator(".lib-subagentownfile").getAttribute("placeholder"), "~/code/agents/test-writer.md");
await more.getByText(w("A Markdown file anywhere, in a git repository say. One there already is what the subagent says."), { exact: true }).waitFor();
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: "subagents/save", body: { old: "", subagent: { name: "test-writer", description: "写测试", prompt: "Write tests first.\nThen run them.", model: "group/review", skills: ["tdd"], mcp: [], agents: ["claude", "codex", "cursor", "droid"] } } });
assert.deepEqual(posts.shift(), { what: "subagents/save", body: { old: "", subagent: { name: "test-writer", description: "写测试", prompt: "Write tests first.\nThen run them.", model: "group/review", skills: ["tdd"], mcp: [], agents: ["claude", "codex", "cursor", "droid"], file: OWN } } });
await row("test-writer").waitFor();
assert.equal((await row("test-writer").locator(".lib-subagentuses").textContent()).trim(), w("Model: {name}", { name: "review" }) + " · " + w("Skills: {names}", { names: "tdd" }));
await v.locator(".lib-subagents-nomodel").filter({ hasText: w("{agents} can't be given a subagent's model: theirs runs on the model the agent picks.", { agents: "Claude Code, Cursor, Droid" }) }).waitFor();
@@ -280,6 +300,17 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal((await ed.locator(".ehead b").textContent()).trim(), "reviewer");
assert.equal(await ed.locator(".lib-subagentprompt").inputValue(), "You review code.\n\nReport bugs only.");
assert.equal((await ed.locator(".lib-subagentmcp").textContent()).trim(), "github");
// where it is kept: shown in the file manager on a click, and why
// the edit made there wasn't taken in
const file = ed.locator(".lib-subagentfile");
assert.equal((await file.locator(".lib-path").textContent()).trim(), "~/.magpie/library/subagents/reviewer.md");
await ed.getByText(w("Edit it in any editor or agent: magpie takes the change in and gives it to the agents"), { exact: true }).waitFor();
assert.equal((await ed.locator(".lib-subagentfile-err").textContent()).trim(), BAD);
await file.locator(".lib-path").click();
for (let i = 0; !reveals.length && i < 100; i++) await new Promise((r) => setTimeout(r, 50));
assert.deepEqual(reveals, [FILE]);
assert.equal(await file.locator("button.copy").count(), 1);
assert.equal(await ed.locator(".lib-subagentmore").evaluate((d) => d.open), false, "Advanced open with no file of the user's own");
await ed.locator(".bar button.danger").click();
const sheet = page.locator("dialog.action-confirm");
await sheet.waitFor();
@@ -299,6 +330,11 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await ed.waitFor();
await settled(page);
assert.equal((await ed.locator(".lib-subagentmodel").textContent()).trim(), "review");
// kept in the user's file: shown, and Advanced open with it
assert.equal((await ed.locator(".lib-subagentfile .lib-path").textContent()).trim(), "~/code/agents/test-writer.md");
assert.equal(await ed.locator(".lib-subagentmore").evaluate((d) => d.open), true, "Advanced folded over the user's file");
assert.equal(await ed.locator(".lib-subagentownfile").inputValue(), OWN);
assert.equal(await ed.locator(".lib-subagentfile-err").count(), 0);
assert.equal((await hint("model").textContent()).trim(), w("Not set for {agents}: theirs runs on the model the agent picks", { agents: "Claude Code, Cursor, Droid" }) + " · " + w("Codex's subagent model on the Agents page is set, and takes the place of this one"));
await ed.locator(".bar button", { hasText: w("Cancel") }).click();
await ed.waitFor({ state: "detached" });
+11
View File
@@ -215,6 +215,7 @@ func Collect() (*Bundle, error) {
c.Skills, c.MCP = slices.Sorted(slices.Values(s.Skills)), slices.Sorted(slices.Values(s.MCP))
c.Agents = orNone(slices.Sorted(slices.Values(s.Agents)))
c.From = s.From.clone()
c.File, c.FileHash = "", "" // this computer's
subs = append(subs, &c)
}
b.Subagents = &subs
@@ -826,8 +827,18 @@ func Put(b *Bundle) (*Result, error) {
c := *s
c.Skills, c.MCP, c.Agents = slices.Clone(s.Skills), slices.Clone(s.MCP), slices.Clone(orNone(s.Agents))
c.From = s.From.clone()
// the file it is kept in here stays this computer's
c.File, c.FileHash = "", ""
if here := l.subagent(s.Name); here != nil {
c.File, c.FileHash = here.File, here.FileHash
}
subs = append(subs, &c)
}
for _, s := range l.Subagents {
if !slices.ContainsFunc(subs, func(c *Subagent) bool { return c.Name == s.Name }) {
dropSubagentFile(s)
}
}
l.Subagents = subs
}
// slash commands the same way: Applied.Commands decides
+2
View File
@@ -901,6 +901,8 @@ func KeepLinked(ctx context.Context, interval time.Duration) {
}
// what was ticked for a stopped WSL distro's agents, once it runs
keepWoken()
// an edit made in a subagent's own file (subagent_file.go)
keepSubagentFiles()
// a git worktree made or removed beside a project follows it
keepProjectTrees()
// Claude Code's auto-compaction beside a bili plugin magpie
+2
View File
@@ -394,6 +394,8 @@ func changeLocked(f func(l *Library) error) (*Result, error) {
if err != nil {
return nil, err
}
// what a subagent's file says first, for f to change that
l.followSubagentFiles()
if err := f(l); err != nil {
return nil, err
}
+308
View File
@@ -0,0 +1,308 @@
package library
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"github.com/yetone/magpie/internal/edit"
)
// A subagent's own file (JonahFu on X: show where a subagent is, to edit
// it with an LLM, or keep it in a git repository). Each subagent of the
// library is kept in a Markdown file on this computer as well, in Claude
// Code's shape with its model: <library>/subagents/<name>.md, or a file
// of the user's own (File), in a repository say. An edit made there, by
// hand, by an agent or by a git pull, is taken into the library at the
// next sync (followSubagentFiles), and every agent ticked for it gets it;
// one made on the page is written there (writeSubagentFiles). FileHash is
// what the file said when magpie last wrote or took it in: a file that
// says anything else is the user's edit, to take in, never to write over.
// One that can't be read as a subagent stays as it is, the agents keep
// what it said before, and the page says why (FileError).
//
// The file is this computer's, as Applied is: a bundle carries neither
// File nor FileHash, and Put keeps this computer's. A plugin's subagent
// (Bundle) has none: the plugin's update would undo an edit.
// subagentsDir is where the library keeps its subagents' files.
func subagentsDir() string { return filepath.Join(Dir(), "subagents") }
// file is where s is kept on this computer, "" for a plugin's.
func (s *Subagent) file() string {
switch {
case s.Bundle != "":
return ""
case s.File != "":
return s.File
}
return filepath.Join(subagentsDir(), s.Name+".md")
}
// ownSubagentFile is s as its own file says it.
func ownSubagentFile(s *Subagent) []byte {
kv := [][2]string{{"name", yamlStr(s.Name)}, {"description", yamlStr(s.Description)}}
if s.Model != "" {
kv = append(kv, [2]string{"model", yamlStr(s.Model)})
}
if len(s.Skills) > 0 {
kv = append(kv, [2]string{"skills", yamlList(s.Skills)})
}
if len(s.MCP) > 0 {
kv = append(kv, [2]string{"mcpServers", yamlList(s.MCP)})
}
return frontmatter(kv, s.Prompt)
}
// readOwnSubagent is the subagent a file of its own says, named name, or
// why it can't be one.
func readOwnSubagent(name string, b []byte) (*Subagent, error) {
if len(b) > maxSubagentFile {
return nil, errors.New("it is over 1 MB")
}
front, body := splitFront(b)
if front == nil {
return nil, errors.New("it has no front matter (--- name, description --- above the prompt)")
}
if n := plStr(front["name"]); n != "" && n != name {
return nil, fmt.Errorf("it names it %s: rename it in magpie", n)
}
s := &Subagent{
Name: name,
Description: strings.Join(strings.Fields(plStr(front["description"])), " "),
Prompt: strings.TrimRight(strings.TrimLeft(body, "\n"), " \n\t"),
Model: plStr(front["model"]),
}
for _, k := range []struct {
key string
to *[]string
}{{"skills", &s.Skills}, {"mcpServers", &s.MCP}} {
named := pathsOf(front[k.key])
if len(named) == 1 {
named = strings.Split(named[0], ",") // Claude Code's comma list
}
for _, x := range named {
if x = strings.TrimSpace(x); x != "" {
*k.to = append(*k.to, x)
}
}
*k.to = slices.Compact(slices.Sorted(slices.Values(*k.to)))
}
if err := s.check(); err != nil {
return nil, err
}
return s, nil
}
// saysSame is whether s and f say the same, the agents aside.
func (s *Subagent) saysSame(f *Subagent) bool {
return s.Description == f.Description && s.Prompt == f.Prompt && s.Model == f.Model &&
slices.Equal(s.Skills, f.Skills) && slices.Equal(s.MCP, f.MCP)
}
// readSteady reads f once it holds still: a file read while another
// process writes it in place may be half there. ok false: it changed
// while being read, to look at again later.
func readSteady(f string) (b []byte, ok bool, err error) {
before, err := os.Stat(f)
if err != nil {
return nil, false, err
}
if b, err = os.ReadFile(f); err != nil {
return nil, false, err
}
after, err := os.Stat(f)
if err != nil {
return nil, false, err
}
return b, before.Size() == after.Size() && before.ModTime().Equal(after.ModTime()) && int64(len(b)) == after.Size(), nil
}
// takeFile takes what s's file says, when it changed since magpie last
// wrote or took it in: true when s changed. A file that can't be read as
// a subagent is left for writeSubagentFiles to leave too.
func (s *Subagent) takeFile() bool {
f := s.file()
if f == "" {
return false
}
b, ok, err := readSteady(f)
if err != nil || !ok || subagentHash(b) == s.FileHash {
return false
}
x, err := readOwnSubagent(s.Name, b)
if err != nil {
return false
}
changed := !s.saysSame(x)
s.Description, s.Prompt, s.Model, s.Skills, s.MCP = x.Description, x.Prompt, x.Model, x.Skills, x.MCP
s.FileHash = subagentHash(b)
return changed
}
// followSubagentFiles takes into the library every edit made in a
// subagent's file, before the agents are written from it.
func (l *Library) followSubagentFiles() {
for _, s := range l.Subagents {
s.takeFile()
}
}
// writeSubagentFiles writes each subagent's file where it says other than
// the library: one missing, or one as magpie last wrote or took it in. An
// edit not taken in (it can't be read) stays.
func (l *Library) writeSubagentFiles() {
for _, s := range l.Subagents {
f := s.file()
if f == "" {
continue
}
b, err := os.ReadFile(f)
switch {
case errors.Is(err, os.ErrNotExist):
case err != nil:
continue // unknown: left as it is
case subagentHash(b) != s.FileHash:
continue
default:
if x, err := readOwnSubagent(s.Name, b); err == nil && s.saysSame(x) {
continue
}
}
body := ownSubagentFile(s)
if err := os.MkdirAll(filepath.Dir(f), 0o755); err != nil {
log.Printf("library: subagent %s's file: %v", s.Name, err)
continue
}
if err := edit.WriteAtomic(f, body); err != nil {
log.Printf("library: subagent %s's file: %v", s.Name, err)
continue
}
s.FileHash = subagentHash(body)
}
}
// dropSubagentFile takes away the library's own file of s, still as magpie
// wrote it, when s goes or is renamed. A file of the user's own (File)
// always stays, as does one edited since.
func dropSubagentFile(s *Subagent) {
if s.File != "" || s.Bundle != "" {
return
}
f := s.file()
if b, err := os.ReadFile(f); err == nil && subagentHash(b) == s.FileHash {
os.Remove(f)
}
}
// subagentFileError is why s's file isn't followed, or "".
func subagentFileError(s *Subagent) string {
f := s.file()
if f == "" {
return ""
}
b, err := os.ReadFile(f)
switch {
case errors.Is(err, os.ErrNotExist):
return ""
case err != nil:
return err.Error()
case subagentHash(b) == s.FileHash:
return ""
}
if _, err := readOwnSubagent(s.Name, b); err != nil {
return "magpie can't read " + f + ": " + err.Error() + ". The agents keep what it said before."
}
return ""
}
// ownSubagentPath is where the user asked a subagent kept, made absolute,
// or why it can't be: a file magpie writes for an agent, one of the
// library's own, a folder, or one another subagent is kept in.
func (l *Library) ownSubagentPath(name, file string) (string, error) {
file = strings.TrimSpace(file)
if file == "" {
return "", nil
}
if rest, ok := strings.CutPrefix(file, "~"); ok && (rest == "" || rest[0] == '/' || rest[0] == filepath.Separator) {
file = home() + rest
}
if !filepath.IsAbs(file) {
return "", fmt.Errorf("%s: give the file's full path", file)
}
file = filepath.Clean(file)
if !strings.EqualFold(filepath.Ext(file), ".md") {
return "", fmt.Errorf("%s: give a Markdown file (.md)", file)
}
if st, err := os.Stat(file); err == nil && st.IsDir() {
return "", fmt.Errorf("%s is a folder: give a file", file)
}
real := realBelow(file)
if lib := realBelow(Dir()); strings.HasPrefix(real, lib+string(filepath.Separator)) {
return "", fmt.Errorf("%s is the library's own", file)
}
for _, s := range l.Subagents {
if s.Name != name && s.File != "" && realBelow(s.File) == real {
return "", fmt.Errorf("the subagent %s is kept in %s already", s.Name, file)
}
}
for _, a := range l.Applied {
for _, fs := range [][]SubagentFile{a.Subagents, a.Commands, a.Rules} {
for _, f := range fs {
if realBelow(f.Path) == real {
return "", fmt.Errorf("magpie writes %s for an agent: a subagent can't be kept there", file)
}
}
}
}
return file, nil
}
// subagentFilesTried is, for each file, the edit keepSubagentFiles last
// took a sync for: one that can't be read is tried once, not every tick.
var subagentFilesTried struct {
sync.Mutex
at map[string]string
}
// keepSubagentFiles writes the agents again when a subagent's file says
// other than magpie last wrote or took in: edited by an agent, or pulled
// by git, while magpie runs.
func keepSubagentFiles() {
mu.Lock()
l, err := load()
edited := map[string]string{}
if err == nil {
for _, s := range l.Subagents {
if f := s.file(); f != "" {
if b, err := os.ReadFile(f); err == nil && subagentHash(b) != s.FileHash {
edited[f] = subagentHash(b)
}
}
}
}
mu.Unlock()
if err != nil {
return
}
subagentFilesTried.Lock()
changed := false
for f, h := range edited {
if subagentFilesTried.at[f] != h {
changed = true
}
}
subagentFilesTried.at = edited
subagentFilesTried.Unlock()
if !changed {
return
}
if _, err := change(func(*Library) error { return nil }); err != nil {
log.Println("library: subagent files:", err)
}
}
+202
View File
@@ -0,0 +1,202 @@
package library
import (
"os"
"path/filepath"
"strings"
"testing"
)
func subagentViewOf(t *testing.T, name string) SubagentView {
t.Helper()
v, err := Read(nil)
if err != nil {
t.Fatal(err)
}
for _, s := range v.Subagents {
if s.Name == name {
return s
}
}
t.Fatalf("no %s in the view", name)
return SubagentView{}
}
// Each subagent is kept in a file of its own on this computer: an edit
// made there, by hand or by an agent, reaches the library and every agent
// ticked for it; one made on the page is written there.
func TestSubagentFileFollowed(t *testing.T) {
h := sandbox(t)
claude := filepath.Join(h, ".claude/agents/reviewer.md")
s := Subagent{Name: "reviewer", Description: "Reviews a diff.", Prompt: "You review code.", Agents: []string{"claude"}}
ok(t)(SaveSubagent("", s))
f := filepath.Join(Dir(), "subagents/reviewer.md")
if got := read(t, f); got != "---\nname: \"reviewer\"\ndescription: \"Reviews a diff.\"\n---\n\nYou review code.\n" {
t.Fatalf("its file: %q", got)
}
if v := subagentViewOf(t, "reviewer"); v.Path != f || v.FileError != "" || v.FileHash != "" {
t.Errorf("view: path %q error %q hash %q", v.Path, v.FileError, v.FileHash)
}
// edited there, as an agent would: the library and Claude Code follow
write(t, f, "---\nname: reviewer\ndescription: Reviews a diff for bugs.\nmodel: gpt-5.5\nskills: tdd, lint\n---\n\nYou review code.\n\nReport bugs only.\n")
ok(t)(Sync())
l, _ := load()
got := l.subagent("reviewer")
if got.Description != "Reviews a diff for bugs." || got.Prompt != "You review code.\n\nReport bugs only." || got.Model != "gpt-5.5" || strings.Join(got.Skills, ",") != "lint,tdd" {
t.Errorf("the library after the edit: %+v", got)
}
if c := read(t, claude); !strings.Contains(c, "Report bugs only.") || !strings.Contains(c, "Reviews a diff for bugs.") {
t.Errorf("claude's after the edit: %q", c)
}
// the user's own words stay as they wrote them
if !strings.Contains(read(t, f), "skills: tdd, lint") {
t.Error("the edited file was written over")
}
// a change on the page is written there
s.Prompt = "Be brief."
ok(t)(SaveSubagent("reviewer", s))
if got := read(t, f); !strings.HasSuffix(got, "---\n\nBe brief.\n") {
t.Errorf("its file after a save: %q", got)
}
// renamed: the old file goes with the old name
s.Name = "checker"
ok(t)(SaveSubagent("reviewer", s))
if _, err := os.Stat(f); !os.IsNotExist(err) {
t.Errorf("reviewer.md after the rename: %v", err)
}
g := filepath.Join(Dir(), "subagents/checker.md")
if !strings.Contains(read(t, g), "name: \"checker\"") {
t.Errorf("checker.md: %q", read(t, g))
}
ok(t)(RemoveSubagents([]string{"checker"}))
if _, err := os.Stat(g); !os.IsNotExist(err) {
t.Errorf("checker.md after remove: %v", err)
}
}
// An edit that can't be read as a subagent is left as it is, the agents
// keep what it said before, and the page says why; once it reads again,
// it is taken in.
func TestSubagentFileUnreadable(t *testing.T) {
h := sandbox(t)
claude := filepath.Join(h, ".claude/agents/reviewer.md")
ok(t)(SaveSubagent("", Subagent{Name: "reviewer", Description: "Reviews.", Prompt: "Review.", Agents: []string{"claude"}}))
f := filepath.Join(Dir(), "subagents/reviewer.md")
before := read(t, claude)
for _, bad := range []string{
"Just a prompt, no front matter.\n",
"---\nname: other\ndescription: x\n---\n\nhi\n",
"---\ndescription: Reviews.\n---\n\n \n",
} {
write(t, f, bad)
ok(t)(Sync())
if read(t, f) != bad {
t.Errorf("%q was written over", bad)
}
if read(t, claude) != before {
t.Errorf("claude's changed on %q", bad)
}
if v := subagentViewOf(t, "reviewer"); !strings.Contains(v.FileError, f) || v.Prompt != "Review." {
t.Errorf("view on %q: %q %q", bad, v.FileError, v.Prompt)
}
// a change on the page meanwhile leaves the user's text too
ok(t)(SubagentAgentsSet("reviewer", []string{"claude"}))
if read(t, f) != bad {
t.Errorf("%q was written over by a change", bad)
}
}
write(t, f, "---\ndescription: Reviews.\n---\n\nReview twice.\n")
ok(t)(Sync())
if !strings.Contains(read(t, claude), "Review twice.") || subagentViewOf(t, "reviewer").FileError != "" {
t.Errorf("not taken once fixed: %q", read(t, claude))
}
// a file the user deleted comes back
os.Remove(f)
ok(t)(Sync())
if !strings.Contains(read(t, f), "Review twice.") {
t.Errorf("not written again: %q", read(t, f))
}
// one edited and not taken in stays when the subagent goes
write(t, f, "mine")
ok(t)(RemoveSubagents([]string{"reviewer"}))
if read(t, f) != "mine" {
t.Error("an edited file went with the subagent")
}
}
// Kept in a file of the user's own, in a repository say: one there
// already is what the subagent says; one not there yet is written. It
// stays when the subagent goes.
func TestSubagentOwnFile(t *testing.T) {
h := sandbox(t)
claude := filepath.Join(h, ".claude/agents/reviewer.md")
mine := filepath.Join(h, "repo/agents/reviewer.md")
write(t, mine, "---\nname: reviewer\ndescription: From the repo.\n---\n\nThe repo's prompt.\n")
s := Subagent{Name: "reviewer", Description: "Typed.", Prompt: "Typed.", Agents: []string{"claude"}, File: "~/repo/agents/reviewer.md"}
ok(t)(SaveSubagent("", s))
if c := read(t, claude); !strings.Contains(c, "The repo's prompt.") || !strings.Contains(c, "From the repo.") {
t.Errorf("claude's: %q", c)
}
if _, err := os.Stat(filepath.Join(Dir(), "subagents/reviewer.md")); !os.IsNotExist(err) {
t.Errorf("the library's own file too: %v", err)
}
if v := subagentViewOf(t, "reviewer"); v.Path != mine || v.File != mine {
t.Errorf("view: %q %q", v.Path, v.File)
}
// a git pull, as keepSubagentFiles sees it while magpie runs
write(t, mine, "---\nname: reviewer\ndescription: From the repo.\n---\n\nPulled.\n")
keepSubagentFiles()
if !strings.Contains(read(t, claude), "Pulled.") {
t.Errorf("claude's after a pull: %q", read(t, claude))
}
// one not there yet is written
other := filepath.Join(h, "repo/agents/new.md")
ok(t)(SaveSubagent("", Subagent{Name: "new", Description: "New.", Prompt: "New.", Agents: []string{}, File: other}))
if !strings.Contains(read(t, other), "New.") {
t.Errorf("new.md: %q", read(t, other))
}
ok(t)(RemoveSubagents([]string{"reviewer", "new"}))
if !strings.Contains(read(t, mine), "Pulled.") || read(t, other) == "" {
t.Error("removing took the user's own files")
}
for _, bad := range []string{"repo/x.md", filepath.Join(h, "repo/x.txt"), filepath.Join(Dir(), "x.md"), filepath.Join(h, "repo")} {
if _, err := SaveSubagent("", Subagent{Name: "bad", Description: "x", Prompt: "x", File: bad}); err == nil {
t.Errorf("kept in %s", bad)
}
}
ok(t)(SaveSubagent("", Subagent{Name: "given", Description: "x", Prompt: "x", Agents: []string{"claude"}}))
if _, err := SaveSubagent("", Subagent{Name: "bad", Description: "x", Prompt: "x", File: filepath.Join(h, ".claude/agents/given.md")}); err == nil {
t.Error("kept in a file magpie writes for Claude Code")
}
write(t, filepath.Join(h, "repo/broken.md"), "no front matter")
if _, err := SaveSubagent("", Subagent{Name: "broken", Description: "x", Prompt: "x", File: filepath.Join(h, "repo/broken.md")}); err == nil {
t.Error("kept in a file that isn't a subagent")
}
}
// The file is this computer's: a bundle carries none, and Put keeps the
// file each subagent here is kept in.
func TestSubagentFileNotCarried(t *testing.T) {
h := sandbox(t)
mine := filepath.Join(h, "repo/reviewer.md")
ok(t)(SaveSubagent("", Subagent{Name: "reviewer", Description: "Reviews.", Prompt: "Review.", Agents: []string{}, File: mine}))
b, err := Collect()
if err != nil {
t.Fatal(err)
}
if c := (*b.Subagents)[0]; c.File != "" || c.FileHash != "" {
t.Fatalf("carried: %q %q", c.File, c.FileHash)
}
(*b.Subagents)[0].Prompt = "From the other computer."
if _, err := Put(b); err != nil {
t.Fatal(err)
}
l, _ := load()
if s := l.subagent("reviewer"); s.File != mine || !strings.Contains(read(t, mine), "From the other computer.") {
t.Errorf("after put: %+v, file %q", s, read(t, mine))
}
}
+43 -4
View File
@@ -66,6 +66,11 @@ type Subagent struct {
// repository, and FromHash what it said then (subagent_import.go)
From *Source `json:"from,omitempty"`
FromHash string `json:"fromHash,omitempty"`
// File is a file of the user's own it is kept in on this computer,
// "" for the library's; FileHash what the file said when magpie last
// wrote or took it in (subagent_file.go)
File string `json:"file,omitempty"`
FileHash string `json:"fileHash,omitempty"`
}
// SubagentFile is a file magpie wrote for a subagent, and the hash of what
@@ -436,20 +441,43 @@ func SaveSubagent(old string, s Subagent) (*Result, error) {
if s.Name != old && l.subagent(s.Name) != nil {
return fmt.Errorf("the library already has a subagent called %s", s.Name)
}
s.From, s.FromHash = nil, ""
file, err := l.ownSubagentPath(s.Name, s.File)
if err != nil {
return err
}
s.From, s.FromHash, s.File, s.FileHash = nil, "", file, ""
if old != "" {
i := slices.IndexFunc(l.Subagents, func(x *Subagent) bool { return x.Name == old })
if i < 0 {
return fmt.Errorf("no subagent called %s", old)
}
was := l.Subagents[i]
// where it was imported from stays, its edits telling an
// import again to leave it alone
s.From, s.FromHash = l.Subagents[i].From.clone(), l.Subagents[i].FromHash
s.From, s.FromHash = was.From.clone(), was.FromHash
if was.file() == s.file() {
s.FileHash = was.FileHash
} else {
dropSubagentFile(was)
}
l.Subagents = slices.Delete(l.Subagents, i, i+1)
if old != s.Name {
l.renameProjectSubagents(old, s.Name)
}
}
// a file of the user's own that is there already is what it says
if file != "" && s.FileHash == "" {
if b, err := os.ReadFile(file); err == nil {
x, err := readOwnSubagent(s.Name, b)
if err != nil {
return fmt.Errorf("%s: %v", file, err)
}
s.Description, s.Prompt, s.Model, s.Skills, s.MCP = x.Description, x.Prompt, x.Model, x.Skills, x.MCP
s.FileHash = subagentHash(b)
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
}
s.Skills = slices.Compact(slices.Sorted(slices.Values(s.Skills)))
s.MCP = slices.Compact(slices.Sorted(slices.Values(s.MCP)))
s.Agents = orNone(slices.Compact(slices.Sorted(slices.Values(s.Agents))))
@@ -487,7 +515,13 @@ func RemoveSubagents(names []string) (*Result, error) {
return fmt.Errorf("no subagent called %s", n)
}
}
l.Subagents = slices.DeleteFunc(l.Subagents, func(s *Subagent) bool { return slices.Contains(names, s.Name) })
l.Subagents = slices.DeleteFunc(l.Subagents, func(s *Subagent) bool {
if slices.Contains(names, s.Name) {
dropSubagentFile(s)
return true
}
return false
})
return nil
})
}
@@ -499,6 +533,10 @@ type SubagentView struct {
*Subagent
// Files are, for each agent it was written to, the file
Files map[string]string `json:"files,omitempty"`
// Path is the file it is kept in on this computer, to edit it in;
// FileError why an edit there wasn't taken in
Path string `json:"path,omitempty"`
FileError string `json:"fileError,omitempty"`
// Problems are the agents it couldn't be given to, and why
Problems map[string]string `json:"problems,omitempty"`
}
@@ -546,7 +584,8 @@ func (l *Library) subagentsView(targets []*Target, asleep []*agent.Agent, of fun
for _, s := range l.Subagents {
c := *s
c.Agents = orNone(c.Agents)
sv := SubagentView{Subagent: &c, Problems: of("subagent:" + s.Name)}
sv := SubagentView{Subagent: &c, Problems: of("subagent:" + s.Name), Path: s.file(), FileError: subagentFileError(s)}
c.FileHash = ""
for id, a := range l.Applied {
for _, f := range a.Subagents {
if f.Name == s.Name && slices.Contains(s.Agents, id) {
+3 -2
View File
@@ -111,7 +111,8 @@ func (l *Library) sync() *Result {
func syncSteps(all, gone []*Target, b *backups, res *Result) []func(*Library) {
// a skill whose app moved it is followed first, for every agent to
// get the moved one (skill_moved.go)
steps := []func(*Library){func(l *Library) { l.followMovedSkills() }}
// an edit made in a subagent's own file too (subagent_file.go)
steps := []func(*Library){func(l *Library) { l.followMovedSkills(); l.followSubagentFiles() }}
for _, t := range all {
steps = append(steps, func(l *Library) {
l.syncInstructions(t, all, b, res, true)
@@ -154,7 +155,7 @@ func syncSteps(all, gone []*Target, b *backups, res *Result) []func(*Library) {
}
// magpie's copies in a WSL distro no agent there is linked to any more
steps = append(steps, func(l *Library) { l.sweepWSLStores(append(slices.Clone(all), gone...), res) })
return append(steps, func(l *Library) { l.syncProjects(res) })
return append(steps, func(l *Library) { l.syncProjects(res) }, func(l *Library) { l.writeSubagentFiles() })
}
// Sync writes the library into the agents again: after an agent is