library, gui: Hooks are a fifth Library category, kept once and written into each ticked agent's own hooks file (#1790, AllenReder)

What: the Library page has a Hooks tab beside Instructions, MCP, Skills
and RTK. A hook is a command, an event, an optional tool filter, a
timeout and the agents ticked for it. magpie writes it into each agent in
that agent's own file and shape:
  Claude Code  <claude dir>/settings.json   hooks.<Event>[{matcher, hooks[]}]
  Codex        <codex home>/hooks.json       same shape
  Gemini CLI   ~/.gemini/settings.json       same shape, timeout in ms
  Cursor       ~/.cursor/hooks.json          flat entries, version 1
Portable events (turn end, after a tool, before a tool, prompt sent,
session start) map to each agent's own name; "shell"/"edit" map to each
agent's own tool names. An agent's own event (codex:PermissionRequest,
cursor:afterFileEdit, ...) is offered too and given to that agent only.
Rows have agent chips (All first), Select + bar, and Remove all, like
skills and servers. An agent that can't take a hook has its chip greyed
with the reason: every agent but those four ("has no hooks magpie can
write"), an agent in WSL (not yet), and another agent for a native event.
The page also says when an agent has all hooks turned off
(disableAllHooks, hooksConfig.enabled=false, [features] hooks=false).

Why these choices (product call delegated to us): the four agents are
the ones with a documented, file-based command-hook API whose events line
up; others (OpenCode's JS plugins, dsh, ...) have no comparable file, so
they're named as unavailable rather than half-supported. Removal is
exact: Applied.Hooks records each entry as written (canonical JSON), and
only an entry still exactly as written is taken out; one the user edited
is theirs, and their own hooks beside it are never touched. A hooks file
that doesn't parse is a problem, never treated as empty or written over.
Codex keeps trust per hook in config.toml keyed by group position, so
taking a group out re-keys the user's trust for the groups after it
(codexRekey) instead of silently untrusting them. Carried bundles
(backup/WebDAV/S3) don't carry hooks in this first version.

Run:
- go test ./internal/library ./internal/gui (sandbox HOME): pass. New
  hooks_test.go: each agent's shape; the user's edited entry stays and is
  no longer recorded; an unparseable file is left alone and reported;
  Codex trust moves with its groups; native events/unavailable agents;
  hooks-off reported.
- library-hooks.test.cjs: 12/12 in chromium and webkit, at 440px, in en,
  zh, zh-TW, ja, de; against the old library.js it fails (timeouts on the
  missing tab). All 52 new strings translated in the 4 languages.
- library-loading.test.cjs expects the Hooks tab in its tab lists
  (it failed on this change before; 6/6 now).
- Every library-*/skill-* GUI test in chromium and webkit: all pass but
  WebKit timeouts in library-mcp-tool-switch/library-mcp-tools, which fail
  the same on origin/main b0a904bd9 under load (#1609, commented).
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean. Full go test ./... at the pre-rebase
  head c1c1a730f: 49 packages ok. After rebasing onto 86b2f4d05:
  library, gui and gateway's Anthropic/Zed tests ok.

Not tried: real Claude Code / Codex / Gemini / Cursor runs firing the
written hooks; the shapes were checked against each agent's source and
docs, not executed.
This commit is contained in:
yetone
2026-10-12 22:44:28 +08:00
parent 50eeaae6ce
commit e3a497d7a2
11 changed files with 1851 additions and 37 deletions
+10 -6
View File
@@ -1,8 +1,9 @@
# Library: instructions, MCP servers, skills and RTK
# Library: instructions, MCP servers, skills, hooks and RTK
The library keeps what every agent should know in one place: the
instructions each agent reads before a conversation, the MCP servers it can
call, and the skills it can load. magpie writes these into each agent's own
call, the skills it can load, and the hooks it runs at points of its turn.
magpie writes these into each agent's own
files in that agent's format, and takes back only what it wrote. Everything
else in those files stays as it was. Package `internal/library` also gives
agents RTK, a CLI that cuts shell output down before the model reads it.
@@ -22,14 +23,15 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
| Skills a repository 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}`). | [`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. `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. | [`skill_from.go`](../../internal/library/skill_from.go), [`library.js`](../../internal/gui/assets/library.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. `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`) 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. | [`skill_changed.go`](../../internal/library/skill_changed.go), [`skillcheck.go`](../../internal/library/skillcheck.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 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. `syncHooks` writes each into the agent's own file and shape (`hookSpecOf`): Claude Code `<claude dir>/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`). 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) |
| Backups | Before a change first writes an agent file, `backups` copies it to `BackupDir`, one folder per change. The last `keepBackups` (30) changes are kept. | [`backup.go`](../../internal/library/backup.go) |
| RTK | `SetRTK` runs rtk's own installer (`rtk init -g …`) for an agent being switched on. For one being switched off, it removes exactly what the installer wrote, using magpie's own code, which works even with rtk gone. `ReadRTK` reads each agent's files to say which have the hook. `rtkSpec.blocked` stops the installer where it would break an agent. A detected agent RTK has no hook for at all is still listed, from `rtkNoHook`, with the reason and a switch that can't be turned on (dsh: its hooks can allow or deny a command but not rewrite it, and `rtk init` has no `--agent dsh`). | [`rtk.go`](../../internal/library/rtk.go) |
## Runtime path
1. **Edit.** The Library page or `magpie library` calls an exported function such as `SaveServer`, `ServerAgents`, `InstallSkills`, `SkillAgents` or `SetSkillHow`. The skills and servers pages each have Select, Turn all on, Turn all off and Remove all. Select's bar calls `SomeSkillsAgents` or `SomeServersAgents` (`/api/library/{skills,servers}/agents-some`), Turn all on or off calls `EverySkillAgents` or `EveryServerAgents` for the agents shown, and Remove all calls `RemoveSkills` or `RemoveServers`. Each of these is one change that takes every item out as a single removal would (#1027). A row's agent chips start with All (`allChip` in `library.js`), which gives the item to every agent shown that can take it, or takes it from them all; the pickers that choose the agents before an item is added (installing skills from a repository or the market, adding, bringing in or installing a server) have the same All: most start with every agent lit, and one agent alone took a click on each of the others (#1531).
1. **Edit.** The Library page or `magpie library` calls an exported function such as `SaveServer`, `ServerAgents`, `InstallSkills`, `SkillAgents` or `SetSkillHow`. The skills and servers pages each have Select, Turn all on, Turn all off and Remove all. Select's bar calls `SomeSkillsAgents` or `SomeServersAgents` (`/api/library/{skills,servers}/agents-some`), Turn all on or off calls `EverySkillAgents` or `EveryServerAgents` for the agents shown, and Remove all calls `RemoveSkills` or `RemoveServers`. The hooks page has Select and Remove all too (`SomeHooksAgents`, `RemoveHooks`). Each of these is one change that takes every item out as a single removal would (#1027). A row's agent chips start with All (`allChip` in `library.js`), which gives the item to every agent shown that can take it, or takes it from them all; the pickers that choose the agents before an item is added (installing skills from a repository or the market, adding, bringing in or installing a server) have the same All: most start with every agent lit, and one agent alone took a click on each of the others (#1531).
2. **Change.** `change` edits `library.json` under the lock and calls `sync`.
3. **Write.** For each target, `syncInstructions` and `syncMCP` write magpie's part in the agent's format and record it in `Applied`. Skills are linked or copied into the agent's skills folder. A copy edited since it was made is taken into the library first.
3. **Write.** For each target, `syncInstructions`, `syncMCP` and `syncHooks` write magpie's part in the agent's format and record it in `Applied`. Skills are linked or copied into the agent's skills folder. A copy edited since it was made is taken into the library first.
4. **Result.** The `Result` lists the agents changed, a `Problem` for each thing that couldn't be given, and the backup folder.
## Constraints and failure behavior
@@ -56,6 +58,8 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
- Zed's servers go in `context_servers` of the settings.json magpie sets its model in (`agent.zed`: `~/.config/zed` on macOS, `$XDG_CONFIG_HOME/zed` on Linux, `%APPDATA%\Zed` on Windows, or `$MAGPIE_ZED_CONFIG_DIR`), as `command`/`args`/`env` or `url`/`headers` (`ContextServerSettingsContent`, zed-industries/zed 2c99f547). The file is JSONC: it is edited in place, so the user's comments, other settings and own servers stay, and `enabled`, `remote`, `timeout` and `oauth` in magpie's entry are the user's. Zed speaks streamable HTTP only (its `http.rs` only POSTs), so no SSE. An entry Zed's extensions configure (`settings` and no command or url) is never written over: a server by that name is refused for Zed (`mcpFile.foreign`), and asks for another name. Zed reloads the file as it changes.
- An agent with no place for an item is refused by `Takes`, never recorded as given it. The refusal lists the agents here that take that item (`takenBy`), and says where it goes instead (`noPlace`): OpenChamber reads OpenCode's global AGENTS.md, skills folder and opencode.json (its server's `shared.js`), so it gets them from OpenCode; Claude Desktop's chat keeps its instructions in its own settings, with the Claude account, and its Code tab reads Claude Code's. A plugin's agent is refused an item its `agent.library` names no place for, and the refusal names the key its plugin would set.
- Removing RTK never uses `rtk init --uninstall`. That command deletes Gemini's `GEMINI.md` whole and removes Claude Code, OpenCode and Cursor together.
- A hook is recorded entry by entry, as written (`Applied.Hooks`, compared as canonical JSON). magpie takes out only an entry still exactly as it wrote it; one the user edited is theirs from then on, and the user's own hooks beside it stay. A hooks file that doesn't parse is a problem and is never written. Codex keeps each hook's trust in config.toml as `[hooks.state."<path>:<event>:<group>:<handler>"]`, keyed by position, so when magpie takes a group out `codexRekey` moves the user's trust for the groups after it to their new place.
- A carried library (backup, WebDAV, S3, profile bundles) doesn't carry hooks yet.
- CC Switch's own skills folder is only ever read.
- Reading the page never waits on reading skills through (#541). `Read` compares an agent's own skill with the same name in another agent (`sameTree`) and hashes each library skill given as a copy (`hashFiles`, for `behind`). Both are kept against a stamp of the folders (each file's and link's path, type, size and mtime, `stamper` in [`treememo.go`](../../internal/library/treememo.go)), taken by the same walk that compares or hashes them, before a file is opened; a later read walks the folder without opening a file, and while the stamps match reuses the answer. Only an answer from a whole read of folders untouched for `settleFor` (3s) is kept: a folder that couldn't be walked or read, or was written a moment ago, is read again next time, never taken as unchanged. A rewrite that keeps a file's size and mtime isn't seen. `Glance` (`GET /api/library?glance=1`) is the page without those two, marked `partial`; the page draws it first, then the whole read, which runs `behind` and `foundSkills` after the library's lock is let go, so a change doesn't wait on them either.
- Skills installed together (`InstallSkills`, `InstallMarketSkill`, `AddNewSkills`, through `installFrom` and `installChange`) install each on its own. One the library lists from the same source, or a folder in the library's own skills folder holding exactly that skill's files (left by an install that stopped before the library was saved), is had already and goes in `Result.Had`. Its files are never written, so the user's edits stay. Another skill by that name, listed or only in the folder, or a folder that can't be read, is left as it is and goes in `Result.Skipped` with why. The rest are installed and named in `Result.Installed`. Only when nothing was installed or had does the change fail, with the first reason.
@@ -63,9 +67,9 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
## Verification
```sh
go test -tags nogui ./internal/library -run 'TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestServer|TestImportServer|TestCheck|TestInstructions|TestInstructionSets|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'
go test -tags nogui ./internal/library -run 'TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestServer|TestImportServer|TestCheck|TestInstructions|TestInstructionSets|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'
go test -tags nogui ./internal/library
node --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs
node --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs internal/gui/tests/library-hooks.test.cjs
```
The package's `TestMain` runs in a home of its own (`testenv`), never the
+208
View File
@@ -3920,6 +3920,58 @@ const I18N = {
"{n} servers are on for all {m} agents": "已为全部 {m} 个 Agent 启用 {n} 个服务器",
"{n} servers are off for all {m} agents": "已从全部 {m} 个 Agent 中关闭 {n} 个服务器",
"Take all {n} servers out of the library": "从资源库中删除全部 {n} 个服务器",
"+ Add a hook": "+ 添加 Hook",
"+ Add hook": "+ 添加 Hook",
"{agent} can run none of these hooks": "{agent} 运行不了其中任何一个 Hook",
"{agent} has {n} of these hooks — click to give it the rest": "{agent} 已有其中 {n} 个 Hook — 点击启用其余的",
"{agent} has all of these hooks — click to take them away": "{agent} 已有这些 Hook — 点击全部停用",
"{agent} has hooks turned off in its settings: it runs none of them until they're turned on there.": "{agent} 在自己的设置里关闭了 Hook:在那里重新打开之前,它一个也不会运行。",
"{agent} has no hooks magpie can write": "magpie 还不能给 {agent} 写入 Hook",
"{agent}'s own event": "{agent} 自己的事件",
"{event} is {agent}'s own event: only it can run this hook": "{event} 是 {agent} 自己的事件:只有它能运行这个 Hook",
"{n} hooks are off for {agents}": "已为 {agents} 停用 {n} 个 Hook",
"{n} hooks are on for {agents}": "已为 {agents} 启用 {n} 个 Hook",
"{n} hooks removed": "已删除 {n} 个 Hook",
"A hook is a command an agent runs at a point of its turn — a notification when it ends, a formatter after it edits a file. Add it once and magpie writes it into each agent you pick, in the shape that agent reads.": "Hook 是 Agent 在一轮对话的某个时刻运行的命令——结束时发个通知,改完文件后跑一下格式化。只需添加一次,magpie 会按每个 Agent 自己读取的格式,写进你选中的 Agent。",
"Add one, and pick the agents that run it.": "添加一个,再选要运行它的 Agent。",
"After a tool runs": "工具运行之后",
"Any tool": "任何工具",
"Before a tool runs": "工具运行之前",
"Codex runs a new or changed hook only once you trust it: review it in Codex's /hooks.": "新加或改过的 Hook,Codex 要等你信任后才会运行:请在 Codex 的 /hooks 里审阅。",
"Cursor runs Claude Code's hooks too: a hook given to both runs twice in Cursor.": "Cursor 也会运行 Claude Code 的 Hook:同时给两者启用的 Hook,在 Cursor 里会运行两次。",
"e.g. notify": "例如 notify",
"Each agent's own names for them": "按每个 Agent 自己对它们的叫法",
"Every agent has all of these hooks — click to take them from every one": "每个 Agent 都已有这些 Hook — 点击从全部 Agent 停用",
"every tool": "全部工具",
"File edits": "编辑文件",
"For which tools": "对哪些工具",
"Give {agent} all of these hooks": "给 {agent} 启用这些 Hook",
"Give all of these hooks to every agent": "为每个 Agent 启用这些 Hook",
"Hook {name}": "Hook {name}",
"Hooks your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file.": "Agent 自己的、不在资源库中的 Hook 保持不变,你在 Agent 文件里改过的也一样。",
"Hooks": "Hooks",
"Letters, digits, - and _": "字母、数字、- 和 _",
"magpie can't give hooks to {agents} yet: their chips are greyed, and say why.": "magpie 还不能给 {agents} 写入 Hook:它们的图标是灰的,悬停可看原因。",
"magpie gives hooks only to agents on this computer, not yet to {agent} in WSL": "magpie 目前只给这台电脑上的 Agent 写入 Hook,还不支持 WSL 里的 {agent}",
"Matcher": "匹配规则",
"New hook": "新 Hook",
"No hooks in the library yet": "资源库里还没有 Hook",
"Pick hooks to turn them on or off together": "选中 Hook,一起开启或关闭",
"Pick some hooks and turn them on or off together": "选中多个 Hook,一起开启或关闭",
"Remove all {n} hooks?": "删除全部 {n} 个 Hook?",
"Run by the agent's shell, in the session's folder; the agent passes what happened as JSON on its input": "由 Agent 的 shell 在会话的文件夹里运行;Agent 会把发生了什么以 JSON 传到它的标准输入",
"Shell commands": "Shell 命令",
"Stop picking hooks": "结束选择 Hook",
"Take all {n} hooks out of the library": "从资源库中删除全部 {n} 个 Hook",
"The agent's own matcher, as its hooks file has it; empty for all": "Agent 自己的匹配规则,照它的 Hook 文件里的写法;留空表示全部",
"the agent's own": "沿用 Agent 自己的",
"Timeout (seconds)": "超时(秒)",
"When a prompt is sent": "发送提示词时",
"When a session starts": "会话开始时",
"When a turn ends": "一轮结束时",
"When it runs": "何时运行",
"Find an event": "查找事件",
"every agent, in its own name for it": "所有 Agent,各用自己的事件名",
"Remove all {n} servers?": "删除全部 {n} 个服务器?",
"The servers magpie placed in {n} projects are taken away too.": "magpie 放进 {n} 个项目的这些服务器也会一并移除。",
"magpie's sign-in to {n} of them is forgotten too.": "magpie 对其中 {n} 个服务器的登录也会一并清除。",
@@ -8280,6 +8332,58 @@ const I18N = {
"{n} servers are on for all {m} agents": "已為全部 {m} 個 Agent 啟用 {n} 個伺服器",
"{n} servers are off for all {m} agents": "已從全部 {m} 個 Agent 中關閉 {n} 個伺服器",
"Take all {n} servers out of the library": "從資源庫中刪除全部 {n} 個伺服器",
"+ Add a hook": "+ 新增 Hook",
"+ Add hook": "+ 新增 Hook",
"{agent} can run none of these hooks": "{agent} 執行不了其中任何一個 Hook",
"{agent} has {n} of these hooks — click to give it the rest": "{agent} 已有其中 {n} 個 Hook — 點擊啟用其餘的",
"{agent} has all of these hooks — click to take them away": "{agent} 已有這些 Hook — 點擊全部停用",
"{agent} has hooks turned off in its settings: it runs none of them until they're turned on there.": "{agent} 在自己的設定裡關閉了 Hook:在那裡重新開啟之前,它一個也不會執行。",
"{agent} has no hooks magpie can write": "magpie 還不能給 {agent} 寫入 Hook",
"{agent}'s own event": "{agent} 自己的事件",
"{event} is {agent}'s own event: only it can run this hook": "{event} 是 {agent} 自己的事件:只有它能執行這個 Hook",
"{n} hooks are off for {agents}": "已為 {agents} 停用 {n} 個 Hook",
"{n} hooks are on for {agents}": "已為 {agents} 啟用 {n} 個 Hook",
"{n} hooks removed": "已刪除 {n} 個 Hook",
"A hook is a command an agent runs at a point of its turn — a notification when it ends, a formatter after it edits a file. Add it once and magpie writes it into each agent you pick, in the shape that agent reads.": "Hook 是 Agent 在一輪對話的某個時刻執行的命令——結束時發個通知,改完檔案後跑一下格式化。只需新增一次,magpie 會按每個 Agent 自己讀取的格式,寫進你選中的 Agent。",
"Add one, and pick the agents that run it.": "新增一個,再選要執行它的 Agent。",
"After a tool runs": "工具執行之後",
"Any tool": "任何工具",
"Before a tool runs": "工具執行之前",
"Codex runs a new or changed hook only once you trust it: review it in Codex's /hooks.": "新增或改過的 Hook,Codex 要等你信任後才會執行:請在 Codex 的 /hooks 裡審閱。",
"Cursor runs Claude Code's hooks too: a hook given to both runs twice in Cursor.": "Cursor 也會執行 Claude Code 的 Hook:同時給兩者啟用的 Hook,在 Cursor 裡會執行兩次。",
"e.g. notify": "例如 notify",
"Each agent's own names for them": "按每個 Agent 自己對它們的叫法",
"Every agent has all of these hooks — click to take them from every one": "每個 Agent 都已有這些 Hook — 點擊從全部 Agent 停用",
"every tool": "全部工具",
"File edits": "編輯檔案",
"For which tools": "對哪些工具",
"Give {agent} all of these hooks": "給 {agent} 啟用這些 Hook",
"Give all of these hooks to every agent": "為每個 Agent 啟用這些 Hook",
"Hook {name}": "Hook {name}",
"Hooks your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file.": "Agent 自己的、不在資源庫中的 Hook 保持不變,你在 Agent 檔案裡改過的也一樣。",
"Hooks": "Hooks",
"Letters, digits, - and _": "字母、數字、- 和 _",
"magpie can't give hooks to {agents} yet: their chips are greyed, and say why.": "magpie 還不能給 {agents} 寫入 Hook:它們的圖示是灰的,懸停可看原因。",
"magpie gives hooks only to agents on this computer, not yet to {agent} in WSL": "magpie 目前只給這台電腦上的 Agent 寫入 Hook,還不支援 WSL 裡的 {agent}",
"Matcher": "匹配規則",
"New hook": "新 Hook",
"No hooks in the library yet": "資源庫裡還沒有 Hook",
"Pick hooks to turn them on or off together": "選中 Hook,一起開啟或關閉",
"Pick some hooks and turn them on or off together": "選中多個 Hook,一起開啟或關閉",
"Remove all {n} hooks?": "刪除全部 {n} 個 Hook?",
"Run by the agent's shell, in the session's folder; the agent passes what happened as JSON on its input": "由 Agent 的 shell 在工作階段的資料夾裡執行;Agent 會把發生了什麼以 JSON 傳到它的標準輸入",
"Shell commands": "Shell 命令",
"Stop picking hooks": "結束選擇 Hook",
"Take all {n} hooks out of the library": "從資源庫中刪除全部 {n} 個 Hook",
"The agent's own matcher, as its hooks file has it; empty for all": "Agent 自己的匹配規則,照它的 Hook 檔案裡的寫法;留空表示全部",
"the agent's own": "沿用 Agent 自己的",
"Timeout (seconds)": "逾時(秒)",
"When a prompt is sent": "送出提示詞時",
"When a session starts": "工作階段開始時",
"When a turn ends": "一輪結束時",
"When it runs": "何時執行",
"Find an event": "搜尋事件",
"every agent, in its own name for it": "所有 Agent,各用自己的事件名",
"Remove all {n} servers?": "刪除全部 {n} 個伺服器?",
"The servers magpie placed in {n} projects are taken away too.": "magpie 放進 {n} 個專案的這些伺服器也會一併移除。",
"magpie's sign-in to {n} of them is forgotten too.": "magpie 對其中 {n} 個伺服器的登入也會一併清除。",
@@ -12661,6 +12765,58 @@ const I18N = {
"{n} servers are on for all {m} agents": "{m} 個のエージェントすべてで {n} 個のサーバーをオンにしました",
"{n} servers are off for all {m} agents": "{m} 個のエージェントすべてで {n} 個のサーバーをオフにしました",
"Take all {n} servers out of the library": "{n} 個のサーバーをすべてライブラリから削除",
"+ Add a hook": "+ フックを追加",
"+ Add hook": "+ フックを追加",
"{agent} can run none of these hooks": "{agent} はこれらのフックをどれも実行できません",
"{agent} has {n} of these hooks — click to give it the rest": "{agent} にはこのうち {n} 個のフックがあります — クリックで残りも渡す",
"{agent} has all of these hooks — click to take them away": "{agent} にはこれらのフックがすべてあります — クリックで外す",
"{agent} has hooks turned off in its settings: it runs none of them until they're turned on there.": "{agent} は設定でフックをオフにしています。そこでオンにするまで、どのフックも実行しません。",
"{agent} has no hooks magpie can write": "magpie は {agent} にフックを書き込めません",
"{agent}'s own event": "{agent} 独自のイベント",
"{event} is {agent}'s own event: only it can run this hook": "{event} は {agent} 独自のイベントです。このフックを実行できるのは {agent} だけです",
"{n} hooks are off for {agents}": "{agents} で {n} 個のフックをオフにしました",
"{n} hooks are on for {agents}": "{agents} で {n} 個のフックをオンにしました",
"{n} hooks removed": "{n} 個のフックを削除しました",
"A hook is a command an agent runs at a point of its turn — a notification when it ends, a formatter after it edits a file. Add it once and magpie writes it into each agent you pick, in the shape that agent reads.": "フックは、エージェントがターンの特定の時点で実行するコマンドです。終わったときに通知する、ファイルを編集した後にフォーマッターを走らせる、など。一度追加すれば、magpie が選んだ各エージェントに、そのエージェントが読む形式で書き込みます。",
"Add one, and pick the agents that run it.": "追加して、実行するエージェントを選んでください。",
"After a tool runs": "ツールの実行後",
"Any tool": "すべてのツール",
"Before a tool runs": "ツールの実行前",
"Codex runs a new or changed hook only once you trust it: review it in Codex's /hooks.": "Codex は新しいフックや変更されたフックを、信頼するまで実行しません。Codex の /hooks で確認してください。",
"Cursor runs Claude Code's hooks too: a hook given to both runs twice in Cursor.": "Cursor は Claude Code のフックも実行します。両方に渡したフックは Cursor で 2 回実行されます。",
"e.g. notify": "例: notify",
"Each agent's own names for them": "各エージェントでの呼び名で書き込みます",
"Every agent has all of these hooks — click to take them from every one": "すべてのエージェントにこれらのフックがあります — クリックですべてから外す",
"every tool": "すべてのツール",
"File edits": "ファイル編集",
"For which tools": "対象のツール",
"Give {agent} all of these hooks": "{agent} にこれらのフックをすべて渡す",
"Give all of these hooks to every agent": "すべてのエージェントにこれらのフックをすべて渡す",
"Hook {name}": "フック {name}",
"Hooks your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file.": "エージェント自身の、ライブラリにないフックはそのまま残ります。エージェントのファイルで変更したものも同じです。",
"Hooks": "フック",
"Letters, digits, - and _": "英字・数字・- と _",
"magpie can't give hooks to {agents} yet: their chips are greyed, and say why.": "magpie はまだ {agents} にフックを渡せません。チップはグレーになっていて、理由を表示します。",
"magpie gives hooks only to agents on this computer, not yet to {agent} in WSL": "magpie がフックを渡せるのはこのコンピューター上のエージェントだけで、WSL の {agent} にはまだ渡せません",
"Matcher": "マッチャー",
"New hook": "新しいフック",
"No hooks in the library yet": "ライブラリにはまだフックがありません",
"Pick hooks to turn them on or off together": "フックを選んでまとめてオン・オフする",
"Pick some hooks and turn them on or off together": "複数のフックを選んでまとめてオン・オフする",
"Remove all {n} hooks?": "{n} 個のフックをすべて削除しますか?",
"Run by the agent's shell, in the session's folder; the agent passes what happened as JSON on its input": "エージェントのシェルがセッションのフォルダーで実行します。何が起きたかは JSON で標準入力に渡されます",
"Shell commands": "シェルコマンド",
"Stop picking hooks": "フックの選択を終える",
"Take all {n} hooks out of the library": "{n} 個のフックをすべてライブラリから削除",
"The agent's own matcher, as its hooks file has it; empty for all": "エージェント独自のマッチャー。フックファイルでの書き方のまま。空ならすべて",
"the agent's own": "エージェントの既定",
"Timeout (seconds)": "タイムアウト(秒)",
"When a prompt is sent": "プロンプトの送信時",
"When a session starts": "セッションの開始時",
"When a turn ends": "ターンの終了時",
"When it runs": "実行するタイミング",
"Find an event": "イベントを検索",
"every agent, in its own name for it": "すべてのエージェント、それぞれの呼び名で",
"Remove all {n} servers?": "{n} 個のサーバーをすべて削除しますか?",
"The servers magpie placed in {n} projects are taken away too.": "magpie が {n} 個のプロジェクトに置いたこれらのサーバーも外されます。",
"magpie's sign-in to {n} of them is forgotten too.": "そのうち {n} 個のサーバーへの magpie のサインインも消去されます。",
@@ -17044,6 +17200,58 @@ const I18N = {
"{n} servers are on for all {m} agents": "{n} Server sind für alle {m} Agenten an",
"{n} servers are off for all {m} agents": "{n} Server sind für alle {m} Agenten aus",
"Take all {n} servers out of the library": "Alle {n} Server aus der Bibliothek entfernen",
"+ Add a hook": "+ Hook hinzufügen",
"+ Add hook": "+ Hook hinzufügen",
"{agent} can run none of these hooks": "{agent} kann keinen dieser Hooks ausführen",
"{agent} has {n} of these hooks — click to give it the rest": "{agent} hat {n} dieser Hooks — klicken, um ihm den Rest zu geben",
"{agent} has all of these hooks — click to take them away": "{agent} hat alle diese Hooks — klicken, um sie zu entfernen",
"{agent} has hooks turned off in its settings: it runs none of them until they're turned on there.": "{agent} hat Hooks in seinen Einstellungen ausgeschaltet: Es führt keinen davon aus, bis sie dort wieder eingeschaltet sind.",
"{agent} has no hooks magpie can write": "magpie kann für {agent} keine Hooks schreiben",
"{agent}'s own event": "Eigenes Ereignis von {agent}",
"{event} is {agent}'s own event: only it can run this hook": "{event} ist ein eigenes Ereignis von {agent}: Nur es kann diesen Hook ausführen",
"{n} hooks are off for {agents}": "{n} Hooks sind für {agents} aus",
"{n} hooks are on for {agents}": "{n} Hooks sind für {agents} an",
"{n} hooks removed": "{n} Hooks entfernt",
"A hook is a command an agent runs at a point of its turn — a notification when it ends, a formatter after it edits a file. Add it once and magpie writes it into each agent you pick, in the shape that agent reads.": "Ein Hook ist ein Befehl, den ein Agent an einem Punkt seines Durchgangs ausführt — eine Benachrichtigung, wenn er endet, ein Formatierer, nachdem er eine Datei bearbeitet hat. Einmal hinzugefügt, schreibt magpie ihn in jeden gewählten Agenten, in der Form, die dieser liest.",
"Add one, and pick the agents that run it.": "Fügen Sie einen hinzu und wählen Sie die Agenten, die ihn ausführen.",
"After a tool runs": "Nachdem ein Tool läuft",
"Any tool": "Jedes Tool",
"Before a tool runs": "Bevor ein Tool läuft",
"Codex runs a new or changed hook only once you trust it: review it in Codex's /hooks.": "Codex führt einen neuen oder geänderten Hook erst aus, wenn Sie ihm vertrauen: Prüfen Sie ihn in Codex unter /hooks.",
"Cursor runs Claude Code's hooks too: a hook given to both runs twice in Cursor.": "Cursor führt auch die Hooks von Claude Code aus: Ein Hook, der beiden gegeben wird, läuft in Cursor zweimal.",
"e.g. notify": "z. B. notify",
"Each agent's own names for them": "Unter den eigenen Namen jedes Agenten",
"Every agent has all of these hooks — click to take them from every one": "Jeder Agent hat alle diese Hooks — klicken, um sie allen zu entfernen",
"every tool": "jedes Tool",
"File edits": "Dateiänderungen",
"For which tools": "Für welche Tools",
"Give {agent} all of these hooks": "{agent} alle diese Hooks geben",
"Give all of these hooks to every agent": "Allen Agenten alle diese Hooks geben",
"Hook {name}": "Hook {name}",
"Hooks your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file.": "Hooks Ihrer Agenten, die nicht in der Bibliothek sind, bleiben unverändert, ebenso einer, den Sie in der Datei eines Agenten geändert haben.",
"Hooks": "Hooks",
"Letters, digits, - and _": "Buchstaben, Ziffern, - und _",
"magpie can't give hooks to {agents} yet: their chips are greyed, and say why.": "magpie kann {agents} noch keine Hooks geben: Ihre Chips sind ausgegraut und sagen, warum.",
"magpie gives hooks only to agents on this computer, not yet to {agent} in WSL": "magpie gibt Hooks nur Agenten auf diesem Computer, noch nicht {agent} in WSL",
"Matcher": "Matcher",
"New hook": "Neuer Hook",
"No hooks in the library yet": "Noch keine Hooks in der Bibliothek",
"Pick hooks to turn them on or off together": "Hooks auswählen, um sie gemeinsam ein- oder auszuschalten",
"Pick some hooks and turn them on or off together": "Mehrere Hooks auswählen und gemeinsam ein- oder ausschalten",
"Remove all {n} hooks?": "Alle {n} Hooks entfernen?",
"Run by the agent's shell, in the session's folder; the agent passes what happened as JSON on its input": "Von der Shell des Agenten im Ordner der Sitzung ausgeführt; der Agent übergibt, was geschah, als JSON auf der Eingabe",
"Shell commands": "Shell-Befehle",
"Stop picking hooks": "Auswahl der Hooks beenden",
"Take all {n} hooks out of the library": "Alle {n} Hooks aus der Bibliothek entfernen",
"The agent's own matcher, as its hooks file has it; empty for all": "Der eigene Matcher des Agenten, wie in seiner Hook-Datei; leer für alle",
"the agent's own": "der des Agenten",
"Timeout (seconds)": "Zeitlimit (Sekunden)",
"When a prompt is sent": "Wenn ein Prompt gesendet wird",
"When a session starts": "Wenn eine Sitzung beginnt",
"When a turn ends": "Wenn ein Durchgang endet",
"When it runs": "Wann er läuft",
"Find an event": "Ereignis suchen",
"every agent, in its own name for it": "jeder Agent, unter seinem eigenen Namen dafür",
"Remove all {n} servers?": "Alle {n} Server entfernen?",
"The servers magpie placed in {n} projects are taken away too.": "Die Server, die magpie in {n} Projekte gelegt hat, werden ebenfalls entfernt.",
"magpie's sign-in to {n} of them is forgotten too.": "magpies Anmeldung bei {n} von ihnen wird ebenfalls vergessen.",
+5
View File
@@ -580,3 +580,8 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col
.lib-row.click:hover > .lib-agents:hover .lib-ag:not(:focus) { outline-color: transparent; }
.lib-grouphead > .lib-agents .lib-ag:not(:focus) { outline-color: var(--card-2); }
}
/* Hooks (#1790): the event and the tools it is for are app menus, as wide
as the dialog lets them be */
.lib-hookedit .lib-menu { max-width: 100%; height: 28px; color: var(--fg); }
.lib-hookedit .lib-hooktimeout { max-width: 140px; }
+237 -24
View File
@@ -40,6 +40,7 @@
key: "M10 2.8a3.2 3.2 0 1 0 0 6.4 3.2 3.2 0 0 0 0-6.4z M7.8 8.2 3 13 M4.5 11.5 6 13",
person: "M8 3a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5z M3.5 13.5c.6-2.4 2.3-3.6 4.5-3.6s3.9 1.2 4.5 3.6",
back: "m9.5 4.5-3 3.5 3 3.5",
hook: "M10.5 2.5v6.5a3 3 0 0 1-6 0V7.5 M3 9l1.5-1.5L6 9",
};
const tilde = (p) => (lib?.home && p?.startsWith(lib.home) ? "~" + p.slice(lib.home.length) : p || "");
@@ -372,7 +373,7 @@
// What All did, said of the item: on for how many of the agents it went
// to, and which of them couldn't be given it, and why.
function reportAll(v, me) {
const what = (me.list === "servers" ? "mcp:" : "skill:") + me.name;
const what = ({ servers: "mcp:", hooks: "hook:" }[me.list] || "skill:") + me.name;
const shown = [...me.box.children].filter((x) => x.dataset.agent && !cannot(x)).map((x) => x.dataset.agent);
const n = shown.filter((id) => me.want.includes(id)).length;
const bad = (v.result?.problems || []).filter((p) => p.what === what && shown.includes(p.agent));
@@ -578,6 +579,7 @@
if (kind === "instructions") return t("Instructions");
if (kind === "mcp") return name ? t("MCP server {name}", { name }) : t("MCP servers");
if (kind === "skill") return t("Skill {name}", { name });
if (kind === "hook") return t("Hook {name}", { name });
if (kind === "project") return name ? t("Skill {name}", { name }) : t("The project");
return what;
}
@@ -658,6 +660,7 @@
["instructions", t("Instructions")],
["mcp", t("MCP servers") + n("mcp")],
["skills", t("Skills") + n("skills")],
["hooks", t("Hooks") + n("hooks")],
["rtk", "RTK"],
], tab, (id) => {
tab = id;
@@ -706,7 +709,7 @@
const caret = focus ? [document.activeElement.selectionStart, document.activeElement.selectionEnd] : null;
page.replaceChildren();
fits = [];
const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length });
const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length });
page.append(head);
head.classList.toggle("stuck", top > 0);
if (!lib.agents.length) {
@@ -722,6 +725,7 @@
if (tab === "instructions") renderInstructions(body);
else if (tab === "mcp") renderServers(body);
else if (tab === "rtk") renderRTK(body);
else if (tab === "hooks") renderHooks(body);
else renderSkills(body);
page.append(body);
for (const n of body.querySelectorAll(".row-head .note")) n.title = n.textContent;
@@ -1976,6 +1980,206 @@
openLib(ed);
}
// ---------- hooks ----------
// A hook (#1790, AllenReder) is a command an agent runs at a point of
// its turn: a phone notification when it ends, a formatter after it
// edits a file. It is kept once and written into each agent picked, in
// that agent's own file and shape (hooks.go). An event is one every
// agent has, under its own name, or one agent's own, for it alone.
const HOOK_EVENTS = () => [
["turn-end", t("When a turn ends")],
["after-tool", t("After a tool runs")],
["before-tool", t("Before a tool runs")],
["prompt", t("When a prompt is sent")],
["session-start", t("When a session starts")],
];
const HOOK_TOOLS = () => [["", t("Any tool")], ["shell", t("Shell commands")], ["edit", t("File edits")]];
const toolEvent = (ev) => ev === "after-tool" || ev === "before-tool";
const hookAgentOf = (id) => (lib.hookAgents || []).find((x) => x.id === id);
// the agents the tab shows a chip for: every one shown, those magpie
// can't give a hook greyed, saying why
const hookAgents = () => shownAgents().filter((a) => hookAgentOf(a.id));
// why a can't be given h, or ""
const hookBlocked = (h) => (a) => {
const ha = hookAgentOf(a.id);
if (!ha || ha.no) return ha?.wsl ? t("magpie gives hooks only to agents on this computer, not yet to {agent} in WSL", { agent: a.name }) : t("{agent} has no hooks magpie can write", { agent: a.name });
const own = h.event?.includes(":") && h.event.split(":")[0];
if (own && own !== a.id) return t("{event} is {agent}'s own event: only it can run this hook", { event: h.event.slice(own.length + 1), agent: nameOf(own) });
return "";
};
function hookEventLabel(h) {
const i = h.event.indexOf(":");
if (i > 0) return nameOf(h.event.slice(0, i)) + " · " + h.event.slice(i + 1);
return HOOK_EVENTS().find(([v]) => v === h.event)?.[1] || h.event;
}
function hookLine(h) {
let s = hookEventLabel(h);
if (h.matcher) s += " · " + (h.event.includes(":") ? h.matcher : HOOK_TOOLS().find(([v]) => v === h.matcher)?.[1] || h.matcher);
return s;
}
function renderHooks(body) {
body.append(intro(t("A hook is a command an agent runs at a point of its turn — a notification when it ends, a formatter after it edits a file. Add it once and magpie writes it into each agent you pick, in the shape that agent reads.")));
const all = hookAgents();
const hooks = lib.hooks || [];
pickingFor("hooks", hooks);
if (!hooks.length) {
body.append(empty(t("No hooks in the library yet"), t("Add one, and pick the agents that run it."), button(t("+ Add a hook"), "action", () => editHook(null))));
} else {
if (hooks.length > 1) {
const rh = el("div", "row-head lib-hookhead");
rh.append(el("span", "label", t("In the library")), el("span", "grow"));
if (all.length) rh.append(pickButton("hooks"));
rh.append(removeEveryButton("hooks"));
body.append(rh);
}
const list = el("div", "list lib-list");
list.append(...[...hooks].sort((a, b) => a.name.localeCompare(b.name)).map((h) => hookRow(h, all)));
body.append(list);
if (picking) body.append(pickBar(all));
const after = el("div", "after-list");
after.append(button(t("+ Add hook"), "", () => editHook(null)));
body.append(after);
}
const given = (id) => hooks.some((h) => h.agents?.includes(id));
for (const a of all) {
const ha = hookAgentOf(a.id);
if (ha.off && given(a.id)) body.append(el("p", "lib-aside lib-hooks-off", t("{agent} has hooks turned off in its settings: it runs none of them until they're turned on there.", { agent: a.name })));
}
// Codex runs a hook only once it is trusted there, again after it
// changes (codex-rs/hooks: trusted_hash)
if (given("codex")) body.append(el("p", "lib-aside lib-hooks-codex", t("Codex runs a new or changed hook only once you trust it: review it in Codex's /hooks.")));
// Cursor runs Claude Code's hooks as well as its own
if (hooks.some((h) => h.agents?.includes("cursor") && h.agents?.includes("claude"))) body.append(el("p", "lib-aside lib-hooks-twice", t("Cursor runs Claude Code's hooks too: a hook given to both runs twice in Cursor.")));
// the agents greyed: Claude Code, Codex, Gemini CLI and Cursor are the
// ones whose hooks files magpie knows
const skip = all.filter((a) => hookAgentOf(a.id).no);
if (skip.length) body.append(el("p", "lib-aside lib-hooks-no", t("magpie can't give hooks to {agents} yet: their chips are greyed, and say why.", { agents: skip.map((a) => a.name).join(", ") })));
}
function hookRow(h, all) {
const row = el("div", "row lib-row click lib-hook");
const who = el("div", "who");
who.append(el("div", "name mono", h.name), el("div", "sub lib-hookev", hookLine(h)));
const cmd = el("div", "sub mono lib-hookcmd", h.command);
cmd.title = h.command;
who.append(cmd);
row.append(glyph(GLYPH.hook), who,
agentChips(all, h.agents, chipsChange("hooks/agents", h.name, "hooks", (x) => hookRow(x, all)), { problems: h.problems, blocked: hookBlocked(h), all: true }));
if (picking) return pickRow(row, h.name);
row.onclick = () => editHook(h);
row.title = t("Edit {name}", { name: h.name });
return row;
}
function editHook(h) {
const all = hookAgents();
const d = h ? { name: h.name, event: h.event, matcher: h.matcher || "", command: h.command, timeout: h.timeout || 0, agents: [...(h.agents || [])] }
: { name: "", event: "turn-end", matcher: "", command: "", timeout: 0, agents: [] };
if (!h) d.agents = all.filter((a) => !hookBlocked(d)(a)).map((a) => a.id);
const ed = el("div", "editor lib-editor lib-hookedit");
const head = el("div", "ehead");
head.append(glyph(GLYPH.hook), el("b", "", h ? h.name : t("New hook")));
ed.append(head);
const err = el("div", "editor-error");
const name = field2(d.name, t("e.g. notify"), (v) => { d.name = v.trim(); });
ed.append(...field(t("Name"), name, t("Letters, digits, - and _")));
// the event and the tools it is narrowed to: menus, never a <select>
const evBtn = el("button", "sess-pick lib-menu lib-hookevent");
evBtn.type = "button";
evBtn.setAttribute("aria-haspopup", "menu");
evBtn.setAttribute("aria-expanded", "false");
evBtn.onclick = (e) => {
e.stopPropagation();
const opts = HOOK_EVENTS().map(([v, n]) => ({ v, name: n, literalName: true, note: "every agent, in its own name for it", always: true }));
// an agent's own events, for it alone
for (const a of all) {
const ha = hookAgentOf(a.id);
if (ha.no) continue;
for (const ev of ha.events || []) opts.push({ v: a.id + ":" + ev, name: a.name + " · " + ev, literalName: true, note: t("{agent}'s own event", { agent: a.name }) });
}
openProtoMenu(evBtn, opts, d.event, (v) => {
d.event = v;
if (v.includes(":")) d.agents = [v.split(":")[0]];
else if (!toolEvent(v)) d.matcher = "";
if (v.includes(":") || !HOOK_TOOLS().some(([m]) => m === d.matcher)) d.matcher = "";
draw();
}, "When it runs", "", "left", false, "Find an event");
};
ed.append(...field(t("When it runs"), evBtn));
const slot = el("div", "lib-slot");
ed.append(slot);
const cmd = field2(d.command, "curl -s https://api.day.app/KEY/done", (v) => { d.command = v; });
cmd.classList.add("mono");
ed.append(...field(t("Command"), cmd, t("Run by the agent's shell, in the session's folder; the agent passes what happened as JSON on its input")));
const to = field2(d.timeout ? String(d.timeout) : "", t("the agent's own"), (v) => { d.timeout = Math.max(0, parseInt(v, 10) || 0); });
to.inputMode = "numeric";
to.classList.add("lib-hooktimeout");
ed.append(...field(t("Timeout (seconds)"), to));
const agentsBox = el("div");
ed.append(...field(t("Agents"), agentsBox));
ed.append(err);
function drawAgents() {
agentsBox.replaceChildren(agentChips(all, d.agents, (next) => { d.agents = next; drawAgents(); }, { names: true, blocked: hookBlocked(d), all: true }));
}
function draw() {
evBtn.replaceChildren(el("span", "", hookEventLabel(d)), svg(CHEV, 11, 1.6));
slot.replaceChildren();
if (d.event.includes(":")) {
const m = field2(d.matcher, t("every tool"), (v) => { d.matcher = v.trim(); });
m.classList.add("mono", "lib-hookmatcher");
slot.append(...field(t("Matcher"), m, t("The agent's own matcher, as its hooks file has it; empty for all")));
} else if (toolEvent(d.event)) {
const mb = el("button", "sess-pick lib-menu lib-hooktool");
mb.type = "button";
mb.setAttribute("aria-haspopup", "menu");
mb.setAttribute("aria-expanded", "false");
mb.append(el("span", "", HOOK_TOOLS().find(([v]) => v === d.matcher)?.[1] || ""), svg(CHEV, 11, 1.6));
mb.onclick = (e) => {
e.stopPropagation();
openProtoMenu(mb, HOOK_TOOLS().map(([v, n]) => ({ v, name: n, literalName: true, note: "" })), d.matcher, (v) => { d.matcher = v; draw(); }, "For which tools");
};
slot.append(...field(t("For which tools"), mb, t("Each agent's own names for them")));
}
drawAgents();
}
draw();
const bar = el("div", "bar");
if (h) bar.append(button(t("Remove from the library"), "danger", async () => {
if (!await confirmRemoval(h.name, "It will be removed from the library and the agents it was given to.")) return;
if (await change("hooks/remove", { name: h.name }, t("{name} is out of the library and the agents it was given to", { name: h.name }))) closeLibModal(true);
}));
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal));
const save = async () => {
err.textContent = "";
try {
const hook = { name: d.name, event: d.event, matcher: d.matcher, command: d.command, timeout: d.timeout, agents: d.agents.filter((id) => !hookBlocked(d)(agentOf(id) || { id })) };
take(await api("library/hooks/save", { old: h ? h.name : "", hook }));
report(lib.result, h ? t("{name} saved", { name: d.name }) : "");
closeLibModal(true);
render();
} catch (e) { err.textContent = e.message; }
};
bar.append(button(h ? t("Save") : t("Add"), "primary", save));
ed.append(bar);
const original = JSON.stringify(d);
modal = { save, dirty: () => JSON.stringify(d) !== original };
openLib(ed);
if (!h) requestAnimationFrame(() => name.focus());
}
function confirmRemoveEveryHook() {
const hooks = (lib.hooks || []).slice(), names = hooks.map((x) => x.name);
confirmRemoveEvery("hooks", names, t("Remove all {n} hooks?", { n: names.length }), [
takenFrom(hooks),
t("Hooks your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file."),
]);
}
// ---------- skills ----------
function renderSkills(body) {
@@ -2482,9 +2686,9 @@
// reach: one given every server it can reach of them has them all, and
// one that can reach none of them can't be given them.
function groupChips(skills, all, repo, kind = "skills") {
const servers = kind === "servers";
const servers = kind === "servers", hooks = kind === "hooks";
const n = skills.length, names = skills.map((s) => s.name);
const can = (s, a) => !servers || reaches(s)(a);
const can = (s, a) => (servers ? !!reaches(s)(a) : hooks ? !hookBlocked(s)(a) : true);
const reach = (a) => skills.filter((s) => can(s, a)).length;
const count = (a) => skills.filter((s) => can(s, a) && s.agents?.includes(a.id)).length;
const full = all.filter((a) => reach(a) && count(a) === reach(a)).map((a) => a.id);
@@ -2502,18 +2706,24 @@
? (on.length ? t("{repo}'s skills are on for {agents}", { repo, agents: who(on) }) : t("{repo}'s skills are off for {agents}", { repo, agents: who(off) }))
: n === 1 ? (on.length ? t("{name} is on for {agents}", { name: names[0], agents: who(on) }) : t("{name} is off for {agents}", { name: names[0], agents: who(off) }))
: servers ? (on.length ? t("{n} servers are on for {agents}", { n, agents: who(on) }) : t("{n} servers are off for {agents}", { n, agents: who(off) }))
: hooks ? (on.length ? t("{n} hooks are on for {agents}", { n, agents: who(on) }) : t("{n} hooks are off for {agents}", { n, agents: who(off) }))
: on.length ? t("{n} skills are on for {agents}", { n, agents: who(on) }) : t("{n} skills are off for {agents}", { n, agents: who(off) }));
} catch (e) {
status(e.message, "err", 6000);
}
render();
}, { all: true, blocked: servers ? (a) => (reach(a) ? "" : n === 1 ? sseBlocked(skills[0])(a) : t("{agent} can reach none of these servers", { agent: a.name })) : null });
}, { all: true, blocked: servers ? (a) => (reach(a) ? "" : n === 1 ? sseBlocked(skills[0])(a) : t("{agent} can reach none of these servers", { agent: a.name }))
: hooks ? (a) => (reach(a) ? "" : n === 1 ? hookBlocked(skills[0])(a) : t("{agent} can run none of these hooks", { agent: a.name })) : null });
box.classList.add("lib-groupchips");
for (const c of box.querySelectorAll(".lib-ag[data-agent]")) {
const a = all.find((x) => x.id === c.dataset.agent), k = count(a), m = reach(a);
if (!m) continue;
if (k && k < m) c.classList.add("some");
c.title = servers
c.title = hooks
? (k === m ? t("{agent} has all of these hooks — click to take them away", { agent: a.name })
: k ? t("{agent} has {n} of these hooks — click to give it the rest", { agent: a.name, n: k })
: t("Give {agent} all of these hooks", { agent: a.name }))
: servers
? (k === m ? t("{agent} has all of these servers — click to take them away", { agent: a.name })
: k ? t("{agent} has {n} of these servers — click to give it the rest", { agent: a.name, n: k })
: t("Give {agent} all of these servers", { agent: a.name }))
@@ -2523,8 +2733,8 @@
}
const every = box.querySelector(".lib-ag.all");
if (every) every.title = every.classList.contains("on")
? (servers ? t("Every agent has all of these servers — click to take them from every one") : t("Every agent has all of them — click to take them from every one"))
: servers ? t("Give all of these servers to every agent") : t("Give all of them to every agent");
? (servers ? t("Every agent has all of these servers — click to take them from every one") : hooks ? t("Every agent has all of these hooks — click to take them from every one") : t("Every agent has all of them — click to take them from every one"))
: servers ? t("Give all of these servers to every agent") : hooks ? t("Give all of these hooks to every agent") : t("Give all of them to every agent");
return box;
}
@@ -2541,9 +2751,9 @@
picked.clear();
render();
});
const skills = kind === "skills";
b.title = picking ? (skills ? t("Stop picking skills") : t("Stop picking servers"))
: skills ? t("Pick some skills and turn them on or off together") : t("Pick some servers and turn them on or off together");
const skills = kind === "skills", hooks = kind === "hooks";
b.title = picking ? (skills ? t("Stop picking skills") : hooks ? t("Stop picking hooks") : t("Stop picking servers"))
: skills ? t("Pick some skills and turn them on or off together") : hooks ? t("Pick some hooks and turn them on or off together") : t("Pick some servers and turn them on or off together");
return b;
}
@@ -2591,33 +2801,34 @@
box.checked = k > 0 && k === box._names.length;
box.indeterminate = k > 0 && k < box._names.length;
const row = box.parentElement;
if (row?.classList.contains("lib-skill") || row?.classList.contains("lib-server")) row.classList.toggle("picked", box.checked);
if (row?.classList.contains("lib-skill") || row?.classList.contains("lib-server") || row?.classList.contains("lib-hook")) row.classList.toggle("picked", box.checked);
}
// every box drawn, and the bar, as the picks are now
function syncPicks() {
if (!picked.size) naming = false;
for (const b of page.querySelectorAll(".lib-pickbox")) paintPick(b);
const bar = page.querySelector(".lib-pickbar");
if (bar) bar.replaceWith(pickBar(picking === "servers" ? mcpAgents() : skillAgents()));
if (bar) bar.replaceWith(pickBar(picking === "servers" ? mcpAgents() : picking === "hooks" ? hookAgents() : skillAgents()));
}
// the servers' bar is the same, with no filter or groups (#1027)
function pickBar(all) {
const bar = el("div", "row lib-row lib-pickbar");
const servers = picking === "servers";
const shown = servers ? lib.servers : shownSkills(), q = servers ? "" : skillQuery.trim();
const servers = picking === "servers", hooks = picking === "hooks";
const own = servers ? lib.servers : hooks ? lib.hooks || [] : lib.skills;
const shown = servers || hooks ? own : shownSkills(), q = servers || hooks ? "" : skillQuery.trim();
const every = el("label", "lib-pickall");
every.append(pickAll(shown), el("span", "", q ? t("All {n} that match", { n: shown.length }) : t("All {n}", { n: shown.length })));
every.onclick = (e) => e.stopPropagation();
const skills = (servers ? lib.servers : lib.skills).filter((s) => picked.has(s.name));
const skills = own.filter((s) => picked.has(s.name));
const n = skills.length;
bar.append(every, el("span", "lib-pickn" + (n ? "" : " none"), n ? t("{n} selected", { n })
: servers ? t("Pick servers to turn them on or off together") : t("Pick skills to turn them on or off together")), el("span", "grow"));
: servers ? t("Pick servers to turn them on or off together") : hooks ? t("Pick hooks to turn them on or off together") : t("Pick skills to turn them on or off together")), el("span", "grow"));
if (n && naming) return nameBar(bar, skills);
if (n) {
bar.append(groupChips(skills, all, null, servers ? "servers" : "skills"));
bar.append(groupChips(skills, all, null, picking || "skills"));
// a group of the user's made of them, or the ones in one let go (#791)
if (!servers && sortOf("libSkills", SKILL_SORTS()) === "source") {
if (!servers && !hooks && sortOf("libSkills", SKILL_SORTS()) === "source") {
const gb = button(t("Group…"), "lib-updall lib-pickgroup", () => { naming = true; syncPicks(); });
gb.title = t("Put the skills picked in a group of your own");
bar.append(gb);
@@ -3420,9 +3631,11 @@
// project magpie gave it to, its sign-in forgotten; the agents' servers
// of their own stay. It asks first, in the page, saying who loses what.
function removeEveryButton(kind) {
const skills = kind === "skills";
const b = button(t("Remove all"), "action danger lib-updall lib-everyrm", () => skills ? confirmRemoveEverySkill() : confirmRemoveEveryServer());
b.title = skills ? t("Take all {n} skills out of the library", { n: lib.skills.length }) : t("Take all {n} servers out of the library", { n: lib.servers.length });
const skills = kind === "skills", hooks = kind === "hooks";
const b = button(t("Remove all"), "action danger lib-updall lib-everyrm", () => skills ? confirmRemoveEverySkill() : hooks ? confirmRemoveEveryHook() : confirmRemoveEveryServer());
b.title = skills ? t("Take all {n} skills out of the library", { n: lib.skills.length })
: hooks ? t("Take all {n} hooks out of the library", { n: (lib.hooks || []).length })
: t("Take all {n} servers out of the library", { n: lib.servers.length });
return b;
}
@@ -3480,8 +3693,8 @@
const res = v.result || {}, no = res.unremoved || [];
if (no.length) {
const p = no[0];
status(t("{name} wasn't removed: {error}", { name: p.what.replace(/^(skill|mcp):/, ""), error: p.error }) + (no.length > 1 ? " " + t("(and {n} more)", { n: no.length - 1 }) : ""), "warn", 8000);
} else report(res, kind === "skills" ? t("{n} skills removed", { n: names.length }) : t("{n} servers removed", { n: names.length }));
status(t("{name} wasn't removed: {error}", { name: p.what.replace(/^(skill|mcp|hook):/, ""), error: p.error }) + (no.length > 1 ? " " + t("(and {n} more)", { n: no.length - 1 }) : ""), "warn", 8000);
} else report(res, kind === "skills" ? t("{n} skills removed", { n: names.length }) : kind === "hooks" ? t("{n} hooks removed", { n: names.length }) : t("{n} servers removed", { n: names.length }));
render();
return true;
} catch (e) {
+11
View File
@@ -427,6 +427,7 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
Paths []string
Names []string // the skills to update, of those a check found changed; to bring in, of those found in the agents
Server library.Server
Hook library.Hook // a hook saved (#1790)
Agent string // the agent whose own skill is in the library's way
ID string // a market server's, or a market skill's in its repository
Values map[string]string // what a market server needs
@@ -472,6 +473,16 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
res, err = library.ImportServer(in.Name)
case "servers/remove-found":
res, err = library.RemoveFoundServer(in.Name)
case "hooks/save":
res, err = library.SaveHook(in.Old, in.Hook)
case "hooks/agents":
res, err = library.HookAgents(in.Name, in.Agents)
case "hooks/agents-some":
res, err = library.SomeHooksAgents(in.Names, in.Agents, in.On)
case "hooks/remove":
res, err = library.RemoveHooks([]string{in.Name})
case "hooks/remove-all":
res, err = library.RemoveHooks(in.Names)
case "skills/install":
res, err = library.InstallSkills(in.Source, in.Paths, in.Agents)
case "skills/update":
+260
View File
@@ -0,0 +1,260 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// #1790 (AllenReder): Hooks, the Library's fifth tab. A hook is kept once
// and given to agents with the chips every other tab has. The tab lists
// each hook with what it runs on, in words (After a tool runs · File
// edits), and its command; an agent magpie can't write hooks for has its
// chip greyed, saying why, and a click on it posts nothing. Asides say
// what an agent does with a hook given to it: Codex runs one only once it
// is trusted in its /hooks, Cursor runs Claude Code's too. A row's chip
// posts hooks/agents. Add opens the editor: the event and the tools it is
// for are app menus (never a <select>), an agent's own event (Claude
// Code · Notification) leaves only that agent's chip, and Save posts
// hooks/save with what was picked. Select and the bar's chips post
// hooks/agents-some; Remove all asks first and posts hooks/remove-all.
// At 440px wide in en, zh, zh-TW, ja and de: no sideways scroll, and what
// each click pressed stays where it was on the screen.
// No backend: the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const HOME = "/Users/allen";
const agent = (id, name, more = {}) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json`, ...more });
const hk = (name, event, matcher, command, agents) => ({ name, event, matcher, command, agents });
const HOOK_AGENTS = [
{ id: "claude", file: `${HOME}/.claude/settings.json`, events: ["PreToolUse", "PostToolUse", "Notification", "Stop"] },
{ id: "codex", file: `${HOME}/.codex/hooks.json`, events: ["PreToolUse", "PostToolUse", "Stop"] },
{ id: "cursor", file: `${HOME}/.cursor/hooks.json`, events: ["afterFileEdit", "stop"] },
{ id: "gemini", file: `${HOME}/.gemini/settings.json`, events: ["AfterTool", "AfterAgent"] },
{ id: "opencode", no: "OpenCode has no hooks magpie can write" },
];
const lib = (hooks) => ({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [agent("claude", "Claude Code"), agent("codex", "Codex"), agent("cursor", "Cursor"), agent("gemini", "Gemini CLI"), agent("opencode", "OpenCode")],
instructions: { agents: [] }, servers: [], skills: [], foundServers: [], projects: [], foundSkills: [], problems: [],
hooks, hookAgents: HOOK_AGENTS,
});
let I18N;
async function loadI18N() {
const src = await fs.readFile(path.join(assets, "i18n.js"), "utf8");
I18N = new Function(src.slice(0, src.indexOf("\n};") + 3) + "; return I18N;")();
}
// the words the page says in lang; a string missing from a language fails
function tr(lang, key, vars = {}) {
let s = key;
if (lang !== "en") {
assert.equal(typeof I18N[lang][key], "string", `${lang} has no ${JSON.stringify(key)}`);
s = I18N[lang][key];
}
return s.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m));
}
function server(lang, state, posts) {
const can = (h, a) => a !== "opencode" && (!h.event.includes(":") || h.event.startsWith(a + ":"));
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/library") return json(lib(state.hooks));
if (url.pathname.startsWith("/api/library/") && req.method() === "POST" && !url.pathname.endsWith("/reveal")) {
const body = req.postDataJSON(), what = url.pathname.replace("/api/library/", "");
posts.push({ what, body });
const put = (x, agents, on) => ({ ...x, agents: on ? [...new Set([...x.agents, ...agents.filter((a) => can(x, a))])].sort() : x.agents.filter((a) => !agents.includes(a)) });
if (what === "hooks/agents") state.hooks = state.hooks.map((x) => (x.name === body.name ? { ...x, agents: body.agents.filter((a) => can(x, a)) } : x));
if (what === "hooks/agents-some") state.hooks = state.hooks.map((x) => (body.names.includes(x.name) ? put(x, body.agents, body.on) : x));
if (what === "hooks/save") state.hooks = [...state.hooks.filter((x) => x.name !== body.old), body.hook];
if (what === "hooks/remove-all") state.hooks = state.hooks.filter((x) => !body.names.includes(x.name));
return json({ ...lib(state.hooks), result: { changed: ["claude"] } });
}
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true } });
if (url.pathname.startsWith("/api/")) return json({});
if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" });
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
// a click where the button is, as the reader's, and what was clicked stays
// where it was on the screen while the click redraws around it
const press = async (page, loc) => {
await page.waitForFunction(() => !document.querySelector("#view-library").getAnimations({ subtree: true }).some((a) => a.effect?.getComputedTiming().endTime !== Infinity));
const b = await loc.boundingBox();
const sel = String(loc);
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
await page.waitForTimeout(250);
if (!(await loc.count())) return;
const a = await loc.boundingBox();
if (a && a.width) assert(Math.abs(a.y - b.y) <= 1, `${sel} moved on the screen from ${Math.round(b.y)} to ${Math.round(a.y)}`);
};
const settled = (page) => page.waitForFunction(() => !document.querySelector("#modal").getAnimations({ subtree: true }).length);
// nothing wider than the window: the page, the Library, its rows, bar and dialog
const sideways = (page) => page.evaluate(() => {
const over = [];
const w = document.documentElement.clientWidth;
if (document.documentElement.scrollWidth > w) over.push("page " + document.documentElement.scrollWidth);
const v = document.querySelector("#view-library");
if (v.scrollWidth > v.clientWidth + 1) over.push("library " + v.scrollWidth + ">" + v.clientWidth);
for (const e of document.querySelectorAll("#view-library .lib-hookhead > *, #view-library .lib-hook, #view-library .lib-pickbar, #view-library .lib-tabs, #modal .lib-hookedit *")) {
const r = e.getBoundingClientRect();
if (r.width && (r.right > w + 0.5 || r.left < -0.5)) over.push((e.className || e.tagName) + " " + Math.round(r.left) + "–" + Math.round(r.right));
}
return over;
});
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": the Library's Hooks tab", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
await loadI18N();
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
t.after(() => browser.close());
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
await t.test(lang, async () => {
const w = (key, vars) => tr(lang, key, vars);
const state = { hooks: [hk("bark", "turn-end", "", "curl -s https://api.day.app/KEY/done", ["codex"]), hk("fmt", "after-tool", "edit", "prettier -w .", ["claude", "cursor"])] };
const posts = [], errors = [];
const ctx = await browser.newContext({ viewport: { width: 440, height: 1000 }, reducedMotion: "reduce" });
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "hooks"); } catch {} });
const page = await ctx.newPage();
page.setDefaultTimeout(5000);
page.on("pageerror", (e) => errors.push(e.message));
page.on("dialog", (d) => { errors.push("a browser dialog: " + d.message()); d.dismiss(); });
await page.route("**/*", server(lang, state, posts));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
const v = page.locator("#view-library");
await v.locator(".lib-hook").first().waitFor();
const row = (name) => v.locator(".lib-hook").filter({ has: page.locator(".name", { hasText: new RegExp("^" + name + "$") }) });
const agentsOf = (name) => state.hooks.find((s) => s.name === name)?.agents;
// the tab, with its count, between Skills and RTK
const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim());
assert.deepEqual(tabs.slice(2, 5), [w("Skills"), w("Hooks") + " · 2", "RTK"]);
// each hook says when it runs, in words, and what it runs
assert.equal((await row("fmt").locator(".lib-hookev").textContent()).trim(), w("After a tool runs") + " · " + w("File edits"));
assert.equal((await row("bark").locator(".lib-hookev").textContent()).trim(), w("When a turn ends"));
assert.equal((await row("bark").locator(".lib-hookcmd").textContent()).trim(), "curl -s https://api.day.app/KEY/done");
// what an agent does with one given to it
await v.locator(".lib-hooks-codex").filter({ hasText: w("Codex runs a new or changed hook only once you trust it: review it in Codex's /hooks.") }).waitFor();
await v.locator(".lib-hooks-twice").filter({ hasText: w("Cursor runs Claude Code's hooks too: a hook given to both runs twice in Cursor.") }).waitFor();
await v.locator(".lib-hooks-no").filter({ hasText: w("magpie can't give hooks to {agents} yet: their chips are greyed, and say why.", { agents: "OpenCode" }) }).waitFor();
assert.equal(await v.locator(".lib-hooks-off").count(), 0, "Gemini CLI, given none, said to have hooks off");
assert.deepEqual(await sideways(page), [], "sideways scroll with the list");
// OpenCode's chip is greyed, says why, and a click posts nothing
const oc = row("bark").locator('.lib-ag[data-agent="opencode"]');
assert.equal(await oc.getAttribute("aria-disabled"), "true");
assert.equal(await oc.getAttribute("title"), w("{agent} has no hooks magpie can write", { agent: "OpenCode" }));
await press(page, oc);
await page.waitForTimeout(150);
assert.deepEqual(posts, [], "a greyed chip posted");
// a row's chip gives the hook to Gemini CLI
await press(page, row("bark").locator('.lib-ag[data-agent="gemini"]'));
await page.waitForFunction(() => document.querySelector('#view-library .lib-hook .lib-ag[data-agent="gemini"][aria-pressed="true"]'));
await page.waitForTimeout(200);
assert.deepEqual(posts.shift(), { what: "hooks/agents", body: { name: "bark", agents: ["codex", "gemini"] } });
assert.deepEqual(agentsOf("bark"), ["codex", "gemini"]);
// Add: the editor, its event and tools from app menus
await press(page, v.locator(".after-list button"));
const ed = page.locator("#modal .lib-hookedit");
await ed.waitFor();
await settled(page);
assert.equal(await page.locator("#modal select").count(), 0, "a native <select>");
assert.equal((await ed.locator(".ehead b").textContent()).trim(), w("New hook"));
assert.equal((await ed.locator(".lib-hookevent").textContent()).trim(), w("When a turn ends"));
await ed.locator("input").first().fill("notify");
// an agent's own event: only that agent can run it
await ed.locator(".lib-hookevent").click();
const menu = page.locator(".proto-menu");
await menu.waitFor();
assert.equal((await menu.locator(".pm-head").textContent()).trim(), w("When it runs"));
await menu.locator(".pm-item", { hasText: "Claude Code · Notification" }).click();
await menu.waitFor({ state: "detached" });
assert.equal((await ed.locator(".lib-hookevent").textContent()).trim(), "Claude Code · Notification");
const edChip = (id) => ed.locator(`.lib-ag[data-agent="${id}"]`);
assert.equal(await edChip("claude").getAttribute("aria-pressed"), "true");
assert.equal(await edChip("codex").getAttribute("aria-disabled"), "true");
assert.equal(await edChip("codex").getAttribute("title"), w("{event} is {agent}'s own event: only it can run this hook", { event: "Notification", agent: "Claude Code" }));
await ed.locator(".lib-hookmatcher").waitFor();
// back to one every agent has, after a tool, for shell commands
await ed.locator(".lib-hookevent").click();
await menu.waitFor();
await menu.locator(".pm-item", { hasText: w("After a tool runs") }).click();
await menu.waitFor({ state: "detached" });
await ed.locator(".lib-hooktool").click();
await menu.waitFor();
assert.equal((await menu.locator(".pm-head").textContent()).trim(), w("For which tools"));
await menu.locator(".pm-item", { hasText: w("Shell commands") }).click();
await menu.waitFor({ state: "detached" });
assert.equal((await ed.locator(".lib-hooktool").textContent()).trim(), w("Shell commands"));
assert.equal(await edChip("codex").getAttribute("aria-disabled"), null);
await edChip("codex").click();
await ed.locator('input[placeholder="curl -s https://api.day.app/KEY/done"]').fill("say done");
await ed.locator(".lib-hooktimeout").fill("30");
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: "hooks/save", body: { old: "", hook: { name: "notify", event: "after-tool", matcher: "shell", command: "say done", timeout: 30, agents: ["claude", "codex"] } } });
await row("notify").waitFor();
assert.equal((await row("notify").locator(".lib-hookev").textContent()).trim(), w("After a tool runs") + " · " + w("Shell commands"));
// Select: the bar's chips turn the ones picked on for an agent
const head = v.locator(".row-head.lib-hookhead");
assert.equal(await head.locator(".lib-select").getAttribute("title"), w("Pick some hooks and turn them on or off together"));
await press(page, head.locator(".lib-select"));
await v.locator(".lib-pickbar .lib-pickn.none").filter({ hasText: w("Pick hooks to turn them on or off together") }).waitFor();
await press(page, row("bark").locator(".lib-pickbox"));
await press(page, row("fmt").locator(".lib-pickbox"));
await v.locator(".lib-pickbar .lib-pickn").filter({ hasText: w("{n} selected", { n: 2 }) }).waitFor();
const chip = (id) => v.locator(`.lib-pickbar .lib-ag[data-agent="${id}"]`);
assert.equal(await chip("opencode").getAttribute("aria-disabled"), "true");
assert.equal(await chip("gemini").getAttribute("title"), w("{agent} has {n} of these hooks — click to give it the rest", { agent: "Gemini CLI", n: 1 }));
await press(page, chip("gemini"));
await page.locator("#status").filter({ hasText: w("{n} hooks are on for {agents}", { n: 2, agents: "Gemini CLI" }) }).waitFor();
assert.deepEqual(posts.shift(), { what: "hooks/agents-some", body: { names: ["bark", "fmt"], agents: ["gemini"], on: true } });
assert.deepEqual(agentsOf("fmt"), ["claude", "cursor", "gemini"]);
assert.deepEqual(await sideways(page), [], "sideways scroll with the bar");
await press(page, v.locator(".lib-pickdone"));
assert.equal(await v.locator(".lib-pickbox").count(), 0);
// Remove all asks first; Cancel posts nothing
await press(page, head.locator(".lib-everyrm"));
const sheet = page.locator("#modal .lib-editor");
await sheet.waitFor();
await settled(page);
assert.equal((await sheet.locator(".ehead b").textContent()).trim(), w("Remove all {n} hooks?", { n: 3 }));
const said = (await sheet.locator(".lib-confirm").allTextContents()).map((x) => x.trim());
assert.equal(said[1], w("Hooks your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file."));
await sheet.locator(".bar button", { hasText: w("Cancel") }).click();
await sheet.waitFor({ state: "detached" });
await page.waitForTimeout(150);
assert.deepEqual(posts, [], "Cancel posts nothing");
await press(page, v.locator(".lib-hookhead .lib-everyrm"));
await sheet.waitFor();
await settled(page);
await sheet.locator(".bar button.danger-fill").click();
await sheet.waitFor({ state: "detached" });
assert.deepEqual(posts.shift(), { what: "hooks/remove-all", body: { names: ["bark", "fmt", "notify"] } });
await page.locator("#status").filter({ hasText: w("{n} hooks removed", { n: 3 }) }).waitFor();
assert.equal(await v.locator(".lib-hook").count(), 0);
await v.locator(".lib-empty").filter({ hasText: w("No hooks in the library yet") }).waitFor();
assert.deepEqual(posts, []);
assert.deepEqual(errors, []);
await ctx.close();
});
}
});
}
+2 -2
View File
@@ -72,7 +72,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(await skel.getAttribute("aria-busy"), "true");
const tabs = v.locator(".lib-head .lib-tabs .opt");
assert.deepEqual(await tabs.allTextContents(), ["Instructions", "MCP servers", "Skills", "RTK"]);
assert.deepEqual(await tabs.allTextContents(), ["Instructions", "MCP servers", "Skills", "Hooks", "RTK"]);
assert.equal(await v.locator(".lib-tabs .opt.on").textContent(), "Skills");
assert.ok(await v.locator(".lib-head .lib-more").isDisabled(), "the folder waits for the library");
// Skills in outline: rows with a switch, no section heading
@@ -89,7 +89,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
open();
await v.locator(".lib-head .lib-more:not([disabled])").waitFor();
assert.equal(await v.locator(".lib-skel").count(), 0, "the outline goes");
assert.deepEqual(await v.locator(".lib-tabs .opt").allTextContents(), ["Instructions", "MCP servers · 1", "Skills · 1", "RTK"]);
assert.deepEqual(await v.locator(".lib-tabs .opt").allTextContents(), ["Instructions", "MCP servers · 1", "Skills · 1", "Hooks", "RTK"]);
assert.equal(await v.locator(".lib-tabs .opt.on").textContent(), "Instructions");
assert.equal(await v.locator(".lib-head .lib-more").getAttribute("title"), "~/.magpie/library");
const after = await v.locator(".lib-tabs").boundingBox();
+854
View File
@@ -0,0 +1,854 @@
package library
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"github.com/pelletier/go-toml/v2"
"github.com/tidwall/gjson"
"github.com/tidwall/jsonc"
"github.com/yetone/magpie/internal/edit"
)
// Hooks (#1790) are commands an agent runs at a point of its turn: when
// it ends (a phone notification), after it edits a file (a formatter).
// One is kept once and written into each agent ticked for it, in that
// agent's own file and shape:
//
// Claude Code <claude dir>/settings.json hooks.<Event>: [{matcher, hooks: [{type, command, timeout}]}]
// Codex <codex home>/hooks.json the same shape
// Gemini CLI ~/.gemini/settings.json the same shape, timeout in ms
// Cursor ~/.cursor/hooks.json hooks.<event>: [{command, timeout, matcher}], version 1
//
// 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")
// is given to that agent alone. What magpie wrote is recorded entry by
// entry (Applied.Hooks), and only an entry still exactly as magpie wrote
// it is ever taken out: one the user changed is theirs from then on, and
// the user's own hooks around it stay as they are.
// Hook is a command the agents ticked for it run at Event.
type Hook struct {
Name string `json:"name"`
// Event is a portable event (HookEvents), or an agent's own,
// "<agent>:<Event>" as that agent names it
Event string `json:"event"`
// Matcher narrows a tool event to some tools: for a portable event
// "shell" or "edit" (each agent's own tool names for them), for an
// agent's own event the agent's own matcher; "" is every tool
Matcher string `json:"matcher,omitempty"`
Command string `json:"command"`
Timeout int `json:"timeout,omitempty"` // seconds; 0 is the agent's own
Agents []string `json:"agents"`
}
// HookEntry is one entry magpie wrote into an agent's hooks: the hook it
// is of, the agent's event it is under, and the entry exactly as written.
type HookEntry struct {
Name string `json:"name"`
Event string `json:"event"`
Entry json.RawMessage `json:"entry"`
}
// HookEvents are the portable events, in the order the page offers them.
var HookEvents = []string{"turn-end", "after-tool", "before-tool", "prompt", "session-start"}
// HookTools are the kinds of tools a portable tool event can be narrowed to.
var HookTools = []string{"shell", "edit"}
// hookSpec is how one agent keeps its hooks.
type hookSpec struct {
path string
events map[string]string // portable → the agent's own
native []string // every event the agent has
tools map[string]string // shell, edit → the agent's matcher for them
flat bool // Cursor: an entry is the command itself, not a group of them
ms bool // Gemini: timeouts in milliseconds
}
// hookAgents are the agents magpie can give hooks to.
var hookAgents = []string{"claude", "codex", "cursor", "gemini"}
// toolEvents are the portable events that take a matcher.
var toolEvents = []string{"after-tool", "before-tool"}
// hookSpecOf is how t keeps its hooks, or why magpie can't give it any.
func hookSpecOf(t *Target) (*hookSpec, string) {
if t.Agent.WSL != "" {
return nil, fmt.Sprintf("magpie gives hooks only to agents on this computer, not yet to %s in WSL", t.Agent.Name)
}
switch t.Agent.ID {
case "claude":
return &hookSpec{
path: filepath.Join(claudeDir(), "settings.json"),
events: map[string]string{"turn-end": "Stop", "after-tool": "PostToolUse", "before-tool": "PreToolUse",
"prompt": "UserPromptSubmit", "session-start": "SessionStart"},
native: []string{"PreToolUse", "PostToolUse", "PostToolUseFailure", "PermissionRequest", "Notification", "UserPromptSubmit",
"Stop", "SubagentStart", "SubagentStop", "PreCompact", "SessionStart", "SessionEnd"},
tools: map[string]string{"shell": "Bash", "edit": "Edit|Write|MultiEdit"},
}, ""
case "codex":
// codex-rs/hooks: hooks.json beside config.toml, whose events are
// HookEventName's
return &hookSpec{
path: filepath.Join(codexDir(), "hooks.json"),
events: map[string]string{"turn-end": "Stop", "after-tool": "PostToolUse", "before-tool": "PreToolUse",
"prompt": "UserPromptSubmit", "session-start": "SessionStart"},
native: []string{"PreToolUse", "PermissionRequest", "PostToolUse", "PreCompact", "PostCompact", "SessionStart", "SessionEnd",
"UserPromptSubmit", "SubagentStart", "SubagentStop", "Stop", "Interrupt"},
tools: map[string]string{"shell": "Bash", "edit": "apply_patch"},
}, ""
case "gemini":
// gemini-cli packages/core/src/hooks/types.ts, HookEventName
return &hookSpec{
path: filepath.Join(home(), ".gemini", "settings.json"),
events: map[string]string{"turn-end": "AfterAgent", "after-tool": "AfterTool", "before-tool": "BeforeTool",
"prompt": "BeforeAgent", "session-start": "SessionStart"},
native: []string{"BeforeTool", "AfterTool", "BeforeAgent", "AfterAgent", "Notification", "SessionStart", "SessionEnd",
"PreCompress", "BeforeModel", "AfterModel", "BeforeToolSelection"},
tools: map[string]string{"shell": "run_shell_command", "edit": "write_file|replace"},
ms: true,
}, ""
case "cursor":
return &hookSpec{
path: filepath.Join(home(), ".cursor", "hooks.json"),
events: map[string]string{"turn-end": "stop", "after-tool": "postToolUse", "before-tool": "preToolUse",
"prompt": "beforeSubmitPrompt", "session-start": "sessionStart"},
native: []string{"beforeShellExecution", "afterShellExecution", "beforeMCPExecution", "afterMCPExecution", "beforeReadFile",
"afterFileEdit", "beforeSubmitPrompt", "stop", "afterAgentResponse", "afterAgentThought", "sessionStart", "sessionEnd",
"preToolUse", "postToolUse", "postToolUseFailure", "subagentStart", "subagentStop", "preCompact"},
tools: map[string]string{"shell": "Shell", "edit": "Write"},
flat: true,
}, ""
}
return nil, fmt.Sprintf("%s has no hooks magpie can write", t.Agent.Name)
}
// event is the agent's own name for h's event, or why it has none.
func (sp *hookSpec) event(agent string, h *Hook) (string, error) {
if a, ev, ok := strings.Cut(h.Event, ":"); ok {
if a != agent {
return "", fmt.Errorf("%s is an event of another agent's", ev)
}
if !slices.Contains(sp.native, ev) {
return "", fmt.Errorf("it has no event called %s", ev)
}
return ev, nil
}
if ev := sp.events[h.Event]; ev != "" {
return ev, nil
}
return "", fmt.Errorf("no event called %s", h.Event)
}
// entry is h as the agent's file holds it, under event ev.
func (sp *hookSpec) entry(h *Hook) json.RawMessage {
m := h.Matcher
if !strings.Contains(h.Event, ":") {
m = sp.tools[h.Matcher] // "" for none, and for an event that takes no matcher
}
timeout := h.Timeout
if sp.ms {
timeout *= 1000
}
var v any
if sp.flat {
v = struct {
Command string `json:"command"`
Timeout int `json:"timeout,omitempty"`
Matcher string `json:"matcher,omitempty"`
}{h.Command, timeout, m}
} else {
type cmd struct {
Type string `json:"type"`
Command string `json:"command"`
Timeout int `json:"timeout,omitempty"`
}
v = struct {
Matcher string `json:"matcher,omitempty"`
Hooks []cmd `json:"hooks"`
}{m, []cmd{{"command", h.Command, timeout}}}
}
b, _ := json.Marshal(v)
return b
}
func (h *Hook) check() error {
if err := checkName("hook", h.Name); err != nil {
return err
}
if strings.TrimSpace(h.Command) == "" {
return errors.New("a hook needs a command to run")
}
if h.Timeout < 0 || h.Timeout > 86400 {
return errors.New("a hook's timeout is between 0 (the agent's own) and 86400 seconds")
}
if a, ev, ok := strings.Cut(h.Event, ":"); ok {
if !slices.Contains(hookAgents, a) || ev == "" {
return fmt.Errorf("no event called %s", h.Event)
}
for _, x := range h.Agents {
if x != a {
return fmt.Errorf("%s is %s's own event: only it can be given this hook", ev, a)
}
}
return nil
}
if !slices.Contains(HookEvents, h.Event) {
return fmt.Errorf("no event called %s", h.Event)
}
if h.Matcher != "" && (!slices.Contains(toolEvents, h.Event) || !slices.Contains(HookTools, h.Matcher)) {
return fmt.Errorf("%s can't be narrowed to %s", h.Event, h.Matcher)
}
return nil
}
func (l *Library) hook(name string) *Hook {
for _, h := range l.Hooks {
if h.Name == name {
return h
}
}
return nil
}
// canonical is a JSON value written one way, its keys sorted, for two
// entries to be told the same however each was spaced.
func canonical(raw []byte) string {
var v any
d := json.NewDecoder(bytes.NewReader(raw))
d.UseNumber()
if d.Decode(&v) != nil {
return string(raw)
}
b, _ := json.Marshal(v)
return string(b)
}
// readHooksFile is an agent's hooks file as JSON, "" for one not there. One
// that can't be read, or isn't JSON, is an error: what it holds is unknown,
// never nothing to keep.
func readHooksFile(path string) ([]byte, error) {
raw, err := edit.Read(path)
if err != nil {
return nil, err
}
raw = edit.TrimBOM(raw)
if len(bytes.TrimSpace(raw)) == 0 {
return nil, nil
}
j := jsonc.ToJSON(raw)
if !json.Valid(j) {
return nil, fmt.Errorf("%s isn't JSON magpie can read: it is left as it is", path)
}
if !gjson.ParseBytes(j).IsObject() {
return nil, fmt.Errorf("%s isn't a JSON object: it is left as it is", path)
}
return j, nil
}
// hookList is the list the file has under hooks.<ev>.
func hookList(doc []byte, path, ev string) ([]json.RawMessage, error) {
r := gjson.GetBytes(doc, "hooks."+ev)
if !r.Exists() {
return nil, nil
}
if !r.IsArray() {
return nil, fmt.Errorf("%s: hooks.%s isn't a list", path, ev)
}
var list []json.RawMessage
if err := json.Unmarshal([]byte(r.Raw), &list); err != nil {
return nil, fmt.Errorf("%s: hooks.%s: %w", path, ev, err)
}
return list, nil
}
// syncHooks writes into t the hooks the library gives it and takes out the
// ones it no longer does: only entries exactly as magpie wrote them, the
// user's own hooks, before and after them, left where they are.
func (l *Library) syncHooks(t *Target, b *backups, res *Result) {
id := t.Agent.ID
a := l.applied(id)
var want []*Hook
for _, h := range l.Hooks {
if slices.Contains(h.Agents, id) {
want = append(want, h)
}
}
if len(a.Hooks) == 0 && len(want) == 0 {
return
}
sp, why := hookSpecOf(t)
if sp == nil {
for _, h := range want {
res.fail(id, "hook:"+h.Name, errors.New(why))
}
return
}
failAll := func(err error) {
for _, h := range want {
res.fail(id, "hook:"+h.Name, err)
}
if len(want) == 0 {
res.fail(id, "hooks", err)
}
}
doc, err := readHooksFile(sp.path)
if err != nil {
failAll(err)
return
}
lists := map[string][]json.RawMessage{}
listOf := func(ev string) ([]json.RawMessage, error) {
if x, ok := lists[ev]; ok {
return x, nil
}
x, err := hookList(doc, sp.path, ev)
if err == nil {
lists[ev] = x
}
return x, err
}
type wanted struct {
h *Hook
ev string
entry json.RawMessage
done bool
}
var ws []*wanted
for _, h := range want {
ev, err := sp.event(id, h)
if err != nil {
res.fail(id, "hook:"+h.Name, err)
continue
}
if _, err := listOf(ev); err != nil {
res.fail(id, "hook:"+h.Name, err)
continue
}
ws = append(ws, &wanted{h: h, ev: ev, entry: sp.entry(h)})
}
claimed := map[string]map[int]bool{} // event → the entries magpie's records found
find := func(ev string, entry json.RawMessage) int {
c := canonical(entry)
for i, e := range lists[ev] {
if !claimed[ev][i] && canonical(e) == c {
return i
}
}
return -1
}
claim := func(ev string, i int) {
if claimed[ev] == nil {
claimed[ev] = map[int]bool{}
}
claimed[ev][i] = true
}
var kept []HookEntry
drop := map[string][]int{} // event → the entries to take out
var unread []HookEntry // records of an event whose list can't be read now
for _, rec := range a.Hooks {
if _, err := listOf(rec.Event); err != nil {
res.fail(id, "hook:"+rec.Name, err)
unread = append(unread, rec)
continue
}
i := find(rec.Event, rec.Entry)
if i < 0 {
continue // gone, or changed by the user: theirs now
}
claim(rec.Event, i)
if j := slices.IndexFunc(ws, func(w *wanted) bool {
return !w.done && w.h.Name == rec.Name && w.ev == rec.Event && canonical(w.entry) == canonical(rec.Entry)
}); j >= 0 {
ws[j].done = true
kept = append(kept, rec)
continue
}
drop[rec.Event] = append(drop[rec.Event], i)
}
add := map[string][]json.RawMessage{}
var added []HookEntry
for _, w := range ws {
if w.done {
continue
}
// the same entry of the user's own already runs: it isn't written
// twice, nor taken as magpie's
if i := find(w.ev, w.entry); i >= 0 {
continue
}
add[w.ev] = append(add[w.ev], w.entry)
added = append(added, HookEntry{Name: w.h.Name, Event: w.ev, Entry: w.entry})
}
if len(drop) == 0 && len(add) == 0 {
a.Hooks = append(kept, unread...)
return
}
// what each list becomes, and where each entry left in it moves to
var set []edit.KV
var del []string
moved := map[string]map[int]int{} // event → old index → new, -1 for one taken out
for _, ev := range slices.Sorted(func(yield func(string) bool) {
seen := map[string]bool{}
for k := range drop {
if !seen[k] && !yield(k) {
return
}
seen[k] = true
}
for k := range add {
if !seen[k] && !yield(k) {
return
}
seen[k] = true
}
}) {
old := lists[ev]
m := map[int]int{}
var next []json.RawMessage
for i, e := range old {
if slices.Contains(drop[ev], i) {
m[i] = -1
continue
}
m[i] = len(next)
next = append(next, e)
}
next = append(next, add[ev]...)
moved[ev] = m
if len(next) == 0 {
del = append(del, "hooks."+ev)
} else {
set = append(set, edit.KV{Path: "hooks." + ev, Value: next})
}
}
if err := b.keep(id, sp.path); err != nil {
failAll(err)
return
}
// Codex trusts a hook by where it is (codex-rs/hooks: hook_key, the
// file's path, the event, the group's and the handler's index): an
// entry taken out from before the user's own would leave their trust
// on the wrong ones, so it is moved with them
var rekey func() error
if id == "codex" && len(drop) > 0 {
cfg := filepath.Join(codexDir(), "config.toml")
f, err := codexRekey(cfg, sp.path, moved)
if err != nil {
failAll(err)
return
}
if f != nil {
if err := b.keep(id, cfg); err != nil {
failAll(err)
return
}
rekey = f
}
}
raw := doc
if raw == nil {
raw = []byte("{}\n")
} else if orig, err := edit.Read(sp.path); err == nil {
raw = orig // its comments and spacing, as the user has them
}
if sp.flat && !gjson.GetBytes(jsonc.ToJSON(edit.TrimBOM(raw)), "version").Exists() {
set = append(set, edit.KV{Path: "version", Value: 1})
}
out, err := edit.PatchJSON(raw, set, del)
if err == nil && len(del) > 0 && len(set) == 0 {
// a hooks object left empty by magpie goes with what it held
if h := gjson.GetBytes(jsonc.ToJSON(edit.TrimBOM(out)), "hooks"); h.IsObject() && len(h.Map()) == 0 {
out, err = edit.PatchJSON(out, nil, []string{"hooks"})
}
}
if err == nil {
err = os.MkdirAll(filepath.Dir(sp.path), 0o755)
}
if err == nil {
err = edit.WriteAtomic(sp.path, out)
}
if err != nil {
failAll(fmt.Errorf("%s: %w", sp.path, err))
return
}
res.changed(id)
if rekey != nil {
if err := rekey(); err != nil {
res.fail(id, "hooks", fmt.Errorf("the hooks are written, but Codex's trust of the ones after them couldn't be moved: review them in Codex's /hooks (%w)", err))
}
}
a.Hooks = append(append(kept, added...), unread...)
}
// codexState is a [hooks.state."<key>"] header line in Codex's config.toml.
var codexState = regexp.MustCompile(`^(\s*\[\s*hooks\s*\.\s*state\s*\.\s*)("(?:[^"\\]|\\.)*"|'[^']*')(\s*\].*)$`)
// codexStateKey splits a hook's trust key: the file's path, the event's
// label, the group's index and the handler's.
func codexStateKey(k string) (path, label string, group, handler int, ok bool) {
parts := strings.Split(k, ":")
if len(parts) < 4 {
return "", "", 0, 0, false
}
n := len(parts)
g, err1 := strconv.Atoi(parts[n-2])
h, err2 := strconv.Atoi(parts[n-1])
if err1 != nil || err2 != nil {
return "", "", 0, 0, false
}
return strings.Join(parts[:n-3], ":"), parts[n-3], g, h, true
}
// snake is an event's label in Codex's trust keys (hook_event_key_label):
// PreToolUse is pre_tool_use.
func snake(ev string) string {
var b strings.Builder
for i, r := range ev {
if r >= 'A' && r <= 'Z' {
if i > 0 {
b.WriteByte('_')
}
r += 'a' - 'A'
}
b.WriteRune(r)
}
return b.String()
}
// samePath is whether two paths are the same file.
func samePath(a, b string) bool {
if filepath.Clean(a) == filepath.Clean(b) {
return true
}
ra, err1 := filepath.EvalSymlinks(filepath.Dir(a))
rb, err2 := filepath.EvalSymlinks(filepath.Dir(b))
return err1 == nil && err2 == nil && filepath.Base(a) == filepath.Base(b) && ra == rb
}
// codexRekey is what moves Codex's trust records of hooks.json's groups
// along with them (moved: event → old index → new, -1 for one taken out),
// or nil when none needs moving. A record kept in some other spelling than
// a [hooks.state."…"] table of its own can't be moved: that is an error,
// and nothing is written.
func codexRekey(cfg, hooksPath string, moved map[string]map[int]int) (func() error, error) {
raw, err := edit.Read(cfg)
if err != nil {
return nil, err
}
if len(bytes.TrimSpace(raw)) == 0 {
return nil, nil
}
var whole struct {
Hooks struct {
State map[string]any `toml:"state"`
} `toml:"hooks"`
}
if err := toml.Unmarshal(raw, &whole); err != nil {
return nil, fmt.Errorf("%s: %w", cfg, err)
}
labels := map[string]map[int]int{}
for ev, m := range moved {
labels[snake(ev)] = m
}
// to is where the record keyed k goes: ok false for one that stays
to := func(k string) (string, bool) {
p, label, g, h, ok := codexStateKey(k)
if !ok || !samePath(p, hooksPath) {
return "", false
}
m := labels[label]
if m == nil {
return "", false
}
n, in := m[g]
if !in {
// a record of a group past the end of the list, whose place
// an entry magpie adds takes: it goes
return "", g >= len(m)
}
if n == g {
return "", false
}
if n < 0 {
return "", true
}
return fmt.Sprintf("%s:%s:%d:%d", p, label, n, h), true
}
need := map[string]bool{}
for k := range whole.Hooks.State {
if _, ok := to(k); ok {
need[k] = true
}
}
if len(need) == 0 {
return nil, nil
}
lines := strings.SplitAfter(string(raw), "\n")
type span struct {
from, to int
key string
m []string
}
var spans []span
for i, ln := range lines {
m := codexState.FindStringSubmatch(strings.TrimRight(ln, "\r\n"))
if m == nil {
continue
}
q := m[2]
var k string
if q[0] == '\'' {
k = q[1 : len(q)-1]
} else if u, err := strconv.Unquote(q); err == nil {
k = u
} else {
continue
}
end := len(lines)
for j := i + 1; j < len(lines); j++ {
if s := strings.TrimSpace(lines[j]); strings.HasPrefix(s, "[") {
end = j
break
}
}
spans = append(spans, span{i, end, k, m})
}
for k := range need {
if !slices.ContainsFunc(spans, func(s span) bool { return s.key == k }) {
return nil, fmt.Errorf("%s keeps Codex's trust of %s in a way magpie can't move: take the hook out in Codex's /hooks instead", cfg, k)
}
}
return func() error {
var out strings.Builder
at := 0
for _, s := range spans {
if !need[s.key] {
continue
}
out.WriteString(strings.Join(lines[at:s.from], ""))
at = s.to
nk, _ := to(s.key)
if nk == "" {
continue // its group is gone, and its record with it
}
// the key's end, :<label>:<group>:<handler>, is digits and a
// label alone: it is written over as it is spelled
_, label, g, h, _ := codexStateKey(s.key)
_, _, ng, _, _ := codexStateKey(nk)
oldEnd, newEnd := fmt.Sprintf(":%s:%d:%d", label, g, h), fmt.Sprintf(":%s:%d:%d", label, ng, h)
q := s.m[2]
nq := q[:len(q)-1-len(oldEnd)] + newEnd + q[len(q)-1:]
nl := s.m[1] + nq + s.m[3]
if strings.HasSuffix(lines[s.from], "\r\n") {
nl += "\r\n"
} else if strings.HasSuffix(lines[s.from], "\n") {
nl += "\n"
}
out.WriteString(nl)
out.WriteString(strings.Join(lines[s.from+1:s.to], ""))
}
out.WriteString(strings.Join(lines[at:], ""))
return edit.WriteAtomic(cfg, []byte(out.String()))
}, nil
}
// hooksOff is whether the agent has every hook turned off in its settings,
// for the page to say why one given it doesn't run.
func hooksOff(t *Target, sp *hookSpec) bool {
switch t.Agent.ID {
case "claude":
v, _ := edit.GetJSON(sp.path, "disableAllHooks")
return v == "true"
case "gemini":
v, _ := edit.GetJSON(sp.path, "hooksConfig.enabled")
return v == "false"
case "codex":
f, _ := edit.GetTOMLTable(filepath.Join(codexDir(), "config.toml"), "features")
return f["hooks"] == "false"
}
return false
}
// ---- changes ---------------------------------------------------------------
// SaveHook adds a hook, or replaces the one called old (renaming it). An
// agent it can't be given is left out of it, said in the result.
func SaveHook(old string, h Hook) (*Result, error) {
if err := h.check(); err != nil {
return nil, err
}
return change(func(l *Library) error {
if h.Name != old && l.hook(h.Name) != nil {
return fmt.Errorf("the library already has a hook called %s", h.Name)
}
if old != "" {
i := slices.IndexFunc(l.Hooks, func(x *Hook) bool { return x.Name == old })
if i < 0 {
return fmt.Errorf("no hook called %s", old)
}
l.Hooks = slices.Delete(l.Hooks, i, i+1)
}
h.Agents = orNone(slices.Compact(slices.Sorted(slices.Values(h.Agents))))
l.Hooks = append(l.Hooks, &h)
return nil
})
}
// HookAgents sets which agents get a hook.
func HookAgents(name string, agents []string) (*Result, error) {
return change(func(l *Library) error {
h := l.hook(name)
if h == nil {
return fmt.Errorf("no hook called %s", name)
}
c := *h
c.Agents = agents
if err := c.check(); err != nil {
return err
}
h.Agents = orNone(slices.Compact(slices.Sorted(slices.Values(agents))))
return nil
})
}
// SomeHooksAgents gives the hooks named to the agents, or takes them from
// them, each to the agents that can take it: an agent's own event stays
// that agent's alone.
func SomeHooksAgents(names, agents []string, on bool) (*Result, error) {
if len(names) == 0 {
return nil, errors.New("no hooks to give the agents")
}
if len(agents) == 0 {
return nil, errors.New("no agents to give the hooks to")
}
return change(func(l *Library) error {
for _, name := range names {
if l.hook(name) == nil {
return fmt.Errorf("no hook called %s", name)
}
}
for _, h := range l.Hooks {
if !slices.Contains(names, h.Name) {
continue
}
list := slices.Clone(h.Agents)
for _, a := range agents {
if on && !hookTakes(h, a) {
continue
}
list = set(list, a, on)
}
h.Agents = orNone(list)
}
return nil
})
}
// hookTakes is whether agent a can be given h.
func hookTakes(h *Hook, a string) bool {
if x, _, ok := strings.Cut(h.Event, ":"); ok {
return x == a
}
return slices.Contains(hookAgents, a)
}
// RemoveHooks takes the hooks named out of the library, and what magpie
// wrote of them out of every agent. A name the library hasn't is said in
// Unremoved, the others gone all the same.
func RemoveHooks(names []string) (*Result, error) {
if len(names) == 0 {
return nil, errors.New("no hooks to remove")
}
names = slices.Compact(slices.Sorted(slices.Values(names)))
var failed []Problem
res, err := change(func(l *Library) error {
failed = nil
for _, name := range names {
if l.hook(name) == nil {
failed = append(failed, Problem{What: "hook:" + name, Error: "no hook called " + name})
}
}
if len(failed) == len(names) {
return errors.New(failed[0].Error)
}
l.Hooks = slices.DeleteFunc(l.Hooks, func(h *Hook) bool { return slices.Contains(names, h.Name) })
return nil
})
if res != nil {
res.Unremoved = failed
}
return res, err
}
// ---- the page --------------------------------------------------------------
// HookView is a library hook, and what each agent makes of it.
type HookView struct {
*Hook
// Native is what each agent it can go to calls its event
Native map[string]string `json:"native,omitempty"`
// Problems are the agents it couldn't be given to, and why
Problems map[string]string `json:"problems,omitempty"`
}
// HookAgentView is an agent the Hooks tab lists.
type HookAgentView struct {
ID string `json:"id"`
// File is where its hooks are; No is why magpie can't give it any
File string `json:"file,omitempty"`
No string `json:"no,omitempty"`
// WSL: No is that it runs in WSL, which magpie gives no hooks yet
WSL bool `json:"wsl,omitempty"`
// Off: it has every hook turned off in its settings
Off bool `json:"off,omitempty"`
// Events are its own events, for a hook of its alone
Events []string `json:"events,omitempty"`
}
func (l *Library) hooksView(targets []*Target, of func(string) map[string]string) ([]HookView, []HookAgentView) {
agents := []HookAgentView{}
specs := map[string]*hookSpec{}
for _, t := range targets {
sp, why := hookSpecOf(t)
av := HookAgentView{ID: t.Agent.ID, No: why, WSL: t.Agent.WSL != ""}
if sp != nil {
specs[t.Agent.ID] = sp
av.File, av.Off, av.Events = sp.path, hooksOff(t, sp), sp.native
}
agents = append(agents, av)
}
hooks := []HookView{}
for _, h := range l.Hooks {
c := *h
c.Agents = orNone(c.Agents)
hv := HookView{Hook: &c, Native: map[string]string{}, Problems: of("hook:" + h.Name)}
for id, sp := range specs {
if ev, err := sp.event(id, h); err == nil {
hv.Native[id] = ev
}
}
// an agent ticked that can't take it says why, before any change
for _, av := range agents {
if av.No != "" && slices.Contains(h.Agents, av.ID) {
if hv.Problems == nil {
hv.Problems = map[string]string{}
}
if hv.Problems[av.ID] == "" {
hv.Problems[av.ID] = av.No
}
}
}
hooks = append(hooks, hv)
}
return hooks, agents
}
+243
View File
@@ -0,0 +1,243 @@
package library
import (
"encoding/json"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/tidwall/gjson"
"github.com/tidwall/jsonc"
)
// hooksOf is the list a hooks file has under hooks.<ev>, as JSON.
func hooksOf(t *testing.T, path, ev string) []string {
t.Helper()
var out []string
for _, e := range gjson.GetBytes(jsonc.ToJSON([]byte(read(t, path))), "hooks."+ev).Array() {
out = append(out, canonical([]byte(e.Raw)))
}
return out
}
// The two of #1790: Bark when a Codex turn ends, a formatter after Claude
// Code edits a file. Each goes into its agent's file in its own shape,
// beside the user's own hooks, and comes out of it alone: the user's
// hooks, their comments and their other settings stay as they were.
func TestHooksEachAgentsOwnShape(t *testing.T) {
h := sandbox(t)
settings := filepath.Join(h, ".claude/settings.json")
mine := `{
// the user's own
"model": "opus",
"hooks": {
"Stop": [{"hooks": [{"type": "command", "command": "say done"}]}],
"PostToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "my-log"}]}]
}
}
`
write(t, settings, mine)
codexHooks := filepath.Join(h, ".codex/hooks.json")
ok(t)(SaveHook("", Hook{Name: "bark", Event: "turn-end", Command: "curl -s https://api.day.app/KEY/done", Timeout: 10,
Agents: []string{"codex", "gemini", "cursor"}}))
ok(t)(SaveHook("", Hook{Name: "fmt", Event: "after-tool", Matcher: "edit", Command: "prettier --write .", Agents: []string{"claude", "codex", "gemini", "cursor"}}))
if got := hooksOf(t, codexHooks, "Stop"); len(got) != 1 || got[0] != `{"hooks":[{"command":"curl -s https://api.day.app/KEY/done","timeout":10,"type":"command"}]}` {
t.Errorf("codex Stop: %v", got)
}
if got := hooksOf(t, codexHooks, "PostToolUse"); len(got) != 1 || got[0] != `{"hooks":[{"command":"prettier --write .","type":"command"}],"matcher":"apply_patch"}` {
t.Errorf("codex PostToolUse: %v", got)
}
if got := hooksOf(t, settings, "PostToolUse"); len(got) != 2 || got[1] != `{"hooks":[{"command":"prettier --write .","type":"command"}],"matcher":"Edit|Write|MultiEdit"}` {
t.Errorf("claude PostToolUse, the user's first: %v", got)
}
if got := hooksOf(t, settings, "Stop"); len(got) != 1 {
t.Errorf("claude was given bark, which isn't ticked for it: %v", got)
}
gem := filepath.Join(h, ".gemini/settings.json")
if got := hooksOf(t, gem, "AfterAgent"); len(got) != 1 || !strings.Contains(got[0], `"timeout":10000`) {
t.Errorf("gemini's timeout is in ms: %v", got)
}
if got := hooksOf(t, gem, "AfterTool"); len(got) != 1 || !strings.Contains(got[0], `"matcher":"write_file|replace"`) {
t.Errorf("gemini AfterTool: %v", got)
}
cur := filepath.Join(h, ".cursor/hooks.json")
if got := hooksOf(t, cur, "stop"); len(got) != 1 || got[0] != `{"command":"curl -s https://api.day.app/KEY/done","timeout":10}` {
t.Errorf("cursor's entry is the command itself: %v", got)
}
if v := gjson.Get(read(t, cur), "version").Int(); v != 1 {
t.Errorf("cursor's hooks.json has version %d", v)
}
v, err := Read(nil)
if err != nil {
t.Fatal(err)
}
if len(v.Hooks) != 2 || v.Hooks[0].Name != "bark" || v.Hooks[0].Native["codex"] != "Stop" || v.Hooks[0].Native["gemini"] != "AfterAgent" {
t.Errorf("view: %+v", v.Hooks)
}
ok(t)(RemoveHooks([]string{"bark", "fmt"}))
// the same settings, its comment kept (a list magpie wrote into is
// spaced the way the editor spaces one)
if got := read(t, settings); canonical(jsonc.ToJSON([]byte(got))) != canonical(jsonc.ToJSON([]byte(mine))) || !strings.Contains(got, "// the user's own") {
t.Errorf("claude's settings after, not as the user had them:\n%s", got)
}
if got := gjson.Get(read(t, codexHooks), "hooks"); got.Exists() {
t.Errorf("codex's hooks left: %s", got.Raw)
}
if got := gjson.Get(read(t, gem), "hooks"); got.Exists() {
t.Errorf("gemini's hooks left: %s", got.Raw)
}
if v, _ := Read(nil); len(v.Hooks) != 0 {
t.Errorf("left in the library: %+v", v.Hooks)
}
}
// An entry the user changed after magpie wrote it is theirs: taking the
// hook out of the library, or changing it, leaves their entry be. One the
// user had already, the same as the library's, is neither written twice
// nor taken.
func TestHooksTheUsersEditsAreTheirs(t *testing.T) {
h := sandbox(t)
settings := filepath.Join(h, ".claude/settings.json")
write(t, settings, `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"bark"}]}]}}`)
ok(t)(SaveHook("", Hook{Name: "bark", Event: "turn-end", Command: "bark", Agents: []string{"claude"}}))
if got := hooksOf(t, settings, "Stop"); len(got) != 1 {
t.Fatalf("the user's own was written again: %v", got)
}
ok(t)(RemoveHooks([]string{"bark"}))
if got := hooksOf(t, settings, "Stop"); len(got) != 1 {
t.Fatalf("the user's own was taken out: %v", got)
}
ok(t)(SaveHook("", Hook{Name: "fmt", Event: "after-tool", Matcher: "edit", Command: "gofmt -w .", Agents: []string{"claude"}}))
s := read(t, settings)
write(t, settings, strings.Replace(s, "gofmt -w .", "gofmt -w ./cmd", 1))
ok(t)(HookAgents("fmt", []string{}))
if got := hooksOf(t, settings, "PostToolUse"); len(got) != 1 || !strings.Contains(got[0], "./cmd") {
t.Errorf("the user's edit of magpie's entry was taken out: %v", got)
}
// a changed hook goes out as it was and in as it is
ok(t)(SaveHook("", Hook{Name: "lint", Event: "before-tool", Matcher: "shell", Command: "lint-a", Agents: []string{"claude"}}))
ok(t)(SaveHook("lint", Hook{Name: "lint", Event: "before-tool", Matcher: "shell", Command: "lint-b", Agents: []string{"claude"}}))
if got := hooksOf(t, settings, "PreToolUse"); len(got) != 1 || !strings.Contains(got[0], "lint-b") || !strings.Contains(got[0], `"matcher":"Bash"`) {
t.Errorf("claude PreToolUse after the change: %v", got)
}
}
// A file that doesn't parse is unknown, never empty: it is left as it is,
// and the hook said not to be given.
func TestHooksUnreadableFileLeftAlone(t *testing.T) {
h := sandbox(t)
codexHooks := filepath.Join(h, ".codex/hooks.json")
bad := `{"hooks": {"Stop": [ oops`
write(t, codexHooks, bad)
res, err := SaveHook("", Hook{Name: "bark", Event: "turn-end", Command: "bark", Agents: []string{"codex"}})
if err != nil {
t.Fatal(err)
}
if read(t, codexHooks) != bad {
t.Error("a hooks.json magpie can't read was written over")
}
if !slices.ContainsFunc(res.Problems, func(p Problem) bool { return p.Agent == "codex" && p.What == "hook:bark" }) {
t.Errorf("problems: %+v", res.Problems)
}
if a := mustLoad(t).Applied["codex"]; a != nil && len(a.Hooks) != 0 {
t.Errorf("recorded as written: %+v", a.Hooks)
}
}
// Codex trusts a hook by its place in hooks.json: a group of magpie's
// taken out from before the user's own moves the user's trust with it,
// and the record of the group taken out goes.
func TestHooksCodexTrustMovesWithTheGroups(t *testing.T) {
h := sandbox(t)
codexHooks := filepath.Join(h, ".codex/hooks.json")
cfg := filepath.Join(h, ".codex/config.toml")
write(t, cfg, "model = \"gpt-5\"\n")
ok(t)(SaveHook("", Hook{Name: "bark", Event: "turn-end", Command: "bark", Agents: []string{"codex"}}))
// the user adds one of their own after it and trusts both in /hooks
raw := read(t, codexHooks)
var doc map[string]map[string][]json.RawMessage
if err := json.Unmarshal([]byte(raw), &doc); err != nil {
t.Fatal(err)
}
doc["hooks"]["Stop"] = append(doc["hooks"]["Stop"], json.RawMessage(`{"hooks":[{"type":"command","command":"mine"}]}`))
b, _ := json.Marshal(doc)
write(t, codexHooks, string(b))
key := func(g int) string { return codexHooks + ":stop:" + string(rune('0'+g)) + ":0" }
write(t, cfg, read(t, cfg)+"\n[hooks.state.\""+key(0)+"\"]\ntrusted_hash = \"sha256:aaa\"\n\n[hooks.state.\""+key(1)+"\"]\ntrusted_hash = \"sha256:bbb\"\n\n[hooks.state.\""+codexHooks+":pre_tool_use:0:0\"]\nenabled = false\n")
ok(t)(RemoveHooks([]string{"bark"}))
if got := hooksOf(t, codexHooks, "Stop"); len(got) != 1 || !strings.Contains(got[0], "mine") {
t.Fatalf("codex Stop after: %v", got)
}
c := read(t, cfg)
want := "model = \"gpt-5\"\n\n[hooks.state.\"" + key(0) + "\"]\ntrusted_hash = \"sha256:bbb\"\n\n[hooks.state.\"" + codexHooks + ":pre_tool_use:0:0\"]\nenabled = false\n"
if c != want {
t.Errorf("config.toml after:\n%s\nwant:\n%s", c, want)
}
}
// An agent's own event goes to that agent alone, and an agent magpie can't
// give hooks to is said to be one, on the page, before any change.
func TestHooksNativeEventsAndUnavailableAgents(t *testing.T) {
h := sandbox(t)
if _, err := SaveHook("", Hook{Name: "ask", Event: "codex:PermissionRequest", Command: "x", Agents: []string{"claude"}}); err == nil {
t.Error("codex's own event was given to claude")
}
if _, err := SaveHook("", Hook{Name: "bad", Event: "turn-end", Matcher: "shell", Command: "x"}); err == nil {
t.Error("turn-end was narrowed to the shell")
}
if _, err := SaveHook("", Hook{Name: "bad", Event: "after-tool", Command: " "}); err == nil {
t.Error("a hook with no command was kept")
}
ok(t)(SaveHook("", Hook{Name: "ask", Event: "codex:PermissionRequest", Matcher: "Bash", Command: "notify", Agents: []string{"codex"}}))
ok(t)(SaveHook("", Hook{Name: "bark", Event: "turn-end", Command: "bark"}))
ok(t)(SomeHooksAgents([]string{"ask", "bark"}, []string{"claude", "opencode"}, true))
l := mustLoad(t)
if a := l.hook("ask").Agents; !slices.Equal(a, []string{"codex"}) {
t.Errorf("ask's agents: %v", a)
}
// many at once go to the agents that can take them; one ticked by
// itself that can't is said why
if a := l.hook("bark").Agents; !slices.Equal(a, []string{"claude"}) {
t.Errorf("bark's agents: %v", a)
}
if _, err := HookAgents("bark", []string{"claude", "opencode"}); err != nil {
t.Fatal(err)
}
if got := hooksOf(t, filepath.Join(h, ".codex/hooks.json"), "PermissionRequest"); len(got) != 1 || !strings.Contains(got[0], `"matcher":"Bash"`) {
t.Errorf("codex PermissionRequest: %v", got)
}
v, err := Read(nil)
if err != nil {
t.Fatal(err)
}
i := slices.IndexFunc(v.Hooks, func(x HookView) bool { return x.Name == "bark" })
if i < 0 || v.Hooks[i].Problems["opencode"] == "" || v.Hooks[i].Problems["claude"] != "" {
t.Errorf("bark's problems: %+v", v.Hooks)
}
j := slices.IndexFunc(v.HookAgents, func(a HookAgentView) bool { return a.ID == "codex" })
if j < 0 || !slices.Contains(v.HookAgents[j].Events, "PermissionRequest") || v.HookAgents[j].File == "" {
t.Errorf("codex's view: %+v", v.HookAgents)
}
}
// Hooks turned off in the agent are said: Claude Code's disableAllHooks.
func TestHooksOffSaid(t *testing.T) {
h := sandbox(t)
write(t, filepath.Join(h, ".claude/settings.json"), `{"disableAllHooks": true}`)
v, err := Read(nil)
if err != nil {
t.Fatal(err)
}
j := slices.IndexFunc(v.HookAgents, func(a HookAgentView) bool { return a.ID == "claude" })
if j < 0 || !v.HookAgents[j].Off {
t.Errorf("claude's view: %+v", v.HookAgents)
}
}
+10
View File
@@ -26,6 +26,9 @@ type Library struct {
Skills []*Skill `json:"skills"`
// Projects are folders whose agents get some of the skills there
Projects []*Project `json:"projects,omitempty"`
// Hooks are commands the agents ticked for each run at a point of
// their turn (hooks.go, #1790)
Hooks []*Hook `json:"hooks,omitempty"`
// Applied is what magpie wrote into each agent, so that what it takes
// away is only ever its own.
Applied map[string]*Applied `json:"applied,omitempty"`
@@ -85,6 +88,9 @@ type Applied struct {
// rules, OpenCode's tools keys). Neither holds one the user had.
ToolsOff map[string][]string `json:"toolsOff,omitempty"`
ToolRules []string `json:"toolRules,omitempty"`
// Hooks are the entries magpie wrote into the agent's hooks, each
// exactly as written: one changed since is the user's (hooks.go)
Hooks []HookEntry `json:"hooks,omitempty"`
}
var mu sync.Mutex // one change at a time, from the page or the CLI's process
@@ -116,6 +122,10 @@ func (l *Library) save() error {
sort.Slice(l.MCP, func(i, j int) bool { return l.MCP[i].Name < l.MCP[j].Name })
sort.Slice(l.Skills, func(i, j int) bool { return l.Skills[i].Name < l.Skills[j].Name })
sort.Slice(l.Projects, func(i, j int) bool { return l.Projects[i].Dir < l.Projects[j].Dir })
sort.Slice(l.Hooks, func(i, j int) bool { return l.Hooks[i].Name < l.Hooks[j].Name })
for _, h := range l.Hooks {
h.Agents = orNone(h.Agents)
}
for _, a := range l.Applied {
sort.Strings(a.MCP)
sort.Strings(a.Skills)
+11 -5
View File
@@ -67,6 +67,7 @@ func (l *Library) sync() *Result {
for _, t := range all {
l.syncInstructions(t, b, res)
l.syncMCP(t, b, res)
l.syncHooks(t, b, res)
}
// an edit made in an agent's copy of a skill goes to the library first,
// for the others to get rather than be undone (takeEdits)
@@ -271,11 +272,15 @@ type SkillView struct {
// View is the Library page.
type View struct {
Agents []AgentView `json:"agents"`
Servers []ServerView `json:"servers"`
FoundServers []Found `json:"foundServers"`
Skills []SkillView `json:"skills"`
FoundSkills []FoundSkill `json:"foundSkills"`
Agents []AgentView `json:"agents"`
Servers []ServerView `json:"servers"`
// Hooks are the library's hooks, and HookAgents what each agent on
// this computer can take of them (hooks.go)
Hooks []HookView `json:"hooks"`
HookAgents []HookAgentView `json:"hookAgents"`
FoundServers []Found `json:"foundServers"`
Skills []SkillView `json:"skills"`
FoundSkills []FoundSkill `json:"foundSkills"`
// NewSkills are skills a check found its skills' repositories to have
// added beside them, to add or set aside
NewSkills []NewSkill `json:"newSkills"`
@@ -377,6 +382,7 @@ func readView(problems []Problem, glance bool) (*View, error) {
}
v.Servers = append(v.Servers, sv)
}
v.Hooks, v.HookAgents = l.hooksView(targets, of)
tr := &tracer{}
for _, s := range l.Skills {
sv := SkillView{Name: s.Name, Agents: append([]string{}, s.Agents...), Icon: skillIcon(s), Problems: of("skill:" + s.Name), Repo: tr.repoOf(s)}