@pluginfinity/engine 0.2.1 → 0.3.1

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.
@@ -0,0 +1,12 @@
1
+ //#region src/env-lib.generated.ts
2
+ /** The session env library's files, embedded so a build needs no asset on disk. */
3
+ const ENV_LIB_FILES = [{
4
+ name: "env-run.sh",
5
+ content: "# shellcheck shell=sh\n# pluginfinity session env runner. `pluginfinity build` writes this file at\n# lib/pluginfinity/env-run.sh into every target whose config declares `env`,\n# and runs it as the first SessionStart entry; do not edit a copy under builds/.\n#\n# POSIX sh. Run as a script (`sh <path>`), with the SessionStart event on stdin.\n# Writes nothing to stdout or stderr and always exits 0: every problem is a log\n# line, and the shell's own job-control notices are redirected away.\n#\n# Once per SessionStart (every source) it resolves each declared name through\n# rungs 1-5 (default, setup output, <project>/.env, <project>/.env.local, the\n# environment this process inherited), then writes the resolved values to the\n# session values file, points the project at this session, and on Claude\n# appends `export NAME='value'` lines to CLAUDE_ENV_FILE for the Bash tool.\n#\n# The setup script runs under bash with cwd the project, the hook environment\n# plus PLUGINFINITY_EVENT=SessionStart, and the event on stdin. Its stdout is\n# NAME=value lines (blank and # lines ignored, values literal, later lines\n# win); an undeclared name is skipped with a log line. It is bounded by\n# _pf_env_setup_timeout seconds: on timeout the setup and every process it\n# started are terminated (then killed after 1 s) and nothing it printed is\n# kept; on a non-zero exit its valid lines are kept. With no project (a Copilot\n# event with no cwd) setup is skipped with a log line.\n#\n# Under the session lock it keeps the names a same-id rerun finds recorded as\n# set at rung 6, writes the values, then writes the session's done marker.\n\n_pf_env_lib_dir=$(CDPATH='' cd -- \"$(dirname -- \"$0\")\" 2>/dev/null && pwd) || exit 0\n_pf_env_manual=1\n_pf_env_component=hook\n[ -r \"$_pf_env_lib_dir/env.sh\" ] || exit 0\n# shellcheck source=/dev/null\n. \"$_pf_env_lib_dir/env.sh\" || exit 0\n[ -n \"$_pf_env_names\" ] || exit 0\n\n_pf_r_tmp=$(mktemp -d \"${TMPDIR:-/tmp}/pluginfinity-env.XXXXXX\" 2>/dev/null) || {\n _pf_env_log \"cannot create a temporary directory; session env not resolved\"\n exit 0\n}\ntrap 'rm -rf \"$_pf_r_tmp\" 2>/dev/null' EXIT\n\nif [ -t 0 ]; then\n printf '{}' >\"$_pf_r_tmp/input\"\nelse\n cat >\"$_pf_r_tmp/input\" 2>/dev/null || :\nfi\n\n# A top-level string field of the event: jq when it works, else a plain match\n# that keeps escape sequences as written (a session id holding one is invalid).\n_pf_r_jq=\nif command -v jq >/dev/null 2>&1 && jq -n 1 >/dev/null 2>&1; then _pf_r_jq=1; fi\n_pf_r_field() {\n if [ -n \"$_pf_r_jq\" ]; then\n jq -r --arg k \"$1\" 'if type == \"object\" then (.[$k] // empty) | strings else empty end' \\\n <\"$_pf_r_tmp/input\" 2>/dev/null || :\n else\n tr -d '\\n' <\"$_pf_r_tmp/input\" | sed -n \"s/.*\\\"$1\\\"[[:space:]]*:[[:space:]]*\\\"\\([^\\\"]*\\)\\\".*/\\1/p\"\n fi\n}\n\n_pf_r_sid=$(_pf_r_field session_id)\n[ -n \"$_pf_r_sid\" ] || _pf_r_sid=$(_pf_r_field sessionId)\n_pf_r_cwd=$(_pf_r_field cwd)\n\n# The project: the event's cwd walked up to .git. Without one, Claude's rule\n# for a script; Copilot runs hooks from the plugin root, which is no project.\ncase $_pf_r_cwd in\n/*) _pf_r_proj=$(_pf_env_project_of \"$_pf_r_cwd\") ;;\n*)\n if [ \"${PLUGINFINITY_HOST:-}\" = copilot ]; then\n _pf_r_proj=\n _pf_env_log \"the event has no cwd; .env files not read\"\n else\n _pf_r_proj=$(_pf_env_script_project)\n fi\n ;;\nesac\n\n_pf_env_init\n\n# Every process below $1, from one ps snapshot.\n_pf_r_descendants() {\n ps -A -o pid= -o ppid= 2>/dev/null | awk -v root=\"$1\" '\n { parent[$1] = $2 }\n END {\n for (p in parent) {\n q = p\n for (i = 0; i < 64 && q != \"\" && q != 0 && q != 1; i++) {\n q = parent[q]\n if (q == root) { print p; break }\n }\n }\n }'\n}\n\n# Send signal $1 to process $2, to its process group when it leads one ($4 is\n# the group id seen at the first signal), and to the pids in $3.\n_pf_r_signal() {\n case ${2:-} in '' | 0 | 1 | *[!0123456789]*) return 0 ;; esac\n if [ \"${4:-}\" = \"$2\" ]; then kill -s \"$1\" -- \"-$2\" 2>/dev/null || :; fi\n # shellcheck disable=SC2086 # pids are words\n kill -s \"$1\" \"$2\" ${3:-} 2>/dev/null || :\n}\n\n# Rung 2: the setup script.\n_pf_r_setup() {\n [ -n \"$_pf_env_setup\" ] || return 0\n _pf_r_script=\"$_pf_env_lib_dir/../../$_pf_env_setup\"\n if [ ! -f \"$_pf_r_script\" ]; then\n _pf_env_log \"setup script $_pf_env_setup is missing; skipped\"\n return 0\n fi\n if [ -z \"$_pf_r_proj\" ]; then\n _pf_env_log \"no project; setup script $_pf_env_setup skipped\"\n return 0\n fi\n _pf_r_t=$_pf_env_setup_timeout\n case $_pf_r_t in '' | *[!0123456789]*) _pf_r_t=10 ;; esac\n # Its own process group where job control allows (bash, bash as sh), so a\n # timeout can signal the group; the descendant walk covers dash, which has no\n # job control without a terminal.\n set -m 2>/dev/null || :\n (\n CDPATH='' cd -- \"$_pf_r_proj\" 2>/dev/null || exit 1\n PLUGINFINITY_EVENT=SessionStart\n export PLUGINFINITY_EVENT\n exec bash \"$_pf_r_script\"\n ) <\"$_pf_r_tmp/input\" >\"$_pf_r_tmp/out\" 2>\"$_pf_r_tmp/err\" &\n _pf_r_pid=$!\n set +m 2>/dev/null || :\n (\n sleep \"$_pf_r_t\"\n : >\"$_pf_r_tmp/timedout\"\n # One snapshot: by the KILL the orphans belong to init and no walk finds them.\n _pf_r_kids=$(_pf_r_descendants \"$_pf_r_pid\")\n _pf_r_pg=$(ps -o pgid= -p \"$_pf_r_pid\" 2>/dev/null | tr -d ' ')\n _pf_r_signal TERM \"$_pf_r_pid\" \"$_pf_r_kids\" \"$_pf_r_pg\"\n sleep 1\n _pf_r_signal KILL \"$_pf_r_pid\" \"$_pf_r_kids\" \"$_pf_r_pg\"\n ) </dev/null >/dev/null 2>&1 &\n _pf_r_watch=$!\n if wait \"$_pf_r_pid\" 2>/dev/null; then _pf_r_rc=0; else _pf_r_rc=$?; fi\n # After a timeout the watcher still owes the KILL for anything that ignored TERM.\n if [ -e \"$_pf_r_tmp/timedout\" ]; then\n wait \"$_pf_r_watch\" 2>/dev/null || :\n else\n # Reaped inside the redirect: bash as sh prints \"Terminated\" for a killed job.\n { kill \"$_pf_r_watch\" && wait \"$_pf_r_watch\"; } 2>/dev/null || :\n fi\n if pf_debug_on 2>/dev/null && [ -s \"$_pf_r_tmp/err\" ]; then\n head -n 20 \"$_pf_r_tmp/err\" | while IFS= read -r _pf_r_l; do _pf_env_debug \"setup: $_pf_r_l\"; done\n fi\n if [ -e \"$_pf_r_tmp/timedout\" ]; then\n _pf_env_log \"setup script $_pf_env_setup timed out after ${_pf_r_t}s; its output is discarded\"\n return 0\n fi\n [ \"$_pf_r_rc\" -eq 0 ] || _pf_env_log \"setup script $_pf_env_setup exited $_pf_r_rc; keeping its valid lines\"\n while IFS= read -r _pf_e_l || [ -n \"$_pf_e_l\" ]; do\n case $_pf_e_l in '' | '#'*) continue ;; esac\n _pf_e_k=${_pf_e_l%%=*}\n [ \"$_pf_e_k\" != \"$_pf_e_l\" ] || continue\n if _pf_env_declared \"$_pf_e_k\"; then\n _pf_e_v=${_pf_e_l#*=}\n eval \"_pf_env_val_$_pf_e_k=\\$_pf_e_v\"\n elif _pf_env_is_name \"$_pf_e_k\"; then\n _pf_env_log \"setup printed $_pf_e_k, which is not declared; skipped\"\n fi\n done <\"$_pf_r_tmp/out\"\n return 0\n}\n_pf_r_setup\n\n# Rungs 3-5.\n_pf_env_live \"$_pf_r_proj\"\n\nif _pf_env_valid_id \"$_pf_r_sid\"; then\n _pf_r_sd=$(_pf_env_session_dir \"$_pf_r_sid\")\n _pf_env_lock \"$_pf_r_sd\"\n # A same-id rerun keeps what _pf_env_set wrote (rung 6) and re-resolves the rest.\n _pf_env_keep_set \"$_pf_r_sd\"\n if _pf_env_write_values \"$_pf_r_sd/env\"; then _pf_r_ok=1; else _pf_r_ok=; fi\n _pf_env_unlock\n (umask 077 && : >\"$_pf_r_sd/done\") 2>/dev/null || :\n if [ -n \"$_pf_r_ok\" ] && [ -n \"$_pf_r_proj\" ]; then\n _pf_r_ptr=$(_pf_env_pointer_path \"$_pf_r_proj\")\n if (umask 077 && mkdir -p \"$(dirname -- \"$_pf_r_ptr\")\") 2>/dev/null &&\n printf '%s\\n%s\\n' \"$_pf_r_sid\" \"$_pf_r_proj\" >\"$_pf_r_ptr.tmp.$$\" 2>/dev/null &&\n mv -f \"$_pf_r_ptr.tmp.$$\" \"$_pf_r_ptr\" 2>/dev/null; then\n :\n else\n rm -f \"$_pf_r_ptr.tmp.$$\" 2>/dev/null\n _pf_env_log \"cannot write the project pointer\"\n fi\n fi\nelif [ -z \"$_pf_r_sid\" ]; then\n _pf_env_log \"the event has no session id; session values not written\"\nelse\n _pf_env_log \"invalid session id; session values not written\"\nfi\n\n# shellcheck disable=SC2086 # the names are words\n_pf_env_claude_export $_pf_env_names\nexit 0\n"
6
+ }, {
7
+ name: "env.sh",
8
+ content: "# shellcheck shell=sh\n# pluginfinity session env. `pluginfinity build` writes this file into every\n# target whose config declares `env`, at lib/pluginfinity/env.sh, with the\n# declarations block below filled in; do not edit a copy under builds/, the\n# next build overwrites it.\n#\n# POSIX sh. Writes nothing to stdout. Fails open: every problem is a log line\n# and the variables keep what the chain could resolve.\n#\n# From a skill script or a monitor, two lines apply the session's values. Build\n# the path from an absolute directory, before any cd: a relative $0 no longer\n# resolves after one.\n# _pf_lib_dir=\"$(cd \"$(dirname \"$0\")/../../../lib/pluginfinity\" && pwd)\" # skills/<s>/scripts/x.sh\n# . \"$_pf_lib_dir/env.sh\"\n# A script that resolves its own project sources first, changes directory, then\n# loads for that project:\n# _pf_env_manual=1; . \"$_pf_lib_dir/env.sh\"; cd \"$PROJECT_DIR\"; env_load \"\" \"$PROJECT_DIR\"\n#\n# Precedence, lowest first: the config default, the setup script's output,\n# <project>/.env, <project>/.env.local, the ambient environment (a declared\n# name already set when this file is sourced), then _pf_env_set at run time.\n# The SessionStart runner (env-run.sh) resolves the first five once and writes\n# the result to the session values file; a reader takes that file as\n# authoritative and evaluates the chain live (without setup) only for names the\n# file lacks, or when there is no file at all.\n#\n# State, under ${XDG_STATE_HOME:-$HOME/.local/state}/pluginfinity/<plugin>/\n# (directories and files created under umask 077):\n# session/<session id>/env one NAME=value line per declared name, the\n# resolved value; the value is literal to the\n# end of the line\n# session/<session id>/set provenance: one NAME per line for each name\n# last written by _pf_env_set (rung 6). A\n# SessionStart rerun under the same id keeps\n# these names' values and re-resolves the rest.\n# session/<session id>/done written by the runner when it has finished\n# session/<session id>/lock/ a mkdir lock around every read-merge-write of\n# env and set; lock/at holds its epoch seconds\n# project/<cksum of dir> line 1 the latest session id, line 2 the dir\n#\n# Locking: a writer waits up to about 5 s for the lock, removes one older than\n# 10 s (or with no lock/at after 2 s) as stale, and on timeout logs and writes\n# anyway (fail open).\n#\n# Claude runs an event's hooks in parallel, so a SessionStart hook may read\n# before the runner has finished. In SessionStart only (PLUGINFINITY_EVENT),\n# env_load with a session id but no values file waits up to 3 s for the\n# runner's done marker, then resolves live with a log line. Other events never\n# wait.\n#\n# Contract for callers (the hook library and the runner):\n# _pf_env_lib_dir set before sourcing to this file's directory when\n# _pf_lib_dir names another (the hook library's) directory.\n# _pf_env_manual=1 set before sourcing to skip the automatic env_load; the\n# caller then calls env_load itself.\n# _pf_env_component the log component (hook|script|monitor); guessed if unset.\n# env_load [<session id> [<project dir>]]\n# apply the chain into the current shell and export every\n# declared name. With no session id, CLAUDE_CODE_SESSION_ID\n# names the session when it is a valid id whose values file\n# exists; otherwise the project pointer for <project dir>\n# (default: CLAUDE_PROJECT_DIR or $PWD, walked up to the\n# nearest .git) does. A <project dir> of - means no project:\n# no pointer and no .env read. An invalid session id\n# (empty, ., /, .., a backslash, a control character) is\n# logged and nothing is read. Always returns 0.\n# env_reload env_load again with the arguments the last one got.\n# _pf_env_set NAME VALUE\n# rank-6 write: under the lock, update the session values\n# file (atomically) and record NAME in the set file,\n# export NAME in this shell and, on Claude with\n# CLAUDE_ENV_FILE set, append `export NAME='VALUE'` to it.\n# Returns 1, with a log line, for an undeclared name, a\n# value holding a newline, or no valid session from the last\n# env_load. It does not check the event: the caller does.\n# The hook library's hook_env_set wraps it and always\n# returns 0, so a refusal can never fail a hook.\n# _pf_env_declared NAME 0 when NAME is declared.\n\n# >>> pluginfinity env declarations (the build replaces this block)\n_pf_env_names=''\n_pf_env_setup=''\n_pf_env_setup_timeout=10\n# <<< pluginfinity env declarations\n\n_pf_env_dir=\"${_pf_env_lib_dir:-${_pf_lib_dir:-${_pf_log_dir:-.}}}\"\nif ! command -v pf_log >/dev/null 2>&1; then\n if [ -r \"$_pf_env_dir/log.sh\" ]; then\n _pf_log_dir=\"$_pf_env_dir\"\n # shellcheck source=/dev/null\n . \"$_pf_env_dir/log.sh\"\n else\n pf_log() { return 0; }\n pf_debug() { return 0; }\n pf_debug_on() { return 1; }\n fi\nfi\nif [ -z \"${PLUGINFINITY_PLUGIN:-}\" ] && [ -r \"$_pf_env_dir/host.sh\" ]; then\n # shellcheck source=/dev/null\n . \"$_pf_env_dir/host.sh\" 2>/dev/null || :\nfi\nif [ -z \"${_pf_env_component:-}\" ]; then\n if command -v hook_log >/dev/null 2>&1; then\n _pf_env_component=hook\n elif command -v monitor_log >/dev/null 2>&1; then\n _pf_env_component=monitor\n else\n _pf_env_component=script\n fi\nfi\n\n_pf_env_log() { pf_log \"$_pf_env_component\" \"env: $*\"; }\n_pf_env_debug() { pf_debug \"$_pf_env_component\" \"env: $*\"; }\n\n_pf_env_cr=$(printf '\\r')\n_pf_env_nl='\n'\n\n# 0 when $1 is a declared name. The character check keeps eval safe.\n_pf_env_declared() {\n case ${1:-} in\n '' | [0123456789]* | *[!ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]*) return 1 ;;\n esac\n case \" $_pf_env_names \" in\n *\" $1 \"*) return 0 ;;\n esac\n return 1\n}\n\n# 0 when $1 looks like a variable name at all (declared or not).\n_pf_env_is_name() {\n case ${1:-} in\n '' | [0123456789]* | *[!ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]*) return 1 ;;\n esac\n return 0\n}\n\n# 0 when $1 is a usable session id: not empty, not ., no /, no .., no \\, no control character.\n_pf_env_valid_id() {\n case ${1:-} in\n '' | . | */* | *..* | *\\\\*) return 1 ;;\n esac\n [ \"$(printf '%s' \"$1\" | tr -d '[:cntrl:]')\" = \"$1\" ]\n}\n\n_pf_env_state_root() {\n printf '%s\\n' \"${XDG_STATE_HOME:-${HOME:-/nonexistent}/.local/state}/pluginfinity/${PLUGINFINITY_PLUGIN:-unknown}\"\n}\n\n# $1 as a physical path, or as given when it cannot be entered.\n_pf_env_physical() {\n (CDPATH='' cd -- \"$1\" 2>/dev/null && pwd -P) || printf '%s\\n' \"$1\"\n}\n\n# The project for directory $1: the nearest directory at or above it holding .git, else $1.\n_pf_env_project_of() {\n _pf_e_p=$(_pf_env_physical \"$1\")\n _pf_e_q=$_pf_e_p\n while [ -n \"$_pf_e_q\" ] && [ \"$_pf_e_q\" != / ] && [ \"$_pf_e_q\" != . ]; do\n if [ -e \"$_pf_e_q/.git\" ]; then\n printf '%s\\n' \"$_pf_e_q\"\n return 0\n fi\n _pf_e_q=$(dirname -- \"$_pf_e_q\")\n done\n printf '%s\\n' \"$_pf_e_p\"\n}\n\n# The project of a script with no session: CLAUDE_PROJECT_DIR, else $PWD, walked to .git.\n_pf_env_script_project() {\n _pf_env_project_of \"${CLAUDE_PROJECT_DIR:-$PWD}\"\n}\n\n_pf_env_key() {\n printf '%s' \"$1\" | cksum | awk '{ print $1 \"-\" $2 }'\n}\n\n_pf_env_pointer_path() { printf '%s/project/%s\\n' \"$(_pf_env_state_root)\" \"$(_pf_env_key \"$1\")\"; }\n_pf_env_session_dir() { printf '%s/session/%s\\n' \"$(_pf_env_state_root)\" \"$1\"; }\n_pf_env_values_path() { printf '%s/env\\n' \"$(_pf_env_session_dir \"$1\")\"; }\n\n# Sleep one tick (0.1 s) and count it in _pf_e_ticks; where sleep takes whole\n# seconds only, sleep 1 and count ten.\n_pf_env_nap() {\n if sleep 0.1 2>/dev/null; then\n _pf_e_ticks=$((_pf_e_ticks + 1))\n else\n sleep 1\n _pf_e_ticks=$((_pf_e_ticks + 10))\n fi\n}\n\n# Take the lock in session directory $1: mkdir with bounded retry (about 5 s).\n# A lock older than 10 s, or one whose at file is still missing after 2 s, is\n# stale and removed. On timeout, log and go on without it. Always returns 0.\n_pf_env_lock() {\n _pf_e_lk=\"$1/lock\"\n _pf_e_held=\n (umask 077 && mkdir -p \"$1\") 2>/dev/null || return 0\n _pf_e_ticks=0\n _pf_e_noat=0\n while [ \"$_pf_e_ticks\" -lt 50 ]; do\n if mkdir \"$_pf_e_lk\" 2>/dev/null; then\n date +%s >\"$_pf_e_lk/at\" 2>/dev/null || :\n _pf_e_held=1\n return 0\n fi\n _pf_e_at=$(cat \"$_pf_e_lk/at\" 2>/dev/null) || _pf_e_at=\n case $_pf_e_at in\n '' | *[!0123456789]*)\n _pf_e_noat=$((_pf_e_noat + 1))\n if [ \"$_pf_e_noat\" -gt 20 ]; then\n _pf_env_debug \"removing a lock with no time as stale\"\n rm -f \"$_pf_e_lk/at\" 2>/dev/null\n rmdir \"$_pf_e_lk\" 2>/dev/null\n _pf_e_noat=0\n continue\n fi\n ;;\n *)\n _pf_e_now=$(date +%s 2>/dev/null) || _pf_e_now=$_pf_e_at\n if [ $((_pf_e_now - _pf_e_at)) -gt 10 ]; then\n _pf_env_debug \"removing a stale lock\"\n rm -f \"$_pf_e_lk/at\" 2>/dev/null\n rmdir \"$_pf_e_lk\" 2>/dev/null\n continue\n fi\n ;;\n esac\n _pf_env_nap\n done\n _pf_env_log \"the session values lock is held too long; writing without it\"\n return 0\n}\n\n_pf_env_unlock() {\n if [ \"${_pf_e_held:-}\" = 1 ]; then\n rm -f \"$_pf_e_lk/at\" 2>/dev/null\n rmdir \"$_pf_e_lk\" 2>/dev/null\n fi\n _pf_e_held=\n return 0\n}\n\n# 0 when NAME $2 is listed in the set file of session directory $1.\n_pf_env_was_set() {\n [ -r \"$1/set\" ] || return 1\n while IFS= read -r _pf_e_sl || [ -n \"$_pf_e_sl\" ]; do\n [ \"$_pf_e_sl\" != \"$2\" ] || return 0\n done <\"$1/set\"\n return 1\n}\n\n# Under the caller's lock: the names the set file lists keep their value from the\n# values file in session directory $1 (a same-id SessionStart rerun).\n_pf_env_keep_set() {\n [ -r \"$1/set\" ] && [ -r \"$1/env\" ] || return 0\n while IFS= read -r _pf_e_l || [ -n \"$_pf_e_l\" ]; do\n _pf_e_k=${_pf_e_l%%=*}\n [ \"$_pf_e_k\" != \"$_pf_e_l\" ] || continue\n _pf_env_declared \"$_pf_e_k\" || continue\n _pf_env_was_set \"$1\" \"$_pf_e_k\" || continue\n _pf_e_v=${_pf_e_l#*=}\n eval \"_pf_env_val_$_pf_e_k=\\$_pf_e_v\"\n done <\"$1/env\"\n return 0\n}\n\n# The session id the pointer for project $1 names, when it names this very project.\n_pf_env_pointer_read() {\n _pf_e_f=$(_pf_env_pointer_path \"$1\")\n [ -r \"$_pf_e_f\" ] || return 1\n _pf_e_ps=\n _pf_e_pd=\n {\n IFS= read -r _pf_e_ps || :\n IFS= read -r _pf_e_pd || :\n } <\"$_pf_e_f\" 2>/dev/null || return 1\n [ \"$_pf_e_pd\" = \"$1\" ] || return 1\n _pf_env_valid_id \"$_pf_e_ps\" || return 1\n printf '%s\\n' \"$_pf_e_ps\"\n}\n\n# Every declared name back to its config default; nothing marked as read from a file.\n_pf_env_init() {\n for _pf_e_n in $_pf_env_names; do\n _pf_env_declared \"$_pf_e_n\" || continue\n eval \"_pf_env_val_$_pf_e_n=\\${_pf_env_default_$_pf_e_n:-}; _pf_env_got_$_pf_e_n=\"\n done\n}\n\n# Parse a .env file into the current values: KEY=value or export KEY=value,\n# one matching pair of quotes stripped, nothing expanded, declared names only.\n_pf_env_dotenv() {\n [ -e \"$1\" ] || return 0\n if [ ! -f \"$1\" ] || [ ! -r \"$1\" ]; then\n _pf_env_log \"cannot read $1; skipped\"\n return 0\n fi\n while IFS= read -r _pf_e_l || [ -n \"$_pf_e_l\" ]; do\n _pf_e_l=${_pf_e_l%\"$_pf_env_cr\"}\n _pf_e_l=${_pf_e_l#\"${_pf_e_l%%[! ]*}\"}\n case $_pf_e_l in\n 'export '* | 'export '*)\n _pf_e_l=${_pf_e_l#export}\n _pf_e_l=${_pf_e_l#\"${_pf_e_l%%[! ]*}\"}\n ;;\n esac\n _pf_e_k=${_pf_e_l%%=*}\n [ \"$_pf_e_k\" != \"$_pf_e_l\" ] || continue\n _pf_env_declared \"$_pf_e_k\" || continue\n _pf_e_v=${_pf_e_l#*=}\n case $_pf_e_v in\n \\\"*\\\")\n _pf_e_v=${_pf_e_v#\\\"}\n _pf_e_v=${_pf_e_v%\\\"}\n ;;\n \\'*\\')\n _pf_e_v=${_pf_e_v#\\'}\n _pf_e_v=${_pf_e_v%\\'}\n ;;\n esac\n eval \"_pf_env_val_$_pf_e_k=\\$_pf_e_v\"\n done <\"$1\"\n return 0\n}\n\n# The ambient values captured when this file was sourced (rung 5).\n_pf_env_ambient() {\n for _pf_e_n in $_pf_env_names; do\n _pf_env_declared \"$_pf_e_n\" || continue\n eval \"_pf_e_h=\\${_pf_env_hasamb_$_pf_e_n:-}\"\n [ \"$_pf_e_h\" = 1 ] || continue\n eval \"_pf_e_v=\\${_pf_env_amb_$_pf_e_n:-}\"\n case $_pf_e_v in\n *\"$_pf_env_nl\"*)\n _pf_env_log \"ambient $_pf_e_n holds a newline; ignored\"\n continue\n ;;\n esac\n eval \"_pf_env_val_$_pf_e_n=\\$_pf_e_v\"\n done\n return 0\n}\n\n# Rungs 3-5 over the current values, for project $1 (none when empty).\n_pf_env_live() {\n if [ -n \"${1:-}\" ]; then\n _pf_env_dotenv \"$1/.env\"\n _pf_env_dotenv \"$1/.env.local\"\n fi\n _pf_env_ambient\n}\n\n# Read a session values file over the current values, marking each name it holds.\n_pf_env_read_values() {\n while IFS= read -r _pf_e_l || [ -n \"$_pf_e_l\" ]; do\n _pf_e_k=${_pf_e_l%%=*}\n [ \"$_pf_e_k\" != \"$_pf_e_l\" ] || continue\n _pf_env_declared \"$_pf_e_k\" || continue\n _pf_e_v=${_pf_e_l#*=}\n eval \"_pf_env_val_$_pf_e_k=\\$_pf_e_v; _pf_env_got_$_pf_e_k=1\"\n done <\"$1\"\n return 0\n}\n\n# Every declared name not marked as read from the values file.\n_pf_env_missing() {\n for _pf_e_n in $_pf_env_names; do\n _pf_env_declared \"$_pf_e_n\" || continue\n eval \"_pf_e_g=\\${_pf_env_got_$_pf_e_n:-}\"\n [ \"$_pf_e_g\" = 1 ] || return 0\n done\n return 1\n}\n\n# Export the current values into this shell.\n_pf_env_apply() {\n for _pf_e_n in $_pf_env_names; do\n _pf_env_declared \"$_pf_e_n\" || continue\n eval \"$_pf_e_n=\\${_pf_env_val_$_pf_e_n:-}\"\n export \"${_pf_e_n?}\"\n done\n return 0\n}\n\n# Print $1 single-quoted for a shell, with no newline after it.\n_pf_env_squote() {\n _pf_e_r=$1\n _pf_e_o=\n while :; do\n case $_pf_e_r in\n *\\'*)\n _pf_e_o=\"$_pf_e_o${_pf_e_r%%\\'*}'\\\\''\"\n _pf_e_r=${_pf_e_r#*\\'}\n ;;\n *)\n _pf_e_o=\"$_pf_e_o$_pf_e_r\"\n break\n ;;\n esac\n done\n printf \"'%s'\" \"$_pf_e_o\"\n}\n\n# Append `export NAME='value'` for each NAME given, from the current values, to CLAUDE_ENV_FILE.\n# Only on Claude, and only when the host set CLAUDE_ENV_FILE.\n_pf_env_claude_export() {\n [ \"${PLUGINFINITY_HOST:-}\" = claude ] || return 0\n if [ -z \"${CLAUDE_ENV_FILE:-}\" ]; then\n _pf_env_log \"CLAUDE_ENV_FILE is not set; the Bash tool will not see the session values\"\n return 0\n fi\n for _pf_e_n in \"$@\"; do\n eval \"_pf_e_v=\\${_pf_env_val_$_pf_e_n:-}\"\n {\n printf 'export %s=' \"$_pf_e_n\"\n _pf_env_squote \"$_pf_e_v\"\n printf '\\n'\n } >>\"$CLAUDE_ENV_FILE\" 2>/dev/null || {\n _pf_env_log \"cannot append to CLAUDE_ENV_FILE\"\n return 0\n }\n done\n return 0\n}\n\n# Write the current values of every declared name to values file $1, atomically.\n_pf_env_write_values() {\n _pf_e_d=$(dirname -- \"$1\")\n (umask 077 && mkdir -p \"$_pf_e_d\") 2>/dev/null || {\n _pf_env_log \"cannot create $_pf_e_d; session values not written\"\n return 1\n }\n _pf_e_t=\"$1.tmp.$$\"\n (\n umask 077\n for _pf_e_n in $_pf_env_names; do\n _pf_env_declared \"$_pf_e_n\" || continue\n eval \"_pf_e_v=\\${_pf_env_val_$_pf_e_n:-}\"\n printf '%s=%s\\n' \"$_pf_e_n\" \"$_pf_e_v\"\n done >\"$_pf_e_t\"\n ) 2>/dev/null && mv -f \"$_pf_e_t\" \"$1\" 2>/dev/null && return 0\n rm -f \"$_pf_e_t\" 2>/dev/null\n _pf_env_log \"cannot write $1\"\n return 1\n}\n\nenv_load() {\n _pf_env_arg_sid=${1:-}\n _pf_env_arg_proj=${2:-}\n _pf_env_sid=\n _pf_env_file=\n [ -n \"$_pf_env_names\" ] || return 0\n case $_pf_env_arg_proj in\n -) _pf_env_proj= ;;\n '') _pf_env_proj=$(_pf_env_script_project) ;;\n *) _pf_env_proj=$_pf_env_arg_proj ;;\n esac\n if [ -n \"$_pf_env_arg_sid\" ]; then\n if _pf_env_valid_id \"$_pf_env_arg_sid\"; then\n _pf_env_sid=$_pf_env_arg_sid\n else\n _pf_env_log \"invalid session id; session values not read\"\n fi\n elif [ -n \"${CLAUDE_CODE_SESSION_ID:-}\" ] && _pf_env_valid_id \"$CLAUDE_CODE_SESSION_ID\" &&\n [ -e \"$(_pf_env_values_path \"$CLAUDE_CODE_SESSION_ID\")\" ]; then\n # Claude gives a skill script and a monitor CLAUDE_CODE_SESSION_ID, so prefer\n # its own session over the pointer, which names the project's latest one.\n # It equals the hook session_id (measured on Claude Code 2.1.291); an id\n # whose values file is missing falls back to the pointer. Copilot sets no\n # such variable for a script, so it always takes the pointer.\n _pf_env_sid=$CLAUDE_CODE_SESSION_ID\n elif [ -n \"$_pf_env_proj\" ] && _pf_e_s=$(_pf_env_pointer_read \"$_pf_env_proj\"); then\n _pf_env_sid=$_pf_e_s\n fi\n [ -z \"$_pf_env_sid\" ] || _pf_env_file=$(_pf_env_values_path \"$_pf_env_sid\")\n # In SessionStart a parallel runner may not have finished: wait for its done marker.\n if [ -n \"$_pf_env_arg_sid\" ] && [ -n \"$_pf_env_file\" ] && [ ! -e \"$_pf_env_file\" ] &&\n [ \"${PLUGINFINITY_EVENT:-}\" = SessionStart ]; then\n _pf_e_done=\"$(_pf_env_session_dir \"$_pf_env_sid\")/done\"\n _pf_e_ticks=0\n while [ ! -e \"$_pf_e_done\" ] && [ \"$_pf_e_ticks\" -lt 30 ]; do _pf_env_nap; done\n [ -e \"$_pf_e_done\" ] || _pf_env_log \"the env runner had not finished after 3s; resolving live\"\n fi\n _pf_env_init\n if [ -n \"$_pf_env_file\" ] && [ -r \"$_pf_env_file\" ]; then\n _pf_env_read_values \"$_pf_env_file\"\n if _pf_env_missing; then\n # A name the file lacks (declared after SessionStart) resolves live; file values win.\n _pf_env_init\n _pf_env_live \"$_pf_env_proj\"\n _pf_env_read_values \"$_pf_env_file\"\n fi\n else\n _pf_env_debug \"no session values; resolving live\"\n _pf_env_live \"$_pf_env_proj\"\n fi\n _pf_env_apply\n return 0\n}\n\nenv_reload() {\n env_load \"${_pf_env_arg_sid:-}\" \"${_pf_env_arg_proj:-}\"\n}\n\n_pf_env_set() {\n _pf_e_sn=${1:-}\n _pf_e_sv=${2-}\n if ! _pf_env_declared \"$_pf_e_sn\"; then\n _pf_env_log \"cannot set $_pf_e_sn: not a declared session variable\"\n return 1\n fi\n case $_pf_e_sv in\n *\"$_pf_env_nl\"*)\n _pf_env_log \"cannot set $_pf_e_sn: the value holds a newline\"\n return 1\n ;;\n esac\n if [ -z \"${_pf_env_file:-}\" ]; then\n _pf_env_log \"cannot set $_pf_e_sn: no session\"\n return 1\n fi\n # Under the lock, keep every other name as the file has it (a name it lacks keeps\n # its resolved value), then record NAME as set at rung 6.\n _pf_e_sd=$(dirname -- \"$_pf_env_file\")\n _pf_env_lock \"$_pf_e_sd\"\n if [ -r \"$_pf_env_file\" ]; then _pf_env_read_values \"$_pf_env_file\"; fi\n eval \"_pf_env_val_$_pf_e_sn=\\$_pf_e_sv\"\n if ! _pf_env_write_values \"$_pf_env_file\"; then\n _pf_env_unlock\n return 1\n fi\n if ! _pf_env_was_set \"$_pf_e_sd\" \"$_pf_e_sn\"; then\n (umask 077 && printf '%s\\n' \"$_pf_e_sn\" >>\"$_pf_e_sd/set\") 2>/dev/null ||\n _pf_env_log \"cannot record $_pf_e_sn in the set file\"\n fi\n _pf_env_unlock\n eval \"$_pf_e_sn=\\$_pf_e_sv\"\n export \"${_pf_e_sn?}\"\n _pf_env_claude_export \"$_pf_e_sn\"\n return 0\n}\n\n# Capture the ambient values once, before anything here exports a declared name.\nif [ \"${_pf_env_captured:-}\" != 1 ]; then\n _pf_env_captured=1\n for _pf_e_n in $_pf_env_names; do\n _pf_env_declared \"$_pf_e_n\" || continue\n eval \"_pf_e_h=\\${$_pf_e_n+x}\"\n if [ \"$_pf_e_h\" = x ]; then\n eval \"_pf_env_amb_$_pf_e_n=\\$$_pf_e_n; _pf_env_hasamb_$_pf_e_n=1\"\n else\n eval \"_pf_env_hasamb_$_pf_e_n=\"\n fi\n done\nfi\n\nif [ \"${_pf_env_manual:-}\" != 1 ]; then\n env_load\nfi\n:\n"
9
+ }];
10
+
11
+ //#endregion
12
+ export { ENV_LIB_FILES };
package/env.js ADDED
@@ -0,0 +1,128 @@
1
+ import { ENV_LIB_FILES } from "./env-lib.generated.js";
2
+ import { CONFIG_NOTE_PATH } from "./notes.js";
3
+
4
+ //#region src/env.ts
5
+ /**
6
+ * Seconds the env runner gives the `setup` script before it discards its
7
+ * output and resolves without it.
8
+ *
9
+ * @public
10
+ */
11
+ const ENV_SETUP_TIMEOUT = 10;
12
+ /**
13
+ * The host timeout, in seconds, of the generated SessionStart entry: the setup
14
+ * bound plus room for the runner to write the values after a setup timeout.
15
+ *
16
+ * @public
17
+ */
18
+ const ENV_RUNNER_TIMEOUT = 15;
19
+ /** The env runner's file name beside `env.sh`. */
20
+ const RUNNER = "env-run.sh";
21
+ const BLOCK = /^(# >>> pluginfinity env declarations[^\n]*\n)[\s\S]*?^(# <<< pluginfinity env declarations)$/m;
22
+ const singleQuote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
23
+ /**
24
+ * `env.sh` with its declarations block filled in: the declared names in
25
+ * config order, each default, the setup path and its time bound.
26
+ *
27
+ * @remarks
28
+ * Every value is single-quoted for the shell. The names need no quoting: the
29
+ * config schema admits only `[A-Z_][A-Z0-9_]*`.
30
+ *
31
+ * @public
32
+ */
33
+ const renderEnvLib = (env) => {
34
+ const source = ENV_LIB_FILES.find((file) => file.name === "env.sh")?.content;
35
+ if (source === void 0 || !BLOCK.test(source)) throw new Error("env.sh has no declarations block");
36
+ const names = Object.keys(env.vars);
37
+ const declarations = [
38
+ `_pf_env_names=${singleQuote(names.join(" "))}`,
39
+ ...names.map((name) => `_pf_env_default_${name}=${singleQuote(env.vars[name]?.default ?? "")}`),
40
+ `_pf_env_setup=${singleQuote(env.setup ?? "")}`,
41
+ `_pf_env_setup_timeout=${10}`,
42
+ ""
43
+ ].join("\n");
44
+ return source.replace(BLOCK, (_match, begin, end) => `${begin}${declarations}${end}`);
45
+ };
46
+ /**
47
+ * The session env library as a build writes it under `dir`: `env.sh` with its
48
+ * declarations, and the SessionStart runner `env-run.sh`.
49
+ *
50
+ * @public
51
+ */
52
+ const envLibFiles = (env, dir) => ENV_LIB_FILES.map((file) => ({
53
+ path: `${dir}/${file.name}`,
54
+ content: file.name === "env.sh" ? renderEnvLib(env) : file.content
55
+ }));
56
+ /**
57
+ * The hook entry that runs the env runner at `${PLUGIN_ROOT}/<dir>/env-run.sh`
58
+ * under `sh`, with no matcher, so it runs for every SessionStart source.
59
+ *
60
+ * @public
61
+ */
62
+ const envRunnerEntry = (dir) => ({
63
+ command: `sh "\${PLUGIN_ROOT}/${dir}/${RUNNER}"`,
64
+ timeout: 15
65
+ });
66
+ /**
67
+ * The events with `entry` first among the SessionStart entries, adding the
68
+ * event (first) when the plugin has no SessionStart hooks. A target without
69
+ * SessionStart gets the events unchanged.
70
+ *
71
+ * @remarks
72
+ * First in order is not first to finish: Claude Code runs an event's matching
73
+ * hooks in parallel, so another SessionStart hook may read before the runner
74
+ * has written the session values, and then resolves the chain live.
75
+ *
76
+ * @public
77
+ */
78
+ const withEnvRunner = (target, events, entry) => {
79
+ const existing = events.find((event) => event.event === "SessionStart");
80
+ if (existing !== void 0) return events.map((event) => event === existing ? {
81
+ ...event,
82
+ entries: [entry, ...event.entries]
83
+ } : event);
84
+ const name = target.hooks.ownEvents.includes("SessionStart") ? "SessionStart" : target.hooks.events.SessionStart;
85
+ if (typeof name !== "string") return events;
86
+ return [{
87
+ event: "SessionStart",
88
+ name,
89
+ entries: [entry]
90
+ }, ...events];
91
+ };
92
+ /**
93
+ * The build notes for a target's session env: `env-shell-unsupported` when
94
+ * the host cannot pass values from SessionStart to the model's shell, so a
95
+ * skill script must source `env.sh` to see them.
96
+ *
97
+ * @public
98
+ */
99
+ const envNotes = (target, id) => target.hooks.envShell.includes("SessionStart") ? [] : [{
100
+ target: id,
101
+ path: CONFIG_NOTE_PATH,
102
+ kind: "env-shell-unsupported",
103
+ name: "env"
104
+ }];
105
+ /**
106
+ * Seconds a SessionStart reader may wait for the env runner (3) plus headroom;
107
+ * a SessionStart hook with a smaller `timeout` can be killed while it waits.
108
+ *
109
+ * @public
110
+ */
111
+ const ENV_WAIT_TIMEOUT_FLOOR = 5;
112
+ /**
113
+ * An `env-wait-timeout` note for each SessionStart entry (other than the
114
+ * runner, which is added later) whose `timeout` is set and under
115
+ * {@link ENV_WAIT_TIMEOUT_FLOOR}: its hook library waits up to 3 s for the
116
+ * runner before it reads. The note's path is the entry's script, else `config`.
117
+ *
118
+ * @public
119
+ */
120
+ const envWaitNotes = (id, events) => events.filter((event) => event.event === "SessionStart").flatMap((event) => event.entries).filter((entry) => entry.timeout !== void 0 && entry.timeout < 5).map((entry) => ({
121
+ target: id,
122
+ path: "script" in entry ? entry.script : CONFIG_NOTE_PATH,
123
+ kind: "env-wait-timeout",
124
+ name: "SessionStart"
125
+ }));
126
+
127
+ //#endregion
128
+ export { ENV_RUNNER_TIMEOUT, ENV_SETUP_TIMEOUT, ENV_WAIT_TIMEOUT_FLOOR, envLibFiles, envNotes, envRunnerEntry, envWaitNotes, renderEnvLib, withEnvRunner };
package/errors.js CHANGED
@@ -255,7 +255,11 @@ var HookEventUnsupported = class extends Schema.TaggedError()("HookEventUnsuppor
255
255
  *
256
256
  * @public
257
257
  */
258
- const HookScriptProblem = Schema.Literals(["missing", "not-executable"]);
258
+ const HookScriptProblem = Schema.Literals([
259
+ "missing",
260
+ "not-executable",
261
+ "equals-in-path"
262
+ ]);
259
263
  /**
260
264
  * A hook `script` cannot be shipped as configured.
261
265
  *
@@ -266,13 +270,22 @@ var HookScriptInvalid = class extends Schema.TaggedError()("HookScriptInvalid",
266
270
  path: Schema.String,
267
271
  /** The script, relative to the plugin root. */
268
272
  script: Schema.String,
269
- problem: HookScriptProblem
273
+ problem: HookScriptProblem,
274
+ /** The component that runs the script: `hooks`, `monitors`, or `env` for the `env.setup` script. */
275
+ component: Schema.Literals([
276
+ "hooks",
277
+ "monitors",
278
+ "env"
279
+ ])
270
280
  }) {
281
+ get kind() {
282
+ return this.component === "monitors" ? "monitor script" : this.component === "env" ? "env setup script" : "hook script";
283
+ }
271
284
  get message() {
272
- return this.problem === "missing" ? `hook script ${this.script} named in ${this.path} does not exist` : `hook script ${this.script} is not executable, and ${this.path} sets scripts.invoke to "exec"`;
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"`;
273
286
  }
274
287
  get remediation() {
275
- return this.problem === "missing" ? { hint: `Create ${this.script} under the plugin root, or fix the path in ${this.path}.` } : { hint: `Run \`chmod +x ${this.script}\`, or drop scripts.invoke so hooks run through bash.` };
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.` };
276
289
  }
277
290
  };
278
291
  /**
@@ -334,17 +347,22 @@ var PathConflict = class extends Schema.TaggedError()("PathConflict", {
334
347
  target: Schema.String,
335
348
  /** The build path both claim, relative to `builds/<target>/`. */
336
349
  file: Schema.String,
337
- /** Why the path is taken: a generated file, a reserved library directory, or a reserved server file. */
350
+ /**
351
+ * Why the path is taken: a generated file, a reserved library directory, a reserved server file,
352
+ * or the monitors file a `monitors` field generates.
353
+ */
338
354
  conflict: Schema.Literals([
339
355
  "generated",
340
356
  "reserved-dir",
341
- "reserved-server-file"
357
+ "reserved-server-file",
358
+ "reserved-monitors-file"
342
359
  ])
343
360
  }) {
344
361
  get message() {
345
362
  switch (this.conflict) {
346
363
  case "reserved-dir": return `${this.file} is under a directory pluginfinity reserves for its injected library`;
347
364
  case "reserved-server-file": return `${this.target} loads ${this.file} as a server config file, but the plugin also ships a source file at that path`;
365
+ case "reserved-monitors-file": return `${this.target} generates ${this.file} from the monitors field, but the plugin source also has a file at that path`;
348
366
  default: return `${this.target} generates ${this.file}, but the plugin also ships a source file at that path`;
349
367
  }
350
368
  }
@@ -352,6 +370,7 @@ var PathConflict = class extends Schema.TaggedError()("PathConflict", {
352
370
  switch (this.conflict) {
353
371
  case "reserved-dir": return { hint: `Move ${this.file} out of the reserved directory.` };
354
372
  case "reserved-server-file": return { hint: `Declare those servers under mcpServers or lspServers in the pluginfinity config instead of shipping ${this.file}.` };
373
+ case "reserved-monitors-file": return { hint: `Delete the source ${this.file} and declare those monitors under the monitors field in the pluginfinity config.` };
355
374
  default: return { hint: `Delete or move the source ${this.file}; pluginfinity writes that file itself.` };
356
375
  }
357
376
  }
@@ -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_pf_event=\"\"\n_pf_marker=\"\"\n_pf_kind_prefix=\"\"\n\n# --- logging --------------------------------------------------------------\n\n_pf_write_log() { # kind message\n local dir=\"${XDG_STATE_HOME:-${HOME:-/nonexistent}/.local/state}/pluginfinity/${PLUGINFINITY_PLUGIN:-unknown}\"\n mkdir -p \"$dir\" 2>/dev/null || return 0\n printf '%s [%s] %s: %s\\n' \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\" \"${PLUGINFINITY_HOST:-unknown}\" \\\n \"$(basename \"$0\")\" \"$2\" >>\"$dir/hook-$1.log\" 2>/dev/null || return 0\n}\n\n# Append a line to the plugin's error log.\nhook_log() { _pf_write_log error \"$*\"; }\n\n# Append a line to the plugin's debug log when PLUGINFINITY_HOOK_DEBUG=1.\nhook_debug() {\n [ \"${PLUGINFINITY_HOOK_DEBUG:-0}\" = 1 ] || return 0\n _pf_write_log debug \"$*\"\n}\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_pf_lib_dir=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd) || exit 0\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# --- 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[ -n \"$_pf_input\" ] || _pf_input='{}'\n\nif ! command -v jq >/dev/null 2>&1; then\n hook_log \"jq not found; hook skipped\"\n exit 0\nfi\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 [ \"${PLUGINFINITY_HOOK_DEBUG:-0}\" = 1 ]; 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.\nhook_event() {\n if [ -n \"${PLUGINFINITY_EVENT:-}\" ]; then\n printf '%s\\n' \"$PLUGINFINITY_EVENT\"\n else\n hook_input hook_event_name\n fi\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 project the session works in: CLAUDE_PROJECT_DIR on Claude, else the\n# closest directory above the input's cwd holding .git, else that cwd.\nhook_project_dir() {\n if [ \"$PLUGINFINITY_HOST\" = claude ] && [ -n \"${CLAUDE_PROJECT_DIR:-}\" ]; then\n printf '%s\\n' \"$CLAUDE_PROJECT_DIR\"\n return 0\n fi\n local dir probe\n dir=$(hook_input cwd)\n [ -n \"$dir\" ] || dir=$PWD\n probe=$dir\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 printf '%s\\n' \"$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# Whether the host honours capability $1 on event $2 (default: this event).\n# Mirrors okf/references/{claude-code,copilot-cli}-plugin-format.md.\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 esac\n return 1\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, optionally replacing its input (JSON).\nhook_allow() {\n hook_supports allow || {\n _pf_unsupported hook_allow\n return 0\n }\n _pf_permission allow \"\" \"${1:-null}\"\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# 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 [ \"${PLUGINFINITY_HOOK_DEBUG:-0}\" = 1 ]; then hook_debug \"input: ${_pf_input:0:4000}\"; fi\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\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"
6
6
  }];
7
7
 
8
8
  //#endregion
package/hook-lib.js CHANGED
@@ -12,14 +12,21 @@ const renderHostFile = (host, plugin, version) => [
12
12
  `PLUGINFINITY_LIB_VERSION=${version}`,
13
13
  ""
14
14
  ].join("\n");
15
- /** The hook library and its `host.sh`, as one target's build writes them. */
16
- const hookLibFiles = (host, plugin, version) => [...HOOK_LIB_FILES.map((file) => ({
17
- path: `${HOOK_LIB_DIR}/${file.name}`,
18
- content: file.content
19
- })), {
20
- path: `${HOOK_LIB_DIR}/host.sh`,
21
- content: renderHostFile(host, plugin, version)
22
- }];
15
+ /** The hook library, its `host.sh` and the `tools.sh` tool map, as one target's build writes them. */
16
+ const hookLibFiles = (host, plugin, version, toolMap) => [
17
+ ...HOOK_LIB_FILES.map((file) => ({
18
+ path: `${HOOK_LIB_DIR}/${file.name}`,
19
+ content: file.content
20
+ })),
21
+ {
22
+ path: `${HOOK_LIB_DIR}/host.sh`,
23
+ content: renderHostFile(host, plugin, version)
24
+ },
25
+ {
26
+ path: `${HOOK_LIB_DIR}/tools.sh`,
27
+ content: toolMap
28
+ }
29
+ ];
23
30
 
24
31
  //#endregion
25
32
  export { HOOK_LIB_DIR, hookLibFiles, renderHostFile };
package/hook-output.js ADDED
@@ -0,0 +1,68 @@
1
+ //#region src/hook-output.ts
2
+ /** The hook library helpers whose output a host may ignore, by the `hooks.output` key that says where it is honoured. */
3
+ const HELPERS = [{
4
+ helper: "hook_context",
5
+ kind: "context"
6
+ }, {
7
+ helper: "hook_system_message",
8
+ kind: "system_message"
9
+ }];
10
+ /**
11
+ * The script text without its `#` comments: a `#` that starts a word outside
12
+ * a quoted string ends the line. Best effort, line by line: a quote left open
13
+ * across lines, a heredoc body and `$#` are not modelled.
14
+ */
15
+ const stripComments = (script) => script.split("\n").map((line) => {
16
+ let quote;
17
+ for (let index = 0; index < line.length; index++) {
18
+ const char = line.charAt(index);
19
+ if (quote !== void 0) {
20
+ if (char === "\\" && quote === "\"") index++;
21
+ else if (char === quote) quote = void 0;
22
+ } else if (char === "\\") index++;
23
+ else if (char === "'" || char === "\"") quote = char;
24
+ else if (char === "#" && (index === 0 || /\s/.test(line.charAt(index - 1)))) return line.slice(0, index);
25
+ }
26
+ return line;
27
+ }).join("\n");
28
+ /** Whether `helper` appears in `text` as a whole word. */
29
+ const callsHelper = (text, helper) => new RegExp(`(?<![A-Za-z0-9_])${helper}(?![A-Za-z0-9_])`).test(text);
30
+ /**
31
+ * The `hook-output-ignored` notes for a target's hook scripts: each `script`
32
+ * entry that calls `hook_context` or `hook_system_message` on an event where
33
+ * the host ignores that output (`target.hooks.output`).
34
+ *
35
+ * Best effort: it reads the script text, strips comments and looks for the
36
+ * helper names as words, so it cannot see a call made through a variable or a
37
+ * sourced file, and it cannot tell a call on a branch that never runs. An
38
+ * event the target owns (one outside the Claude event table) is skipped, since
39
+ * the table says nothing about it. A script `read` returns `undefined` for is
40
+ * skipped.
41
+ *
42
+ * @param id - The target's id, which each note names.
43
+ * @param target - The target description.
44
+ * @param events - The target's hook events, as `targetHooks` returns them.
45
+ * @param read - The source text of a plugin-relative script path.
46
+ */
47
+ const ignoredOutput = (id, target, events, read) => {
48
+ const notes = [];
49
+ for (const { event, entries } of events) {
50
+ if (target.hooks.ownEvents.includes(event)) continue;
51
+ for (const entry of entries) {
52
+ if (!("script" in entry)) continue;
53
+ const source = read(entry.script);
54
+ if (source === void 0) continue;
55
+ const text = stripComments(source);
56
+ for (const { helper, kind } of HELPERS) if (!target.hooks.output[kind].includes(event) && callsHelper(text, helper)) notes.push({
57
+ target: id,
58
+ path: entry.script,
59
+ kind: "hook-output-ignored",
60
+ name: `${event}:${helper}`
61
+ });
62
+ }
63
+ }
64
+ return notes;
65
+ };
66
+
67
+ //#endregion
68
+ export { ignoredOutput };