hookmux 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +402 -2
  3. package/dist/chunks/add-ZWGK62EX.mjs +1 -0
  4. package/dist/chunks/chunk-2ZCM3JZR.mjs +3 -0
  5. package/dist/chunks/chunk-5GQP3BA6.mjs +1 -0
  6. package/dist/chunks/chunk-65XA3RK3.mjs +4 -0
  7. package/dist/chunks/chunk-6GL55FEQ.mjs +20 -0
  8. package/dist/chunks/chunk-7Z3AMI24.mjs +1 -0
  9. package/dist/chunks/chunk-AHPMRYYF.mjs +1 -0
  10. package/dist/chunks/chunk-BF25CRHJ.mjs +1 -0
  11. package/dist/chunks/chunk-CA2GWCFP.mjs +3 -0
  12. package/dist/chunks/chunk-CSXS5D2F.mjs +1 -0
  13. package/dist/chunks/chunk-CZY5UAXM.mjs +1 -0
  14. package/dist/chunks/chunk-DJHE642J.mjs +7 -0
  15. package/dist/chunks/chunk-DZU2NMID.mjs +1 -0
  16. package/dist/chunks/chunk-F3USS665.mjs +1 -0
  17. package/dist/chunks/chunk-FF55QGCZ.mjs +1 -0
  18. package/dist/chunks/chunk-G6SJQTFF.mjs +1 -0
  19. package/dist/chunks/chunk-IAGBX723.mjs +2 -0
  20. package/dist/chunks/chunk-IJHUIMJA.mjs +5 -0
  21. package/dist/chunks/chunk-K73ZPBFM.mjs +45 -0
  22. package/dist/chunks/chunk-L3BSVLQG.mjs +1 -0
  23. package/dist/chunks/chunk-OMKE4U3M.mjs +1 -0
  24. package/dist/chunks/chunk-OXHAGFXG.mjs +12 -0
  25. package/dist/chunks/chunk-OYGOSD6V.mjs +1 -0
  26. package/dist/chunks/chunk-QTY23VNU.mjs +1 -0
  27. package/dist/chunks/chunk-RG3EOP4J.mjs +1 -0
  28. package/dist/chunks/chunk-SXIEWTYT.mjs +1 -0
  29. package/dist/chunks/chunk-UERSXYXZ.mjs +3 -0
  30. package/dist/chunks/chunk-WZSNBZ6D.mjs +2 -0
  31. package/dist/chunks/chunk-XPLEWNGF.mjs +1 -0
  32. package/dist/chunks/chunk-ZDCAHPWY.mjs +2 -0
  33. package/dist/chunks/chunk-ZNEBE4WO.mjs +1 -0
  34. package/dist/chunks/disable-KRHQYUQU.mjs +3 -0
  35. package/dist/chunks/doctor-KERAJBFA.mjs +7 -0
  36. package/dist/chunks/enable-SWA7C4K2.mjs +4 -0
  37. package/dist/chunks/explain-WNQLELTA.mjs +9 -0
  38. package/dist/chunks/hook-main-PW67WMNF.mjs +1 -0
  39. package/dist/chunks/init-46THKH7Z.mjs +12 -0
  40. package/dist/chunks/install-J4QGOOCD.mjs +15 -0
  41. package/dist/chunks/list-NAFC2CUM.mjs +5 -0
  42. package/dist/chunks/log-ELHUFP5Y.mjs +11 -0
  43. package/dist/chunks/new-UASRUAP2.mjs +186 -0
  44. package/dist/chunks/promote-4RJUMW7Y.mjs +24 -0
  45. package/dist/chunks/registry-P6V5HZQN.mjs +1 -0
  46. package/dist/chunks/remove-XCOCPNJJ.mjs +3 -0
  47. package/dist/chunks/schema-FFOAJAET.mjs +4 -0
  48. package/dist/chunks/sync-UCVS5O2X.mjs +4 -0
  49. package/dist/chunks/test-BCLMCB5A.mjs +8 -0
  50. package/dist/chunks/uninstall-ZMGYPYVA.mjs +7 -0
  51. package/dist/chunks/validate-ICFP6TSC.mjs +1 -0
  52. package/dist/cli.mjs +4 -0
  53. package/dist/hook.mjs +1 -0
  54. package/launcher/hookmux-hook.sh +83 -0
  55. package/launcher/opencode-plugin.js +236 -0
  56. package/package.json +57 -4
  57. package/plugins/hookmux-authoring/plugin.toml +65 -0
  58. package/plugins/hookmux-authoring/tests.toml +119 -0
  59. package/skills/hookmux/SKILL.md +102 -0
  60. package/skills/hookmux/references/check-kinds.md +124 -0
  61. package/skills/hookmux/references/effects.md +24 -0
  62. package/skills/hookmux/references/examples/moodboard/plugin.toml +72 -0
  63. package/skills/hookmux/references/examples/moodboard/tests.toml +20 -0
  64. package/skills/hookmux/references/hosts.md +173 -0
  65. package/skills/hookmux/references/plugin-format.md +400 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 khanglvm
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,403 @@
1
- # Temporary Holding Version
1
+ <p align="center"><img src=".github/assets/cover.png" alt="hookmux: one hook entry for every coding agent" width="100%"></p>
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # <img src=".github/assets/icon-256.png" alt="" width="36" align="top"> hookmux
4
+
5
+ Coding agents such as Claude Code, Codex, Gemini CLI and Qwen Code can run a command of yours at fixed moments: when you send a prompt, when a session starts, and before or after the agent uses a tool. That command is called a hook. What it prints back can add a note to what the agent reads, stop the prompt or the tool call, or show you a message.
6
+
7
+ hookmux takes that hook slot once in each agent and runs small plugins inside it. You write a behaviour once, as a plugin folder, and it works in every agent you use. Adding, changing or removing a plugin never touches an agent's config again.
8
+
9
+ To use it, run `hookmux init` to wire your agents, then write a plugin or install one someone else wrote. The npm release is not published yet, so for now you build hookmux from source; the Install section below has the steps.
10
+
11
+ ## What you can do with it
12
+
13
+ A hook sees what is about to happen and answers before the agent carries on, so the range is wide. A few examples:
14
+
15
+ - Stop a prompt that contains an API key before it reaches the model.
16
+ - Refuse a `git push --force` or an `rm -rf` the agent is about to run.
17
+ - Remind the agent of a project's rules whenever a session starts in that folder.
18
+ - Point the agent at a skill or a doc when a prompt asks for a certain kind of work, such as "redesign the pricing page".
19
+ - Tell the agent to run the tests after it edits a file.
20
+ - Run your own script and pass what it prints to the agent, such as the current git branch or the ticket you are working on.
21
+
22
+ Plugins decide with checks: words, regular expressions, the tool being called, the working folder, your own scripts, or an optional small model. Rules-only plugins run in-process in about a millisecond.
23
+
24
+ ## How it works
25
+
26
+ ```text
27
+ Claude Code ──┐ ┌── no-secrets
28
+ Codex ────────┤ │
29
+ Gemini CLI ───┼──▶ hookmux (one hook) ───┼── project-rules
30
+ Qwen Code ────┤ │
31
+ ... ────┘ └── run-the-tests
32
+ ```
33
+
34
+ `hookmux init` adds one hookmux entry per event to each agent's hook config. When an agent fires it, hookmux reads the event, runs every plugin listening for that event, and returns one combined answer in that agent's format. A plugin is a folder with a `plugin.toml` and, optionally, scripts and tests.
35
+
36
+ ## Install
37
+
38
+ <!-- docs:begin install.md -->
39
+ hookmux needs Node.js 22 or later. The npm release is not published yet, so today you install it from source; `npx hookmux init` is the command once the package is on npm.
40
+
41
+ ### Install from source
42
+
43
+ You need Node.js 22 or later, git, and pnpm 12 (the version pinned in `package.json`).
44
+
45
+ 1. Clone the repository and install its dependencies:
46
+
47
+ ```sh
48
+ git clone https://github.com/khanglvm/hookmux.git
49
+ cd hookmux
50
+ pnpm install
51
+ ```
52
+
53
+ 2. Build the CLI. This writes it to `dist/`:
54
+
55
+ ```sh
56
+ pnpm build
57
+ ```
58
+
59
+ 3. Run `init` with the built CLI:
60
+
61
+ ```sh
62
+ node dist/cli.mjs init
63
+ ```
64
+
65
+ `init` copies the built engine into `~/.hookmux`, writes a launcher script there, and asks which agents to wire. Your existing hooks stay as they are. It then offers to install the plugins that ship with hookmux and the authoring skill, which teaches your agent to write plugins. The agents run the local launcher, never `npx`, so a hook never waits on the network.
66
+
67
+ Until the npm release exists, there is no `hookmux` command on your `PATH`. Run every command in these docs as `node /path/to/hookmux/dist/cli.mjs <command>`, or add a shell alias:
68
+
69
+ ```sh
70
+ alias hookmux='node /path/to/hookmux/dist/cli.mjs'
71
+ ```
72
+
73
+ To update a source install, pull the latest changes, run `pnpm install` and `pnpm build` again, then run `init` again. A re-run updates the engine and the hosts it already wired.
74
+
75
+ ### Install from npm (not available yet)
76
+
77
+ Once the package is published, this is the install:
78
+
79
+ ```sh
80
+ npx hookmux init
81
+ ```
82
+
83
+ Or install the CLI globally first:
84
+
85
+ ```sh
86
+ npm i -g hookmux
87
+ hookmux init
88
+ ```
89
+
90
+ These commands work only after the release. As of this writing the package is not on npm, so use the source install above.
91
+
92
+ ### Choose the agents
93
+
94
+ Run `init` in a terminal and it asks about each agent it detects. To skip the questions, pass the agents yourself:
95
+
96
+ ```sh
97
+ hookmux init --host claude-code --host codex
98
+ hookmux init --yes
99
+ ```
100
+
101
+ `--host <id>` wires one agent and can repeat. `--yes` wires every detected agent. Without a terminal, `init` needs one of the two. The agent ids are `claude-code`, `codex`, `gemini-cli`, `qwen-code`, `droid`, `qoder`, `codebuddy` and `opencode`; see [Supported agents](docs/hosts.md). `--no-skill` and `--no-bundled` leave out the authoring skill and the bundled plugins.
102
+
103
+ ### Check the install
104
+
105
+ ```sh
106
+ hookmux doctor
107
+ ```
108
+
109
+ `doctor` checks Node, the engine, the launcher, every agent you wired (including a real launcher run), your plugins and the log. Add `--fix` to let it repair what is safe to repair.
110
+
111
+ ### Uninstall
112
+
113
+ ```sh
114
+ hookmux uninstall
115
+ ```
116
+
117
+ `uninstall` removes only hookmux's own hook entries and leaves your other hooks alone. Your plugins, config and logs stay in `~/.hookmux`. Add `--purge` to delete that folder too; it asks first unless you pass `--yes`. If you installed the CLI with npm, also run `npm uninstall -g hookmux`.
118
+ <!-- docs:end -->
119
+
120
+ ## Write your first plugin
121
+
122
+ <!-- docs:begin quickstart.md -->
123
+ This walkthrough builds a plugin that stops any prompt that looks like it contains an AWS key or a GitHub token, then checks it without opening an agent. It assumes you have already run `hookmux init`; see [Install](docs/install.md).
124
+
125
+ 1. Create the plugin folder:
126
+
127
+ ```sh
128
+ hookmux new no-secrets
129
+ ```
130
+
131
+ 2. Replace `no-secrets/plugin.toml` with:
132
+
133
+ ```toml
134
+ schema = 1
135
+ id = "no-secrets"
136
+ events = ["prompt.submit"]
137
+ phase = "guard"
138
+ when = "secret_shape"
139
+
140
+ [checks.secret_shape]
141
+ kind = "regex"
142
+ patterns = ['AKIA[0-9A-Z]{16}', 'ghp_[A-Za-z0-9]{36}']
143
+
144
+ [[then]]
145
+ effect = "block"
146
+ reason = "The prompt looks like it contains a credential. Remove it and send again."
147
+ ```
148
+
149
+ 3. Install it and turn it on:
150
+
151
+ ```sh
152
+ hookmux add ./no-secrets
153
+ hookmux promote no-secrets
154
+ ```
155
+
156
+ hookmux runs a plugin only after you approve it. `promote` shows what the plugin is allowed to do (block, add context, run scripts) and asks you to type `y`, so an agent cannot switch on code that runs on every prompt without you. Run it in your own terminal.
157
+
158
+ 4. Check what it decides for a prompt, without opening an agent:
159
+
160
+ ```sh
161
+ hookmux explain "deploy with AKIAIOSFODNN7EXAMPLE"
162
+ ```
163
+
164
+ Every agent you set up with `init` now refuses that prompt and shows the reason.
165
+
166
+ If you run hookmux from a source checkout, replace `hookmux` in these commands with `node /path/to/hookmux/dist/cli.mjs`, as described in [Install](docs/install.md).
167
+
168
+ You can also ask your agent to write a plugin for you, for example "make a hook that reminds me to run the tests before a release". hookmux installs an authoring skill into each agent that walks it through writing, testing and installing the plugin. The agent installs the plugin in shadow mode, where it runs and is logged but adds nothing, and you approve it when you are ready.
169
+
170
+ To see what each part of the manifest means, read [How plugins decide](docs/how-plugins-decide.md). To add test cases, read [Test a plugin](docs/testing.md).
171
+ <!-- docs:end -->
172
+
173
+ ## Install and share plugins
174
+
175
+ <!-- docs:begin plugin-sources.md -->
176
+ `hookmux add` installs plugins from a local folder or a git repository. If you maintain a hook, the same command lets other people install yours.
177
+
178
+ ### Install plugins other people wrote
179
+
180
+ ```sh
181
+ hookmux add owner/repo --list # see what the repository contains
182
+ hookmux add owner/repo # install its plugins
183
+ hookmux promote <id> # approve each one you want on
184
+ ```
185
+
186
+ `add` finds plugins at the repository root and under `plugins/`, `hookmux/` and `skills/*/hookmux/`. Other sources are a full https or SSH git URL, a `@ref` suffix for a branch or tag, and a GitHub `tree/<ref>/<path>` link. Installed plugins stay untrusted until you promote them. Use `--plugin <id>` to install only some of a repository's plugins, and `--shadow` to install one that runs and is logged but adds nothing.
187
+
188
+ Read a plugin's `plugin.toml` before you promote it. `promote` also lists what the plugin can do and which files it covers.
189
+
190
+ ### Install a plugin someone sent you
191
+
192
+ A plugin author may send you one line to run, or a sentence to paste to your coding agent. Both do the same three things: set up hookmux if you do not have it yet, copy the plugin onto your machine and ask whether to turn it on. The plugin stays off until you say yes.
193
+
194
+ ```sh
195
+ npx -y hookmux install owner/name
196
+ ```
197
+
198
+ `npx` runs hookmux without installing it first, and works once hookmux is published on npm. It needs Node.js 22 or later. If you paste the line to your agent, the agent runs the command and shows you what it prints, but it cannot answer for you.
199
+
200
+ What it prints is a card. It names the plugin, says where it came from, how often it runs and what it can do. Each thing it can do carries a risk word:
201
+
202
+ - `high` means it can run code as you or stop your work: it runs a script, or it can stop a tool call or discard your prompt.
203
+ - `medium` means it reaches further than reading: it adds text the agent reads and may follow, sends your prompt or tool details to your model provider, or passes an environment variable to its script.
204
+ - `low` means it only shows you a message.
205
+
206
+ Approve a `high` line only when you trust where the plugin came from.
207
+
208
+ You answer in one of two ways:
209
+
210
+ - At your own terminal, `hookmux install` shows the card and asks you to type `y`.
211
+ - When your agent runs it, the agent shows you the card and a four-character code. Reply with `approve K7Q2` (using your code) in your next message. hookmux sees your reply and tells the agent to finish.
212
+
213
+ [Safety](docs/safety.md) says what each of these proves and what it does not.
214
+
215
+ To undo it, run `hookmux disable <id>` to turn the plugin off and keep it, or `hookmux remove <id>` to delete it.
216
+
217
+ ### Share a plugin you wrote
218
+
219
+ If you maintain a hook for one agent, publishing it as a hookmux plugin lets it run in every agent hookmux supports. You describe when it fires and what it does; hookmux handles each agent's config file, payload and output format.
220
+
221
+ Logic that needs code goes in a script check. hookmux runs the script from your plugin folder, in the agent's working folder, with the event as JSON on stdin. The script answers with exit code 0 (true) or 1 (false), or prints `{"value": true, "evidence": "..."}`, and effect text can quote the evidence with `{evidence.<check>}`.
222
+
223
+ This plugin tells the agent which git branch it is on when a session starts:
224
+
225
+ ```toml
226
+ # branch-note/plugin.toml
227
+ schema = 1
228
+ id = "branch-note"
229
+ events = ["session.start"]
230
+ phase = "enrich"
231
+ origins = ["unknown"]
232
+ when = "on_branch"
233
+
234
+ [checks.on_branch]
235
+ kind = "script"
236
+ command = "branch.sh"
237
+
238
+ [[then]]
239
+ effect = "inject"
240
+ text = "You are on the git branch {evidence.on_branch}."
241
+ ```
242
+
243
+ ```sh
244
+ #!/bin/sh
245
+ # branch-note/branch.sh: exit 1 (false) outside a git checkout.
246
+ branch=$(git branch --show-current 2>/dev/null)
247
+ [ -n "$branch" ] || exit 1
248
+ printf '{"value": true, "evidence": "%s"}\n' "$branch"
249
+ ```
250
+
251
+ To ship it:
252
+
253
+ 1. Add a `tests.toml` with cases that should fire and cases that should stay silent, and run `hookmux test ./branch-note --run-scripts`.
254
+ 2. Run `hookmux validate ./branch-note` to check the manifest.
255
+ 3. Push the folder to a git repository. People install it with `hookmux add you/your-repo` and approve it with `hookmux promote branch-note`.
256
+
257
+ The [plugin.toml reference](docs/plugins.md) lists every manifest key, check kind, effect and template placeholder. `hookmux schema --json` prints the same data for tools. [Test a plugin](docs/testing.md) explains the test cases.
258
+ <!-- docs:end -->
259
+
260
+ ## For plugin creators: a one-line install
261
+
262
+ You can publish a plugin so that people install hookmux and your plugin with one line, and never have to learn how hookmux works.
263
+
264
+ 1. Scaffold a plugin that is also a repository:
265
+
266
+ ```sh
267
+ hookmux new my-plugin --template tool-guard --repo you/my-plugin
268
+ ```
269
+
270
+ `--template` picks a starting point (`prompt-context`, `tool-guard` or `session-note`). `--repo` adds a `README.md` with the install line and a card showing what your users will approve, and a CI workflow that runs `validate` and `test`.
271
+
272
+ 2. Edit `plugin.toml` and `tests.toml`, then check them on your machine. The generated CI runs the same two commands on every push:
273
+
274
+ ```sh
275
+ hookmux validate ./my-plugin
276
+ hookmux test ./my-plugin --run-scripts
277
+ ```
278
+
279
+ 3. Push the folder to GitHub. Put this install line in your README:
280
+
281
+ ```sh
282
+ npx -y hookmux install you/my-plugin
283
+ ```
284
+
285
+ `npx` works once hookmux is published on npm.
286
+
287
+ 4. Give your users a sentence to paste to their coding agent:
288
+
289
+ ```text
290
+ Install the my-plugin plugin with hookmux: run `npx -y hookmux install you/my-plugin`, show me the approval card it prints word for word, and wait for my answer.
291
+ ```
292
+
293
+ Here is what your users see. The command prints a card with what your plugin does and a risk word on each thing it can do. At a terminal, the user types `y` to turn it on. When their agent runs the line, the agent shows them the card and a short code, and the user replies with the code. The README you scaffolded shows the card, so you can check it matches what you meant to ask for.
294
+
295
+ Your plugin stays off until the user approves. A change you publish later needs a new approval, unless the user granted a standing one for your plugin (see [Safety](#safety)). The [agent notes](docs/hosts.md) list which clients use which approval.
296
+
297
+ ## Commands
298
+
299
+ | Command | What it does |
300
+ | --------------------------------------------- | -------------------------------------------------------------------- |
301
+ | `hookmux init` | Installs hookmux and adds its hook to the agents you choose |
302
+ | `hookmux uninstall` | Removes hookmux's hook from every agent config |
303
+ | `hookmux sync` | Updates the agent configs to match the events your plugins use |
304
+ | `hookmux new <id>` | Creates a plugin folder; `--template` and `--repo` shape it |
305
+ | `hookmux validate <dir>` | Checks a plugin folder without installing it |
306
+ | `hookmux test <id or dir>` | Runs a plugin's `tests.toml` cases |
307
+ | `hookmux install <source>` | Sets up hookmux, adds a plugin and asks you to approve it |
308
+ | `hookmux add <source>` | Installs plugins from a folder or git repository |
309
+ | `hookmux promote <id>` | Approves a plugin and turns it on; asks you to confirm |
310
+ | `hookmux promote <id> --standing` | Also lets later `hookmux add` updates of it go live without asking |
311
+ | `hookmux remove <id>` | Uninstalls a plugin |
312
+ | `hookmux enable <id>`, `hookmux disable <id>` | Turns a plugin on or off |
313
+ | `hookmux list` | Lists installed plugins and their status; `--json` for scripts |
314
+ | `hookmux explain "<prompt>"` | Shows how every installed plugin decides on a prompt |
315
+ | `hookmux doctor` | Reports problems with the install, the agent configs and the plugins |
316
+ | `hookmux log on`, `hookmux log off` | Turns the decision log on or off |
317
+ | `hookmux schema --json` | Prints the manifest schema, check kinds, effects and agents |
318
+
319
+ `hookmux help` lists the commands in your installed version. The [command reference](docs/cli.md) covers every flag.
320
+
321
+ ## Safety
322
+
323
+ <!-- docs:begin safety.md -->
324
+ A hook runs on every prompt or tool call, so hookmux is built to fail quietly, to run only code you approved, and to keep what it records to a minimum. This page lists what it guarantees and where the limits are.
325
+
326
+ - A broken hook never breaks your agent. If Node or hookmux is missing, fails, hangs or runs past its time limit, the hook prints nothing and exits 0, which every agent reads as "no opinion". A check that errors or times out counts as unknown and never blocks. Because a guard that stops running also stops blocking, each session start shows you a notice naming any guard plugin that is waiting for approval or does not load.
327
+ - Approvals are pinned to the files. `promote` records a SHA-256 hash of the plugin folder and the capabilities it has. If a file changes afterwards, whether by you, an agent or an update, the plugin stops running until you approve it again. A plugin you change often can get a standing approval (`hookmux promote <id> --standing`): later `hookmux add` updates go live without asking while they need no new capability. Anyone who can run `hookmux add`, agents included, can then replace its files within those capabilities. `hookmux promote <id> --end-standing` ends it.
328
+ - Approval needs you. `promote` asks you to type `y`, has no `--yes` flag, and refuses when stdin is not a terminal or when it sees the environment an agent gives the commands it runs. In Claude Code, an agent that runs `hookmux promote <id>` gets Claude Code's own permission prompt, and approving that prompt turns the plugin on. This stops an agent from turning on a plugin because of an injected instruction or by accident. It is not a sandbox: a process running as your user can still edit `~/.hookmux` directly.
329
+ - Previews run no unapproved code. `hookmux test` and `hookmux explain --all` skip the scripts of plugins you have not approved unless you pass `--run-scripts`.
330
+ - Shadow mode lets you try a plugin safely. A plugin added with `--shadow` (or `shadow = true`) runs and is logged, but adds nothing to what the agent sees.
331
+ - Blocks need a rule. By default a block needs a check that is not model-backed to agree, so a model's misreading cannot discard your prompt.
332
+ - No telemetry. hookmux collects no usage data.
333
+ - Private logs. The decision log is off until you run `hookmux log on`. It keeps a short hash and the length of each prompt, and stores prompt text only when you also pass `--prompts`. It rotates at 1 MiB and keeps one previous file.
334
+ <!-- docs:end -->
335
+
336
+ ## Troubleshooting
337
+
338
+ <!-- docs:begin troubleshooting.md -->
339
+ Start with `hookmux doctor`, then use `explain` and the log to see why a plugin did or did not fire.
340
+
341
+ - Run `hookmux doctor` first. It reports problems with the install, the agent configs and your plugins. `hookmux doctor --fix` repairs what is safe to repair.
342
+ - To see why a plugin did or did not fire, run `hookmux explain "<the prompt>"`.
343
+ - To trace real hook runs, turn the log on, reproduce the problem, then read `~/.hookmux/logs/hookmux.log`:
344
+
345
+ ```sh
346
+ hookmux log on
347
+ # ...use your agent...
348
+ hookmux log off
349
+ ```
350
+
351
+ - To switch hookmux off for one session without uninstalling it, start the agent with `HOOKMUX_DISABLE=1` in its environment. Guard plugins keep running, because a session can set that variable itself; turn one off with `hookmux disable <id>`, which the next session start reports.
352
+ <!-- docs:end -->
353
+
354
+ ## Supported agents
355
+
356
+ <details>
357
+ <summary>Agents, events and what a plugin can do in each</summary>
358
+
359
+ hookmux uses four events across agents: `prompt.submit` (you send a prompt), `session.start`, `tool.before` and `tool.after`. A plugin's effects are `inject` (add text for the agent), `block` and `notify` (show you a message). Where an agent cannot block on an event, a block becomes a notice.
360
+
361
+ <!-- hosts:begin -->
362
+ <!-- Generated by scripts/gen-skill-refs.ts from src/hosts. Do not edit; run `pnpm gen:refs`. -->
363
+ | Host | `prompt.submit` | `session.start` | `tool.before` | `tool.after` |
364
+ | -------------- | --------------------- | --------------- | --------------------- | --------------------- |
365
+ | Claude Code | inject, block, notify | inject, notify | inject, block, notify | inject, block, notify |
366
+ | CodeBuddy Code | inject, block, notify | inject, notify | inject, block, notify | inject, notify |
367
+ | Codex | inject, block, notify | inject, notify | inject, block, notify | inject, block, notify |
368
+ | Factory Droid | inject, block, notify | inject, notify | block, notify | inject, block, notify |
369
+ | Gemini CLI | inject, block, notify | inject, notify | block, notify | inject, block, notify |
370
+ | opencode | inject, notify | inject, notify | block, notify | inject, notify |
371
+ | Qoder CLI | inject, block, notify | inject, notify | inject, block, notify | inject, notify |
372
+ | Qwen Code | inject, block, notify | inject, notify | inject, block, notify | inject, block, notify |
373
+ <!-- hosts:end -->
374
+
375
+ Tested versions:
376
+
377
+ - Claude Code 2.1.325 and Codex 0.167.1 have been run live: adding context and blocking a prompt both work.
378
+ - The Gemini CLI adapter was written from the Gemini CLI source (v0.68.0). The Qwen Code (0.28.0), Factory Droid (1.16.0), Qoder CLI (1.1.94) and CodeBuddy Code (2.185.0) adapters were written from each client's hooks documentation. All five are covered by tests but have not been run against a live client yet.
379
+ - opencode 1.19.6 has been run live with a scripted model: context on prompts, at session start and after tool calls, and blocking a tool call, all work. hookmux installs a small plugin file there instead of a hook entry.
380
+ - Cursor and Devin CLI read Claude Code's `~/.claude/settings.json`, so they run hookmux's Claude Code entries too. That path is untested.
381
+
382
+ Codex runs a new or changed hook entry only after it is approved. `init`, `sync` and every command that changes a plugin approve hookmux's own entries through `codex app-server` and leave every other hook as it was; if that fails, approve them in Codex's `/hooks` screen.
383
+
384
+ [Supported agents](docs/hosts.md) covers each agent's config file, event names and limits.
385
+
386
+ </details>
387
+
388
+ ## Documentation
389
+
390
+ The docs are published at [docs.khangle.dev/hookmux](https://docs.khangle.dev/hookmux). The pages live in `docs/`:
391
+
392
+ - [Install](docs/install.md) and [Write your first plugin](docs/quickstart.md)
393
+ - [How plugins decide](docs/how-plugins-decide.md) and [Test a plugin](docs/testing.md)
394
+ - [Command reference](docs/cli.md) and [plugin.toml reference](docs/plugins.md)
395
+ - [Supported agents](docs/hosts.md)
396
+ - [Use hookmux with coding agents](docs/agents.md)
397
+ - [Design notes](docs/design.md)
398
+ - [Contributing](CONTRIBUTING.md)
399
+ - [Security policy](SECURITY.md)
400
+
401
+ ## License
402
+
403
+ MIT
@@ -0,0 +1 @@
1
+ import{addFromSource,run,usage}from"./chunk-6GL55FEQ.mjs";import"./chunk-DJHE642J.mjs";import"./chunk-CA2GWCFP.mjs";import"./chunk-IAGBX723.mjs";import"./chunk-CZY5UAXM.mjs";import"./chunk-5GQP3BA6.mjs";import"./chunk-CSXS5D2F.mjs";import"./chunk-RG3EOP4J.mjs";import"./chunk-G6SJQTFF.mjs";import"./chunk-BF25CRHJ.mjs";import"./chunk-XPLEWNGF.mjs";import"./chunk-IJHUIMJA.mjs";import"./chunk-K73ZPBFM.mjs";import"./chunk-OXHAGFXG.mjs";import"./chunk-2ZCM3JZR.mjs";import"./chunk-7Z3AMI24.mjs";import"./chunk-ZNEBE4WO.mjs";import"./chunk-OYGOSD6V.mjs";import"./chunk-AHPMRYYF.mjs";export{addFromSource,run,usage};
@@ -0,0 +1,3 @@
1
+ import{MAX_MATCH_CHARS,clip,compilePatterns,isKnownField,readField,regexFlags,registerCheck}from"./chunk-ZNEBE4WO.mjs";import{homePaths,writeFileAtomic}from"./chunk-OYGOSD6V.mjs";var ALL_EVENTS=["prompt.submit","session.start","tool.before","tool.after"],PROMPT=["prompt.submit"],TOOLS=["tool.before","tool.after"],BLOCKING=["prompt.submit","tool.before","tool.after"],DEFINITIONS=[{id:"host.version",meaning:"The payload reports the client version",events:ALL_EVENTS,caveat:"the client reports no version, so a version range is unknown"},{id:"prompt.origin",meaning:"hookmux can tell user prompts from system or agent sends",events:PROMPT,caveat:"system and agent sends look like user prompts"},{id:"tool.file-path",meaning:"Every file-edit tool carries tool_input.file_path",events:TOOLS,caveat:"some file edits carry no file_path to match on"},{id:"inject.markup",meaning:"< and > in added context reach the model unescaped",events:ALL_EVENTS,effect:"inject",caveat:"markup in added context may be escaped"},{id:"inject.inline",meaning:"All added context up to the context limit is shown inline",events:ALL_EVENTS,effect:"inject",caveat:"long added context may be moved out of the prompt"},{id:"inject.before-call",meaning:"The model sees added context before the tool runs",events:["tool.before"],effect:"inject",caveat:"added context may reach the model only with the tool result"},{id:"block.prevents",meaning:"A block stops the action before it happens",events:BLOCKING,effect:"block",caveat:"the tool already ran"},{id:"block.reason-to-agent",meaning:"The agent sees the block reason",events:BLOCKING,effect:"block",caveat:"the agent may not see the block reason"},{id:"block.suppress-prompt",meaning:"suppress_original_prompt is honoured",events:PROMPT,effect:"block",caveat:"the blocked prompt may stay in the history"}],FEATURES=DEFINITIONS;function isFeatureId(id){return FEATURES.some(f=>f.id===id)}function cells(value,...events){return Object.fromEntries(events.map(e=>[e,value]))}function isDeclared(host,feature,event){return!feature.events.includes(event)||host.nativeEvents[event]===null?!1:feature.effect===void 0||host.supports[event].includes(feature.effect)}function featuresFor(host,event){let facts={};if(host.nativeEvents[event]===null)return facts;for(let feature of FEATURES){if(!feature.events.includes(event))continue;let id=feature.id;facts[id]=isDeclared(host,feature,event)?host.features[id][event]??null:!1}return facts}function fieldProblems(spec){return isKnownField(spec.field)?[]:[`field '${String(spec.field)}' is not a known event field`]}function firstMatch(patterns,text){for(let re of patterns){let m=re.exec(text);if(m)return m[0]}return null}function matchAll(patterns,text,mode){if(mode==="all"){let hits=patterns.map(re=>re.exec(text)?.[0]??null);return hits.every(h=>h!==null)?{value:!0,evidence:clip(hits.join(" "))}:{value:!1}}let hit=firstMatch(patterns,text);return hit===null?{value:!1}:{value:!0,evidence:clip(hit)}}registerCheck({kind:"regex",summary:"True when any (or all) of the patterns match the field.",options:{patterns:"list of regex sources (max 300 chars each)",flags:'subset of "imsu", default "iu"',match:'"any" (default) or "all"',field:'event field to read, default "prompt"'},tier:0,output:"bool",modelBacked:!1,validate(spec){let problems=fieldProblems(spec);return compilePatterns(spec.patterns,regexFlags(spec.flags,problems),"patterns",problems),spec.match!==void 0&&spec.match!=="any"&&spec.match!=="all"&&problems.push("match must be 'any' or 'all'"),problems},run(spec,ctx){let text=readField(ctx.event,spec.field);if(text===null)return{value:!1};let patterns=compilePatterns(spec.patterns,regexFlags(spec.flags,[]),"patterns",[]);return matchAll(patterns,text,spec.match)}});function escapeRegex(word){return word.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function keywordPatterns(spec,problems){let words=spec.words;if(!Array.isArray(words)||words.length===0||words.some(w=>typeof w!="string"||w===""))return problems.push("words must be a non-empty list of strings"),[];let wholeWord=spec.whole_word!==!1,sources=words.map(w=>wholeWord?`(?<![\\p{L}\\p{N}_])${escapeRegex(w)}(?![\\p{L}\\p{N}_])`:escapeRegex(w)),flags=spec.case_sensitive===!0?"u":"iu";return compilePatterns(sources,flags,"words",problems)}registerCheck({kind:"keywords",summary:"True when any (or all) of the words appear as whole words, case-insensitive by default.",options:{words:"list of literal words or phrases",whole_word:"default true",case_sensitive:"default false",match:'"any" (default) or "all"',field:'event field to read, default "prompt"'},tier:0,output:"bool",modelBacked:!1,validate(spec){let problems=fieldProblems(spec);return keywordPatterns(spec,problems),problems},run(spec,ctx){let text=readField(ctx.event,spec.field);return text===null?{value:!1}:matchAll(keywordPatterns(spec,[]),text,spec.match)}});registerCheck({kind:"regex_groups",summary:"Named groups of patterns; true when every group in at least one fire_when combination matches.",options:{groups:"table of group name to pattern list",fire_when:"list of group-name lists",flags:'subset of "imsu", default "iu"',field:'event field to read, default "prompt"'},tier:0,output:"bool",modelBacked:!1,validate(spec){let problems=fieldProblems(spec),groups=spec.groups;if(groups===null||typeof groups!="object"||Array.isArray(groups))return[...problems,"groups must be a table of pattern lists"];let flags=regexFlags(spec.flags,problems);for(let[name,patterns]of Object.entries(groups))compilePatterns(patterns,flags,`groups.${name}`,problems);let combos=spec.fire_when;if(!Array.isArray(combos)||combos.length===0)problems.push("fire_when must be a non-empty list of group-name lists");else for(let combo of combos){if(!Array.isArray(combo)||combo.length===0){problems.push("each fire_when entry must be a non-empty list");continue}for(let name of combo)(typeof name!="string"||!(name in groups))&&problems.push(`fire_when names unknown group '${name}'`)}return problems},run(spec,ctx){let text=readField(ctx.event,spec.field);if(text===null)return{value:!1};let flags=regexFlags(spec.flags,[]),hits=new Map;for(let[name,patterns]of Object.entries(spec.groups)){let hit=firstMatch(compilePatterns(patterns,flags,name,[]),text);hit!==null&&hits.set(name,hit)}for(let combo of spec.fire_when)if(combo.every(name=>hits.has(name)))return{value:!0,evidence:clip(combo.map(name=>hits.get(name)).join(" + "))};return{value:!1}}});import{existsSync}from"node:fs";import{isAbsolute,resolve}from"node:path";function stringList(value){return Array.isArray(value)&&value.length>0&&value.every(v=>typeof v=="string"&&v!=="")}function requireList(spec,key,problems,optional=!1){optional&&spec[key]===void 0||stringList(spec[key])||problems.push(`${key} must be a non-empty list of strings`)}function compareVersions(a,b){let pa=a.split(/[.+-]/).map(p=>Number.parseInt(p,10)||0),pb=b.split(/[.+-]/).map(p=>Number.parseInt(p,10)||0);for(let i=0;i<Math.max(pa.length,pb.length);i++){let d=(pa[i]??0)-(pb[i]??0);if(d!==0)return Math.sign(d)}return 0}var VERSION_RANGE=/^(<=|>=|<|>|=)?\s*(\d+(?:\.\d+)*)$/;function satisfiesRange(version,range){return range.trim().split(/\s+/).every(part=>{let m=VERSION_RANGE.exec(part);if(!m)return!1;let cmp=compareVersions(version,m[2]);switch(m[1]??"="){case"<":return cmp<0;case"<=":return cmp<=0;case">":return cmp>0;case">=":return cmp>=0;default:return cmp===0}})}function allOf(parts){return parts.includes(!1)?!1:parts.includes(null)?null:!0}function featureProblems(spec,key,problems){if(requireList(spec,key,problems,!0),!!stringList(spec[key]))for(let id of spec[key])isFeatureId(id)||problems.push(`${key}: unknown feature '${id}'`)}function contradictions(spec){return!stringList(spec.features)||!stringList(spec.lacks)?[]:spec.features.filter(id=>spec.lacks.includes(id))}registerCheck({kind:"host",summary:"True when the agent client matches: its id, a version range, the effects it supports on this event, or the features it has (features) or lacks (lacks). Unknown version or feature gives unknown.",options:{id:'list of host ids, e.g. ["codex"]',version:'range such as ">=0.40" or ">=1.2 <2"',supports:"list of effects that must be supported here",features:'list of feature ids that must all be yes here, e.g. ["inject.markup"]; unknown gives unknown',lacks:'list of feature ids that must all be no here, e.g. ["block.prevents"]; unknown gives unknown'},tier:0,output:"bool",modelBacked:!1,validate(spec){let problems=[],keys=["id","version","supports","features","lacks"];keys.every(k=>spec[k]===void 0)&&problems.push(`host check needs at least one of ${keys.join(", ")}`),requireList(spec,"id",problems,!0),requireList(spec,"supports",problems,!0),featureProblems(spec,"features",problems),featureProblems(spec,"lacks",problems);for(let id of contradictions(spec))problems.push(`${id} is in both features and lacks`);return spec.version!==void 0&&(typeof spec.version=="string"&&spec.version.trim().split(/\s+/).every(p=>VERSION_RANGE.test(p))||problems.push("version must be a range like '>=0.40' or '>=1.2 <2'")),problems},run(spec,ctx){let host=ctx.event.host,parts=[];spec.id!==void 0&&parts.push(spec.id.includes(host.id)),spec.supports!==void 0&&parts.push(spec.supports.every(e=>host.supports.includes(e))),spec.version!==void 0&&parts.push(host.version===null?null:satisfiesRange(host.version,spec.version));let fact=id=>host.features[id]??null;for(let id of spec.features??[])parts.push(fact(id));for(let id of spec.lacks??[]){let value=fact(id);parts.push(value===null?null:!value)}return{value:allOf(parts)}}});registerCheck({kind:"origin",summary:"True when the prompt origin is one of the listed values.",options:{is:'list of "user", "system", "unknown"'},tier:0,output:"bool",modelBacked:!1,validate(spec){let problems=[];return requireList(spec,"is",problems),problems},run(spec,ctx){return{value:spec.is.includes(ctx.event.origin)}}});registerCheck({kind:"tool",summary:"True when the tool call names one of these tools (canonical or host name).",options:{names:'list such as ["Bash", "Write"]'},tier:0,output:"bool",modelBacked:!1,validate(spec){let problems=[];return requireList(spec,"names",problems),problems},run(spec,ctx){let tool=ctx.event.tool;if(!tool)return{value:!1};let names=spec.names;return{value:names.includes(tool.canonicalName)||names.includes(tool.name),evidence:tool.canonicalName}}});function globToRegex(glob){let out="";for(let i=0;i<glob.length;i++){let c=glob[i];c==="*"&&glob[i+1]==="*"?(out+=".*",i++,glob[i+1]==="/"&&i++):c==="*"?out+="[^/]*":c==="?"?out+="[^/]":out+=c.replace(/[.+^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${out}$`)}function expandHome(pattern){return pattern.startsWith("~/")?`${process.env.HOME??""}${pattern.slice(1)}`:pattern}registerCheck({kind:"cwd_glob",summary:"True when the working folder matches one of the globs.",options:{patterns:"globs with *, ** and ?; ~/ expands to home"},tier:0,output:"bool",modelBacked:!1,validate(spec){let problems=[];return requireList(spec,"patterns",problems),problems},run(spec,ctx){let cwd=ctx.event.cwd.replaceAll("\\","/"),hit=spec.patterns.find(p=>globToRegex(expandHome(p)).test(cwd));return hit?{value:!0,evidence:hit}:{value:!1}}});registerCheck({kind:"path_exists",summary:"True when any (or all) paths exist, relative to the working folder.",options:{paths:"list of paths",match:'"any" (default) or "all"'},tier:0,output:"bool",modelBacked:!1,validate(spec){let problems=[];return requireList(spec,"paths",problems),spec.match!==void 0&&spec.match!=="any"&&spec.match!=="all"&&problems.push("match must be 'any' or 'all'"),problems},run(spec,ctx){let paths=spec.paths.map(p=>{let expanded=expandHome(p);return isAbsolute(expanded)?expanded:resolve(ctx.event.cwd,expanded)}),found=paths.filter(p=>existsSync(p));return(spec.match==="all"?found.length===paths.length:found.length>0)?{value:!0,evidence:found[0]??""}:{value:!1}}});import{createHash}from"node:crypto";import{readFileSync,rmSync}from"node:fs";import{join}from"node:path";var COOLDOWN_MS=3e4;function breakerDir(){return join(homePaths().root,"state","providers")}function breakerFile(dir,name){return join(dir,`${createHash("sha256").update(name).digest("hex").slice(0,32)}.json`)}function readUntil(file){try{let until=JSON.parse(readFileSync(file,"utf8"))?.until;return typeof until=="number"?until:void 0}catch{return}}function isCoolingDown(name,now=Date.now(),dir=breakerDir()){let until=readUntil(breakerFile(dir,name));return until!==void 0&&now<until}function recordFailure(name,now=Date.now(),dir=breakerDir()){try{writeFileAtomic(breakerFile(dir,name),JSON.stringify({until:now+COOLDOWN_MS}))}catch{}}function recordSuccess(name,dir=breakerDir()){let file=breakerFile(dir,name);if(readUntil(file)!==void 0)try{rmSync(file,{force:!0})}catch{}}function requestBody(provider,request){let system=`${request.instructions}
2
+
3
+ Classify the user's message as exactly one of these labels: ${JSON.stringify(request.labels)}. Reply only with JSON {"label": <one label>, "confidence": <number from 0 to 1>}.`;return{...provider.model?{model:provider.model}:{},temperature:0,messages:[{role:"system",content:system},{role:"user",content:request.text}],response_format:{type:"json_schema",json_schema:{name:"classification",strict:!0,schema:{type:"object",properties:{label:{type:"string",enum:request.labels},confidence:{type:"number"}},required:["label","confidence"],additionalProperties:!1}}}}}function parseJson(text){try{return JSON.parse(text)}catch{return null}}function parseClassification(body,labels){let content=body?.choices?.[0]?.message?.content;if(typeof content!="string")return null;let{label,confidence}=parseJson(content)??{};return typeof label!="string"||!labels.includes(label)||typeof confidence!="number"||!Number.isFinite(confidence)||confidence<0||confidence>1?null:{label,confidence}}function headers(provider){let key=provider.apiKeyEnv?process.env[provider.apiKeyEnv]:void 0;return{"content-type":"application/json",...key?{authorization:`Bearer ${key}`}:{}}}function isProviderFaultStatus(status){return status>=500||status===429}function envProxyActive(env=process.env,execArgv=process.execArgv){return env.NODE_USE_ENV_PROXY!==void 0&&env.NODE_USE_ENV_PROXY!==""?!0:execArgv.includes("--use-env-proxy")||(env.NODE_OPTIONS??"").split(/\s+/).includes("--use-env-proxy")}var PROXY_REFUSAL="an environment proxy is active (NODE_USE_ENV_PROXY or --use-env-proxy), so a local provider's prompt could leave the machine; unset it or set allow_remote = true";async function classifyOpenAICompat(provider,request,budget){if(provider.allowRemote!==!0&&envProxyActive())return{ok:!1,error:PROXY_REFUSAL,providerFault:!1};let ownTimeout=Math.max(1,Math.floor(provider.timeoutMs??800)),clipped=budget.remainingMs<ownTimeout,timeoutMs=clipped?Math.floor(budget.remainingMs):ownTimeout;if(budget.deadline.aborted||timeoutMs<=0)return{ok:!1,error:"deadline reached",providerFault:!1};let timeout=AbortSignal.timeout(timeoutMs);try{let response=await fetch(`${provider.url.replace(/\/+$/,"")}/chat/completions`,{method:"POST",headers:headers(provider),body:JSON.stringify(requestBody(provider,request)),redirect:"manual",signal:AbortSignal.any([budget.deadline,timeout])});if(response.status>=300&&response.status<400)return{ok:!1,error:"provider redirected; redirects are not followed",providerFault:!1};if(!response.ok)return{ok:!1,error:`provider returned HTTP ${response.status}`,providerFault:isProviderFaultStatus(response.status)};let parsed=parseClassification(parseJson(await response.text()),request.labels);return parsed?{ok:!0,...parsed}:{ok:!1,error:"provider returned no valid label and confidence",providerFault:!1}}catch(error){if(budget.deadline.aborted)return{ok:!1,error:"deadline reached",providerFault:!1};if(timeout.aborted)return{ok:!1,error:`provider timed out after ${timeoutMs} ms`,providerFault:!clipped};let code=error.cause?.code;return{ok:!1,error:`provider unreachable${typeof code=="string"?` (${code})`:""}`,providerFault:!0}}}var CLASSIFIERS={openai_compat:classifyOpenAICompat};function classifierFor(kind){return Object.hasOwn(CLASSIFIERS,kind)?CLASSIFIERS[kind]:void 0}var IPV4_LOOPBACK=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;function isLoopbackUrl(url){let host;try{host=new URL(url).hostname.toLowerCase()}catch{return!1}return host==="localhost"||host==="[::1]"||IPV4_LOOPBACK.test(host)}function remoteRefusal(name,provider){let protocol;try{protocol=new URL(provider.url).protocol}catch{return`provider '${name}' has an invalid url`}return protocol!=="http:"&&protocol!=="https:"?`provider '${name}' url must be http or https`:provider.allowRemote===!0||isLoopbackUrl(provider.url)?null:`provider '${name}' is not on this machine; set allow_remote = true under [providers.${name}] to send prompts to it`}var MIN_LABELS=2,MAX_LABELS=20,MAX_INSTRUCTIONS_CHARS=2e3,DEFAULT_MAX_CHARS=2e3;function unknown(error){return{value:null,error}}function labelProblems(spec){let labels=spec.labels;if(!Array.isArray(labels)||labels.length<MIN_LABELS||labels.length>MAX_LABELS||labels.some(l=>typeof l!="string"||l===""))return[`labels must be a list of ${MIN_LABELS} to ${MAX_LABELS} non-empty strings`];let problems=[];return new Set(labels).size!==labels.length&&problems.push("labels must be unique"),(typeof spec.target!="string"||!labels.includes(spec.target))&&problems.push("target must be one of the labels"),problems}function optionProblems(spec){let problems=[];(typeof spec.provider!="string"||spec.provider==="")&&problems.push("provider must name a [providers.<name>] table");let instructions=spec.instructions;typeof instructions!="string"||instructions.trim()===""?problems.push("instructions are required"):instructions.length>MAX_INSTRUCTIONS_CHARS&&problems.push(`instructions are longer than ${MAX_INSTRUCTIONS_CHARS} chars`),isKnownField(spec.field)||problems.push(`field '${String(spec.field)}' is not a known event field`);let max=spec.max_chars;return max!==void 0&&(!Number.isInteger(max)||max<1||max>MAX_MATCH_CHARS)&&problems.push(`max_chars must be a whole number from 1 to ${MAX_MATCH_CHARS}`),problems}function targetScore(label,confidence,target){return label===target?confidence:1-confidence}registerCheck({kind:"classify",summary:"Score from 0 to 1 that the field is the target label, decided by a configured model provider.",options:{provider:"name of a [providers.<name>] table in config.toml",labels:"list of 2 to 20 labels",target:"the label to score",instructions:"what the labels mean, at most 2000 chars",field:'event field to read, default "prompt"',max_chars:`characters of the field sent to the model, default ${DEFAULT_MAX_CHARS}`},tier:2,output:"score",modelBacked:!0,validate(spec){return[...optionProblems(spec),...labelProblems(spec)]},async run(spec,ctx){let name=spec.provider,provider=Object.hasOwn(ctx.settings.providers,name)?ctx.settings.providers[name]:void 0;if(!provider)return unknown(`provider '${name}' is not configured`);let classify=classifierFor(provider.kind);if(!classify)return unknown(`provider kind '${provider.kind}' is not supported`);let refusal=remoteRefusal(name,provider);if(refusal)return unknown(refusal);if(isCoolingDown(name))return unknown("provider cooling down");let text=readField(ctx.event,spec.field);if(text===null||text.trim()==="")return unknown("nothing to classify");let maxChars=spec.max_chars??DEFAULT_MAX_CHARS,outcome=await classify(provider,{labels:spec.labels,instructions:spec.instructions,text:text.slice(0,maxChars)},{deadline:ctx.signal,remainingMs:ctx.remainingMs()});return outcome.ok?(recordSuccess(name),{value:targetScore(outcome.label,outcome.confidence,spec.target)}):(outcome.providerFault&&recordFailure(name),unknown(outcome.error))}});export{FEATURES,cells,featuresFor};
@@ -0,0 +1 @@
1
+ var AGENT_ENV_MARKERS=["CLAUDECODE","CLAUDE_CODE_ENTRYPOINT","CODEX_SANDBOX","CODEX_SANDBOX_NETWORK_DISABLED","CODEX_THREAD_ID","CODEX_SESSION_ID","CODEX_TOOL_CALL_ID","CODEX_VERSION","GEMINI_CLI","OPENCODE"],MARKER_HOST={CLAUDECODE:"claude-code",CLAUDE_CODE_ENTRYPOINT:"claude-code",CODEX_SANDBOX:"codex",CODEX_SANDBOX_NETWORK_DISABLED:"codex",CODEX_THREAD_ID:"codex",CODEX_SESSION_ID:"codex",CODEX_TOOL_CALL_ID:"codex",CODEX_VERSION:"codex",GEMINI_CLI:"gemini-cli",OPENCODE:"opencode"};function agentMarker(env){return AGENT_ENV_MARKERS.find(name=>env[name]!==void 0&&env[name]!=="")}function agentHost(env){let marker=agentMarker(env);return marker===void 0?void 0:MARKER_HOST[marker]}function activationRefusal(ctx){if(ctx.assumeYes)return"yes-flag";if(agentMarker(ctx.env)!==void 0)return"agent";if(!ctx.interactive)return"no-terminal"}export{agentMarker,agentHost,activationRefusal};
@@ -0,0 +1,4 @@
1
+ import{compatLines,planPlugin}from"./chunk-DZU2NMID.mjs";import{loadDefaults}from"./chunk-CSXS5D2F.mjs";import{detail,printJson,say}from"./chunk-BF25CRHJ.mjs";import{UsageError,parseCommand}from"./chunk-XPLEWNGF.mjs";import{capabilitiesOf,hashPlugin,listPluginFiles,readConfig}from"./chunk-IJHUIMJA.mjs";import{MANIFEST_FILE,ManifestError,compileManifest,readManifest}from"./chunk-K73ZPBFM.mjs";import{ADAPTERS}from"./chunk-OXHAGFXG.mjs";import{homePaths}from"./chunk-OYGOSD6V.mjs";import{existsSync,statSync}from"node:fs";import{basename,dirname,resolve}from"node:path";var usage=`Usage: hookmux validate <path> [--json]
2
+
3
+ Checks a plugin folder (or its plugin.toml) the way 'hookmux add' would.
4
+ Exit 1 when it has problems.`;function validatePlugin(dir){let report={ok:!1,path:dir,id:null,problems:[],warnings:[],capabilities:[],compat:[]};try{listPluginFiles(dir),hashPlugin(dir);let raw=readManifest(dir);typeof raw.id=="string"&&(report.id=raw.id);let compiled=compileManifest(raw,dir,void 0,loadDefaults(readConfig(homePaths().config)));report.warnings=compiled.warnings,report.capabilities=capabilitiesOf(compiled.base,Object.values(compiled.variants)),report.compat=planPlugin(compiled,Object.values(ADAPTERS))}catch(error){report.problems=error instanceof ManifestError?error.problems:[error.message]}return report.ok=report.problems.length===0,report}async function run(argv){let parsed=parseCommand(argv,{json:{type:"boolean"}},usage,1);if(!parsed)return 0;let target=parsed.positionals[0];if(!target)throw new UsageError("name the plugin folder to validate");let dir=resolve(target);if(basename(dir)===MANIFEST_FILE&&(dir=dirname(dir)),!existsSync(dir)||!statSync(dir).isDirectory())throw new UsageError(`${target} is not a folder`);let report=validatePlugin(dir);if(parsed.values.json)return printJson(report),report.ok?0:1;if(report.ok){say("ok",`${report.id} is valid (${report.capabilities.join(", ")})`);for(let l of compatLines(report.compat))detail(l)}else say("fail",`${report.id??dir} has ${report.problems.length} problem(s)`,`fix them, then: hookmux validate ${target}`);for(let p of report.problems)detail(`\u2717 ${p}`);for(let w of report.warnings)detail(`! ${w}`);return report.ok?0:1}export{usage,validatePlugin,run};
@@ -0,0 +1,20 @@
1
+ import{applyStandingApprovals,promotePlugin}from"./chunk-DJHE642J.mjs";import{renderCardShort}from"./chunk-IAGBX723.mjs";import{PluginExistsError,discardStaged,discoverPlugins,placeStaged,stagePlugin}from"./chunk-CZY5UAXM.mjs";import{agentMarker}from"./chunk-5GQP3BA6.mjs";import{loadDefaults}from"./chunk-CSXS5D2F.mjs";import{isInteractive}from"./chunk-RG3EOP4J.mjs";import{syncAfterChange}from"./chunk-G6SJQTFF.mjs";import{detail,say}from"./chunk-BF25CRHJ.mjs";import{UsageError,parseCommand}from"./chunk-XPLEWNGF.mjs";import{cardFactsOf,readConfig,readFlagsForUpdate,readSources,writeFlags,writeSources}from"./chunk-IJHUIMJA.mjs";import{homePaths}from"./chunk-OYGOSD6V.mjs";import{existsSync as existsSync2}from"node:fs";import{relative}from"node:path";import{execFile}from"node:child_process";import{existsSync,mkdtempSync,rmSync,statSync}from"node:fs";import{tmpdir}from"node:os";import{join,resolve,sep}from"node:path";import{promisify}from"node:util";var run=promisify(execFile),CLONE_TIMEOUT_MS=12e4,GIT_SAFETY=["-c","core.hooksPath=/dev/null","-c","protocol.file.allow=user"];async function fetchSource(spec){if(spec.kind==="local"){if(!existsSync(spec.path)||!statSync(spec.path).isDirectory())throw new Error(`${spec.path} is not a folder`);return{root:spec.path,source:spec.path,ref:null,commit:null,cleanup:()=>{}}}let temp=mkdtempSync(join(tmpdir(),"hookmux-add-")),cleanup=()=>rmSync(temp,{recursive:!0,force:!0});try{let repo=join(temp,"repo");await git([...GIT_SAFETY,"clone","--depth","1","--no-recurse-submodules",...spec.ref?["--branch",spec.ref]:[],"--",spec.url,repo]);let commit=(await git(["-C",repo,"rev-parse","HEAD"])).trim()||null,root=spec.subpath?resolve(repo,spec.subpath):repo;if(!root.startsWith(repo+sep)&&root!==repo)throw new Error(`${spec.subpath} leaves the repository`);if(!existsSync(root))throw new Error(`${spec.subpath} does not exist in ${spec.url}`);return{root,source:spec.url,ref:spec.ref,commit,cleanup}}catch(error){throw cleanup(),error}}async function git(args){try{let{stdout}=await run("git",args,{env:{...process.env,GIT_TERMINAL_PROMPT:"0"},timeout:CLONE_TIMEOUT_MS,maxBuffer:4194304});return stdout}catch(error){let e=error;if(e.code==="ENOENT")throw new Error("git is not installed or not on PATH");let last=(e.stderr??"").trim().split(`
2
+ `).at(-1)||e.message;throw new Error(`git ${args.includes("clone")?"clone":args[2]} failed: ${last}`)}}import{homedir}from"node:os";import{isAbsolute,join as join2,resolve as resolve2}from"node:path";var SourceError=class extends Error{},GITHUB_SHORTHAND=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?(?:@(.+))?$/,SSH_URL=/^git@[A-Za-z0-9.-]+:[A-Za-z0-9._/-]+$/,GITHUB_TREE=/^\/([^/]+)\/([^/]+?)(?:\.git)?\/tree\/([^/]+)(?:\/(.+?))?\/?$/,SAFE_REF=/^[A-Za-z0-9][A-Za-z0-9._/-]*$/;function parseSource(text,exists){let value=text.trim();if(value==="")throw new SourceError("source is empty");let local=localPath(value);if(local!==null&&(exists(local)||/^(\.{1,2}\/|\/|~)/.test(value)))return{kind:"local",path:local};if(SSH_URL.test(value))return{kind:"git",url:value,ref:null,subpath:null};if(value.startsWith("https://"))return httpsSource(value);if(/^[a-z]+:\/\//i.test(value))throw new SourceError("only https:// and git@ URLs are supported");let short=GITHUB_SHORTHAND.exec(value);if(short)return{kind:"git",url:`https://github.com/${short[1]}/${short[2]}.git`,ref:checkRef(short[3]),subpath:null};throw new SourceError(`'${value}' is not a folder, owner/repo, https:// URL or git@ URL`)}function localPath(value){return value==="~"?homedir():value.startsWith("~/")?join2(homedir(),value.slice(2)):isAbsolute(value)||!value.includes("://")?resolve2(value):null}function httpsSource(value){let url;try{url=new URL(value)}catch{throw new SourceError(`'${value}' is not a valid URL`)}if(url.username||url.password)throw new SourceError("remove the credentials from the URL; private repos use your git credential helper");let tree=url.hostname==="github.com"?GITHUB_TREE.exec(url.pathname):null;return tree?{kind:"git",url:`https://github.com/${tree[1]}/${tree[2]}.git`,ref:checkRef(tree[3]),subpath:checkSubpath(tree[4])}:{kind:"git",url:value,ref:null,subpath:null}}function checkRef(ref){if(ref===void 0)return null;if(!SAFE_REF.test(ref)||ref.includes(".."))throw new SourceError(`'${ref}' is not a valid branch or tag name`);return ref}function checkSubpath(subpath){if(subpath===void 0||subpath==="")return null;let parts=decodeURIComponent(subpath).split("/");if(parts.some(p=>p===".."||p===""))throw new SourceError(`'${subpath}' is not a plain folder path`);return parts.join("/")}var usage=`Usage: hookmux add <source> [--plugin <id>]... [--shadow] [--list] [--force]
3
+
4
+ Copies plugins into the hookmux home and prints what each can do. They stay
5
+ untrusted until you approve them with hookmux promote, unless a standing
6
+ approval (hookmux promote <id> --standing) covers them.
7
+
8
+ Sources:
9
+ ./path or /path a local folder (an existing path always wins)
10
+ owner/repo[@ref] a GitHub repository
11
+ https://host/o/r(.git) any https git URL
12
+ https://github.com/o/r/tree/<ref>/<subpath>
13
+ git@host:o/r.git an SSH git URL (uses your git credentials)
14
+
15
+ Plugins are found at plugin.toml, plugins/*/, hookmux/*/ and skills/*/hookmux/.
16
+
17
+ --plugin <id> only these plugins (repeatable)
18
+ --shadow mark them shadow: evaluated and logged, output withheld
19
+ --list show what the source contains; install nothing
20
+ --force replace an installed plugin with the same id`;async function run2(argv){let parsed=parseCommand(argv,{plugin:{type:"string",multiple:!0},shadow:{type:"boolean"},list:{type:"boolean"},force:{type:"boolean"}},usage,1);if(!parsed)return 0;let sourceText=parsed.positionals[0];if(!sourceText)throw new UsageError("name a source: a folder, owner/repo or a git URL");let paths=homePaths(),plugins=parsed.values.plugin??[];if(parsed.values.list)return listSource(paths,sourceText,plugins);let result=await addFromSource(paths,sourceText,{plugins,force:parsed.values.force===!0,shadow:parsed.values.shadow===!0});if(!result)return 1;let canAsk=isInteractive()&&agentMarker(process.env)===void 0;for(let id of result.added.filter(a=>!result.standing.includes(a)))canAsk?await promotePlugin(paths,id,{assumeYes:!1}):say("info",`${id} stays off until the person approves it`,`hookmux promote ${id}`);return result.ok?0:1}function parseSourceText(sourceText){try{return parseSource(sourceText,existsSync2)}catch(error){throw error instanceof SourceError?new UsageError(error.message):error}}async function listSource(paths,sourceText,wanted){let spec=parseSourceText(sourceText),fetched=await fetchSource(spec);try{let candidates=stageAll(fetched,paths,wanted);return candidates===null?1:listCandidates(candidates,fetched,paths)}finally{fetched.cleanup()}}async function addFromSource(paths,sourceText,opts){let spec=parseSourceText(sourceText);readFlagsForUpdate(paths.flags);let fetched=await fetchSource(spec),added,ok;try{let candidates=stageAll(fetched,paths,opts.plugins);if(candidates===null)return null;({added,ok}=install(candidates,fetched,paths,{force:opts.force,shadow:opts.shadow,updateSameSource:opts.updateSameSource===!0}))}finally{fetched.cleanup()}if(added.length===0)return null;let standing=applyStandingApprovals(paths,added);return await syncAfterChange(paths)||(ok=!1),{added,standing,ok}}function stageAll(fetched,paths,wanted){let dirs=discoverPlugins(fetched.root);if(dirs.length===0)return say("fail",`no plugin.toml found in ${fetched.source}`,"hookmux new <id> to start one"),null;let defaults=loadDefaults(readConfig(paths.config)),candidates=dirs.map(dir=>{try{return{dir,staged:stagePlugin(dir,paths,defaults)}}catch(error){return{dir,problem:error.message}}});if(wanted.length===0)return candidates;let picked=candidates.filter(c=>c.staged&&wanted.includes(c.staged.id));for(let c of candidates)c.staged&&!picked.includes(c)&&discardStaged(c.staged);let missing=wanted.filter(id=>!picked.some(c=>c.staged?.id===id));if(missing.length>0){for(let c of picked)c.staged&&discardStaged(c.staged);return say("fail",`not found in the source: ${missing.join(", ")}`,`hookmux add ${fetched.source} --list`),null}return picked}function listCandidates(candidates,fetched,paths){let deadlineMs=readConfig(paths.config).settings.deadlineMs;for(let c of candidates){let where=relative(fetched.root,c.dir)||".";if(!c.staged){say("fail",`${where}: ${c.problem}`,`hookmux validate ${c.dir}`);continue}let{id,compiled,capabilities}=c.staged;say("ok",`${id} ${compiled.base.version} (${where}): ${compiled.base.description||"no description"}`),detail(shortCard(c.staged,capabilities,fetched,deadlineMs)),discardStaged(c.staged)}return candidates.every(c=>c.staged)?0:1}function shortCard(staged,capabilities,fetched,deadlineMs){let{id,compiled}=staged,source={source:fetched.source,ref:fetched.ref,commit:fetched.commit},facts=cardFactsOf({id,base:compiled.base,variants:Object.values(compiled.variants),source});return renderCardShort(facts,capabilities,deadlineMs)}function install(candidates,fetched,paths,opts){let sources=readSources(paths.sources),flags=readFlagsForUpdate(paths.flags),deadlineMs=readConfig(paths.config).settings.deadlineMs,added=[],ok=!0;for(let c of candidates){if(!c.staged){ok=!1,say("fail",`${relative(fetched.root,c.dir)||"."}: ${c.problem}`,"hookmux validate <folder> after fixing it");continue}let{id,hash,capabilities,compiled}=c.staged;try{let sameSource=opts.updateSameSource&&sources[id]?.source===fetched.source;placeStaged(c.staged,paths,opts.force||sameSource)}catch(error){if(!(error instanceof PluginExistsError))throw error;ok=!1,say("fail",error.message,`hookmux add ${fetched.source} --force, or hookmux remove ${id}`);continue}sources[id]={source:fetched.source,ref:fetched.ref,commit:fetched.commit,hash,addedAt:new Date().toISOString()},opts.shadow&&flags.shadow.push(id),added.push(id),say("ok",`added ${id} ${compiled.base.version}${opts.shadow?" (shadow)":""}`),detail(shortCard(c.staged,capabilities,fetched,deadlineMs));for(let w of compiled.warnings)detail(`! ${w}`)}return writeSources(paths.sources,sources),writeFlags(paths.flags,flags),{added,ok}}export{usage,run2 as run,addFromSource};
@@ -0,0 +1 @@
1
+ import{readJson,writeFileAtomic}from"./chunk-OYGOSD6V.mjs";import{VERSION}from"./chunk-AHPMRYYF.mjs";import{statSync}from"node:fs";var REGISTRY_FORMAT=6,KNOWN_HOSTS=["claude-code","codex","gemini-cli","qwen-code","droid","qoder","codebuddy","opencode"];function stamp(path){try{let s=statSync(path);return{path,mtimeMs:s.mtimeMs,size:s.isDirectory()?0:s.size}}catch{return{path,mtimeMs:-1,size:0}}}function isStale(registry){if(registry.format!==REGISTRY_FORMAT||registry.engine!==VERSION)return!0;for(let source of registry.sources){let now=stamp(source.path);if(now.mtimeMs!==source.mtimeMs||now.size!==source.size)return!0}return!1}function saveRegistry(paths,registry){writeFileAtomic(paths.registry,JSON.stringify(registry))}function readRegistry(paths){let registry=readJson(paths.registry,null);return registry&&registry.format===REGISTRY_FORMAT&&Array.isArray(registry.plugins)?registry:null}async function loadRegistry(paths){let saved=readRegistry(paths);if(saved&&!isStale(saved))return saved;let{compileRegistry}=await import("./registry-P6V5HZQN.mjs"),fresh=compileRegistry(paths);try{saveRegistry(paths,fresh)}catch{}return fresh}function activeSpecs(registry,hostId,guardsOnly=!1){let out=[];for(let p of registry.plugins){if(p.status!=="active"||!p.base||guardsOnly&&p.phase!=="guard")continue;let spec=p.variants?.[hostId]??p.base;out.push(p.fileHashes?{...spec,fileHashes:p.fileHashes}:spec)}return out}export{REGISTRY_FORMAT,KNOWN_HOSTS,stamp,saveRegistry,loadRegistry,activeSpecs};
@@ -0,0 +1 @@
1
+ var VERSION="0.1.0";export{VERSION};
@@ -0,0 +1 @@
1
+ var MARKS={ok:"\u2713",warn:"!",fail:"\u2717",info:"\xB7"},COLOURS={ok:32,warn:33,fail:31,info:2};function colourOn(){return process.stdout.isTTY===!0&&!process.env.NO_COLOR}function paint(code,text){return colourOn()?`\x1B[${code}m${text}\x1B[0m`:text}function dim(text){return paint(2,text)}function bold(text){return paint(1,text)}function mark(status){return paint(COLOURS[status],MARKS[status])}function say(status,text,next){console.log(`${mark(status)} ${text}`),next&&console.log(` ${dim("\u2192")} ${next}`)}function detail(text){console.log(` ${text}`)}function printJson(value){console.log(JSON.stringify(value,null,2))}function clip(text,max=60){let flat=text.replace(/\s+/g," ").trim();return flat.length>max?`${flat.slice(0,max-1)}\u2026`:flat}function formatBytes(bytes){return bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KiB`:`${(bytes/1024/1024).toFixed(1)} MiB`}export{dim,bold,say,detail,printJson,clip,formatBytes};
@@ -0,0 +1,3 @@
1
+ import{PLUGIN_ID}from"./chunk-ZNEBE4WO.mjs";import{writeFileAtomic}from"./chunk-OYGOSD6V.mjs";import{randomInt}from"node:crypto";import{existsSync,mkdirSync,readdirSync,readFileSync,rmdirSync,rmSync}from"node:fs";import{join}from"node:path";var CARD_TTL_MS=1800*1e3,CODE_ALPHABET="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",CODE_LENGTH=4,CODE_PATTERN=/^[A-HJ-NP-Z2-9]{4}$/;function newCode(){for(;;){let code="";for(let i=0;i<CODE_LENGTH;i++)code+=CODE_ALPHABET[randomInt(CODE_ALPHABET.length)];if(/[A-Z]/.test(code)&&/\d/.test(code))return code}}function cardFile(dir,id){return join(dir,`${id}.json`)}function parseCard(text){try{let card=JSON.parse(text);return PLUGIN_ID.test(card.id)&&CODE_PATTERN.test(card.code)&&typeof card.hash=="string"&&Array.isArray(card.capabilities)&&typeof card.expiresAt=="number"?card:null}catch{return null}}function loadCard(file){try{return parseCard(readFileSync(file,"utf8"))}catch{return null}}function readCard(dir,id){return loadCard(cardFile(dir,id))}function writeCard(dir,card){writeFileAtomic(cardFile(dir,card.id),`${JSON.stringify(card)}
2
+ `)}function deleteCard(dir,id){rmSync(cardFile(dir,id),{force:!0}),removeIfEmpty(dir)}function removeIfEmpty(dir){try{rmdirSync(dir)}catch{}}function issueCard(dir,content,now=Date.now()){mkdirSync(dir,{recursive:!0,mode:448}),dropExpired(dir,now);let card={...content,code:newCode(),issuedAt:now,expiresAt:now+CARD_TTL_MS};return writeCard(dir,card),card}function dropExpired(dir,now){for(let name of readdirSync(dir)){if(!name.endsWith(".json"))continue;let card=loadCard(join(dir,name));(!card||card.expiresAt<=now)&&rmSync(join(dir,name),{force:!0})}}function mentionsCode(text,code){return new RegExp(`--confirm\\s+${code}(?![A-Za-z0-9])`,"i").test(text)?!1:new RegExp(`(?<![A-Za-z0-9])${code}(?![A-Za-z0-9])`,"i").test(text)}function approveFromPrompt(dir,text,host,now=Date.now()){if(!existsSync(dir))return[];let approved=[];for(let name of readdirSync(dir)){if(!name.endsWith(".json"))continue;let card=loadCard(join(dir,name));if(!card||card.expiresAt<=now){rmSync(join(dir,name),{force:!0});continue}if(card.approvedAt!==void 0||!mentionsCode(text,card.code))continue;let marked={...card,approvedAt:now,host};writeCard(dir,marked),approved.push(marked)}return removeIfEmpty(dir),approved}import{createHash,randomBytes,timingSafeEqual}from"node:crypto";import{mkdirSync as mkdirSync2,readdirSync as readdirSync2,readFileSync as readFileSync2,rmSync as rmSync2}from"node:fs";import{join as join2}from"node:path";var GRANT_TTL_MS=7200*1e3;function newGrantToken(){return randomBytes(24).toString("hex")}function hashToken(token){return createHash("sha256").update(token).digest("hex")}function grantFile(dir,tokenHash){return join2(dir,`${tokenHash.slice(0,32)}.json`)}function readGrant(file){try{let grant=JSON.parse(readFileSync2(file,"utf8"));return typeof grant.tokenHash=="string"&&typeof grant.expiresAt=="number"?grant:null}catch{return null}}function saveGrant(dir,token,request,now=Date.now()){mkdirSync2(dir,{recursive:!0,mode:448});for(let name of readdirSync2(dir)){if(!name.endsWith(".json"))continue;let file=join2(dir,name),old=readGrant(file);old&&old.expiresAt<=now&&rmSync2(file,{force:!0})}let tokenHash=hashToken(token),grant={...request,tokenHash,expiresAt:now+GRANT_TTL_MS};writeFileAtomic(grantFile(dir,tokenHash),`${JSON.stringify(grant)}
3
+ `)}function takeGrant(dir,token,now=Date.now()){let tokenHash=hashToken(token),file=grantFile(dir,tokenHash),grant=readGrant(file);return!grant||!(grant.tokenHash.length===tokenHash.length&&timingSafeEqual(Buffer.from(grant.tokenHash),Buffer.from(tokenHash)))?null:(rmSync2(file,{force:!0}),grant.expiresAt>now?grant:null)}export{CODE_PATTERN,readCard,deleteCard,issueCard,approveFromPrompt,newGrantToken,saveGrant,takeGrant};
@@ -0,0 +1 @@
1
+ import{UsageError}from"./chunk-XPLEWNGF.mjs";import{applyFlags,compileRegistry,readConfig,readFlags,readSources}from"./chunk-IJHUIMJA.mjs";import{compileManifest,readManifest}from"./chunk-K73ZPBFM.mjs";import{KNOWN_HOSTS}from"./chunk-7Z3AMI24.mjs";import{PLUGIN_ID}from"./chunk-ZNEBE4WO.mjs";import{existsSync}from"node:fs";import{join}from"node:path";function loadDefaults(config){return{routeOrigins:config.settings.routeOrigins,knownHosts:KNOWN_HOSTS}}function inspectInstalled(paths){let registry=compileRegistry(paths),config=readConfig(paths.config),flags=readFlags(paths.flags),sources=readSources(paths.sources),rows=registry.plugins.map(entry=>{let dir=join(paths.plugins,entry.id),row={id:entry.id,dir,status:entry.status,entry,variants:entry.variants??{}};if(sources[entry.id]&&(row.source=sources[entry.id]),entry.base)row.spec=entry.base;else if(entry.status==="untrusted")try{let compiled=compileManifest(readManifest(dir),dir,config.overrides[entry.id],loadDefaults(config));row.spec=applyFlags(compiled.base,flags),row.variants=Object.fromEntries(Object.entries(compiled.variants).map(([host,spec])=>[host,applyFlags(spec,flags)]))}catch{}return entry.status==="active"&&row.spec&&(row.spec.enabled?row.spec.shadow&&(row.status="shadow"):row.status="disabled"),row});return{registry,rows}}function specFor(row,hostId){let spec=row.variants[hostId]??row.spec;return spec&&row.entry.fileHashes?{...spec,fileHashes:row.entry.fileHashes}:spec}function installedDir(paths,id){if(!PLUGIN_ID.test(id))throw new UsageError(`'${id}' is not a valid plugin id`);return join(paths.plugins,id)}function isInstalled(paths,id){return existsSync(installedDir(paths,id))}export{loadDefaults,inspectInstalled,specFor,installedDir,isInstalled};
@@ -0,0 +1 @@
1
+ import{capabilitiesOf,hashPlugin,listPluginFiles}from"./chunk-IJHUIMJA.mjs";import{MANIFEST_FILE,compileManifest,readManifest}from"./chunk-K73ZPBFM.mjs";import{PLUGIN_ID}from"./chunk-ZNEBE4WO.mjs";import{lstatSync,readdirSync}from"node:fs";import{join}from"node:path";function isRealDir(path){try{return lstatSync(path).isDirectory()}catch{return!1}}function hasManifest(dir){try{return lstatSync(join(dir,MANIFEST_FILE)).isFile()}catch{return!1}}function childDirs(dir){return isRealDir(dir)?readdirSync(dir,{withFileTypes:!0}).filter(d=>d.isDirectory()).map(d=>join(dir,d.name)).sort():[]}function pluginFoldersIn(dir){return childDirs(dir).filter(hasManifest)}function discoverPlugins(root){let candidates=[root,...childDirs(join(root,"plugins")),...childDirs(join(root,"hookmux")),...childDirs(join(root,"skills")).map(d=>join(d,"hookmux"))];return[...new Set(candidates.filter(d=>isRealDir(d)&&hasManifest(d)))]}import{chmodSync,copyFileSync,existsSync,lstatSync as lstatSync2,mkdirSync,mkdtempSync,renameSync,rmSync}from"node:fs";import{dirname,join as join2,relative}from"node:path";var SHARED_WRITE=18,DIR_MODE=493,PluginExistsError=class extends Error{};function stagePlugin(sourceDir,paths,defaults){let{files}=listPluginFiles(sourceDir);mkdirSync(paths.staging,{recursive:!0,mode:448});let dir=mkdtempSync(join2(paths.staging,"add-"));try{chmodSync(dir,DIR_MODE);let relFiles=files.map(f=>relative(sourceDir,f));for(let rel of relFiles)copyPrivate(join2(sourceDir,rel),join2(dir,rel),dir);let raw=readManifest(dir);if(typeof raw.id!="string"||!PLUGIN_ID.test(raw.id))throw new Error("id must be lowercase letters, digits and dashes (max 64)");let compiled=compileManifest(raw,dir,void 0,defaults);return{id:raw.id,dir,compiled,capabilities:capabilitiesOf(compiled.base,Object.values(compiled.variants)),hash:hashPlugin(dir),files:relFiles}}catch(error){throw rmSync(dir,{recursive:!0,force:!0}),error}}function copyPrivate(from,to,root){let parent=dirname(to);mkdirSync(parent,{recursive:!0});for(let d=parent;d!==root;d=dirname(d))chmodSync(d,DIR_MODE);copyFileSync(from,to);let mode=lstatSync2(from).mode&511&~SHARED_WRITE|384;if(chmodSync(to,mode),(lstatSync2(to).mode&SHARED_WRITE)!==0)throw new Error(`${relative(root,to)} is still group or world writable`)}function placeStaged(staged,paths,force){let target=join2(paths.plugins,staged.id);if(mkdirSync(paths.plugins,{recursive:!0,mode:448}),existsSync(target)){if(!force)throw discardStaged(staged),new PluginExistsError(`plugin '${staged.id}' is already installed`);let old=join2(paths.staging,`old-${staged.id}-${process.pid}`);renameSync(target,old),renameSync(staged.dir,target),rmSync(old,{recursive:!0,force:!0})}else renameSync(staged.dir,target);return target}function discardStaged(staged){rmSync(staged.dir,{recursive:!0,force:!0})}export{pluginFoldersIn,discoverPlugins,PluginExistsError,stagePlugin,placeStaged,discardStaged};
@@ -0,0 +1,7 @@
1
+ import{CODE_PATTERN,deleteCard,issueCard,readCard,takeGrant}from"./chunk-CA2GWCFP.mjs";import{cardSummary,renderCard}from"./chunk-IAGBX723.mjs";import{activationRefusal}from"./chunk-5GQP3BA6.mjs";import{inspectInstalled,installedDir,isInstalled}from"./chunk-CSXS5D2F.mjs";import{confirm,isInteractive}from"./chunk-RG3EOP4J.mjs";import{syncAfterChange}from"./chunk-G6SJQTFF.mjs";import{detail,say}from"./chunk-BF25CRHJ.mjs";import{isCapabilitySubset,listPluginFiles,readFlagsForUpdate,readTrust,uncoveredCapabilities,writeFlags,writeTrust}from"./chunk-IJHUIMJA.mjs";function readPromotable(paths,id){if(!isInstalled(paths,id))return say("fail",`plugin '${id}' is not installed`,"hookmux list"),null;let dir=installedDir(paths,id),{registry,rows}=inspectInstalled(paths),row=rows.find(r=>r.id===id);if(!row||row.status==="invalid"||row.entry.hash===void 0)return say("fail",`${id} is invalid: ${row?.entry.problem??"not found"}`,`hookmux validate ${dir}`),null;let{hash,capabilities}=row.entry;return{id,dir,entry:row.entry,hash,capabilities,deadlineMs:registry.settings.deadlineMs}}function changeState(paths,p){let previous=readTrust(paths.trust).plugins[p.id],sameContent=previous?.hash===p.hash,capsCovered=previous!==void 0&&isCapabilitySubset(p.capabilities,previous.capabilities),shadow=readFlagsForUpdate(paths.flags).shadow.includes(p.id),standingCovered=previous?.standing!==void 0&&isCapabilitySubset(p.capabilities,previous.standing.capabilities);return{previous,change:previous?sameContent?capsCovered?"same":"caps":"changed":"new",alreadyApproved:sameContent&&capsCovered&&!shadow,standingCovered}}var APPROVAL_TEXT={new:"first approval",same:"same content as the last approval; clears shadow mode",caps:"same content, but config.toml overrides add capabilities",changed:"content CHANGED since the last approval"};function cardFor(p,change){let facts=p.entry.card;if(!facts)throw new Error(`no card facts for ${p.id}; run hookmux doctor`);let text=renderCard(facts,p.capabilities,{hash:p.hash,approval:APPROVAL_TEXT[change],deadlineMs:p.deadlineMs});return{facts,text}}function pin(paths,id,content,standing,record){let now=new Date().toISOString(),trust=readTrust(paths.trust),kept=standing?{capabilities:content.capabilities,grantedAt:now}:trust.plugins[id]?.standing;trust.plugins[id]={...content,promotedAt:now,via:record.via,...record.host?{host:record.host}:{},...record.approvedAt?{approvedAt:record.approvedAt}:{},...kept?{standing:kept}:{}},writeTrust(paths.trust,trust);let flags=readFlagsForUpdate(paths.flags);writeFlags(paths.flags,{...flags,shadow:flags.shadow.filter(s=>s!==id)})}var EXIT_WAITING=3,cli=()=>process.env.npm_command==="exec"?"npx -y hookmux":"hookmux",approveCommand=(id,code)=>`${cli()} promote ${id} --confirm ${code}`,askAgain=id=>`ask again: ${cli()} promote ${id}`;function refuseStandingRelay(id){return say("fail","a standing approval needs your terminal or your client's permission prompt",`hookmux promote ${id} --standing`),1}function matchingCard(paths,p){let card=readCard(paths.cards,p.id),same=card&&card.hash===p.hash&&card.capabilities.join(`
2
+ `)===p.capabilities.join(`
3
+ `);return card&&same&&card.expiresAt>Date.now()?card:null}function relayPromote(paths,id,opts){if(opts.standing)return refuseStandingRelay(id);let p=readPromotable(paths,id);if(!p)return 1;let state=changeState(paths,p);if(state.alreadyApproved)return say("ok",`${id} is already promoted and unchanged since ${state.previous?.promotedAt}`),0;let{facts,text}=cardFor(p,state.change),card=matchingCard(paths,p)??issueCard(paths.cards,{id,hash:p.hash,capabilities:p.capabilities,summary:cardSummary(facts,p.capabilities,p.deadlineMs),command:cli()});return printRelay(id,text,card),EXIT_WAITING}function printRelay(id,cardText,card){if(console.log(`hookmux: approval needed for ${id}`),console.log(cardText),card.approvedAt!==void 0){console.log(`The user has already replied with ${card.code}. Run exactly:
4
+ ${approveCommand(id,card.code)}`);return}let until=new Date(card.expiresAt).toTimeString().slice(0,5);console.log(["Show this card to the user word for word and ask whether to turn the plugin on.","Do not answer for them. To approve, the user replies `approve "+card.code+"` in their","own message; hookmux reads that reply itself. After they reply, run exactly:",` ${approveCommand(id,card.code)}`,`The code expires at ${until} and covers only this content. If the plugin changes,`,`run ${cli()} promote ${id} again.`].join(`
5
+ `))}async function confirmRelay(paths,id,rawCode){let code=rawCode.toUpperCase(),card=CODE_PATTERN.test(code)?readCard(paths.cards,id):null;if(!card||card.code!==code||card.expiresAt<=Date.now())return say("fail",`this approval code for '${id}' is unknown or expired`,askAgain(id)),1;if(card.approvedAt===void 0)return say("fail",`the user has not replied with ${code} yet. Ask them, and run this only after they reply`),EXIT_WAITING;let p=readPromotable(paths,id);if(!p)return 1;if(!matchingCard(paths,p))return deleteCard(paths.cards,id),say("fail",`${id} changed after the card was shown, so it was not turned on`,`show the new card: ${cli()} promote ${id}`),1;deleteCard(paths.cards,id);let host=card.host??"an agent client";return pin(paths,id,p,!1,{via:"relay",host:card.host,approvedAt:new Date(card.approvedAt).toISOString()}),say("ok",`${id} turned on with the user's approval (relayed through ${host})`,`undo: hookmux disable ${id}`),await syncAfterChange(paths),0}import{relative}from"node:path";async function promotePlugin(paths,id,opts){let{assumeYes,standing=!1}=opts,refusal=activationRefusal({assumeYes,interactive:isInteractive(),env:process.env});if(refusal==="yes-flag")return say("fail","promote does not take --yes: a person types y to activate a plugin",`run this yourself in a terminal: hookmux promote ${id}`),1;if(refusal)return relayPromote(paths,id,{standing});let p=readPromotable(paths,id);if(!p)return 1;let state=changeState(paths,p),{previous,change}=state;return state.alreadyApproved&&(!standing||state.standingCovered)?(say("ok",`${id} is already promoted and unchanged since ${previous?.promotedAt}`),0):(describe(p.dir,cardFor(p,change).text),previous&&detail(`last promoted ${previous.promotedAt}`),standing&&describeStanding(id,p.capabilities),await confirm(standing?`Activate ${id} and grant the standing approval?`:`Activate ${id}?`,!1)?(pin(paths,id,p,standing,{via:"promote"}),say("ok",`${id} promoted; it runs on the next hook event`),await syncAfterChange(paths),0):(say("info",`${id} left as it was`),1))}async function promoteWithGrant(paths,id,opts){let again=`hookmux promote ${id}${opts.standing?" --standing":""}`,grant=takeGrant(paths.grants,opts.token);if(!grant||grant.id!==id||grant.standing!==opts.standing)return say("fail",`this approval for '${id}' is unknown, already used or expired`,`ask again: ${again}`),1;let row=inspectInstalled(paths).rows.find(r=>r.id===id);if(!row||row.status==="invalid"||row.entry.hash===void 0)return say("fail",`${id} is invalid: ${row?.entry.problem??"not installed"}`,"hookmux list"),1;let sameCapabilities=Array.isArray(grant.capabilities)&&grant.capabilities.join(`
6
+ `)===row.entry.capabilities.join(`
7
+ `);return row.entry.hash!==grant.hash||!sameCapabilities?(say("fail",`${id} changed after the approval was shown, so it was not activated`,`ask again: ${again}`),1):(pin(paths,id,{hash:row.entry.hash,capabilities:row.entry.capabilities},opts.standing,{via:"prompt",host:grant.host}),say("ok",`${id} promoted on your approval; it runs on the next hook event`),await syncAfterChange(paths),0)}function applyStandingApprovals(paths,ids){let trust=readTrust(paths.trust),flags=readFlagsForUpdate(paths.flags),rows=inspectInstalled(paths).rows,pinned=[];for(let id of ids){let grant=trust.plugins[id]?.standing;if(!grant)continue;let row=rows.find(r=>r.id===id);if(!row||row.status==="invalid"||row.entry.hash===void 0)continue;if(flags.shadow.includes(id)){say("info",`${id} is in shadow mode, so its standing approval is not applied`,`hookmux promote ${id}`);continue}let beyond=uncoveredCapabilities(row.entry.capabilities,grant.capabilities);if(beyond.length>0){say("warn",`${id} now needs ${beyond.join(", ")}, beyond its standing approval`,`hookmux promote ${id}`);continue}let now=new Date().toISOString();trust.plugins[id]={hash:row.entry.hash,capabilities:row.entry.capabilities,promotedAt:now,via:"standing",standing:grant},pinned.push(id),say("ok",`${id} activated under the standing approval granted ${grant.grantedAt}`)}return pinned.length>0&&writeTrust(paths.trust,trust),pinned}function endStanding(paths,id){let trust=readTrust(paths.trust),entry=trust.plugins[id];return entry?.standing?(delete entry.standing,writeTrust(paths.trust,trust),say("ok",`${id}: standing approval ended; later changes need hookmux promote ${id}`),0):(say("info",`${id} has no standing approval`),0)}function describeStanding(id,capabilities){detail("standing approval:"),detail(` later \`hookmux add\` runs replace and activate ${id} without asking while it needs`),detail(` no more than: ${capabilities.join(", ")||"none"}`),detail(" anyone who can run hookmux add (agents included) can then change its files within that;"),detail(" matchers, folder globs and the phase are not part of the ceiling."),detail(` end it any time: hookmux promote ${id} --end-standing`)}function describe(dir,card){console.log(card),detail("files:");for(let f of listPluginFiles(dir).files)detail(` ${relative(dir,f)}`)}export{EXIT_WAITING,refuseStandingRelay,confirmRelay,promotePlugin,promoteWithGrant,applyStandingApprovals,endStanding};