@pluginfinity/engine 0.3.23 → 0.4.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/errors.js +13 -6
- package/hook-lib.generated.js +1 -1
- package/hooks.js +247 -29
- package/index.d.ts +124 -17
- package/index.js +2 -2
- package/lib-version.generated.js +1 -1
- package/notes.js +3 -1
- package/operations.js +89 -7
- package/package.json +3 -3
- package/tool-map.js +31 -1
- package/version.js +1 -1
package/errors.js
CHANGED
|
@@ -240,10 +240,15 @@ var HookEventUnsupported = class extends Schema.TaggedError()("HookEventUnsuppor
|
|
|
240
240
|
/** The config. */
|
|
241
241
|
path: Schema.String,
|
|
242
242
|
target: Schema.String,
|
|
243
|
-
events: Schema.Array(Schema.String)
|
|
243
|
+
events: Schema.Array(Schema.String),
|
|
244
|
+
/** Entries on events the target has, whose handler kind it cannot run, as `<Event> (<handler>)`. */
|
|
245
|
+
handlers: Schema.optionalKey(Schema.Array(Schema.String))
|
|
244
246
|
}) {
|
|
245
247
|
get message() {
|
|
246
|
-
|
|
248
|
+
const quoted = (names) => names.map((name) => `"${name}"`).join(", ");
|
|
249
|
+
const events = this.events.length === 0 ? [] : [`has no hook event ${quoted(this.events)}`];
|
|
250
|
+
const handlers = this.handlers === void 0 || this.handlers.length === 0 ? [] : [`runs only command hooks, not ${quoted(this.handlers)}`];
|
|
251
|
+
return `${this.target} ${[...events, ...handlers].join(" and ")}, used in ${this.path}`;
|
|
247
252
|
}
|
|
248
253
|
get remediation() {
|
|
249
254
|
return { hint: `Set \`fallback: "omit"\` on those entries to skip them on ${this.target}, or give ${this.target} its own hooks for the event.` };
|
|
@@ -251,14 +256,16 @@ var HookEventUnsupported = class extends Schema.TaggedError()("HookEventUnsuppor
|
|
|
251
256
|
};
|
|
252
257
|
/**
|
|
253
258
|
* What is wrong with a hook script: absent from the plugin, or lacking the
|
|
254
|
-
* executable bit under `scripts.invoke: "exec"`.
|
|
259
|
+
* executable bit under `scripts.invoke: "exec"`. A hook `binary` is always
|
|
260
|
+
* executed, so one without the bit is `binary-not-executable`.
|
|
255
261
|
*
|
|
256
262
|
* @public
|
|
257
263
|
*/
|
|
258
264
|
const HookScriptProblem = Schema.Literals([
|
|
259
265
|
"missing",
|
|
260
266
|
"not-executable",
|
|
261
|
-
"equals-in-path"
|
|
267
|
+
"equals-in-path",
|
|
268
|
+
"binary-not-executable"
|
|
262
269
|
]);
|
|
263
270
|
/**
|
|
264
271
|
* A hook `script` cannot be shipped as configured.
|
|
@@ -282,10 +289,10 @@ var HookScriptInvalid = class extends Schema.TaggedError()("HookScriptInvalid",
|
|
|
282
289
|
return this.component === "monitors" ? "monitor script" : this.component === "env" ? "env setup script" : "hook script";
|
|
283
290
|
}
|
|
284
291
|
get message() {
|
|
285
|
-
return this.problem === "missing" ? `${this.kind} ${this.script} named in ${this.path} does not exist` : this.problem === "equals-in-path" ? `${this.kind} ${this.script} has "=" in its path, and ${this.path} sets scripts.invoke to "exec", where Claude Code runs it after env and env reads it as a variable assignment` : `${this.kind} ${this.script} is not executable, and ${this.path} sets scripts.invoke to "exec"`;
|
|
292
|
+
return this.problem === "missing" ? `${this.kind} ${this.script} named in ${this.path} does not exist` : this.problem === "equals-in-path" ? `${this.kind} ${this.script} has "=" in its path, and ${this.path} sets scripts.invoke to "exec", where Claude Code runs it after env and env reads it as a variable assignment` : this.problem === "binary-not-executable" ? `hook binary ${this.script} named in ${this.path} is not executable` : `${this.kind} ${this.script} is not executable, and ${this.path} sets scripts.invoke to "exec"`;
|
|
286
293
|
}
|
|
287
294
|
get remediation() {
|
|
288
|
-
return this.problem === "missing" ? { hint: `Create ${this.script} under the plugin root, or fix the path in ${this.path}.` } : this.problem === "equals-in-path" ? { hint: `Rename ${this.script} without "=", or drop scripts.invoke so scripts run through bash.` } : { hint: `Run \`chmod +x ${this.script}\`, or drop scripts.invoke so scripts run through bash.` };
|
|
295
|
+
return this.problem === "missing" ? { hint: `Create ${this.script} under the plugin root, or fix the path in ${this.path}.` } : this.problem === "equals-in-path" ? { hint: `Rename ${this.script} without "=", or drop scripts.invoke so scripts run through bash.` } : this.problem === "binary-not-executable" ? { hint: `Run \`chmod +x ${this.script}\`.` } : { hint: `Run \`chmod +x ${this.script}\`, or drop scripts.invoke so scripts run through bash.` };
|
|
289
296
|
}
|
|
290
297
|
};
|
|
291
298
|
/**
|
package/hook-lib.generated.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
/** The hook library's files, embedded so a build needs no asset on disk. */
|
|
3
3
|
const HOOK_LIB_FILES = [{
|
|
4
4
|
name: "hook.sh",
|
|
5
|
-
content: "# shellcheck shell=bash\n# pluginfinity hook library. `pluginfinity build` writes this file into every\n# target that has hooks; do not edit a copy under builds/, the next build\n# overwrites it.\n#\n# Source it first in a hook script, relative to the script:\n# . \"$(dirname \"$0\")/lib/pluginfinity/hook.sh\" # hooks/<name>.sh\n# . \"$(dirname \"$0\")/../lib/pluginfinity/hook.sh\" # hooks/<event>/<name>.sh\n#\n# Bash 3.2 compatible. Writes nothing when sourced. Needs jq.\n#\n# Do not install your own `trap ... EXIT`: it replaces the library's\n# fail-open / fail-closed trap, and a failing hook would then exit non-zero.\n\n_pf_fail_closed=0\n[ \"${PLUGINFINITY_FAIL_CLOSED:-0}\" = 1 ] && _pf_fail_closed=1\n_pf_event=\"\"\n_pf_marker=\"\"\n_pf_kind_prefix=\"\"\n\n# --- logging --------------------------------------------------------------\n\n_pf_lib_dir=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd) || exit 0\n# The one logging standard lives at <root>/lib/pluginfinity. A build without it\n# must still fail open, so fall back to no-ops.\n_pf_log_dir=\"$_pf_lib_dir/../../../lib/pluginfinity\"\n# shellcheck source=/dev/null\n. \"$_pf_log_dir/log.sh\" 2>/dev/null || {\n pf_log() { :; }\n pf_debug() { :; }\n pf_debug_on() { return 1; }\n}\n\n# Append a line to the plugin's error log.\nhook_log() { pf_log hook \"$*\"; }\n\n# Append a line to the plugin's debug log when PLUGINFINITY_DEBUG=1.\nhook_debug() { pf_debug hook \"$*\"; }\n\n# Until the library is fully loaded a failure must still fail open: on Copilot\n# a non-zero exit from a preToolUse hook denies the tool.\n_pf_early_exit() {\n local code=$?\n [ \"$code\" -eq 0 ] || hook_log \"exited $code while loading the hook library\"\n _pf_cleanup\n exit 0\n}\n_pf_cleanup() {\n if [ -n \"$_pf_marker\" ]; then rm -f \"$_pf_marker\" 2>/dev/null || true; fi\n return 0\n}\ntrap _pf_early_exit EXIT\n\n# shellcheck source=/dev/null\n. \"$_pf_lib_dir/host.sh\" 2>/dev/null || {\n hook_log \"host.sh not loadable; hook skipped\"\n exit 0\n}\n\n# The tool map the build wrote for this host. A build without it keeps names\n# as they are.\n_PF_TOOLS=\"\"\n_PF_TOOLS_PLUGIN=\"\"\n_PF_TOOLS_MCP=\"\"\n_PF_TOOLS_SERVERS=\"\"\n_PF_TOOLS_UNLISTED=keep\n_PF_HAS_SKILLS=\"\"\n_PF_HAS_AGENTS=\"\"\n_PF_HAS_MONITORS=\"\"\n_PF_HAS_SERVERS=\"\"\n# A failed `.` aborts a shell on bash 3.2, so test the file first.\nif [ -r \"$_pf_lib_dir/tools.sh\" ]; then\n # shellcheck source=/dev/null\n . \"$_pf_lib_dir/tools.sh\" 2>/dev/null || true\nfi\n\n# --- input ----------------------------------------------------------------\n\n# Read the event once. A terminal on stdin (a hand run) reads as {}.\nif [ -t 0 ]; then\n _pf_input='{}'\nelse\n _pf_input=$(cat) || _pf_input=''\nfi\n\nif ! command -v jq >/dev/null 2>&1; then\n hook_log \"jq not found; hook skipped\"\n exit 0\nfi\n\n# Whether stdin held a JSON object. Anything else reads as {} from here on, so\n# hook_input never sees garbage; hook_require_input turns it into a no-op.\n_pf_input_ok=0\nif jq -e 'type == \"object\"' >/dev/null 2>&1 <<<\"$_pf_input\"; then\n _pf_input_ok=1\nelse\n _pf_input='{}'\nfi\n\n# Return when stdin was a JSON object; otherwise log it, answer with a no-op\n# and end the script.\nhook_require_input() {\n [ \"$_pf_input_ok\" = 1 ] && return 0\n hook_log \"malformed or empty JSON on stdin; skipping\"\n hook_noop\n exit 0\n}\n\n# One marker file records that a response went out, and holds its kind for the\n# debug log. It is a file, not a variable, so a response sent from a subshell\n# or a pipeline still counts.\n_pf_marker=$(mktemp \"${TMPDIR:-/tmp}/pluginfinity-emitted.XXXXXX\" 2>/dev/null) ||\n _pf_marker=\"${TMPDIR:-/tmp}/pluginfinity-emitted.$$\"\n: >\"$_pf_marker\" 2>/dev/null || true\n\n# A Claude field name, read from either payload form: as written, then the\n# camelCase spelling (tool_input from a toolArgs object or JSON string,\n# tool_name from toolName, anything else camelCased at the top level). A\n# tool_input key also falls back to Copilot's own spelling of it, since Copilot\n# keeps its key names (path, file_text, old_str, new_str) under Claude event\n# and tool names.\n_PF_INPUT_FILTER='\ndef camel: gsub(\"_(?<c>[a-z])\"; .c | ascii_upcase);\ndef args: if type == \"string\" then (fromjson? // .) else . end;\ndef alias: {file_path: \"path\", content: \"file_text\", old_string: \"old_str\", new_string: \"new_str\"};\n. as $in\n| ($path | if . == \"\" then [] else split(\".\") end) as $p\n| (try ($in | getpath($p)) catch null) as $v\n| (if $v != null then $v\n elif $p[0] == \"tool_input\" and ($p | length) == 2 and (alias[$p[1]] != null)\n and (try ($in | getpath([$p[0], alias[$p[1]]])) catch null) != null\n then ($in | getpath([$p[0], alias[$p[1]]]))\n elif $p[0] == \"tool_input\" then (try (($in.toolArgs | args) | getpath($p[1:])) catch null)\n elif $p[0] == \"tool_name\" then $in.toolName\n else (try ($in | getpath([$p[0] | camel] + $p[1:])) catch null) end)\n| if . == null then empty elif type == \"string\" then . else tojson end'\n\n# Print an input field by its Claude name (dotted for nested keys), or the\n# whole input as JSON with no argument. Prints nothing for a missing field.\nhook_input() { printf '%s' \"$_pf_input\" | jq -r --arg path \"${1:-}\" \"$_PF_INPUT_FILTER\" 2>/dev/null; }\n\n# --- failure policy -------------------------------------------------------\n\n_pf_has_emitted() { [ -s \"$_pf_marker\" ]; }\n\n_pf_closed_response() { # code\n local reason=\"${PLUGINFINITY_PLUGIN:-a plugin} hook failed (exit $1)\" body\n _pf_kind_prefix=\"fail-closed \"\n if hook_supports deny; then\n _pf_permission deny \"$reason\"\n elif hook_supports block; then\n body=$(jq -nc --arg r \"$reason\" '{decision: \"block\", reason: $r}') || return 1\n _pf_emit \"$body\" block\n fi\n}\n\n_pf_on_exit() {\n local code=$? outcome=none\n if [ \"$code\" -ne 0 ]; then\n hook_log \"exited $code during ${_pf_event:-an unknown event}\"\n if [ \"$_pf_fail_closed\" = 1 ] && ! _pf_has_emitted; then\n # A Stop hook that crashes while stop_hook_active is true must not block again, or it loops.\n case \"$_pf_event\" in\n Stop | SubagentStop)\n [ \"$(hook_input stop_hook_active)\" = true ] || _pf_closed_response \"$code\" || true\n ;;\n *) _pf_closed_response \"$code\" || true ;;\n esac\n fi\n fi\n if pf_debug_on; then\n if _pf_has_emitted; then outcome=$(cat \"$_pf_marker\" 2>/dev/null) || outcome=response; fi\n if [ \"$code\" -ne 0 ]; then outcome=\"$outcome (exit $code)\"; fi\n hook_debug \"outcome: $outcome\"\n fi\n _pf_cleanup\n exit 0\n}\n\n# Make a failure deny (PreToolUse) or block (where blocking is honoured)\n# instead of letting the action through.\nhook_fail_closed() { _pf_fail_closed=1; }\n\n# --- context --------------------------------------------------------------\n\n# The event's Claude name: PLUGINFINITY_EVENT (set on every Copilot entry by\n# the build), else the input's hook_event_name.\n# Prints nothing and returns 1 when neither is available.\nhook_event() {\n local ev=${PLUGINFINITY_EVENT:-}\n [ -n \"$ev\" ] || ev=$(hook_input hook_event_name)\n [ -n \"$ev\" ] || return 1\n printf '%s\\n' \"$ev\"\n}\n_pf_event=$(hook_event 2>/dev/null) || _pf_event=\"\"\n\n# claude or copilot.\nhook_host() { printf '%s\\n' \"$PLUGINFINITY_HOST\"; }\n\n# The build root this script runs from.\nhook_plugin_root() { (cd \"$_pf_lib_dir/../../..\" && pwd); }\n\n# The closest directory at or above $1 holding .git (a directory, or a file in\n# a worktree). Prints nothing and returns 1 when there is none.\n_pf_git_root() {\n local probe=$1\n while [ -n \"$probe\" ] && [ \"$probe\" != / ] && [ \"$probe\" != . ]; do\n if [ -e \"$probe/.git\" ]; then\n printf '%s\\n' \"$probe\"\n return 0\n fi\n probe=$(dirname \"$probe\")\n done\n return 1\n}\n\n# Where this call runs: the input's cwd walked up to the nearest .git, else the\n# cwd itself; with no cwd, CLAUDE_PROJECT_DIR (Claude), else $PWD walked up to\n# .git (Claude), else $PWD as is. On Copilot $PWD is always the plugin root, so\n# it is never walked: that would find the repo holding the plugin.\nhook_project_dir() {\n local dir root\n dir=$(hook_input cwd)\n # A relative cwd means nothing outside the host's own process; ignore it.\n if [ -n \"$dir\" ] && [ \"${dir#/}\" != \"$dir\" ]; then\n if root=$(_pf_git_root \"$dir\"); then\n printf '%s\\n' \"$root\"\n else\n printf '%s\\n' \"$dir\"\n fi\n return 0\n fi\n if [ \"$PLUGINFINITY_HOST\" = claude ]; then\n if [ -n \"${CLAUDE_PROJECT_DIR:-}\" ]; then\n printf '%s\\n' \"$CLAUDE_PROJECT_DIR\"\n return 0\n fi\n if root=$(_pf_git_root \"$PWD\"); then\n printf '%s\\n' \"$root\"\n return 0\n fi\n fi\n printf '%s\\n' \"$PWD\"\n}\n\n# The session's project: CLAUDE_PROJECT_DIR on Claude when set, else what\n# hook_project_dir finds. In a git worktree the two differ.\nhook_session_dir() {\n if [ \"$PLUGINFINITY_HOST\" = claude ] && [ -n \"${CLAUDE_PROJECT_DIR:-}\" ]; then\n printf '%s\\n' \"$CLAUDE_PROJECT_DIR\"\n return 0\n fi\n hook_project_dir\n}\n\n# cd into hook_project_dir, ignoring CDPATH and treating a leading dash as a path.\n# Writes nothing to stdout; on failure it logs through hook_log and returns non-zero.\nhook_cd_project() {\n local dir\n dir=$(hook_project_dir)\n CDPATH= cd -- \"$dir\" >/dev/null 2>&1 || {\n hook_log \"hook_cd_project: cannot cd to $dir\"\n return 1\n }\n}\n\n# Print the host's run-time spelling of a Claude run-time tool name and return\n# 0, or print nothing and return 1 when the host has none. An own MCP tool is\n# written mcp__plugin_<plugin>_<server>__<tool>, as Claude Code names it.\nhook_tool_name() {\n local name=${1:-} line plugin rest head seg server tool template\n [ -n \"$name\" ] || return 1\n while IFS= read -r line; do\n if [ \"${line%%=*}\" = \"$name\" ] && [ \"${line#*=}\" != \"$line\" ]; then\n printf '%s\\n' \"${line#*=}\"\n return 0\n fi\n done <<<\"$_PF_TOOLS\"\n plugin=${_PF_TOOLS_PLUGIN:-${PLUGINFINITY_PLUGIN:-}}\n case \"$name\" in\n \"mcp__plugin_${plugin}_\"*)\n rest=${name#\"mcp__plugin_${plugin}_\"}\n # Try each \"__\" as the server/tool boundary, as the build does.\n head=\"\"\n while [ \"${rest#*__}\" != \"$rest\" ]; do\n seg=${rest%%__*}\n rest=${rest#*__}\n server=\"${head:+${head}__}$seg\"\n tool=$rest\n head=$server\n [ -n \"$server\" ] && [ -n \"$tool\" ] && [ -n \"$_PF_TOOLS_MCP\" ] || continue\n case \" $_PF_TOOLS_SERVERS \" in\n *\" $server \"*)\n template=$_PF_TOOLS_MCP\n template=${template//\\{plugin\\}/$plugin}\n template=${template//\\{server\\}/$server}\n template=${template//\\{tool\\}/$tool}\n printf '%s\\n' \"$template\"\n return 0\n ;;\n esac\n done\n ;;\n esac\n [ \"$_PF_TOOLS_UNLISTED\" = keep ] || return 1\n printf '%s\\n' \"$name\"\n}\n\n# Whether this build ships a component: hook_has <monitor|skill|agent|server> <name>.\n# Returns 0 when it does, 1 when it does not (or tools.sh is missing), 2 for an\n# unknown kind. The lists are built per target, so a skill a target excludes and\n# a monitor on a host without monitors are absent.\nhook_has() {\n local kind=${1:-} name=${2:-} list\n case \"$kind\" in\n skill) list=$_PF_HAS_SKILLS ;;\n agent) list=$_PF_HAS_AGENTS ;;\n monitor) list=$_PF_HAS_MONITORS ;;\n server) list=$_PF_HAS_SERVERS ;;\n *)\n hook_log \"hook_has: unknown kind '$kind'\"\n return 2\n ;;\n esac\n [ -n \"$name\" ] || return 1\n case \" $list \" in\n *\" $name \"*) return 0 ;;\n esac\n return 1\n}\n\n# Print the run-time tool-name prefix of an own MCP server (Claude\n# mcp__plugin_<plugin>_<server>__, Copilot <server>-) and return 0, or print\n# nothing and return 1 for a server this plugin does not declare.\nhook_tool_prefix() {\n local server=${1:-} template plugin\n [ -n \"$server\" ] && [ -n \"$_PF_TOOLS_MCP\" ] || return 1\n case \" $_PF_TOOLS_SERVERS \" in\n *\" $server \"*) ;;\n *) return 1 ;;\n esac\n plugin=${_PF_TOOLS_PLUGIN:-${PLUGINFINITY_PLUGIN:-}}\n template=$_PF_TOOLS_MCP\n template=${template//\\{plugin\\}/$plugin}\n template=${template//\\{server\\}/$server}\n printf '%s\\n' \"${template%%\\{tool\\}*}\"\n}\n\n# Whether the host honours capability $1 on event $2 (default: this event).\n# Mirrors okf/references/{claude-code,copilot-cli}-plugin-format.md.\n# server-project asks about the host, not an event: whether an MCP server can\n# learn the project (Claude gives it CLAUDE_PROJECT_DIR and roots; Copilot\n# gives none, measured 2026-10-07), the question server_project_dir answers.\nhook_supports() {\n local cap=\"${1:-}\" event=\"${2:-$_pf_event}\"\n case \"$PLUGINFINITY_HOST:$cap\" in\n *:noop | *:raw) return 0 ;;\n claude:system_message)\n case \"$event\" in Notification | SessionEnd | PreCompact | ConfigChange) return 1 ;; esac\n return 0\n ;;\n *:deny | *:allow | *:ask) [ \"$event\" = PreToolUse ] && return 0 ;;\n claude:context)\n case \"$event\" in\n SessionStart | SubagentStart | PostModelSwitch | UserPromptSubmit | UserPromptExpansion | PreToolUse | \\\n PostToolUse | PostToolUseFailure | PostToolBatch | Stop | SubagentStop) return 0 ;;\n esac\n ;;\n copilot:context)\n case \"$event\" in SessionStart | SubagentStart | PostToolUse | Notification) return 0 ;; esac\n ;;\n claude:block)\n case \"$event\" in\n UserPromptSubmit | UserPromptExpansion | PostToolUse | PostToolBatch | Stop | \\\n SubagentStop | ConfigChange | PreCompact | TaskCreated | PreModelSwitch) return 0 ;;\n esac\n ;;\n copilot:block)\n case \"$event\" in Stop | SubagentStop) return 0 ;; esac\n ;;\n claude:server-project) return 0 ;;\n claude:env-shell)\n case \"$event\" in SessionStart | Setup | CwdChanged | FileChanged) return 0 ;; esac\n ;;\n esac\n return 1\n}\n\n# --- session env ---------------------------------------------------------\n\n# Whether env.sh is loaded: the build ships it only when the config declares env.\n_pf_env_loaded=0\n\n# Set a declared session variable (the run-time rung of the env chain): record\n# it in the session values file, export it in this hook and, on Claude, append\n# it to CLAUDE_ENV_FILE so the model's shell sees it. Only the events that can\n# produce a value (SessionStart, Setup, CwdChanged, FileChanged) may call it,\n# and only for a name the config declares. It always returns 0: a refusal (any\n# other event, an undeclared name, a value with a newline, a build with no env)\n# is a log line, or a debug line for an event that cannot produce, and changes\n# nothing, so it never aborts a `set -e` hook or denies a fail-closed one.\nhook_env_set() {\n local name=${1:-}\n if [ \"$_pf_env_loaded\" != 1 ]; then\n hook_log \"hook_env_set: no session env is declared in this build\"\n return 0\n fi\n case \"$_pf_event\" in\n SessionStart | Setup | CwdChanged | FileChanged) ;;\n *)\n hook_debug \"hook_env_set $name ignored: ${_pf_event:-an unknown event} does not produce session values\"\n return 0\n ;;\n esac\n _pf_env_set \"$name\" \"${2-}\" || true\n return 0\n}\n\n# Load env.sh and apply the session values. A failure here never aborts the hook, even under set -e.\n_pf_env_start() {\n local sid proj cwd errexit=0 nounset=0\n [ -r \"$_pf_log_dir/env.sh\" ] || return 0\n case $- in *e*) errexit=1 ;; esac\n case $- in *u*) nounset=1 ;; esac\n set +eu\n _pf_env_lib_dir=\"$_pf_log_dir\"\n _pf_env_manual=1\n _pf_env_component=hook\n # shellcheck source=/dev/null\n if . \"$_pf_log_dir/env.sh\" 2>/dev/null; then\n _pf_env_loaded=1\n sid=$(hook_input session_id)\n cwd=$(hook_input cwd)\n if [ \"$PLUGINFINITY_HOST\" = copilot ] && [ \"${cwd#/}\" = \"$cwd\" ]; then\n # The runner's rule: Copilot runs hooks from the plugin root, which is no\n # project, so with no absolute cwd read no .env (the session file or the defaults).\n proj=-\n else\n proj=$(_pf_env_project_of \"$(hook_project_dir)\")\n fi\n env_load \"$sid\" \"$proj\"\n else\n hook_log \"env.sh not loadable; session env skipped\"\n fi\n [ \"$errexit\" = 1 ] && set -e\n [ \"$nounset\" = 1 ] && set -u\n return 0\n}\n\n# --- output ---------------------------------------------------------------\n\n_pf_emit() { # json [kind]\n if [ -z \"${1:-}\" ]; then\n hook_log \"refused to send an empty response\"\n return 1\n fi\n if _pf_has_emitted; then\n hook_debug \"ignored a second response: $1\"\n return 0\n fi\n printf '%s' \"${_pf_kind_prefix}${2:-response}\" >\"$_pf_marker\" 2>/dev/null || true\n printf '%s\\n' \"$1\"\n}\n\n_pf_unsupported() { # function-name\n hook_debug \"$1 does nothing on $PLUGINFINITY_HOST for ${_pf_event:-an unknown event}\"\n hook_noop\n}\n\n_pf_permission() { # decision reason [updated-input-json]\n local key=updatedInput body u=null\n [ \"$PLUGINFINITY_HOST\" = copilot ] && key=modifiedArgs\n if [ -n \"${3:-}\" ]; then\n u=$(printf '%s' \"$3\" | jq -c . 2>/dev/null) || {\n hook_log \"hook_allow: not JSON: $3\"\n return 1\n }\n fi\n body=$(jq -nc --arg d \"$1\" --arg r \"${2:-}\" --argjson u \"$u\" --arg k \"$key\" \\\n '{permissionDecision: $d}\n + (if $r == \"\" then {} else {permissionDecisionReason: $r} end)\n + (if $u == null then {} else {($k): $u} end)' 2>/dev/null) || return 1\n if [ \"$PLUGINFINITY_HOST\" != copilot ]; then\n body=$(jq -nc --argjson b \"$body\" '{hookSpecificOutput: ({hookEventName: \"PreToolUse\"} + $b)}') || return 1\n fi\n _pf_emit \"$body\" \"$1\"\n}\n\n# Respond with nothing to change.\nhook_noop() { _pf_emit '{}' noop; }\n\n# Add text to the model's context.\nhook_context() {\n hook_supports context || {\n _pf_unsupported hook_context\n return 0\n }\n local body\n if [ \"$PLUGINFINITY_HOST\" = copilot ]; then\n body=$(jq -nc --arg c \"${1:-}\" '{additionalContext: $c}') || return 1\n else\n body=$(jq -nc --arg e \"$_pf_event\" --arg c \"${1:-}\" \\\n '{hookSpecificOutput: {hookEventName: $e, additionalContext: $c}}') || return 1\n fi\n _pf_emit \"$body\" context\n}\n\n# PreToolUse: refuse the tool call.\nhook_deny() {\n hook_supports deny || {\n _pf_unsupported hook_deny\n return 0\n }\n _pf_permission deny \"${1:-Blocked by ${PLUGINFINITY_PLUGIN:-a plugin}}\"\n}\n\n# PreToolUse: allow the tool call, with an optional reason and an optional\n# replacement input (JSON).\nhook_allow() {\n hook_supports allow || {\n _pf_unsupported hook_allow\n return 0\n }\n _pf_permission allow \"${1:-}\" \"${2:-}\"\n}\n\n# PreToolUse: ask the user.\nhook_ask() {\n hook_supports ask || {\n _pf_unsupported hook_ask\n return 0\n }\n _pf_permission ask \"${1:-}\"\n}\n\n# Block the event's action with a reason (Stop: keep working on it).\nhook_block() {\n hook_supports block || {\n _pf_unsupported hook_block\n return 0\n }\n local body\n body=$(jq -nc --arg r \"${1:-Blocked by ${PLUGINFINITY_PLUGIN:-a plugin}}\" '{decision: \"block\", reason: $r}') || return 1\n _pf_emit \"$body\" block\n}\n\n# Show the user a message.\nhook_system_message() {\n hook_supports system_message || {\n _pf_unsupported hook_system_message\n return 0\n }\n local body\n body=$(jq -nc --arg m \"${1:-}\" '{systemMessage: $m}') || return 1\n _pf_emit \"$body\" system_message\n}\n\n# Print the input the way Claude would send it. On Copilot: hook_event_name\n# from hook_event, snake_case top-level keys (toolName/toolArgs become\n# tool_name/tool_input, parsed when a string), and Copilot's tool_input key\n# names mapped to Claude's where the Claude key is absent. On Claude: the\n# input unchanged, with hook_event_name filled in when missing.\nhook_envelope() {\n if [ \"${1:-}\" != claude ]; then\n hook_log \"hook_envelope: unknown target: ${1:-none}\"\n return 1\n fi\n local event\n event=$(hook_event 2>/dev/null) || event=\"\"\n printf '%s' \"$_pf_input\" | jq -c --arg event \"$event\" --arg host \"$PLUGINFINITY_HOST\" '\ndef snake: gsub(\"(?<c>[A-Z])\"; \"_\" + (.c | ascii_downcase));\ndef args: if type == \"string\" then (fromjson? // .) else . end;\ndef alias: {path: \"file_path\", file_text: \"content\", old_str: \"old_string\", new_str: \"new_string\"};\ndef fix: if type == \"object\" then\n . as $o | reduce (keys_unsorted[]) as $k ($o;\n if alias[$k] != null and (has(alias[$k]) | not) then . + {(alias[$k]): $o[$k]} else . end)\n else . end;\n(if $host == \"copilot\" then\n with_entries(.key |= (if . == \"toolName\" then \"tool_name\" elif . == \"toolArgs\" then \"tool_input\" else snake end))\n | if has(\"tool_input\") then .tool_input |= (args | fix) else . end\n else . end)\n| if (has(\"hook_event_name\") | not) and $event != \"\" then . + {hook_event_name: $event} else . end' 2>/dev/null || {\n hook_log \"hook_envelope: input is not a JSON object\"\n return 1\n }\n}\n\n# Map one Claude-shaped hook response onto this host's emitters. First match\n# wins: permission decision, block, additional context, system message, then\n# noop. Fields that lose or have no mapping are written to the debug log.\nhook_relay() {\n local plan kind reason input text path\n plan=$(printf '%s' \"${1:-}\" | jq -c '\nif type != \"object\" then error(\"not an object\") else . end\n| (.hookSpecificOutput | if type == \"object\" then . else {} end) as $h\n| ($h.permissionDecision) as $d\n| (if ($d == \"allow\" or $d == \"deny\" or $d == \"ask\") then\n {kind: $d, reason: ($h.permissionDecisionReason // \"\"), input: (if $d == \"allow\" and ($h.updatedInput != null) then ($h.updatedInput | tojson) else \"\" end), text: \"\",\n used: [\"hookSpecificOutput.permissionDecision\", \"hookSpecificOutput.permissionDecisionReason\", \"hookSpecificOutput.updatedInput\"]}\n elif .decision == \"block\" then\n {kind: \"block\", reason: (.reason // \"\"), input: \"\", text: \"\", used: [\"decision\", \"reason\"]}\n elif ($h.additionalContext != null) then\n {kind: \"context\", reason: \"\", input: \"\", text: ($h.additionalContext | if type == \"string\" then . else tojson end), used: [\"hookSpecificOutput.additionalContext\"]}\n elif .systemMessage != null then\n {kind: \"system_message\", reason: \"\", input: \"\", text: (.systemMessage | if type == \"string\" then . else tojson end), used: [\"systemMessage\"]}\n else {kind: \"noop\", reason: \"\", input: \"\", text: \"\", used: []} end) as $p\n| ([paths | select((length == 1 and (.[0] != \"hookSpecificOutput\" or ($h | length) == 0)) or (length == 2 and .[0] == \"hookSpecificOutput\" and (($h | length) > 0)))\n | join(\".\")] | map(select(. != \"hookSpecificOutput.hookEventName\"))) as $all\n| $p + {dropped: ($all - $p.used)}' 2>/dev/null) || {\n hook_log \"hook_relay: not a JSON object\"\n return 1\n }\n kind=$(jq -r .kind <<<\"$plan\")\n reason=$(jq -r .reason <<<\"$plan\")\n input=$(jq -r .input <<<\"$plan\")\n text=$(jq -r .text <<<\"$plan\")\n while IFS= read -r path; do\n [ -n \"$path\" ] && hook_debug \"hook_relay dropped $path\"\n done <<<\"$(jq -r '.dropped[]' <<<\"$plan\")\"\n case \"$kind\" in\n allow) hook_allow \"$reason\" \"$input\" ;;\n deny) hook_deny \"$reason\" ;;\n ask) hook_ask \"$reason\" ;;\n block) hook_block \"$reason\" ;;\n context) hook_context \"$text\" ;;\n system_message) hook_system_message \"$text\" ;;\n *) hook_noop ;;\n esac\n}\n\n# Emit a host-specific JSON response verbatim, only on that host.\nhook_raw() {\n if [ \"${1:-}\" != \"$PLUGINFINITY_HOST\" ]; then\n hook_debug \"hook_raw for ${1:-no host} skipped on $PLUGINFINITY_HOST\"\n return 0\n fi\n local body\n body=$(printf '%s' \"${2:-}\" | jq -c . 2>/dev/null) || {\n hook_log \"hook_raw: not JSON: ${2:-}\"\n return 1\n }\n _pf_emit \"$body\" raw\n}\n\ntrap _pf_on_exit EXIT\n\nif pf_debug_on; then hook_debug \"input: ${_pf_input:0:4000}\"; fi\n\n# --- matcher ---------------------------------------------------------------\n\n# A host that ignores an event's matcher (Copilot on SessionStart, SessionEnd\n# and SubagentStop) has the build pass it as PLUGINFINITY_MATCHER. Apply\n# Claude's rules here: empty or `*` matches all; only [A-Za-z0-9_| ,-] is an\n# exact `|` list; anything else is an unanchored extended regex. No match ends\n# the script quietly, so nothing is emitted and the exit is 0.\n_pf_matcher_applies() { # matcher value\n local m=$1 v=$2 item\n local -a items\n { [ -z \"$m\" ] || [ \"$m\" = '*' ]; } && return 0\n if [[ ! \"$m\" =~ [^A-Za-z0-9_\\|\\ ,-] ]]; then\n IFS='|' read -r -a items <<<\"$m\"\n for item in \"${items[@]}\"; do\n [ \"$item\" = \"$v\" ] && return 0\n done\n return 1\n fi\n printf '%s' \"$v\" | grep -Eq -- \"$m\" 2>/dev/null\n}\n\nif [ -n \"${PLUGINFINITY_MATCHER+x}\" ]; then\n _pf_match_field=\"\"\n case \"$_pf_event\" in\n SessionStart) _pf_match_field=source ;;\n SessionEnd) _pf_match_field=reason ;;\n SubagentStop) _pf_match_field=agent_type ;;\n esac\n if [ -n \"$_pf_match_field\" ]; then\n _pf_match_value=$(hook_input \"$_pf_match_field\")\n if ! _pf_matcher_applies \"$PLUGINFINITY_MATCHER\" \"$_pf_match_value\"; then\n hook_debug \"matcher $PLUGINFINITY_MATCHER did not match $_pf_match_value\"\n exit 0\n fi\n fi\nfi\n\n# --- session env ------------------------------------------------------------\n\n# After the matcher, so a skipped hook does not pay for it. A build with no\n# env.sh has no session env and this does nothing.\n_pf_env_start\n"
|
|
5
|
+
content: "# shellcheck shell=bash\n# pluginfinity hook library. `pluginfinity build` writes this file into every\n# target that has hooks; do not edit a copy under builds/, the next build\n# overwrites it.\n#\n# Source it first in a hook script, relative to the script:\n# . \"$(dirname \"$0\")/lib/pluginfinity/hook.sh\" # hooks/<name>.sh\n# . \"$(dirname \"$0\")/../lib/pluginfinity/hook.sh\" # hooks/<event>/<name>.sh\n#\n# Bash 3.2 compatible. Writes nothing when sourced. Needs jq.\n#\n# Do not install your own `trap ... EXIT`: it replaces the library's\n# fail-open / fail-closed trap, and a failing hook would then exit non-zero.\n\n_pf_fail_closed=0\n[ \"${PLUGINFINITY_FAIL_CLOSED:-0}\" = 1 ] && _pf_fail_closed=1\n_pf_event=\"\"\n_pf_marker=\"\"\n_pf_kind_prefix=\"\"\n_pf_rewake=0\n\n# --- logging --------------------------------------------------------------\n\n_pf_lib_dir=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd) || exit 0\n# The one logging standard lives at <root>/lib/pluginfinity. A build without it\n# must still fail open, so fall back to no-ops.\n_pf_log_dir=\"$_pf_lib_dir/../../../lib/pluginfinity\"\n# shellcheck source=/dev/null\n. \"$_pf_log_dir/log.sh\" 2>/dev/null || {\n pf_log() { :; }\n pf_debug() { :; }\n pf_debug_on() { return 1; }\n}\n\n# Append a line to the plugin's error log.\nhook_log() { pf_log hook \"$*\"; }\n\n# Append a line to the plugin's debug log when PLUGINFINITY_DEBUG=1.\nhook_debug() { pf_debug hook \"$*\"; }\n\n# Until the library is fully loaded a failure must still fail open: on Copilot\n# a non-zero exit from a preToolUse hook denies the tool.\n_pf_early_exit() {\n local code=$?\n [ \"$code\" -eq 0 ] || hook_log \"exited $code while loading the hook library\"\n _pf_cleanup\n exit 0\n}\n_pf_cleanup() {\n if [ -n \"$_pf_marker\" ]; then rm -f \"$_pf_marker\" 2>/dev/null || true; fi\n return 0\n}\ntrap _pf_early_exit EXIT\n\n# shellcheck source=/dev/null\n. \"$_pf_lib_dir/host.sh\" 2>/dev/null || {\n hook_log \"host.sh not loadable; hook skipped\"\n exit 0\n}\n\n# The tool map the build wrote for this host. A build without it keeps names\n# as they are.\n_PF_TOOLS=\"\"\n_PF_TOOLS_PLUGIN=\"\"\n_PF_TOOLS_MCP=\"\"\n_PF_TOOLS_SERVERS=\"\"\n_PF_TOOLS_UNLISTED=keep\n_PF_HAS_SKILLS=\"\"\n_PF_HAS_AGENTS=\"\"\n_PF_HAS_MONITORS=\"\"\n_PF_HAS_SERVERS=\"\"\n# A failed `.` aborts a shell on bash 3.2, so test the file first.\nif [ -r \"$_pf_lib_dir/tools.sh\" ]; then\n # shellcheck source=/dev/null\n . \"$_pf_lib_dir/tools.sh\" 2>/dev/null || true\nfi\n\n# --- input ----------------------------------------------------------------\n\n# Read the event once. A terminal on stdin (a hand run) reads as {}.\nif [ -t 0 ]; then\n _pf_input='{}'\nelse\n _pf_input=$(cat) || _pf_input=''\nfi\n\nif ! command -v jq >/dev/null 2>&1; then\n hook_log \"jq not found; hook skipped\"\n exit 0\nfi\n\n# Whether stdin held a JSON object. Anything else reads as {} from here on, so\n# hook_input never sees garbage; hook_require_input turns it into a no-op.\n_pf_input_ok=0\nif jq -e 'type == \"object\"' >/dev/null 2>&1 <<<\"$_pf_input\"; then\n _pf_input_ok=1\nelse\n _pf_input='{}'\nfi\n\n# Return when stdin was a JSON object; otherwise log it, answer with a no-op\n# and end the script.\nhook_require_input() {\n [ \"$_pf_input_ok\" = 1 ] && return 0\n hook_log \"malformed or empty JSON on stdin; skipping\"\n hook_noop\n exit 0\n}\n\n# One marker file records that a response went out, and holds its kind for the\n# debug log. It is a file, not a variable, so a response sent from a subshell\n# or a pipeline still counts.\n_pf_marker=$(mktemp \"${TMPDIR:-/tmp}/pluginfinity-emitted.XXXXXX\" 2>/dev/null) ||\n _pf_marker=\"${TMPDIR:-/tmp}/pluginfinity-emitted.$$\"\n: >\"$_pf_marker\" 2>/dev/null || true\n\n# A Claude field name, read from either payload form: as written, then the\n# camelCase spelling (tool_input from a toolArgs object or JSON string,\n# tool_name from toolName, anything else camelCased at the top level). A\n# tool_input key also falls back to Copilot's own spelling of it, since Copilot\n# keeps its key names (path, file_text, old_str, new_str) under Claude event\n# and tool names.\n_PF_INPUT_FILTER='\ndef camel: gsub(\"_(?<c>[a-z])\"; .c | ascii_upcase);\ndef args: if type == \"string\" then (fromjson? // .) else . end;\ndef alias: {file_path: \"path\", content: \"file_text\", old_string: \"old_str\", new_string: \"new_str\"};\n. as $in\n| ($path | if . == \"\" then [] else split(\".\") end) as $p\n| (try ($in | getpath($p)) catch null) as $v\n| (if $v != null then $v\n elif $p[0] == \"tool_input\" and ($p | length) == 2 and (alias[$p[1]] != null)\n and (try ($in | getpath([$p[0], alias[$p[1]]])) catch null) != null\n then ($in | getpath([$p[0], alias[$p[1]]]))\n elif $p[0] == \"tool_input\" then (try (($in.toolArgs | args) | getpath($p[1:])) catch null)\n elif $p[0] == \"tool_name\" then $in.toolName\n else (try ($in | getpath([$p[0] | camel] + $p[1:])) catch null) end)\n| if . == null then empty elif type == \"string\" then . else tojson end'\n\n# Print an input field by its Claude name (dotted for nested keys), or the\n# whole input as JSON with no argument. Prints nothing for a missing field.\nhook_input() { printf '%s' \"$_pf_input\" | jq -r --arg path \"${1:-}\" \"$_PF_INPUT_FILTER\" 2>/dev/null; }\n\n# --- failure policy -------------------------------------------------------\n\n_pf_has_emitted() { [ -s \"$_pf_marker\" ]; }\n\n_pf_closed_response() { # code\n local reason=\"${PLUGINFINITY_PLUGIN:-a plugin} hook failed (exit $1)\" body\n _pf_kind_prefix=\"fail-closed \"\n if hook_supports deny; then\n _pf_permission deny \"$reason\"\n elif hook_supports block; then\n body=$(jq -nc --arg r \"$reason\" '{decision: \"block\", reason: $r}') || return 1\n _pf_emit \"$body\" block\n fi\n}\n\n_pf_on_exit() {\n local code=$? outcome=none\n # hook_rewake asked for exit 2, the one exit code an asyncRewake hook wakes the agent with.\n if [ \"$_pf_rewake\" = 1 ]; then\n if pf_debug_on; then hook_debug \"outcome: rewake\"; fi\n _pf_cleanup\n exit 2\n fi\n if [ \"$code\" -ne 0 ]; then\n hook_log \"exited $code during ${_pf_event:-an unknown event}\"\n if [ \"$_pf_fail_closed\" = 1 ] && ! _pf_has_emitted; then\n # A Stop hook that crashes while stop_hook_active is true must not block again, or it loops.\n case \"$_pf_event\" in\n Stop | SubagentStop)\n [ \"$(hook_input stop_hook_active)\" = true ] || _pf_closed_response \"$code\" || true\n ;;\n # A block here sends a teammate back to work, and it cannot repair a hook that will not run.\n TaskCompleted | TeammateIdle) ;;\n *) _pf_closed_response \"$code\" || true ;;\n esac\n fi\n fi\n if pf_debug_on; then\n if _pf_has_emitted; then outcome=$(cat \"$_pf_marker\" 2>/dev/null) || outcome=response; fi\n if [ \"$code\" -ne 0 ]; then outcome=\"$outcome (exit $code)\"; fi\n hook_debug \"outcome: $outcome\"\n fi\n _pf_cleanup\n exit 0\n}\n\n# Make a failure deny (PreToolUse) or block (where blocking is honoured)\n# instead of letting the action through.\nhook_fail_closed() { _pf_fail_closed=1; }\n\n# --- context --------------------------------------------------------------\n\n# The event's Claude name: PLUGINFINITY_EVENT (set on every Copilot entry by\n# the build), else the input's hook_event_name.\n# Prints nothing and returns 1 when neither is available.\nhook_event() {\n local ev=${PLUGINFINITY_EVENT:-}\n [ -n \"$ev\" ] || ev=$(hook_input hook_event_name)\n [ -n \"$ev\" ] || return 1\n printf '%s\\n' \"$ev\"\n}\n_pf_event=$(hook_event 2>/dev/null) || _pf_event=\"\"\n\n# claude or copilot.\nhook_host() { printf '%s\\n' \"$PLUGINFINITY_HOST\"; }\n\n# The build root this script runs from.\nhook_plugin_root() { (cd \"$_pf_lib_dir/../../..\" && pwd); }\n\n# The closest directory at or above $1 holding .git (a directory, or a file in\n# a worktree). Prints nothing and returns 1 when there is none.\n_pf_git_root() {\n local probe=$1\n while [ -n \"$probe\" ] && [ \"$probe\" != / ] && [ \"$probe\" != . ]; do\n if [ -e \"$probe/.git\" ]; then\n printf '%s\\n' \"$probe\"\n return 0\n fi\n probe=$(dirname \"$probe\")\n done\n return 1\n}\n\n# Where this call runs: the input's cwd walked up to the nearest .git, else the\n# cwd itself; with no cwd, CLAUDE_PROJECT_DIR (Claude), else $PWD walked up to\n# .git (Claude), else $PWD as is. On Copilot $PWD is always the plugin root, so\n# it is never walked: that would find the repo holding the plugin.\nhook_project_dir() {\n local dir root\n dir=$(hook_input cwd)\n # A relative cwd means nothing outside the host's own process; ignore it.\n if [ -n \"$dir\" ] && [ \"${dir#/}\" != \"$dir\" ]; then\n if root=$(_pf_git_root \"$dir\"); then\n printf '%s\\n' \"$root\"\n else\n printf '%s\\n' \"$dir\"\n fi\n return 0\n fi\n if [ \"$PLUGINFINITY_HOST\" = claude ]; then\n if [ -n \"${CLAUDE_PROJECT_DIR:-}\" ]; then\n printf '%s\\n' \"$CLAUDE_PROJECT_DIR\"\n return 0\n fi\n if root=$(_pf_git_root \"$PWD\"); then\n printf '%s\\n' \"$root\"\n return 0\n fi\n fi\n printf '%s\\n' \"$PWD\"\n}\n\n# The session's project: CLAUDE_PROJECT_DIR on Claude when set, else what\n# hook_project_dir finds. In a git worktree the two differ.\nhook_session_dir() {\n if [ \"$PLUGINFINITY_HOST\" = claude ] && [ -n \"${CLAUDE_PROJECT_DIR:-}\" ]; then\n printf '%s\\n' \"$CLAUDE_PROJECT_DIR\"\n return 0\n fi\n hook_project_dir\n}\n\n# cd into hook_project_dir, ignoring CDPATH and treating a leading dash as a path.\n# Writes nothing to stdout; on failure it logs through hook_log and returns non-zero.\nhook_cd_project() {\n local dir\n dir=$(hook_project_dir)\n CDPATH= cd -- \"$dir\" >/dev/null 2>&1 || {\n hook_log \"hook_cd_project: cannot cd to $dir\"\n return 1\n }\n}\n\n# Print the host's run-time spelling of a Claude run-time tool name and return\n# 0, or print nothing and return 1 when the host has none. An own MCP tool is\n# written mcp__plugin_<plugin>_<server>__<tool>, as Claude Code names it.\nhook_tool_name() {\n local name=${1:-} line plugin rest head seg server tool template\n [ -n \"$name\" ] || return 1\n while IFS= read -r line; do\n if [ \"${line%%=*}\" = \"$name\" ] && [ \"${line#*=}\" != \"$line\" ]; then\n printf '%s\\n' \"${line#*=}\"\n return 0\n fi\n done <<<\"$_PF_TOOLS\"\n plugin=${_PF_TOOLS_PLUGIN:-${PLUGINFINITY_PLUGIN:-}}\n case \"$name\" in\n \"mcp__plugin_${plugin}_\"*)\n rest=${name#\"mcp__plugin_${plugin}_\"}\n # Try each \"__\" as the server/tool boundary, as the build does.\n head=\"\"\n while [ \"${rest#*__}\" != \"$rest\" ]; do\n seg=${rest%%__*}\n rest=${rest#*__}\n server=\"${head:+${head}__}$seg\"\n tool=$rest\n head=$server\n [ -n \"$server\" ] && [ -n \"$tool\" ] && [ -n \"$_PF_TOOLS_MCP\" ] || continue\n case \" $_PF_TOOLS_SERVERS \" in\n *\" $server \"*)\n template=$_PF_TOOLS_MCP\n template=${template//\\{plugin\\}/$plugin}\n template=${template//\\{server\\}/$server}\n template=${template//\\{tool\\}/$tool}\n printf '%s\\n' \"$template\"\n return 0\n ;;\n esac\n done\n ;;\n esac\n [ \"$_PF_TOOLS_UNLISTED\" = keep ] || return 1\n printf '%s\\n' \"$name\"\n}\n\n# Whether this build ships a component: hook_has <monitor|skill|agent|server> <name>.\n# Returns 0 when it does, 1 when it does not (or tools.sh is missing), 2 for an\n# unknown kind. The lists are built per target, so a skill a target excludes and\n# a monitor on a host without monitors are absent.\nhook_has() {\n local kind=${1:-} name=${2:-} list\n case \"$kind\" in\n skill) list=$_PF_HAS_SKILLS ;;\n agent) list=$_PF_HAS_AGENTS ;;\n monitor) list=$_PF_HAS_MONITORS ;;\n server) list=$_PF_HAS_SERVERS ;;\n *)\n hook_log \"hook_has: unknown kind '$kind'\"\n return 2\n ;;\n esac\n [ -n \"$name\" ] || return 1\n case \" $list \" in\n *\" $name \"*) return 0 ;;\n esac\n return 1\n}\n\n# Print the run-time tool-name prefix of an own MCP server (Claude\n# mcp__plugin_<plugin>_<server>__, Copilot <server>-) and return 0, or print\n# nothing and return 1 for a server this plugin does not declare.\nhook_tool_prefix() {\n local server=${1:-} template plugin\n [ -n \"$server\" ] && [ -n \"$_PF_TOOLS_MCP\" ] || return 1\n case \" $_PF_TOOLS_SERVERS \" in\n *\" $server \"*) ;;\n *) return 1 ;;\n esac\n plugin=${_PF_TOOLS_PLUGIN:-${PLUGINFINITY_PLUGIN:-}}\n template=$_PF_TOOLS_MCP\n template=${template//\\{plugin\\}/$plugin}\n template=${template//\\{server\\}/$server}\n printf '%s\\n' \"${template%%\\{tool\\}*}\"\n}\n\n# Whether the host honours capability $1 on event $2 (default: this event).\n# Mirrors okf/references/{claude-code,copilot-cli}-plugin-format.md.\n# server-project asks about the host, not an event: whether an MCP server can\n# learn the project (Claude gives it CLAUDE_PROJECT_DIR and roots; Copilot\n# gives none, measured 2026-10-07), the question server_project_dir answers.\nhook_supports() {\n local cap=\"${1:-}\" event=\"${2:-$_pf_event}\"\n case \"$PLUGINFINITY_HOST:$cap\" in\n *:noop | *:raw) return 0 ;;\n claude:system_message)\n # The events whose systemMessage Claude Code discards, or delivers somewhere the user does not see.\n case \"$event\" in\n Setup | InstructionsLoaded | MessageDisplay | Notification | StopFailure | ConfigChange | DirectoryAdded | \\\n WorktreeCreate | WorktreeRemove | PreCompact | PostCompact | SessionEnd | Elicitation | ElicitationResult) return 1 ;;\n esac\n return 0\n ;;\n *:deny | *:allow | *:ask)\n [ \"$event\" = PreToolUse ] && return 0\n # Claude Code takes the same decision object on a model switch, and only a deny before a\n # skill's injected shell command (an allow there changes nothing; an ask is read as a deny).\n if [ \"$PLUGINFINITY_HOST\" = claude ]; then\n case \"$cap:$event\" in\n deny:PreModelSwitch | allow:PreModelSwitch | ask:PreModelSwitch | deny:PreSkillShellCommand) return 0 ;;\n esac\n fi\n ;;\n claude:context)\n case \"$event\" in\n SessionStart | SubagentStart | PostModelSwitch | UserPromptSubmit | UserPromptExpansion | PreToolUse | \\\n PostToolUse | PostToolUseFailure | PostToolBatch | Stop | SubagentStop) return 0 ;;\n esac\n ;;\n copilot:context)\n case \"$event\" in SessionStart | SubagentStart | PostToolUse | Notification) return 0 ;; esac\n ;;\n claude:block)\n case \"$event\" in\n UserPromptSubmit | UserPromptExpansion | PreSkillShellCommand | PostToolUse | PostToolBatch | Stop | \\\n SubagentStop | ConfigChange | PreCompact | TaskCreated | TaskCompleted | TeammateIdle | \\\n PreModelSwitch | Elicitation | ElicitationResult) return 0 ;;\n esac\n ;;\n copilot:block)\n case \"$event\" in Stop | SubagentStop) return 0 ;; esac\n ;;\n claude:server-project) return 0 ;;\n claude:env-shell)\n case \"$event\" in SessionStart | Setup | CwdChanged | FileChanged) return 0 ;; esac\n ;;\n esac\n return 1\n}\n\n# --- session env ---------------------------------------------------------\n\n# Whether env.sh is loaded: the build ships it only when the config declares env.\n_pf_env_loaded=0\n\n# Set a declared session variable (the run-time rung of the env chain): record\n# it in the session values file, export it in this hook and, on Claude, append\n# it to CLAUDE_ENV_FILE so the model's shell sees it. Only the events that can\n# produce a value (SessionStart, Setup, CwdChanged, FileChanged) may call it,\n# and only for a name the config declares. It always returns 0: a refusal (any\n# other event, an undeclared name, a value with a newline, a build with no env)\n# is a log line, or a debug line for an event that cannot produce, and changes\n# nothing, so it never aborts a `set -e` hook or denies a fail-closed one.\nhook_env_set() {\n local name=${1:-}\n if [ \"$_pf_env_loaded\" != 1 ]; then\n hook_log \"hook_env_set: no session env is declared in this build\"\n return 0\n fi\n case \"$_pf_event\" in\n SessionStart | Setup | CwdChanged | FileChanged) ;;\n *)\n hook_debug \"hook_env_set $name ignored: ${_pf_event:-an unknown event} does not produce session values\"\n return 0\n ;;\n esac\n _pf_env_set \"$name\" \"${2-}\" || true\n return 0\n}\n\n# Load env.sh and apply the session values. A failure here never aborts the hook, even under set -e.\n_pf_env_start() {\n local sid proj cwd errexit=0 nounset=0\n [ -r \"$_pf_log_dir/env.sh\" ] || return 0\n case $- in *e*) errexit=1 ;; esac\n case $- in *u*) nounset=1 ;; esac\n set +eu\n _pf_env_lib_dir=\"$_pf_log_dir\"\n _pf_env_manual=1\n _pf_env_component=hook\n # shellcheck source=/dev/null\n if . \"$_pf_log_dir/env.sh\" 2>/dev/null; then\n _pf_env_loaded=1\n sid=$(hook_input session_id)\n cwd=$(hook_input cwd)\n if [ \"$PLUGINFINITY_HOST\" = copilot ] && [ \"${cwd#/}\" = \"$cwd\" ]; then\n # The runner's rule: Copilot runs hooks from the plugin root, which is no\n # project, so with no absolute cwd read no .env (the session file or the defaults).\n proj=-\n else\n proj=$(_pf_env_project_of \"$(hook_project_dir)\")\n fi\n env_load \"$sid\" \"$proj\"\n else\n hook_log \"env.sh not loadable; session env skipped\"\n fi\n [ \"$errexit\" = 1 ] && set -e\n [ \"$nounset\" = 1 ] && set -u\n return 0\n}\n\n# --- output ---------------------------------------------------------------\n\n_pf_emit() { # json [kind]\n if [ -z \"${1:-}\" ]; then\n hook_log \"refused to send an empty response\"\n return 1\n fi\n if _pf_has_emitted; then\n hook_debug \"ignored a second response: $1\"\n return 0\n fi\n printf '%s' \"${_pf_kind_prefix}${2:-response}\" >\"$_pf_marker\" 2>/dev/null || true\n printf '%s\\n' \"$1\"\n}\n\n_pf_unsupported() { # function-name\n hook_debug \"$1 does nothing on $PLUGINFINITY_HOST for ${_pf_event:-an unknown event}\"\n hook_noop\n}\n\n_pf_permission() { # decision reason [updated-input-json]\n local key=updatedInput body u=null event=${_pf_event:-PreToolUse}\n [ \"$PLUGINFINITY_HOST\" = copilot ] && key=modifiedArgs\n if [ -n \"${3:-}\" ] && [ \"$event\" != PreToolUse ]; then\n hook_debug \"hook_allow: $event takes no updated input; sent the decision without it\"\n elif [ -n \"${3:-}\" ]; then\n u=$(printf '%s' \"$3\" | jq -c . 2>/dev/null) || {\n hook_log \"hook_allow: not JSON: $3\"\n return 1\n }\n fi\n body=$(jq -nc --arg d \"$1\" --arg r \"${2:-}\" --argjson u \"$u\" --arg k \"$key\" \\\n '{permissionDecision: $d}\n + (if $r == \"\" then {} else {permissionDecisionReason: $r} end)\n + (if $u == null then {} else {($k): $u} end)' 2>/dev/null) || return 1\n if [ \"$PLUGINFINITY_HOST\" != copilot ]; then\n body=$(jq -nc --argjson b \"$body\" --arg e \"$event\" '{hookSpecificOutput: ({hookEventName: $e} + $b)}') || return 1\n fi\n _pf_emit \"$body\" \"$1\"\n}\n\n# Respond with nothing to change.\nhook_noop() { _pf_emit '{}' noop; }\n\n# Add text to the model's context.\nhook_context() {\n hook_supports context || {\n _pf_unsupported hook_context\n return 0\n }\n local body\n if [ \"$PLUGINFINITY_HOST\" = copilot ]; then\n body=$(jq -nc --arg c \"${1:-}\" '{additionalContext: $c}') || return 1\n else\n body=$(jq -nc --arg e \"$_pf_event\" --arg c \"${1:-}\" \\\n '{hookSpecificOutput: {hookEventName: $e, additionalContext: $c}}') || return 1\n fi\n _pf_emit \"$body\" context\n}\n\n# Refuse the tool call (PreToolUse), and on Claude Code a model switch\n# (PreModelSwitch) or a skill's injected shell command (PreSkillShellCommand).\nhook_deny() {\n hook_supports deny || {\n _pf_unsupported hook_deny\n return 0\n }\n _pf_permission deny \"${1:-Blocked by ${PLUGINFINITY_PLUGIN:-a plugin}}\"\n}\n\n# PreToolUse: allow the tool call, with an optional reason and an optional\n# replacement input (JSON). On Claude Code it also allows a model switch\n# (PreModelSwitch), which takes no replacement input.\nhook_allow() {\n hook_supports allow || {\n _pf_unsupported hook_allow\n return 0\n }\n _pf_permission allow \"${1:-}\" \"${2:-}\"\n}\n\n# PreToolUse: ask the user. On Claude Code, also before a model switch (PreModelSwitch).\nhook_ask() {\n hook_supports ask || {\n _pf_unsupported hook_ask\n return 0\n }\n _pf_permission ask \"${1:-}\"\n}\n\n# Block the event's action with a reason (Stop: keep working on it).\nhook_block() {\n hook_supports block || {\n _pf_unsupported hook_block\n return 0\n }\n local body\n body=$(jq -nc --arg r \"${1:-Blocked by ${PLUGINFINITY_PLUGIN:-a plugin}}\" '{decision: \"block\", reason: $r}') || return 1\n _pf_emit \"$body\" block\n}\n\n# Show the user a message.\nhook_system_message() {\n hook_supports system_message || {\n _pf_unsupported hook_system_message\n return 0\n }\n local body\n body=$(jq -nc --arg m \"${1:-}\" '{systemMessage: $m}') || return 1\n _pf_emit \"$body\" system_message\n}\n\n# Print the input the way Claude would send it. On Copilot: hook_event_name\n# from hook_event, snake_case top-level keys (toolName/toolArgs become\n# tool_name/tool_input, parsed when a string), and Copilot's tool_input key\n# names mapped to Claude's where the Claude key is absent. On Claude: the\n# input unchanged, with hook_event_name filled in when missing.\nhook_envelope() {\n if [ \"${1:-}\" != claude ]; then\n hook_log \"hook_envelope: unknown target: ${1:-none}\"\n return 1\n fi\n local event\n event=$(hook_event 2>/dev/null) || event=\"\"\n printf '%s' \"$_pf_input\" | jq -c --arg event \"$event\" --arg host \"$PLUGINFINITY_HOST\" '\ndef snake: gsub(\"(?<c>[A-Z])\"; \"_\" + (.c | ascii_downcase));\ndef args: if type == \"string\" then (fromjson? // .) else . end;\ndef alias: {path: \"file_path\", file_text: \"content\", old_str: \"old_string\", new_str: \"new_string\"};\ndef fix: if type == \"object\" then\n . as $o | reduce (keys_unsorted[]) as $k ($o;\n if alias[$k] != null and (has(alias[$k]) | not) then . + {(alias[$k]): $o[$k]} else . end)\n else . end;\n(if $host == \"copilot\" then\n with_entries(.key |= (if . == \"toolName\" then \"tool_name\" elif . == \"toolArgs\" then \"tool_input\" else snake end))\n | if has(\"tool_input\") then .tool_input |= (args | fix) else . end\n else . end)\n| if (has(\"hook_event_name\") | not) and $event != \"\" then . + {hook_event_name: $event} else . end' 2>/dev/null || {\n hook_log \"hook_envelope: input is not a JSON object\"\n return 1\n }\n}\n\n# Map one Claude-shaped hook response onto this host's emitters. First match\n# wins: permission decision, block, additional context, system message, then\n# noop. Fields that lose or have no mapping are written to the debug log.\nhook_relay() {\n local plan kind reason input text path\n plan=$(printf '%s' \"${1:-}\" | jq -c '\nif type != \"object\" then error(\"not an object\") else . end\n| (.hookSpecificOutput | if type == \"object\" then . else {} end) as $h\n| ($h.permissionDecision) as $d\n| (if ($d == \"allow\" or $d == \"deny\" or $d == \"ask\") then\n {kind: $d, reason: ($h.permissionDecisionReason // \"\"), input: (if $d == \"allow\" and ($h.updatedInput != null) then ($h.updatedInput | tojson) else \"\" end), text: \"\",\n used: [\"hookSpecificOutput.permissionDecision\", \"hookSpecificOutput.permissionDecisionReason\", \"hookSpecificOutput.updatedInput\"]}\n elif .decision == \"block\" then\n {kind: \"block\", reason: (.reason // \"\"), input: \"\", text: \"\", used: [\"decision\", \"reason\"]}\n elif ($h.additionalContext != null) then\n {kind: \"context\", reason: \"\", input: \"\", text: ($h.additionalContext | if type == \"string\" then . else tojson end), used: [\"hookSpecificOutput.additionalContext\"]}\n elif .systemMessage != null then\n {kind: \"system_message\", reason: \"\", input: \"\", text: (.systemMessage | if type == \"string\" then . else tojson end), used: [\"systemMessage\"]}\n else {kind: \"noop\", reason: \"\", input: \"\", text: \"\", used: []} end) as $p\n| ([paths | select((length == 1 and (.[0] != \"hookSpecificOutput\" or ($h | length) == 0)) or (length == 2 and .[0] == \"hookSpecificOutput\" and (($h | length) > 0)))\n | join(\".\")] | map(select(. != \"hookSpecificOutput.hookEventName\"))) as $all\n| $p + {dropped: ($all - $p.used)}' 2>/dev/null) || {\n hook_log \"hook_relay: not a JSON object\"\n return 1\n }\n kind=$(jq -r .kind <<<\"$plan\")\n reason=$(jq -r .reason <<<\"$plan\")\n input=$(jq -r .input <<<\"$plan\")\n text=$(jq -r .text <<<\"$plan\")\n while IFS= read -r path; do\n [ -n \"$path\" ] && hook_debug \"hook_relay dropped $path\"\n done <<<\"$(jq -r '.dropped[]' <<<\"$plan\")\"\n case \"$kind\" in\n allow) hook_allow \"$reason\" \"$input\" ;;\n deny) hook_deny \"$reason\" ;;\n ask) hook_ask \"$reason\" ;;\n block) hook_block \"$reason\" ;;\n context) hook_context \"$text\" ;;\n system_message) hook_system_message \"$text\" ;;\n *) hook_noop ;;\n esac\n}\n\n# Wake the agent from a background hook, with a message it will read. Only an\n# entry that sets `asyncRewake: true` may: the build then passes\n# PLUGINFINITY_ASYNC_REWAKE=1, and this ends the script with the exit code the\n# host wakes on. On any other entry it logs and returns 0, since that exit code\n# would block the action instead. Call it at the top level, not in a subshell.\nhook_rewake() {\n if [ \"${PLUGINFINITY_ASYNC_REWAKE:-0}\" != 1 ]; then\n hook_log \"hook_rewake: this entry does not set asyncRewake; ignored\"\n return 0\n fi\n printf '%s\\n' \"${1:-}\" >&2\n _pf_rewake=1\n exit 2\n}\n\n# Emit a host-specific JSON response verbatim, only on that host.\nhook_raw() {\n if [ \"${1:-}\" != \"$PLUGINFINITY_HOST\" ]; then\n hook_debug \"hook_raw for ${1:-no host} skipped on $PLUGINFINITY_HOST\"\n return 0\n fi\n local body\n body=$(printf '%s' \"${2:-}\" | jq -c . 2>/dev/null) || {\n hook_log \"hook_raw: not JSON: ${2:-}\"\n return 1\n }\n _pf_emit \"$body\" raw\n}\n\ntrap _pf_on_exit EXIT\n\nif pf_debug_on; then hook_debug \"input: ${_pf_input:0:4000}\"; fi\n\n# --- matcher ---------------------------------------------------------------\n\n# A host that ignores an event's matcher (Copilot on SessionStart, SessionEnd\n# and SubagentStop) has the build pass it as PLUGINFINITY_MATCHER. Apply\n# Claude's rules here: empty or `*` matches all; only [A-Za-z0-9_| ,-] is an\n# exact list split on `|` or `,` with spaces around an item ignored; anything\n# else is an unanchored extended regex. No match ends\n# the script quietly, so nothing is emitted and the exit is 0.\n_pf_matcher_applies() { # matcher value\n local m=$1 v=$2 item\n local -a items\n { [ -z \"$m\" ] || [ \"$m\" = '*' ]; } && return 0\n if [[ ! \"$m\" =~ [^A-Za-z0-9_\\|\\ ,-] ]]; then\n IFS='|,' read -r -a items <<<\"$m\"\n for item in \"${items[@]}\"; do\n item=\"${item#\"${item%%[![:space:]]*}\"}\"\n item=\"${item%\"${item##*[![:space:]]}\"}\"\n [ \"$item\" = \"$v\" ] && return 0\n done\n return 1\n fi\n printf '%s' \"$v\" | grep -Eq -- \"$m\" 2>/dev/null\n}\n\nif [ -n \"${PLUGINFINITY_MATCHER+x}\" ]; then\n _pf_match_field=\"\"\n case \"$_pf_event\" in\n SessionStart) _pf_match_field=source ;;\n SessionEnd) _pf_match_field=reason ;;\n SubagentStop) _pf_match_field=agent_type ;;\n esac\n if [ -n \"$_pf_match_field\" ]; then\n _pf_match_value=$(hook_input \"$_pf_match_field\")\n if ! _pf_matcher_applies \"$PLUGINFINITY_MATCHER\" \"$_pf_match_value\"; then\n hook_debug \"matcher $PLUGINFINITY_MATCHER did not match $_pf_match_value\"\n exit 0\n fi\n fi\nfi\n\n# --- session env ------------------------------------------------------------\n\n# After the matcher, so a skipped hook does not pay for it. A build with no\n# env.sh has no session env and this does nothing.\n_pf_env_start\n"
|
|
6
6
|
}];
|
|
7
7
|
|
|
8
8
|
export { HOOK_LIB_FILES };
|
package/hooks.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { hookHandler } from "@pluginfinity/core";
|
|
2
|
+
|
|
1
3
|
// src/hooks.ts
|
|
2
4
|
/**
|
|
3
5
|
* The hooks a target builds, before rendering: the base `hooks` with the
|
|
@@ -19,20 +21,33 @@ const targetHooks = (target, id, config) => {
|
|
|
19
21
|
const events = [];
|
|
20
22
|
const unsupported = [];
|
|
21
23
|
const omitted = [];
|
|
22
|
-
|
|
23
|
-
|
|
24
|
+
const unsupportedHandlers = [];
|
|
25
|
+
for (const [event, all] of Object.entries(merged)) {
|
|
26
|
+
if (all === void 0 || all.length === 0) continue;
|
|
24
27
|
const mapped = target.hooks.ownEvents.includes(event) ? event : target.hooks.events[event];
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
28
|
+
const entries = typeof mapped === "string" ? all.filter((entry) => {
|
|
29
|
+
const handler = hookHandler(entry);
|
|
30
|
+
if (target.hooks.handlers.includes(handler)) return true;
|
|
31
|
+
if (entry.fallback === "omit") omitted.push(`${event} (${handler})`);
|
|
32
|
+
else unsupportedHandlers.push({
|
|
33
|
+
event,
|
|
34
|
+
handler
|
|
35
|
+
});
|
|
36
|
+
return false;
|
|
37
|
+
}) : all;
|
|
38
|
+
if (typeof mapped === "string") {
|
|
39
|
+
if (entries.length > 0) events.push({
|
|
40
|
+
event,
|
|
41
|
+
name: mapped,
|
|
42
|
+
entries
|
|
43
|
+
});
|
|
44
|
+
} else if (entries.some((entry) => entry.fallback !== "omit")) unsupported.push({ event });
|
|
31
45
|
else omitted.push(event);
|
|
32
46
|
}
|
|
33
47
|
return {
|
|
34
48
|
events,
|
|
35
49
|
unsupported,
|
|
50
|
+
unsupportedHandlers,
|
|
36
51
|
omitted
|
|
37
52
|
};
|
|
38
53
|
};
|
|
@@ -42,6 +57,128 @@ const targetHooks = (target, id, config) => {
|
|
|
42
57
|
* @public
|
|
43
58
|
*/
|
|
44
59
|
const hookScripts = (events) => [...new Set(events.flatMap((event) => event.entries.flatMap((entry) => "script" in entry ? [entry.script] : [])))];
|
|
60
|
+
/**
|
|
61
|
+
* Every `binary` path prefix the given events run.
|
|
62
|
+
*
|
|
63
|
+
* @public
|
|
64
|
+
*/
|
|
65
|
+
const hookBinaries = (events) => [...new Set(events.flatMap((event) => event.entries.flatMap((entry) => "binary" in entry ? [entry.binary] : [])))];
|
|
66
|
+
/**
|
|
67
|
+
* The `sh -c` program a `binary` entry runs: `$0` is the binary's path prefix,
|
|
68
|
+
* `$1` the plugin root (handed to the program as `PLUGINFINITY_ROOT`, where it
|
|
69
|
+
* finds the facts the build wrote for it), and the file for this machine is
|
|
70
|
+
* named after what `uname` prints. Under Git Bash on Windows the system reads
|
|
71
|
+
* as `Windows` and the file ends in `.exe`. A machine
|
|
72
|
+
* the plugin ships no binary for exits 0 with no output, so the hook fails
|
|
73
|
+
* open there; on a `failClosed` entry it exits 1, which Claude Code blocks on
|
|
74
|
+
* (`onFailure`) and Copilot reads as a deny on `preToolUse`. It holds no
|
|
75
|
+
* single quote, so it can sit inside a pair.
|
|
76
|
+
*
|
|
77
|
+
* @public
|
|
78
|
+
*/
|
|
79
|
+
const BINARY_DISPATCH = "r=$1; shift; s=$(uname -s); e=; case \"$s\" in MINGW*|MSYS*|CYGWIN*) s=Windows; e=.exe;; esac; b=\"$0-$s-$(uname -m)$e\"; [ -x \"$b\" ] || exit \"${PLUGINFINITY_FAIL_CLOSED:-0}\"; PLUGINFINITY_ROOT=\"$r\" exec \"$b\" \"$@\"";
|
|
80
|
+
const ON_FAILURE_INERT = /* @__PURE__ */ new Set([
|
|
81
|
+
"Stop",
|
|
82
|
+
"SubagentStop",
|
|
83
|
+
"TaskCompleted",
|
|
84
|
+
"TeammateIdle"
|
|
85
|
+
]);
|
|
86
|
+
/**
|
|
87
|
+
* Claude Code's `onFailure` for an entry: `{ onFailure: "block" }` when the
|
|
88
|
+
* entry is `failClosed` and the event honours it, so a hook the host cannot
|
|
89
|
+
* start, that times out or that prints unreadable output stops the action too.
|
|
90
|
+
* The hook library covers a failure inside a running script; this covers the
|
|
91
|
+
* ones no script can.
|
|
92
|
+
*
|
|
93
|
+
* @public
|
|
94
|
+
*/
|
|
95
|
+
const onFailure = (event, entry) => entry.failClosed === true && !ON_FAILURE_INERT.has(event) && !BACKGROUND(entry) && READS_ON_FAILURE.has(hookHandler(entry)) ? { onFailure: "block" } : {};
|
|
96
|
+
const READS_ON_FAILURE = /* @__PURE__ */ new Set([
|
|
97
|
+
"command",
|
|
98
|
+
"http",
|
|
99
|
+
"mcp_tool"
|
|
100
|
+
]);
|
|
101
|
+
const BACKGROUND = (entry) => "async" in entry && entry.async === true || "asyncRewake" in entry && entry.asyncRewake === true;
|
|
102
|
+
/**
|
|
103
|
+
* The events a hook's `if` condition is evaluated on. Elsewhere Claude Code
|
|
104
|
+
* never runs a hook that sets one.
|
|
105
|
+
*
|
|
106
|
+
* @public
|
|
107
|
+
*/
|
|
108
|
+
const IF_EVENTS = [
|
|
109
|
+
"PreToolUse",
|
|
110
|
+
"PostToolUse",
|
|
111
|
+
"PostToolUseFailure",
|
|
112
|
+
"PermissionRequest",
|
|
113
|
+
"PermissionDenied",
|
|
114
|
+
"PreSkillShellCommand"
|
|
115
|
+
];
|
|
116
|
+
const ALL_HANDLER_EVENTS = /* @__PURE__ */ new Set([
|
|
117
|
+
"PermissionDenied",
|
|
118
|
+
"PostToolBatch",
|
|
119
|
+
"PostToolUse",
|
|
120
|
+
"PostToolUseFailure",
|
|
121
|
+
"PreToolUse",
|
|
122
|
+
"Stop",
|
|
123
|
+
"SubagentStop",
|
|
124
|
+
"TaskCompleted",
|
|
125
|
+
"TaskCreated",
|
|
126
|
+
"TeammateIdle",
|
|
127
|
+
"UserPromptExpansion",
|
|
128
|
+
"UserPromptSubmit"
|
|
129
|
+
]);
|
|
130
|
+
/**
|
|
131
|
+
* The handler kinds Claude Code runs on an event: all five on the events that
|
|
132
|
+
* can ask a model, no `agent` on `PermissionRequest`, only `command` on
|
|
133
|
+
* `Setup`, only `command` and `mcp_tool` on `SessionStart`, and no `prompt` or
|
|
134
|
+
* `agent` anywhere else.
|
|
135
|
+
*
|
|
136
|
+
* @public
|
|
137
|
+
*/
|
|
138
|
+
const eventHandlers = (event) => ALL_HANDLER_EVENTS.has(event) ? [
|
|
139
|
+
"command",
|
|
140
|
+
"http",
|
|
141
|
+
"mcp_tool",
|
|
142
|
+
"prompt",
|
|
143
|
+
"agent"
|
|
144
|
+
] : event === "PermissionRequest" ? [
|
|
145
|
+
"command",
|
|
146
|
+
"http",
|
|
147
|
+
"mcp_tool",
|
|
148
|
+
"prompt"
|
|
149
|
+
] : event === "Setup" ? ["command"] : event === "SessionStart" ? ["command", "mcp_tool"] : [
|
|
150
|
+
"command",
|
|
151
|
+
"http",
|
|
152
|
+
"mcp_tool"
|
|
153
|
+
];
|
|
154
|
+
/**
|
|
155
|
+
* The problems in one event's entries, in Claude Code's terms, which the
|
|
156
|
+
* config is written in.
|
|
157
|
+
*
|
|
158
|
+
* @public
|
|
159
|
+
*/
|
|
160
|
+
const hookProblems = (event, entries, prefix = "hooks") => entries.flatMap((entry, index) => {
|
|
161
|
+
const key = `${prefix}.${event}[${index}]`;
|
|
162
|
+
const handler = hookHandler(entry);
|
|
163
|
+
const found = [];
|
|
164
|
+
if (entry.if !== void 0 && !IF_EVENTS.includes(event)) found.push({
|
|
165
|
+
key: `${key}.if`,
|
|
166
|
+
message: `is only evaluated on ${IF_EVENTS.join(", ")}; on ${event} the hook would never run`
|
|
167
|
+
});
|
|
168
|
+
if (!eventHandlers(event).includes(handler)) found.push({
|
|
169
|
+
key,
|
|
170
|
+
message: `is a ${handler} hook, and ${event} runs only ${eventHandlers(event).join(", ")} hooks`
|
|
171
|
+
});
|
|
172
|
+
if (entry.failClosed === true && BACKGROUND(entry)) found.push({
|
|
173
|
+
key: `${key}.failClosed`,
|
|
174
|
+
message: "has no effect on a background hook, which cannot stop the action it follows"
|
|
175
|
+
});
|
|
176
|
+
if (entry.failClosed === true && !READS_ON_FAILURE.has(handler)) found.push({
|
|
177
|
+
key: `${key}.failClosed`,
|
|
178
|
+
message: `has no effect on a ${handler} hook`
|
|
179
|
+
});
|
|
180
|
+
return found;
|
|
181
|
+
});
|
|
45
182
|
const COMMAND_FILE = /\$\{PLUGIN_ROOT\}\/([^\s"'`;|&<>()$]+)/g;
|
|
46
183
|
/**
|
|
47
184
|
* Every file a command names as `${PLUGIN_ROOT}/<path>`, in order.
|
|
@@ -68,10 +205,15 @@ const SAFE_PATH = /^[A-Za-z0-9_\-./@%+,=:]+$/;
|
|
|
68
205
|
*
|
|
69
206
|
* @public
|
|
70
207
|
*/
|
|
71
|
-
const entryEnv = (event, entry, matcher) => ({
|
|
208
|
+
const entryEnv = (event, entry, matcher, facts) => ({
|
|
72
209
|
PLUGINFINITY_EVENT: event,
|
|
73
210
|
...entry.failClosed === true ? { PLUGINFINITY_FAIL_CLOSED: "1" } : {},
|
|
74
|
-
...matcher === void 0 ? {} : { PLUGINFINITY_MATCHER: matcher }
|
|
211
|
+
...matcher === void 0 ? {} : { PLUGINFINITY_MATCHER: matcher },
|
|
212
|
+
..."binary" in entry && facts !== void 0 ? {
|
|
213
|
+
PLUGINFINITY_HOST: facts.host,
|
|
214
|
+
PLUGINFINITY_PLUGIN: facts.plugin
|
|
215
|
+
} : {},
|
|
216
|
+
..."asyncRewake" in entry && entry.asyncRewake === true ? { PLUGINFINITY_ASYNC_REWAKE: "1" } : {}
|
|
75
217
|
});
|
|
76
218
|
const quoteValue = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
|
|
77
219
|
/**
|
|
@@ -84,7 +226,8 @@ const shellEnvPrefix = (env) => Object.entries(env).map(([key, value]) => `${key
|
|
|
84
226
|
/**
|
|
85
227
|
* The shell command a hook entry runs on a target: a `script` through `bash`
|
|
86
228
|
* (or executed directly under `scripts.invoke: "exec"`) at the target's
|
|
87
|
-
* plugin root,
|
|
229
|
+
* plugin root, a `binary` through the platform dispatch, or a `command` with
|
|
230
|
+
* `${PLUGIN_ROOT}` spelled the target's way.
|
|
88
231
|
*
|
|
89
232
|
* @public
|
|
90
233
|
*/
|
|
@@ -94,12 +237,22 @@ const hookCommand = (entry, root, invoke, env = {}) => {
|
|
|
94
237
|
const command = entry.command.replaceAll(PLUGIN_ROOT, root);
|
|
95
238
|
return pairs.length === 0 ? command : `${pairs.map((pair) => `export ${pair};`).join(" ")} ${command}`;
|
|
96
239
|
}
|
|
97
|
-
|
|
240
|
+
if (!("binary" in entry) && !("script" in entry)) throw new Error(`a ${hookHandler(entry)} hook has no command; the build leaves it out of a target that runs commands only`);
|
|
241
|
+
const file = "binary" in entry ? entry.binary : entry.script;
|
|
242
|
+
const path = SAFE_PATH.test(file) ? `"${root}/${file}"` : `"${root}"/${shellQuote(file)}`;
|
|
98
243
|
const args = (entry.args ?? []).map(shellQuote);
|
|
244
|
+
if ("binary" in entry) return [
|
|
245
|
+
"sh",
|
|
246
|
+
"-c",
|
|
247
|
+
`'${BINARY_DISPATCH}'`,
|
|
248
|
+
path,
|
|
249
|
+
`"${root}"`,
|
|
250
|
+
...args
|
|
251
|
+
].join(" ");
|
|
99
252
|
return [...invoke === "bash" ? ["bash", path] : [path], ...args].join(" ");
|
|
100
253
|
};
|
|
101
254
|
/**
|
|
102
|
-
* A `script` entry in exec form, for a host that spawns `command` with `args`
|
|
255
|
+
* A `script` or `binary` entry in exec form, for a host that spawns `command` with `args`
|
|
103
256
|
* and no shell: `bash` with the script path as its first argument, or under
|
|
104
257
|
* `scripts.invoke: "exec"` the script itself. The root placeholder is
|
|
105
258
|
* substituted by the host in `args`, and no shell ever parses the path.
|
|
@@ -107,9 +260,26 @@ const hookCommand = (entry, root, invoke, env = {}) => {
|
|
|
107
260
|
* @public
|
|
108
261
|
*/
|
|
109
262
|
const hookExec = (entry, root, invoke, env = {}) => {
|
|
110
|
-
const path = `${root}/${entry.script}`;
|
|
111
263
|
const args = [...entry.args ?? []];
|
|
112
264
|
const pairs = Object.entries(env).map(([key, value]) => `${key}=${value}`);
|
|
265
|
+
if ("binary" in entry) {
|
|
266
|
+
const dispatch = [
|
|
267
|
+
"sh",
|
|
268
|
+
"-c",
|
|
269
|
+
BINARY_DISPATCH,
|
|
270
|
+
`${root}/${entry.binary}`,
|
|
271
|
+
root,
|
|
272
|
+
...args
|
|
273
|
+
];
|
|
274
|
+
return pairs.length > 0 ? {
|
|
275
|
+
command: "env",
|
|
276
|
+
args: [...pairs, ...dispatch]
|
|
277
|
+
} : {
|
|
278
|
+
command: "sh",
|
|
279
|
+
args: dispatch.slice(1)
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
const path = `${root}/${entry.script}`;
|
|
113
283
|
if (pairs.length > 0) return {
|
|
114
284
|
command: "env",
|
|
115
285
|
args: [
|
|
@@ -129,12 +299,19 @@ const hookExec = (entry, root, invoke, env = {}) => {
|
|
|
129
299
|
};
|
|
130
300
|
const EXACT_LIST = /^[A-Za-z0-9_| ,-]*$/;
|
|
131
301
|
/**
|
|
302
|
+
* Whether Claude Code reads a matcher as a regular expression: anything but
|
|
303
|
+
* empty, `*`, or an exact list of letters, digits, `_`, `-`, spaces, `,` and `|`.
|
|
304
|
+
*
|
|
305
|
+
* @public
|
|
306
|
+
*/
|
|
307
|
+
const isRegexMatcher = (matcher) => matcher !== "" && matcher !== "*" && !EXACT_LIST.test(matcher);
|
|
308
|
+
/**
|
|
132
309
|
* How a host that ignores the SessionStart matcher is told a matcher: a host
|
|
133
310
|
* names a fresh session's source `new` where Claude says `startup`, so a
|
|
134
311
|
* matcher that matches `startup` must match `new` too.
|
|
135
312
|
*
|
|
136
313
|
* An exact list holding `startup` gains `new` right after it (`startup|resume`
|
|
137
|
-
* becomes `startup|new|resume`); one that already holds `new`, an empty or `*`
|
|
314
|
+
* becomes `startup|new|resume`, as does `startup, resume`); one that already holds `new`, an empty or `*`
|
|
138
315
|
* matcher and any matcher not matching `startup` stay as written. A regex
|
|
139
316
|
* that matches `startup` but not `new` also stays as written, reported as
|
|
140
317
|
* `unwidened` so the build can note it. The regex is tried as a JavaScript
|
|
@@ -151,7 +328,7 @@ const sessionStartMatcher = (matcher) => {
|
|
|
151
328
|
};
|
|
152
329
|
if (matcher === "" || matcher === "*") return same;
|
|
153
330
|
if (EXACT_LIST.test(matcher)) {
|
|
154
|
-
const items = matcher.split(
|
|
331
|
+
const items = matcher.split(/[|,]/).map((item) => item.trim());
|
|
155
332
|
const at = items.indexOf("startup");
|
|
156
333
|
if (at === -1 || items.includes("new")) return same;
|
|
157
334
|
items.splice(at + 1, 0, "new");
|
|
@@ -179,23 +356,64 @@ const sessionStartMatcher = (matcher) => {
|
|
|
179
356
|
*/
|
|
180
357
|
const widensSessionStart = (ignored, event) => event === "SessionStart" && ignored.includes(event);
|
|
181
358
|
const runtimeMatcher = (ignored, event, entry) => ignored.includes(event) ? entry.matcher !== void 0 && widensSessionStart(ignored, event) ? sessionStartMatcher(entry.matcher).matcher : entry.matcher : void 0;
|
|
359
|
+
const present = (key, value) => value === void 0 ? {} : { [key]: value };
|
|
360
|
+
const claudeHandler = (event, entry, command, exec, ignored, facts) => {
|
|
361
|
+
if ("http" in entry) return {
|
|
362
|
+
type: "http",
|
|
363
|
+
url: entry.http,
|
|
364
|
+
...present("headers", entry.headers),
|
|
365
|
+
...present("allowedEnvVars", entry.allowedEnvVars)
|
|
366
|
+
};
|
|
367
|
+
if ("mcpTool" in entry) return {
|
|
368
|
+
type: "mcp_tool",
|
|
369
|
+
server: facts?.servers?.has(entry.mcpTool.server) === true ? `plugin:${facts?.plugin ?? ""}:${entry.mcpTool.server}` : entry.mcpTool.server,
|
|
370
|
+
tool: entry.mcpTool.tool,
|
|
371
|
+
...present("input", entry.mcpTool.input)
|
|
372
|
+
};
|
|
373
|
+
if ("prompt" in entry) return {
|
|
374
|
+
type: "prompt",
|
|
375
|
+
prompt: entry.prompt,
|
|
376
|
+
...present("model", entry.model),
|
|
377
|
+
...present("continueOnBlock", entry.continueOnBlock)
|
|
378
|
+
};
|
|
379
|
+
if ("agent" in entry) return {
|
|
380
|
+
type: "agent",
|
|
381
|
+
prompt: entry.agent,
|
|
382
|
+
...present("model", entry.model)
|
|
383
|
+
};
|
|
384
|
+
const env = entryEnv(event, entry, runtimeMatcher(ignored, event, entry), facts);
|
|
385
|
+
return {
|
|
386
|
+
type: "command",
|
|
387
|
+
..."command" in entry ? {
|
|
388
|
+
command: command(entry, env),
|
|
389
|
+
...present("shell", entry.shell)
|
|
390
|
+
} : exec(entry, env),
|
|
391
|
+
..."async" in entry ? present("async", entry.async) : {},
|
|
392
|
+
..."asyncRewake" in entry ? present("asyncRewake", entry.asyncRewake) : {}
|
|
393
|
+
};
|
|
394
|
+
};
|
|
182
395
|
const FORMATS = {
|
|
183
|
-
"claude-hooks-json": (events, command, exec, ignored
|
|
184
|
-
...
|
|
185
|
-
hooks: [{
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
396
|
+
"claude-hooks-json": (events, command, exec, ignored, facts) => ({
|
|
397
|
+
...present("description", facts?.description),
|
|
398
|
+
hooks: Object.fromEntries(events.map(({ event, name, entries }) => [name, entries.map((entry) => ({
|
|
399
|
+
...entry.matcher === void 0 || ignored.includes(event) ? {} : { matcher: entry.matcher },
|
|
400
|
+
hooks: [{
|
|
401
|
+
...claudeHandler(event, entry, command, exec, ignored, facts),
|
|
402
|
+
...present("if", entry.if),
|
|
403
|
+
...present("timeout", entry.timeout),
|
|
404
|
+
...present("statusMessage", entry.statusMessage),
|
|
405
|
+
...onFailure(event, entry)
|
|
406
|
+
}]
|
|
407
|
+
}))]))
|
|
408
|
+
}),
|
|
409
|
+
"copilot-hooks-v1": (events, command, _exec, ignored, facts) => ({
|
|
192
410
|
version: 1,
|
|
193
411
|
hooks: Object.fromEntries(events.map(({ event, name, entries }) => [name, entries.map((entry) => ({
|
|
194
412
|
type: "command",
|
|
195
413
|
bash: command(entry),
|
|
196
414
|
...entry.matcher === void 0 || ignored.includes(event) ? {} : { matcher: entry.matcher },
|
|
197
415
|
...entry.timeout === void 0 ? {} : { timeoutSec: entry.timeout },
|
|
198
|
-
env: entryEnv(event, entry, runtimeMatcher(ignored, event, entry))
|
|
416
|
+
env: entryEnv(event, entry, runtimeMatcher(ignored, event, entry), facts)
|
|
199
417
|
}))]))
|
|
200
418
|
})
|
|
201
419
|
};
|
|
@@ -205,11 +423,11 @@ const FORMATS = {
|
|
|
205
423
|
*
|
|
206
424
|
* @public
|
|
207
425
|
*/
|
|
208
|
-
const renderHooks = (target, events, invoke) => {
|
|
426
|
+
const renderHooks = (target, events, invoke, facts) => {
|
|
209
427
|
if (events.length === 0) return void 0;
|
|
210
428
|
const root = target.pluginRoot.hooks;
|
|
211
429
|
if (typeof root !== "string") throw new Error(`target has no plugin-root spelling for hook commands: ${root.note}`);
|
|
212
|
-
return `${JSON.stringify(FORMATS[target.hooks.format](events, (entry, env) => hookCommand(entry, root, invoke, env), (entry, env) => hookExec(entry, root, invoke, env), target.hooks.matcherIgnored), null, " ")}\n`;
|
|
430
|
+
return `${JSON.stringify(FORMATS[target.hooks.format](events, (entry, env) => hookCommand(entry, root, invoke, env), (entry, env) => hookExec(entry, root, invoke, env), target.hooks.matcherIgnored, facts), null, " ")}\n`;
|
|
213
431
|
};
|
|
214
432
|
|
|
215
|
-
export { commandFiles, entryEnv, hookCommand, hookCommandFiles, hookExec, hookScripts, renderHooks, sessionStartMatcher, shellEnvPrefix, targetHooks, widensSessionStart };
|
|
433
|
+
export { BINARY_DISPATCH, IF_EVENTS, commandFiles, entryEnv, eventHandlers, hookBinaries, hookCommand, hookCommandFiles, hookExec, hookProblems, hookScripts, isRegexMatcher, onFailure, renderHooks, sessionStartMatcher, shellEnvPrefix, targetHooks, widensSessionStart };
|
package/index.d.ts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
*
|
|
10
10
|
* @packageDocumentation
|
|
11
11
|
*/
|
|
12
|
-
import { AgentFrontmatter, EnvConfig, FieldMapEntry, HookEntry, MonitorEntry, SkillFrontmatter, Target } from "@pluginfinity/core";
|
|
12
|
+
import { AgentFrontmatter, EnvConfig, FieldMapEntry, HookEntry, HookHandler, MonitorEntry, SkillFrontmatter, Target } from "@pluginfinity/core";
|
|
13
13
|
import { KnownTargetId, PluginfinityConfig } from "@pluginfinity/targets";
|
|
14
14
|
import { Duration, Effect, FileSystem, Layer, Path, PlatformError, Schema } from "effect";
|
|
15
15
|
import { Remediation } from "@effected/kit";
|
|
@@ -274,6 +274,8 @@ declare const HookEventUnsupported_base: Schema.Class<HookEventUnsupported, Sche
|
|
|
274
274
|
readonly path: Schema.String;
|
|
275
275
|
readonly target: Schema.String;
|
|
276
276
|
readonly events: Schema.$Array<Schema.String>;
|
|
277
|
+
/** Entries on events the target has, whose handler kind it cannot run, as `<Event> (<handler>)`. */
|
|
278
|
+
readonly handlers: Schema.optionalKey<Schema.$Array<Schema.String>>;
|
|
277
279
|
}>, import("effect/Cause").YieldableError>;
|
|
278
280
|
/**
|
|
279
281
|
* A target lacks a hook event the config uses, and an entry for it does not
|
|
@@ -287,17 +289,18 @@ export declare class HookEventUnsupported extends HookEventUnsupported_base {
|
|
|
287
289
|
}
|
|
288
290
|
/**
|
|
289
291
|
* What is wrong with a hook script: absent from the plugin, or lacking the
|
|
290
|
-
* executable bit under `scripts.invoke: "exec"`.
|
|
292
|
+
* executable bit under `scripts.invoke: "exec"`. A hook `binary` is always
|
|
293
|
+
* executed, so one without the bit is `binary-not-executable`.
|
|
291
294
|
*
|
|
292
295
|
* @public
|
|
293
296
|
*/
|
|
294
|
-
export declare const HookScriptProblem: Schema.Literals<readonly ["missing", "not-executable", "equals-in-path"]>;
|
|
297
|
+
export declare const HookScriptProblem: Schema.Literals<readonly ["missing", "not-executable", "equals-in-path", "binary-not-executable"]>;
|
|
295
298
|
declare const HookScriptInvalid_base: Schema.Class<HookScriptInvalid, Schema.TaggedStruct<"HookScriptInvalid", {
|
|
296
299
|
/** The config. */
|
|
297
300
|
readonly path: Schema.String;
|
|
298
301
|
/** The script, relative to the plugin root. */
|
|
299
302
|
readonly script: Schema.String;
|
|
300
|
-
readonly problem: Schema.Literals<readonly ["missing", "not-executable", "equals-in-path"]>;
|
|
303
|
+
readonly problem: Schema.Literals<readonly ["missing", "not-executable", "equals-in-path", "binary-not-executable"]>;
|
|
301
304
|
/** The component that runs the script: `hooks`, `monitors`, or `env` for the `env.setup` script. */
|
|
302
305
|
readonly component: Schema.Literals<readonly ["hooks", "monitors", "env"]>;
|
|
303
306
|
}>, import("effect/Cause").YieldableError>;
|
|
@@ -408,7 +411,7 @@ export declare const isBuildError: (error: unknown) => error is BuildError;
|
|
|
408
411
|
*
|
|
409
412
|
* @public
|
|
410
413
|
*/
|
|
411
|
-
export declare const BUILD_NOTE_KINDS: readonly ["dropped", "degraded", "tool-dropped", "hook-matcher-runtime", "hook-output-ignored", "hook-omitted", "monitor-omitted", "env-shell-unsupported", "env-wait-timeout", "hook-matcher-widened", "hook-matcher-regex"];
|
|
414
|
+
export declare const BUILD_NOTE_KINDS: readonly ["dropped", "degraded", "tool-dropped", "hook-matcher-runtime", "hook-output-ignored", "hook-omitted", "monitor-omitted", "env-shell-unsupported", "env-wait-timeout", "hook-matcher-widened", "hook-matcher-regex", "hook-matcher-native-regex", "hook-field-dropped"];
|
|
412
415
|
/**
|
|
413
416
|
* What a target did to something it could not carry as written: `dropped` a
|
|
414
417
|
* field, `degraded` a field into another form (a description suffix or a body
|
|
@@ -423,7 +426,11 @@ export declare const BUILD_NOTE_KINDS: readonly ["dropped", "degraded", "tool-dr
|
|
|
423
426
|
* (`env-wait-timeout`), or widened a SessionStart matcher that matches
|
|
424
427
|
* `startup` to match a host's `new` source too (`hook-matcher-widened`), or left
|
|
425
428
|
* a regex matcher as written that matches `startup` but not `new`
|
|
426
|
-
* (`hook-matcher-regex`)
|
|
429
|
+
* (`hook-matcher-regex`), or met a regular-expression matcher on a `binary`
|
|
430
|
+
* hook where the host ignores the matcher, which the native library applies only
|
|
431
|
+
* when the hooks were built with regex support (`hook-matcher-native-regex`),
|
|
432
|
+
* or left out a hook entry field the host's hooks format has no place for, such
|
|
433
|
+
* as `if` or `async` (`hook-field-dropped`).
|
|
427
434
|
*
|
|
428
435
|
* @public
|
|
429
436
|
*/
|
|
@@ -948,6 +955,16 @@ interface TargetHookEvent {
|
|
|
948
955
|
interface UnsupportedHookEvent {
|
|
949
956
|
readonly event: string;
|
|
950
957
|
}
|
|
958
|
+
/**
|
|
959
|
+
* A hook entry whose handler kind the target cannot run, with `fallback`
|
|
960
|
+
* `"fail"`, the default.
|
|
961
|
+
*
|
|
962
|
+
* @public
|
|
963
|
+
*/
|
|
964
|
+
interface UnsupportedHookHandler {
|
|
965
|
+
readonly event: string;
|
|
966
|
+
readonly handler: HookHandler;
|
|
967
|
+
}
|
|
951
968
|
/**
|
|
952
969
|
* The hooks a target builds, before rendering: the base `hooks` with the
|
|
953
970
|
* target's per-event overrides applied (an override replaces the base entries
|
|
@@ -961,7 +978,12 @@ interface UnsupportedHookEvent {
|
|
|
961
978
|
export declare const targetHooks: (target: Target, id: KnownTargetId, config: PluginfinityConfig) => {
|
|
962
979
|
readonly events: ReadonlyArray<TargetHookEvent>;
|
|
963
980
|
readonly unsupported: ReadonlyArray<UnsupportedHookEvent>;
|
|
964
|
-
/**
|
|
981
|
+
/** Entries whose handler kind the target cannot run, and that do not set `fallback: "omit"`. */
|
|
982
|
+
readonly unsupportedHandlers: ReadonlyArray<UnsupportedHookHandler>;
|
|
983
|
+
/**
|
|
984
|
+
* Source event names the target lacks whose every entry sets `fallback: "omit"`, and, as
|
|
985
|
+
* `<Event> (<handler>)`, each entry left out because the target cannot run its handler kind.
|
|
986
|
+
*/
|
|
965
987
|
readonly omitted: ReadonlyArray<string>;
|
|
966
988
|
};
|
|
967
989
|
/**
|
|
@@ -970,6 +992,75 @@ export declare const targetHooks: (target: Target, id: KnownTargetId, config: Pl
|
|
|
970
992
|
* @public
|
|
971
993
|
*/
|
|
972
994
|
export declare const hookScripts: (events: ReadonlyArray<TargetHookEvent>) => ReadonlyArray<string>;
|
|
995
|
+
/**
|
|
996
|
+
* Every `binary` path prefix the given events run.
|
|
997
|
+
*
|
|
998
|
+
* @public
|
|
999
|
+
*/
|
|
1000
|
+
export declare const hookBinaries: (events: ReadonlyArray<TargetHookEvent>) => ReadonlyArray<string>;
|
|
1001
|
+
/**
|
|
1002
|
+
* The `sh -c` program a `binary` entry runs: `$0` is the binary's path prefix,
|
|
1003
|
+
* `$1` the plugin root (handed to the program as `PLUGINFINITY_ROOT`, where it
|
|
1004
|
+
* finds the facts the build wrote for it), and the file for this machine is
|
|
1005
|
+
* named after what `uname` prints. Under Git Bash on Windows the system reads
|
|
1006
|
+
* as `Windows` and the file ends in `.exe`. A machine
|
|
1007
|
+
* the plugin ships no binary for exits 0 with no output, so the hook fails
|
|
1008
|
+
* open there; on a `failClosed` entry it exits 1, which Claude Code blocks on
|
|
1009
|
+
* (`onFailure`) and Copilot reads as a deny on `preToolUse`. It holds no
|
|
1010
|
+
* single quote, so it can sit inside a pair.
|
|
1011
|
+
*
|
|
1012
|
+
* @public
|
|
1013
|
+
*/
|
|
1014
|
+
export declare const BINARY_DISPATCH = "r=$1; shift; s=$(uname -s); e=; case \"$s\" in MINGW*|MSYS*|CYGWIN*) s=Windows; e=.exe;; esac; b=\"$0-$s-$(uname -m)$e\"; [ -x \"$b\" ] || exit \"${PLUGINFINITY_FAIL_CLOSED:-0}\"; PLUGINFINITY_ROOT=\"$r\" exec \"$b\" \"$@\"";
|
|
1015
|
+
/**
|
|
1016
|
+
* The events a hook's `if` condition is evaluated on. Elsewhere Claude Code
|
|
1017
|
+
* never runs a hook that sets one.
|
|
1018
|
+
*
|
|
1019
|
+
* @public
|
|
1020
|
+
*/
|
|
1021
|
+
export declare const IF_EVENTS: ReadonlyArray<string>;
|
|
1022
|
+
/**
|
|
1023
|
+
* The handler kinds Claude Code runs on an event: all five on the events that
|
|
1024
|
+
* can ask a model, no `agent` on `PermissionRequest`, only `command` on
|
|
1025
|
+
* `Setup`, only `command` and `mcp_tool` on `SessionStart`, and no `prompt` or
|
|
1026
|
+
* `agent` anywhere else.
|
|
1027
|
+
*
|
|
1028
|
+
* @public
|
|
1029
|
+
*/
|
|
1030
|
+
export declare const eventHandlers: (event: string) => ReadonlyArray<HookHandler>;
|
|
1031
|
+
/**
|
|
1032
|
+
* One problem with a hook entry that no single field shows: a combination the
|
|
1033
|
+
* host would silently ignore or never run.
|
|
1034
|
+
*
|
|
1035
|
+
* @public
|
|
1036
|
+
*/
|
|
1037
|
+
interface HookProblem {
|
|
1038
|
+
/** Where in the config: `hooks.<Event>[<index>]`. */
|
|
1039
|
+
readonly key: string;
|
|
1040
|
+
readonly message: string;
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* The problems in one event's entries, in Claude Code's terms, which the
|
|
1044
|
+
* config is written in.
|
|
1045
|
+
*
|
|
1046
|
+
* @public
|
|
1047
|
+
*/
|
|
1048
|
+
export declare const hookProblems: (event: string, entries: ReadonlyArray<HookEntry>, prefix?: string) => ReadonlyArray<HookProblem>;
|
|
1049
|
+
/**
|
|
1050
|
+
* What a `binary` entry is told beyond `entryEnv`: its host and the plugin's
|
|
1051
|
+
* name there. A script reads both from the `host.sh` the build writes beside
|
|
1052
|
+
* the hook library; a native program has only its environment.
|
|
1053
|
+
*
|
|
1054
|
+
* @public
|
|
1055
|
+
*/
|
|
1056
|
+
interface HookFacts {
|
|
1057
|
+
readonly host: string;
|
|
1058
|
+
readonly plugin: string;
|
|
1059
|
+
/** The plugin's description, written at the top of a hooks file that has a place for it. */
|
|
1060
|
+
readonly description?: string;
|
|
1061
|
+
/** The plugin's own MCP servers on this target, which an `mcpTool` hook names with the plugin's scope. */
|
|
1062
|
+
readonly servers?: ReadonlySet<string>;
|
|
1063
|
+
}
|
|
973
1064
|
/**
|
|
974
1065
|
* Every file a command names as `${PLUGIN_ROOT}/<path>`, in order.
|
|
975
1066
|
*
|
|
@@ -992,7 +1083,7 @@ export declare const hookCommandFiles: (events: ReadonlyArray<TargetHookEvent>)
|
|
|
992
1083
|
*
|
|
993
1084
|
* @public
|
|
994
1085
|
*/
|
|
995
|
-
export declare const entryEnv: (event: string, entry: HookEntry, matcher?: string) => Readonly<Record<string, string>>;
|
|
1086
|
+
export declare const entryEnv: (event: string, entry: HookEntry, matcher?: string, facts?: HookFacts) => Readonly<Record<string, string>>;
|
|
996
1087
|
/**
|
|
997
1088
|
* An env as a shell prefix, `K='V' ` per pair: every value single-quoted, and
|
|
998
1089
|
* empty for an empty env.
|
|
@@ -1003,32 +1094,48 @@ export declare const shellEnvPrefix: (env: Readonly<Record<string, string>>) =>
|
|
|
1003
1094
|
/**
|
|
1004
1095
|
* The shell command a hook entry runs on a target: a `script` through `bash`
|
|
1005
1096
|
* (or executed directly under `scripts.invoke: "exec"`) at the target's
|
|
1006
|
-
* plugin root,
|
|
1097
|
+
* plugin root, a `binary` through the platform dispatch, or a `command` with
|
|
1098
|
+
* `${PLUGIN_ROOT}` spelled the target's way.
|
|
1007
1099
|
*
|
|
1008
1100
|
* @public
|
|
1009
1101
|
*/
|
|
1010
1102
|
export declare const hookCommand: (entry: HookEntry, root: string, invoke: "bash" | "exec", env?: Readonly<Record<string, string>>) => string;
|
|
1011
1103
|
/**
|
|
1012
|
-
* A `script` entry in exec form, for a host that spawns `command` with `args`
|
|
1104
|
+
* A `script` or `binary` entry in exec form, for a host that spawns `command` with `args`
|
|
1013
1105
|
* and no shell: `bash` with the script path as its first argument, or under
|
|
1014
1106
|
* `scripts.invoke: "exec"` the script itself. The root placeholder is
|
|
1015
1107
|
* substituted by the host in `args`, and no shell ever parses the path.
|
|
1016
1108
|
*
|
|
1017
1109
|
* @public
|
|
1018
1110
|
*/
|
|
1019
|
-
export declare const hookExec: (entry:
|
|
1020
|
-
readonly script: string;
|
|
1021
|
-
}>, root: string, invoke: "bash" | "exec", env?: Readonly<Record<string, string>>) => {
|
|
1111
|
+
export declare const hookExec: (entry: FileHookEntry, root: string, invoke: "bash" | "exec", env?: Readonly<Record<string, string>>) => {
|
|
1022
1112
|
readonly command: string;
|
|
1023
1113
|
readonly args: ReadonlyArray<string>;
|
|
1024
1114
|
};
|
|
1115
|
+
/**
|
|
1116
|
+
* A hook entry that names a file the plugin ships: a `script` or a `binary`.
|
|
1117
|
+
*
|
|
1118
|
+
* @public
|
|
1119
|
+
*/
|
|
1120
|
+
type FileHookEntry = Extract<HookEntry, {
|
|
1121
|
+
readonly script: string;
|
|
1122
|
+
} | {
|
|
1123
|
+
readonly binary: string;
|
|
1124
|
+
}>;
|
|
1125
|
+
/**
|
|
1126
|
+
* Whether Claude Code reads a matcher as a regular expression: anything but
|
|
1127
|
+
* empty, `*`, or an exact list of letters, digits, `_`, `-`, spaces, `,` and `|`.
|
|
1128
|
+
*
|
|
1129
|
+
* @public
|
|
1130
|
+
*/
|
|
1131
|
+
export declare const isRegexMatcher: (matcher: string) => boolean;
|
|
1025
1132
|
/**
|
|
1026
1133
|
* How a host that ignores the SessionStart matcher is told a matcher: a host
|
|
1027
1134
|
* names a fresh session's source `new` where Claude says `startup`, so a
|
|
1028
1135
|
* matcher that matches `startup` must match `new` too.
|
|
1029
1136
|
*
|
|
1030
1137
|
* An exact list holding `startup` gains `new` right after it (`startup|resume`
|
|
1031
|
-
* becomes `startup|new|resume`); one that already holds `new`, an empty or `*`
|
|
1138
|
+
* becomes `startup|new|resume`, as does `startup, resume`); one that already holds `new`, an empty or `*`
|
|
1032
1139
|
* matcher and any matcher not matching `startup` stay as written. A regex
|
|
1033
1140
|
* that matches `startup` but not `new` also stays as written, reported as
|
|
1034
1141
|
* `unwidened` so the build can note it. The regex is tried as a JavaScript
|
|
@@ -1055,7 +1162,7 @@ export declare const widensSessionStart: (ignored: ReadonlyArray<string>, event:
|
|
|
1055
1162
|
*
|
|
1056
1163
|
* @public
|
|
1057
1164
|
*/
|
|
1058
|
-
export declare const renderHooks: (target: Target, events: ReadonlyArray<TargetHookEvent>, invoke: "bash" | "exec") => string | undefined;
|
|
1165
|
+
export declare const renderHooks: (target: Target, events: ReadonlyArray<TargetHookEvent>, invoke: "bash" | "exec", facts?: HookFacts) => string | undefined;
|
|
1059
1166
|
/**
|
|
1060
1167
|
* Seconds the env runner gives the `setup` script before it discards its
|
|
1061
1168
|
* output and resolves without it.
|
|
@@ -1377,7 +1484,7 @@ interface TargetValidation {
|
|
|
1377
1484
|
*
|
|
1378
1485
|
* @public
|
|
1379
1486
|
*/
|
|
1380
|
-
type PlanError = PackageVersionMissing | HookEventUnsupported | HookScriptInvalid | ShippedFileInvalid | PathConflict | ComponentsInvalid | PlatformError.PlatformError;
|
|
1487
|
+
type PlanError = PackageVersionMissing | ConfigInvalid | HookEventUnsupported | HookScriptInvalid | ShippedFileInvalid | PathConflict | ComponentsInvalid | PlatformError.PlatformError;
|
|
1381
1488
|
/**
|
|
1382
1489
|
* Regenerate `builds/<id>/` for every selected plugin and target, writing
|
|
1383
1490
|
* only what differs. With `check`, write nothing and fail with
|
|
@@ -1531,5 +1638,5 @@ export declare const ToolDiscoveryLive: Layer.Layer<ToolDiscovery, never, ChildP
|
|
|
1531
1638
|
* @public
|
|
1532
1639
|
*/
|
|
1533
1640
|
export declare const ENGINE_VERSION: string;
|
|
1534
|
-
export type { BuildError, BuildInput, BuildNote, BuildNoteKind, ConfigError, ConfigSelection, DoctorInput, EmittedFile, FieldDrop, HostBlockProblem, LoadedConfig, LogEntry, LogFileName, LogTail, Manifest, MappedFrontmatter, MonitorContext, MonitorMap, OwnMcp, PlanError, PreparedPlugin, RawLogLine, RenderedAgent, RenderedMonitors, RenderedSkill, ServerFiles, ServerRender, SourceAgent, SourceSkill, SplitMarkdown, TargetBuild, TargetHookEvent, TargetValidation, TokenContext, TokenProblem, UnresolvedField, UnsupportedHookEvent, ValidateInput };
|
|
1641
|
+
export type { BuildError, BuildInput, BuildNote, BuildNoteKind, ConfigError, ConfigSelection, DoctorInput, EmittedFile, FieldDrop, FileHookEntry, HookFacts, HookProblem, HostBlockProblem, LoadedConfig, LogEntry, LogFileName, LogTail, Manifest, MappedFrontmatter, MonitorContext, MonitorMap, OwnMcp, PlanError, PreparedPlugin, RawLogLine, RenderedAgent, RenderedMonitors, RenderedSkill, ServerFiles, ServerRender, SourceAgent, SourceSkill, SplitMarkdown, TargetBuild, TargetHookEvent, TargetValidation, TokenContext, TokenProblem, UnresolvedField, UnsupportedHookEvent, UnsupportedHookHandler, ValidateInput };
|
|
1535
1642
|
//# sourceMappingURL=index.d.ts.map
|
package/index.js
CHANGED
|
@@ -6,7 +6,7 @@ import { EmitPlan, GENERATED_MODE, applyEmit, planEmit } from "./emit.js";
|
|
|
6
6
|
import { ENV_RUNNER_TIMEOUT, ENV_SETUP_TIMEOUT, ENV_WAIT_TIMEOUT_FLOOR, envLibFiles, envNotes, envRunnerEntry, envWaitNotes, renderEnvLib, withEnvRunner } from "./env.js";
|
|
7
7
|
import { BuildStale, ComponentInvalid, ComponentsInvalid, ConfigAmbiguous, ConfigInvalid, ConfigIssue, ConfigLoadFailed, ConfigNotFound, HookEventUnsupported, HookScriptInvalid, HookScriptProblem, HostRejected, NotImplemented, PackageVersionMissing, PathConflict, ShippedFileInvalid, ShippedFileProblem, TargetDrift, TargetNotEnabled, UnknownTarget, isBuildError, isConfigError } from "./errors.js";
|
|
8
8
|
import { appendSections, mapFrontmatter, splitFrontmatter } from "./frontmatter.js";
|
|
9
|
-
import { commandFiles, entryEnv, hookCommand, hookCommandFiles, hookExec, hookScripts, renderHooks, sessionStartMatcher, shellEnvPrefix, targetHooks, widensSessionStart } from "./hooks.js";
|
|
9
|
+
import { BINARY_DISPATCH, IF_EVENTS, commandFiles, entryEnv, eventHandlers, hookBinaries, hookCommand, hookCommandFiles, hookExec, hookProblems, hookScripts, isRegexMatcher, renderHooks, sessionStartMatcher, shellEnvPrefix, targetHooks, widensSessionStart } from "./hooks.js";
|
|
10
10
|
import { ConfigLoader } from "./loader.js";
|
|
11
11
|
import { configPluginNames, listLogPlugins, logDirectory, logRoot, parseLogLine, readLog, readLogFrom } from "./logs.js";
|
|
12
12
|
import { renderManifest, serializeManifest } from "./manifest.js";
|
|
@@ -20,4 +20,4 @@ import { renderTokens } from "./tokens.js";
|
|
|
20
20
|
import { ToolDiscoveryLive } from "./tools.js";
|
|
21
21
|
import { ENGINE_VERSION } from "./version.js";
|
|
22
22
|
|
|
23
|
-
export { BUILD_NOTE_KINDS, BuildStale, CONFIG_FILE_NAMES, CheckGroup, CheckSeverity, CheckStatus, ComponentInvalid, ComponentsInvalid, ConfigAmbiguous, ConfigDiscovery, ConfigInvalid, ConfigIssue, ConfigLoadFailed, ConfigLoader, ConfigNotFound, DEFAULT_CHECK_TIMEOUT, DoctorCheck, DoctorReport, ENGINE_VERSION, ENV_RUNNER_TIMEOUT, ENV_SETUP_TIMEOUT, ENV_WAIT_TIMEOUT_FLOOR, EmitPlan, GENERATED_MODE, HookEventUnsupported, HookScriptInvalid, HookScriptProblem, HostRejected, NODE_FLOOR, NotImplemented, PackageVersionMissing, PathConflict, SKILL_DESCRIPTION_MAX, ShippedFileInvalid, ShippedFileProblem, TargetDrift, TargetNotEnabled, ToolDiscoveryLive, UnknownTarget, appendSections, applyEmit, applyHostBlocks, build, commandFiles, configPluginNames, entryEnv, envLibFiles, envNotes, envRunnerEntry, envWaitNotes, hookCommand, hookCommandFiles, hookExec, hookScripts, isBuildError, isConfigError, listLogPlugins, logDirectory, logRoot, mapFrontmatter, parseLogLine, planEmit, preparePlugins, readAgents, readLog, readLogFrom, readSkills, renderAgent, renderEnvLib, renderHooks, renderManifest, renderMonitors, renderServers, renderSkill, renderTokens, runDoctor, selectConfigPaths, serializeManifest, serverFiles, sessionStartMatcher, shellEnvPrefix, splitFrontmatter, targetHooks, targetMonitors, validate, widensSessionStart, withEnvRunner };
|
|
23
|
+
export { BINARY_DISPATCH, BUILD_NOTE_KINDS, BuildStale, CONFIG_FILE_NAMES, CheckGroup, CheckSeverity, CheckStatus, ComponentInvalid, ComponentsInvalid, ConfigAmbiguous, ConfigDiscovery, ConfigInvalid, ConfigIssue, ConfigLoadFailed, ConfigLoader, ConfigNotFound, DEFAULT_CHECK_TIMEOUT, DoctorCheck, DoctorReport, ENGINE_VERSION, ENV_RUNNER_TIMEOUT, ENV_SETUP_TIMEOUT, ENV_WAIT_TIMEOUT_FLOOR, EmitPlan, GENERATED_MODE, HookEventUnsupported, HookScriptInvalid, HookScriptProblem, HostRejected, IF_EVENTS, NODE_FLOOR, NotImplemented, PackageVersionMissing, PathConflict, SKILL_DESCRIPTION_MAX, ShippedFileInvalid, ShippedFileProblem, TargetDrift, TargetNotEnabled, ToolDiscoveryLive, UnknownTarget, appendSections, applyEmit, applyHostBlocks, build, commandFiles, configPluginNames, entryEnv, envLibFiles, envNotes, envRunnerEntry, envWaitNotes, eventHandlers, hookBinaries, hookCommand, hookCommandFiles, hookExec, hookProblems, hookScripts, isBuildError, isConfigError, isRegexMatcher, listLogPlugins, logDirectory, logRoot, mapFrontmatter, parseLogLine, planEmit, preparePlugins, readAgents, readLog, readLogFrom, readSkills, renderAgent, renderEnvLib, renderHooks, renderManifest, renderMonitors, renderServers, renderSkill, renderTokens, runDoctor, selectConfigPaths, serializeManifest, serverFiles, sessionStartMatcher, shellEnvPrefix, splitFrontmatter, targetHooks, targetMonitors, validate, widensSessionStart, withEnvRunner };
|
package/lib-version.generated.js
CHANGED
package/notes.js
CHANGED
|
@@ -15,7 +15,9 @@ const BUILD_NOTE_KINDS = [
|
|
|
15
15
|
"env-shell-unsupported",
|
|
16
16
|
"env-wait-timeout",
|
|
17
17
|
"hook-matcher-widened",
|
|
18
|
-
"hook-matcher-regex"
|
|
18
|
+
"hook-matcher-regex",
|
|
19
|
+
"hook-matcher-native-regex",
|
|
20
|
+
"hook-field-dropped"
|
|
19
21
|
];
|
|
20
22
|
/** The path of notes about the config: hooks and servers. */
|
|
21
23
|
const CONFIG_NOTE_PATH = "config";
|
package/operations.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Run } from "@effected/commands";
|
|
2
|
+
import { HOOK_ENTRY_FIELDS } from "@pluginfinity/core";
|
|
2
3
|
import { KNOWN_TARGET_IDS, TARGETS } from "@pluginfinity/targets";
|
|
3
4
|
import { Effect, FileSystem, Path, Schema } from "effect";
|
|
4
5
|
import { ChildProcess } from "effect/process";
|
|
@@ -6,10 +7,10 @@ import { readAgents, renderAgent } from "./agents.js";
|
|
|
6
7
|
import { isJunk } from "./component.js";
|
|
7
8
|
import { applyEmit, planEmit } from "./emit.js";
|
|
8
9
|
import { envNotes, envRunnerEntry, envWaitNotes, withEnvRunner } from "./env.js";
|
|
9
|
-
import { BuildStale, ComponentInvalid, ComponentsInvalid, HookEventUnsupported, HookScriptInvalid, HostRejected, PackageVersionMissing, PathConflict, ShippedFileInvalid, TargetDrift } from "./errors.js";
|
|
10
|
+
import { BuildStale, ComponentInvalid, ComponentsInvalid, ConfigInvalid, ConfigIssue, HookEventUnsupported, HookScriptInvalid, HostRejected, PackageVersionMissing, PathConflict, ShippedFileInvalid, TargetDrift } from "./errors.js";
|
|
10
11
|
import { HOOK_LIB_DIR, hookLibFiles } from "./hook-lib.js";
|
|
11
12
|
import { ignoredOutput } from "./hook-output.js";
|
|
12
|
-
import { hookCommandFiles, hookScripts, renderHooks, sessionStartMatcher, targetHooks, widensSessionStart } from "./hooks.js";
|
|
13
|
+
import { hookBinaries, hookCommandFiles, hookProblems, hookScripts, isRegexMatcher, renderHooks, sessionStartMatcher, targetHooks, widensSessionStart } from "./hooks.js";
|
|
13
14
|
import { LIB_DIR, libFiles } from "./lib-files.js";
|
|
14
15
|
import { LIB_VERSION } from "./lib-version.generated.js";
|
|
15
16
|
import { pluginName, renderManifest, serializeManifest } from "./manifest.js";
|
|
@@ -19,7 +20,7 @@ import { preparePlugins } from "./selection.js";
|
|
|
19
20
|
import { SERVER_LIB_DIR, serverLibFiles } from "./server-lib.js";
|
|
20
21
|
import { mcpServerNames, renderServers, serverFiles } from "./servers.js";
|
|
21
22
|
import { readSkills, renderSkill } from "./skills.js";
|
|
22
|
-
import { renderToolMap } from "./tool-map.js";
|
|
23
|
+
import { renderFacts, renderToolMap } from "./tool-map.js";
|
|
23
24
|
|
|
24
25
|
// src/operations.ts
|
|
25
26
|
const PackageVersion = Schema.fromJsonString(Schema.Struct({ version: Schema.String }));
|
|
@@ -84,6 +85,41 @@ const checkScript = (config, script, invoke, component = "hooks") => Effect.gen(
|
|
|
84
85
|
component
|
|
85
86
|
}));
|
|
86
87
|
});
|
|
88
|
+
/**
|
|
89
|
+
* The platform files of a hook `binary`: every `<binary>-<os>-<arch>` beside
|
|
90
|
+
* the prefix. Fails with `HookScriptInvalid` when there is none, or when one
|
|
91
|
+
* lacks the executable bit, since a binary is always executed.
|
|
92
|
+
*/
|
|
93
|
+
const binaryFiles = (config, binary) => Effect.gen(function* () {
|
|
94
|
+
const fs = yield* FileSystem.FileSystem;
|
|
95
|
+
const path = yield* Path.Path;
|
|
96
|
+
const slash = binary.lastIndexOf("/");
|
|
97
|
+
const dir = slash === -1 ? "" : binary.slice(0, slash);
|
|
98
|
+
const prefix = `${binary.slice(slash + 1)}-`;
|
|
99
|
+
const absolute = path.join(config.root, dir);
|
|
100
|
+
const names = (yield* fs.exists(absolute)) ? yield* fs.readDirectory(absolute) : [];
|
|
101
|
+
const files = [];
|
|
102
|
+
const platform = (name) => name.startsWith(prefix) && /^\w+-\w+(\.exe)?$/.test(name.slice(prefix.length));
|
|
103
|
+
for (const name of names.filter(platform).sort()) {
|
|
104
|
+
const info = yield* fs.stat(path.join(absolute, name));
|
|
105
|
+
if (info.type !== "File") continue;
|
|
106
|
+
const file = dir === "" ? name : `${dir}/${name}`;
|
|
107
|
+
if ((info.mode & 73) === 0) return yield* Effect.fail(new HookScriptInvalid({
|
|
108
|
+
path: config.path,
|
|
109
|
+
script: file,
|
|
110
|
+
problem: "binary-not-executable",
|
|
111
|
+
component: "hooks"
|
|
112
|
+
}));
|
|
113
|
+
files.push(file);
|
|
114
|
+
}
|
|
115
|
+
if (files.length === 0) return yield* Effect.fail(new HookScriptInvalid({
|
|
116
|
+
path: config.path,
|
|
117
|
+
script: `${binary}-<os>-<arch>`,
|
|
118
|
+
problem: "missing",
|
|
119
|
+
component: "hooks"
|
|
120
|
+
}));
|
|
121
|
+
return files;
|
|
122
|
+
});
|
|
87
123
|
/** Whether `real` is `root` or under it; both are real paths. */
|
|
88
124
|
const isInside = (root, real) => real === root || real.startsWith(`${root}/`);
|
|
89
125
|
/** Whether a plugin-relative path has no empty, `.` or `..` segment. */
|
|
@@ -238,12 +274,28 @@ const planPlugin = (prepared) => Effect.gen(function* () {
|
|
|
238
274
|
...targetHooks(target, id, config.config)
|
|
239
275
|
};
|
|
240
276
|
});
|
|
241
|
-
|
|
277
|
+
const problems = [...Object.entries(config.config.hooks ?? {}).flatMap(([event, entries]) => hookProblems(event, entries ?? [])), ...config.targets.flatMap((id) => {
|
|
278
|
+
const setting = config.config[id];
|
|
279
|
+
const own = typeof setting === "object" ? setting.hooks ?? {} : {};
|
|
280
|
+
return Object.entries(own).flatMap(([event, entries]) => hookProblems(event, entries ?? [], `${id}.hooks`));
|
|
281
|
+
})];
|
|
282
|
+
if (problems.length > 0) return yield* Effect.fail(new ConfigInvalid({
|
|
283
|
+
path: config.path,
|
|
284
|
+
issues: problems.map((problem) => ConfigIssue.make(problem))
|
|
285
|
+
}));
|
|
286
|
+
for (const { id, unsupported, unsupportedHandlers } of hooks) if (unsupported.length > 0 || unsupportedHandlers.length > 0) return yield* Effect.fail(new HookEventUnsupported({
|
|
242
287
|
path: config.path,
|
|
243
288
|
target: id,
|
|
244
|
-
events: unsupported.map((u) => u.event)
|
|
289
|
+
events: unsupported.map((u) => u.event),
|
|
290
|
+
handlers: unsupportedHandlers.map((u) => `${u.event} (${u.handler})`)
|
|
245
291
|
}));
|
|
246
|
-
const
|
|
292
|
+
const platformFiles = /* @__PURE__ */ new Map();
|
|
293
|
+
for (const { events } of hooks) for (const binary of hookBinaries(events)) if (!platformFiles.has(binary)) platformFiles.set(binary, yield* binaryFiles(config, binary));
|
|
294
|
+
const filesOf = (events) => [
|
|
295
|
+
...hookScripts(events),
|
|
296
|
+
...hookCommandFiles(events),
|
|
297
|
+
...hookBinaries(events).flatMap((binary) => platformFiles.get(binary) ?? [])
|
|
298
|
+
];
|
|
247
299
|
const everyScript = new Set(config.targets.flatMap((id) => filesOf(targetHooks(targetOf(id), id, config.config).events)));
|
|
248
300
|
for (const { events } of hooks) {
|
|
249
301
|
for (const script of hookScripts(events)) yield* checkScript(config, script, invoke);
|
|
@@ -296,6 +348,20 @@ const planPlugin = (prepared) => Effect.gen(function* () {
|
|
|
296
348
|
kind: "hook-matcher-runtime",
|
|
297
349
|
name: event
|
|
298
350
|
});
|
|
351
|
+
for (const entry of entries) for (const field of HOOK_ENTRY_FIELDS) if (entry[field] !== void 0 && !target.hooks.entryFields.includes(field)) notes.push({
|
|
352
|
+
target: id,
|
|
353
|
+
path: CONFIG_NOTE_PATH,
|
|
354
|
+
kind: "hook-field-dropped",
|
|
355
|
+
name: `${event} ${field}`
|
|
356
|
+
});
|
|
357
|
+
if (target.hooks.matcherIgnored.includes(event)) {
|
|
358
|
+
for (const entry of entries) if ("binary" in entry && entry.matcher !== void 0 && isRegexMatcher(entry.matcher)) notes.push({
|
|
359
|
+
target: id,
|
|
360
|
+
path: CONFIG_NOTE_PATH,
|
|
361
|
+
kind: "hook-matcher-native-regex",
|
|
362
|
+
name: `${event} ${entry.matcher}`
|
|
363
|
+
});
|
|
364
|
+
}
|
|
299
365
|
if (widensSessionStart(target.hooks.matcherIgnored, event)) for (const entry of entries) {
|
|
300
366
|
if (entry.matcher === void 0) continue;
|
|
301
367
|
const spelled = sessionStartMatcher(entry.matcher);
|
|
@@ -361,7 +427,12 @@ const planPlugin = (prepared) => Effect.gen(function* () {
|
|
|
361
427
|
path: target.manifest.path,
|
|
362
428
|
content: serializeManifest(manifest)
|
|
363
429
|
}];
|
|
364
|
-
const hooksFile = renderHooks(target, env === void 0 ? events : withEnvRunner(target, events, envRunnerEntry(LIB_DIR)), invoke
|
|
430
|
+
const hooksFile = renderHooks(target, env === void 0 ? events : withEnvRunner(target, events, envRunnerEntry(LIB_DIR)), invoke, {
|
|
431
|
+
host: id,
|
|
432
|
+
plugin: pluginName(config.config, id),
|
|
433
|
+
description: config.config.description,
|
|
434
|
+
servers: mcpServerNames(id, config.config)
|
|
435
|
+
});
|
|
365
436
|
if (hooksFile !== void 0) generated.push({
|
|
366
437
|
path: target.hooks.path,
|
|
367
438
|
content: hooksFile
|
|
@@ -371,6 +442,17 @@ const planPlugin = (prepared) => Effect.gen(function* () {
|
|
|
371
442
|
agents: builtFor(agents, id).map((agent) => agent.name),
|
|
372
443
|
monitors: Object.keys(targetMonitors(id, config.config))
|
|
373
444
|
})));
|
|
445
|
+
if (hookBinaries(events).length > 0) generated.push({
|
|
446
|
+
path: `${LIB_DIR}/facts.json`,
|
|
447
|
+
content: renderFacts(target, id, {
|
|
448
|
+
host: pluginName(config.config, id),
|
|
449
|
+
claude: pluginName(config.config, "claude")
|
|
450
|
+
}, [...mcpServerNames(id, config.config)], {
|
|
451
|
+
skills: builtFor(skills, id).map((skill) => skill.name),
|
|
452
|
+
agents: builtFor(agents, id).map((agent) => agent.name),
|
|
453
|
+
monitors: Object.keys(targetMonitors(id, config.config))
|
|
454
|
+
}, env?.vars ?? {})
|
|
455
|
+
});
|
|
374
456
|
if (monitored.rendered.file !== void 0) generated.push(monitored.rendered.file);
|
|
375
457
|
generated.push(...libFiles(id, String(manifest.name), LIB_VERSION, {
|
|
376
458
|
monitors: monitored.rendered.file !== void 0,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pluginfinity/engine",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "The pluginfinity build pipeline shared by every pluginfinity front end: config discovery, read, transform per target, emit and check.",
|
|
6
6
|
"keywords": [
|
|
@@ -41,8 +41,8 @@
|
|
|
41
41
|
"@effected/walker": "0.30.0",
|
|
42
42
|
"@effected/workspaces": "0.49.1",
|
|
43
43
|
"@effected/yaml": "0.30.0",
|
|
44
|
-
"@pluginfinity/core": "0.
|
|
45
|
-
"@pluginfinity/targets": "0.
|
|
44
|
+
"@pluginfinity/core": "0.4.0",
|
|
45
|
+
"@pluginfinity/targets": "0.4.0",
|
|
46
46
|
"jiti": "^2.6.1"
|
|
47
47
|
},
|
|
48
48
|
"peerDependencies": {
|
package/tool-map.js
CHANGED
|
@@ -30,5 +30,35 @@ const renderToolMap = (target, plugin, servers, has) => {
|
|
|
30
30
|
""
|
|
31
31
|
].join("\n");
|
|
32
32
|
};
|
|
33
|
+
/**
|
|
34
|
+
* `lib/pluginfinity/facts.json`: what a native hook reads where a script
|
|
35
|
+
* sources `tools.sh`, `host.sh` and `env.sh`. It holds the host's run-time
|
|
36
|
+
* tool names, the components this build ships and the plugin's declared
|
|
37
|
+
* session variables with their defaults. A `binary` hook finds it through the
|
|
38
|
+
* plugin root its entry hands over.
|
|
39
|
+
*
|
|
40
|
+
* @public
|
|
41
|
+
*/
|
|
42
|
+
const renderFacts = (target, host, plugin, servers, has, env = {}) => {
|
|
43
|
+
const runtime = target.tools.runtime;
|
|
44
|
+
return `${JSON.stringify({
|
|
45
|
+
host,
|
|
46
|
+
plugin: plugin.host,
|
|
47
|
+
tools: {
|
|
48
|
+
names: Object.fromEntries(Object.entries(runtime.names).flatMap(([name, spelled]) => typeof spelled === "string" ? [[name, spelled]] : [])),
|
|
49
|
+
plugin: plugin.claude,
|
|
50
|
+
mcp: runtime.mcp,
|
|
51
|
+
servers,
|
|
52
|
+
unlisted: runtime.unlisted
|
|
53
|
+
},
|
|
54
|
+
has: {
|
|
55
|
+
skills: has.skills,
|
|
56
|
+
agents: has.agents,
|
|
57
|
+
monitors: "path" in target.monitors ? has.monitors : [],
|
|
58
|
+
servers
|
|
59
|
+
},
|
|
60
|
+
env: { vars: Object.fromEntries(Object.entries(env).map(([name, declared]) => [name, declared.default ?? ""])) }
|
|
61
|
+
}, null, " ")}\n`;
|
|
62
|
+
};
|
|
33
63
|
|
|
34
|
-
export { renderToolMap };
|
|
64
|
+
export { renderFacts, renderToolMap };
|