diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index ec24ea347..352bbdefd 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -35,7 +35,7 @@ Pi's extensions and packages. | Skills a repository or folder added | A check for updates (`CheckSkills`) also asks, for each GitHub repository and ref the library has skills from, GitHub's list of its files (`repoTree`, one API request, free when the ETag still matches). Only when that list has a skill folder beside the installed ones (under `newBase`, their deepest common folder) that the library doesn't have and hasn't offered does `findNew` fetch the repository for the skills' names and descriptions. `SeenSkills` records per `repo@ref` the paths the install picker showed and the ones set aside, so they aren't offered again. The finds live in memory (`newFound`) and reach the page as `View.NewSkills`; `AddNewSkills` gives each to the agents that have its repository's other skills, and `IgnoreNewSkills` sets it aside (`/api/library/skills/{add-new,ignore-new}`). A git repository on another host has no such list: when `git ls-remote` gives its ref a head, `findNewGit` reads the fetch the check shares (`fetcher`), once per head while its finds are kept (`gitLooked`), and offers the skills under `newBase` with the address as the library has it, `.git` and all, so an Add keeps the same `repo@ref`. A folder the user added linked skills from is kept as `folder:` in `SeenSkills` (`offered`, at install), which is also how the library knows which folder to look in again: `findNewFolder` reads it as Add from folder does and offers a skill folder there the library doesn't link, hasn't offered, and has no skill by that name of; a folder that can't be read keeps what was found. `View.CheckFolders` (`addedFromFolders`, which reads no folder) puts Check for updates on the page with only linked skills, and makes `checkDue` true. A check never adds or writes a skill: each is offered, and one the user removed or set aside isn't offered again. A folder added before this kept no `folder:` key and is looked in only once the user adds from it again (refeccd on Discord; `TestCheckSkillsFindsNewInGitRepo`, `TestCheckSkillsFindsNewInFolder`, `skill-new-in-repo.test.cjs`). | [`skillnew.go`](../../internal/library/skillnew.go), [`skillcheck.go`](../../internal/library/skillcheck.go) | | Skill groups | The page groups skills by `SkillView.Repo`, the repository each came from (`tracer.repoOf`): its GitHub source, CC Switch's `Origin`, `From`, the skills CLI's lock or the git checkout a linked folder is in. That checkout is the one git finds (`provider.GitAt` in `gitRepoOf`): an empty `.git` between the skill and its checkout is passed over, as git passes it over, and a `.git` file that names no repository (a worktree left behind) is none (#3675, `TestSkillRepoTraced`). A lock entry of `sourceType: well-known` (a site's kit at its `/.well-known/agent-skills/`) is grouped by its `sourceBaseUrl` as host/path (`wellKnownBase`), not by each skill's own `sourceUrl`: Feishu's lark-* skills are one group and Fish Audio's another, while two kits under one host with different base URLs stay apart. An older entry with no base URL takes the part of its `sourceUrl` before `/.well-known/`, and one with neither is grouped by its `sourceUrl` as before. Such a kit is never fetched from GitHub by Group again, even when it reads like owner/repo (a GitHub owner has no dot), and its heading's link opens the site (#1862, `TestWellKnownKitGrouped`). `From` is written when a repository is probed (installing from it again, `noteFrom`): for a skill with the very same `SKILL.md`, and for one traced to nowhere by a name the repository has when the library has others from there, since a pack added a while ago is mostly older copies edited there since (White Immortal on Discord: 20 of mattpocock/skills' 38). Group again (`RegroupSkills`, `POST /api/library/skills/regroup`) fetches each GitHub repository the skills are traced to and does the same; it fails only when none could be fetched. A skill traced to another repository is never moved. A group's (or part's, or the Select bar's) agent chips count, give and take only the skills magpie decides for each agent: one kept in `~/.agents/skills` is in `SkillView.Always` for the agents that read that folder themselves, so a chip's `agents-some` for such an agent leaves it out, its tooltip and the status after a click say how many it still reads itself, and an agent that reads every one of them itself has a lit, locked chip as the row's is, which sends nothing (`groupChips` in plugins/library/client.js). The heading says how many of its skills are in `~/.agents/skills`. A row's locked chip is lit with a lock on its corner, not greyed like a chip that can't be given the skill (#1862, `skill-group-shared.test.cjs`). Collapse all / Expand all, beside the sort, folds or opens every group the list shows at once (`foldAllButton`): without a filter it sets each group's kept fold (`magpie.libSkillFolds`), as a click on each heading would; while filtering, only the groups the filter shows, till the filter changes (`unfiltered`), leaving the kept folds alone. It reads Collapse all while any shown group is open, is hidden with fewer than two groups (A→Z, or a filter one group matches), leaves a part's own fold as it is and sends nothing (#1862, `skill-fold-all.test.cjs`). A group's, part's, project's or agent's heading opened or folded stays where it was clicked, its rows coming in below it (jinpwng on X, `library-group-steady.test.cjs`). | [`skill_from.go`](../../internal/library/skill_from.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) | | Skill updates | A skill from GitHub (`kind: github`, a market install among them) keeps the commit it was fetched at and `Hash`, the hash of its files as fetched. `CheckSkills` asks GitHub for each one's last commit and keeps the result in memory; `View.CheckDue` says none was checked since magpie started, or not for `checkEvery` (12 hours), and the page then checks by itself as the skills open (#1449). `editState` says a skill was changed here when the library's folder no longer hashes to `Hash` (`.DS_Store` aside), or an agent's copy was edited since its mark and not yet taken in; the view's `edited` says so. What installing a skill's dependencies or running it writes in its folder is no change (`fromInstall`: `node_modules`, `.venv`, `venv`, `__pycache__`, `.pytest_cache`, `.mypy_cache`, `.ruff_cache` folders, `*.pyc`/`*.pyo`, and `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `bun.lock`, `bun.lockb`, `uv.lock` written again; ggbr on Discord): `Own` is the hash of the files as fetched leaving those aside (`ownHash`), and `onlyInstalled` compares the folder with it, or for a skill fetched before `Own` was kept with `Hash` (so a lock file the install wrote again still reads as changed until its next update). An update carries those entries over to the version fetched where it has none of its own (`carryInstalled`), so they aren't installed again. `UpdateSkill` refuses such a skill with `*EditedError` unless told to replace it (the page's own Update asks first; the CLI takes `--replace-edits`), and `UpdateSkills`/`UpdateSomeSkills` leave it as it is, in `Unupdated`. A replaced version that was changed, or that can't be told (no `Hash`), is moved to the backups (`keepReplaced`). Skills the skills CLI manages (`npx skills`, `~/.agents/.skill-lock.json`, or `$XDG_STATE_HOME/skills/.skill-lock.json` when that is set, both read with the XDG one winning) are only grouped: the CLI updates them (`npx skills update`). A linked folder, a skill imported from an agent and a `From`-only skill have no remote to check; one CC Switch installed (`Origin`) can be updated by hand but isn't checked. A skill from another git repository (`kind: git`) keeps the repository's head commit it was fetched at in `Commit`, and `Hash`. A check runs `git ls-remote` for the ref (`gitRemoteHead`): the same head is current; another one is fetched shallowly, once per repository and ref in a check, and the skill's folder hashed, so a commit that left the skill as it was is current and its head is kept as `Commit` (`checkGitSkill`). Its `*EditedError` and the page's Changed here, Update and the question before replacing a change name that repository, not GitHub (`editedError`, `skill-git-source.test.cjs`). New skills in such a repository are found from its fetch (`findNewGit`, above); Group again, icons and the market are GitHub's only. A skill whose source was read whole and no longer has its folder or `SKILL.md` was removed there (`goneFrom`; スライム on Discord): `UpdateSkill` returns `*GoneError`, `UpdateSkills`/`UpdateSomeSkills` list it in `Result.Gone`, not `Unupdated`, and a check gives it status `gone`. Each records `Skill.Gone` (the view's `gone`), cleared when a check or an update finds it there again. A fetch that failed, a skill left out of a fetch as too big (`leftOutAt`) and a folder that can't be read are unknown, never gone. Nothing is taken out by itself: `RemoveGoneSkills` (`POST /api/library/skills/remove-gone`, `magpie library skill rm --gone [--yes]`, the TUI's `d` on the row) takes the ones named, or every one marked, as `RemoveSkills` does, folders to the backups, and keeps one found in its source again. The page tags such a row Removed upstream with no Update, says them apart from failures after Update all, and offers Clean up N in the group's heading (in the bar with one group), which asks first, naming each one and which was changed here (`confirmRemoveGone`, `skill-gone.test.cjs`). Updates by themselves (`AutoUpdateSkills` in library.json, this computer's own; 0xYaCo on X): off by default; on, `KeepSkillsCurrent` (a `gateway.WhileServing` loop) runs `AutoUpdateTick` two minutes after the gateway starts and hourly after, which, every `checkEvery`, runs `CheckSkills` and `UpdateSomeSkills` on the skills it found at `update`, so everything above holds: one changed here stays in `Unupdated` and keeps its Update button, one removed there is only marked, a replaced version that was changed goes to the backups. Updated names and a new error are logged. Set by the Skills tab's Update by themselves switch under the list, shown while a skill comes from GitHub or git (`skillAutoPart`, `POST /api/library/skills/auto-update` with `on`), and `magpie library skill auto-update on\|off` (`TestAutoUpdateSkills`, `skill-auto-update.test.cjs`). | [`skill_changed.go`](../../internal/library/skill_changed.go), [`skillcheck.go`](../../internal/library/skillcheck.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skills.go`](../../internal/library/skills.go) | -| Hooks | A `Hook` (#1790) is a command, an event, an optional matcher, a timeout and the agents ticked for it. Its optional `Description` (#2011) says what it is for in any language, since its name is letters, digits, - and _: one line of at most `maxHookDescription` (200) characters, shown under the name; only library.json keeps it, and no agent is given it. Its event is portable (`HookEvents`: turn-end, after-tool, before-tool, prompt, session-start, each under the agent's own name) or an agent's own (`"codex:PermissionRequest"`), which only that agent is given. A portable tool event can be narrowed to shell or edit tools, each agent's own tool names for them. A session-start hook can be narrowed to some starts (#5604, NEKO-CwC: re-inject a file after compaction alone), one or more of `HookStarts` (startup, resume, clear, compact, fork, Claude Code's words) joined by `|`; `startMatcher` writes each agent's own matcher for them. Claude Code and Codex take the starts as written (Codex reads a `|` list as exact names). Gemini CLI has startup, resume and clear only and compares its matcher whole, so it takes one of them. Grok has `new` (startup and /clear) and `load` (resume), so it takes exactly one of those groups. Cursor's sessionStart takes no matcher. Starts an agent doesn't have are dropped, and one that has all that are left is given the hook whole. An agent that can't run it at exactly the starts picked is refused with why, as for any other per-agent limit: never widened to every start, which would run it at the starts the user narrowed away (a fork per subagent), nor written with a matcher it never matches. The written matcher is in `Applied.Hooks`, so an agent's own edit of the entry is still theirs. `HookAgentView.Starts` lists the matchers each agent takes, and the editor's At which starts app menu greys the chips of those that can't. A bundle carrying a narrowed hook to a magpie before this writes it whole. `syncHooks` writes each into the agent's own file and shape (`hookSpecOf`): Claude Code `/settings.json`, Codex `hooks.json` beside its config.toml, Gemini CLI `~/.gemini/settings.json` (timeout in ms), Cursor `~/.cursor/hooks.json` (flat entries, `version: 1`), and Grok Build `~/.grok/config.toml` and Grok App `agent-home/config.toml` as `[[hooks.]]` array tables with a `[[hooks..hooks]]` child. Grok Build and Grok App run the one CLI, so a `grok:` own event goes to both (`sameHookFamily`). Every other agent, and an agent in WSL, is refused with why, and the page greys its chip with that reason. The page also says when an agent has every hook turned off (`hooksOff`: Claude Code's `disableAllHooks`, Gemini's `hooksConfig.enabled`, Codex's `[features] hooks`). | [`hooks.go`](../../internal/library/hooks.go) | +| Hooks | A `Hook` (#1790) is a command, an event, an optional matcher, a timeout and the agents ticked for it. Its optional `Description` (#2011) says what it is for in any language, since its name is letters, digits, - and _: one line of at most `maxHookDescription` (200) characters, shown under the name; only library.json keeps it, and no agent is given it. Its event is portable (`HookEvents`: turn-end, after-tool, before-tool, prompt, session-start, each under the agent's own name) or an agent's own (`"codex:PermissionRequest"`), which only that agent is given. A portable tool event can be narrowed to shell or edit tools, each agent's own tool names for them. A session-start hook can be narrowed to some starts (#5604, NEKO-CwC: re-inject a file after compaction alone), one or more of `HookStarts` (startup, resume, clear, compact, fork, Claude Code's words) joined by `|`; `startMatcher` writes each agent's own matcher for them. Claude Code and Codex take the starts as written (Codex reads a `|` list as exact names). Gemini CLI has startup, resume and clear only and compares its matcher whole, so it takes one of them. Grok has `new` (startup and /clear) and `load` (resume), so it takes exactly one of those groups. Cursor's sessionStart takes no matcher. Starts an agent doesn't have are dropped, and one that has all that are left is given the hook whole. An agent that can't run it at exactly the starts picked is refused with why, as for any other per-agent limit: never widened to every start, which would run it at the starts the user narrowed away (a fork per subagent), nor written with a matcher it never matches. The written matcher is in `Applied.Hooks`, so an agent's own edit of the entry is still theirs. `HookAgentView.Starts` lists the matchers each agent takes, and the editor's At which starts app menu greys the chips of those that can't. A bundle carrying a narrowed hook to a magpie before this writes it whole. `syncHooks` writes each into the agent's own file and shape (`hookSpecOf`): Claude Code `/settings.json`, Codex `hooks.json` beside its config.toml, Gemini CLI `~/.gemini/settings.json` (timeout in ms), Cursor `~/.cursor/hooks.json` (flat entries, `version: 1`), DeepSeek Harness `$DSH_HOME/magpie-hooks.json` (Claude Code's shape under dsh's tool names, `bash|pwsh` and `write|edit|str_replace_editor`; the events its bridge runs, `dshHookEvents`; `dsh_hooks.go`: every profile gets the plugin `@deepseek-ai/dsh-hooks-claude-code` and `@deepseek-ai/dsh-hook-protocol` installed at dsh's own version with `dsh plugin --profile add` (a failed install is said, retried after ten minutes, and writes no row: dsh leaves out a row whose plugin isn't there, and a deny hook would then allow what it was set to stop), then one marked `magpie-hooks` insert row naming the file; a row of the user's for that plugin is left alone and said; the last hook taken out takes the rows out; session-start can't be narrowed there; real dsh 0.2.2-rc.5 denied a `bash` call through it, @eiyuuzaki2333 on X), and Grok Build `~/.grok/config.toml` and Grok App `agent-home/config.toml` as `[[hooks.]]` array tables with a `[[hooks..hooks]]` child. Grok Build and Grok App run the one CLI, so a `grok:` own event goes to both (`sameHookFamily`). Every other agent, and an agent in WSL, is refused with why, and the page greys its chip with that reason. The page also says when an agent has every hook turned off (`hooksOff`: Claude Code's `disableAllHooks`, Gemini's `hooksConfig.enabled`, Codex's `[features] hooks`). | [`hooks.go`](../../internal/library/hooks.go) | | 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) | @@ -83,6 +83,7 @@ Pi's extensions and packages. - OpenCode: `"_": false` in the top-level `tools` of opencode.json (opencode.ai/docs/mcp-servers, "Manage"), the names spelt as `name()` in `packages/core/src/tool/mcp.ts` does; `migrateTools` in `packages/core/src/config/normalize.ts` makes each a deny rule (sst/opencode 0d61729b). - Every other agent (Cursor, Copilot and Goose, whose lists are allow-lists only, Zed, Kimi, Pi, Grok, Devin, Antigravity, Alma, dsh, omp, ZCode, Command Code, Cline, WorkBuddy, CodeBuddy, Droid, Claude Desktop, MiMo Code, DevEco Code, a plugin's agent) gets the server whole. `AgentView.ToolsOff` is false for it, and the open list of tools names those given the server as unable to turn off single tools. A project's file and Copy config… carry no tools turned off either. magpie records what it added (`Applied.ToolsOff` per server for a list in an entry, `Applied.ToolRules` for Claude Code's rules and OpenCode's keys) and takes back only that (`offList`): a name, rule or key the user had already is theirs and stays when the tool is turned on again, and an OpenCode key the user set to `true` is never written over. A list or `permissions.deny` that isn't a list of names is a problem, never taken as empty, and the file is left as it is. The key, and Claude Code's `permissions` or OpenCode's `tools`, goes when magpie's were the last in it. The editor's save sends no tools, so `SaveServer` keeps those turned off. +- DeepSeek Harness takes instructions, MCP servers, skills and hooks from the Library. Subagents, slash commands, rules, env, project MCP files and Claude Code plugins stay off for it: dsh reads no folder or file of its own for any of them (its subagents are presets inside a profile's patch list, which magpie doesn't write; `projectMCPFiles` has no dsh file since its servers are profile patch rows, one set for all projects), so there is nothing magpie could write that dsh reads for a project or an agent. Checked against dsh 0.2.2-rc.5 (@eiyuuzaki2333 on X). - With the MCP router on (`MCPHub`), an agent that takes a Streamable HTTP server is given magpie's one `magpie` entry in place of the Library servers ticked for it, and each server's own entry again when it is turned off. One that can't, or has an entry called magpie of its own, or whose library has a server called magpie, keeps each server's own entry, and the page says why ([MCP router](mcp-router.md)). - A gateway key held to some MCP servers and tools (wakaka on Discord) reaches through the router only those: the gateway holds each hub tool to the Library server behind it (see [gateway routing](gateway-routing.md)). The key editor lists every Library server, the hub's or not, with the tools it last listed (`KeyMCPServers`, from the router's cards); a server that never listed shows no tools and can still be given whole. - magpie's own MCP servers (`magpie-image`, `magpie-browser`, `magpie-web-search`, `magpie-vision`, and any `mcp …` run by a program named magpie) run this computer's magpie (#1439). `InstallServer` gives it magpie by full path (`update.Program`: the AppImage, not its mount; Homebrew's opt link, not the Cellar), and that path is right only on this computer. When the library is read, and after every change, `heal` points such a server whose program isn't on this computer (another system's path, a magpie moved out of Downloads, a bare `magpie`) at this magpie, so the agents and `CheckServers` get it; a magpie program that is here (another build) and a server run by any other program stay as they are. A carried library (`Collect`, for a backup or a WebDAV or S3 sync) names it as plain `magpie`, so two computers carry the same bundle and a sync doesn't write one's path over the other's; `Put` then reads it as that computer's magpie. [`self_here.go`](../../internal/library/self_here.go) diff --git a/internal/library/dsh_hooks.go b/internal/library/dsh_hooks.go new file mode 100644 index 000000000..4ac7c4aa4 --- /dev/null +++ b/internal/library/dsh_hooks.go @@ -0,0 +1,244 @@ +package library + +// DeepSeek Harness has no hooks file of its own. Its plugin +// @deepseek-ai/dsh-hooks-claude-code runs a Claude Code hooks.json on dsh's +// interception points (session start, prompt, tool before and after, turn +// end, subagents), and a profile loads it through a row its patch list +// inserts: +// +// - insert: # magpie +// - id: magpie-hooks +// name: "@deepseek-ai/dsh-hooks-claude-code" +// config: +// configPath: "/magpie-hooks.json" +// +// magpie keeps its hooks in $DSH_HOME/magpie-hooks.json, in Claude Code's +// shape (hooks.go writes it as it does Claude's), and gives every profile +// that row. The plugin is a profile's own npm package, at the dsh's own +// version (its peer dependencies are pinned to it), so magpie installs it +// with `dsh plugin --profile add` first and writes the row only once +// it is there: a row for a plugin that isn't installed is one dsh warns of +// and leaves out, and a deny hook would then allow what it was set to stop. + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/proc" +) + +const ( + dshHooksPkg = "@deepseek-ai/dsh-hooks-claude-code" + dshHooksProtocol = "@deepseek-ai/dsh-hook-protocol" + dshHooksRowID = "magpie-hooks" +) + +// dshHookEvents are the events the bridge runs (CLAUDE_EVENTS in +// dsh-hooks-claude-code 0.2.2-rc.5); a hook under another Claude Code event +// is one it never runs. +var dshHookEvents = []string{"SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop", "SubagentStart", "SubagentStop"} + +// dshHookSpec is how dsh keeps hooks, or why it can't. Its tools are bash, +// pwsh, read, write, edit and str_replace_editor (dsh-agent's tool names), +// and the bridge reads a matcher of names joined by | as exact names. +func dshHookSpec(t *Target) (*hookSpec, string) { + if t.MCP == nil || filepath.Base(t.MCP.Path) != "cordis.patch.yml" { + return nil, "DeepSeek Harness has no profile yet: start dsh once, and hooks can be given to it" + } + return &hookSpec{ + path: filepath.Join(t.Agent.Dir, "magpie-hooks.json"), + events: map[string]string{"turn-end": "Stop", "after-tool": "PostToolUse", "before-tool": "PreToolUse", + "prompt": "UserPromptSubmit", "session-start": "SessionStart"}, + native: dshHookEvents, + tools: map[string]string{"shell": "bash|pwsh", "edit": "write|edit|str_replace_editor"}, + }, "" +} + +// dshInstalled is the version of an npm package a profile has, "" when it +// has none. +func dshInstalled(profile, pkg string) string { + b, err := os.ReadFile(filepath.Join(profile, "node_modules", filepath.FromSlash(pkg), "package.json")) + if err != nil { + return "" + } + var v struct { + Version string `json:"version"` + } + json.Unmarshal(b, &v) + return v.Version +} + +// dshTool is the version and command of the dsh a; a var for tests. +var dshTool = func(a *agent.Agent) (string, string) { return a.InstalledVersion(), a.BinPath() } + +// dshPluginRun runs `dsh ` in cwd, a profile's folder, under +// DSH_HOME dir; a var for tests. +var dshPluginRun = func(bin, dir, cwd string, args ...string) (string, error) { + const timeout = 3 * time.Minute + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cmd := proc.CommandContext(ctx, bin, args...) + cmd.Stdin = nil + cmd.Dir = cwd + cmd.Env = append(os.Environ(), "DSH_HOME="+dir, "PATH="+filepath.Dir(bin)+string(os.PathListSeparator)+os.Getenv("PATH")) + out, err := cmd.CombinedOutput() + text := strings.TrimSpace(string(out)) + if err != nil { + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return text, fmt.Errorf("dsh %s didn't finish in %s", strings.Join(args, " "), timeout) + } + if text == "" { + text = err.Error() + } + return text, fmt.Errorf("dsh %s: %s", strings.Join(args, " "), lastLines(text, 4)) + } + return text, nil +} + +// dshInstallFailed remembers an install that failed, per profile and +// version, so a sync that runs every few seconds doesn't wait on the +// network again each time. +var ( + dshInstallMu sync.Mutex + dshInstallFailed = map[string]time.Time{} +) + +const dshInstallRetry = 10 * time.Minute + +// dshHooksPlugin brings every profile to what the hooks need: with any +// hook (want), the plugin installed at dsh's version and the row in its +// patch list; with none, the row taken out. A profile that fails is said +// in the error, the others done. +func dshHooksPlugin(t *Target, file string, want bool, keep func(path string) error) error { + dir := t.Agent.Dir + var ver, bin string + if want { + ver, bin = dshTool(t.Agent) + if ver == "" || bin == "" { + return errors.New("DeepSeek Harness's version or command isn't known, so its hooks plugin can't be installed") + } + } + var errs []error + for _, patch := range agent.DshPatchFiles(dir) { + if filepath.Base(patch) != "cordis.patch.yml" { + continue + } + profile := filepath.Dir(patch) + name := filepath.Base(profile) + if !want { + if err := dshDelHooksRow(patch, keep); err != nil { + errs = append(errs, fmt.Errorf("profile %s: %w", name, err)) + } + continue + } + if dshInstalled(profile, dshHooksPkg) != ver || dshInstalled(profile, dshHooksProtocol) != ver { + key := profile + "\x00" + ver + dshInstallMu.Lock() + at, failed := dshInstallFailed[key] + dshInstallMu.Unlock() + if failed && time.Since(at) < dshInstallRetry { + errs = append(errs, fmt.Errorf("profile %s: the hooks plugin didn't install a moment ago; trying again later", name)) + // a plugin the user removed leaves no row of magpie's behind + if err := dshDelHooksRow(patch, keep); err != nil { + errs = append(errs, fmt.Errorf("profile %s: %w", name, err)) + } + continue + } + _, err := dshPluginRun(bin, dir, profile, "plugin", "--profile", name, "add", dshHooksProtocol+"@"+ver, dshHooksPkg+"@"+ver) + if err == nil && (dshInstalled(profile, dshHooksPkg) != ver || dshInstalled(profile, dshHooksProtocol) != ver) { + err = fmt.Errorf("%s isn't installed after its install", dshHooksPkg) + } + dshInstallMu.Lock() + if err != nil { + dshInstallFailed[key] = time.Now() + } else { + delete(dshInstallFailed, key) + } + dshInstallMu.Unlock() + if err != nil { + errs = append(errs, fmt.Errorf("profile %s: %w", name, err)) + // the plugin isn't there, so no row of magpie's points at it + if derr := dshDelHooksRow(patch, keep); derr != nil { + errs = append(errs, fmt.Errorf("profile %s: %w", name, derr)) + } + continue + } + } + if err := dshPutHooksRow(patch, file, keep); err != nil { + errs = append(errs, fmt.Errorf("profile %s: %w", name, err)) + } + } + return errors.Join(errs...) +} + +// dshHooksItem is the index of magpie's hooks insert in the list, -1 when +// there is none, and whether a row of the user's loads the same plugin. +func (p *dshPatches) dshHooksItem() (mine int, theirs bool) { + mine = -1 + for i, it := range p.items { + switch { + case strings.TrimSpace(it[0]) == dshMark && len(it) > 1 && strings.TrimSpace(it[1]) == "- id: "+dshHooksRowID: + mine = i + case strings.Contains(strings.Join(it, "\n"), dshHooksPkg): + theirs = true + } + } + return mine, theirs +} + +func dshPutHooksRow(patch, file string, keep func(string) error) error { + p, err := dshRead(patch) + if err != nil { + return err + } + i, theirs := p.dshHooksItem() + if theirs { + return errors.New("its patch list loads the hooks plugin already, with a config of its own; magpie leaves that one") + } + lines := []string{ + dshMark, + " - id: " + dshHooksRowID, + " name: " + dshScalar(dshHooksPkg), + " config:", + " configPath: " + dshScalar(file), + } + if i >= 0 { + if strings.Join(p.items[i], "\n") == strings.Join(lines, "\n") { + return nil + } + p.items[i] = lines + } else { + p.items = append(p.items, lines) + } + if err := keep(patch); err != nil { + return err + } + return p.write(patch) +} + +func dshDelHooksRow(patch string, keep func(string) error) error { + p, err := dshRead(patch) + if err != nil { + if os.IsNotExist(err) { + return nil + } + return err + } + i, _ := p.dshHooksItem() + if i < 0 { + return nil + } + p.items = append(p.items[:i], p.items[i+1:]...) + if err := keep(patch); err != nil { + return err + } + return p.write(patch) +} diff --git a/internal/library/dsh_hooks_test.go b/internal/library/dsh_hooks_test.go new file mode 100644 index 000000000..4a5b74360 --- /dev/null +++ b/internal/library/dsh_hooks_test.go @@ -0,0 +1,204 @@ +package library + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/agent" +) + +// fakeDshPlugins stands in for `dsh plugin add`: it lays the two packages +// down in the profile as pnpm would, at version ver, and counts the runs. +func fakeDshPlugins(t *testing.T, ver string, fail error) *[][]string { + t.Helper() + var runs [][]string + was, wasRun := dshTool, dshPluginRun + dshTool = func(*agent.Agent) (string, string) { return ver, "dsh" } + dshPluginRun = func(bin, dir, cwd string, args ...string) (string, error) { + runs = append(runs, append([]string{cwd}, args...)) + if fail != nil { + return "", fail + } + for _, pkg := range []string{dshHooksPkg, dshHooksProtocol} { + b, _ := json.Marshal(map[string]string{"name": pkg, "version": ver}) + write(t, filepath.Join(cwd, "node_modules", filepath.FromSlash(pkg), "package.json"), string(b)) + } + return "", nil + } + t.Cleanup(func() { + dshTool, dshPluginRun = was, wasRun + dshInstallMu.Lock() + clear(dshInstallFailed) + dshInstallMu.Unlock() + }) + return &runs +} + +// A hook given to DeepSeek Harness lands in magpie's Claude-shaped hooks +// file under dsh's own tool names, the plugin that runs it is installed in +// every profile at dsh's version, and each profile's patch list gets one +// marked row naming the file. The user's rows stay; taking the last hook +// away takes the row away and leaves the user's rows. +func TestHooksDsh(t *testing.T) { + h := sandbox(t) + web := filepath.Join(h, ".dsh/profiles/web/cordis.patch.yml") + other := filepath.Join(h, ".dsh/profiles/other/cordis.patch.yml") + write(t, web, "- id: some-plugin\n disabled: false\n") + write(t, other, "[]\n") + runs := fakeDshPlugins(t, "0.2.2-rc.5", nil) + + ok(t)(SaveHook("", Hook{Name: "guard", Event: "before-tool", Matcher: "shell", Command: "check.sh", Timeout: 5, Agents: []string{"dsh"}})) + ok(t)(SaveHook("", Hook{Name: "fmt", Event: "after-tool", Matcher: "edit", Command: "prettier --write .", Agents: []string{"dsh"}})) + + file := filepath.Join(h, ".dsh", "magpie-hooks.json") + var doc struct { + Hooks map[string][]struct { + Matcher string `json:"matcher"` + Hooks []struct { + Type, Command string + Timeout int + } + } + } + if err := json.Unmarshal([]byte(read(t, file)), &doc); err != nil { + t.Fatalf("%v\n%s", err, read(t, file)) + } + if g := doc.Hooks["PreToolUse"]; len(g) != 1 || g[0].Matcher != "bash|pwsh" || g[0].Hooks[0].Command != "check.sh" || g[0].Hooks[0].Timeout != 5 { + t.Errorf("PreToolUse: %+v", doc.Hooks["PreToolUse"]) + } + if g := doc.Hooks["PostToolUse"]; len(g) != 1 || g[0].Matcher != "write|edit|str_replace_editor" { + t.Errorf("PostToolUse: %+v", doc.Hooks["PostToolUse"]) + } + if len(*runs) != 2 { + t.Errorf("the plugin was installed %d times, want once a profile: %v", len(*runs), *runs) + } + row := "- insert: # magpie\n - id: magpie-hooks\n name: \"@deepseek-ai/dsh-hooks-claude-code\"\n config:\n configPath: " + dshScalar(file) + "\n" + for _, p := range []string{web, other} { + if s := read(t, p); strings.Count(s, "id: magpie-hooks\n") != 1 || !strings.Contains(s, row) { + t.Errorf("%s:\n%s", p, s) + } + } + if s := read(t, web); !strings.HasPrefix(s, "- id: some-plugin\n disabled: false\n") { + t.Errorf("the user's row moved:\n%s", s) + } + + // a second hook installs nothing again and writes one row still + ok(t)(SaveHook("", Hook{Name: "bark", Event: "turn-end", Command: "notify", Agents: []string{"dsh"}})) + if len(*runs) != 2 || strings.Count(read(t, web), "id: magpie-hooks\n") != 1 { + t.Errorf("runs %d\n%s", len(*runs), read(t, web)) + } + + ok(t)(RemoveHooks([]string{"guard", "fmt", "bark"})) + if s := read(t, web); strings.Contains(s, "id: magpie-hooks\n") || !strings.Contains(s, "some-plugin") { + t.Errorf("after removing every hook:\n%s", s) + } + if s := read(t, other); strings.Contains(s, "id: magpie-hooks\n") { + t.Errorf("after removing every hook:\n%s", s) + } +} + +// With the plugin not installed, no row is written: dsh would warn of the +// row, leave it out, and run no hook, so a deny hook would allow everything. +// The failure is said, and the next sync installs it. +func TestHooksDshNeedsItsPlugin(t *testing.T) { + h := sandbox(t) + web := filepath.Join(h, ".dsh/profiles/web/cordis.patch.yml") + write(t, web, "[]\n") + fakeDshPlugins(t, "0.2.2-rc.5", errors.New("pnpm: no network")) + + res, err := SaveHook("", Hook{Name: "guard", Event: "before-tool", Command: "check.sh", Agents: []string{"dsh"}}) + if err != nil { + t.Fatal(err) + } + if len(res.Problems) == 0 || !strings.Contains(res.Problems[0].Error, "no network") { + t.Fatalf("problems: %+v", res.Problems) + } + if s := read(t, web); strings.Contains(s, "id: magpie-hooks\n") { + t.Fatalf("a row for a plugin that isn't there:\n%s", s) + } +} + +// A plugin of another version than dsh's is installed again: its peer +// dependencies are pinned to dsh's exact version. +func TestHooksDshReinstallsOnVersion(t *testing.T) { + h := sandbox(t) + web := filepath.Join(h, ".dsh/profiles/web/cordis.patch.yml") + write(t, web, "[]\n") + for _, pkg := range []string{dshHooksPkg, dshHooksProtocol} { + write(t, filepath.Join(h, ".dsh/profiles/web/node_modules", filepath.FromSlash(pkg), "package.json"), `{"version":"0.2.1-rc.2"}`) + } + runs := fakeDshPlugins(t, "0.2.2-rc.5", nil) + ok(t)(SaveHook("", Hook{Name: "guard", Event: "before-tool", Command: "check.sh", Agents: []string{"dsh"}})) + if len(*runs) != 1 || !strings.Contains(strings.Join((*runs)[0], " "), dshHooksPkg+"@0.2.2-rc.5") { + t.Fatalf("runs: %v", *runs) + } +} + +// A user's own row for the plugin is left as it is. +func TestHooksDshLeavesUsersRow(t *testing.T) { + h := sandbox(t) + web := filepath.Join(h, ".dsh/profiles/web/cordis.patch.yml") + mine := "- insert:\n - id: my-hooks\n name: \"@deepseek-ai/dsh-hooks-claude-code\"\n config:\n configPath: /x/hooks.json\n" + write(t, web, mine) + fakeDshPlugins(t, "0.2.2-rc.5", nil) + res, err := SaveHook("", Hook{Name: "guard", Event: "before-tool", Command: "check.sh", Agents: []string{"dsh"}}) + if err != nil { + t.Fatal(err) + } + if len(res.Problems) == 0 { + t.Fatal("no problem said") + } + if s := read(t, web); s != mine { + t.Fatalf("the user's row was changed:\n%s", s) + } +} + +// dsh has the Claude Code events its bridge runs and no more: a hook under +// another event is refused, not written where nothing reads it. +func TestHooksDshEvents(t *testing.T) { + h := sandbox(t) + write(t, filepath.Join(h, ".dsh/profiles/web/cordis.patch.yml"), "[]\n") + fakeDshPlugins(t, "0.2.2-rc.5", nil) + res, err := SaveHook("", Hook{Name: "n", Event: "dsh:Notification", Command: "x", Agents: []string{"dsh"}}) + if err != nil { + t.Fatal(err) + } + if len(res.Problems) == 0 || !strings.Contains(res.Problems[0].Error, "no event called Notification") { + t.Fatalf("problems: %+v", res.Problems) + } + if read(t, filepath.Join(h, ".dsh", "magpie-hooks.json")) != "" && strings.Contains(read(t, filepath.Join(h, ".dsh", "magpie-hooks.json")), "Notification") { + t.Fatal("written") + } +} + +// A user who removes the plugin from a profile finds no row of magpie's left +// pointing at it: the next sync can't install it again, and takes the row out. +func TestHooksDshRemovedPluginLeavesNoRow(t *testing.T) { + h := sandbox(t) + web := filepath.Join(h, ".dsh/profiles/web/cordis.patch.yml") + write(t, web, "- id: some-plugin\n disabled: false\n") + fakeDshPlugins(t, "0.2.2-rc.5", nil) + ok(t)(SaveHook("", Hook{Name: "guard", Event: "before-tool", Command: "check.sh", Agents: []string{"dsh"}})) + if !strings.Contains(read(t, web), "id: magpie-hooks\n") { + t.Fatal("no row to start from") + } + // the user removes the plugin, and the network is down + if err := os.RemoveAll(filepath.Join(h, ".dsh/profiles/web/node_modules")); err != nil { + t.Fatal(err) + } + fakeDshPlugins(t, "0.2.2-rc.5", errors.New("pnpm: no network")) + res, err := SaveHook("guard", Hook{Name: "guard", Event: "before-tool", Command: "check2.sh", Agents: []string{"dsh"}}) + if err != nil { + t.Fatal(err) + } + if len(res.Problems) == 0 { + t.Fatal("no problem said") + } + if s := read(t, web); strings.Contains(s, "id: magpie-hooks\n") || !strings.Contains(s, "some-plugin") { + t.Fatalf("a row left pointing at a plugin that isn't there:\n%s", s) + } +} diff --git a/internal/library/hooks.go b/internal/library/hooks.go index 631670cb0..f8acad522 100644 --- a/internal/library/hooks.go +++ b/internal/library/hooks.go @@ -30,6 +30,7 @@ import ( // Codex /hooks.json the same shape // Gemini CLI ~/.gemini/settings.json the same shape, timeout in ms // Cursor ~/.cursor/hooks.json hooks.: [{command, timeout, matcher}], version 1 +// DeepSeek Harness $DSH_HOME/magpie-hooks.json the Claude Code shape, run by the plugin dsh-hooks-claude-code (dsh_hooks.go) // // A portable event ("turn-end") is the same moment in each agent, under // each one's own name; an agent's own event ("codex:PermissionRequest") @@ -204,7 +205,7 @@ type hookSpec struct { } // hookAgents are the agents magpie can give hooks to. -var hookAgents = []string{"claude", "codex", "cursor", "gemini", "grok", "grok-app"} +var hookAgents = []string{"claude", "codex", "cursor", "dsh", "gemini", "grok", "grok-app"} // grokHookEvents are the events the Grok CLI fires (docs/user-guide/10-hooks.md), // shared by Grok Build and the Grok App that runs it. Only the ones magpie @@ -328,6 +329,8 @@ func hookSpecFor(t *Target) (*hookSpec, string) { // Grok App runs the same CLI, on a custom route reading // agent-home/config.toml, the same [[hooks.]] shape return grokHookSpec(t.MCP.Path), "" + case "dsh": + return dshHookSpec(t) } return nil, fmt.Sprintf("%s has no hooks magpie can write", t.Agent.Name) } @@ -704,6 +707,12 @@ func (l *Library) syncHooks(t *Target, b *backups, res *Result) { } if ok { a.Hooks = recs + if id == "dsh" { + // dsh runs a hooks file through a plugin its profiles load + if err := dshHooksPlugin(t, sp.path, len(recs) > 0, func(path string) error { return b.keep(id, path) }); err != nil { + res.fail(id, "hooks", err) + } + } } }