diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index ff1c45c65..a74045d70 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -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:`), 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` (`.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: `/subagents/.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`): `/commands/.md` (front matter `description`; `$n` becomes Claude Code's `$ARGUMENTS[n-1]`, counted from 0), OpenCode's `commands/.md` beside its config and Pi's `/prompts/.md` (`$ARGUMENTS` and `$n` as magpie's), `~/.gemini/commands/.toml` (`description`, `prompt`, `$ARGUMENTS` as `{{args}}`), Qwen Code's `commands/.md` (`{{args}}`) and `~/.factory/commands/.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 `.md` in each ticked agent's own folder of rules (`ruleSpecOf`), through the shared `syncOwnFiles`: Claude Code's `/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 `/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' diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 1bb15114b..77d98694c 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -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); diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index cd3a0e418..53678c555 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -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", diff --git a/internal/gui/library.go b/internal/gui/library.go index eb7a51d98..4e5a0bb33 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -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) diff --git a/internal/gui/tests/library-subagents.test.cjs b/internal/gui/tests/library-subagents.test.cjs index cffabeb7f..4c9fef169 100644 --- a/internal/gui/tests/library-subagents.test.cjs +++ b/internal/gui/tests/library-subagents.test.cjs @@ -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