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.
- package/LICENSE +21 -0
- package/README.md +402 -2
- package/dist/chunks/add-ZWGK62EX.mjs +1 -0
- package/dist/chunks/chunk-2ZCM3JZR.mjs +3 -0
- package/dist/chunks/chunk-5GQP3BA6.mjs +1 -0
- package/dist/chunks/chunk-65XA3RK3.mjs +4 -0
- package/dist/chunks/chunk-6GL55FEQ.mjs +20 -0
- package/dist/chunks/chunk-7Z3AMI24.mjs +1 -0
- package/dist/chunks/chunk-AHPMRYYF.mjs +1 -0
- package/dist/chunks/chunk-BF25CRHJ.mjs +1 -0
- package/dist/chunks/chunk-CA2GWCFP.mjs +3 -0
- package/dist/chunks/chunk-CSXS5D2F.mjs +1 -0
- package/dist/chunks/chunk-CZY5UAXM.mjs +1 -0
- package/dist/chunks/chunk-DJHE642J.mjs +7 -0
- package/dist/chunks/chunk-DZU2NMID.mjs +1 -0
- package/dist/chunks/chunk-F3USS665.mjs +1 -0
- package/dist/chunks/chunk-FF55QGCZ.mjs +1 -0
- package/dist/chunks/chunk-G6SJQTFF.mjs +1 -0
- package/dist/chunks/chunk-IAGBX723.mjs +2 -0
- package/dist/chunks/chunk-IJHUIMJA.mjs +5 -0
- package/dist/chunks/chunk-K73ZPBFM.mjs +45 -0
- package/dist/chunks/chunk-L3BSVLQG.mjs +1 -0
- package/dist/chunks/chunk-OMKE4U3M.mjs +1 -0
- package/dist/chunks/chunk-OXHAGFXG.mjs +12 -0
- package/dist/chunks/chunk-OYGOSD6V.mjs +1 -0
- package/dist/chunks/chunk-QTY23VNU.mjs +1 -0
- package/dist/chunks/chunk-RG3EOP4J.mjs +1 -0
- package/dist/chunks/chunk-SXIEWTYT.mjs +1 -0
- package/dist/chunks/chunk-UERSXYXZ.mjs +3 -0
- package/dist/chunks/chunk-WZSNBZ6D.mjs +2 -0
- package/dist/chunks/chunk-XPLEWNGF.mjs +1 -0
- package/dist/chunks/chunk-ZDCAHPWY.mjs +2 -0
- package/dist/chunks/chunk-ZNEBE4WO.mjs +1 -0
- package/dist/chunks/disable-KRHQYUQU.mjs +3 -0
- package/dist/chunks/doctor-KERAJBFA.mjs +7 -0
- package/dist/chunks/enable-SWA7C4K2.mjs +4 -0
- package/dist/chunks/explain-WNQLELTA.mjs +9 -0
- package/dist/chunks/hook-main-PW67WMNF.mjs +1 -0
- package/dist/chunks/init-46THKH7Z.mjs +12 -0
- package/dist/chunks/install-J4QGOOCD.mjs +15 -0
- package/dist/chunks/list-NAFC2CUM.mjs +5 -0
- package/dist/chunks/log-ELHUFP5Y.mjs +11 -0
- package/dist/chunks/new-UASRUAP2.mjs +186 -0
- package/dist/chunks/promote-4RJUMW7Y.mjs +24 -0
- package/dist/chunks/registry-P6V5HZQN.mjs +1 -0
- package/dist/chunks/remove-XCOCPNJJ.mjs +3 -0
- package/dist/chunks/schema-FFOAJAET.mjs +4 -0
- package/dist/chunks/sync-UCVS5O2X.mjs +4 -0
- package/dist/chunks/test-BCLMCB5A.mjs +8 -0
- package/dist/chunks/uninstall-ZMGYPYVA.mjs +7 -0
- package/dist/chunks/validate-ICFP6TSC.mjs +1 -0
- package/dist/cli.mjs +4 -0
- package/dist/hook.mjs +1 -0
- package/launcher/hookmux-hook.sh +83 -0
- package/launcher/opencode-plugin.js +236 -0
- package/package.json +57 -4
- package/plugins/hookmux-authoring/plugin.toml +65 -0
- package/plugins/hookmux-authoring/tests.toml +119 -0
- package/skills/hookmux/SKILL.md +102 -0
- package/skills/hookmux/references/check-kinds.md +124 -0
- package/skills/hookmux/references/effects.md +24 -0
- package/skills/hookmux/references/examples/moodboard/plugin.toml +72 -0
- package/skills/hookmux/references/examples/moodboard/tests.toml +20 -0
- package/skills/hookmux/references/hosts.md +173 -0
- package/skills/hookmux/references/plugin-format.md +400 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{resolveEffect}from"./chunk-OXHAGFXG.mjs";import{FEATURES,featuresFor}from"./chunk-2ZCM3JZR.mjs";var TOOL_FILE_PATH_FIELD="tool.input.file_path";function caveatFor(feature,value){if(value===!0)return;let note=FEATURES.find(f=>f.id===feature)?.caveat??feature;return{feature,value,note}}function inputFeatures(spec,event){let checks=Object.values(spec.checks),out=[];return checks.some(c=>c.kind==="host"&&c.version!==void 0)&&out.push("host.version"),event==="prompt.submit"&&spec.origins.length===1&&spec.origins[0]==="user"&&out.push("prompt.origin"),checks.some(c=>typeof c.field=="string"&&c.field.startsWith(TOOL_FILE_PATH_FIELD))&&out.push("tool.file-path"),out}function matters(feature,effect){return feature==="block.suppress-prompt"?effect.effect==="block"&&effect.suppressOriginalPrompt===!0:feature==="inject.markup"?/[<>]/.test(effect.effect==="block"?effect.reason:effect.text):!0}function effectFeatures(performed,effect,facts){return FEATURES.filter(f=>f.effect===performed&&f.id in facts).map(f=>f.id).filter(id=>matters(id,effect))}function rowsFor(spec,host,event){let facts=featuresFor(host,event),supports=new Set(host.supports[event]),input=inputFeatures(spec,event);return spec.effects.map((effect,index)=>{let resolved=resolveEffect(effect.effect,effect.fallback,supports),caveats=[...input,...resolved.as?effectFeatures(resolved.as,effect,facts):[]].flatMap(id=>caveatFor(id,facts[id]??null)??[]),outcome=resolved.as===null?"dropped":resolved.via==="native"?"works":"fallback";return{host:host.id,event,index,effect:effect.effect,outcome,as:resolved.as,via:resolved.via,...resolved.note?{note:resolved.note}:{},caveats}})}function planPlugin(compiled,hosts){return hosts.flatMap(host=>{let spec=compiled.variants[host.id]??compiled.base;return spec.hosts.length>0&&!spec.hosts.includes(host.id)?[]:spec.events.filter(e=>host.nativeEvents[e]!==null).flatMap(e=>rowsFor(spec,host,e))})}function isPlain(row){return row.outcome==="works"&&row.caveats.length===0}var WIDTHS={host:11,event:14,effect:7};function outcomeText(row){return row.outcome==="works"?"works":row.outcome==="fallback"?`\u2192 ${row.as} (${row.via==="author"?"fallback":"engine"})`:`dropped: ${row.note??"host cannot do this here"}`}function caveatText(c){return`${c.value===!1?"\u2717":"?"} ${c.feature}: ${c.note}`}function line(row){return[[row.host.padEnd(WIDTHS.host),row.event.padEnd(WIDTHS.event),row.effect.padEnd(WIDTHS.effect),outcomeText(row)].join(" "),...row.caveats.map(caveatText)].join(" ")}function compatLines(rows){if(rows.length===0)return[];let plainHosts=[...new Set(rows.map(r=>r.host))].filter(h=>rows.filter(r=>r.host===h).every(isPlain)),lines=[];plainHosts.length>0&&lines.push(`compat: works everywhere on ${plainHosts.join(", ")}`);for(let row of rows)plainHosts.includes(row.host)||lines.push(line(row));return lines}export{planPlugin,isPlain,compatLines};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{compose}from"./chunk-OXHAGFXG.mjs";import{evalExpr,exprRefs,getCheck,parseExpr}from"./chunk-ZNEBE4WO.mjs";function selectPlugins(event,plugins){return plugins.filter(p=>p.enabled&&p.events.includes(event.name)&&(p.hosts.length===0||p.hosts.includes(event.host.id))&&p.origins.includes(event.origin))}async function runEngine(input){let{event,settings}=input,deadlineAt=performance.now()+settings.deadlineMs,controller=new AbortController,timer=setTimeout(()=>controller.abort(),settings.deadlineMs);timer.unref();let skipped=[],candidates=[];for(let plugin of selectPlugins(event,input.plugins)){if(plugin.dedupe==="session"&&input.firedThisSession.has(plugin.id)){skipped.push(trace(plugin,"skipped",{},0,"already fired this session"));continue}let candidate=prepare(plugin);typeof candidate=="string"?skipped.push(trace(plugin,"error",{},0,candidate)):candidates.push(candidate)}let ctxFor=plugin=>({event,plugin,signal:controller.signal,remainingMs:()=>Math.max(0,deadlineAt-performance.now()),settings:settings.runtime});try{for(let tier of[0,1,2]){let jobs=[];for(let c of candidates)if(c.decided=evalExpr(c.when,c.signals),c.decided===null)for(let name of c.refs){if(c.signals[name]!==void 0)continue;let spec=c.plugin.checks[name],kind=spec?getCheck(spec.kind):void 0;if(!spec||!kind){c.signals[name]={value:null,error:`unknown check '${name}'`};continue}kind.tier===tier&&jobs.push(runCheck(()=>kind.run(spec,ctxFor(c.plugin)),controller.signal).then(s=>{c.signals[name]=s}))}await Promise.all(jobs)}}finally{clearTimeout(timer)}let traces=[...skipped],fired=[];for(let c of candidates){let outcome=decide(c);traces.push(trace(c.plugin,outcome,c.signals,performance.now()-c.started,c.error)),outcome==="fire"&&fired.push(c.plugin)}return compose(event,fired,traces,settings)}function prepare(plugin){try{let when=parseExpr(plugin.when),degraded=plugin.whenDegraded?parseExpr(plugin.whenDegraded):void 0,refs=exprRefs(when);return degraded&&exprRefs(degraded,refs),{plugin,when,degraded,refs:[...refs],signals:{},started:performance.now(),decided:null}}catch(error){return`invalid when: ${error.message}`}}function decide(c){let value=evalExpr(c.when,c.signals);if(value===!0)return"fire";if(value===!1)return"silent";if(c.degraded){let fallback=evalExpr(c.degraded,c.signals);if(fallback===!0)return"fire";if(fallback===!1)return"silent"}return"unknown"}async function runCheck(run,abort){let started=performance.now();try{if(abort.aborted)return{value:null,error:"deadline reached",ms:0};let pending=Promise.resolve().then(run),aborted=new Promise(done=>{abort.addEventListener("abort",()=>done({value:null,error:"deadline reached"}),{once:!0})});return{...await Promise.race([pending,aborted]),ms:Math.round(performance.now()-started)}}catch(error){return{value:null,error:error?.message??String(error),ms:Math.round(performance.now()-started)}}}function trace(plugin,outcome,signals,ms,note){return{id:plugin.id,outcome,shadow:plugin.shadow,signals,ms:Math.round(ms),...note?{note}:{}}}export{selectPlugins,runEngine};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{engineStatus,installEngine,stableNodePath,writeLauncher}from"./chunk-L3BSVLQG.mjs";import{discardStaged,placeStaged,pluginFoldersIn,stagePlugin}from"./chunk-CZY5UAXM.mjs";import{agentHost}from"./chunk-5GQP3BA6.mjs";import{loadDefaults}from"./chunk-CSXS5D2F.mjs";import{confirm,isInteractive}from"./chunk-RG3EOP4J.mjs";import{allAdapters,approveHubs,installHub,neededEvents,printHostResults}from"./chunk-G6SJQTFF.mjs";import{say}from"./chunk-BF25CRHJ.mjs";import{UsageError}from"./chunk-XPLEWNGF.mjs";import{BUNDLED_SOURCE,compileRegistry,hashPlugin,readConfig,readSources,readTrust,writeInstallState,writeSources,writeTrust}from"./chunk-IJHUIMJA.mjs";import{packageLayout}from"./chunk-OXHAGFXG.mjs";import{saveRegistry}from"./chunk-7Z3AMI24.mjs";import{VERSION}from"./chunk-AHPMRYYF.mjs";import{existsSync}from"node:fs";import{basename,join}from"node:path";function installBundled(paths,pluginsDir,defaults){if(!existsSync(pluginsDir))return[];let sources=readSources(paths.sources),trust=readTrust(paths.trust),results=[];for(let dir of pluginFoldersIn(pluginsDir)){let staged;try{staged=stagePlugin(dir,paths,defaults)}catch(error){results.push({id:basename(dir),status:"invalid",detail:error.message});continue}let target=join(paths.plugins,staged.id),origin=sources[staged.id]?.source;if(existsSync(target)&&origin!==BUNDLED_SOURCE){discardStaged(staged),results.push({id:staged.id,status:"skipped",detail:`an installed plugin from ${origin??"elsewhere"} uses this id`});continue}if(existsSync(target)&&hashPlugin(target)===staged.hash&&trust.plugins[staged.id]?.hash===staged.hash){discardStaged(staged),results.push({id:staged.id,status:"unchanged"});continue}placeStaged(staged,paths,!0);let now=new Date().toISOString();trust.plugins[staged.id]={hash:staged.hash,capabilities:staged.capabilities,promotedAt:now},sources[staged.id]={source:BUNDLED_SOURCE,ref:VERSION,commit:null,hash:staged.hash,addedAt:now},results.push({id:staged.id,status:"installed"})}return writeTrust(paths.trust,trust),writeSources(paths.sources,sources),results}import{cpSync,existsSync as existsSync2,mkdirSync,renameSync,rmSync}from"node:fs";import{dirname,join as join2}from"node:path";var SKILL_FOLDER="hookmux";function installSkill(skillDir,adapters){if(!existsSync2(skillDir))return[];let results=[];for(let adapter of adapters){if(!adapter.skills)continue;let target=join2(adapter.skills.global,SKILL_FOLDER);try{let temp=`${target}.tmp-${process.pid}`;mkdirSync(dirname(target),{recursive:!0}),rmSync(temp,{recursive:!0,force:!0}),cpSync(skillDir,temp,{recursive:!0}),rmSync(target,{recursive:!0,force:!0}),renameSync(temp,target),results.push({adapter,target})}catch(error){results.push({adapter,target,error:error.message})}}return results}function versionParts(version){let m=/^(\d+)\.(\d+)\.(\d+)/.exec(version);return m?[Number(m[1]),Number(m[2]),Number(m[3])]:null}function engineNeedsSetup(paths,cliVersion=VERSION){let status=engineStatus(paths);if(!status.ok||status.version===null)return!0;if(status.version===cliVersion)return!1;let have=versionParts(status.version),want=versionParts(cliVersion);if(!have||!want)return!0;for(let i=0;i<3;i++)if(have[i]!==want[i])return have[i]<want[i];return!1}async function setupHub(paths,opts){let layout=packageLayout();if(opts.engine){let engine=installEngine(paths,layout.dist,VERSION);say("ok",`engine ${engine.version} ${engine.copied?"installed":"already current"} (${engine.dir})`),engine.pruned.length>0&&say("info",`removed old engines: ${engine.pruned.join(", ")}`),writeLauncher(paths,layout.launcherTemplate),say("ok",`launcher ${paths.launcher} (node ${stableNodePath()})`),writeInstallState(paths.installState,{timeoutSec:opts.timeoutSec})}opts.bundled&&printBundled(installBundled(paths,layout.plugins,loadDefaults(readConfig(paths.config))));let registry=compileRegistry(paths);saveRegistry(paths,registry);let events=neededEvents(registry),hostResults=opts.adapters.map(a=>installHub(a,paths,events)),printed=printHostResults(hostResults),hostsOk=await approveHubs(paths,hostResults)&&printed;return opts.skill&&printSkill(layout.skill,opts.adapters),hostsOk}function printBundled(results){results.length===0&&say("info","no bundled plugins in this package");for(let r of results)r.status==="installed"?say("ok",`bundled plugin ${r.id} installed and trusted`):r.status==="unchanged"?say("ok",`bundled plugin ${r.id} already current`):r.status==="skipped"?say("warn",`bundled plugin ${r.id} skipped: ${r.detail}`,"hookmux list"):say("fail",`bundled plugin ${r.id} is invalid: ${r.detail}`,"reinstall hookmux")}function printSkill(skillDir,adapters){let results=installSkill(skillDir,adapters);results.length===0&&say("info","authoring skill not installed (not in this package, or no host has a skill folder)");for(let r of results)r.error?say("fail",`${r.adapter.name} skill: ${r.error}`,"hookmux init"):say("ok",`${r.adapter.name} skill: ${r.target}`)}var detectedClients=()=>allAdapters().filter(a=>a.config.detect());function namedHosts(ids){let all=allAdapters();return[...new Set(ids)].map(id=>{let adapter=all.find(a=>a.id===id);if(!adapter)throw new UsageError(`unknown host '${id}'; known hosts: ${all.map(a=>a.id).join(", ")}`);return adapter.config.detect()||say("warn",`${adapter.name} was not detected; wiring it anyway`),adapter})}async function pickOnTerminal(){let picked=[];for(let adapter of detectedClients())await confirm(`Wire ${adapter.name}?`,!0)&&picked.push(adapter);return picked}async function chooseHosts(ids,yes,wired){if(ids.length>0)return namedHosts(ids);if(yes)return detectedClients();if(isInteractive())return pickOnTerminal();if(wired.length>0)return say("info",`updating hosts already wired: ${wired.map(a=>a.id).join(", ")}`),wired;let found=detectedClients().map(a=>a.id).join(", ")||"none";throw new UsageError(`stdin is not a terminal: pass --host <id> or --yes (detected: ${found})`)}async function chooseInstallHosts(ids,atTerminal,env){if(ids.length>0)return namedHosts(ids);if(atTerminal)return pickOnTerminal();let marked=agentHost(env);if(marked)return namedHosts([marked]);let found=detectedClients().map(a=>a.id).join(", ")||"none";throw new UsageError(`name your client: hookmux install <source> --host <id> (detected: ${found})`)}export{engineNeedsSetup,setupHub,chooseHosts,chooseInstallHosts};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{detail,say}from"./chunk-BF25CRHJ.mjs";import{compileRegistry,readInstallState}from"./chunk-IJHUIMJA.mjs";import{ADAPTERS,CodexUnavailableError}from"./chunk-OXHAGFXG.mjs";import{saveRegistry}from"./chunk-7Z3AMI24.mjs";import{CANONICAL_EVENTS}from"./chunk-ZNEBE4WO.mjs";var BASE_EVENTS=["prompt.submit","session.start"],EVENT_CAPABILITY="event:";function allAdapters(){return Object.values(ADAPTERS)}function neededEvents(registry){let wanted=new Set(BASE_EVENTS);for(let p of registry.plugins)if(p.status!=="invalid")for(let c of p.capabilities)c.startsWith(EVENT_CAPABILITY)&&wanted.add(c.slice(EVENT_CAPABILITY.length));return CANONICAL_EVENTS.filter(e=>wanted.has(e))}function wiredAdapters(paths){return allAdapters().filter(a=>a.config.installed(paths.launcher).length>0)}function installHub(adapter,paths,events){try{let{timeoutSec}=readInstallState(paths.installState);return{adapter,change:adapter.config.install({launcher:paths.launcher,events,timeoutSec})}}catch(error){return{adapter,error:error.message}}}function syncHosts(paths){let registry=compileRegistry(paths);try{saveRegistry(paths,registry)}catch{}let events=neededEvents(registry);return{events,results:wiredAdapters(paths).map(a=>installHub(a,paths,events))}}function printHostResults(results){let ok=!0;for(let{adapter,change,error}of results){if(error||!change){ok=!1,say("fail",`${adapter.name}: ${error??"no change reported"}`,"fix the file, then run: hookmux sync");continue}let parts=[change.added.length>0?`added ${change.added.join(", ")}`:"",change.removed.length>0?`removed ${change.removed.join(", ")}`:""].filter(Boolean),summary=parts.length>0?parts.join("; "):change.changed?"updated":"up to date";say("ok",`${adapter.name}: ${summary} (${change.file})`);for(let note of change.notes)detail(`! ${note}`)}return ok}async function approveHubs(paths,results){let ok=!0;for(let{adapter,change}of results)if(!(!change||!adapter.config.approve))try{let r=await adapter.config.approve(paths.launcher);r.missing.length>0&&(ok=!1,say("warn",`${adapter.name} does not list the hub entries for ${r.missing.join(", ")}`,APPROVE_BY_HAND)),r.stillUntrusted.length>0?(ok=!1,say("warn",`${adapter.name}: ${r.stillUntrusted.length} hub entries still need approval`,APPROVE_BY_HAND)):r.approved.length>0&&say("ok",`${adapter.name}: approved ${r.approved.length} hub entries`)}catch(error){error instanceof CodexUnavailableError||(ok=!1),say("warn",`${adapter.name}: could not approve hub entries (${error.message})`,APPROVE_BY_HAND)}return ok}var APPROVE_BY_HAND="open Codex, run /hooks and approve the hookmux entries";async function syncAfterChange(paths){let{results}=syncHosts(paths);if(results.length===0)return say("info","no host has hub entries yet","hookmux init"),!0;let printed=printHostResults(results);return await approveHubs(paths,results)&&printed}export{allAdapters,neededEvents,wiredAdapters,installHub,syncHosts,printHostResults,approveHubs,syncAfterChange};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var SAFE_FILE=/^[\w./-]{1,80}$/,SAFE_NAME=/^[\w.-]{1,40}$/,SAFE_ENV=/^[A-Za-z_][A-Za-z0-9_]{0,63}$/,RISKS={high:0,medium:1,low:2},SEPARATOR=" \xB7 ",ESCAPES=/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|[@-Z\\-_])/g,CONTROLS=new RegExp("[\\u0000-\\u001f\\u007f-\\u009f\\u061c\\u180e\\u200b-\\u200f\\u202a-\\u202e\\u2060-\\u2069\\ufe00-\\ufe0f\\ufeff\\u{e0000}-\\u{e007f}\\u{e0100}-\\u{e01ef}]","gu");function safeText(text,max=200){let flat=String(text??"").replace(ESCAPES,"").replace(CONTROLS," ").replace(/\s+/g," ").trim(),chars=[...flat];return chars.length>max?`${chars.slice(0,max-1).join("")}\u2026`:flat}var hasTool=events=>events.includes("tool.before")||events.includes("tool.after"),joinNames=(names,fallback)=>names.length>0?names.join(", "):fallback;function shownFile(name){return SAFE_FILE.test(name)?name:null}function scriptLine(facts){let files=facts.scripts.map(shownFile);return{risk:"high",text:`Runs ${files.length>0&&files.every(f=>f!==null)?joinNames(files,"its script"):"its scripts"} as your user, not sandboxed`}}function modelLine(facts){let names=facts.modelProviders.filter(n=>SAFE_NAME.test(n)),provider=names.length>0?` (${names.join(", ")})`:"",sent=[...facts.events.includes("prompt.submit")?["your prompt text"]:[],...hasTool(facts.events)?["tool-call details"]:[]];return{risk:"medium",text:`Sends ${sent.length>0?sent.join(" and "):"event details"} to your configured model provider${provider}`}}function capabilityLine(capability,facts){let[code="",arg=""]=splitOnce(capability);if(code==="event")return[];switch(code){case"script":return[scriptLine(facts)];case"block":{let lines=[];return hasTool(facts.events)&&lines.push({risk:"high",text:"Can stop the agent's tool calls"}),facts.events.includes("prompt.submit")&&lines.push({risk:"high",text:"Can discard your prompt before the agent sees it"}),lines}case"model":return[modelLine(facts)];case"env":{let name=SAFE_ENV.test(arg)?`$${arg}`:"an environment variable with an unusual name";return[{risk:"medium",text:`Passes ${name} from your environment to its script`,short:`Passes ${name} to its script`}]}case"inject":return[{risk:"medium",text:"Adds text the agent reads and may follow"}];case"evidence_chars":return[{risk:"medium",text:`Can quote up to ${/^\d{1,7}$/.test(arg)?arg:"an unusual number of"} characters of script output to the agent`}];case"notify":return[{risk:"low",text:"Shows you messages the agent does not see"}];default:return[{risk:"high",text:`Uses ${safeText(capability,40)} (hookmux has no description for it)`}]}}function splitOnce(capability){let i=capability.indexOf(":");return i<0?[capability,""]:[capability.slice(0,i),capability.slice(i+1)]}var CODE_ORDER=["script","block","model","env","inject","evidence_chars","notify"];function capabilityLines(capabilities,facts){let rank=c=>{let i=CODE_ORDER.indexOf(splitOnce(c)[0]);return i<0?CODE_ORDER.length:i};return[...capabilities].sort((a,b)=>rank(a)-rank(b)||a.localeCompare(b)).flatMap(c=>capabilityLine(c,facts)).map((line,i)=>({line,i})).sort((a,b)=>RISKS[a.line.risk]-RISKS[b.line.risk]||a.i-b.i).map(x=>x.line)}var FREQUENCY=[["session.start","At session start"],["prompt.submit","On every prompt"],["tool.before","Before every tool call"],["tool.after","After every tool call"]];function frequency(events){let parts=FREQUENCY.filter(([e])=>events.includes(e)).map(([,text])=>text);if(parts.length===0)return"On no event";let lowered=parts.map((p,i)=>i===0?p:p.charAt(0).toLowerCase()+p.slice(1));return lowered.length===1?lowered[0]:`${lowered.slice(0,-1).join(", ")} and ${lowered[lowered.length-1]}`}var TIER_TEXT={0:"in-process checks only",1:"runs a script",2:"calls your model provider"};function costLine(facts,deadlineMs){let parts=[frequency(facts.events),TIER_TEXT[facts.tier]];return facts.tier>0&&parts.push(`can add up to ${Math.round(deadlineMs/100)/10} s`),parts.join(SEPARATOR)}function sourceName(source){return source.replace(/^[a-z+]+:\/\//i,"").replace(/^[\w.-]+@([\w.-]+):/,"$1/").replace(/\.git$/,"")}function fromLine(facts){let{source}=facts;if(source===null)return"unknown (the folder was placed by hand; hookmux has not reviewed it)";if(source==="bundled")return"bundled with hookmux";let at=facts.commit?` @ ${safeText(facts.commit.slice(0,7),7)}`:facts.ref?` @ ${safeText(facts.ref,40)}`:"";return`${safeText(sourceName(source),120)}${at} (hookmux has not reviewed it)`}function shortSource(facts){if(facts.source===null)return"an unknown source";if(facts.source==="bundled")return"hookmux";let name=sourceName(facts.source).replace(/^github\.com\//,""),shown=name.startsWith("/")?`\u2026/${name.split("/").slice(-2).join("/")}`:name;return safeText(shown,60)}function shortHash(hash){let[algo="",hex=""]=splitOnce(hash);return hex.length>9?`${algo}:${hex.slice(0,4)}\u2026${hex.slice(-4)}`:safeText(hash,20)}var RISK_WIDTH=8;function renderCard(facts,capabilities,opts){let lines=capabilityLines(capabilities,facts),out=[`hookmux plugin: ${facts.id} ${safeText(facts.version,40)}`,`From: ${fromLine(facts)}`,`Does: ${safeText(facts.description)||"no description given"}`,`Runs: ${costLine(facts,opts.deadlineMs)}`,"Can:",...lines.length>0?lines.map(l=>` ${l.risk.padEnd(RISK_WIDTH)}${l.text}`):[" none beyond reading the event"]];return capabilities.includes("model")&&out.push("A model alone never blocks anything."),out.push(`Content: ${shortHash(opts.hash)}, ${opts.approval}`),out.join(`
|
|
2
|
+
`)}function cardSummary(facts,capabilities,deadlineMs){let risky=capabilityLines(capabilities,facts).filter(l=>l.risk!=="low");return[`${facts.id} ${safeText(facts.version,40)} from ${shortSource(facts)}.`,`${costLine(facts,deadlineMs)}.`,...risky.map(l=>`${l.short??l.text}.`)].join(" ")}function renderCardShort(facts,capabilities,deadlineMs){return`hookmux: approve to turn on ${cardSummary(facts,capabilities,deadlineMs)}`}export{renderCard,cardSummary,renderCardShort};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{MANIFEST_FILE,ManifestError,compileManifest,parse,readManifestText}from"./chunk-K73ZPBFM.mjs";import{KNOWN_HOSTS,REGISTRY_FORMAT,stamp}from"./chunk-7Z3AMI24.mjs";import{DEFAULT_EVIDENCE_CHARS,PLUGIN_ID,declaredEnv,getCheck,scriptEvidenceLimit}from"./chunk-ZNEBE4WO.mjs";import{readJson,writeFileAtomic}from"./chunk-OYGOSD6V.mjs";import{VERSION}from"./chunk-AHPMRYYF.mjs";import{existsSync as existsSync2,readdirSync as readdirSync2}from"node:fs";import{join as join2}from"node:path";var BUNDLED_SOURCE="bundled",DEFAULT_TIMEOUT_SEC=10;function readSources(file){let raw=readJson(file,{});return raw!==null&&typeof raw=="object"&&!Array.isArray(raw)?raw:{}}function writeSources(file,store){writeFileAtomic(file,`${JSON.stringify(store,null,2)}
|
|
2
|
+
`)}function readInstallState(file){let raw=readJson(file,{});return{timeoutSec:typeof raw.timeoutSec=="number"&&raw.timeoutSec>0?raw.timeoutSec:DEFAULT_TIMEOUT_SEC}}function writeInstallState(file,state){writeFileAtomic(file,`${JSON.stringify(state,null,2)}
|
|
3
|
+
`)}function cardFactsOf({id,base,variants,source}){let specs=[base,...variants],events=new Set,scripts=new Set,providers=new Set,tier=0;for(let spec of specs){for(let e of spec.events)events.add(e);for(let check of Object.values(spec.checks)){let kind=getCheck(check.kind);kind?.modelBacked?tier=2:kind?.tier===1&&tier<1&&(tier=1),check.kind==="script"&&typeof check.command=="string"&&scripts.add(check.command),kind?.modelBacked&&typeof check.provider=="string"&&providers.add(check.provider)}}return{id,version:base.version,description:base.description,source:source?.source??null,ref:source?.ref??null,commit:source?.commit??null,events:[...events],scripts:[...scripts].sort(),modelProviders:[...providers].sort(),tier}}import{existsSync,readFileSync}from"node:fs";var DEFAULT_SETTINGS={deadlineMs:2e3,blockRequiresRule:!0,routeOrigins:["user"],contextBudget:9e3,autoTrustDeclarative:!1},DEADLINE_RANGE=[50,2e4];function readConfig(file){let config={settings:{...DEFAULT_SETTINGS},providers:{},overrides:{},problems:[]};if(!existsSync(file))return config;let raw;try{raw=parse(readFileSync(file,"utf8"))}catch(error){return config.problems.push(`config.toml is invalid TOML: ${error.message}`),config}let s=table(raw.settings),set=config.settings;typeof s.deadline_ms=="number"&&(set.deadlineMs=Math.min(DEADLINE_RANGE[1],Math.max(DEADLINE_RANGE[0],Math.round(s.deadline_ms)))),typeof s.block_requires_rule=="boolean"&&(set.blockRequiresRule=s.block_requires_rule),Array.isArray(s.route_origins)&&(set.routeOrigins=s.route_origins.filter(isOrigin)),typeof s.context_budget=="number"&&s.context_budget>0&&(set.contextBudget=Math.round(s.context_budget)),typeof s.auto_trust_declarative=="boolean"&&(set.autoTrustDeclarative=s.auto_trust_declarative);for(let[name,p]of Object.entries(table(raw.providers))){let t=table(p);if(typeof t.kind!="string"||typeof t.url!="string"){config.problems.push(`providers.${name} needs kind and url`);continue}config.providers[name]={kind:t.kind,url:t.url,...typeof t.model=="string"?{model:t.model}:{},...typeof t.timeout_ms=="number"?{timeoutMs:t.timeout_ms}:{},...typeof t.api_key_env=="string"?{apiKeyEnv:t.api_key_env}:{},...typeof t.allow_remote=="boolean"?{allowRemote:t.allow_remote}:{}}}for(let[id,o]of Object.entries(table(raw.override)))config.overrides[id]=table(o);return config}function table(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:{}}function isOrigin(value){return value==="user"||value==="system"||value==="unknown"}import{readFileSync as readFileSync2}from"node:fs";var FLAGS_PROBLEM="flags.json is unreadable; fix or delete it";function isStringList(value){return Array.isArray(value)&&value.every(v=>typeof v=="string")}function readFlags(file){let text;try{text=readFileSync2(file,"utf8")}catch(error){return error.code==="ENOENT"?{shadow:[],disabled:[]}:{shadow:[],disabled:[],problem:FLAGS_PROBLEM}}let raw;try{raw=JSON.parse(text)}catch{return{shadow:[],disabled:[],problem:FLAGS_PROBLEM}}if(raw===null||typeof raw!="object"||Array.isArray(raw))return{shadow:[],disabled:[],problem:FLAGS_PROBLEM};let{shadow=[],disabled=[]}=raw;return!isStringList(shadow)||!isStringList(disabled)?{shadow:[],disabled:[],problem:FLAGS_PROBLEM}:{shadow,disabled}}function readFlagsForUpdate(file){let flags=readFlags(file);if(flags.problem)throw new Error(`${file}: ${flags.problem}`);return{shadow:flags.shadow,disabled:flags.disabled}}function writeFlags(file,flags){let clean={shadow:[...new Set(flags.shadow)].sort(),disabled:[...new Set(flags.disabled)].sort()};writeFileAtomic(file,`${JSON.stringify(clean,null,2)}
|
|
4
|
+
`)}function applyFlags(spec,flags){let shadow=flags.shadow.includes(spec.id),disabled=flags.disabled.includes(spec.id);return!shadow&&!disabled?spec:{...spec,shadow:spec.shadow||shadow,enabled:spec.enabled&&!disabled}}import{createHash}from"node:crypto";import{lstatSync,readdirSync,readFileSync as readFileSync3}from"node:fs";import{join,relative}from"node:path";var MAX_PLUGIN_FILES=200,MAX_PLUGIN_BYTES=4*1024*1024;function readTrust(file){let store=readJson(file,{plugins:{}});if(!store||typeof store.plugins!="object"||store.plugins===null)return{plugins:{}};for(let entry of Object.values(store.plugins))entry&&!Array.isArray(entry.capabilities)&&(entry.capabilities=[]);return store}function writeTrust(file,store){writeFileAtomic(file,`${JSON.stringify(store,null,2)}
|
|
5
|
+
`)}function listPluginFiles(dir){let files=[],dirs=[dir],walk=current=>{for(let entry of readdirSync(current,{withFileTypes:!0})){if(entry.name===".git"||entry.name===".DS_Store")continue;let full=join(current,entry.name);if(entry.isSymbolicLink())throw new Error(`${relative(dir,full)} is a symlink; plugins may not contain links`);if(entry.isDirectory()?(dirs.push(full),walk(full)):entry.isFile()&&files.push(full),files.length>MAX_PLUGIN_FILES)throw new Error(`more than ${MAX_PLUGIN_FILES} files`)}};return walk(dir),files.sort(),{files,dirs}}function readPluginFiles(dir){let listing=listPluginFiles(dir),files=[],total=0;for(let file of listing.files){if(total+=lstatSync(file).size,total>MAX_PLUGIN_BYTES)throw new Error(`plugin folder is larger than ${MAX_PLUGIN_BYTES} bytes`);files.push({rel:relative(dir,file).replaceAll("\\","/"),bytes:readFileSync3(file)})}return{files,dirs:listing.dirs,paths:listing.files}}function hashFiles(files){let hash=createHash("sha256");for(let{rel,bytes}of files)hash.update(rel),hash.update("\0"),hash.update(String(bytes.length)),hash.update("\0"),hash.update(bytes);return`sha256:${hash.digest("hex")}`}function fileHashesOf(files){return Object.fromEntries(files.map(f=>[f.rel,createHash("sha256").update(f.bytes).digest("hex")]))}function hashPlugin(dir){return hashFiles(readPluginFiles(dir).files)}function capabilitiesOf(spec,variants=[]){let caps=new Set;for(let s of[spec,...variants]){for(let e of s.events)caps.add(`event:${e}`);for(let e of s.effects)for(let kind of[e.effect,...e.fallback??[]])caps.add(kind);for(let c of Object.values(s.checks)){let kind=getCheck(c.kind);if(kind?.tier===1&&caps.add("script"),c.kind==="script"){for(let name of declaredEnv(c))caps.add(`env:${name}`);let evidenceLimit=scriptEvidenceLimit(c);evidenceLimit>DEFAULT_EVIDENCE_CHARS&&caps.add(`evidence_chars:${evidenceLimit}`)}kind?.modelBacked&&caps.add("model")}}return[...caps].sort()}var EVIDENCE_CAP=/^evidence_chars:(\d+)$/;function covers(approved,capability){if(approved.includes(capability))return!0;let wanted=EVIDENCE_CAP.exec(capability);return wanted?approved.some(a=>{let granted=EVIDENCE_CAP.exec(a);return granted!==null&&Number(granted[1])>=Number(wanted[1])}):!1}function uncoveredCapabilities(effective,approved){return effective.filter(c=>!covers(approved,c))}function isCapabilitySubset(effective,approved){return uncoveredCapabilities(effective,approved).length===0}function isDeclarativeOnly(capabilities){return!capabilities.some(c=>c==="block"||c==="script")}function compileRegistry(paths){let config=readConfig(paths.config),trust=readTrust(paths.trust),flags=readFlags(paths.flags),records=readSources(paths.sources),sources=[stamp(paths.config),stamp(paths.trust),stamp(paths.flags),stamp(paths.sources),stamp(paths.plugins)],plugins=[],ids=existsSync2(paths.plugins)?readdirSync2(paths.plugins,{withFileTypes:!0}).filter(d=>d.isDirectory()).map(d=>d.name).sort():[];for(let id of ids){let dir=join2(paths.plugins,id);plugins.push(compileOne({id,dir,config,flags,pinned:trust.plugins[id],record:records[id],sources}))}return{format:REGISTRY_FORMAT,engine:VERSION,builtAt:new Date().toISOString(),sources,settings:config.settings,providers:config.providers,plugins,problems:config.problems}}function compileOne({id,dir,config,flags,pinned,record,sources}){let entry={id,status:"invalid",warnings:[],capabilities:[]};try{let read=readPluginFiles(dir);for(let d of read.dirs)sources.push(stamp(d));for(let f of read.paths)sources.push(stamp(f));if(!PLUGIN_ID.test(id))throw new Error("folder name is not a valid plugin id");if(flags.problem)throw new Error(flags.problem);let manifest=read.files.find(f=>f.rel===MANIFEST_FILE);if(!manifest)throw new Error(`no ${MANIFEST_FILE}`);let raw=readManifestText(dir,manifest.bytes.toString("utf8"));if(raw.id!==id)throw new Error(`manifest id '${String(raw.id)}' does not match folder '${id}'`);let compiled=compileManifest(raw,dir,config.overrides[id],{routeOrigins:config.settings.routeOrigins,knownHosts:KNOWN_HOSTS});entry.warnings=compiled.warnings,entry.phase=guardOnAnyLayer(raw,compiled)?"guard":compiled.base.phase,entry.hash=hashFiles(read.files),entry.fileHashes=fileHashesOf(read.files);let flagged=spec=>applyFlags(spec,flags),base=flagged(compiled.base),variants=Object.fromEntries(Object.entries(compiled.variants).map(([host,spec])=>[host,flagged(spec)]));entry.capabilities=capabilitiesOf(base,Object.values(variants)),entry.card=cardFactsOf({id,base,variants:Object.values(variants),source:record});let decision=trustDecision({id,hash:entry.hash,capabilities:entry.capabilities,pinned,autoTrustDeclarative:config.settings.autoTrustDeclarative}),shadowPreview=!decision.trusted&&flags.shadow.includes(id)&&!entry.capabilities.includes("script");if(!decision.trusted&&!shadowPreview)return entry.status="untrusted",entry.problem=decision.problem,entry;entry.status="active",entry.trusted=decision.trusted,shadowPreview&&(entry.problem="not promoted yet; running in shadow only");let finish=spec=>shadowPreview?{...spec,shadow:!0}:spec;entry.base=finish(base),entry.variants=Object.fromEntries(Object.entries(variants).map(([host,spec])=>[host,finish(spec)]))}catch(error){entry.problem=error instanceof ManifestError?error.problems.join("; "):error.message,!flags.problem&&!existsSync2(join2(dir,MANIFEST_FILE))&&(entry.problem=`no ${MANIFEST_FILE}`)}return entry}function guardOnAnyLayer(raw,compiled){let rawHosts=raw.host!==null&&typeof raw.host=="object"?Object.values(raw.host):[];return[raw.phase,...rawHosts.map(h=>h!==null&&typeof h=="object"?h.phase:void 0),compiled.base.phase,...Object.values(compiled.variants).map(v=>v.phase)].includes("guard")}function trustDecision(input){let{id,hash,capabilities,pinned,autoTrustDeclarative}=input;if(autoTrustDeclarative&&isDeclarativeOnly(capabilities))return{trusted:!0};if(!pinned)return{trusted:!1,problem:"not promoted yet"};if(pinned.hash!==hash)return{trusted:!1,problem:"content changed since promote"};let added=uncoveredCapabilities(capabilities,pinned.capabilities);return added.length===0?{trusted:!0}:{trusted:!1,problem:`config override adds ${added.join(", ")}; run hookmux promote ${id}`}}export{BUNDLED_SOURCE,readSources,writeSources,readInstallState,writeInstallState,cardFactsOf,readConfig,readFlags,readFlagsForUpdate,writeFlags,applyFlags,readTrust,writeTrust,listPluginFiles,readPluginFiles,fileHashesOf,hashPlugin,capabilitiesOf,uncoveredCapabilities,isCapabilitySubset,compileRegistry};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import{CANONICAL_EVENTS,ExprError,PHASES,PLUGIN_ID,getCheck,parseExpr}from"./chunk-ZNEBE4WO.mjs";import{readFileSync,statSync}from"node:fs";import{join}from"node:path";function getLineColFromPtr(string,ptr){let lines=string.slice(0,ptr).split(/\r?\n/);return[lines.length,lines.pop().length+1]}function makeCodeBlock(string,line,column){let lines=string.split(/\r?\n/),codeblock="",numberLen=(Math.log10(line+1)|0)+1;for(let i=line-1;i<=line+1;i++){let l=lines[i-1];l&&(codeblock+=i.toString().padEnd(numberLen," "),codeblock+=": ",codeblock+=l,codeblock+=`
|
|
2
|
+
`,i===line&&(codeblock+=" ".repeat(numberLen+column+2),codeblock+=`^
|
|
3
|
+
`))}return codeblock}var TomlError=class _TomlError extends Error{line;column;codeblock;constructor(message,options){let[line,column]=getLineColFromPtr(options.toml,options.ptr),codeblock=makeCodeBlock(options.toml,line,column);super(`Invalid TOML document: ${message}
|
|
4
|
+
|
|
5
|
+
${codeblock}`,options),this.line=line,this.column=column,this.codeblock=codeblock}static x(message,ctx,ptr){throw new _TomlError(message,{toml:ctx.s,ptr:ptr??ctx.p})}};function parseString(ctx){let startPtr=ctx.p,c=ctx.s.charCodeAt(ctx.p++),first=c,isLiteral=c===39,isMultiline=c===ctx.s.charCodeAt(ctx.p)&&c===ctx.s.charCodeAt(ctx.p+1);isMultiline&&((c=ctx.s.charCodeAt(ctx.p+=2))===10?ctx.p++:c===13&&ctx.s.charCodeAt(ctx.p+1)===10&&(ctx.p+=2));let parsed="",sliceStart=ctx.p,state=0;for(;ctx.p<ctx.s.length;ctx.p++)if(c=ctx.s.charCodeAt(ctx.p),isMultiline&&(c===10||c===13&&ctx.s.charCodeAt(ctx.p+1)===10))state=state&&3;else if(c<32&&c!==9||c===127)TomlError.x("control characters are not allowed in strings",ctx);else if((!state||state===3)&&c===first&&(!isMultiline||ctx.s.charCodeAt(ctx.p+1)===first&&ctx.s.charCodeAt(ctx.p+2)===first)){if(isMultiline&&(ctx.s.charCodeAt(ctx.p+3)===first&&ctx.p++,ctx.s.charCodeAt(ctx.p+3)===first&&ctx.p++),!state){let s=ctx.s.slice(sliceStart,ctx.p);parsed=parsed?parsed+s:s}return ctx.p+=isMultiline?3:1,parsed}else if(!state)!isLiteral&&c===92&&(parsed+=ctx.s.slice(sliceStart,sliceStart=ctx.p),state=1);else if(state===1)if(c===120||c===117||c===85){let errPtr=ctx.p++-1,value=0,len=c===120?2:c===117?4:8;for(let j=0;j<len;j++,ctx.p++){let hex=ctx.s.charCodeAt(ctx.p),digit=hex>=48&&hex<=57?hex-48:hex>=65&&hex<=70?hex-65+10:hex>=97&&hex<=102?hex-97+10:-1;digit<0&&TomlError.x("invalid non-hex character in unicode escape",ctx),value=value<<4|digit}(value<0||value>1114111||value>=55296&&value<=57343)&&TomlError.x("invalid unicode escape",ctx,errPtr),parsed+=String.fromCodePoint(value),sliceStart=ctx.p--,state=0}else isMultiline&&(c===32||c===9)?state=2:(c===98?parsed+="\b":c===116?parsed+=" ":c===110?parsed+=`
|
|
6
|
+
`:c===102?parsed+="\f":c===114?parsed+="\r":c===101?parsed+="\x1B":c===34?parsed+='"':c===92?parsed+="\\":TomlError.x("unrecognised escape sequence",ctx),sliceStart=ctx.p+1,state=0);else c!==32&&c!==9&&(state===2&&TomlError.x("invalid escape: only line-ending whitespace may be escaped",ctx,sliceStart),state=!isLiteral&&c===92?1:0,sliceStart=ctx.p);TomlError.x("unfinished string",ctx,startPtr)}var DATE_TIME_RE=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i,TomlDate=class _TomlDate extends Date{#hasDate=!1;#hasTime=!1;#offset=null;constructor(date,fasttype,unsafeDelim){let hasDate=!0,hasTime=!0,offset="Z",c;if(typeof date=="string")if(fasttype)prep:{if(fasttype<3){if(+date.slice(11,13)>23){date="";break prep}fasttype===2?(offset=null,date+="Z"):(c=date.charCodeAt(date.length-1))!==90&&c!==122&&(offset=date.slice(date.length-6)),unsafeDelim&&(date=date.slice(0,10)+"T"+date.slice(11))}else fasttype===4&&(date=+date.slice(0,2)>23?"":`0000-01-01T${date}Z`);hasDate=fasttype!==4,hasTime=fasttype!==3}else{let match=date.match(DATE_TIME_RE);match?(match[1]||(hasDate=!1,date=`0000-01-01T${date}`),hasTime=!!match[2],hasTime&&date[10]===" "&&(date=date.replace(" ","T")),match[2]&&+match[2]>23?date="":(offset=match[3]||null,!offset&&hasTime&&(date+="Z"))):date=""}super(date),isNaN(this.getTime())||(this.#hasDate=hasDate,this.#hasTime=hasTime,this.#offset=offset)}isDateTime(){return this.#hasDate&&this.#hasTime}isLocal(){return!this.#hasDate||!this.#hasTime||!this.#offset}isDate(){return this.#hasDate&&!this.#hasTime}isTime(){return this.#hasTime&&!this.#hasDate}isValid(){return this.#hasDate||this.#hasTime}toISOString(){let iso=super.toISOString();if(this.isDate())return iso.slice(0,10);if(this.isTime())return iso.slice(11,23);if(this.#offset===null)return iso.slice(0,-1);if(this.#offset==="Z"||this.#offset==="z")return iso;let offset=+this.#offset.slice(1,3)*60+ +this.#offset.slice(4,6);return offset=this.#offset[0]==="-"?offset:-offset,new Date(this.getTime()-offset*6e4).toISOString().slice(0,-1)+this.#offset}static wrapAsOffsetDateTime(jsDate,offset="Z"){let date=new _TomlDate(jsDate);return date.#offset=offset,date}static wrapAsLocalDateTime(jsDate){let date=new _TomlDate(jsDate);return date.#offset=null,date}static wrapAsLocalDate(jsDate){let date=new _TomlDate(jsDate);return date.#hasTime=!1,date.#offset=null,date}static wrapAsLocalTime(jsDate){let date=new _TomlDate(jsDate);return date.#hasDate=!1,date.#offset=null,date}};function isDigit(char,base=10){return base===16?char>47&&char<58||char>64&&char<71||char>96&&char<103:char>47&&char<48+base}function isEndOfValue(char,delim){return char===32||char===9||char===10||char===13||delim&&(char===delim||char===44)||char===35}function extractValue(ctx,end){let errPtr=ctx.p,c=ctx.s.charCodeAt(ctx.p);if(c===91||c===123){ctx.d--||TomlError.x("document contains excessively nested structures. aborting.",ctx);let value=c===91?parseArray(ctx):parseInlineTable(ctx);return ctx.d++,value}return c===34||c===39?parseString(ctx):c===116?((ctx.s.charCodeAt(++ctx.p)!==114||ctx.s.charCodeAt(++ctx.p)!==117||ctx.s.charCodeAt(++ctx.p)!==101)&&TomlError.x("invalid value",ctx,errPtr),ctx.p++,!0):c===102?((ctx.s.charCodeAt(++ctx.p)!==97||ctx.s.charCodeAt(++ctx.p)!==108||ctx.s.charCodeAt(++ctx.p)!==115||ctx.s.charCodeAt(++ctx.p)!==101)&&TomlError.x("invalid value",ctx,errPtr),ctx.p++,!1):c===43||c===45?parseNumber(ctx,ctx.p,ctx.s.charCodeAt(++ctx.p),44-c,end):ctx.s.charCodeAt(ctx.p+4)===45&&ctx.s.charCodeAt(ctx.p+7)===45?parseDate(ctx,c,end):ctx.s.charCodeAt(ctx.p+2)===58?parseTime(ctx,c,end):parseNumber(ctx,ctx.p,c,0,end)}function parseNumber(ctx,startPtr,startChr,sign,endChr){let c=startChr,state=0,hasUnderscores=!1;if(c===105)return(ctx.s.charCodeAt(++ctx.p)!==110||ctx.s.charCodeAt(++ctx.p)!==102)&&TomlError.x("invalid value",ctx,startPtr),ctx.p++,(sign||1)/0;if(c===110)return(ctx.s.charCodeAt(++ctx.p)!==97||ctx.s.charCodeAt(++ctx.p)!==110)&&TomlError.x("invalid value",ctx,startPtr),ctx.p++,NaN;if(c===48){if(++ctx.p>=ctx.s.length||isEndOfValue(c=ctx.s.charCodeAt(ctx.p),endChr))return ctx.bi===!0?0n:0;if(!sign){if(c===120)return parseIntegerBaseN(ctx,startPtr,16,endChr);if(c===98)return parseIntegerBaseN(ctx,startPtr,2,endChr);if(c===111)return parseIntegerBaseN(ctx,startPtr,8,endChr)}c===46?state=2:c===101||c===69?state=4:TomlError.x("illegal leading zero",ctx,startPtr)}else isDigit(c)||TomlError.x("invalid value",ctx,startPtr);for(;++ctx.p<ctx.s.length&&(c=ctx.s.charCodeAt(ctx.p),!isEndOfValue(c,endChr));)state||(state=1),c===95?(state&1||TomlError.x("illegal underscore",ctx),state+=11,hasUnderscores=!0):state===1&&c===46?state=2:(state===1||state===3)&&(c===101||c===69)?state=4:state===4&&(c===43||c===45)?state=6:isDigit(c)?state>9?state-=11:state&1||state++:TomlError.x("illegal character in numeric literal",ctx);if(!state){let val=(startChr-48)*(sign||1);return ctx.bi===!0?BigInt(val):val}state&1||TomlError.x("unfinished numeric value",ctx,startPtr);let str=ctx.s.slice(startPtr,ctx.p);return hasUnderscores&&(str=str.replaceAll("_","")),state>1?parseFloat(str):parseInteger(ctx,str,10,startPtr)}function parseIntegerBaseN(ctx,startPtr,base,endChr){let c,underscore=1;for(;++ctx.p<ctx.s.length&&(c=ctx.s.charCodeAt(ctx.p),!isEndOfValue(c,endChr));)c===95?(underscore&1&&TomlError.x("illegal underscore",ctx),underscore=3):isDigit(c,base)?underscore&1&&underscore--:TomlError.x("illegal character in numeric literal",ctx);underscore&1&&TomlError.x("unfinished numeric value",ctx);let str=ctx.s.slice(startPtr+2,ctx.p);return underscore&&(str=str.replaceAll("_","")),parseInteger(ctx,str,base,startPtr)}function parseInteger(ctx,str,base,startPtr){if(ctx.bi!==!0)int:{let val=parseInt(str,base);if(!Number.isSafeInteger(val)){if(ctx.bi)break int;TomlError.x("integer value cannot be represented losslessly",ctx,startPtr)}return val}return BigInt(base===10?str:(base===2?"0b":base===8?"0o":"0x")+str)}function parseDate(ctx,c,endChr){let startPtr=ctx.p++,unsafeSeparator;if(!isDigit(c)||!isDigit(ctx.s.charCodeAt(ctx.p++))||!isDigit(ctx.s.charCodeAt(ctx.p++))||!isDigit(ctx.s.charCodeAt(ctx.p++)))return parseNumber(ctx,ctx.p=startPtr,c,0,endChr);if(ctx.p+=5,isDigit(ctx.s.charCodeAt(ctx.p++))||TomlError.x("invalid date-time: date part is malformed",ctx,startPtr),ctx.p>=ctx.s.length||((c=ctx.s.charCodeAt(ctx.p))!==32||(unsafeSeparator=!0,!isDigit(ctx.s.charCodeAt(ctx.p+1))))&&c!==84&&c!==116){let t2=ctx.s.slice(startPtr,ctx.p);return readDate(ctx,t2,3,!1,startPtr)}if(ctx.s.charCodeAt(ctx.p+=3)!==58&&TomlError.x("invalid date-time: time part is malformed",ctx,startPtr),ctx.s.charCodeAt(ctx.p+=3)===58&&(ctx.p+=3),ctx.s.charCodeAt(ctx.p)===46)for(;isDigit(ctx.s.charCodeAt(++ctx.p)););if(c=ctx.s.charCodeAt(ctx.p)){if(c===90||c===122){let t2=ctx.s.slice(startPtr,++ctx.p);return readDate(ctx,t2,1,unsafeSeparator,startPtr,"[+00:00]")}if(c===43||c===45){let t2=ctx.s.slice(startPtr,ctx.p+=6);return readDate(ctx,t2,1,unsafeSeparator,startPtr,!ctx.ld&&"["+ctx.s.slice(ctx.p-6,ctx.p)+"]")}}let t=ctx.s.slice(startPtr,ctx.p);return readDate(ctx,t,2,unsafeSeparator,startPtr)}function parseTime(ctx,c,endChr){let start=ctx.p;if(!isDigit(c)||!isDigit(ctx.s.charCodeAt(++ctx.p)))return parseNumber(ctx,--ctx.p,c,0,endChr);if(ctx.s.charCodeAt(ctx.p+=4)===58&&(ctx.p+=3),ctx.s.charCodeAt(ctx.p)===46)for(;isDigit(ctx.s.charCodeAt(++ctx.p)););let t=ctx.s.slice(start,ctx.p);return readDate(ctx,t,4,!1,start)}function readDate(ctx,str,type,unsafeDelim,errPtr,temporalSuffix){if(ctx.ld){let date=new TomlDate(str,type,unsafeDelim);return date.isValid()||TomlError.x("invalid date",ctx,errPtr),date}try{switch(temporalSuffix&&(str+=temporalSuffix),type){case 1:return Temporal.ZonedDateTime.from(str);case 2:return Temporal.PlainDateTime.from(str);case 3:return Temporal.PlainDate.from(str);case 4:return Temporal.PlainTime.from(str)}}catch(e){TomlError.x(e instanceof Error?e.message:""+e,ctx,errPtr)}}function skipComment(ctx){for(;ctx.p<ctx.s.length;ctx.p++){let c=ctx.s.charCodeAt(ctx.p);if(c===10)break;if(c===13&&ctx.s.charCodeAt(ctx.p+1)===10){ctx.p++;break}(c<32&&c!==9||c===127)&&TomlError.x("control characters are not allowed in comments",ctx)}}function skipVoid(ctx,banNewLines,banComments){let c;for(;ctx.p<ctx.s.length;){for(;ctx.p<ctx.s.length&&((c=ctx.s.charCodeAt(ctx.p))===32||c===9||!banNewLines&&(c===10||c===13&&ctx.s.charCodeAt(ctx.p+1)===10));)ctx.p++;if(banComments||c!==35)break;skipComment(ctx)}}function parseKey(ctx,end=61){let startPtr,state=0,parsed=[],sliceStart,c=ctx.s.charCodeAt(startPtr=ctx.p);do{if(c===end)return state||TomlError.x("unexpected end of key",ctx),state===1&&parsed.push(ctx.s.slice(sliceStart,ctx.p)),ctx.p++,parsed;c===46?(state||TomlError.x("illegal empty bare key",ctx),state===1&&parsed.push(ctx.s.slice(sliceStart,ctx.p)),state=0):!state&&(c===34||c===39)?(c===ctx.s.charCodeAt(ctx.p+1)&&c===ctx.s.charCodeAt(ctx.p+2)&&TomlError.x("illegal quoted key: multiline strings are not allowed",ctx),parsed.push(parseString(ctx)),state=2,ctx.p--):c===32||c===9?state===1&&(parsed.push(ctx.s.slice(sliceStart,ctx.p)),state=2):state===2||c<48&&c!==45||c>57&&c<65||c>90&&c<97&&c!==95||c>122?TomlError.x("illegal character in key",ctx):state||(state=1,sliceStart=ctx.p)}while(c=ctx.s.charCodeAt(++ctx.p));TomlError.x("incomplete key-value: cannot find end of key",ctx,startPtr)}function parseInlineTable(ctx){let startPtr=ctx.p++,res=Object.create(null),seen=new Set,c;for(;ctx.p<ctx.s.length;){if(skipVoid(ctx),(c=ctx.s.charCodeAt(ctx.p))===125)return ctx.p++,res;let k,t=res,hasOwn=!1,errPtr=ctx.p,key=parseKey(ctx);for(let i=0;i<key.length;i++){i&&(t=hasOwn?t[k]:t[k]=Object.create(null)),k=key[i],(hasOwn=Object.hasOwn(t,k))&&(typeof t[k]!="object"||seen.has(t[k]))&&TomlError.x("trying to redefine an already defined value",ctx,errPtr);let unsafe=k==="__proto__";if(ctx.uk&&(unsafe||k==="constructor")){t=ctx.uk!==1&&TomlError.x("document contains an unsafe property",ctx,errPtr);break}!hasOwn&&unsafe&&Object.defineProperty(t,k,{enumerable:!0,configurable:!0,writable:!0})}hasOwn&&TomlError.x("trying to redefine an already defined value",ctx,errPtr),skipVoid(ctx,!0,!0);let value=extractValue(ctx,125);if(t&&typeof(t[k]=value)=="object"&&seen.add(value),skipVoid(ctx),(c=ctx.s.charCodeAt(ctx.p++))===125)return res;c!==44&&TomlError.x("expected comma or end of structure",ctx,ctx.p-1)}TomlError.x("unfinished table",ctx,startPtr)}function parseArray(ctx){let startPtr=ctx.p++,res=[],c;for(;ctx.p<ctx.s.length;){if(skipVoid(ctx),(c=ctx.s.charCodeAt(ctx.p))===93)return ctx.p++,res;if(res.push(extractValue(ctx,93)),skipVoid(ctx),(c=ctx.s.charCodeAt(ctx.p++))===93)return res;c!==44&&TomlError.x("expected comma or end of structure",ctx,ctx.p-1)}TomlError.x("unfinished array",ctx,startPtr)}function peekTable(ctx,key,table,meta,type){let t=table,m=meta,k,hasOwn=!1,state;for(let i=0;i<key.length;i++){if(i){if(t=hasOwn?t[k]:t[k]=Object.create(null),m=(state=m[k]).c,type===0&&(state.t===1||state.t===2))return null;if(state.t===2){let l=t.length-1;t=t[l],m=m[l].c}}if(k=key[i],(hasOwn=Object.hasOwn(t,k))&&m[k]?.t===0&&m[k]?.d)return null;if(!hasOwn){let unsafe=k==="__proto__";if(ctx.uk&&(unsafe||k==="constructor"))return!1;unsafe&&(Object.defineProperty(t,k,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(m,k,{enumerable:!0,configurable:!0,writable:!0})),m[k]={t:i<key.length-1&&type===2?3:type,d:!1,i:0,c:Object.create(null)}}}if(state=m[k],state.t!==type&&!(type===1&&state.t===3)||(type===2&&(state.d||(state.d=!0,t[k]=[]),t[k].push(t=Object.create(null)),state.c[state.i++]=state={t:1,d:!1,i:0,c:Object.create(null)}),state.d))return null;if(state.d=!0,type===1)t=hasOwn?t[k]:t[k]=Object.create(null);else if(type===0&&hasOwn)return null;return[k,t,state.c]}function validateTablePeek(ctx,peek,ptr){(peek===null||ctx.uk===2)&&TomlError.x(peek===null?"trying to redefine an already defined table or value":"document contains an unsafe property",ctx,ptr)}function parse(toml,options={}){let ctx={s:toml,p:0,d:options.maxDepth??1e3,bi:options.integersAsBigInt??!1,ld:options.useLegacyDate??!0,uk:options.unsafeKeyBehaviour==="throw"?2:options.unsafeKeyBehaviour==="drop"?1:0},res=Object.create(null),meta=Object.create(null),tmp,skipping=!1,tbl=res,m=meta;for(toml.charCodeAt(0)===65279&&ctx.p++,skipVoid(ctx);ctx.p<toml.length;){if(toml.charCodeAt(ctx.p)===91){let isTableArray=toml.charCodeAt(++ctx.p)===91;tmp=ctx.p+=+isTableArray,skipping=!1;let k=parseKey(ctx,93);isTableArray&&(toml.charCodeAt(ctx.p)!==93&&TomlError.x("expected end of table array declaration",ctx),ctx.p++);let p=peekTable(ctx,k,res,meta,isTableArray?2:1);p?(m=p[2],tbl=p[1]):(validateTablePeek(ctx,p,tmp),skipping=!0)}else{tmp=ctx.p;let k=parseKey(ctx),p=peekTable(ctx,k,tbl,m,0);!p&&!skipping&&validateTablePeek(ctx,p,tmp),skipVoid(ctx,!0,!0);let v=extractValue(ctx,void 0);p&&!skipping&&(p[1][p[0]]=v)}skipVoid(ctx,!0),ctx.p<toml.length&&(tmp=toml.charCodeAt(ctx.p))!==10&&(tmp!==13||toml.charCodeAt(ctx.p+1)!==10)&&TomlError.x("each key-value declaration must be followed by an end-of-line",ctx),skipVoid(ctx)}return res}var HAS_WELLFORMED=!!"".isWellFormed;function evalExprShape(label,source,checks){let expr;try{expr=parseExpr(source)}catch(error){return[`${label}: ${error instanceof ExprError?error.message:String(error)}`]}let problems=[],visit=e=>{if(e.t==="ref"||e.t==="cmp"){let spec=checks[e.name];if(!spec){problems.push(`${label}: '${e.name}' is not a declared check`);return}let kind=getCheck(spec.kind),output=kind?.outputOf?.(spec)??kind?.output;e.t==="ref"&&output==="score"&&problems.push(`${label}: '${e.name}' is a score; compare it, e.g. ${e.name} >= 0.7`),e.t==="cmp"&&output==="bool"&&problems.push(`${label}: '${e.name}' is true/false; use it without a comparison`)}else e.t==="not"?visit(e.e):(e.t==="and"||e.t==="or")&&(visit(e.l),visit(e.r))};return visit(expr),problems}var MANIFEST_FILE="plugin.toml",MANIFEST_SCHEMA=1,MAX_MANIFEST_BYTES=256*1024,MAX_TEXT_CHARS=4e3;var ORIGINS=["user","system","unknown"],ON_ERROR_PROBLEM="hookmux always fails open; remove on_error",KNOWN_KEYS=new Set(["schema","id","version","description","events","hosts","phase","priority","enabled","shadow","origins","dedupe","exclusive","on_error","when","when_degraded","params","checks","then","host","requires_hookmux"]),ManifestError=class extends Error{file;problems;constructor(file,problems){super(`${file}: ${problems.join("; ")}`),this.file=file,this.problems=problems}};function readManifest(dir){return readManifestText(dir,()=>readFileSync(join(dir,MANIFEST_FILE),"utf8"))}function readManifestText(dir,text){let file=join(dir,MANIFEST_FILE),stat=statSync(file);if(stat.size>MAX_MANIFEST_BYTES)throw new ManifestError(file,[`larger than ${MAX_MANIFEST_BYTES} bytes`]);if(process.platform!=="win32"){if((stat.mode&18)!==0)throw new ManifestError(file,["writable by group or others; run chmod go-w"]);if(typeof process.getuid=="function"&&stat.uid!==process.getuid())throw new ManifestError(file,["not owned by the current user"])}let source=typeof text=="string"?text:text();if(Buffer.byteLength(source)>MAX_MANIFEST_BYTES)throw new ManifestError(file,[`larger than ${MAX_MANIFEST_BYTES} bytes`]);try{return parse(source)}catch(error){throw new ManifestError(file,[`invalid TOML: ${error.message}`])}}function mergeTables(base,top){if(!top)return base;let out={...base};for(let[key,value]of Object.entries(top)){let current=out[key];out[key]=isTable(current)&&isTable(value)?mergeTables(current,value):value}return out}function isTable(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)&&!(value instanceof Date)}function compileManifest(raw,dir,override,defaults){let file=join(dir,MANIFEST_FILE),warnings=[];for(let key of Object.keys(raw))KNOWN_KEYS.has(key)||warnings.push(`unknown key '${key}' ignored`);if(raw.schema!==MANIFEST_SCHEMA)throw new ManifestError(file,[`schema must be ${MANIFEST_SCHEMA}`]);let pluginHosts=isTable(raw.host)?raw.host:{},overrideHosts=isTable(override?.host)?override.host:{},strip=m=>{if(!m)return;let{host:_host,...rest}=m;return rest},baseRaw=mergeTables(strip(raw),strip(override)),base=toSpec(baseRaw,dir,defaults,file),variants={};for(let hostId of new Set([...Object.keys(pluginHosts),...Object.keys(overrideHosts)])){if(!defaults.knownHosts.includes(hostId)){warnings.push(`[host.${hostId}] ignored: no adapter for '${hostId}' in this version`);continue}let layered=mergeTables(mergeTables(mergeTables(strip(raw),asTable(pluginHosts[hostId])),strip(override)),asTable(overrideHosts[hostId]));variants[hostId]=toSpec(layered,dir,defaults,`${file} [host.${hostId}]`)}return{base,variants,warnings}}function asTable(value){return isTable(value)?value:void 0}function toSpec(m,dir,defaults,where){let problems=[],str=(key,fallback)=>{let v=m[key]??fallback;return typeof v!="string"?(problems.push(`${key} must be a string`),""):v},bool=(key,fallback)=>{let v=m[key]??fallback;return typeof v!="boolean"&&problems.push(`${key} must be true or false`),v===!0},id=str("id");id&&!PLUGIN_ID.test(id)&&problems.push("id must be lowercase letters, digits and dashes (max 64)");let phase=str("phase","route");PHASES.includes(phase)||problems.push(`phase must be one of ${PHASES.join(", ")}`);let events=stringArray(m.events,"events",problems);for(let e of events)CANONICAL_EVENTS.includes(e)||problems.push(`unknown event '${e}'`);events.length===0&&problems.push("events must list at least one event");let priority=m.priority??100;(typeof priority!="number"||!Number.isInteger(priority))&&problems.push("priority must be an integer");let origins=m.origins===void 0?phase==="guard"?[...ORIGINS]:defaults.routeOrigins:stringArray(m.origins,"origins",problems);for(let o of origins)ORIGINS.includes(o)||problems.push(`unknown origin '${o}'`);let dedupe=str("dedupe","none");dedupe!=="none"&&dedupe!=="session"&&problems.push("dedupe must be 'none' or 'session'"),m.on_error!==void 0&&m.on_error!=="open"&&problems.push(ON_ERROR_PROBLEM);let checks=readChecks(m.checks,problems),when=str("when"),whenDegraded=m.when_degraded===void 0?void 0:str("when_degraded");for(let[label,source]of[["when",when],["when_degraded",whenDegraded]])source!==void 0&&source!==""&&problems.push(...evalExprShape(label,source,checks));let effects=readEffects(m.then,problems),params=readParams(m.params,problems);if(problems.length>0)throw new ManifestError(where,problems);return{id,version:typeof m.version=="string"?m.version:"0.0.0",description:typeof m.description=="string"?m.description:"",dir,events,hosts:m.hosts===void 0?[]:stringArray(m.hosts,"hosts",[]),phase,priority,enabled:bool("enabled",!0),shadow:bool("shadow",!1),origins,checks,when,...whenDegraded?{whenDegraded}:{},effects,dedupe,...typeof m.exclusive=="string"?{exclusive:m.exclusive}:{},params}}function stringArray(value,label,problems){return!Array.isArray(value)||value.some(v=>typeof v!="string")?(problems.push(`${label} must be a list of strings`),[]):value}function readChecks(value,problems){if(value===void 0)return{};if(!isTable(value))return problems.push("checks must be a table"),{};let out={};for(let[name,spec]of Object.entries(value)){if(/^[a-z_][a-z0-9_]*$/.test(name)||problems.push(`check name '${name}' must be lowercase snake_case`),!isTable(spec)||typeof spec.kind!="string"){problems.push(`checks.${name} needs a kind`);continue}let kind=getCheck(spec.kind);if(!kind){problems.push(`checks.${name}: unknown kind '${spec.kind}'`);continue}for(let p of kind.validate(spec))problems.push(`checks.${name}: ${p}`);out[name]=spec}return out}function readEffects(value,problems){if(!Array.isArray(value)||value.length===0)return problems.push("needs at least one [[then]] effect"),[];let out=[];for(let[i,e]of value.entries()){let at=`then[${i}]`;if(!isTable(e)){problems.push(`${at} must be a table`);continue}let text=e.effect==="block"?e.reason:e.text;if(typeof text!="string"||text.trim()===""){problems.push(`${at} needs ${e.effect==="block"?"reason":"text"}`);continue}text.length>MAX_TEXT_CHARS&&problems.push(`${at} text longer than ${MAX_TEXT_CHARS} chars`);let fallback=e.fallback===void 0?{}:{fallback:readFallback(e.fallback,e.effect,at,problems)};e.effect==="inject"||e.effect==="notify"?out.push({effect:e.effect,text,...fallback}):e.effect==="block"?out.push({effect:"block",reason:text,suppressOriginalPrompt:e.suppress_original_prompt===!0,...fallback}):problems.push(`${at}: unknown effect '${String(e.effect)}'`)}return out}var FALLBACK_KINDS=["inject","notify"];function readFallback(value,own,at,problems){if(!Array.isArray(value))return problems.push(`${at}.fallback must be a list such as ["inject", "notify"]`),[];let out=[];for(let item of value)item==="block"?problems.push(`${at}.fallback cannot contain 'block': a fallback never adds a block`):typeof item!="string"||!FALLBACK_KINDS.includes(item)?problems.push(`${at}.fallback: unknown effect '${String(item)}' (use inject or notify)`):item===own?problems.push(`${at}.fallback lists the effect's own kind '${item}'`):out.includes(item)?problems.push(`${at}.fallback lists '${item}' twice`):out.push(item);return out}function readParams(value,problems){if(value===void 0)return{};if(!isTable(value))return problems.push("params must be a table"),{};let out={};for(let[k,v]of Object.entries(value))typeof v=="string"||typeof v=="number"||typeof v=="boolean"?out[k]=String(v):problems.push(`params.${k} must be a string, number or boolean`);return out}export{parse,MANIFEST_FILE,MANIFEST_SCHEMA,KNOWN_KEYS,ManifestError,readManifest,readManifestText,compileManifest};
|
|
7
|
+
/*! Bundled license information:
|
|
8
|
+
|
|
9
|
+
smol-toml/dist/error.js:
|
|
10
|
+
smol-toml/dist/primitive.js:
|
|
11
|
+
smol-toml/dist/date.js:
|
|
12
|
+
smol-toml/dist/extract.js:
|
|
13
|
+
smol-toml/dist/util.js:
|
|
14
|
+
smol-toml/dist/struct.js:
|
|
15
|
+
smol-toml/dist/parse.js:
|
|
16
|
+
smol-toml/dist/stringify.js:
|
|
17
|
+
smol-toml/dist/index.js:
|
|
18
|
+
(*!
|
|
19
|
+
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
20
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
21
|
+
*
|
|
22
|
+
* Redistribution and use in source and binary forms, with or without
|
|
23
|
+
* modification, are permitted provided that the following conditions are met:
|
|
24
|
+
*
|
|
25
|
+
* 1. Redistributions of source code must retain the above copyright notice, this
|
|
26
|
+
* list of conditions and the following disclaimer.
|
|
27
|
+
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
28
|
+
* this list of conditions and the following disclaimer in the
|
|
29
|
+
* documentation and/or other materials provided with the distribution.
|
|
30
|
+
* 3. Neither the name of the copyright holder nor the names of its contributors
|
|
31
|
+
* may be used to endorse or promote products derived from this software without
|
|
32
|
+
* specific prior written permission.
|
|
33
|
+
*
|
|
34
|
+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
35
|
+
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
36
|
+
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
37
|
+
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
38
|
+
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
39
|
+
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
40
|
+
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
41
|
+
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
42
|
+
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
43
|
+
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
44
|
+
*)
|
|
45
|
+
*/
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{writeFileAtomic}from"./chunk-OYGOSD6V.mjs";import{createHash}from"node:crypto";import{cpSync,existsSync,lstatSync,mkdirSync,readdirSync,readFileSync,readlinkSync,realpathSync,renameSync,rmSync,statSync,symlinkSync}from"node:fs";import{basename,join,relative}from"node:path";var ENGINE_ENTRY="hook.mjs",KEEP_PREVIOUS=2,CURRENT="current";function installEngine(paths,distDir,version){if(!existsSync(join(distDir,ENGINE_ENTRY)))throw new Error(`no engine build at ${distDir}; run 'pnpm build' in the hookmux package`);mkdirSync(paths.engineRoot,{recursive:!0,mode:448});let target=join(paths.engineRoot,version),copied=treeDigest(distDir)!==treeDigest(target);return copied&&replaceFolder(distDir,target),pointCurrent(paths,version),{version,dir:target,copied,pruned:pruneEngines(paths,version)}}function engineStatus(paths){let link;try{link=readlinkSync(paths.engineCurrent)}catch{return{ok:!1,version:null,problem:existsSync(paths.engineCurrent)?"engine/current is not a symlink":"engine/current is missing"}}try{let version=basename(realpathSync(paths.engineCurrent));return existsSync(join(paths.engineCurrent,ENGINE_ENTRY))?{ok:!0,version}:{ok:!1,version,problem:`engine ${version} has no ${ENGINE_ENTRY}`}}catch{return{ok:!1,version:null,problem:`engine/current points at missing '${link}'`}}}function replaceFolder(source,target){let temp=`${target}.tmp-${process.pid}`,old=`${target}.old-${process.pid}`;rmSync(temp,{recursive:!0,force:!0}),cpSync(source,temp,{recursive:!0}),existsSync(target)&&renameSync(target,old),renameSync(temp,target),rmSync(old,{recursive:!0,force:!0})}function pointCurrent(paths,version){let temp=`${paths.engineCurrent}.tmp-${process.pid}`;rmSync(temp,{force:!0}),symlinkSync(version,temp);try{lstatSync(paths.engineCurrent).isDirectory()&&rmSync(paths.engineCurrent,{recursive:!0})}catch{}renameSync(temp,paths.engineCurrent)}function pruneEngines(paths,active){let entries=readdirSync(paths.engineRoot,{withFileTypes:!0}).filter(d=>d.name!==CURRENT&&d.name!==active),leftovers=entries.filter(d=>/\.(tmp|old)-\d+$/.test(d.name)),versions=entries.filter(d=>d.isDirectory()&&!leftovers.includes(d)).map(d=>({name:d.name,mtime:statSync(join(paths.engineRoot,d.name)).mtimeMs})).sort((a,b)=>b.mtime-a.mtime),doomed=[...leftovers.map(d=>d.name),...versions.slice(KEEP_PREVIOUS).map(v=>v.name)];for(let name of doomed)rmSync(join(paths.engineRoot,name),{recursive:!0,force:!0});return doomed}function treeDigest(dir){if(!existsSync(dir))return"";let hash=createHash("sha256"),walk=current=>{for(let entry of readdirSync(current,{withFileTypes:!0}).sort((a,b)=>a.name.localeCompare(b.name))){let full=join(current,entry.name);entry.isDirectory()?walk(full):entry.isFile()&&hash.update(`${relative(dir,full)}\0`).update(readFileSync(full))}};return walk(dir),hash.digest("hex")}import{accessSync,constants,realpathSync as realpathSync2,statSync as statSync2}from"node:fs";import{delimiter,dirname,isAbsolute,join as join2}from"node:path";var OTHER_WRITE=2,UNSAFE_IN_LAUNCHER=/['\p{Cc}]/u;function resolved(path){try{return accessSync(path,constants.X_OK),realpathSync2(path)}catch{return null}}function ownFolder(candidate){try{let s=statSync2(dirname(candidate)),uid=process.getuid?.();return(s.uid===0||s.uid===uid)&&(s.mode&OTHER_WRITE)===0}catch{return!1}}function stableNodePath(execPath=process.execPath,searchPath=process.env.PATH??""){let target=resolved(execPath);if(target===null)return execPath;for(let dir of searchPath.split(delimiter)){if(!isAbsolute(dir))continue;let candidate=join2(dir,"node");if(!(candidate===target||UNSAFE_IN_LAUNCHER.test(candidate)||!ownFolder(candidate))&&resolved(candidate)===target)return candidate}return execPath}import{accessSync as accessSync2,constants as constants2,existsSync as existsSync2,readFileSync as readFileSync2}from"node:fs";var LAUNCHER_MODE=493,NODE_LINE=/^NODE='([^']*)'$/m,ENGINE_LINE=/^ENGINE='([^']*)\/engine\/current\/hook\.mjs'$/m;function renderLauncher(template,nodePath,root){for(let[label,value]of[["Node path",nodePath],["home folder",root]])if(value.includes("'"))throw new Error(`${label} '${value}' contains a single quote; move it to a plain path`);return template.replaceAll("@NODE@",()=>nodePath).replaceAll("@ROOT@",()=>root)}function writeLauncher(paths,templateFile,nodePath=stableNodePath()){let text=renderLauncher(readFileSync2(templateFile,"utf8"),nodePath,paths.root);writeFileAtomic(paths.launcher,text,LAUNCHER_MODE)}function rerecordNode(paths,nodePath=stableNodePath()){let text=readFileSync2(paths.launcher,"utf8");if(!NODE_LINE.test(text))throw new Error(`${paths.launcher} has no NODE= line; run 'hookmux init' to rewrite it`);if(nodePath.includes("'"))throw new Error(`Node path '${nodePath}' contains a single quote`);writeFileAtomic(paths.launcher,text.replace(NODE_LINE,()=>`NODE='${nodePath}'`),LAUNCHER_MODE)}function readLauncherInfo(paths){if(!existsSync2(paths.launcher))return{exists:!1,executable:!1,node:null,root:null};let executable=!0;try{accessSync2(paths.launcher,constants2.X_OK)}catch{executable=!1}let text="";try{text=readFileSync2(paths.launcher,"utf8")}catch{}return{exists:!0,executable,node:NODE_LINE.exec(text)?.[1]??null,root:ENGINE_LINE.exec(text)?.[1]??null}}export{installEngine,engineStatus,stableNodePath,writeLauncher,rerecordNode,readLauncherInfo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{DEFAULT_HOST}from"./chunk-SXIEWTYT.mjs";import{parse}from"./chunk-K73ZPBFM.mjs";import{CANONICAL_EVENTS}from"./chunk-ZNEBE4WO.mjs";var TESTS_FILE="tests.toml",CASE_FIELDS={prompt:"prompt text (required for prompt.submit)",expect:'"fire" or "silent"',host:`host id, default "${DEFAULT_HOST}"`,event:'canonical event, default "prompt.submit"',cwd:"working folder the event reports, default the current folder",command:'shell command a tool event carries, such as "git push --force" (tool events only)'};function parseCases(text,knownHosts){let raw;try{raw=parse(text)}catch(error){return{cases:[],problems:[`invalid TOML: ${error.message}`]}}let list=raw.case;if(!Array.isArray(list)||list.length===0)return{cases:[],problems:["needs at least one [[case]]"]};let cases=[],problems=[];return list.forEach((entry,i)=>{let result=readCase(entry,knownHosts);typeof result=="string"?problems.push(`case ${i+1}: ${result}`):cases.push(result)}),{cases,problems}}function readCase(entry,knownHosts){if(entry===null||typeof entry!="object"||Array.isArray(entry))return"must be a table";let c=entry,event=c.event??"prompt.submit";if(typeof event!="string"||!CANONICAL_EVENTS.includes(event))return`unknown event '${String(event)}'`;if(c.expect!=="fire"&&c.expect!=="silent")return'expect must be "fire" or "silent"';if(c.prompt!==void 0&&typeof c.prompt!="string")return"prompt must be a string";if(event==="prompt.submit"&&typeof c.prompt!="string")return"prompt.submit cases need a prompt";let host=c.host??DEFAULT_HOST;return typeof host!="string"||!knownHosts.includes(host)?`unknown host '${String(host)}'`:c.cwd!==void 0&&typeof c.cwd!="string"?"cwd must be a string":c.command!==void 0&&typeof c.command!="string"?"command must be a string":c.command!==void 0&&!event.startsWith("tool.")?"command only applies to tool events":{prompt:c.prompt??"",expect:c.expect,host,event,...c.cwd!==void 0?{cwd:c.cwd}:{},...c.command!==void 0?{command:c.command}:{}}}export{TESTS_FILE,CASE_FIELDS,parseCases};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{cells,featuresFor}from"./chunk-2ZCM3JZR.mjs";import{CANONICAL_EVENTS,PHASES,getCheck}from"./chunk-ZNEBE4WO.mjs";import{readJson,writeFileAtomic}from"./chunk-OYGOSD6V.mjs";import{existsSync}from"node:fs";import{dirname,join}from"node:path";import{fileURLToPath}from"node:url";var PACKAGE_NAME="hookmux";function packageLayout(from=import.meta.url){let dir=dirname(fileURLToPath(from));for(;;){let manifest=join(dir,"package.json");if(existsSync(manifest)&&readJson(manifest,{}).name===PACKAGE_NAME)return{root:dir,dist:join(dir,"dist"),launcherTemplate:join(dir,"launcher","hookmux-hook.sh"),plugins:join(dir,"plugins"),skill:join(dir,"skills","hookmux")};let parent=dirname(dir);if(parent===dir)throw new Error("cannot find the hookmux package folder; reinstall hookmux");dir=parent}}import{existsSync as existsSync3}from"node:fs";import{homedir}from"node:os";import{join as join2}from"node:path";var PLACEHOLDER=/\{(params|host|event|evidence)\.([A-Za-z0-9_-]+)\}/g;function renderTemplate(text,plugin,event,signals){return text.replace(PLACEHOLDER,(whole,scope,key)=>{switch(scope){case"params":return plugin.params[key]??whole;case"host":return key==="id"?event.host.id:key==="name"?event.host.name:key==="version"?event.host.version??"unknown":whole;case"event":return key==="cwd"?event.cwd:key==="name"?event.name:whole;case"evidence":{let spec=plugin.checks[key];return!spec||getCheck(spec.kind)?.modelBacked!==!1?"":signals[key]?.evidence??""}default:return whole}})}var CONTEXT_SEPARATOR=`
|
|
2
|
+
|
|
3
|
+
`;function orderPlugins(plugins){return[...plugins].sort((a,b)=>PHASES.indexOf(a.phase)-PHASES.indexOf(b.phase)||a.priority-b.priority||a.id.localeCompare(b.id))}var EFFECT_VERB={inject:"add context",block:"block",notify:"notify"};function resolveEffect(kind,fallback,supports){let can=e=>supports.has(e);if(can(kind))return{as:kind,via:"native"};let verb=EFFECT_VERB[kind];if(fallback!==void 0){let chosen=fallback.find(can);return chosen?{as:chosen,via:"author",note:`host cannot ${verb} here; fallback ${chosen}`}:{as:null,via:"author",note:`host cannot ${verb} here; no listed fallback works; dropped`}}return kind!=="block"?{as:null,via:"engine",note:`host cannot ${verb} here; dropped`}:can("notify")?{as:"notify",via:"engine",note:"host cannot block here; shown as a notice"}:{as:null,via:"engine",note:"host cannot block or notify here; dropped"}}function compose(event,fired,traces,settings){let result={context:[],notices:[],trace:traces,errors:[]},byId=new Map(traces.map(t=>[t.id,t])),note=(id,text)=>{let t=byId.get(id);t&&(t.note=t.note?`${t.note}; ${text}`:text)},supports=new Set(event.host.supports),claimed=new Set,budget=Math.min(settings.contextBudget,event.host.limits.contextChars),used=0;for(let plugin of orderPlugins(fired)){if(plugin.shadow){note(plugin.id,"shadow: output withheld");continue}if(plugin.exclusive){if(claimed.has(plugin.exclusive)){note(plugin.id,`exclusive group '${plugin.exclusive}' already taken`);continue}claimed.add(plugin.exclusive)}let signals=byId.get(plugin.id)?.signals??{};for(let effect of plugin.effects){let text=renderTemplate(effect.effect==="block"?effect.reason:effect.text,plugin,event,signals);if(effect.effect==="block"){if(result.block)continue;if(settings.blockRequiresRule&&!hasRuleYes(plugin,signals)){note(plugin.id,"block dropped: no rule-backed check agreed");continue}}let resolved=resolveEffect(effect.effect,effect.fallback,supports);if(resolved.note&¬e(plugin.id,resolved.note),resolved.as==="block"&&effect.effect==="block")result.block={reason:text,suppressOriginalPrompt:effect.suppressOriginalPrompt===!0,pluginId:plugin.id};else if(resolved.as==="inject"){let cost=text.length+(result.context.length>0?CONTEXT_SEPARATOR.length:0);if(used+cost>budget){note(plugin.id,`over context budget (${budget} chars); dropped`);continue}used+=cost,result.context.push({pluginId:plugin.id,text})}else resolved.as==="notify"&&result.notices.push({pluginId:plugin.id,text})}}return result}function joinContext(result){return result.context.map(c=>c.text).join(CONTEXT_SEPARATOR)}function hasRuleYes(plugin,signals){return Object.entries(signals).some(([name,s])=>{let spec=plugin.checks[name];return s.value===!0&&spec!==void 0&&getCheck(spec.kind)?.modelBacked===!1})}function asRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null}function str(value){return typeof value=="string"?value:void 0}function parseHostPayload(host,event,payload,reading){let p=asRecord(payload);if(!p)return null;let prompt=str(p.prompt),toolName=str(p.tool_name),parsed={name:event,host:{id:host.id,name:host.name,version:null,adapterContract:1,nativeEvent:str(p.hook_event_name)??host.nativeEvents[event],canonicalEvent:event,supports:host.supports[event],features:featuresFor(host,event),limits:{contextChars:host.contextChars}},sessionId:str(p.session_id)??"",cwd:str(p.cwd)||process.cwd(),origin:event==="prompt.submit"?reading.promptOrigin(p,prompt):"unknown",raw:payload};prompt!==void 0&&(parsed.prompt=prompt);let submitted=event==="prompt.submit"?reading.submittedPrompt?.(p):void 0;submitted!==void 0&&(parsed.submittedPrompt=submitted),toolName!==void 0&&(parsed.tool={name:toolName,canonicalName:reading.canonicalTool(toolName),input:p.tool_input});let source=str(p.source);return source!==void 0&&(parsed.source=source),parsed}import{copyFileSync,existsSync as existsSync2,readFileSync,statSync}from"node:fs";var PLAIN_PATH=/^[A-Za-z0-9_./-]+$/;function shellQuote(value){return PLAIN_PATH.test(value)?value:`'${value.replaceAll("'","'\\''")}'`}function hubCommand(launcher,hostId,event){return`${shellQuote(launcher)} --host ${hostId} --event ${event}`}function firstShellWord(command){let i=0,word="";for(;i<command.length&&!/\s/.test(command[i]);){let ch=command[i];if(ch==="'"){let end=command.indexOf("'",i+1);if(end<0)return null;word+=command.slice(i+1,end),i=end+1}else if(ch==='"'){let closed=readDoubleQuoted(command,i+1);if(!closed)return null;word+=closed.text,i=closed.end+1}else if(ch==="\\"){if(i+1>=command.length)return null;word+=command[i+1],i+=2}else word+=ch,i++}return word===""?null:{word,rest:command.slice(i)}}function readDoubleQuoted(command,start){let text="";for(let i=start;i<command.length;i++){let ch=command[i];if(ch==='"')return{text,end:i};ch==="\\"&&(command[i+1]==='"'||command[i+1]==="\\")?(text+=command[i+1],i++):text+=ch}return null}var HUB_ARGS=/^\s+--host\s+\S+\s+--event\s+(\S+)/;function hubEventOf(command,launcher){if(typeof command!="string")return;let parsed=firstShellWord(command.trim());if(!(parsed===null||parsed.word!==launcher))return HUB_ARGS.exec(parsed.rest)?.[1]}function isHubCommand(command,launcher){return hubEventOf(command,launcher)!==void 0}var ConfigEditError=class extends Error{};function readConfigJson(file){if(!existsSync2(file))return{};let text=readFileSync(file,"utf8");if(text.trim()==="")return{};let parsed;try{parsed=JSON.parse(text)}catch(error){throw new ConfigEditError(`${file} is not valid JSON (${error.message}); fix it first`)}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new ConfigEditError(`${file} must contain a JSON object`);return parsed}function readChecked(file,layout4){let config2=readConfigJson(file);return layout4.checkRoot?.(config2,file),config2}function hookTable(config2,layout4){if(layout4.rootTable)return config2;let hooks=config2.hooks;if(hooks===void 0)return{};if(hooks===null||typeof hooks!="object"||Array.isArray(hooks))throw new ConfigEditError("'hooks' is not an object; fix it first");return hooks}function groupHasHub(group,launcher){return Array.isArray(group?.hooks)&&group.hooks.some(h=>isHubCommand(h?.command,launcher))}function installedEvents(file,launcher,layout4){let hooks;try{hooks=hookTable(readChecked(file,layout4),layout4)}catch{return[]}let out=[];for(let[canonical,native]of Object.entries(layout4.nativeEvents))native&&Array.isArray(hooks[native])&&hooks[native].some(g=>groupHasHub(g,launcher))&&out.push(canonical);return out}function readEventNames(file,layout4){let hooks=hookTable(readChecked(file,layout4),layout4);return new Set(Object.keys(hooks).filter(name=>Array.isArray(hooks[name])))}function save(file,config2,change){existsSync2(file)&&(change.backup=`${file}.hookmux.bak`,copyFileSync(file,change.backup));let mode=existsSync2(file)?statSync(file).mode&511:384;writeFileAtomic(file,`${JSON.stringify(config2,null,2)}
|
|
4
|
+
`,mode),change.changed=!0}function installEntries(file,entry,layout4){let config2=readChecked(file,layout4),hooks=hookTable(config2,layout4),change={file,changed:!1,added:[],removed:[],notes:[]};for(let event of entry.events){let native=layout4.nativeEvents[event];if(!native){change.notes.push(`${layout4.hostId} has no ${event} event; skipped`);continue}let groups=Array.isArray(hooks[native])?hooks[native]:[];if(groups.some(g=>groupHasHub(g,entry.launcher)))continue;let group={},matcher=layout4.matcher?.(event);matcher!==void 0&&(group.matcher=matcher),group.hooks=[layout4.handler(hubCommand(entry.launcher,layout4.hostId,event),entry.timeoutSec,event)],hooks[native]=[...groups,group],change.added.push(event)}return change.added.length>0&&(layout4.rootTable||(config2.hooks=hooks),save(file,config2,change)),change}function uninstallEntries(file,launcher,layout4){let change={file,changed:!1,added:[],removed:[],notes:[]};if(!existsSync2(file))return change;let config2=readChecked(file,layout4),hooks=hookTable(config2,layout4);for(let[canonical,native]of Object.entries(layout4.nativeEvents)){if(!native||!Array.isArray(hooks[native]))continue;let groups=hooks[native];if(!groups.some(g=>groupHasHub(g,launcher)))continue;let kept=withoutHub(groups,launcher,layout4.preserveGroupPositions===!0),lastIndex=groups.findLastIndex(g=>groupHasHub(g,launcher));!layout4.preserveGroupPositions&&lastIndex<groups.length-1&&change.notes.push(`${native}: entries after the hub entry moved up one place; ${layout4.hostId} may ask to re-approve them`),kept.length>0?hooks[native]=kept:delete hooks[native],change.removed.push(canonical)}return change.removed.length>0&&(layout4.rootTable||(Object.keys(hooks).length===0?delete config2.hooks:config2.hooks=hooks),save(file,config2,change)),change}var PLACEHOLDER2=Symbol("removed hub group");function withoutHub(groups,launcher,preserve){let kept=[];for(let group of groups){if(!groupHasHub(group,launcher)){kept.push(group);continue}let others=(group.hooks??[]).filter(h=>!isHubCommand(h?.command,launcher));others.length>0?kept.push({...group,hooks:others}):preserve&&kept.push(PLACEHOLDER2)}for(;kept.at(-1)===PLACEHOLDER2;)kept.pop();return kept.map(g=>g===PLACEHOLDER2?{hooks:[]}:g)}var ID="claude-code",NATIVE={"prompt.submit":"UserPromptSubmit","session.start":"SessionStart","tool.before":"PreToolUse","tool.after":"PostToolUse"},SUPPORTS={"prompt.submit":["inject","block","notify"],"session.start":["inject","notify"],"tool.before":["inject","block","notify"],"tool.after":["inject","block","notify"]},HOST_FEATURES={"host.version":cells(!1,...CANONICAL_EVENTS),"prompt.origin":cells(!0,"prompt.submit"),"tool.file-path":cells(!0,"tool.before","tool.after"),"inject.markup":cells(!0,...CANONICAL_EVENTS),"inject.inline":cells(!0,...CANONICAL_EVENTS),"inject.before-call":cells(!0,"tool.before"),"block.prevents":{...cells(!0,"prompt.submit","tool.before"),...cells(!1,"tool.after")},"block.reason-to-agent":{...cells(!1,"prompt.submit"),...cells(!0,"tool.before","tool.after")},"block.suppress-prompt":cells(!0,"prompt.submit")},FEATURE_NOTES={"block.reason-to-agent":"On a prompt the reason is shown to the user only."},CONTEXT_CHARS=1e4,SYSTEM_PROMPT_PREFIXES=["<task-notification>"];function configDir(env){return env.CLAUDE_CONFIG_DIR||join2(homedir(),".claude")}var layout={hostId:ID,nativeEvents:NATIVE,handler:(command,timeoutSec)=>({type:"command",command,timeout:timeoutSec})};function originOf(prompt){if(prompt===void 0)return"unknown";let head=prompt.trimStart();return SYSTEM_PROMPT_PREFIXES.some(p=>head.startsWith(p))?"system":"user"}var HOST={id:ID,name:"Claude Code",nativeEvents:NATIVE,supports:SUPPORTS,contextChars:CONTEXT_CHARS,features:HOST_FEATURES,featureNotes:FEATURE_NOTES},claudeCode={...HOST,contractVersion:1,parse(event,payload){return parseHostPayload(HOST,event,payload,{promptOrigin:(_payload,prompt)=>originOf(prompt),canonicalTool:name=>name})},render(result,event){let native=NATIVE[event.name],out={},context=joinContext(result);return result.notices.length>0&&(out.systemMessage=result.notices.map(n=>n.text).join(`
|
|
5
|
+
`)),result.block?event.name==="tool.before"?out.hookSpecificOutput={hookEventName:native,permissionDecision:"deny",permissionDecisionReason:result.block.reason}:(out.decision="block",out.reason=result.block.reason,event.name==="prompt.submit"&&result.block.suppressOriginalPrompt&&(out.hookSpecificOutput={hookEventName:native,suppressOriginalPrompt:!0})):context&&(out.hookSpecificOutput={hookEventName:native,additionalContext:context}),Object.keys(out).length>0?JSON.stringify(out):""},confirm(_event,ask){return JSON.stringify({hookSpecificOutput:{hookEventName:NATIVE["tool.before"],permissionDecision:"ask",permissionDecisionReason:ask.reason,updatedInput:ask.input}})},sample(event,prompt="hookmux doctor check"){let base={session_id:"hookmux-doctor",transcript_path:"",cwd:process.cwd(),hook_event_name:NATIVE[event]};return event==="prompt.submit"?{...base,prompt,permission_mode:"default"}:event==="session.start"?{...base,source:"startup"}:event==="tool.before"?{...base,tool_name:"Bash",tool_input:{command:"echo ok"}}:{...base,tool_name:"Bash",tool_input:{command:"echo ok"},tool_response:{stdout:"ok"}}},config:{file:(env=process.env)=>join2(configDir(env),"settings.json"),detect:(env=process.env)=>existsSync3(configDir(env)),installed(launcher,env=process.env){return installedEvents(this.file(env),launcher,layout)},install(entry,env=process.env){return installEntries(this.file(env),entry,layout)},uninstall(launcher,env=process.env){return uninstallEntries(this.file(env),launcher,layout)}},skills:{global:join2(configDir(process.env),"skills")}};import{homedir as homedir2}from"node:os";import{join as join4}from"node:path";import{existsSync as existsSync4}from"node:fs";import{join as join3}from"node:path";var CLAUDE_EVENTS={"prompt.submit":"UserPromptSubmit","session.start":"SessionStart","tool.before":"PreToolUse","tool.after":"PostToolUse"},DEFAULT_CONTEXT_CHARS=1e4;function claudeLayout(hostId,rootTable=!1){return{hostId,nativeEvents:CLAUDE_EVENTS,handler:(command,timeoutSec)=>({type:"command",command,timeout:timeoutSec}),rootTable}}function denyTool(native,reason){return{hookSpecificOutput:{hookEventName:native,permissionDecision:"deny",permissionDecisionReason:reason}}}function renderClaudeStyle(spec,result,event){let supports=spec.supports[event.name],native=CLAUDE_EVENTS[event.name],out={};result.notices.length>0&&supports.includes("notify")&&(out.systemMessage=result.notices.map(n=>n.text).join(`
|
|
6
|
+
`));let context=joinContext(result);if(result.block&&supports.includes("block")){let reason=result.block.reason;Object.assign(out,event.name==="tool.before"?denyTool(native,reason):spec.blockOutput(event.name,native,reason))}else context&&supports.includes("inject")&&(out.hookSpecificOutput={hookEventName:native,additionalContext:context});return Object.keys(out).length>0?JSON.stringify(out):""}function sampleFor(spec,event,prompt){let base={session_id:"hookmux-doctor",transcript_path:"",cwd:process.cwd(),hook_event_name:CLAUDE_EVENTS[event]};if(event==="prompt.submit")return{...base,prompt,...spec.samplePromptFields?.(prompt)};if(event==="session.start")return{...base,source:"startup"};let tool={...base,tool_name:spec.sampleShellTool??"Bash",tool_input:{command:"echo ok"}};return event==="tool.before"?tool:{...tool,tool_response:{stdout:"ok"}}}function settingsEditor(spec){let layout4=claudeLayout(spec.id);return{file:(env=process.env)=>join3(spec.configDir(env),"settings.json"),detect:(env=process.env)=>existsSync4(spec.configDir(env)),installed(launcher,env=process.env){return installedEvents(this.file(env),launcher,layout4)},install(entry,env=process.env){return installEntries(this.file(env),entry,layout4)},uninstall(launcher,env=process.env){return uninstallEntries(this.file(env),launcher,layout4)}}}function claudeStyleAdapter(spec){let host={id:spec.id,name:spec.name,nativeEvents:CLAUDE_EVENTS,supports:spec.supports,contextChars:DEFAULT_CONTEXT_CHARS,features:spec.features,...spec.featureNotes?{featureNotes:spec.featureNotes}:{}},tools=spec.canonicalTools??{},base=spec.config??settingsEditor(spec),config2=spec.installNote?{...base,install(entry,env){let change=base.install(entry,env);return change.notes.push(spec.installNote),change}}:base;return{...host,contractVersion:1,parse(event,payload){return parseHostPayload(host,event,payload,{promptOrigin:spec.promptOrigin??((_payload,prompt)=>prompt===void 0?"unknown":"user"),canonicalTool:name=>Object.hasOwn(tools,name)?tools[name]:name,...spec.submittedPrompt?{submittedPrompt:spec.submittedPrompt}:{}})},render:(result,event)=>renderClaudeStyle(spec,result,event),...spec.confirmOutput?{confirm:(_event,ask)=>JSON.stringify(spec.confirmOutput(CLAUDE_EVENTS["tool.before"],ask.reason,ask.input))}:{},sample:(event,prompt="hookmux doctor check")=>sampleFor(spec,event,prompt),config:config2,...spec.skillsDir?{skills:{global:spec.skillsDir(process.env)}}:{}}}var SUPPORTS2={"prompt.submit":["inject","block","notify"],"session.start":["inject","notify"],"tool.before":["inject","block","notify"],"tool.after":["inject","notify"]},HOST_FEATURES2={"host.version":cells(!1,...CANONICAL_EVENTS),"prompt.origin":cells(!1,"prompt.submit"),"tool.file-path":cells(!0,"tool.before","tool.after"),"inject.markup":cells(null,...CANONICAL_EVENTS),"inject.inline":cells(null,...CANONICAL_EVENTS),"inject.before-call":cells(null,"tool.before"),"block.prevents":cells(!0,"prompt.submit","tool.before"),"block.reason-to-agent":{...cells(!1,"prompt.submit"),...cells(null,"tool.before")},"block.suppress-prompt":cells(!1,"prompt.submit")},FEATURE_NOTES2={"block.reason-to-agent":"A blocked prompt's reason is shown to the user only."},codebuddy=claudeStyleAdapter({id:"codebuddy",name:"CodeBuddy Code",supports:SUPPORTS2,features:HOST_FEATURES2,featureNotes:FEATURE_NOTES2,configDir:env=>join4(env.HOME||homedir2(),".codebuddy"),blockOutput:(_event,_native,reason)=>({continue:!1,reason})});import{existsSync as existsSync5}from"node:fs";import{homedir as homedir4}from"node:os";import{join as join6}from"node:path";import{spawn}from"node:child_process";import{realpathSync}from"node:fs";import{homedir as homedir3}from"node:os";import{basename,dirname as dirname2,join as join5}from"node:path";import{createInterface}from"node:readline";var DEFAULT_TIMEOUT_MS=2e4,KILL_GRACE_MS=2e3;function hubEntries(hooks,target){let sourcePaths=codexSourcePaths(target.hooksFile),entries=hooks.filter(h=>hubEventOf(h.command,target.launcher)!==void 0&&sourcePaths.includes(h.sourcePath)&&h.source==="user"&&!h.isManaged),seen=new Set(entries.map(h=>hubEventOf(h.command,target.launcher)));return{entries,missing:target.events.filter(e=>!seen.has(e))}}function isCurrentHubEntry(hook,launcher){return hook.handlerType==="command"&&hook.async===!1&&hook.matcher===null&&CANONICAL_EVENTS.some(e=>hook.command===hubCommand(launcher,"codex",e))}var CodexUnavailableError=class extends Error{};function codexSourcePaths(hooksFile){try{return[hooksFile,join5(realpathSync(dirname2(hooksFile)),basename(hooksFile))]}catch{return[hooksFile]}}function needsApproval(hook){return hook.trustStatus==="untrusted"||hook.trustStatus==="modified"}async function approveHubEntries(target){return withAppServer(target,async call=>{let{entries:listed,missing}=hubEntries(await listHooks(call),target),untrusted=listed.filter(needsApproval),pending=untrusted.filter(h=>isCurrentHubEntry(h,target.launcher));if(pending.length===0){let stillUntrusted=untrusted.map(h=>h.key);return{approved:[],alreadyTrusted:listed.length-untrusted.length,stillUntrusted,missing}}await call("config/batchWrite",{edits:pending.map(h=>({keyPath:`hooks.state.${tomlKey(h.key)}.trusted_hash`,mergeStrategy:"upsert",value:h.currentHash}))});let after=hubEntries(await listHooks(call),target).entries;return{approved:pending.map(h=>h.key).filter(k=>after.some(h=>h.key===k&&h.trustStatus==="trusted")),alreadyTrusted:listed.length-untrusted.length,stillUntrusted:after.filter(needsApproval).map(h=>h.key),missing}})}async function listHubEntries(target){return withAppServer(target,async call=>hubEntries(await listHooks(call),target))}async function listHooks(call){return((await call("hooks/list",{cwds:[homedir3()]})).data??[]).flatMap(entry=>entry.hooks??[])}function tomlKey(key){return JSON.stringify(key)}async function withAppServer(target,body){let child=spawn(target.codex??"codex",["app-server"],{env:target.env,stdio:["pipe","pipe","ignore"]}),waiting=new Map,nextId=0,failure,failAll=error=>{failure??=error;for(let w of waiting.values())w.reject(failure);waiting.clear()};child.on("error",error=>{let message=`could not start codex app-server: ${error.message}`;failAll(error.code==="ENOENT"?new CodexUnavailableError(message):new Error(message))}),child.on("exit",code=>failAll(new Error(`codex app-server exited (${code??"signal"})`))),child.stdin.on("error",error=>failAll(new Error(`codex app-server closed its input: ${error.message}`))),createInterface({input:child.stdout}).on("line",line=>{let message;try{message=JSON.parse(line)}catch{return}if(message.method!==void 0)return;let w=typeof message.id=="number"?waiting.get(message.id):void 0;w&&(waiting.delete(message.id),message.error?w.reject(new Error(message.error.message??"codex app-server returned an error")):w.resolve(message.result))});let send=payload=>child.stdin.write(`${JSON.stringify(payload)}
|
|
7
|
+
`),call=(method,params)=>new Promise((resolve,reject)=>{if(failure)return reject(failure);let id=++nextId;waiting.set(id,{resolve,reject}),send({jsonrpc:"2.0",id,method,params})}),timer=setTimeout(()=>failAll(new Error("codex app-server did not answer in time")),target.timeoutMs??DEFAULT_TIMEOUT_MS);try{return await call("initialize",{clientInfo:{name:"hookmux",version:"1"}}),send({jsonrpc:"2.0",method:"initialized"}),await body(call)}finally{clearTimeout(timer),await stop(child)}}async function stop(child){if(child.pid===void 0||child.exitCode!==null||child.signalCode!==null)return;let exited=new Promise(resolve=>child.once("exit",()=>resolve()));child.stdin?.end(),child.kill();let escalate=setTimeout(()=>child.kill("SIGKILL"),KILL_GRACE_MS);await exited,clearTimeout(escalate)}var ID2="codex",NATIVE2={"prompt.submit":"UserPromptSubmit","session.start":"SessionStart","tool.before":"PreToolUse","tool.after":"PostToolUse"},SUPPORTS3={"prompt.submit":["inject","block","notify"],"session.start":["inject","notify"],"tool.before":["inject","block","notify"],"tool.after":["inject","block","notify"]},HOST_FEATURES3={"host.version":cells(!1,...CANONICAL_EVENTS),"prompt.origin":cells(!0,"prompt.submit"),"tool.file-path":cells(!1,"tool.before","tool.after"),"inject.markup":cells(null,...CANONICAL_EVENTS),"inject.inline":cells(!1,...CANONICAL_EVENTS),"inject.before-call":cells(null,"tool.before"),"block.prevents":{...cells(!0,"prompt.submit","tool.before"),...cells(!1,"tool.after")},"block.reason-to-agent":{...cells(null,"prompt.submit","tool.before"),...cells(!0,"tool.after")},"block.suppress-prompt":cells(!1,"prompt.submit")},FEATURE_NOTES3={"tool.file-path":"apply_patch edits carry patch text in tool_input.command.","inject.inline":"Context over about 2,500 tokens is saved to a file and the model sees a preview."},CONTEXT_CHARS2=1e4,FALLBACK_BLOCK_REASON="Blocked by a hookmux plugin.",CANONICAL_TOOLS={apply_patch:"Edit"},ROOT_KEYS=new Set(["description","hooks"]);function codexHome(env){return env.CODEX_HOME||join6(homedir4(),".codex")}function checkRoot(config2,file){let foreign=Object.keys(config2).filter(key=>!ROOT_KEYS.has(key));if(foreign.length!==0)throw new ConfigEditError(`${file} has root keys Codex does not accept (${foreign.join(", ")}); Codex ignores the whole file until they are removed`)}var layout2={hostId:ID2,nativeEvents:NATIVE2,handler:(command,timeoutSec)=>({type:"command",command,timeout:timeoutSec}),checkRoot,preserveGroupPositions:!0};function originOf2(payload,prompt){return prompt===void 0?"unknown":typeof payload.agent_id=="string"?"system":"user"}function reasonOf(reason){return reason.trim()===""?FALLBACK_BLOCK_REASON:reason}function blockOutput(event,native,reason){return event==="tool.before"?{hookSpecificOutput:{hookEventName:native,permissionDecision:"deny",permissionDecisionReason:reason}}:{decision:"block",reason}}var HOST2={id:ID2,name:"Codex",nativeEvents:NATIVE2,supports:SUPPORTS3,contextChars:CONTEXT_CHARS2,features:HOST_FEATURES3,featureNotes:FEATURE_NOTES3},codex={...HOST2,contractVersion:1,parse(event,payload){return parseHostPayload(HOST2,event,payload,{promptOrigin:originOf2,canonicalTool:name=>CANONICAL_TOOLS[name]??name})},render(result,event){let native=NATIVE2[event.name],supports=SUPPORTS3[event.name],out={};result.notices.length>0&&supports.includes("notify")&&(out.systemMessage=result.notices.map(n=>n.text).join(`
|
|
8
|
+
`));let context=joinContext(result);return result.block&&supports.includes("block")?Object.assign(out,blockOutput(event.name,native,reasonOf(result.block.reason))):context&&supports.includes("inject")&&(out.hookSpecificOutput={hookEventName:native,additionalContext:context}),Object.keys(out).length>0?JSON.stringify(out):""},sample(event,prompt="hookmux doctor check"){let base={session_id:"hookmux-doctor",transcript_path:null,cwd:process.cwd(),hook_event_name:NATIVE2[event],model:"hookmux-doctor",permission_mode:"default"};if(event==="session.start")return{...base,source:"startup"};let turn={...base,turn_id:"hookmux-doctor-turn"};if(event==="prompt.submit")return{...turn,prompt};let tool={...turn,tool_name:"Bash",tool_input:{command:"echo ok"},tool_use_id:"hookmux-doctor-call"};return event==="tool.before"?tool:{...tool,tool_response:`ok
|
|
9
|
+
`}},config:{file:(env=process.env)=>join6(codexHome(env),"hooks.json"),detect:(env=process.env)=>existsSync5(codexHome(env)),installed(launcher,env=process.env){return installedEvents(this.file(env),launcher,layout2)},install(entry,env=process.env){return installEntries(this.file(env),entry,layout2)},uninstall(launcher,env=process.env){return uninstallEntries(this.file(env),launcher,layout2)},approve(launcher,env=process.env){return approveHubEntries({launcher,hooksFile:this.file(env),events:this.installed(launcher,env),env,codex:env.HOOKMUX_CODEX||"codex"})}},skills:{global:join6(homedir4(),".agents","skills")}};import{existsSync as existsSync6}from"node:fs";import{homedir as homedir5}from"node:os";import{join as join7}from"node:path";var SUPPORTS4={"prompt.submit":["inject","block","notify"],"session.start":["inject","notify"],"tool.before":["block","notify"],"tool.after":["inject","block","notify"]},HOST_FEATURES4={"host.version":cells(!1,...CANONICAL_EVENTS),"prompt.origin":cells(!1,"prompt.submit"),"tool.file-path":cells(!1,"tool.before","tool.after"),"inject.markup":cells(null,"prompt.submit","session.start","tool.after"),"inject.inline":cells(null,"prompt.submit","session.start","tool.after"),"inject.before-call":{},"block.prevents":{...cells(!0,"prompt.submit","tool.before"),...cells(!1,"tool.after")},"block.reason-to-agent":{...cells(null,"prompt.submit","tool.before"),...cells(!0,"tool.after")},"block.suppress-prompt":cells(!1,"prompt.submit")},FEATURE_NOTES4={"tool.file-path":"ApplyPatch input has no file_path."},CANONICAL_TOOLS2={Execute:"Bash",Create:"Write",ApplyPatch:"Edit"},factoryDir=(env=process.env)=>join7(env.HOME||homedir5(),".factory"),rootLayout=claudeLayout("droid",!0),settingsLayout=claudeLayout("droid");function files(dir){let hooksJson=join7(dir,"hooks.json"),legacy=join7(dir,"hooks","hooks.json"),activeRoot=!existsSync6(hooksJson)&&existsSync6(legacy)?legacy:hooksJson;return{hooksJson,settingsJson:join7(dir,"settings.json"),activeRoot}}function definedEvents(f){return{root:readEventNames(f.activeRoot,rootLayout),settings:readEventNames(f.settingsJson,settingsLayout)}}function settingsOwned(f,events){let defined=definedEvents(f);return events.filter(e=>!defined.root.has(CLAUDE_EVENTS[e])&&defined.settings.has(CLAUDE_EVENTS[e]))}function merge(a,b){let written=[a,b].filter(c=>c.changed);return{file:written.length>0?written.map(c=>c.file).join(", "):a.file,changed:written.length>0,...written[0]?.backup?{backup:written[0].backup}:{},added:[...a.added,...b.added],removed:[...a.removed,...b.removed],notes:[...a.notes,...b.notes]}}var config={file:env=>files(factoryDir(env)).hooksJson,detect:env=>existsSync6(factoryDir(env)),installed(launcher,env){let f=files(factoryDir(env)),shadowed;try{shadowed=readEventNames(f.activeRoot,rootLayout)}catch{shadowed=new Set}let found=new Set([...installedEvents(f.activeRoot,launcher,rootLayout),...installedEvents(f.settingsJson,launcher,settingsLayout).filter(e=>!shadowed.has(CLAUDE_EVENTS[e]))]);return Object.keys(CLAUDE_EVENTS).filter(e=>found.has(e))},install(entry,env){let f=files(factoryDir(env)),toSettings=settingsOwned(f,entry.events),toRoot=entry.events.filter(e=>!toSettings.includes(e));if(toRoot.length>0&&f.activeRoot!==f.hooksJson)throw new ConfigEditError(`${f.activeRoot} is Droid's legacy hooks file, and Droid stops reading it once hooks.json exists; save any hook from Droid's /hooks screen once to migrate it, then run hookmux sync`);return merge(installEntries(f.activeRoot,{...entry,events:toRoot},rootLayout),installEntries(f.settingsJson,{...entry,events:toSettings},settingsLayout))},uninstall(launcher,env){let f=files(factoryDir(env));return readEventNames(f.hooksJson,rootLayout),readEventNames(f.settingsJson,settingsLayout),merge(uninstallEntries(f.hooksJson,launcher,rootLayout),uninstallEntries(f.settingsJson,launcher,settingsLayout))}},droid=claudeStyleAdapter({id:"droid",name:"Factory Droid",supports:SUPPORTS4,features:HOST_FEATURES4,featureNotes:FEATURE_NOTES4,configDir:factoryDir,blockOutput:(_event,_native,reason)=>({decision:"block",reason}),canonicalTools:CANONICAL_TOOLS2,config,sampleShellTool:"Execute"});import{existsSync as existsSync7}from"node:fs";import{homedir as homedir6}from"node:os";import{join as join8}from"node:path";var ID3="gemini-cli",NATIVE3={"prompt.submit":"BeforeAgent","session.start":"SessionStart","tool.before":"BeforeTool","tool.after":"AfterTool"},SUPPORTS5={"prompt.submit":["inject","block","notify"],"session.start":["inject","notify"],"tool.before":["block","notify"],"tool.after":["inject","block","notify"]},HOST_FEATURES5={"host.version":cells(!1,...CANONICAL_EVENTS),"prompt.origin":cells(!1,"prompt.submit"),"tool.file-path":cells(null,"tool.before","tool.after"),"inject.markup":cells(!1,"prompt.submit","session.start","tool.after"),"inject.inline":cells(!0,"prompt.submit","session.start","tool.after"),"inject.before-call":{},"block.prevents":{...cells(!0,"prompt.submit","tool.before"),...cells(!1,"tool.after")},"block.reason-to-agent":cells(null,"prompt.submit","tool.before","tool.after"),"block.suppress-prompt":cells(!0,"prompt.submit")},FEATURE_NOTES5={"inject.markup":"< and > are escaped and the context is wrapped in hook_context tags."},CONTEXT_CHARS3=1e4,MS_PER_SECOND=1e3,HANDLER_NAME="hookmux",CANONICAL_TOOLS3={run_shell_command:"Bash",write_file:"Write",replace:"Edit",read_file:"Read",glob:"Glob",grep_search:"Grep",list_directory:"LS"},TRUST_NOTE="Gemini CLI runs these hooks only in folders you have marked as trusted";function geminiDir(env){return join8(env.GEMINI_CLI_HOME||homedir6(),".gemini")}var layout3={hostId:ID3,nativeEvents:NATIVE3,handler:(command,timeoutSec)=>({type:"command",name:HANDLER_NAME,command,timeout:timeoutSec*MS_PER_SECOND})};function blockOutput2(event,reason,suppressOriginalPrompt){return event==="prompt.submit"&&!suppressOriginalPrompt?{continue:!1,stopReason:reason}:{decision:"deny",reason}}var HOST3={id:ID3,name:"Gemini CLI",nativeEvents:NATIVE3,supports:SUPPORTS5,contextChars:CONTEXT_CHARS3,features:HOST_FEATURES5,featureNotes:FEATURE_NOTES5},geminiCli={...HOST3,contractVersion:1,parse(event,payload){return parseHostPayload(HOST3,event,payload,{promptOrigin:(_payload,prompt)=>prompt===void 0?"unknown":"user",canonicalTool:name=>CANONICAL_TOOLS3[name]??name})},render(result,event){let supports=SUPPORTS5[event.name],out={};result.notices.length>0&&supports.includes("notify")&&(out.systemMessage=result.notices.map(n=>n.text).join(`
|
|
10
|
+
`));let context=joinContext(result);return result.block&&supports.includes("block")?Object.assign(out,blockOutput2(event.name,result.block.reason,result.block.suppressOriginalPrompt)):context&&supports.includes("inject")&&(out.hookSpecificOutput={hookEventName:NATIVE3[event.name],additionalContext:context}),Object.keys(out).length>0?JSON.stringify(out):""},sample(event,prompt="hookmux doctor check"){let base={session_id:"hookmux-doctor",transcript_path:"",cwd:process.cwd(),hook_event_name:NATIVE3[event],timestamp:new Date().toISOString()};if(event==="prompt.submit")return{...base,prompt};if(event==="session.start")return{...base,source:"startup"};let tool={...base,tool_name:"run_shell_command",tool_input:{command:"echo ok"}};return event==="tool.before"?tool:{...tool,tool_response:{llmContent:"ok",returnDisplay:"ok"}}},config:{file:(env=process.env)=>join8(geminiDir(env),"settings.json"),detect:(env=process.env)=>existsSync7(geminiDir(env)),installed(launcher,env=process.env){return installedEvents(this.file(env),launcher,layout3)},install(entry,env=process.env){let change=installEntries(this.file(env),entry,layout3);return change.notes.push(TRUST_NOTE),change},uninstall(launcher,env=process.env){return uninstallEntries(this.file(env),launcher,layout3)}},skills:{global:join8(geminiDir(process.env),"skills")}};import{existsSync as existsSync8,readFileSync as readFileSync2,rmSync}from"node:fs";import{homedir as homedir7}from"node:os";import{join as join9}from"node:path";var ID4="opencode",NATIVE4={"prompt.submit":"chat.message","session.start":"event","tool.before":"tool.execute.before","tool.after":"tool.execute.after"},SUPPORTS6={"prompt.submit":["inject","notify"],"session.start":["inject","notify"],"tool.before":["block","notify"],"tool.after":["inject","notify"]},CONTEXT_CHARS4=1e4,CANONICAL_TOOLS4={bash:"Bash",write:"Write",edit:"Edit",read:"Read",apply_patch:"Edit"},HOST_FEATURES6={"host.version":cells(!1,...CANONICAL_EVENTS),"prompt.origin":cells(!0,"prompt.submit"),"tool.file-path":cells(!1,"tool.before","tool.after"),"inject.markup":cells(null,"prompt.submit","session.start","tool.after"),"inject.inline":cells(null,"prompt.submit","session.start","tool.after"),"inject.before-call":{},"block.prevents":cells(!0,"tool.before"),"block.reason-to-agent":cells(!0,"tool.before"),"block.suppress-prompt":{}},FEATURE_NOTES6={"tool.file-path":"apply_patch edits carry patch text, not a file path."};function originOf3(payload,prompt){return payload.origin==="system"||payload.origin==="user"?payload.origin:prompt===void 0?"unknown":"user"}function withFilePath(input){if(input===null||typeof input!="object"||Array.isArray(input))return input;let record=input;return typeof record.filePath!="string"||"file_path"in record?input:{...record,file_path:record.filePath}}var HOST4={id:ID4,name:"opencode",nativeEvents:NATIVE4,supports:SUPPORTS6,contextChars:CONTEXT_CHARS4,features:HOST_FEATURES6,featureNotes:FEATURE_NOTES6};function renderOpencode(result,event){let supports=SUPPORTS6[event.name],out={};result.notices.length>0&&supports.includes("notify")&&(out.notice=result.notices.map(n=>n.text).join(`
|
|
11
|
+
`));let context=joinContext(result);return result.block&&supports.includes("block")?out.block=result.block.reason:context&&supports.includes("inject")&&(out.context=context),Object.keys(out).length>0?JSON.stringify(out):""}function sampleFor2(event,prompt){let base={session_id:"hookmux-doctor",cwd:process.cwd(),hook_event_name:NATIVE4[event]};if(event==="prompt.submit")return{...base,prompt,origin:"user"};if(event==="session.start")return base;let tool={...base,tool_name:"bash",tool_input:{command:"echo ok"}};return event==="tool.before"?tool:{...tool,tool_response:`ok
|
|
12
|
+
`}}var MARKER="// hookmux generated this opencode plugin; `hookmux sync` rewrites it.",LAUNCHER_LINE=/^const LAUNCHER = (".*");$/m,EVENTS_LINE=/^const EVENTS = (\[.*\]);$/m;function readMeta(file){if(!existsSync8(file))return null;let text=readFileSync2(file,"utf8");if(!text.startsWith(MARKER))return null;let launcher=LAUNCHER_LINE.exec(text)?.[1],events=EVENTS_LINE.exec(text)?.[1];if(launcher===void 0||events===void 0)return null;try{return{launcher:JSON.parse(launcher),events:JSON.parse(events)}}catch{return{launcher:"",events:[]}}}function opencodeConfigDir(env){let base=env.XDG_CONFIG_HOME||join9(env.HOME||homedir7(),".config");return join9(base,"opencode")}function renderPlugin(template,launcher,events,timeoutSec){return template.replaceAll('"@LAUNCHER_JSON@"',()=>JSON.stringify(launcher)).replaceAll('"@EVENTS_JSON@"',()=>JSON.stringify(events)).replaceAll('"@TIMEOUT_MS@"',()=>String(timeoutSec*1e3))}function opencodePluginEditor(){let file=(env=process.env)=>join9(opencodeConfigDir(env),"plugins","hookmux.js");return{file,detect:(env=process.env)=>existsSync8(opencodeConfigDir(env)),installed(launcher,env=process.env){let meta=readMeta(file(env));return meta&&meta.launcher===launcher?meta.events:[]},install(entry,env=process.env){let target=file(env),change={file:target,changed:!1,added:[],removed:[],notes:[]},existing=readMeta(target);if(existing===null&&existsSync8(target))throw new ConfigEditError(`${target} exists and was not written by hookmux; move it aside before installing here`);if(entry.events.length===0)return change;let already=existing?.launcher===entry.launcher?existing.events:[],added=CANONICAL_EVENTS.filter(e=>entry.events.includes(e)&&!already.includes(e)),union=CANONICAL_EVENTS.filter(e=>already.includes(e)||added.includes(e)),templateFile=join9(packageLayout().root,"launcher","opencode-plugin.js"),text=renderPlugin(readFileSync2(templateFile,"utf8"),entry.launcher,union,entry.timeoutSec);return existing!==null&&readFileSync2(target,"utf8")===text||(writeFileAtomic(target,text),change.changed=!0,change.added=added),change},uninstall(launcher,env=process.env){let target=file(env),change={file:target,changed:!1,added:[],removed:[],notes:[]},meta=readMeta(target);return!meta||meta.launcher!==launcher||(rmSync(target,{force:!0}),change.changed=!0,change.removed=meta.events),change}}}var opencode={...HOST4,contractVersion:1,parse(event,payload){let parsed=parseHostPayload(HOST4,event,payload,{promptOrigin:originOf3,canonicalTool:name=>CANONICAL_TOOLS4[name]??name});return parsed?.tool&&(parsed.tool.input=withFilePath(parsed.tool.input)),parsed},render:renderOpencode,sample:(event,prompt="hookmux doctor check")=>sampleFor2(event,prompt),config:opencodePluginEditor()};import{homedir as homedir8}from"node:os";import{join as join10}from"node:path";var SUPPORTS7={"prompt.submit":["inject","block","notify"],"session.start":["inject","notify"],"tool.before":["inject","block","notify"],"tool.after":["inject","notify"]},HOST_FEATURES7={"host.version":cells(!1,...CANONICAL_EVENTS),"prompt.origin":cells(!1,"prompt.submit"),"tool.file-path":cells(!0,"tool.before","tool.after"),"inject.markup":cells(null,...CANONICAL_EVENTS),"inject.inline":cells(null,...CANONICAL_EVENTS),"inject.before-call":cells(null,"tool.before"),"block.prevents":cells(!0,"prompt.submit","tool.before"),"block.reason-to-agent":cells(null,"prompt.submit","tool.before"),"block.suppress-prompt":cells(!1,"prompt.submit")};function qoderDir(env){return env.QODER_CONFIG_DIR||join10(homedir8(),".qoder")}var qoder=claudeStyleAdapter({id:"qoder",name:"Qoder CLI",supports:SUPPORTS7,features:HOST_FEATURES7,configDir:qoderDir,blockOutput:(_event,_native,reason)=>({decision:"deny",reason})});import{homedir as homedir9}from"node:os";import{join as join11}from"node:path";var SUPPORTS8={"prompt.submit":["inject","block","notify"],"session.start":["inject","notify"],"tool.before":["inject","block","notify"],"tool.after":["inject","block","notify"]},HOST_FEATURES8={"host.version":cells(!1,...CANONICAL_EVENTS),"prompt.origin":cells(!0,"prompt.submit"),"tool.file-path":cells(!0,"tool.before","tool.after"),"inject.markup":cells(!1,...CANONICAL_EVENTS),"inject.inline":cells(null,...CANONICAL_EVENTS),"inject.before-call":cells(!1,"tool.before"),"block.prevents":{...cells(!0,"prompt.submit","tool.before"),...cells(!1,"tool.after")},"block.reason-to-agent":cells(null,"prompt.submit","tool.before","tool.after"),"block.suppress-prompt":cells(!1,"prompt.submit")},FEATURE_NOTES7={"inject.before-call":"Context added before a tool call is appended to that call's result.","inject.markup":"< and > in added context are escaped."},CANONICAL_TOOLS5={run_shell_command:"Bash",write_file:"Write",edit:"Edit",read_file:"Read"};function qwenDir(env){return env.QWEN_HOME||join11(homedir9(),".qwen")}function originOf4(payload,prompt){return prompt===void 0?"unknown":typeof payload.submitted_prompt=="string"?"user":"system"}var qwenCode=claudeStyleAdapter({id:"qwen-code",name:"Qwen Code",supports:SUPPORTS8,features:HOST_FEATURES8,featureNotes:FEATURE_NOTES7,configDir:qwenDir,blockOutput:(_event,_native,reason)=>({decision:"block",reason}),canonicalTools:CANONICAL_TOOLS5,confirmOutput:(native,reason,input)=>({hookSpecificOutput:{hookEventName:native,permissionDecision:"ask",permissionDecisionReason:reason,updatedInput:input}}),promptOrigin:originOf4,submittedPrompt:payload=>typeof payload.submitted_prompt=="string"?payload.submitted_prompt:void 0,skillsDir:env=>join11(qwenDir(env),"skills"),sampleShellTool:"run_shell_command",samplePromptFields:prompt=>({submitted_prompt:prompt})});var ADAPTERS={[claudeCode.id]:claudeCode,[codex.id]:codex,[geminiCli.id]:geminiCli,[qwenCode.id]:qwenCode,[droid.id]:droid,[qoder.id]:qoder,[codebuddy.id]:codebuddy,[opencode.id]:opencode};function getAdapter(id){return Object.hasOwn(ADAPTERS,id)?ADAPTERS[id]:void 0}export{resolveEffect,compose,CodexUnavailableError,listHubEntries,packageLayout,ADAPTERS,getAdapter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{homedir}from"node:os";import{join}from"node:path";function homePaths(root=process.env.HOOKMUX_HOME||join(homedir(),".hookmux")){return{root,bin:join(root,"bin"),launcher:join(root,"bin","hookmux-hook"),engineRoot:join(root,"engine"),engineCurrent:join(root,"engine","current"),plugins:join(root,"plugins"),config:join(root,"config.toml"),registry:join(root,"registry.json"),trust:join(root,"trust.json"),sessions:join(root,"state","sessions"),logs:join(root,"logs"),logFile:join(root,"logs","hookmux.log"),logSettings:join(root,"logs","settings.json"),health:join(root,"state","health.json"),grants:join(root,"state","grants"),cards:join(root,"state","cards"),flags:join(root,"flags.json"),sources:join(root,"sources.json"),installState:join(root,"install.json"),staging:join(root,"tmp")}}import{mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{dirname}from"node:path";function writeFileAtomic(file,data,mode=384){mkdirSync(dirname(file),{recursive:!0,mode:448});let temp=`${file}.${process.pid}.${Date.now()}.tmp`;try{writeFileSync(temp,data,{mode}),renameSync(temp,file)}catch(error){throw rmSync(temp,{force:!0}),error}}function readJson(file,fallback){try{return JSON.parse(readFileSync(file,"utf8"))}catch{return fallback}}export{homePaths,writeFileAtomic,readJson};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isInstalled}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,writeFlags}from"./chunk-IJHUIMJA.mjs";import{homePaths}from"./chunk-OYGOSD6V.mjs";async function setDisabled(argv,usage,disabled){let parsed=parseCommand(argv,{},usage,1);if(!parsed)return 0;let id=parsed.positionals[0];if(!id)throw new UsageError("name the plugin");let paths=homePaths();if(!isInstalled(paths,id))return say("fail",`plugin '${id}' is not installed`,"hookmux list"),1;let flags=readFlagsForUpdate(paths.flags),others=flags.disabled.filter(d=>d!==id);return writeFlags(paths.flags,{...flags,disabled:disabled?[...others,id]:others}),say("ok",`${id} ${disabled?"disabled":"enabled"}`),disabled||await syncAfterChange(paths)?0:1}export{setDisabled};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createInterface}from"node:readline/promises";function isInteractive(){return process.stdin.isTTY===!0}async function confirm(question,defaultYes){if(!isInteractive())return!1;let rl=createInterface({input:process.stdin,output:process.stdout});try{let answer=(await rl.question(`${question} ${defaultYes?"[Y/n]":"[y/N]"} `)).trim().toLowerCase();return answer===""?defaultYes:answer==="y"||answer==="yes"}finally{rl.close()}}export{isInteractive,confirm};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{clip}from"./chunk-BF25CRHJ.mjs";import{UsageError}from"./chunk-XPLEWNGF.mjs";import{ADAPTERS,getAdapter}from"./chunk-OXHAGFXG.mjs";import{listChecks,registerCheck}from"./chunk-ZNEBE4WO.mjs";var DEFAULT_HOST="claude-code",STUBBED_MODEL_ERROR="model check not run (stubbed; pass --live to call the model)",SCRIPT_NOT_RUN="script not run: plugin not promoted (use --run-scripts)";function adapterOrUsage(id){let adapter=getAdapter(id);if(!adapter)throw new UsageError(`unknown host '${id}'; known hosts: ${Object.keys(ADAPTERS).join(", ")}`);return adapter}function sampleEvent(adapter,event,prompt,cwd){let parsed=adapter.parse(event,adapter.sample(event,prompt),process.env);if(!parsed)throw new Error(`${adapter.id} could not parse its own ${event} sample`);return cwd?{...parsed,cwd}:parsed}function engineSettings(registry){return{deadlineMs:registry.settings.deadlineMs,blockRequiresRule:registry.settings.blockRequiresRule,contextBudget:registry.settings.contextBudget,runtime:{providers:registry.providers}}}function stubModelChecks(){for(let kind of listChecks())kind.modelBacked&®isterCheck({...kind,run:()=>({value:null,error:STUBBED_MODEL_ERROR})})}var unreviewed=new WeakSet,scriptGuardInstalled=!1;function withoutScripts(spec){installScriptGuard();let copy={...spec};return unreviewed.add(copy),copy}function installScriptGuard(){if(!scriptGuardInstalled){scriptGuardInstalled=!0;for(let kind of listChecks())kind.tier===1&®isterCheck({...kind,run:(spec,ctx)=>unreviewed.has(ctx.plugin)?{value:null,error:SCRIPT_NOT_RUN}:kind.run(spec,ctx)})}}function formatSignals(signals){return Object.entries(signals).map(([name,s])=>{let value=s.value===null?"unknown":String(s.value),extra=s.error?` (${clip(s.error,50)})`:s.evidence?` ("${clip(s.evidence,30)}")`:"";return`${name}=${value}${extra}`}).join(" ")}function outcomeStatus(outcome){return outcome==="fire"?"ok":outcome==="silent"?"info":outcome==="error"?"fail":"warn"}export{DEFAULT_HOST,STUBBED_MODEL_ERROR,SCRIPT_NOT_RUN,adapterOrUsage,sampleEvent,engineSettings,stubModelChecks,withoutScripts,formatSignals,outcomeStatus};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{readJson,writeFileAtomic}from"./chunk-OYGOSD6V.mjs";import{createHash}from"node:crypto";import{appendFileSync,closeSync,mkdirSync,openSync,renameSync,rmSync,statSync}from"node:fs";import{dirname}from"node:path";var LOG_ROTATE_BYTES=1024*1024,LOCK_STALE_MS=1e4,PROMPT_TEXT_CHARS=500;function readLogSettings(file){let s=readJson(file,{});return{enabled:s.enabled===!0,prompts:s.prompts===!0,...typeof s.until=="string"?{until:s.until}:{}}}function writeLogSettings(file,settings){writeFileAtomic(file,`${JSON.stringify(settings,null,2)}
|
|
2
|
+
`)}function loggingActive(settings,now=Date.now()){return settings.enabled?settings.until===void 0||Date.parse(settings.until)>now:!1}function shortHash(text){return createHash("sha256").update(text).digest("hex").slice(0,12)}function buildLogLine(run,settings,now=new Date){let e=run.hookEvent,record={ts:now.toISOString(),host:run.host,event:run.event,ms:Math.round(run.ms)};return e&&(record.origin=e.origin,e.sessionId&&(record.session=shortHash(e.sessionId)),e.prompt!==void 0&&(record.prompt={hash:shortHash(e.prompt),chars:e.prompt.length},settings.prompts&&(record.prompt.text=e.prompt.slice(0,PROMPT_TEXT_CHARS))),e.tool&&(record.tool=e.tool.canonicalName)),run.result&&(record.plugins=run.result.trace.map(t=>({id:t.id,outcome:t.outcome,ms:t.ms,...t.shadow?{shadow:!0}:{},...t.note?{note:t.note}:{},signals:Object.fromEntries(Object.entries(t.signals).map(([name,s])=>[name,s.error?`error: ${s.error}`:s.value]))})),record.out={bytes:run.outputBytes,context:run.result.context.map(c=>c.pluginId),...run.result.block?{block:run.result.block.pluginId}:{},...run.result.notices.length>0?{notices:run.result.notices.length}:{}}),run.errors.length>0&&(record.errors=run.errors),`${JSON.stringify(record)}
|
|
3
|
+
`}function appendLog(file,line){mkdirSync(dirname(file),{recursive:!0,mode:448}),logSize(file)+line.length>LOG_ROTATE_BYTES&&rotateLocked(file,line.length),appendFileSync(file,line,{mode:384})}function logSize(file){try{return statSync(file).size}catch{return 0}}function rotateLocked(file,adding){let lock=`${file}.lock`;if(takeLock(lock))try{logSize(file)+adding>LOG_ROTATE_BYTES&&renameSync(file,`${file}.1`)}catch{}finally{rmSync(lock,{force:!0})}}function takeLock(lock){for(let attempt=0;attempt<2;attempt++)try{return closeSync(openSync(lock,"wx",384)),!0}catch(error){if(error.code!=="EEXIST"||attempt>0||!isStale(lock))return!1;rmSync(lock,{force:!0})}return!1}function isStale(lock){try{return Date.now()-statSync(lock).mtimeMs>LOCK_STALE_MS}catch{return!0}}export{readLogSettings,writeLogSettings,loggingActive,buildLogLine,appendLog};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{loggingActive,readLogSettings}from"./chunk-UERSXYXZ.mjs";import{formatBytes}from"./chunk-BF25CRHJ.mjs";import{existsSync,readFileSync}from"node:fs";function readRecords(paths){let out=[];for(let file of[`${paths.logFile}.1`,paths.logFile])if(existsSync(file)){for(let line of readFileSync(file,"utf8").split(`
|
|
2
|
+
`))if(line.trim()!=="")try{out.push(JSON.parse(line))}catch{}}return out}import{existsSync as existsSync2,statSync}from"node:fs";function readLogStatus(paths){let settings=readLogSettings(paths.logSettings),size=f=>existsSync2(f)?statSync(f).size:0;return{enabled:settings.enabled,active:loggingActive(settings),prompts:settings.prompts,until:settings.until??null,file:paths.logFile,bytes:size(paths.logFile)+size(`${paths.logFile}.1`)}}function describeLogStatus(s){let state=s.active?"on":s.enabled?"off (expired)":"off",expiry=s.active&&s.until?`, until ${s.until}`:"";return`log ${state}${expiry}${s.prompts&&s.active?", with prompt text":""}, ${formatBytes(s.bytes)}`}export{readRecords,readLogStatus,describeLogStatus};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{parseArgs}from"node:util";var UsageError=class extends Error{},HELP={help:{type:"boolean",short:"h"}};function parseCommand(argv,options,usage,maxPositionals=0){let parsed;try{parsed=parseArgs({args:argv,options:{...options,...HELP},allowPositionals:!0,strict:!0})}catch(error){throw new UsageError(error.message)}if(parsed.values.help===!0)return console.log(usage),null;let extra=parsed.positionals[maxPositionals];if(extra!==void 0)throw new UsageError(`unexpected argument '${extra}'`);return parsed}function positiveInt(value,flag,fallback){if(value===void 0)return fallback;let n=Number(value);if(!Number.isInteger(n)||n<=0)throw new UsageError(`${flag} must be a positive whole number`);return n}export{UsageError,parseCommand,positiveInt};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{PLUGIN_ID}from"./chunk-ZNEBE4WO.mjs";import{readJson,writeFileAtomic}from"./chunk-OYGOSD6V.mjs";var MAX_ENTRIES=50,MAX_MESSAGE_CHARS=300;function readHealth(file){let h=readJson(file,{entries:[]});return Array.isArray(h.entries)?h:{entries:[]}}function recordFailures(file,failures,now=new Date){if(failures.length===0)return;let health=readHealth(file),at=now.toISOString();for(let f of failures){let message=f.message.slice(0,MAX_MESSAGE_CHARS),existing=health.entries.find(e=>e.key===f.key);existing?(existing.count++,existing.lastAt=at,existing.message=message):health.entries.push({key:f.key,message,count:1,firstAt:at,lastAt:at})}health.entries.sort((a,b)=>b.lastAt.localeCompare(a.lastAt)),health.entries=health.entries.slice(0,MAX_ENTRIES),writeFileAtomic(file,`${JSON.stringify(health,null,2)}
|
|
2
|
+
`)}import{createHash}from"node:crypto";import{closeSync,mkdirSync,openSync,readdirSync,rmSync,statSync}from"node:fs";import{join}from"node:path";var SESSION_TTL_MS=10080*60*1e3;function sessionDir(dir,sessionId){return join(dir,createHash("sha256").update(sessionId).digest("hex").slice(0,32))}function readFired(dir,sessionId){if(!sessionId)return new Set;try{return new Set(readdirSync(sessionDir(dir,sessionId)).filter(name=>PLUGIN_ID.test(name)))}catch{return new Set}}function recordFired(dir,sessionId,ids){if(!sessionId||ids.length===0)return;let session=sessionDir(dir,sessionId);mkdirSync(session,{recursive:!0,mode:448});for(let id of ids)if(PLUGIN_ID.test(id))try{closeSync(openSync(join(session,id),"wx",384))}catch(error){if(error.code!=="EEXIST")throw error}}function pruneSessions(dir,now=Date.now()){let removed=0;try{for(let name of readdirSync(dir)){let entry=join(dir,name);now-statSync(entry).mtimeMs>SESSION_TTL_MS&&(rmSync(entry,{recursive:!0,force:!0}),removed++)}}catch{}return removed}export{readHealth,recordFailures,readFired,recordFired,pruneSessions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{homePaths}from"./chunk-OYGOSD6V.mjs";var kinds=new Map;function registerCheck(kind){kinds.set(kind.kind,kind)}function getCheck(kind){return kinds.get(kind)}function listChecks(){return[...kinds.values()].sort((a,b)=>a.kind.localeCompare(b.kind))}var tracked=new Set,exitHookInstalled=!1;function killGroup(pgid){try{process.kill(-pgid,"SIGKILL")}catch{}}function trackGroup(pgid){exitHookInstalled||(exitHookInstalled=!0,process.on("exit",killTrackedGroups)),tracked.add(pgid)}function untrackGroup(pgid){tracked.delete(pgid)}function killTrackedGroups(){for(let pgid of tracked)killGroup(pgid);tracked.clear()}var CANONICAL_EVENTS=["prompt.submit","session.start","tool.before","tool.after"],PLUGIN_ID=/^[a-z0-9][a-z0-9-]{0,63}$/,PHASES=["guard","route","enrich","observe"];function emptyResult(){return{context:[],notices:[],trace:[],errors:[]}}import{readFileSync as readFileSync2,realpathSync,statSync}from"node:fs";import{isAbsolute,join as join2,relative,sep}from"node:path";import{createHash,randomBytes}from"node:crypto";import{chmodSync,lstatSync,mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{join}from"node:path";var PRIVATE_MODE=448,MODE_BITS=4095;function sha256Hex(bytes){return createHash("sha256").update(bytes).digest("hex")}function cachedScript(bytes,sha256,root=homePaths().root){let cache=join(root,"cache"),dir=join(cache,"scripts");mkdirSync(root,{recursive:!0,mode:PRIVATE_MODE}),ensurePrivateDir(cache),ensurePrivateDir(dir);let file=join(dir,sha256);return isTrustedCopy(file,sha256)||replaceCopy(dir,file,bytes),file}function currentUid(){return process.getuid?.()}function ensurePrivateDir(dir){try{mkdirSync(dir,{mode:PRIVATE_MODE})}catch(error){if(error.code!=="EEXIST")throw error}let stat=lstatSync(dir),uid=currentUid();if(!stat.isDirectory()||uid!==void 0&&stat.uid!==uid)throw new Error(`${dir} is not a folder owned by you; remove it so hookmux can recreate it`);(stat.mode&MODE_BITS)!==PRIVATE_MODE&&chmodSync(dir,PRIVATE_MODE)}function isTrustedCopy(file,sha256){try{let stat=lstatSync(file),uid=currentUid();return!stat.isFile()||uid!==void 0&&stat.uid!==uid||(stat.mode&MODE_BITS)!==PRIVATE_MODE?!1:sha256Hex(readFileSync(file))===sha256}catch{return!1}}function replaceCopy(dir,file,bytes){let temp=join(dir,`.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);try{writeFileSync(temp,bytes,{mode:PRIVATE_MODE,flag:"wx"}),chmodSync(temp,PRIVATE_MODE),renameSync(temp,file)}catch(error){throw rmSync(temp,{force:!0}),error}}import{spawn}from"node:child_process";var MAX_STDOUT_BYTES=64*1024,STDERR_KEEP_CHARS=300,PIPE_GRACE_MS=50;function collectOutput(child,onOverflow){let chunks=[],stdoutBytes=0,stderr="";return child.stdout?.on("data",chunk=>{stdoutBytes+=chunk.length,stdoutBytes>MAX_STDOUT_BYTES?onOverflow():chunks.push(chunk)}),child.stderr?.on("data",chunk=>{stderr.length<STDERR_KEEP_CHARS&&(stderr=(stderr+chunk.toString("utf8")).slice(0,STDERR_KEEP_CHARS))}),{stdout:()=>Buffer.concat(chunks).toString("utf8"),stderr:()=>stderr}}function runProcess(run){return new Promise(done=>{let child=spawnScript(run);typeof child=="string"?done({exitCode:null,stdout:"",stderr:"",failure:child}):supervise(child,run,done)})}function spawnScript(run){try{return spawn(run.file,run.args,{cwd:run.cwd,env:run.env,stdio:"pipe",detached:!0})}catch(error){return`cannot run script: ${error.message}`}}function groupKiller(pgid){if(pgid===void 0)return()=>{};trackGroup(pgid);let killed=!1;return()=>{killed||(killed=!0,untrackGroup(pgid),killGroup(pgid))}}function supervise(child,run,done){let killScriptGroup=groupKiller(child.pid),failure,settled=!1,exitCode=null,stop=reason=>{failure??=reason,killScriptGroup()},onAbort=()=>stop("deadline reached"),timer=setTimeout(()=>stop(`timed out after ${run.budgetMs} ms`),run.budgetMs);run.signal.addEventListener("abort",onAbort,{once:!0});let output=collectOutput(child,()=>stop(`stdout over ${MAX_STDOUT_BYTES/1024} KiB`)),finish=()=>{settled||(settled=!0,clearTimeout(timer),run.signal.removeEventListener("abort",onAbort),killScriptGroup(),child.stdout?.destroy(),child.stderr?.destroy(),done({exitCode,stdout:output.stdout(),stderr:output.stderr(),...failure?{failure}:{}}))};child.stdin?.on("error",()=>{}),child.on("error",error=>{failure??=`cannot run script: ${error.code??error.message}`,finish()}),child.on("exit",code=>{exitCode=code,killScriptGroup(),setTimeout(finish,PIPE_GRACE_MS)}),child.on("close",finish),child.stdin?.end(run.stdin)}function hasNestedRepetition(source){let stack=[{repeats:!1}],i=0;for(;i<source.length;){let ch=source[i],top=stack[stack.length-1];if(ch==="\\")i=afterAtom(source,i+2,top);else if(ch==="[")i=afterAtom(source,skipClass(source,i+1),top);else if(ch==="(")stack.push({repeats:!1}),i=skipGroupPrefix(source,i+1);else if(ch===")"){let inner=stack.length>1?stack.pop():{repeats:!1},parent=stack[stack.length-1],quantifier=readQuantifier(source,i+1);if(quantifier.unbounded&&inner.repeats)return!0;parent.repeats||=inner.repeats||quantifier.unbounded,i=quantifier.end}else i=afterAtom(source,i+1,top)}return!1}function afterAtom(source,end,frame){let quantifier=readQuantifier(source,end);return quantifier.unbounded&&(frame.repeats=!0),quantifier.end}function readQuantifier(source,at){let ch=source[at],unbounded=!1,end=at;if(ch==="*"||ch==="+")unbounded=!0,end=at+1;else if(ch==="?")end=at+1;else if(ch==="{"){let match=/^\{(\d+)(,(\d*))?\}/.exec(source.slice(at));match&&(unbounded=match[2]!==void 0&&match[3]==="",end=at+match[0].length)}return end>at&&source[end]==="?"&&end++,{unbounded,end}}function skipClass(source,at){let i=at;for(source[i]==="]"&&i++;i<source.length&&source[i]!=="]";)i+=source[i]==="\\"?2:1;return i+1}function skipGroupPrefix(source,at){if(source[at]!=="?")return at;let match=/^\?(?::|=|!|<=|<!|<[A-Za-z_$][\w$]*>)/.exec(source.slice(at));return match?at+match[0].length:at+1}var MAX_MATCH_CHARS=8e3,MAX_PATTERN_CHARS=300,MAX_PATTERNS=200;function readField(event,field){let path=field??"prompt",value;if(path==="prompt")value=event.prompt;else if(path==="cwd")value=event.cwd;else if(path==="tool.name")value=event.tool?.canonicalName;else if(path==="tool.input")value=event.tool?.input;else if(path.startsWith("tool.input."))value=dig(event.tool?.input,path.slice(11).split("."));else return null;if(value==null)return null;let text=typeof value=="string"?value:safeJson(value);return text.length>MAX_MATCH_CHARS?text.slice(0,MAX_MATCH_CHARS):text}function isKnownField(field){return field===void 0?!0:typeof field!="string"?!1:["prompt","cwd","tool.name","tool.input"].includes(field)||/^tool\.input(\.[A-Za-z0-9_-]+)+$/.test(field)}function dig(value,keys){let current=value;for(let key of keys){if(current===null||typeof current!="object")return;current=current[key]}return current}function safeJson(value){try{return JSON.stringify(value)??""}catch{return""}}function compilePatterns(raw,flags,label,problems){if(!Array.isArray(raw)||raw.length===0)return problems.push(`${label} must be a non-empty list of patterns`),[];raw.length>MAX_PATTERNS&&problems.push(`${label} has more than ${MAX_PATTERNS} patterns`);let out=[];for(let source of raw){if(typeof source!="string"||source.length===0){problems.push(`${label} contains a non-string or empty pattern`);continue}if(source.length>MAX_PATTERN_CHARS){problems.push(`${label} pattern longer than ${MAX_PATTERN_CHARS} chars`);continue}if(hasNestedRepetition(source)){problems.push(`${label} pattern /${source}/ repeats a group that already repeats (like (a+)+), which can hang on some input; rewrite it without the nesting`);continue}try{out.push(new RegExp(source,flags))}catch(error){problems.push(`${label} pattern /${source}/ is invalid: ${error.message}`)}}return out}function regexFlags(raw,problems){return raw===void 0?"iu":typeof raw!="string"||!/^[imsu]*$/.test(raw)?(problems.push("flags may only contain i, m, s, u"),"iu"):raw}function clip(text,max=80){return text.length>max?`${text.slice(0,max-1)}\u2026`:text}var DEFAULT_TIMEOUT_MS=1e3,MAX_TIMEOUT_MS=1e4,ENV_PASSTHROUGH=["PATH","HOME","LANG","LC_ALL","TMPDIR"],ENV_NAME=/^[A-Za-z_][A-Za-z0-9_]*$/,RESERVED_ENV_PREFIX="HOOKMUX_",MAX_ENV_NAMES=32,DEFAULT_EVIDENCE_CHARS=80,MAX_EVIDENCE_CHARS=4e3;function unknown(error){return{value:null,error}}function commandProblems(command){return typeof command!="string"||command===""?["command must be a path inside the plugin folder"]:isAbsolute(command)||/^[\\/]/.test(command)?["command must be relative to the plugin folder"]:command.split(/[\\/]/).includes("..")?["command may not contain '..'"]:[]}function optionProblems(spec){let problems=commandProblems(spec.command);spec.args!==void 0&&(!Array.isArray(spec.args)||spec.args.some(a=>typeof a!="string"))&&problems.push("args must be a list of strings");let timeout=spec.timeout_ms;timeout!==void 0&&(!Number.isInteger(timeout)||timeout<1||timeout>MAX_TIMEOUT_MS)&&problems.push(`timeout_ms must be a whole number from 1 to ${MAX_TIMEOUT_MS}`),spec.needs_raw!==void 0&&typeof spec.needs_raw!="boolean"&&problems.push("needs_raw must be true or false"),spec.output!==void 0&&spec.output!=="bool"&&spec.output!=="score"&&problems.push("output must be 'bool' or 'score'"),problems.push(...envProblems(spec.env));let chars=spec.evidence_chars;return chars!==void 0&&(!Number.isInteger(chars)||chars<1||chars>MAX_EVIDENCE_CHARS)&&problems.push(`evidence_chars must be a whole number from 1 to ${MAX_EVIDENCE_CHARS}`),problems}function envProblems(env){return env===void 0?[]:!Array.isArray(env)||env.length>MAX_ENV_NAMES?[`env must be a list of at most ${MAX_ENV_NAMES} variable names`]:env.flatMap(name=>typeof name!="string"||!ENV_NAME.test(name)?[`env name ${JSON.stringify(name)} is not valid`]:name.startsWith(RESERVED_ENV_PREFIX)?[`env may not pass ${name}: ${RESERVED_ENV_PREFIX}* is set by hookmux`]:[])}function declaredEnv(spec){return Array.isArray(spec.env)?spec.env.filter(n=>typeof n=="string"):[]}function scriptEvidenceLimit(spec){return spec.evidence_chars??DEFAULT_EVIDENCE_CHARS}function resolveScript(ctx,command){let dir,file;try{dir=realpathSync(ctx.plugin.dir),file=realpathSync(join2(ctx.plugin.dir,command))}catch{return{error:"script not found"}}let rel=relative(dir,file);if(rel===""||rel===".."||rel.startsWith(`..${sep}`)||isAbsolute(rel))return{error:"script resolves outside the plugin folder"};if(!statSync(file).isFile())return{error:"script is not a regular file"};let expected=ctx.plugin.fileHashes?.[rel.replaceAll("\\","/")],bytes=readFileSync2(file),actual=sha256Hex(bytes);if(expected===void 0||expected!==actual)return{error:"script changed since promote"};try{return{file:cachedScript(bytes,actual)}}catch(error){return{error:`cannot prepare script: ${error.message}`}}}function checkName(spec,ctx){return Object.entries(ctx.plugin.checks).find(([,s])=>s===spec)?.[0]??""}function stdinPayload(spec,ctx){let{name,cwd,sessionId,origin,prompt,tool,source}=ctx.event;return JSON.stringify({event:{name,cwd,sessionId,origin,prompt,tool,source},host:ctx.event.host,params:ctx.plugin.params,check:checkName(spec,ctx),...spec.needs_raw===!0?{raw:ctx.event.raw}:{}})}function scriptEnv(spec,ctx){let env={};for(let key of[...ENV_PASSTHROUGH,...declaredEnv(spec)]){let value=process.env[key];value!==void 0&&(env[key]=value)}return env.HOOKMUX_PLUGIN_DIR=ctx.plugin.dir,env.HOOKMUX_HOST=ctx.event.host.id,env.HOOKMUX_EVENT=ctx.event.name,env}function scriptCwd(ctx){try{if(statSync(ctx.event.cwd).isDirectory())return ctx.event.cwd}catch{}return ctx.plugin.dir}function withStderr(reason,stderr){let detail=stderr.trim();return detail?`${reason}: ${detail}`:reason}function parseScriptOutput(text,output,evidenceChars=DEFAULT_EVIDENCE_CHARS){let data;try{data=JSON.parse(text)}catch{return unknown("script printed invalid JSON")}if(data===null||typeof data!="object"||!("value"in data))return unknown("script JSON needs a value field");let{value,evidence}=data,extra=typeof evidence=="string"?{evidence:clip(evidence,evidenceChars)}:{};return value===null?{value:null,...extra}:output==="bool"?typeof value=="boolean"?{value,...extra}:unknown("bool script must return true, false or null"):typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=1?{value,...extra}:unknown("score script must return a number from 0 to 1 or null")}function interpretResult(result,output,evidenceChars=DEFAULT_EVIDENCE_CHARS){if(result.failure)return unknown(withStderr(result.failure,result.stderr));if(result.exitCode!==0&&result.exitCode!==1)return unknown(withStderr(`script exited with ${result.exitCode}`,result.stderr));let text=result.stdout.trim();return text!==""?parseScriptOutput(text,output,evidenceChars):output==="score"?unknown("score script printed nothing"):{value:result.exitCode===0}}registerCheck({kind:"script",outputOf:spec=>spec.output==="score"?"score":"bool",summary:"Runs an executable from the plugin folder; it reads the event as JSON on stdin and prints its value.",options:{command:"path relative to the plugin folder, executable with a shebang; a private copy runs, so find sibling files through $HOOKMUX_PLUGIN_DIR, not $0",args:"list of string arguments",timeout_ms:`default ${DEFAULT_TIMEOUT_MS}, at most ${MAX_TIMEOUT_MS}`,needs_raw:"default false; true also sends the host's original payload",output:'"bool" (default) or "score"',env:`extra environment variable names passed through when set (at most ${MAX_ENV_NAMES}, no HOOKMUX_*); each is a capability that promote approves`,evidence_chars:`characters of evidence kept for templates; default ${DEFAULT_EVIDENCE_CHARS}, at most ${MAX_EVIDENCE_CHARS}. Limits above ${DEFAULT_EVIDENCE_CHARS} need approval`},tier:1,output:"bool",modelBacked:!1,validate:optionProblems,async run(spec,ctx){let script=resolveScript(ctx,spec.command);if("error"in script)return unknown(script.error);let budgetMs=Math.floor(Math.min(spec.timeout_ms??DEFAULT_TIMEOUT_MS,ctx.remainingMs()));if(ctx.signal.aborted||budgetMs<=0)return unknown("deadline reached");let result=await runProcess({file:script.file,args:spec.args??[],cwd:scriptCwd(ctx),env:scriptEnv(spec,ctx),stdin:stdinPayload(spec,ctx),budgetMs,signal:ctx.signal});return interpretResult(result,spec.output==="score"?"score":"bool",scriptEvidenceLimit(spec))}});var TOKEN_RE=/\s*(?:(\()|(\))|(<=|>=|==|!=|<|>)|(-?\d+(?:\.\d+)?)|([A-Za-z_][A-Za-z0-9_]*))/y,ExprError=class extends Error{};function parseExpr(source){if(source.length>2e3)throw new ExprError("expression longer than 2000 chars");let tokens=tokenize(source),pos=0,peek=()=>tokens[pos],next=()=>tokens[pos++],parseOr=()=>{let left=parseAnd();for(;peek()==="or";)next(),left={t:"or",l:left,r:parseAnd()};return left},parseAnd=()=>{let left=parseNot();for(;peek()==="and";)next(),left={t:"and",l:left,r:parseNot()};return left},parseNot=()=>peek()==="not"?(next(),{t:"not",e:parseNot()}):parseCmp(),parseCmp=()=>{let atom=parseAtom(),op=peek();if(op&&isCmpOp(op)){if(next(),atom.t!=="ref")throw new ExprError(`'${op}' needs a check name on its left`);let num=next();if(num===void 0||!/^-?\d/.test(num))throw new ExprError(`'${op}' needs a number on its right`);return{t:"cmp",name:atom.name,op,n:Number(num)}}return atom},parseAtom=()=>{let tok=next();if(tok===void 0)throw new ExprError("expression ends too early");if(tok==="("){let inner=parseOr();if(next()!==")")throw new ExprError("missing ')'");return inner}if(tok==="true"||tok==="false")return{t:"lit",v:tok==="true"};if(/^[A-Za-z_]/.test(tok)&&!KEYWORDS.has(tok))return{t:"ref",name:tok};throw new ExprError(`unexpected '${tok}'`)},expr=parseOr();if(pos!==tokens.length)throw new ExprError(`unexpected '${tokens[pos]}'`);return expr}var KEYWORDS=new Set(["and","or","not","true","false"]);function isCmpOp(tok){return tok==="<"||tok==="<="||tok===">"||tok===">="||tok==="=="||tok==="!="}function tokenize(source){let tokens=[];TOKEN_RE.lastIndex=0;let index=0;for(;index<source.length&&!/^\s*$/.test(source.slice(index));){TOKEN_RE.lastIndex=index;let m=TOKEN_RE.exec(source);if(!m)throw new ExprError(`cannot read expression at '${source.slice(index,index+12)}'`);tokens.push(m[1]??m[2]??m[3]??m[4]??m[5]),index=TOKEN_RE.lastIndex}if(tokens.length===0)throw new ExprError("empty expression");return tokens}function exprRefs(expr,out=new Set){switch(expr.t){case"ref":case"cmp":out.add(expr.name);break;case"not":exprRefs(expr.e,out);break;case"and":case"or":exprRefs(expr.l,out),exprRefs(expr.r,out);break}return out}function evalExpr(expr,signals){switch(expr.t){case"lit":return expr.v;case"ref":{let v=signals[expr.name]?.value;return typeof v=="boolean"?v:null}case"cmp":{let v=signals[expr.name]?.value;return typeof v=="number"?compare(v,expr.op,expr.n):null}case"not":{let v=evalExpr(expr.e,signals);return v===null?null:!v}case"and":{let l=evalExpr(expr.l,signals);if(l===!1)return!1;let r=evalExpr(expr.r,signals);return r===!1?!1:l===!0&&r===!0?!0:null}case"or":{let l=evalExpr(expr.l,signals);if(l===!0)return!0;let r=evalExpr(expr.r,signals);return r===!0?!0:l===!1&&r===!1?!1:null}}}function compare(v,op,n){switch(op){case"<":return v<n;case"<=":return v<=n;case">":return v>n;case">=":return v>=n;case"==":return v===n;case"!=":return v!==n}}export{registerCheck,getCheck,listChecks,MAX_MATCH_CHARS,readField,isKnownField,compilePatterns,regexFlags,clip,killTrackedGroups,DEFAULT_EVIDENCE_CHARS,declaredEnv,scriptEvidenceLimit,CANONICAL_EVENTS,PLUGIN_ID,PHASES,emptyResult,ExprError,parseExpr,exprRefs,evalExpr};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{setDisabled}from"./chunk-QTY23VNU.mjs";import"./chunk-CSXS5D2F.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";var usage=`Usage: hookmux disable <id>
|
|
2
|
+
|
|
3
|
+
Switches a plugin off without deleting it. Undo with 'hookmux enable <id>'.`;function run(argv){return setDisabled(argv,usage,!0)}export{run,usage};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{describeLogStatus,readLogStatus,readRecords}from"./chunk-WZSNBZ6D.mjs";import{pruneSessions,readHealth}from"./chunk-ZDCAHPWY.mjs";import"./chunk-UERSXYXZ.mjs";import{engineStatus,installEngine,readLauncherInfo,rerecordNode,stableNodePath,writeLauncher}from"./chunk-L3BSVLQG.mjs";import{allAdapters,neededEvents,syncHosts}from"./chunk-G6SJQTFF.mjs";import{printJson,say}from"./chunk-BF25CRHJ.mjs";import{parseCommand}from"./chunk-XPLEWNGF.mjs";import{compileRegistry}from"./chunk-IJHUIMJA.mjs";import"./chunk-K73ZPBFM.mjs";import{listHubEntries,packageLayout}from"./chunk-OXHAGFXG.mjs";import"./chunk-2ZCM3JZR.mjs";import"./chunk-7Z3AMI24.mjs";import"./chunk-ZNEBE4WO.mjs";import{homePaths}from"./chunk-OYGOSD6V.mjs";import{VERSION}from"./chunk-AHPMRYYF.mjs";import{existsSync as existsSync2}from"node:fs";import{accessSync,constants,existsSync,readdirSync}from"node:fs";var MIN_NODE_MAJOR=22,HEALTH_SHOWN=5,MANY_SESSIONS=1e3,MIN_RUNS_FOR_TIMING=20,SLOWEST_SHOWN=3,P95=.95;function checkNode(){return Number(process.versions.node.split(".")[0])>=MIN_NODE_MAJOR?[{id:"node",status:"ok",title:`Node ${process.versions.node}`}]:[{id:"node",status:"fail",title:`Node ${process.versions.node} is too old`,fix:`install Node ${MIN_NODE_MAJOR} or later`}]}function checkEngine(paths){let s=engineStatus(paths);return s.ok?s.version!==VERSION?[{id:"engine",status:"warn",title:`engine ${s.version} differs from this CLI (${VERSION})`,fix:"hookmux init"}]:[{id:"engine",status:"ok",title:`engine ${s.version}`}]:[{id:"engine",status:"fail",title:s.problem??"engine missing",fix:"hookmux doctor --fix"}]}function checkLauncher(paths){let l=readLauncherInfo(paths);if(!l.exists)return[{id:"launcher",status:"fail",title:`no launcher at ${paths.launcher}`,fix:"hookmux init"}];let out=[];return l.executable||out.push({id:"launcher",status:"fail",title:"launcher is not executable",fix:"hookmux doctor --fix"}),(!l.node||!isExecutable(l.node))&&out.push({id:"launcher.node",status:"fail",title:`launcher's Node '${l.node??"?"}' is missing`,fix:"hookmux doctor --fix"}),l.root!==paths.root&&out.push({id:"launcher.root",status:"fail",title:`launcher points at home '${l.root??"?"}'`,fix:"hookmux init"}),out.length>0?out:[{id:"launcher",status:"ok",title:`launcher (node ${l.node})`}]}function isExecutable(file){try{return accessSync(file,constants.X_OK),!0}catch{return!1}}function checkRegistry(registry,paths){let out=registry.problems.map(p=>({id:"config",status:"fail",title:p,fix:`edit ${paths.config}`}));for(let p of registry.plugins){p.status==="invalid"?out.push({id:`plugin.${p.id}`,status:"fail",title:`${p.id} is invalid: ${p.problem}`,fix:`hookmux validate ${paths.plugins}/${p.id}`}):p.status==="untrusted"&&out.push({id:`plugin.${p.id}`,status:"warn",title:`${p.id} is untrusted: ${p.problem}`,fix:`hookmux promote ${p.id}`});for(let w of p.warnings)out.push({id:`plugin.${p.id}`,status:"warn",title:`${p.id}: ${w}`})}let active=registry.plugins.filter(p=>p.status==="active").length;return out.unshift({id:"plugins",status:"ok",title:`${registry.plugins.length} plugin(s), ${active} active`}),out}function checkHealth(paths){let entries=readHealth(paths.health).entries;if(entries.length===0)return[{id:"health",status:"ok",title:"no recorded hook failures"}];let out=entries.slice(0,HEALTH_SHOWN).map(e=>({id:`health.${e.key}`,status:"warn",title:`${e.key} failed ${e.count}x, last ${e.lastAt}: ${e.message}`,fix:"hookmux log on --for 30m, then hookmux log show --errors"}));return entries.length>HEALTH_SHOWN&&out.push({id:"health",status:"info",title:`${entries.length-HEALTH_SHOWN} more recorded failure(s)`}),out}function checkLog(paths){return[{id:"log",status:"info",title:describeLogStatus(readLogStatus(paths))}]}function slowestPlugins(records,top=SLOWEST_SHOWN){if(records.length<MIN_RUNS_FOR_TIMING)return[];let samples=new Map;for(let r of records)for(let p of r.plugins??[]){if(typeof p.ms!="number")continue;let event=String(r.event??"?"),entry=samples.get(`${p.id}\0${event}`)??{id:p.id,event,times:[]};entry.times.push(p.ms),samples.set(`${p.id}\0${event}`,entry)}return[...samples.values()].map(({id,event,times})=>(times.sort((a,b)=>a-b),{id,event,p95Ms:times[Math.ceil(P95*times.length)-1]})).sort((a,b)=>b.p95Ms-a.p95Ms||a.id.localeCompare(b.id)).slice(0,top)}function checkTiming(paths){if(!readLogStatus(paths).active)return[];let slowest=slowestPlugins(readRecords(paths));return slowest.length===0?[]:[{id:"timing",status:"info",title:`slowest: ${slowest.map(t=>`${t.id} p95 ${t.p95Ms} ms on ${t.event}`).join(", ")}`}]}function checkSessions(paths){let count=existsSync(paths.sessions)?readdirSync(paths.sessions).length:0;return count>MANY_SESSIONS?[{id:"sessions",status:"warn",title:`${count} session files`,fix:"hookmux doctor --fix"}]:[{id:"sessions",status:"info",title:`${count} session file(s)`}]}import{execFile}from"node:child_process";import{randomUUID}from"node:crypto";import{promisify}from"node:util";var runFile=promisify(execFile),LIVE_TIMEOUT_MS=1e4;async function checkHosts(paths,needed){let out=[];for(let adapter of allAdapters())out.push(...await checkHost(adapter,paths,needed));return out.length===0&&out.push({id:"hosts",status:"warn",title:"no agent client detected or wired",fix:"hookmux init --host <id>"}),out}async function checkHost(adapter,paths,needed){let id=`host.${adapter.id}`,file=adapter.config.file();try{adapter.config.install({launcher:paths.launcher,events:[],timeoutSec:1})}catch(error){return adapter.config.detect()?[{id,status:"fail",title:`${adapter.name}: ${error.message}`,fix:`fix ${file}, then hookmux sync`}]:[]}let installed=adapter.config.installed(paths.launcher);if(installed.length===0)return adapter.config.detect()?[{id,status:"info",title:`${adapter.name}: detected, not wired`,fix:`hookmux init --host ${adapter.id}`}]:[];let out=[],missing=needed.filter(e=>adapter.nativeEvents[e]!==null).filter(e=>!installed.includes(e));return missing.length>0?out.push({id,status:"fail",title:`${adapter.name}: no hub entry for ${missing.join(", ")}`,fix:"hookmux sync"}):out.push({id,status:"ok",title:`${adapter.name}: hub entries for ${installed.join(", ")} (${file})`}),out.push(await liveRun(adapter,paths)),out.push(...await HOST_PROBES[adapter.id]?.(adapter,paths,installed)??[]),out}async function liveRun(adapter,paths){let id=`host.${adapter.id}.run`,payload=adapter.sample("prompt.submit");"session_id"in payload&&(payload.session_id=`hookmux-doctor-${randomUUID()}`);let{HOOKMUX_DISABLE:_off,...env}=process.env,started=performance.now();try{let pending=runFile(paths.launcher,["--host",adapter.id,"--event","prompt.submit"],{timeout:LIVE_TIMEOUT_MS,env});pending.child.stdin?.on("error",()=>{}),pending.child.stdin?.end(JSON.stringify(payload));let{stdout}=await pending,ms=Math.round(performance.now()-started);return stdout.trim()!==""&&JSON.parse(stdout),{id,status:"ok",title:`${adapter.name}: launcher answered in ${ms} ms (${stdout.trim()?"JSON":"empty"} output)`}}catch(error){let e=error,why=e.killed?`no answer within ${LIVE_TIMEOUT_MS/1e3} s`:e instanceof SyntaxError?"stdout is not valid JSON":e.message;return{id,status:"fail",title:`${adapter.name}: launcher run failed: ${why}`,fix:'hookmux log on --for 30m, then hookmux explain "test"'}}}var HOST_PROBES={codex:codexApprovals};async function codexApprovals(adapter,paths,installed){let id=`host.${adapter.id}.approval`,fix="hookmux sync";try{let{entries,missing}=await listHubEntries({launcher:paths.launcher,hooksFile:adapter.config.file(),events:installed,env:process.env,codex:process.env.HOOKMUX_CODEX||"codex"}),unapproved=[...entries.filter(e=>e.trustStatus!=="trusted").map(e=>`${e.key} (${e.trustStatus})`),...missing.map(e=>`${e} (not listed by Codex)`)];return unapproved.length>0?[{id,status:"warn",title:`${adapter.name} has not approved: ${unapproved.join(", ")}`,fix}]:[{id,status:"ok",title:`${adapter.name}: ${entries.length} hub entries approved`}]}catch(error){return[{id,status:"warn",title:`${adapter.name}: could not read hook approvals (${error.message})`,fix:"open Codex, run /hooks and check the hookmux entries"}]}}var usage=`Usage: hookmux doctor [--json] [--fix]
|
|
2
|
+
|
|
3
|
+
Checks Node, the engine, the launcher, every wired host (including a real
|
|
4
|
+
launcher run), plugins, recorded failures, the log and session state.
|
|
5
|
+
|
|
6
|
+
--fix re-record the launcher's Node path, repair the engine link,
|
|
7
|
+
re-sync hub entries and prune old sessions, then check`,MAX_NEXT=3;async function run(argv){let parsed=parseCommand(argv,{json:{type:"boolean"},fix:{type:"boolean"}},usage);if(!parsed)return 0;let paths=homePaths(),fixed=parsed.values.fix?applyFixes(paths):[],registry=compileRegistry(paths),checks=[...checkNode(),...checkEngine(paths),...checkLauncher(paths),...await checkHosts(paths,neededEvents(registry)),...checkRegistry(registry,paths),...checkHealth(paths),...checkLog(paths),...checkTiming(paths),...checkSessions(paths)],problems=checks.filter(c=>c.status==="fail").length,warnings=checks.filter(c=>c.status==="warn").length,next=[...new Set([...checks.filter(c=>c.status==="fail"),...checks.filter(c=>c.status==="warn")].map(c=>c.fix).filter(f=>f!==void 0))].slice(0,MAX_NEXT),verdict=problems>0?`${problems} problem(s), ${warnings} warning(s)`:warnings>0?`working, with ${warnings} warning(s)`:"hookmux is healthy";if(parsed.values.json)return printJson({ok:problems===0,version:VERSION,home:paths.root,fixed,checks,verdict,next}),problems>0?1:0;for(let f of fixed)say(f.ok?"ok":"fail",`fix: ${f.action}${f.detail?` (${f.detail})`:""}`);for(let c of checks)say(c.status,c.title,c.status==="fail"||c.status==="warn"?c.fix:void 0);return console.log(""),say(problems>0?"fail":warnings>0?"warn":"ok",verdict),next.length>0&&console.log(`next: ${next.join("; ")}`),problems>0?1:0}function applyFixes(paths){let results=[],attempt=(action,fn)=>{try{let detail=fn();results.push({action,ok:!0,...detail?{detail}:{}})}catch(error){results.push({action,ok:!1,detail:error.message})}};return engineStatus(paths).ok||attempt("re-copied the engine",()=>installEngine(paths,packageLayout().dist,VERSION).version),attempt("re-recorded the launcher's Node path",()=>(existsSync2(paths.launcher)?rerecordNode(paths):writeLauncher(paths,packageLayout().launcherTemplate),stableNodePath())),attempt("re-synced hub entries",()=>{let{results:hosts}=syncHosts(paths),failed=hosts.filter(h=>h.error);if(failed.length>0)throw new Error(failed.map(h=>`${h.adapter.id}: ${h.error}`).join("; "));let added=hosts.flatMap(h=>h.change?.added.map(e=>`${h.adapter.id} ${e}`)??[]);if(added.length>0)return`added ${added.join(", ")}`;let updated=hosts.filter(h=>h.change?.changed).map(h=>h.adapter.id);return updated.length>0?`updated ${updated.join(", ")}`:"nothing missing"}),attempt("pruned old sessions",()=>`${pruneSessions(paths.sessions)} removed`),results}export{run,usage};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{setDisabled}from"./chunk-QTY23VNU.mjs";import"./chunk-CSXS5D2F.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";var usage=`Usage: hookmux enable <id>
|
|
2
|
+
|
|
3
|
+
Turns a plugin switched off with 'hookmux disable' back on. It still needs to
|
|
4
|
+
be promoted to run.`;function run(argv){return setDisabled(argv,usage,!1)}export{run,usage};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{runEngine}from"./chunk-F3USS665.mjs";import{DEFAULT_HOST,adapterOrUsage,engineSettings,formatSignals,outcomeStatus,sampleEvent,withoutScripts}from"./chunk-SXIEWTYT.mjs";import{inspectInstalled,specFor}from"./chunk-CSXS5D2F.mjs";import{bold,clip,detail,dim,printJson,say}from"./chunk-BF25CRHJ.mjs";import{UsageError,parseCommand}from"./chunk-XPLEWNGF.mjs";import"./chunk-IJHUIMJA.mjs";import"./chunk-K73ZPBFM.mjs";import"./chunk-OXHAGFXG.mjs";import{featuresFor}from"./chunk-2ZCM3JZR.mjs";import{activeSpecs}from"./chunk-7Z3AMI24.mjs";import{CANONICAL_EVENTS}from"./chunk-ZNEBE4WO.mjs";import{homePaths}from"./chunk-OYGOSD6V.mjs";import"./chunk-AHPMRYYF.mjs";var usage=`Usage: hookmux explain "<prompt>" [--host <id>] [--event <event>] [--all] [--json]
|
|
2
|
+
|
|
3
|
+
Shows what every active plugin decides for this prompt, and the exact stdout
|
|
4
|
+
the host would receive. Writes no state and no log.
|
|
5
|
+
|
|
6
|
+
--host <id> host to simulate (default ${DEFAULT_HOST})
|
|
7
|
+
--event <event> ${CANONICAL_EVENTS.join(", ")} (default prompt.submit)
|
|
8
|
+
--all also run untrusted plugins (labelled, never in the stdout)
|
|
9
|
+
--run-scripts with --all, also run untrusted plugins' scripts (default: unknown)`;async function run(argv){let parsed=parseCommand(argv,{host:{type:"string"},event:{type:"string"},all:{type:"boolean"},"run-scripts":{type:"boolean"},json:{type:"boolean"}},usage,1);if(!parsed)return 0;let prompt=parsed.positionals[0];if(prompt===void 0)throw new UsageError('give the prompt to explain, e.g. hookmux explain "redesign the page"');let adapter=adapterOrUsage(parsed.values.host??DEFAULT_HOST),eventName=parsed.values.event??"prompt.submit";if(!CANONICAL_EVENTS.includes(eventName))throw new UsageError(`unknown event '${eventName}'`);let{registry,rows}=inspectInstalled(homePaths()),labels=new Map(rows.map(r=>[r.id,r.status])),plugins=pluginsToRun(registry,rows,adapter.id,{all:parsed.values.all===!0,runScripts:parsed.values["run-scripts"]===!0}),event=sampleEvent(adapter,eventName,prompt),result=await runEngine({event,plugins,settings:engineSettings(registry),firedThisSession:new Set}),stdout=adapter.render(result,event),traces=result.trace.map(t=>({...t,status:labels.get(t.id)??"active"}));return printExplain({adapter,eventName,prompt,traces,result,stdout},{all:parsed.values.all===!0,json:parsed.values.json===!0}),0}function pluginsToRun(registry,rows,hostId,opts){let plugins=activeSpecs(registry,hostId);if(!opts.all)return plugins;for(let row of rows){let spec=row.status==="untrusted"?specFor(row,hostId):void 0;if(!spec)continue;let preview={...spec,shadow:!0};plugins.push(opts.runScripts?preview:withoutScripts(preview))}return plugins}function printExplain(e,opts){let{adapter,eventName,result}=e;if(opts.json){printJson({host:adapter.id,event:eventName,prompt:e.prompt,plugins:e.traces,context:result.context,notices:result.notices,block:result.block??null,hostFeatures:featuresFor(adapter,eventName),errors:result.errors,stdout:e.stdout});return}console.log(bold(`${adapter.name} \xB7 ${eventName} \xB7 "${clip(e.prompt,50)}"`)),e.traces.length===0&&say("info",`no ${opts.all?"":"active "}plugin listens to ${eventName} here`);for(let t of e.traces)printTrace(t);for(let err of result.errors)say("fail",err);console.log(dim(`stdout for ${adapter.name}:`)),console.log(e.stdout===""?dim("(empty: no change to the prompt)"):e.stdout)}function printTrace(t){let label=t.status==="active"?t.id:`${t.id} [${t.status}]`;say(outcomeStatus(t.outcome),`${label} ${t.outcome} ${dim(`${t.ms} ms`)}`),Object.keys(t.signals).length>0&&detail(formatSignals(t.signals)),t.note&&detail(dim(`note: ${t.note}`))}export{run,usage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{runEngine,selectPlugins}from"./chunk-F3USS665.mjs";import{readFired,recordFailures,recordFired}from"./chunk-ZDCAHPWY.mjs";import{appendLog,buildLogLine,loggingActive,readLogSettings}from"./chunk-UERSXYXZ.mjs";import{approveFromPrompt,newGrantToken,saveGrant}from"./chunk-CA2GWCFP.mjs";import{renderCardShort}from"./chunk-IAGBX723.mjs";import{getAdapter}from"./chunk-OXHAGFXG.mjs";import"./chunk-2ZCM3JZR.mjs";import{activeSpecs,loadRegistry}from"./chunk-7Z3AMI24.mjs";import{CANONICAL_EVENTS,PLUGIN_ID,emptyResult,killTrackedGroups}from"./chunk-ZNEBE4WO.mjs";import{homePaths}from"./chunk-OYGOSD6V.mjs";import"./chunk-AHPMRYYF.mjs";import{writeSync}from"node:fs";import{flushCompileCache}from"node:module";var MAX_LISTED=5;function listed(ids){let shown=ids.slice(0,MAX_LISTED).join(", ");return ids.length>MAX_LISTED?`${shown} and ${ids.length-MAX_LISTED} more`:shown}function shownId(id){return PLUGIN_ID.test(id)?id:"(a folder with an invalid name)"}function offPluginsNotice(registry){let unpromotedGuards=registry.plugins.filter(p=>p.status==="untrusted"&&p.phase==="guard"),invalid=registry.plugins.filter(p=>p.status==="invalid"),switchedOff=registry.plugins.filter(p=>p.status==="active"&&p.phase==="guard"&&[p.base,...Object.values(p.variants??{})].some(s=>s?.enabled===!1||s?.shadow===!0)),parts=[];if(unpromotedGuards.length>0){let ids=unpromotedGuards.map(p=>p.id);parts.push(`guard plugin ${listed(ids)} is off until you run hookmux promote ${ids[0]}`)}return switchedOff.length>0&&parts.push(`guard plugin ${listed(switchedOff.map(p=>p.id))} is disabled or in shadow and blocks nothing`),invalid.length>0&&parts.push(`plugin ${listed(invalid.map(p=>shownId(p.id)))} does not load (hookmux doctor)`),parts.length>0?`hookmux: ${parts.join("; ")}.`:null}var PROMOTE=/^\s*hookmux\s+promote\s+(\S+)(?:\s+(--standing))?\s*$/;function parsePromoteCommand(command){if(typeof command!="string")return null;let match=PROMOTE.exec(command);return!match||!PLUGIN_ID.test(match[1])?null:{id:match[1],standing:match[2]!==void 0}}function grantedCommand(request,token){return`hookmux promote ${request.id}${request.standing?" --standing":""} --grant ${token}`}var StdinError=class extends Error{};function readStdin(maxBytes,timeoutMs){return new Promise((resolve,reject)=>{let chunks=[],size=0,timer=setTimeout(()=>done(new StdinError("stdin did not close in time")),timeoutMs);timer.unref();let done=error=>{clearTimeout(timer),process.stdin.removeAllListeners(),process.stdin.pause(),error?reject(error):resolve(Buffer.concat(chunks).toString("utf8"))};process.stdin.on("data",chunk=>{if(size+=chunk.length,size>maxBytes)return done(new StdinError(`stdin larger than ${maxBytes} bytes`));chunks.push(chunk)}),process.stdin.on("end",()=>done()),process.stdin.on("error",error=>done(error))})}var WATCHDOG_GRACE_MS=1e3,DEFAULT_DEADLINE_MS=2e3,MAX_STDIN_BYTES=8*1024*1024,written=!1;function emit(text){if(written)return;written=!0;let buffer=Buffer.from(text,"utf8");for(;buffer.length>0;)try{let n=writeSync(1,buffer);buffer=buffer.subarray(n)}catch(error){if(error.code==="EAGAIN")continue;return}}function parseArgs(argv){let value=flag=>{let i=argv.indexOf(flag);return i>=0?argv[i+1]??"":""};return{host:value("--host"),event:value("--event")}}function promoteConfirmation(adapter,registry,event){if(event.name!=="tool.before"||!adapter.confirm||event.tool?.canonicalName!=="Bash")return null;let input=event.tool.input;if(typeof input!="object"||input===null)return null;let request=parsePromoteCommand(input.command);if(!request)return null;let plugin=registry.plugins.find(p=>p.id===request.id);if(!plugin||plugin.status==="invalid"||plugin.hash===void 0)return null;let token=newGrantToken(),reason=[plugin.card?renderCardShort(plugin.card,plugin.capabilities,registry.settings.deadlineMs):`hookmux: approve to turn on ${request.id}.`,`Now: ${currentState(plugin)}.`,request.standing?"Standing approval: later versions installed with hookmux add go live without asking while they need no more than this.":""].filter(Boolean).join(" "),output=adapter.confirm(event,{reason,input:{...input,command:grantedCommand(request,token),description:`hookmux: activate plugin ${request.id}`}});return{request,hash:plugin.hash,capabilities:plugin.capabilities,host:adapter.id,token,output}}function relayApprovals(paths,event){if(event.name!=="prompt.submit"||event.origin!=="user"||typeof event.prompt!="string")return[];if(event.prompt.includes("<task-notification>"))return[];try{return approveFromPrompt(paths.cards,event.submittedPrompt??event.prompt,event.host.id)}catch{return[]}}function addApprovalMessages(result,event,approvals){for(let card of approvals){if(event.host.supports.includes("notify")){let text=`hookmux: you approved ${card.summary} Undo: hookmux disable ${card.id}`;result.notices.push({pluginId:"hookmux",text})}let run2=`${card.command==="npx -y hookmux"?card.command:"hookmux"} promote ${card.id} --confirm ${card.code}`;result.context.push({pluginId:"hookmux",text:`hookmux: the user approved ${card.id} with code ${card.code}. Run exactly: ${run2}`})}}function currentState(plugin){return plugin.status!=="active"||!plugin.trusted?plugin.problem??"not promoted yet":plugin.base&&!plugin.base.enabled?"turned off; approving does not turn it on":plugin.base?.shadow?"in shadow mode; approving makes it live":"active now"}async function run(){let started=performance.now(),args=parseArgs(process.argv.slice(2)),watchdog=setTimeout(()=>finish(),DEFAULT_DEADLINE_MS+WATCHDOG_GRACE_MS),errors=[],paths=homePaths(),hookEvent,result,output="",granted;try{let adapter=getAdapter(args.host);if(!adapter||!CANONICAL_EVENTS.includes(args.event))return finish();let event=args.event,input=await readStdin(MAX_STDIN_BYTES,DEFAULT_DEADLINE_MS),registry=await loadRegistry(paths),specs=activeSpecs(registry,adapter.id,process.env.HOOKMUX_DISABLE==="1"),payload;try{payload=JSON.parse(input)}catch{errors.push("stdin is not JSON");return}if(hookEvent=adapter.parse(event,payload,process.env)??void 0,!hookEvent)return;let offNotice=event==="session.start"?offPluginsNotice(registry):null,confirmation=promoteConfirmation(adapter,registry,hookEvent),approvals=relayApprovals(paths,hookEvent),hasPlugins=selectPlugins(hookEvent,specs).length>0||offNotice!==null;if(!hasPlugins&&approvals.length===0){confirmation&&(granted=confirmation,output=confirmation.output);return}clearTimeout(watchdog);let deadline=registry.settings.deadlineMs;setTimeout(()=>finish(),deadline+WATCHDOG_GRACE_MS).unref(),result=hasPlugins?await evaluate(registry,specs,hookEvent,paths):emptyResult(),offNotice!==null&&hookEvent.host.supports.includes("notify")&&result.notices.push({pluginId:"hookmux",text:offNotice}),addApprovalMessages(result,hookEvent,approvals),confirmation&&!result.block?(granted=confirmation,output=confirmation.output):output=adapter.render(result,hookEvent)}catch(error){errors.push(error?.message??String(error)),output=""}finally{emit(output),granted&&output===granted.output&&storeGrant(paths.grants,granted),afterOutput(paths,args,performance.now()-started,hookEvent,result,output,errors)}}function evaluate(registry,specs,event,paths){return runEngine({event,plugins:specs,settings:{deadlineMs:registry.settings.deadlineMs,blockRequiresRule:registry.settings.blockRequiresRule,contextBudget:registry.settings.contextBudget,runtime:{providers:registry.providers}},firedThisSession:readFired(paths.sessions,event.sessionId)})}function storeGrant(dir,granted){try{saveGrant(dir,granted.token,{id:granted.request.id,hash:granted.hash,capabilities:granted.capabilities,standing:granted.request.standing,host:granted.host})}catch{}}function afterOutput(paths,args,ms,hookEvent,result,output,errors){try{if(hookEvent&&result){let fired=result.trace.filter(t=>t.outcome==="fire"&&!t.shadow&&!(t.note??"").includes("dropped")).map(t=>t.id);recordFired(paths.sessions,hookEvent.sessionId,fired)}let failures=errors.map(message=>({key:"hub",message}));for(let t of result?.trace??[]){t.outcome==="error"&&failures.push({key:t.id,message:t.note??"error"});for(let[name,s]of Object.entries(t.signals))s.error&&failures.push({key:`${t.id}/${name}`,message:s.error})}recordFailures(paths.health,failures);let settings=readLogSettings(paths.logSettings);loggingActive(settings)&&appendLog(paths.logFile,buildLogLine({host:args.host,event:args.event,ms,hookEvent,result,outputBytes:Buffer.byteLength(output),errors},settings))}catch{}}function finish(){emit(""),exit()}function exit(){try{flushCompileCache?.()}catch{}process.exit(0)}function onHostSignal(){try{killTrackedGroups()}finally{finish()}}for(let signal of["SIGTERM","SIGHUP","SIGINT"])process.on(signal,onHostSignal);run().catch(()=>emit("")).finally(()=>exit());
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{chooseHosts,setupHub}from"./chunk-FF55QGCZ.mjs";import"./chunk-L3BSVLQG.mjs";import"./chunk-CZY5UAXM.mjs";import"./chunk-5GQP3BA6.mjs";import"./chunk-CSXS5D2F.mjs";import{confirm,isInteractive}from"./chunk-RG3EOP4J.mjs";import{allAdapters,wiredAdapters}from"./chunk-G6SJQTFF.mjs";import{say}from"./chunk-BF25CRHJ.mjs";import{parseCommand,positiveInt}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";var usage=`Usage: hookmux init [--host <id>]... [--yes] [--no-skill] [--no-bundled] [--timeout <sec>]
|
|
2
|
+
|
|
3
|
+
Installs the hookmux engine into the home folder and adds one hub entry per
|
|
4
|
+
event to each chosen host. Run it again to update.
|
|
5
|
+
|
|
6
|
+
--host <id> wire this host (repeatable); known: ${allAdapters().map(a=>a.id).join(", ")}
|
|
7
|
+
--yes, -y wire every detected host without asking
|
|
8
|
+
--no-skill do not copy the authoring skill into host skill folders
|
|
9
|
+
--no-bundled do not install the plugins bundled with hookmux
|
|
10
|
+
--timeout <sec> host-side timeout for new hub entries (default 10)
|
|
11
|
+
|
|
12
|
+
Without a terminal, pass --host or --yes (a re-run updates the hosts already wired).`;async function run(argv){let parsed=parseCommand(argv,{host:{type:"string",multiple:!0},yes:{type:"boolean",short:"y"},"no-skill":{type:"boolean"},"no-bundled":{type:"boolean"},timeout:{type:"string"}},usage);if(!parsed)return 0;let v=parsed.values,paths=homePaths(),timeoutSec=positiveInt(v.timeout,"--timeout",readInstallState(paths.installState).timeoutSec),adapters=await chooseHosts(v.host??[],v.yes===!0,wiredAdapters(paths)),bundled=!v["no-bundled"]&&await offer("Install the plugins bundled with hookmux?"),skill=!v["no-skill"]&&await offer("Install the hookmux authoring skill for these hosts?"),hostsOk=await setupHub(paths,{adapters,engine:!0,timeoutSec,bundled,skill});return adapters.length===0?(say("warn","no host wired: no agent client detected","hookmux init --host <id>"),1):(say("info","next: check the install end to end","hookmux doctor"),hostsOk?0:1)}async function offer(question){return isInteractive()?confirm(question,!0):!0}export{run,usage};
|