@pluginfinity/engine 0.1.0 → 0.2.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/agents.js +24 -11
- package/body.js +116 -40
- package/component.js +14 -1
- package/doctor.js +1 -1
- package/emit.js +18 -3
- package/errors.js +70 -4
- package/frontmatter.js +73 -18
- package/hook-lib.generated.js +9 -0
- package/hook-lib.js +25 -0
- package/hooks.js +33 -9
- package/index.d.ts +354 -96
- package/index.js +7 -4
- package/manifest.js +1 -1
- package/notes.js +29 -0
- package/operations.js +192 -21
- package/package.json +5 -5
- package/server-lib.generated.js +9 -0
- package/server-lib.js +21 -0
- package/servers.js +249 -0
- package/skills.js +45 -14
- package/tokens.js +238 -0
- package/version.js +1 -1
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
//#region src/hook-lib.generated.ts
|
|
2
|
+
/** The hook library's files, embedded so a build needs no asset on disk. */
|
|
3
|
+
const HOOK_LIB_FILES = [{
|
|
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"
|
|
6
|
+
}];
|
|
7
|
+
|
|
8
|
+
//#endregion
|
|
9
|
+
export { HOOK_LIB_FILES };
|
package/hook-lib.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { HOOK_LIB_FILES } from "./hook-lib.generated.js";
|
|
2
|
+
|
|
3
|
+
//#region src/hook-lib.ts
|
|
4
|
+
/** Where every build that has hooks gets the hook library, relative to the build root. */
|
|
5
|
+
const HOOK_LIB_DIR = "hooks/lib/pluginfinity";
|
|
6
|
+
const singleQuote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
|
|
7
|
+
/** The generated `host.sh` the library sources to learn which host it runs on. */
|
|
8
|
+
const renderHostFile = (host, plugin, version) => [
|
|
9
|
+
`# Generated by pluginfinity for the ${host} build. Do not edit.`,
|
|
10
|
+
`PLUGINFINITY_HOST=${host}`,
|
|
11
|
+
`PLUGINFINITY_PLUGIN=${singleQuote(plugin)}`,
|
|
12
|
+
`PLUGINFINITY_LIB_VERSION=${version}`,
|
|
13
|
+
""
|
|
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
|
+
}];
|
|
23
|
+
|
|
24
|
+
//#endregion
|
|
25
|
+
export { HOOK_LIB_DIR, hookLibFiles, renderHostFile };
|
package/hooks.js
CHANGED
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
* The hooks a target builds, before rendering: the base `hooks` with the
|
|
4
4
|
* target's per-event overrides applied (an override replaces the base entries
|
|
5
5
|
* for its event, and `[]` removes them), each event resolved to the target's
|
|
6
|
-
* name. An event the target lacks
|
|
7
|
-
*
|
|
6
|
+
* name. An event the target lacks is omitted, and listed in `omitted`, when
|
|
7
|
+
* every entry sets `fallback: "omit"`; when any entry would fail, the event
|
|
8
|
+
* is reported in `unsupported`.
|
|
8
9
|
*
|
|
9
10
|
* @public
|
|
10
11
|
*/
|
|
@@ -17,6 +18,7 @@ const targetHooks = (target, id, config) => {
|
|
|
17
18
|
};
|
|
18
19
|
const events = [];
|
|
19
20
|
const unsupported = [];
|
|
21
|
+
const omitted = [];
|
|
20
22
|
for (const [event, entries] of Object.entries(merged)) {
|
|
21
23
|
if (entries === void 0 || entries.length === 0) continue;
|
|
22
24
|
const mapped = target.hooks.ownEvents.includes(event) ? event : target.hooks.events[event];
|
|
@@ -26,10 +28,12 @@ const targetHooks = (target, id, config) => {
|
|
|
26
28
|
entries
|
|
27
29
|
});
|
|
28
30
|
else if (entries.some((entry) => entry.fallback !== "omit")) unsupported.push({ event });
|
|
31
|
+
else omitted.push(event);
|
|
29
32
|
}
|
|
30
33
|
return {
|
|
31
34
|
events,
|
|
32
|
-
unsupported
|
|
35
|
+
unsupported,
|
|
36
|
+
omitted
|
|
33
37
|
};
|
|
34
38
|
};
|
|
35
39
|
/**
|
|
@@ -63,22 +67,42 @@ const hookCommand = (entry, root, invoke) => {
|
|
|
63
67
|
const args = (entry.args ?? []).map(shellQuote);
|
|
64
68
|
return [...invoke === "bash" ? ["bash", path] : [path], ...args].join(" ");
|
|
65
69
|
};
|
|
70
|
+
/**
|
|
71
|
+
* A `script` entry in exec form, for a host that spawns `command` with `args`
|
|
72
|
+
* and no shell: `bash` with the script path as its first argument, or under
|
|
73
|
+
* `scripts.invoke: "exec"` the script itself. The root placeholder is
|
|
74
|
+
* substituted by the host in `args`, and no shell ever parses the path.
|
|
75
|
+
*
|
|
76
|
+
* @public
|
|
77
|
+
*/
|
|
78
|
+
const hookExec = (entry, root, invoke) => {
|
|
79
|
+
const path = `${root}/${entry.script}`;
|
|
80
|
+
const args = [...entry.args ?? []];
|
|
81
|
+
return invoke === "bash" ? {
|
|
82
|
+
command: "bash",
|
|
83
|
+
args: [path, ...args]
|
|
84
|
+
} : {
|
|
85
|
+
command: path,
|
|
86
|
+
args
|
|
87
|
+
};
|
|
88
|
+
};
|
|
66
89
|
const FORMATS = {
|
|
67
|
-
"claude-hooks-json": (events, command) => ({ hooks: Object.fromEntries(events.map(({ name, entries }) => [name, entries.map((entry) => ({
|
|
90
|
+
"claude-hooks-json": (events, command, exec) => ({ hooks: Object.fromEntries(events.map(({ name, entries }) => [name, entries.map((entry) => ({
|
|
68
91
|
...entry.matcher === void 0 ? {} : { matcher: entry.matcher },
|
|
69
92
|
hooks: [{
|
|
70
93
|
type: "command",
|
|
71
|
-
command: command(entry),
|
|
94
|
+
..."script" in entry ? exec(entry) : { command: command(entry) },
|
|
72
95
|
...entry.timeout === void 0 ? {} : { timeout: entry.timeout }
|
|
73
96
|
}]
|
|
74
97
|
}))])) }),
|
|
75
98
|
"copilot-hooks-v1": (events, command) => ({
|
|
76
99
|
version: 1,
|
|
77
|
-
hooks: Object.fromEntries(events.map(({ name, entries }) => [name, entries.map((entry) => ({
|
|
100
|
+
hooks: Object.fromEntries(events.map(({ event, name, entries }) => [name, entries.map((entry) => ({
|
|
78
101
|
type: "command",
|
|
79
102
|
bash: command(entry),
|
|
80
103
|
...entry.matcher === void 0 ? {} : { matcher: entry.matcher },
|
|
81
|
-
...entry.timeout === void 0 ? {} : { timeoutSec: entry.timeout }
|
|
104
|
+
...entry.timeout === void 0 ? {} : { timeoutSec: entry.timeout },
|
|
105
|
+
env: { PLUGINFINITY_EVENT: event }
|
|
82
106
|
}))]))
|
|
83
107
|
})
|
|
84
108
|
};
|
|
@@ -92,8 +116,8 @@ const renderHooks = (target, events, invoke) => {
|
|
|
92
116
|
if (events.length === 0) return void 0;
|
|
93
117
|
const root = target.pluginRoot.hooks;
|
|
94
118
|
if (typeof root !== "string") throw new Error(`target has no plugin-root spelling for hook commands: ${root.note}`);
|
|
95
|
-
return `${JSON.stringify(FORMATS[target.hooks.format](events, (entry) => hookCommand(entry, root, invoke)), null, " ")}\n`;
|
|
119
|
+
return `${JSON.stringify(FORMATS[target.hooks.format](events, (entry) => hookCommand(entry, root, invoke), (entry) => hookExec(entry, root, invoke)), null, " ")}\n`;
|
|
96
120
|
};
|
|
97
121
|
|
|
98
122
|
//#endregion
|
|
99
|
-
export { hookCommand, hookCommandFiles, hookScripts, renderHooks, targetHooks };
|
|
123
|
+
export { hookCommand, hookCommandFiles, hookExec, hookScripts, renderHooks, targetHooks };
|