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
@@ -0,0 +1,15 @@
1
+ import{chooseInstallHosts,engineNeedsSetup,setupHub}from"./chunk-FF55QGCZ.mjs";import"./chunk-L3BSVLQG.mjs";import{addFromSource}from"./chunk-6GL55FEQ.mjs";import{EXIT_WAITING,promotePlugin}from"./chunk-DJHE642J.mjs";import"./chunk-CA2GWCFP.mjs";import"./chunk-IAGBX723.mjs";import"./chunk-CZY5UAXM.mjs";import{agentMarker}from"./chunk-5GQP3BA6.mjs";import"./chunk-CSXS5D2F.mjs";import{isInteractive}from"./chunk-RG3EOP4J.mjs";import{allAdapters,wiredAdapters}from"./chunk-G6SJQTFF.mjs";import{say}from"./chunk-BF25CRHJ.mjs";import{UsageError,parseCommand}from"./chunk-XPLEWNGF.mjs";import{readInstallState}from"./chunk-IJHUIMJA.mjs";import"./chunk-K73ZPBFM.mjs";import"./chunk-OXHAGFXG.mjs";import"./chunk-2ZCM3JZR.mjs";import"./chunk-7Z3AMI24.mjs";import"./chunk-ZNEBE4WO.mjs";import{homePaths}from"./chunk-OYGOSD6V.mjs";import"./chunk-AHPMRYYF.mjs";import{existsSync}from"node:fs";var usage=`Usage: hookmux install <source> [--plugin <id>]... [--host <id>]...
2
+
3
+ Sets up hookmux if it is not set up yet, adds the plugin from <source> and asks
4
+ you to approve it. The plugin stays off until you do. Sources are the same as
5
+ for hookmux add: a folder, owner/repo or a git URL.
6
+
7
+ --plugin <id> only these plugins (repeatable)
8
+ --host <id> wire this agent client (repeatable); known: ${allAdapters().map(a=>a.id).join(", ")}
9
+
10
+ At your terminal it asks which clients to wire and shows each plugin's card for
11
+ your answer. Run by an agent, it wires the client that is running it (or --host),
12
+ prints the card and a code, and exits 3: the user approves by replying with the
13
+ code, and the agent then runs the confirm command the card names.
14
+
15
+ Exit codes: 0 done, 1 failed, 2 usage error, 3 waiting for the person's reply.`;async function run(argv){let parsed=parseCommand(argv,{plugin:{type:"string",multiple:!0},host:{type:"string",multiple:!0}},usage,1);if(!parsed)return 0;let source=parsed.positionals[0];if(!source)throw new UsageError("name a source: a folder, owner/repo or a git URL");let paths=homePaths(),atTerminal=isInteractive()&&agentMarker(process.env)===void 0,adapters=await chooseInstallHosts(parsed.values.host??[],atTerminal,process.env),freshSetup=engineNeedsSetup(paths),wired=wiredAdapters(paths),unwired=adapters.filter(a=>!wired.some(w=>w.id===a.id)),setUp=freshSetup||unwired.length>0,setupOk=!0;if(setUp){let timeoutSec=readInstallState(paths.installState).timeoutSec;setupOk=await setupHub(paths,{adapters:freshSetup?adapters:unwired,engine:freshSetup||!existsSync(paths.launcher),timeoutSec,bundled:!1,skill:!1})}let added=await addFromSource(paths,source,{plugins:parsed.values.plugin??[],shadow:!1,force:!1,updateSameSource:!0});if(!added)return 1;let asked=await askForApproval(paths,added.added.filter(id=>!added.standing.includes(id)));return asked.waiting&&setUp&&say("info","hookmux was just set up; if the reply is not picked up, start a new session in your client"),setupOk?asked.waiting?EXIT_WAITING:added.ok&&asked.ok?0:1:1}async function askForApproval(paths,ids){let waiting=!1,ok=!0;for(let id of ids){let code=await promotePlugin(paths,id,{assumeYes:!1});code===EXIT_WAITING?waiting=!0:code!==0&&(ok=!1)}return{waiting,ok}}export{run,usage};
@@ -0,0 +1,5 @@
1
+ import{inspectInstalled}from"./chunk-CSXS5D2F.mjs";import{detail,dim,printJson,say}from"./chunk-BF25CRHJ.mjs";import{parseCommand}from"./chunk-XPLEWNGF.mjs";import{readTrust}from"./chunk-IJHUIMJA.mjs";import"./chunk-K73ZPBFM.mjs";import"./chunk-2ZCM3JZR.mjs";import"./chunk-7Z3AMI24.mjs";import"./chunk-ZNEBE4WO.mjs";import{homePaths}from"./chunk-OYGOSD6V.mjs";import"./chunk-AHPMRYYF.mjs";var usage=`Usage: hookmux list [--json]
2
+
3
+ Shows each installed plugin: status (active, untrusted, invalid, shadow,
4
+ disabled), phase, events, capabilities, how it was approved (terminal,
5
+ prompt, relay or standing), its problem if any, and warnings.`,STATUS_MARK={active:"ok",shadow:"info",disabled:"info",untrusted:"warn",invalid:"fail"};function approvalText(entry){if(!entry)return null;let where=entry.host?` (${entry.host})`:"";return entry.via==="prompt"?`prompt${where}`:entry.via==="relay"?`relay (${[entry.host,entry.approvedAt].filter(Boolean).join(", ")})`:entry.via==="standing"?"standing":"terminal"}function toItem(row,entry){return{id:row.id,status:row.status,version:row.spec?.version??null,description:row.spec?.description??null,phase:row.spec?.phase??null,events:row.spec?.events??[],capabilities:row.entry.capabilities,problem:row.entry.problem??null,warnings:row.entry.warnings,source:row.source?.source??null,approval:row.status==="untrusted"||row.status==="invalid"?null:approvalText(entry)}}function nextStep(row){if(row.status==="untrusted")return`hookmux promote ${row.id}`;if(row.status==="invalid")return`hookmux validate ${row.dir}`;if(row.status==="disabled")return`hookmux enable ${row.id}`}async function run(argv){let parsed=parseCommand(argv,{json:{type:"boolean"}},usage);if(!parsed)return 0;let paths=homePaths(),{rows}=inspectInstalled(paths),trust=readTrust(paths.trust).plugins,items=rows.map(row=>toItem(row,trust[row.id]));return parsed.values.json?(printJson({plugins:items}),rows.some(r=>r.status==="invalid")?1:0):rows.length===0?(say("info","no plugins installed","hookmux add <source>, or hookmux new <id>"),0):(rows.forEach((row,i)=>{let item=items[i],what=item.phase?`${item.phase} on ${item.events.join(", ")}`:"";say(STATUS_MARK[row.status],`${row.id} ${dim(row.status)} ${what}`.trimEnd(),nextStep(row)),item.capabilities.length>0&&detail(dim(`can: ${item.capabilities.join(", ")}`)),item.approval&&detail(dim(`approved: ${item.approval}`)),item.problem&&detail(`problem: ${item.problem}`);for(let w of item.warnings)detail(`! ${w}`)}),rows.some(r=>r.status==="invalid")?1:0)}export{approvalText,run,usage};
@@ -0,0 +1,11 @@
1
+ import{describeLogStatus,readLogStatus,readRecords}from"./chunk-WZSNBZ6D.mjs";import{readLogSettings,writeLogSettings}from"./chunk-UERSXYXZ.mjs";import{detail,dim,printJson,say}from"./chunk-BF25CRHJ.mjs";import{UsageError,parseCommand,positiveInt}from"./chunk-XPLEWNGF.mjs";import{homePaths}from"./chunk-OYGOSD6V.mjs";import{rmSync}from"node:fs";var usage=`Usage: hookmux log <on|off|status|show|path|clear> [options]
2
+
3
+ on [--for <30m|24h|7d>] [--prompts] start logging each hook run (no expiry without --for)
4
+ off stop logging
5
+ status [--json] on or off, size and expiry
6
+ show [-n 20] [--json] [--plugin <id>] [--errors]
7
+ one line per run, newest last
8
+ path print the log file path
9
+ clear delete the log files
10
+
11
+ --prompts also stores the first 500 characters of every prompt on this machine.`,DURATION=/^(\d+)(m|h|d)$/,UNIT_MS={m:6e4,h:36e5,d:864e5},DEFAULT_SHOW=20;function parseDuration(text){let m=DURATION.exec(text);if(!m||Number(m[1])===0)throw new UsageError(`--for must look like 30m, 24h or 7d, not '${text}'`);return Number(m[1])*UNIT_MS[m[2]]}async function run(argv){let[sub,...rest]=argv;if(sub===void 0||sub==="--help"||sub==="-h")return console.log(usage),sub===void 0?2:0;let paths=homePaths();switch(sub){case"on":return logOn(paths,rest);case"off":return simple(rest,()=>{writeLogSettings(paths.logSettings,{...readLogSettings(paths.logSettings),enabled:!1}),say("ok","logging off")});case"status":return logStatus(paths,rest);case"show":return logShow(paths,rest);case"path":return simple(rest,()=>console.log(paths.logFile));case"clear":return simple(rest,()=>{for(let f of[paths.logFile,`${paths.logFile}.1`])rmSync(f,{force:!0});say("ok","log cleared")});default:throw new UsageError(`unknown log command '${sub}'`)}}function simple(argv,action){return parseCommand(argv,{},usage)&&action(),0}function logOn(paths,argv){let parsed=parseCommand(argv,{for:{type:"string"},prompts:{type:"boolean"}},usage);if(!parsed)return 0;let forMs=parsed.values.for===void 0?void 0:parseDuration(parsed.values.for),until=forMs===void 0?void 0:new Date(Date.now()+forMs).toISOString(),prompts=parsed.values.prompts===!0;return writeLogSettings(paths.logSettings,{enabled:!0,prompts,...until?{until}:{}}),say("ok",`logging on${until?` until ${until}`:" with no expiry"}: ${paths.logFile}`),prompts?say("warn","prompt text (first 500 characters) will be stored locally in that file","hookmux log off"):detail(dim("prompts are stored only as a short hash and length")),0}function logStatus(paths,argv){let parsed=parseCommand(argv,{json:{type:"boolean"}},usage);if(!parsed)return 0;let status=readLogStatus(paths);return parsed.values.json?printJson(status):say(status.active?"ok":"info",describeLogStatus(status),status.active?void 0:"hookmux log on --for 24h"),0}function hasErrors(r){return(r.errors?.length??0)>0?!0:(r.plugins??[]).some(p=>p.outcome==="error"||Object.values(p.signals??{}).some(v=>typeof v=="string"&&v.startsWith("error:")))}function logShow(paths,argv){let parsed=parseCommand(argv,{n:{type:"string",short:"n"},json:{type:"boolean"},plugin:{type:"string"},errors:{type:"boolean"}},usage);if(!parsed)return 0;let limit=positiveInt(parsed.values.n,"-n",DEFAULT_SHOW),id=parsed.values.plugin,records=readRecords(paths).filter(r=>!id||(r.plugins??[]).some(p=>p.id===id)).filter(r=>!parsed.values.errors||hasErrors(r)).slice(-limit);if(parsed.values.json)return printJson({entries:records}),0;if(records.length===0){let status=readLogStatus(paths);return say("info","no matching log entries",status.active?void 0:"hookmux log on --for 24h"),0}for(let r of records)console.log(formatRecord(r));return 0}function formatRecord(r){let time=typeof r.ts=="string"?`${r.ts.replace("T"," ").slice(0,19)}Z`:"?",fired=(r.plugins??[]).filter(p=>p.outcome==="fire").map(p=>p.id),failed=(r.plugins??[]).filter(p=>p.outcome==="error").map(p=>p.id),parts=[dim(time),String(r.host??"?"),String(r.event??"?"),`${String(r.ms??"?")}ms`,fired.length>0?`fired: ${fired.join(", ")}`:dim("fired: none")];return failed.length>0&&parts.push(`plugin errors: ${failed.join(", ")}`),(r.errors?.length??0)>0&&parts.push(`errors: ${(r.errors??[]).join("; ")}`),parts.join(" ")}export{parseDuration,run,usage};
@@ -0,0 +1,186 @@
1
+ import{validatePlugin}from"./chunk-65XA3RK3.mjs";import"./chunk-DZU2NMID.mjs";import{renderCard}from"./chunk-IAGBX723.mjs";import{loadDefaults}from"./chunk-CSXS5D2F.mjs";import{detail,say}from"./chunk-BF25CRHJ.mjs";import{UsageError,parseCommand}from"./chunk-XPLEWNGF.mjs";import{capabilitiesOf,cardFactsOf,readConfig}from"./chunk-IJHUIMJA.mjs";import{compileManifest,readManifest}from"./chunk-K73ZPBFM.mjs";import"./chunk-OXHAGFXG.mjs";import"./chunk-2ZCM3JZR.mjs";import"./chunk-7Z3AMI24.mjs";import{CANONICAL_EVENTS,PLUGIN_ID}from"./chunk-ZNEBE4WO.mjs";import{homePaths}from"./chunk-OYGOSD6V.mjs";import{VERSION}from"./chunk-AHPMRYYF.mjs";import{existsSync,mkdirSync,writeFileSync as writeFileSync2}from"node:fs";import{dirname,join as join2,resolve}from"node:path";import{readFileSync,writeFileSync}from"node:fs";import{join}from"node:path";var TEMPLATES=["prompt-context","tool-guard","session-note"],TEMPLATE_EVENT={"tool-guard":"tool.before","session-note":"session.start"},TEMPLATE_SUMMARY={"prompt-context":"adds guidance to the agent's context when a prompt mentions a topic","tool-guard":"blocks a risky shell command before the agent runs it","session-note":"gives the agent a short note, such as the current git branch, when a session starts"},FILE_MODE=420,SCRIPT_MODE=493;function checkBlock(event){return event==="prompt.submit"?`[checks.mentions_topic]
2
+ kind = "keywords"
3
+ words = ["example topic", "another phrase"]`:`# ${event} has no prompt, so this example matches the working folder.
4
+ # For tool events, field = "tool.name" or "tool.input.<key>" reads the tool call.
5
+ [checks.mentions_topic]
6
+ kind = "keywords"
7
+ words = ["example-project"]
8
+ field = "cwd"`}function manifestTemplate(id,event){let prompt=event==="prompt.submit";return`# ${id}: say in a line or two what this plugin adds and when.
9
+ # Every key, check kind and effect: run 'hookmux schema'.
10
+ schema = 1
11
+ id = "${id}"
12
+ version = "0.1.0"
13
+ description = "One line on what this plugin does."
14
+ requires_hookmux = ">=${VERSION}"
15
+ events = ["${event}"]
16
+ # guard, route, enrich or observe; lower priority runs first within a phase.
17
+ phase = "${prompt?"route":"enrich"}"
18
+ ${prompt?"":`# Only prompts have a user or system origin; other events arrive as "unknown".
19
+ origins = ["unknown"]
20
+ `}# "session" fires at most once per session; "none" fires on every match.
21
+ dedupe = "session"
22
+ # Boolean expression over the checks below, with and, or, not and parentheses.
23
+ when = "mentions_topic"
24
+
25
+ ${checkBlock(event)}
26
+
27
+ # inject adds text to the agent's context; block and notify are the other effects.
28
+ [[then]]
29
+ effect = "inject"
30
+ text = "Replace this with the guidance the agent should see."
31
+ `}function testsTemplate(id,event){let head=`# Cases for 'hookmux test ${id}'. expect is "fire" or "silent".
32
+ # Optional per case: host (default claude-code), event, cwd.`;return event==="prompt.submit"?`${head}
33
+ [[case]]
34
+ prompt = "tell me about the example topic"
35
+ expect = "fire"
36
+
37
+ [[case]]
38
+ prompt = "rename this variable"
39
+ expect = "silent"
40
+ `:`${head}
41
+ [[case]]
42
+ event = "${event}"
43
+ cwd = "/work/example-project"
44
+ expect = "fire"
45
+
46
+ [[case]]
47
+ event = "${event}"
48
+ cwd = "/work/other"
49
+ expect = "silent"
50
+ `}function toolGuardManifest(id){return`# ${id}: blocks a risky shell command before the agent runs it.
51
+ # Every key, check kind and effect: run 'hookmux schema'.
52
+ schema = 1
53
+ id = "${id}"
54
+ version = "0.1.0"
55
+ description = "Blocks force pushes made through the shell tool."
56
+ requires_hookmux = ">=${VERSION}"
57
+ events = ["tool.before"]
58
+ # Plugins outside the guard phase run only on prompts the user typed, and tool events arrive with origin "unknown".
59
+ phase = "guard"
60
+ # Both must hold: a shell tool call whose command matches a risky pattern.
61
+ when = "is_shell and risky_command"
62
+
63
+ [checks.is_shell]
64
+ kind = "tool"
65
+ names = ["Bash"]
66
+
67
+ # Add the commands you want stopped. Use TOML literal strings ('...') for patterns.
68
+ [checks.risky_command]
69
+ kind = "regex"
70
+ field = "tool.input.command"
71
+ patterns = ['\\bgit\\s+push\\b.*\\s(--force|-f)(\\s|$)']
72
+
73
+ [[then]]
74
+ effect = "block"
75
+ reason = "Force pushes can overwrite other people's commits. Push without --force, or ask the user first."
76
+ `}function toolGuardTests(id){return`# Cases for 'hookmux test ${id}'. expect is "fire" or "silent".
77
+ # On tool events, command sets the shell command the tool call carries.
78
+ [[case]]
79
+ event = "tool.before"
80
+ command = "git push --force origin main"
81
+ expect = "fire"
82
+
83
+ [[case]]
84
+ event = "tool.before"
85
+ command = "git status"
86
+ expect = "silent"
87
+ `}function sessionNoteManifest(id){return`# ${id}: gives the agent a short note when a session starts.
88
+ # Every key, check kind and effect: run 'hookmux schema'.
89
+ schema = 1
90
+ id = "${id}"
91
+ version = "0.1.0"
92
+ description = "Tells the agent which git branch it is on when a session starts."
93
+ requires_hookmux = ">=${VERSION}"
94
+ events = ["session.start"]
95
+ # guard, route, enrich or observe; a note adds context, so it is an enrich plugin.
96
+ phase = "enrich"
97
+ # Only prompts have a user or system origin; session events arrive as "unknown".
98
+ origins = ["unknown"]
99
+ when = "has_note"
100
+
101
+ # note.sh runs in the agent's working folder. Exit 0 or print {"value": true, "evidence": "..."}
102
+ # to say yes; exit 1 for no. Evidence is quoted below as {evidence.has_note}.
103
+ [checks.has_note]
104
+ kind = "script"
105
+ command = "note.sh"
106
+
107
+ [[then]]
108
+ effect = "inject"
109
+ text = "You are on the git branch {evidence.has_note}."
110
+ `}var NOTE_SCRIPT=`#!/bin/sh
111
+ # Prints the current git branch (or the short commit when HEAD is detached) as the note.
112
+ # Exits 1, so the plugin stays silent, outside a git checkout.
113
+ branch=$(git symbolic-ref --short -q HEAD 2>/dev/null || git rev-parse --short HEAD 2>/dev/null) || exit 1
114
+ # Quotes and backslashes would break the JSON below.
115
+ branch=$(printf '%s' "$branch" | tr -d '"\\\\')
116
+ [ -n "$branch" ] || exit 1
117
+ printf '{"value": true, "evidence": "%s"}\\n' "$branch"
118
+ `;function sessionNoteTests(id){return`# Cases for 'hookmux test ${id} --run-scripts'. expect is "fire" or "silent".
119
+ # The first case runs note.sh in the folder you run the test from, so run it inside a git checkout.
120
+ [[case]]
121
+ event = "session.start"
122
+ expect = "fire"
123
+
124
+ # The root folder is not a git checkout.
125
+ [[case]]
126
+ event = "session.start"
127
+ cwd = "/"
128
+ expect = "silent"
129
+ `}function scaffoldFiles(id,template,event){switch(template){case"tool-guard":return[{path:"plugin.toml",content:toolGuardManifest(id),mode:FILE_MODE},{path:"tests.toml",content:toolGuardTests(id),mode:FILE_MODE}];case"session-note":return[{path:"plugin.toml",content:sessionNoteManifest(id),mode:FILE_MODE},{path:"note.sh",content:NOTE_SCRIPT,mode:SCRIPT_MODE},{path:"tests.toml",content:sessionNoteTests(id),mode:FILE_MODE}];case"prompt-context":return[{path:"plugin.toml",content:manifestTemplate(id,event),mode:FILE_MODE},{path:"tests.toml",content:testsTemplate(id,event),mode:FILE_MODE}]}}var REPO_PLACEHOLDER="OWNER/NAME",CARD_MARKER="<!-- card -->",CHECKOUT="actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1",SETUP_NODE="actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0";function readme(id,template,repo){let install=`npx -y hookmux install ${repo}`;return`# ${id}
130
+
131
+ A hookmux plugin that ${TEMPLATE_SUMMARY[template]}.
132
+
133
+ ## Install
134
+
135
+ \`\`\`sh
136
+ ${install}
137
+ \`\`\`
138
+
139
+ Or paste this to your agent:
140
+
141
+ > Install the ${id} plugin with hookmux: run \`${install}\`, show me the approval card it prints word for word, and wait for my answer.
142
+
143
+ The plugin stays off until you approve it.
144
+
145
+ ${CARD_MARKER}
146
+ `}function workflow(id){return`name: hookmux
147
+
148
+ on:
149
+ push:
150
+ branches: [main]
151
+ pull_request:
152
+
153
+ permissions:
154
+ contents: read
155
+
156
+ jobs:
157
+ check:
158
+ name: check ${id}
159
+ runs-on: ubuntu-latest
160
+ steps:
161
+ - uses: ${CHECKOUT}
162
+ with:
163
+ persist-credentials: false
164
+ - uses: ${SETUP_NODE}
165
+ with:
166
+ node-version: "22"
167
+ - run: npx -y hookmux@${VERSION} validate .
168
+ - run: npx -y hookmux@${VERSION} test . --run-scripts
169
+ `}function repoFiles(id,template,repo){return[{path:"README.md",content:readme(id,template,repo||REPO_PLACEHOLDER),mode:420},{path:".github/workflows/hookmux.yml",content:workflow(id),mode:420}]}var CARD_HEADING="What your users approve before it turns on:";function readmeCard(dir,id,repo){let paths=homePaths(),config=readConfig(paths.config),compiled=compileManifest(readManifest(dir),dir,void 0,loadDefaults(config)),facts=cardFactsOf({id,base:compiled.base,variants:Object.values(compiled.variants),source:{source:`https://github.com/${repo||REPO_PLACEHOLDER}.git`,ref:null,commit:null}}),capabilities=capabilitiesOf(compiled.base,Object.values(compiled.variants));return renderCard(facts,capabilities,{hash:"",approval:"",deadlineMs:config.settings.deadlineMs}).split(`
170
+ `).filter(line=>!line.startsWith("Content:")).join(`
171
+ `)}function fillReadmeCard(dir,id,repo){let file=join(dir,"README.md"),text=readFileSync(file,"utf8"),block=`${CARD_HEADING}
172
+
173
+ \`\`\`text
174
+ ${readmeCard(dir,id,repo)}
175
+ \`\`\``;writeFileSync(file,text.replace(CARD_MARKER,block))}var usage=`Usage: hookmux new <id> [--template <name>] [--dir <path>] [--event <event>] [--repo [owner/name]]
176
+
177
+ Creates <dir>/<id>/ with plugin.toml and tests.toml.
178
+
179
+ --template <name> ${TEMPLATES.join(", ")} (default prompt-context)
180
+ tool-guard blocks a risky shell command (tool.before)
181
+ session-note injects a note from note.sh (session.start)
182
+ --dir <path> parent folder (default: the current folder)
183
+ --event <event> ${CANONICAL_EVENTS.join(", ")} (default prompt.submit);
184
+ only prompt-context takes a choice
185
+ --repo [owner/name] make <id>/ a publishable repository: adds a README.md
186
+ with the install line and a CI workflow`,OWNER_NAME=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;function normalizeRepoFlag(argv){return argv.map((arg,i)=>arg==="--repo"&&!OWNER_NAME.test(argv[i+1]??"")?"--repo=":arg)}function resolveEvent(template,requested){if(template==="prompt-context"){let event=requested??"prompt.submit";if(!CANONICAL_EVENTS.includes(event))throw new UsageError(`unknown event '${event}'`);return event}let fixed=TEMPLATE_EVENT[template];if(requested!==void 0&&requested!==fixed)throw new UsageError(`the ${template} template listens to ${fixed}, not '${requested}'`);return fixed}function writeFiles(dir,files){for(let f of files){let target=join2(dir,f.path);mkdirSync(dirname(target),{recursive:!0,mode:493}),writeFileSync2(target,f.content,{mode:f.mode})}}async function run(argv){let parsed=parseCommand(normalizeRepoFlag(argv),{dir:{type:"string"},event:{type:"string"},template:{type:"string"},repo:{type:"string"}},usage,1);if(!parsed)return 0;let id=parsed.positionals[0];if(!id)throw new UsageError("name the new plugin, e.g. hookmux new my-plugin");if(!PLUGIN_ID.test(id))throw new UsageError(`'${id}' is not a valid id: use lowercase letters, digits and dashes`);let template=parsed.values.template??"prompt-context";if(!TEMPLATES.includes(template))throw new UsageError(`unknown template '${template}': use ${TEMPLATES.join(", ")}`);let event=resolveEvent(template,parsed.values.event),repo=parsed.values.repo;if(repo!==void 0&&repo!==""&&!OWNER_NAME.test(repo))throw new UsageError(`--repo takes owner/name, not '${repo}'`);let dir=join2(resolve(parsed.values.dir??"."),id);if(existsSync(dir))return say("fail",`${dir} already exists`,"pick another id or --dir"),1;mkdirSync(dir,{recursive:!0,mode:493}),writeFiles(dir,[...scaffoldFiles(id,template,event),...repo===void 0?[]:repoFiles(id,template,repo)]);let report=validatePlugin(dir);return report.ok?(repo!==void 0&&fillReadmeCard(dir,id,repo),say("ok",`created ${dir}`),detail(`edit plugin.toml and tests.toml, then: hookmux test ${dir}${template==="session-note"?" --run-scripts":""}`),detail(`install it: hookmux add ${dir}`),repo!==void 0&&detail("publish it: git init and push to GitHub"),0):(say("fail",`scaffold does not validate: ${report.problems.join("; ")}`,"report this as a hookmux bug"),1)}export{run,usage};
@@ -0,0 +1,24 @@
1
+ import{confirmRelay,endStanding,promotePlugin,promoteWithGrant,refuseStandingRelay}from"./chunk-DJHE642J.mjs";import"./chunk-CA2GWCFP.mjs";import"./chunk-IAGBX723.mjs";import"./chunk-5GQP3BA6.mjs";import{installedDir}from"./chunk-CSXS5D2F.mjs";import"./chunk-RG3EOP4J.mjs";import"./chunk-G6SJQTFF.mjs";import"./chunk-BF25CRHJ.mjs";import{UsageError,parseCommand}from"./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{homePaths}from"./chunk-OYGOSD6V.mjs";import"./chunk-AHPMRYYF.mjs";var usage=`Usage: hookmux promote <id> [--standing | --end-standing]
2
+ hookmux promote <id> [--standing] --grant <token>
3
+ hookmux promote <id> --confirm <code>
4
+
5
+ Shows a plugin's card (what it can do and where it came from), asks to
6
+ confirm, then trusts its current content and capabilities and clears its
7
+ shadow flag. In your own terminal it asks you. It never accepts --yes.
8
+
9
+ From an agent client or a shell with no terminal, it prints the card and a
10
+ code instead and exits 3: the person approves by replying with that code in
11
+ their own message, and \`--confirm <code>\` then turns the plugin on if it is
12
+ unchanged since the card. A relayed approval never grants --standing.
13
+
14
+ --standing also let later \`hookmux add\` runs of this plugin activate
15
+ without asking while its capabilities stay within today's
16
+ --end-standing end that standing approval (works anywhere)
17
+ --grant <token> a one-time grant from the hub. When an agent in Claude Code
18
+ or Qwen Code runs \`hookmux promote <id>\`, the hub makes the
19
+ client ask you first and adds the grant to the command you
20
+ approve.
21
+ --confirm <code> turn the plugin on after the person replied with the code
22
+ from the card
23
+
24
+ Exit codes: 0 done, 1 refused or failed, 3 waiting for the person's reply.`;async function run(argv){let parsed=parseCommand(argv,{yes:{type:"boolean",short:"y"},standing:{type:"boolean"},"end-standing":{type:"boolean"},grant:{type:"string"},confirm:{type:"string"}},usage,1);if(!parsed)return 0;let id=parsed.positionals[0];if(!id)throw new UsageError("name the plugin to promote");let paths=homePaths();if(installedDir(paths,id),parsed.values["end-standing"]){if(parsed.values.standing)throw new UsageError("--standing and --end-standing do not go together");return endStanding(paths,id)}if(parsed.values.confirm!==void 0){if(parsed.values.grant!==void 0)throw new UsageError("--confirm and --grant do not go together");return parsed.values.yes?promotePlugin(paths,id,{assumeYes:!0}):parsed.values.standing?refuseStandingRelay(id):confirmRelay(paths,id,parsed.values.confirm)}return parsed.values.grant!==void 0?promoteWithGrant(paths,id,{token:parsed.values.grant,standing:parsed.values.standing===!0}):promotePlugin(paths,id,{assumeYes:parsed.values.yes===!0,standing:parsed.values.standing===!0})}export{run,usage};
@@ -0,0 +1 @@
1
+ import{compileRegistry}from"./chunk-IJHUIMJA.mjs";import"./chunk-K73ZPBFM.mjs";import"./chunk-7Z3AMI24.mjs";import"./chunk-ZNEBE4WO.mjs";import"./chunk-OYGOSD6V.mjs";import"./chunk-AHPMRYYF.mjs";export{compileRegistry};
@@ -0,0 +1,3 @@
1
+ import{installedDir}from"./chunk-CSXS5D2F.mjs";import{syncAfterChange}from"./chunk-G6SJQTFF.mjs";import{say}from"./chunk-BF25CRHJ.mjs";import{UsageError,parseCommand}from"./chunk-XPLEWNGF.mjs";import{readFlagsForUpdate,readSources,readTrust,writeFlags,writeSources,writeTrust}from"./chunk-IJHUIMJA.mjs";import"./chunk-K73ZPBFM.mjs";import"./chunk-OXHAGFXG.mjs";import"./chunk-2ZCM3JZR.mjs";import"./chunk-7Z3AMI24.mjs";import"./chunk-ZNEBE4WO.mjs";import{homePaths}from"./chunk-OYGOSD6V.mjs";import"./chunk-AHPMRYYF.mjs";import{existsSync,rmSync}from"node:fs";var usage=`Usage: hookmux remove <id>
2
+
3
+ Deletes plugins/<id>/ and its trust, flag and source records.`;async function run(argv){let parsed=parseCommand(argv,{},usage,1);if(!parsed)return 0;let id=parsed.positionals[0];if(!id)throw new UsageError("name the plugin to remove");let paths=homePaths(),dir=installedDir(paths,id),trust=readTrust(paths.trust),flags=readFlagsForUpdate(paths.flags),sources=readSources(paths.sources);return existsSync(dir)||trust.plugins[id]||sources[id]?(rmSync(dir,{recursive:!0,force:!0}),delete trust.plugins[id],delete sources[id],writeTrust(paths.trust,trust),writeSources(paths.sources,sources),writeFlags(paths.flags,{shadow:flags.shadow.filter(s=>s!==id),disabled:flags.disabled.filter(s=>s!==id)}),say("ok",`removed ${id}`),await syncAfterChange(paths)?0:1):(say("fail",`plugin '${id}' is not installed`,"hookmux list"),1)}export{run,usage};
@@ -0,0 +1,4 @@
1
+ import{CASE_FIELDS}from"./chunk-OMKE4U3M.mjs";import"./chunk-SXIEWTYT.mjs";import{bold,detail,dim}from"./chunk-BF25CRHJ.mjs";import{parseCommand}from"./chunk-XPLEWNGF.mjs";import{KNOWN_KEYS,MANIFEST_SCHEMA}from"./chunk-K73ZPBFM.mjs";import{ADAPTERS}from"./chunk-OXHAGFXG.mjs";import{FEATURES,featuresFor}from"./chunk-2ZCM3JZR.mjs";import{CANONICAL_EVENTS,PHASES,listChecks}from"./chunk-ZNEBE4WO.mjs";import"./chunk-OYGOSD6V.mjs";import{VERSION}from"./chunk-AHPMRYYF.mjs";var MANIFEST_KEY_DOCS={schema:"manifest format version; must be 1",id:"plugin id: lowercase letters, digits and dashes, max 64; must match the folder name",version:'plugin version string, default "0.0.0"',description:"one line shown by list and add",requires_hookmux:'hookmux versions this plugin needs, e.g. ">=0.1.0"',events:"canonical events the plugin listens to (see events)",hosts:"host ids the plugin is limited to; omit for every host",phase:"guard, route (default), enrich or observe; phases run in that order",priority:"integer, default 100; lower runs first within a phase",enabled:"true (default) or false",shadow:"true evaluates and logs the plugin but withholds its output",origins:'who produced the prompt: "user", "system", "unknown"; guards default to all, others to config route_origins',dedupe:'"none" (default) or "session": fire at most once per session',exclusive:"group name; only the first plugin of a group that fires contributes",on_error:'only "open" is accepted, and it changes nothing: hookmux always fails open, so "block" is rejected',when:"boolean expression over check names: and, or, not, parentheses, score comparisons such as s >= 0.7",when_degraded:"fallback expression used when `when` stays unknown (a check failed or timed out)",params:"table of strings, numbers or booleans available to templates",checks:"table of named checks: [checks.<name>] with a kind and that kind's options",then:"list of effects: [[then]] tables, applied in order when the plugin fires",host:"per-host overrides: [host.<id>] tables merged over the plugin for that host"},FALLBACK_DOC='list of "inject" and "notify": what to try, in order, where the host cannot perform this effect; [] drops it. Absent keeps the default.',EFFECT_DOCS={inject:{summary:"add text to the agent's context",fields:{text:"text to add, max 4000 characters",fallback:FALLBACK_DOC}},block:{summary:"stop the prompt or tool call; needs a rule-backed check to agree unless config allows otherwise",fields:{reason:"text shown to the user and the agent, max 4000 characters",suppress_original_prompt:"prompt.submit only: true hides the blocked prompt",fallback:FALLBACK_DOC}},notify:{summary:"show a message to the user without changing the context",fields:{text:"message text",fallback:FALLBACK_DOC}}};var usage=`Usage: hookmux schema [--json]
2
+
3
+ Prints manifest keys, check kinds, effects, events and what each host supports.`;function buildSchema(){return{hookmux:VERSION,manifestSchema:MANIFEST_SCHEMA,keys:[...KNOWN_KEYS].map(key=>({key,meaning:MANIFEST_KEY_DOCS[key]??""})),phases:[...PHASES],checks:listChecks().map(k=>({kind:k.kind,summary:k.summary,options:k.options,tier:k.tier,output:k.output,modelBacked:k.modelBacked})),effects:Object.entries(EFFECT_DOCS).map(([effect,doc])=>({effect,...doc})),events:[...CANONICAL_EVENTS],features:FEATURES.map(f=>({...f,events:[...f.events]})),hosts:Object.values(ADAPTERS).map(a=>({id:a.id,name:a.name,contextChars:a.contextChars,featureNotes:a.featureNotes??{},events:Object.fromEntries(CANONICAL_EVENTS.map(e=>[e,{native:a.nativeEvents[e],supports:a.nativeEvents[e]?a.supports[e]:[],features:featuresFor(a,e)}]))})),testCase:CASE_FIELDS}}async function run(argv){let parsed=parseCommand(argv,{json:{type:"boolean"}},usage);if(!parsed)return 0;let schema=buildSchema();if(parsed.values.json)return console.log(JSON.stringify(schema,null,2)),0;section(`Manifest keys (plugin.toml, schema = ${schema.manifestSchema})`);for(let k of schema.keys)detail(`${k.key.padEnd(18)} ${k.meaning}`);section("Check kinds");for(let c of schema.checks){detail(`${bold(c.kind)} ${dim(`tier ${c.tier}, ${c.output}${c.modelBacked?", model":""}`)} ${c.summary}`);for(let[name,text]of Object.entries(c.options))detail(` ${name}: ${text}`)}section("Effects ([[then]])");for(let e of schema.effects){detail(`${bold(e.effect)} ${e.summary}`);for(let[name,text]of Object.entries(e.fields))detail(` ${name}: ${text}`)}section("Events"),detail(schema.events.join(", ")),section("Features (host check: features, lacks)");for(let f of schema.features)detail(`${f.id.padEnd(22)} ${f.events.join(", ").padEnd(40)} ${f.meaning}`);section("Hosts");for(let h of schema.hosts){detail(bold(`${h.name} (${h.id})`));for(let[event,info]of Object.entries(h.events)){detail(` ${event.padEnd(14)} ${info.native??dim("not available")} ${info.supports.join(", ")}`);let lacks=featureIds(info.features,!1),unknown=featureIds(info.features,null);lacks&&detail(` lacks: ${lacks}`),unknown&&detail(` unknown: ${unknown}`)}}section("Test cases (tests.toml [[case]])");for(let[field,text]of Object.entries(schema.testCase))detail(`${field.padEnd(8)} ${text}`);return 0}function featureIds(facts,value){return Object.entries(facts).filter(([,v])=>v===value).map(([id])=>id).join(", ")}function section(title){console.log(`
4
+ ${bold(title)}`)}export{buildSchema,run,usage};
@@ -0,0 +1,4 @@
1
+ import{approveHubs,printHostResults,syncHosts}from"./chunk-G6SJQTFF.mjs";import{say}from"./chunk-BF25CRHJ.mjs";import{parseCommand}from"./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{homePaths}from"./chunk-OYGOSD6V.mjs";import"./chunk-AHPMRYYF.mjs";var usage=`Usage: hookmux sync
2
+
3
+ Registers the events installed plugins need on each host that already has
4
+ hookmux hub entries. add, remove, enable and promote run it for you.`;async function run(argv){if(!parseCommand(argv,{},usage))return 0;let paths=homePaths(),{events,results}=syncHosts(paths);if(results.length===0)return say("warn","no host has hub entries yet","hookmux init"),1;say("info",`events needed: ${events.join(", ")}`);let printed=printHostResults(results);return await approveHubs(paths,results)&&printed?0:1}export{run,usage};
@@ -0,0 +1,8 @@
1
+ import{TESTS_FILE,parseCases}from"./chunk-OMKE4U3M.mjs";import{compatLines,isPlain,planPlugin}from"./chunk-DZU2NMID.mjs";import{runEngine}from"./chunk-F3USS665.mjs";import{SCRIPT_NOT_RUN,STUBBED_MODEL_ERROR,adapterOrUsage,engineSettings,formatSignals,sampleEvent,stubModelChecks,withoutScripts}from"./chunk-SXIEWTYT.mjs";import{loadDefaults}from"./chunk-CSXS5D2F.mjs";import{clip,detail,printJson,say}from"./chunk-BF25CRHJ.mjs";import{UsageError,parseCommand}from"./chunk-XPLEWNGF.mjs";import{compileRegistry,fileHashesOf,readConfig,readPluginFiles}from"./chunk-IJHUIMJA.mjs";import{ManifestError,compileManifest,readManifest}from"./chunk-K73ZPBFM.mjs";import{ADAPTERS}from"./chunk-OXHAGFXG.mjs";import"./chunk-2ZCM3JZR.mjs";import"./chunk-7Z3AMI24.mjs";import{PLUGIN_ID}from"./chunk-ZNEBE4WO.mjs";import{homePaths}from"./chunk-OYGOSD6V.mjs";import"./chunk-AHPMRYYF.mjs";import{existsSync,readdirSync,readFileSync}from"node:fs";import{basename,join,resolve}from"node:path";var usage=`Usage: hookmux test [<id>|<path>] [--json] [--live] [--run-scripts]
2
+
3
+ Runs the [[case]] entries in a plugin's tests.toml. With no argument, tests
4
+ every installed plugin. Exit 1 when a case fails.
5
+
6
+ --live call model-backed checks (default: they return unknown)
7
+ --run-scripts run the scripts of a folder or an unpromoted plugin
8
+ (default: they return unknown; promoted plugins always run them)`;async function run(argv){let parsed=parseCommand(argv,{json:{type:"boolean"},live:{type:"boolean"},"run-scripts":{type:"boolean"}},usage,1);if(!parsed)return 0;parsed.values.live||stubModelChecks();let paths=homePaths(),targets=resolveTargets(parsed.positionals[0],paths.plugins),registry=compileRegistry(paths),settings=engineSettings(registry),config=readConfig(paths.config),runScripts=parsed.values["run-scripts"]===!0,reports=[];for(let{dir,installed}of targets){let entry=installed?registry.plugins.find(p=>p.id===basename(dir)):void 0,promoted=promotedSpecs(entry),target=promoted?{dir,overrides:{},scripts:{preview:!1,fileHashes:promoted.fileHashes},promoted}:{dir,overrides:installed?config.overrides:{},scripts:scriptAccess(dir,entry,runScripts)};reports.push(await testPlugin(target,{defaults:loadDefaults(config),settings}))}let all=reports.flatMap(r=>r.cases),summary={passed:all.filter(c=>c.status==="pass").length,failed:all.filter(c=>c.status==="fail").length,skipped:all.filter(c=>c.status==="skip").length},ok=summary.failed===0&&reports.every(r=>r.problems.length===0);return parsed.values.json?printJson({ok,plugins:reports,summary}):printReports(reports,summary,targets.length),ok?0:1}function resolveTargets(arg,pluginsDir){if(arg===void 0)return existsSync(pluginsDir)?readdirSync(pluginsDir,{withFileTypes:!0}).filter(d=>d.isDirectory()&&PLUGIN_ID.test(d.name)).map(d=>({dir:join(pluginsDir,d.name),installed:!0})).sort((a,b)=>a.dir.localeCompare(b.dir)):[];if(PLUGIN_ID.test(arg)&&existsSync(join(pluginsDir,arg)))return[{dir:join(pluginsDir,arg),installed:!0}];if(existsSync(arg))return[{dir:resolve(arg),installed:!1}];throw new UsageError(`'${arg}' is neither an installed plugin nor a folder`)}function promotedSpecs(entry){if(!(entry?.status!=="active"||!entry.trusted||!entry.base||!entry.fileHashes))return{id:entry.id,base:entry.base,variants:entry.variants??{},fileHashes:entry.fileHashes}}function scriptAccess(dir,entry,runScripts){if(!runScripts)return{preview:!0};try{return{preview:!1,fileHashes:entry?.fileHashes??fileHashesOf(readPluginFiles(dir).files)}}catch{return{preview:!1}}}async function testPlugin(target,ctx){let{dir,scripts}=target,{settings}=ctx,report={id:target.promoted?.id??basename(dir),path:dir,problems:[],cases:[],compat:[]},compiled=target.promoted??compileFromDisk(target,ctx.defaults,report);if(!compiled)return report;let testsFile=join(dir,TESTS_FILE);if(!existsSync(testsFile))return report.untested=!0,report;let{cases,problems}=parseCases(readFileSync(testsFile,"utf8"),Object.keys(ADAPTERS));report.problems.push(...problems);for(let[i,c]of cases.entries()){let spec=compiled.variants[c.host]??compiled.base,withHashes=scripts.fileHashes?{...spec,fileHashes:scripts.fileHashes}:spec;report.cases.push(await runCase(i+1,c,withHashes,{settings,preview:scripts.preview}))}let used=new Set(report.cases.map(c=>`${c.host}/${c.event}`));return report.compat=planPlugin(compiled,Object.values(ADAPTERS)).filter(r=>used.has(`${r.host}/${r.event}`)),report}function compileFromDisk(target,defaults,report){try{let raw=readManifest(target.dir);return typeof raw.id=="string"&&(report.id=raw.id),compileManifest(raw,target.dir,target.overrides[report.id],defaults)}catch(error){report.problems=error instanceof ManifestError?error.problems:[error.message];return}}async function runCase(index,c,spec,opts){let event=withCommand(sampleEvent(adapterOrUsage(c.host),c.event,c.prompt,c.cwd),c.command),forced={...spec,shadow:!1,dedupe:"none",enabled:!0},plugin=opts.preview?withoutScripts(forced):forced,trace=(await runEngine({event,plugins:[plugin],settings:opts.settings,firedThisSession:new Set})).trace.find(t=>t.id===spec.id),outcome=trace?.outcome??"not-selected",signals=trace?.signals??{},stubbed=Object.values(signals).some(s=>s.error===STUBBED_MODEL_ERROR||s.error===SCRIPT_NOT_RUN),expected=c.expect==="fire"?outcome==="fire":outcome==="silent"||outcome==="not-selected",status=outcome==="unknown"&&stubbed?"skip":expected?"pass":"fail",note=trace?.note??(outcome==="not-selected"?"plugin does not listen to this host, event or origin":void 0);return{index,prompt:c.prompt,host:c.host,event:c.event,expect:c.expect,...c.cwd?{cwd:c.cwd}:{},outcome,status,signals,...note?{note}:{},ms:Math.round(trace?.ms??0)}}function withCommand(event,command){if(command===void 0||!event.tool)return event;let input=typeof event.tool.input=="object"&&event.tool.input!==null?event.tool.input:{};return{...event,tool:{...event.tool,input:{...input,command}}}}function timing(cases){return{totalMs:cases.reduce((sum,c)=>sum+c.ms,0),slowestMs:Math.max(0,...cases.map(c=>c.ms))}}function scriptSkipped(c){return Object.values(c.signals).some(s=>s.error===SCRIPT_NOT_RUN)}function skipReason(c){return scriptSkipped(c)?"script not run":"model check stubbed"}function skipHint(c,r){return scriptSkipped(c)?`hookmux test ${r.path} --run-scripts`:`hookmux test ${r.id} --live`}function printReports(reports,summary,targetCount){targetCount===0&&say("info","no plugins installed","hookmux test <path>");for(let r of reports){r.untested&&say("warn",`${r.id}: no ${TESTS_FILE}, nothing tested`,`add ${TESTS_FILE} next to plugin.toml`);for(let p of r.problems)say("fail",`${r.id}: ${p}`,`hookmux validate ${r.path}`);for(let c of r.cases){let label=`${r.id} #${c.index} ${c.expect}: ${clip(c.prompt||c.cwd||c.event,50)}`;c.status==="pass"?say("ok",label):c.status==="skip"?say("warn",`${label} (unknown: ${skipReason(c)})`,skipHint(c,r)):(say("fail",`${label} \u2192 got ${c.outcome}`),Object.keys(c.signals).length>0&&detail(`signals: ${formatSignals(c.signals)}`),c.note&&detail(`note: ${c.note}`))}for(let l of compatLines(r.compat.filter(row=>!isPlain(row))))detail(`${r.id}: ${l}`);if(r.cases.length>0){let{totalMs,slowestMs}=timing(r.cases);detail(`${r.id}: took ${totalMs} ms (slowest case ${slowestMs} ms)`)}}say(summary.failed>0?"fail":"ok",`${summary.passed} passed, ${summary.failed} failed, ${summary.skipped} skipped`)}export{run,usage};
@@ -0,0 +1,7 @@
1
+ import{adapterOrUsage}from"./chunk-SXIEWTYT.mjs";import{confirm,isInteractive}from"./chunk-RG3EOP4J.mjs";import{allAdapters,printHostResults,wiredAdapters}from"./chunk-G6SJQTFF.mjs";import{say}from"./chunk-BF25CRHJ.mjs";import{parseCommand}from"./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{homePaths}from"./chunk-OYGOSD6V.mjs";import"./chunk-AHPMRYYF.mjs";import{existsSync,rmSync}from"node:fs";import{homedir}from"node:os";import{join,resolve}from"node:path";var usage=`Usage: hookmux uninstall [--host <id>]... [--purge] [--yes]
2
+
3
+ Removes hookmux hub entries from host configs. Other hooks stay as they are.
4
+
5
+ --host <id> only this host (repeatable); default: every host with hub entries
6
+ --purge also delete the hookmux home folder (plugins, trust, logs)
7
+ --yes, -y do not ask before --purge`,HOME_MARKERS=["engine","bin","plugins","trust.json","registry.json"];async function run(argv){let parsed=parseCommand(argv,{host:{type:"string",multiple:!0},purge:{type:"boolean"},yes:{type:"boolean",short:"y"}},usage);if(!parsed)return 0;let paths=homePaths(),ids=parsed.values.host??[],adapters=ids.length>0?ids.map(adapterOrUsage):allAdapters().filter(a=>a.config.installed(paths.launcher).length>0),ok=!0;if(adapters.length===0?say("info","no host has hub entries"):ok=printHostResults(adapters.map(adapter=>{try{return{adapter,change:adapter.config.uninstall(paths.launcher)}}catch(error){return{adapter,error:error.message}}})),!parsed.values.purge)return ok?0:1;let stillWired=wiredAdapters(paths);if(!ok||stillWired.length>0){let which=stillWired.map(a=>a.id).join(", ")||"a host";return say("fail",`home folder kept: ${which} still has hub entries`,"hookmux uninstall --purge"),1}return purge(paths,parsed.values.yes===!0)}async function purge(paths,yes){let root=resolve(paths.root);if(!existsSync(root))return say("info",`${root} does not exist`),0;if(root===resolve(homedir())||root==="/"||!HOME_MARKERS.some(m=>existsSync(join(root,m))))return say("fail",`${root} does not look like a hookmux home; not deleting it`,"delete it by hand if you are sure"),1;if(!yes){if(!isInteractive())return say("fail",`not deleting ${root} without confirmation`,"hookmux uninstall --purge --yes"),1;if(!await confirm(`Delete ${root} and everything in it?`,!1))return say("info","home folder kept"),0}return rmSync(root,{recursive:!0,force:!0}),say("ok",`deleted ${root}`),0}export{run,usage};
@@ -0,0 +1 @@
1
+ import{run,usage,validatePlugin}from"./chunk-65XA3RK3.mjs";import"./chunk-DZU2NMID.mjs";import"./chunk-CSXS5D2F.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{run,usage,validatePlugin};
package/dist/cli.mjs ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import{UsageError}from"./chunks/chunk-XPLEWNGF.mjs";import{VERSION}from"./chunks/chunk-AHPMRYYF.mjs";import{resolve}from"node:path";var COMMANDS={init:{summary:"install the engine and wire hosts (re-run to update)",load:()=>import("./chunks/init-46THKH7Z.mjs")},uninstall:{summary:"remove hub entries from hosts (--purge: also the home folder)",load:()=>import("./chunks/uninstall-ZMGYPYVA.mjs")},sync:{summary:"register the events installed plugins need on wired hosts",load:()=>import("./chunks/sync-UCVS5O2X.mjs")},add:{summary:"install plugins from a folder or git repo (untrusted until promoted)",load:()=>import("./chunks/add-ZWGK62EX.mjs")},install:{summary:"set up hookmux and add a plugin in one step (asks you to approve it)",load:()=>import("./chunks/install-J4QGOOCD.mjs")},promote:{summary:"review and activate a plugin (asks you; an agent gets a card for you to answer)",load:()=>import("./chunks/promote-4RJUMW7Y.mjs")},remove:{summary:"delete an installed plugin",load:()=>import("./chunks/remove-XCOCPNJJ.mjs")},enable:{summary:"turn a disabled plugin back on",load:()=>import("./chunks/enable-SWA7C4K2.mjs")},disable:{summary:"turn a plugin off without removing it",load:()=>import("./chunks/disable-KRHQYUQU.mjs")},list:{summary:"show installed plugins and their status",load:()=>import("./chunks/list-NAFC2CUM.mjs")},new:{summary:"scaffold a plugin.toml and tests.toml",load:()=>import("./chunks/new-UASRUAP2.mjs")},validate:{summary:"check a plugin folder for problems",load:()=>import("./chunks/validate-ICFP6TSC.mjs")},test:{summary:"run a plugin's tests.toml cases",load:()=>import("./chunks/test-BCLMCB5A.mjs")},explain:{summary:"show what each plugin decides for a prompt, and the host output",load:()=>import("./chunks/explain-WNQLELTA.mjs")},doctor:{summary:"check the install end to end (--fix repairs what it can)",load:()=>import("./chunks/doctor-KERAJBFA.mjs")},log:{summary:"turn the decision log on or off, and read it",load:()=>import("./chunks/log-ELHUFP5Y.mjs")},schema:{summary:"print manifest keys, check kinds, effects, events and host support",load:()=>import("./chunks/schema-FFOAJAET.mjs")}};function helpText(){let width=Math.max(...Object.keys(COMMANDS).map(n=>n.length)),rows=Object.entries(COMMANDS).map(([name,c])=>` ${name.padEnd(width)} ${c.summary}`);return[`hookmux ${VERSION}: one hook entry for every coding agent`,"","Usage: hookmux [--home <dir>] <command> [options]","","Commands:",...rows,"","Global options:"," --home <dir> hookmux home folder (default $HOOKMUX_HOME or ~/.hookmux)"," --version print the version","","Run 'hookmux <command> --help' for a command's options."].join(`
3
+ `)}function takeHome(argv){let out=[];for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="--"){out.push(...argv.slice(i));break}let dir;if(arg==="--home"){if(dir=argv[++i],dir===void 0||dir==="")throw new UsageError("--home needs a folder")}else if(arg.startsWith("--home="))dir=arg.slice(7);else{out.push(arg);continue}process.env.HOOKMUX_HOME=resolve(dir)}return out}async function main(argv){let name;try{let[first,...rest]=takeHome(argv);if(name=first,name===void 0||name==="help"||name==="--help"||name==="-h")return console.log(helpText()),0;if(name==="--version"||name==="-v"||name==="version")return console.log(VERSION),0;let command=Object.hasOwn(COMMANDS,name)?COMMANDS[name]:void 0;if(!command)throw new UsageError(`unknown command '${name}'`);return await(await command.load()).run(rest)}catch(error){if(process.env.HOOKMUX_DEBUG==="1"&&console.error(error?.stack??error),error instanceof UsageError){let help=name&&Object.hasOwn(COMMANDS,name)?`hookmux ${name} --help`:"hookmux help";return console.error(`hookmux: ${error.message}
4
+ Run '${help}'.`),2}return console.error(`\u2717 hookmux: ${error?.message??String(error)}`),1}}main(process.argv.slice(2)).then(code=>{process.exitCode=code});
package/dist/hook.mjs ADDED
@@ -0,0 +1 @@
1
+ import{enableCompileCache}from"node:module";import{homedir}from"node:os";import{join}from"node:path";try{enableCompileCache?.(join(process.env.HOOKMUX_HOME||join(homedir(),".hookmux"),"cache","compile"))}catch{}await import("./chunks/hook-main-PW67WMNF.mjs");
@@ -0,0 +1,83 @@
1
+ #!/bin/sh
2
+ # hookmux launcher. Agent clients run this on every hook event, so it must
3
+ # never fail or stall them: whatever happens it exits 0, and it prints the
4
+ # engine's stdout only when the engine finished cleanly, which every client
5
+ # reads as "no opinion" when empty. A watchdog kills an engine that hangs (for
6
+ # example on a regex that backtracks), so the client always gets an answer.
7
+ # `hookmux init` fills in the two paths below. POSIX sh: Ubuntu's /bin/sh is dash.
8
+
9
+ # Gemini CLI parses stderr as output when stdout is empty, so nothing may reach it.
10
+ exec 2>/dev/null
11
+
12
+ NODE='@NODE@'
13
+ ENGINE='@ROOT@/engine/current/hook.mjs'
14
+ # Seconds before the watchdog stops the engine. It bounds a run that cannot
15
+ # reach its own deadline (2 s by default). deadline_ms may be set higher, up to
16
+ # 20 s, but a run past this limit still ends here with no output.
17
+ WATCHDOG_SEC=5
18
+
19
+ # Nothing to run: return at once and leave stdin unread, so a client that keeps
20
+ # the pipe open is not held up.
21
+ if [ ! -x "$NODE" ] || [ ! -f "$ENGINE" ]; then
22
+ exit 0
23
+ fi
24
+
25
+ # The engine writes to a private temp file, so a half-written answer from an
26
+ # engine that crashes or is killed never reaches the client. Both ends are
27
+ # opened here and the name is removed while the engine starts, so nothing is
28
+ # left in TMPDIR even if this script is killed; fd 3 reads the answer back.
29
+ # fd 5 keeps the client's stdin for the engine (see below). `command` keeps a
30
+ # failed redirection from ending the shell with status 2, which Claude Code
31
+ # would read as a block; the temp file is removed before leaving. The fd 5 copy
32
+ # fails when the client started the hook with stdin closed.
33
+ out=$(mktemp "${TMPDIR:-/tmp}/hookmux-out.XXXXXX") || exit 0
34
+ command exec 3<"$out" 4>"$out" 5<&0 || {
35
+ rm -f "$out"
36
+ exit 0
37
+ }
38
+
39
+ # NODE_OPTIONS could load code into the engine, and NODE_USE_ENV_PROXY would
40
+ # send a local model provider's traffic (the prompt) through an HTTP proxy.
41
+ unset NODE_OPTIONS NODE_USE_ENV_PROXY
42
+
43
+ # A background job's stdin is /dev/null before its own redirections apply
44
+ # (POSIX, and what dash does), so `<&0` would only copy /dev/null; the
45
+ # client's stdin comes from the copy saved on fd 5 instead.
46
+ HOOKMUX_HOME='@ROOT@' NODE_NO_WARNINGS=1 "$NODE" "$ENGINE" "$@" <&5 >&4 3<&- 4>&- 5<&- &
47
+ pid=$!
48
+ exec 4>&- 5<&-
49
+ rm -f "$out"
50
+
51
+ # The watchdog's own fds point at /dev/null, so it never holds the client's
52
+ # stdout pipe open after this script exits. TERM first lets a responsive engine
53
+ # kill the scripts it started; KILL follows for one that is stuck. When the
54
+ # engine finishes first, the watchdog is stopped together with its sleep, so
55
+ # no process is left behind after a normal run.
56
+ (
57
+ exec 3<&-
58
+ nap=
59
+ trap 'kill "$nap"; exit 0' TERM
60
+ sleep "$WATCHDOG_SEC" &
61
+ nap=$!
62
+ wait "$nap"
63
+ kill -TERM "$pid"
64
+ sleep 1
65
+ kill -KILL "$pid"
66
+ ) </dev/null >/dev/null 2>&1 &
67
+ watchdog=$!
68
+
69
+ stop_watchdog() {
70
+ kill -TERM "$watchdog"
71
+ }
72
+
73
+ # A client that gives up on the hook signals this script; pass it on so the
74
+ # engine stops its scripts, then leave quietly.
75
+ trap 'kill -TERM "$pid"; wait "$pid"; stop_watchdog; exit 0' TERM HUP INT
76
+
77
+ wait "$pid"
78
+ code=$?
79
+ stop_watchdog
80
+ if [ "$code" -eq 0 ]; then
81
+ cat <&3
82
+ fi
83
+ exit 0