@pluginfinity/hooks 0.0.0-stage → 0.7.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.
package/index.js ADDED
@@ -0,0 +1,16 @@
1
+ import { HOOK_IO } from "./contract/events.js";
2
+ import { CLAUDE_HOOK_EVENTS, ClaudeHookEvent } from "./contract/hook-events.js";
3
+ import { TOOL_INPUTS } from "./contract/tool-inputs.js";
4
+ import { hookEventsZig } from "./contract/zig.js";
5
+ import { matcherApplies } from "./runtime/input.js";
6
+ import { ALLOWED_DECISIONS, ANSWER_EVENTS, DECISION_TAGS, makeDecision, supports } from "./contract/decisions.js";
7
+ import { FACTS_SCHEMA_VERSION, Facts, decodeFacts, factsHas, factsToolName, factsToolPrefix } from "./contract/facts.js";
8
+ import { closedResponse, encodeDecision } from "./contract/wire.js";
9
+ import { hookSchemaFiles } from "./contract.js";
10
+ import { Hook, HookModuleTypeId, isHookModule } from "./hook.js";
11
+ import { main } from "./main.js";
12
+ import { HookContext } from "./runtime/context.js";
13
+ import { DESCRIBE_FLAG, runHook } from "./runtime/runner.js";
14
+ import { HOOKS_VERSION } from "./version.js";
15
+
16
+ export { ALLOWED_DECISIONS, ANSWER_EVENTS, CLAUDE_HOOK_EVENTS, ClaudeHookEvent, DECISION_TAGS, DESCRIBE_FLAG, FACTS_SCHEMA_VERSION, Facts, HOOKS_VERSION, HOOK_IO, Hook, HookContext, HookModuleTypeId, TOOL_INPUTS, closedResponse, decodeFacts, encodeDecision, factsHas, factsToolName, factsToolPrefix, hookEventsZig, hookSchemaFiles, isHookModule, main, makeDecision, matcherApplies, runHook, supports };
package/main.js ADDED
@@ -0,0 +1,47 @@
1
+ import { basename } from "node:path";
2
+ import { NodeServices } from "@effect/platform-node";
3
+ import { Effect } from "effect";
4
+ import { runHook } from "./runtime/runner.js";
5
+
6
+ // src/main.ts
7
+ const readStdin = Effect.promise(() => new Promise((resolve) => {
8
+ if (process.stdin.isTTY) return resolve("");
9
+ const chunks = [];
10
+ process.stdin.on("data", (chunk) => chunks.push(chunk));
11
+ process.stdin.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
12
+ process.stdin.on("error", () => resolve(""));
13
+ }));
14
+ /**
15
+ * Run a module hook as this process: what a bundled hook's entry calls. It
16
+ * prints the answer and sets the exit code; nothing it meets makes it exit
17
+ * non-zero except a rewake (2) and a failed `--pluginfinity-describe` (1).
18
+ *
19
+ * @remarks
20
+ * The host reads stdout as one JSON answer, so from its first line `main`
21
+ * diverts every other write to stdout (the module's top-level code, a timer
22
+ * that fires after the handler) to stderr, and writes the answer through the
23
+ * stream's own writer.
24
+ *
25
+ * @public
26
+ */
27
+ const main = (source) => {
28
+ const answer = process.stdout.write.bind(process.stdout);
29
+ process.stdout.write = ((chunk, ...rest) => process.stderr.write(chunk, ...rest));
30
+ const program = runHook(source, {
31
+ argv: process.argv.slice(2),
32
+ env: process.env,
33
+ stdin: readStdin,
34
+ cwd: process.cwd(),
35
+ script: basename(process.argv[1] ?? "hook")
36
+ }).pipe(Effect.provide(NodeServices.layer));
37
+ Effect.runPromise(program).then((result) => {
38
+ if (result.stdout !== "") answer(result.stdout);
39
+ if (result.stderr !== "") process.stderr.write(result.stderr);
40
+ process.exitCode = result.exitCode;
41
+ }, (cause) => {
42
+ process.stderr.write(`pluginfinity hook runner failed: ${String(cause)}\n`);
43
+ process.exitCode = 0;
44
+ });
45
+ };
46
+
47
+ export { main };
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
- "name": "@pluginfinity/hooks",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@pluginfinity/hooks",
3
+ "version": "0.7.1",
4
+ "private": false,
5
+ "description": "pluginfinity's hook contract and an Effect-based builder for hooks bundled into a plugin: typed event inputs, per-event decisions and each host's wire format.",
6
+ "keywords": [
7
+ "pluginfinity",
8
+ "agent-plugin",
9
+ "hooks",
10
+ "effect"
11
+ ],
12
+ "homepage": "https://github.com/spencerbeggs/pluginfinity/tree/main/packages/hooks#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/spencerbeggs/pluginfinity/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/spencerbeggs/pluginfinity.git",
19
+ "directory": "packages/hooks"
20
+ },
21
+ "license": "MIT",
22
+ "author": {
23
+ "name": "C. Spencer Beggs",
24
+ "email": "spencer@beggs.codes",
25
+ "url": "https://spencerbeg.gs"
26
+ },
27
+ "sideEffects": false,
28
+ "type": "module",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./index.d.ts",
32
+ "import": "./index.js",
33
+ "default": "./index.js"
34
+ },
35
+ "./contract": {
36
+ "types": "./contract.d.ts",
37
+ "import": "./contract.js",
38
+ "default": "./contract.js"
39
+ },
40
+ "./testing": {
41
+ "types": "./testing.d.ts",
42
+ "import": "./testing.js",
43
+ "default": "./testing.js"
44
+ },
45
+ "./package.json": "./package.json"
46
+ },
47
+ "peerDependencies": {
48
+ "@effect/platform-node": "~4.1.0",
49
+ "effect": "~4.1.0"
50
+ },
51
+ "engines": {
52
+ "node": ">=26.0.0"
53
+ }
54
+ }
@@ -0,0 +1,84 @@
1
+ import { Context, Effect, FileSystem, Option, Path } from "effect";
2
+ import { supports } from "../contract/decisions.js";
3
+ import { decodeFacts, factsHas, factsToolName, factsToolPrefix } from "../contract/facts.js";
4
+ import { gitRoot, resolveSessionEnv, setSessionEnv } from "./env.js";
5
+ import { logLine, stateDir } from "./log.js";
6
+
7
+ // src/runtime/context.ts
8
+ const make = (options) => Effect.gen(function* () {
9
+ const fs = yield* FileSystem.FileSystem;
10
+ const path = yield* Path.Path;
11
+ const services = (effect) => effect.pipe(Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path));
12
+ const { host, event, input, env } = options;
13
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
14
+ const pluginRoot = options.pluginRoot ?? env.PLUGINFINITY_ROOT;
15
+ const plugin = env.PLUGINFINITY_PLUGIN ?? "unknown";
16
+ const state = stateDir(env, plugin);
17
+ const debugOn = env.PLUGINFINITY_DEBUG === "1";
18
+ const write = (file, message) => state === void 0 ? Effect.void : fs.makeDirectory(state, { recursive: true }).pipe(Effect.andThen(fs.writeFileString(`${state}/${file}`, logLine(now(), host, options.script, message), { flag: "a" })), Effect.ignore);
19
+ const log = (message) => write("error.log", message);
20
+ const debug = (message) => debugOn ? write("debug.log", message) : Effect.void;
21
+ const facts = pluginRoot === void 0 ? void 0 : yield* fs.readFileString(`${pluginRoot}/lib/pluginfinity/facts.json`).pipe(Effect.map(decodeFacts), Effect.tap((decoded) => decoded === void 0 ? log(`facts at ${pluginRoot} are not readable`) : Effect.void), Effect.catch(() => debug(`no facts at ${pluginRoot}/lib/pluginfinity/facts.json`).pipe(Effect.as(void 0))));
22
+ const cwd = typeof input.cwd === "string" ? input.cwd : "";
23
+ const projectDir = services(Effect.gen(function* () {
24
+ if (path.isAbsolute(cwd)) return (yield* gitRoot(cwd)) ?? cwd;
25
+ if (host === "claude") {
26
+ const fromHost = env.CLAUDE_PROJECT_DIR ?? "";
27
+ if (fromHost !== "") return fromHost;
28
+ const root = yield* gitRoot(options.cwd);
29
+ if (root !== void 0) return root;
30
+ }
31
+ return options.cwd;
32
+ }));
33
+ const sessionDir = host === "claude" && (env.CLAUDE_PROJECT_DIR ?? "") !== "" ? Effect.succeed(env.CLAUDE_PROJECT_DIR ?? "") : projectDir;
34
+ const envHost = {
35
+ host,
36
+ event,
37
+ input,
38
+ env,
39
+ declared: facts?.env?.vars ?? {},
40
+ stateDir: state,
41
+ project: Effect.gen(function* () {
42
+ if (host === "copilot" && !path.isAbsolute(cwd)) return void 0;
43
+ const dir = yield* projectDir;
44
+ const physical = yield* fs.realPath(dir).pipe(Effect.orElseSucceed(() => dir));
45
+ return (yield* gitRoot(physical)) ?? physical;
46
+ }),
47
+ log,
48
+ debug
49
+ };
50
+ const resolved = yield* Effect.cached(services(resolveSessionEnv(envHost)));
51
+ let failClosed = env.PLUGINFINITY_FAIL_CLOSED === "1";
52
+ return {
53
+ event,
54
+ host,
55
+ plugin,
56
+ pluginRoot,
57
+ projectDir,
58
+ sessionDir,
59
+ toolName: (name) => facts === void 0 ? Option.some(name) : factsToolName(facts, name),
60
+ toolPrefix: (server) => facts === void 0 ? Option.none() : factsToolPrefix(facts, server),
61
+ has: (kind, name) => facts !== void 0 && factsHas(facts, kind, name),
62
+ supports: (tag) => supports(host, tag, event),
63
+ env: Effect.map(resolved, (session) => session?.values ?? /* @__PURE__ */ new Map()),
64
+ envSet: (name, value) => Effect.flatMap(resolved, (session) => services(setSessionEnv(envHost, session, name, value))),
65
+ log,
66
+ debug,
67
+ failClosed: Effect.sync(() => {
68
+ failClosed = true;
69
+ }),
70
+ failsClosed: Effect.sync(() => failClosed)
71
+ };
72
+ });
73
+ /**
74
+ * The hook context service a module hook's handler reads. The runner provides
75
+ * it; `HookContext.make` builds one from the process's facts.
76
+ *
77
+ * @public
78
+ */
79
+ var HookContext = class extends Context.Service()("@pluginfinity/hooks/HookContext") {
80
+ /** Build a hook context from the process's facts, environment and input. */
81
+ static make = make;
82
+ };
83
+
84
+ export { HookContext };
package/runtime/env.js ADDED
@@ -0,0 +1,210 @@
1
+ import { Effect, FileSystem, Path } from "effect";
2
+
3
+ // src/runtime/env.ts
4
+ /**
5
+ * The name of a project's pointer file: what `cksum` prints for the
6
+ * directory, `<crc>-<length>`, which is how the bash library names it.
7
+ */
8
+ const projectKey = (project) => {
9
+ const bytes = new TextEncoder().encode(project);
10
+ let crc = 0;
11
+ const feed = (byte) => {
12
+ crc ^= byte << 24;
13
+ for (let bit = 0; bit < 8; bit++) crc = crc & 0x80000000 ? crc << 1 ^ 79764919 : crc << 1;
14
+ crc >>>= 0;
15
+ };
16
+ for (const byte of bytes) feed(byte);
17
+ for (let length = bytes.length; length > 0; length = Math.floor(length / 256)) feed(length & 255);
18
+ return `${~crc >>> 0}-${bytes.length}`;
19
+ };
20
+ /** A usable session id: not empty, not `.`, and with no `/`, `..`, `\` or control character. */
21
+ const validSessionId = (id) => id !== "" && id !== "." && !id.includes("..") && !/[/\\\p{Cc}]/u.test(id);
22
+ /** Take `NAME=value` lines over `values`, for declared names; returns the names the text held. */
23
+ const applyValues = (values, text) => {
24
+ const got = /* @__PURE__ */ new Set();
25
+ for (const line of text.split("\n")) {
26
+ const eq = line.indexOf("=");
27
+ if (eq === -1) continue;
28
+ const name = line.slice(0, eq);
29
+ if (!values.has(name)) continue;
30
+ values.set(name, line.slice(eq + 1));
31
+ got.add(name);
32
+ }
33
+ return got;
34
+ };
35
+ /**
36
+ * Take a `.env` file over `values`: `KEY=value` or `export KEY=value`, one
37
+ * matching pair of quotes stripped, nothing expanded, declared names only.
38
+ */
39
+ const applyDotenv = (values, text) => {
40
+ for (const raw of text.split("\n")) {
41
+ let line = raw.replace(/\r$/, "").replace(/^[ \t]+/, "");
42
+ if (line.startsWith("export ") || line.startsWith("export ")) line = line.slice(6).replace(/^[ \t]+/, "");
43
+ const eq = line.indexOf("=");
44
+ if (eq === -1) continue;
45
+ const name = line.slice(0, eq);
46
+ if (!values.has(name)) continue;
47
+ let value = line.slice(eq + 1);
48
+ const first = value.charAt(0);
49
+ if (value.length >= 2 && (first === "\"" || first === "'") && value.endsWith(first)) value = value.slice(1, -1);
50
+ values.set(name, value);
51
+ }
52
+ };
53
+ /** `export NAME='value'` with the value single-quoted for a shell. */
54
+ const shellExport = (name, value) => `export ${name}='${value.replaceAll("'", `'\\''`)}'\n`;
55
+ const readText = (path) => Effect.flatMap(FileSystem.FileSystem, (fs) => fs.readFileString(path)).pipe(Effect.option, Effect.map((text) => text._tag === "Some" ? text.value : void 0));
56
+ const exists = (path) => Effect.flatMap(FileSystem.FileSystem, (fs) => fs.exists(path)).pipe(Effect.orElseSucceed(() => false));
57
+ const PRODUCERS = /* @__PURE__ */ new Set([
58
+ "SessionStart",
59
+ "Setup",
60
+ "CwdChanged",
61
+ "FileChanged"
62
+ ]);
63
+ /** Rungs 3 to 5 over `values`: the project's `.env`, its `.env.local`, then the process environment. */
64
+ const liveEnv = (h, values, project) => Effect.gen(function* () {
65
+ if (project !== void 0) for (const name of [".env", ".env.local"]) {
66
+ const path = `${project}/${name}`;
67
+ if (!(yield* exists(path))) continue;
68
+ const text = yield* readText(path);
69
+ if (text === void 0) yield* h.log(`env: cannot read ${path}; skipped`);
70
+ else applyDotenv(values, text);
71
+ }
72
+ for (const name of values.keys()) {
73
+ const value = h.env[name];
74
+ if (value === void 0) continue;
75
+ if (value.includes("\n")) yield* h.log(`env: ambient ${name} holds a newline; ignored`);
76
+ else values.set(name, value);
77
+ }
78
+ });
79
+ /** Resolve the declared session variables, or `undefined` when the build declares none. */
80
+ const resolveSessionEnv = (h) => Effect.gen(function* () {
81
+ const names = Object.keys(h.declared);
82
+ if (names.length === 0) return void 0;
83
+ const defaults = () => new Map(names.map((name) => [name, h.declared[name] ?? ""]));
84
+ const project = yield* h.project;
85
+ const sessionFile = (id, file) => h.stateDir === void 0 ? void 0 : `${h.stateDir}/session/${id}${file === "" ? "" : `/${file}`}`;
86
+ let session;
87
+ const given = typeof h.input.session_id === "string" ? h.input.session_id : "";
88
+ if (given !== "") {
89
+ if (validSessionId(given)) session = given;
90
+ else yield* h.log("env: invalid session id; session values not read");
91
+ } else {
92
+ const id = h.env.CLAUDE_CODE_SESSION_ID ?? "";
93
+ const file = validSessionId(id) ? sessionFile(id, "env") : void 0;
94
+ if (file !== void 0 && (yield* exists(file))) session = id;
95
+ if (session === void 0 && project !== void 0 && h.stateDir !== void 0) {
96
+ const [id2, dir] = ((yield* readText(`${h.stateDir}/project/${projectKey(project)}`)) ?? "").split("\n");
97
+ if (dir === project && id2 !== void 0 && validSessionId(id2)) session = id2;
98
+ }
99
+ }
100
+ const dir = session === void 0 ? void 0 : sessionFile(session, "");
101
+ const file = session === void 0 ? void 0 : sessionFile(session, "env");
102
+ if (given !== "" && file !== void 0 && h.event === "SessionStart" && !(yield* exists(file))) {
103
+ const done = sessionFile(given, "done") ?? "";
104
+ let ticks = 0;
105
+ while (!(yield* exists(done)) && ticks < 30) {
106
+ yield* Effect.sleep("100 millis");
107
+ ticks++;
108
+ }
109
+ if (!(yield* exists(done))) yield* h.log("env: the env runner had not finished after 3s; resolving live");
110
+ }
111
+ const values = defaults();
112
+ const recorded = file === void 0 ? void 0 : yield* readText(file);
113
+ if (recorded !== void 0) {
114
+ if (applyValues(values, recorded).size < names.length) {
115
+ for (const [name, value] of defaults()) values.set(name, value);
116
+ yield* liveEnv(h, values, project);
117
+ applyValues(values, recorded);
118
+ }
119
+ } else {
120
+ yield* h.debug("env: no session values; resolving live");
121
+ yield* liveEnv(h, values, project);
122
+ }
123
+ return {
124
+ values,
125
+ dir
126
+ };
127
+ });
128
+ const lockSession = (h, dir) => Effect.gen(function* () {
129
+ const fs = yield* FileSystem.FileSystem;
130
+ const lock = `${dir}/lock`;
131
+ const at = `${lock}/at`;
132
+ let ticks = 0;
133
+ let withoutTime = 0;
134
+ while (ticks < 50) {
135
+ if (yield* fs.makeDirectory(lock, { mode: 448 }).pipe(Effect.as(true), Effect.orElseSucceed(() => false))) {
136
+ yield* fs.writeFileString(at, `${Math.floor(Date.now() / 1e3)}\n`).pipe(Effect.ignore);
137
+ return true;
138
+ }
139
+ const stamp = Number.parseInt((yield* readText(at)) ?? "", 10);
140
+ let stale = false;
141
+ if (Number.isNaN(stamp)) {
142
+ withoutTime++;
143
+ stale = withoutTime > 20;
144
+ } else stale = Math.floor(Date.now() / 1e3) - stamp > 10;
145
+ if (stale) {
146
+ yield* h.debug("env: removing a stale lock");
147
+ yield* fs.remove(lock, { recursive: true }).pipe(Effect.ignore);
148
+ withoutTime = 0;
149
+ continue;
150
+ }
151
+ yield* Effect.sleep("100 millis");
152
+ ticks++;
153
+ }
154
+ yield* h.log("env: the session values lock is held too long; writing without it");
155
+ return false;
156
+ });
157
+ const append = (path, text) => Effect.flatMap(FileSystem.FileSystem, (fs) => fs.writeFileString(path, text, {
158
+ flag: "a",
159
+ mode: 384
160
+ })).pipe(Effect.ignore);
161
+ /**
162
+ * Set a declared session variable from an event that can produce one: record
163
+ * it for later hooks and, on Claude Code, append it to `CLAUDE_ENV_FILE` for
164
+ * the model's shell. A refusal is a log line; it never fails.
165
+ */
166
+ const setSessionEnv = (h, resolved, name, value) => Effect.gen(function* () {
167
+ if (resolved === void 0) return yield* h.log("envSet: no session env is declared in this build");
168
+ if (!PRODUCERS.has(h.event)) return yield* h.debug(`envSet ${name} ignored: ${h.event} does not produce session values`);
169
+ if (!resolved.values.has(name)) return yield* h.log(`envSet: cannot set ${name}: not a declared session variable`);
170
+ if (value.includes("\n")) return yield* h.log(`envSet: cannot set ${name}: the value holds a newline`);
171
+ const dir = resolved.dir;
172
+ if (dir === void 0) return yield* h.log(`envSet: cannot set ${name}: no session`);
173
+ const fs = yield* FileSystem.FileSystem;
174
+ if (!(yield* fs.makeDirectory(dir, {
175
+ recursive: true,
176
+ mode: 448
177
+ }).pipe(Effect.as(true), Effect.orElseSucceed(() => false)))) return yield* h.log(`envSet: cannot create ${dir}`);
178
+ const file = `${dir}/env`;
179
+ const held = yield* lockSession(h, dir);
180
+ if (!(yield* Effect.gen(function* () {
181
+ const current = yield* readText(file);
182
+ if (current !== void 0) applyValues(resolved.values, current);
183
+ resolved.values.set(name, value);
184
+ const next = [...resolved.values].map(([each, v]) => `${each}=${v}\n`).join("");
185
+ const tmp = `${file}.tmp`;
186
+ const wrote = yield* fs.writeFileString(tmp, next, { mode: 384 }).pipe(Effect.andThen(fs.rename(tmp, file)), Effect.as(true), Effect.orElseSucceed(() => false));
187
+ if (!wrote) yield* h.log(`envSet: cannot write ${file}`);
188
+ return wrote;
189
+ }).pipe(Effect.ensuring(held ? fs.remove(`${dir}/lock`, { recursive: true }).pipe(Effect.ignore) : Effect.void)))) return;
190
+ const setPath = `${dir}/set`;
191
+ if (!((yield* readText(setPath)) ?? "").split("\n").includes(name)) yield* append(setPath, `${name}\n`);
192
+ if (h.host === "claude") {
193
+ const envFile = h.env.CLAUDE_ENV_FILE ?? "";
194
+ if (envFile === "") return yield* h.log(`envSet: CLAUDE_ENV_FILE is not set; the Bash tool will not see ${name}`);
195
+ yield* append(envFile, shellExport(name, value));
196
+ }
197
+ });
198
+ /** The closest directory at or above `dir` holding `.git`, or `undefined`. */
199
+ const gitRoot = (dir) => Effect.gen(function* () {
200
+ const path = yield* Path.Path;
201
+ let probe = dir;
202
+ while (probe !== "" && probe !== "/" && probe !== ".") {
203
+ if (yield* exists(path.join(probe, ".git"))) return probe;
204
+ const parent = path.dirname(probe);
205
+ if (parent === probe) break;
206
+ probe = parent;
207
+ }
208
+ });
209
+
210
+ export { applyDotenv, applyValues, gitRoot, projectKey, resolveSessionEnv, setSessionEnv, shellExport, validSessionId };
@@ -0,0 +1,80 @@
1
+ // src/runtime/input.ts
2
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3
+ /**
4
+ * Read stdin's text as a JSON object, or `undefined` when it is anything else.
5
+ * The hook libraries treat a non-object as no input.
6
+ */
7
+ const parseInput = (text) => {
8
+ try {
9
+ const value = JSON.parse(text);
10
+ return isObject(value) ? value : void 0;
11
+ } catch {
12
+ return;
13
+ }
14
+ };
15
+ const snake = (key) => key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
16
+ const ALIASES = [
17
+ ["path", "file_path"],
18
+ ["file_text", "content"],
19
+ ["old_str", "old_string"],
20
+ ["new_str", "new_string"]
21
+ ];
22
+ const toolArgs = (value) => {
23
+ let args = value;
24
+ if (typeof args === "string") try {
25
+ args = JSON.parse(args);
26
+ } catch {
27
+ return value;
28
+ }
29
+ if (!isObject(args)) return args;
30
+ const fixed = { ...args };
31
+ for (const [theirs, ours] of ALIASES) if (theirs in args && !(ours in args)) fixed[ours] = args[theirs];
32
+ return fixed;
33
+ };
34
+ /**
35
+ * An input the way Claude Code would send it, as the bash `hook_envelope
36
+ * claude` and the Zig `claudeEnvelope` give it. On Copilot: snake_case top-level
37
+ * keys, `toolName` and `toolArgs` as `tool_name` and `tool_input` (parsed when a
38
+ * string), Copilot's tool input key names mapped to Claude's where Claude's is
39
+ * absent. On both: `hook_event_name` filled in from `event` when missing.
40
+ */
41
+ const claudeEnvelope = (host, event, input) => {
42
+ const out = {};
43
+ for (const [key, value] of Object.entries(input)) if (host !== "copilot") out[key] = value;
44
+ else if (key === "toolName") out.tool_name = value;
45
+ else if (key === "toolArgs" || key === "tool_input") out.tool_input = toolArgs(value);
46
+ else out[snake(key)] = value;
47
+ if (!("hook_event_name" in out) && event !== "") out.hook_event_name = event;
48
+ return out;
49
+ };
50
+ /** The Claude event name: `PLUGINFINITY_EVENT`, else the input's `hook_event_name`, else "". */
51
+ const resolveEvent = (env, input) => {
52
+ const fromEnv = env.PLUGINFINITY_EVENT ?? "";
53
+ if (fromEnv !== "") return fromEnv;
54
+ return typeof input.hook_event_name === "string" ? input.hook_event_name : "";
55
+ };
56
+ /** The input field a run-time matcher reads on the events a host may ignore the matcher for. */
57
+ const matchField = (event) => ({
58
+ SessionStart: "source",
59
+ SessionEnd: "reason",
60
+ SubagentStop: "agent_type"
61
+ })[event];
62
+ /**
63
+ * Claude Code's matcher rules: empty or `*` matches everything; a matcher of
64
+ * only `[A-Za-z0-9_| ,-]` is an exact list split on `|` or `,`, spaces around an
65
+ * item ignored; anything else is an unanchored regular expression. A pattern
66
+ * that does not compile matches, so a hook never skips over it.
67
+ *
68
+ * @public
69
+ */
70
+ const matcherApplies = (matcher, value) => {
71
+ if (matcher === "" || matcher === "*") return true;
72
+ if (/^[A-Za-z0-9_| ,-]*$/.test(matcher)) return matcher.split(/[|,]/).map((item) => item.trim()).includes(value);
73
+ try {
74
+ return new RegExp(matcher).test(value);
75
+ } catch {
76
+ return true;
77
+ }
78
+ };
79
+
80
+ export { claudeEnvelope, matchField, matcherApplies, parseInput, resolveEvent };
package/runtime/log.js ADDED
@@ -0,0 +1,15 @@
1
+ // src/runtime/log.ts
2
+ /** One line of `error.log` or `debug.log`, in the format `log.sh` writes. */
3
+ const logLine = (now, host, script, message) => `${now.toISOString().replace(/\.\d{3}Z$/, "Z")} [${host}] hook/${script}: ${message}\n`;
4
+ /**
5
+ * The plugin's state directory, `${XDG_STATE_HOME:-$HOME/.local/state}/pluginfinity/<plugin>`,
6
+ * as the hook libraries spell it. `undefined` when neither variable is set.
7
+ */
8
+ const stateDir = (env, plugin) => {
9
+ const xdg = env.XDG_STATE_HOME ?? "";
10
+ if (xdg !== "") return `${xdg}/pluginfinity/${plugin}`;
11
+ const home = env.HOME ?? "";
12
+ return home === "" ? void 0 : `${home}/.local/state/pluginfinity/${plugin}`;
13
+ };
14
+
15
+ export { logLine, stateDir };