hookloom 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,112 @@
1
+ import { n as eventNames, r as harnesses } from "./events-CHsq0Cl4.mjs";
2
+ import { a as int, c as number, d as strictObject, f as string, h as url, i as discriminatedUnion, n as array, o as literal, p as union, r as boolean, t as _enum, u as record } from "./schemas-B4KRDIno.mjs";
3
+ // src/registry/schema.ts
4
+ /**
5
+ * The shape of a registry document, defined once: the types, the runtime validator and the published JSON Schema all come from these definitions. Rules that depend on the harness or the event are in `check.ts`.
6
+ */
7
+ const environment = record(string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u), string().regex(/^[^\0]*$/u));
8
+ const positive = number().positive();
9
+ const regularExpression = string().refine((pattern) => {
10
+ try {
11
+ new RegExp(pattern);
12
+ return true;
13
+ } catch {
14
+ return false;
15
+ }
16
+ }, "is not a valid regular expression");
17
+ const common = {
18
+ timeout: positive.optional(),
19
+ statusMessage: string().optional(),
20
+ if: string().optional(),
21
+ onFailure: _enum(["block", "continue"]).optional(),
22
+ env: environment.optional(),
23
+ /** Run the handler only when the named payload field matches, so an event it would ignore starts no process. */
24
+ when: strictObject({
25
+ field: string(),
26
+ pattern: regularExpression
27
+ }).optional(),
28
+ /** Reuse a successful result for `ttl` seconds per distinct value of the `key` payload fields, while the files `inputs` matches are unchanged. A hit is silent unless `replay` is set. */
29
+ cache: strictObject({
30
+ ttl: positive,
31
+ key: array(string()).optional(),
32
+ inputs: array(string()).optional(),
33
+ replay: boolean().optional()
34
+ }).optional(),
35
+ /** Drop output identical to what the handler last emitted to the session within the window; `ignore_digits` treats texts differing only in numbers as identical. */
36
+ repeat: strictObject({
37
+ window_seconds: positive,
38
+ ignore_digits: boolean().optional()
39
+ }).optional()
40
+ };
41
+ const commandHandler = strictObject({
42
+ type: literal("command"),
43
+ command: string().min(1),
44
+ args: array(string()).optional(),
45
+ commandWindows: string().min(1).optional(),
46
+ shell: _enum(["bash", "powershell"]).optional(),
47
+ async: boolean().optional(),
48
+ asyncRewake: boolean().optional(),
49
+ additionalContextLimit: int().min(0).optional(),
50
+ ...common
51
+ });
52
+ const httpHandler = strictObject({
53
+ type: literal("http"),
54
+ url: url({ protocol: /^https?$/u }),
55
+ headers: record(string(), string()).optional(),
56
+ allowedEnvVars: array(string()).refine((names) => new Set(names).size === names.length, "repeats a name").optional(),
57
+ ...common
58
+ });
59
+ const handler = discriminatedUnion("type", [commandHandler, httpHandler]);
60
+ const selection = {
61
+ harnesses: array(_enum(harnesses)).min(1).refine((names) => new Set(names).size === names.length, "repeats a harness"),
62
+ matcher: string().optional(),
63
+ env: environment.optional()
64
+ };
65
+ const group = union([strictObject({
66
+ ...selection,
67
+ hooks: array(handler).min(1)
68
+ }), strictObject({
69
+ ...selection,
70
+ command: string().min(1),
71
+ timeout: positive.optional()
72
+ })]);
73
+ const groups = array(group).optional();
74
+ const events = Object.fromEntries([...new Set(harnesses.flatMap((harness) => eventNames(harness)))].map((event) => [event, groups]));
75
+ const schemaPointer = { $schema: string().optional() };
76
+ /** A registry written with its events at the top level or under `hooks`. */
77
+ const registryDocument = union([strictObject({
78
+ ...schemaPointer,
79
+ config: strictObject({ env: environment.optional() }).optional(),
80
+ hooks: strictObject(events)
81
+ }), strictObject({
82
+ ...schemaPointer,
83
+ env: environment.optional(),
84
+ ...events
85
+ })]);
86
+ const eventGroups = record(string(), array(group));
87
+ /**
88
+ * Validates a parsed registry document and returns its events and shared environment.
89
+ * @throws z.ZodError when the document does not match the schema.
90
+ */
91
+ function parseRegistry(value) {
92
+ const document = registryDocument.parse(value);
93
+ if ("hooks" in document) return {
94
+ events: eventGroups.parse(document.hooks),
95
+ env: document.config?.env ?? {}
96
+ };
97
+ const entries = Object.entries(document).filter(([key]) => key !== "$schema" && key !== "env");
98
+ return {
99
+ events: eventGroups.parse(Object.fromEntries(entries)),
100
+ env: environment.parse(document.env ?? {})
101
+ };
102
+ }
103
+ /** The handlers of a group, with the single-command shorthand written out. */
104
+ function handlersOf(entry) {
105
+ if ("hooks" in entry) return entry.hooks;
106
+ return [{
107
+ type: "command",
108
+ command: entry.command,
109
+ ...entry.timeout === void 0 ? {} : { timeout: entry.timeout }
110
+ }];
111
+ }
112
+ export { parseRegistry as n, registryDocument as r, handlersOf as t };
@@ -1 +1 @@
1
- export { t as handlersOf, n as parseRegistry, r as registryDocument } from "./schema-ChV-yJDT.mjs";
1
+ export { t as handlersOf, n as parseRegistry, r as registryDocument } from "./schema-Dl9EJYyt.mjs";
@@ -1,134 +1,3 @@
1
- // src/events.ts
2
- /**
3
- * What each harness does with each lifecycle event, as published at https://code.claude.com/docs/en/hooks and https://learn.chatgpt.com/docs/hooks.
4
- */
5
- const harnesses = ["claude", "codex"];
6
- const general = {
7
- decides: false,
8
- evaluatesIf: false,
9
- defaultTimeoutSeconds: 600,
10
- maxTimeoutSeconds: 600,
11
- registeredByPlugin: true
12
- };
13
- function matching(matchField) {
14
- return {
15
- ...general,
16
- matchField
17
- };
18
- }
19
- function toolEvent(matchField) {
20
- return {
21
- ...matching(matchField),
22
- evaluatesIf: true
23
- };
24
- }
25
- function deciding(contract) {
26
- return {
27
- ...contract,
28
- decides: true
29
- };
30
- }
31
- const CLAUDE_SESSION_END_SECONDS = 1.5;
32
- const CLAUDE_PROMPT_SECONDS = 30;
33
- const CLAUDE_DISPLAY_SECONDS = 10;
34
- const CODEX_SHUTDOWN_DEFAULT_SECONDS = 1;
35
- const CODEX_SHUTDOWN_MAX_SECONDS = 3;
36
- const claude = {
37
- SessionStart: matching("source"),
38
- Setup: matching("trigger"),
39
- UserPromptSubmit: deciding({
40
- ...general,
41
- defaultTimeoutSeconds: CLAUDE_PROMPT_SECONDS
42
- }),
43
- UserPromptExpansion: deciding(matching("command_name")),
44
- PreSkillShellCommand: deciding(toolEvent("tool_name")),
45
- PreToolUse: deciding(toolEvent("tool_name")),
46
- PermissionRequest: deciding(toolEvent("tool_name")),
47
- PermissionDenied: deciding(toolEvent("tool_name")),
48
- PostToolUse: toolEvent("tool_name"),
49
- PostToolUseFailure: toolEvent("tool_name"),
50
- PostToolBatch: deciding(general),
51
- Notification: matching("notification_type"),
52
- MessageDisplay: {
53
- ...general,
54
- defaultTimeoutSeconds: CLAUDE_DISPLAY_SECONDS
55
- },
56
- SubagentStart: matching("agent_type"),
57
- SubagentStop: deciding(matching("agent_type")),
58
- TaskCreated: deciding(general),
59
- TaskCompleted: deciding(general),
60
- Stop: deciding(general),
61
- StopFailure: matching("error"),
62
- TeammateIdle: deciding(general),
63
- InstructionsLoaded: matching("load_reason"),
64
- ConfigChange: deciding(matching("source")),
65
- CwdChanged: general,
66
- DirectoryAdded: matching("source"),
67
- FileChanged: {
68
- ...matching("file_path"),
69
- registeredByPlugin: false
70
- },
71
- WorktreeCreate: deciding({
72
- ...general,
73
- registeredByPlugin: false
74
- }),
75
- WorktreeRemove: deciding({
76
- ...general,
77
- registeredByPlugin: false
78
- }),
79
- PreCompact: deciding(matching("trigger")),
80
- PostCompact: matching("trigger"),
81
- PreModelSwitch: deciding({
82
- ...matching("to_model"),
83
- defaultTimeoutSeconds: CLAUDE_PROMPT_SECONDS
84
- }),
85
- PostModelSwitch: {
86
- ...matching("to_model"),
87
- defaultTimeoutSeconds: CLAUDE_PROMPT_SECONDS
88
- },
89
- Elicitation: deciding(matching("mcp_server_name")),
90
- ElicitationResult: deciding(matching("mcp_server_name")),
91
- SessionEnd: {
92
- ...matching("reason"),
93
- defaultTimeoutSeconds: CLAUDE_SESSION_END_SECONDS,
94
- maxTimeoutSeconds: CLAUDE_SESSION_END_SECONDS
95
- }
96
- };
97
- const codexShutdown = {
98
- ...general,
99
- defaultTimeoutSeconds: CODEX_SHUTDOWN_DEFAULT_SECONDS,
100
- maxTimeoutSeconds: CODEX_SHUTDOWN_MAX_SECONDS
101
- };
102
- const contracts = {
103
- claude,
104
- codex: {
105
- SessionStart: matching("source"),
106
- UserPromptSubmit: deciding(general),
107
- PreToolUse: deciding(matching("tool_name")),
108
- PermissionRequest: deciding(matching("tool_name")),
109
- PostToolUse: matching("tool_name"),
110
- PreModelRequest: deciding(general),
111
- PostModelRequest: general,
112
- PreCompact: deciding(matching("trigger")),
113
- PostCompact: matching("trigger"),
114
- SubagentStart: matching("agent_type"),
115
- SubagentStop: deciding(matching("agent_type")),
116
- Stop: deciding(general),
117
- Interrupt: codexShutdown,
118
- SessionEnd: {
119
- ...codexShutdown,
120
- matchField: "reason"
121
- }
122
- }
123
- };
124
- /** Every event the harness documents, in the order of its contract table. */
125
- function eventNames(harness) {
126
- return Object.keys(contracts[harness]);
127
- }
128
- /** The contract of an event, or `undefined` when the harness has no such event. */
129
- function eventContract(harness, event) {
130
- return Object.hasOwn(contracts[harness], event) ? contracts[harness][event] : void 0;
131
- }
132
1
  // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/util.js
133
2
  function getEnumValues(entries) {
134
3
  const numericValues = Object.values(entries).filter((v) => typeof v === "number");
@@ -5420,6 +5289,14 @@ function strictObject(shape, params) {
5420
5289
  ...normalizeParams(params)
5421
5290
  });
5422
5291
  }
5292
+ function looseObject(shape, params) {
5293
+ return new ZodObject({
5294
+ type: "object",
5295
+ shape,
5296
+ catchall: unknown(),
5297
+ ...normalizeParams(params)
5298
+ });
5299
+ }
5423
5300
  const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => {
5424
5301
  $ZodUnion.init(inst, def);
5425
5302
  ZodType.init(inst, def);
@@ -5698,111 +5575,4 @@ function refine(fn, _params = {}) {
5698
5575
  function superRefine(fn, params) {
5699
5576
  return /* @__PURE__ */ _superRefine(fn, params);
5700
5577
  }
5701
- // src/registry/schema.ts
5702
- /**
5703
- * The shape of a registry document, defined once: the types, the runtime validator and the published JSON Schema all come from these definitions. Rules that depend on the harness or the event are in `check.ts`.
5704
- */
5705
- const environment = record(string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u), string().regex(/^[^\0]*$/u));
5706
- const positive = number().positive();
5707
- const regularExpression = string().refine((pattern) => {
5708
- try {
5709
- new RegExp(pattern);
5710
- return true;
5711
- } catch {
5712
- return false;
5713
- }
5714
- }, "is not a valid regular expression");
5715
- const common = {
5716
- timeout: positive.optional(),
5717
- statusMessage: string().optional(),
5718
- if: string().optional(),
5719
- onFailure: _enum(["block", "continue"]).optional(),
5720
- env: environment.optional(),
5721
- /** Run the handler only when the named payload field matches, so an event it would ignore starts no process. */
5722
- when: strictObject({
5723
- field: string(),
5724
- pattern: regularExpression
5725
- }).optional(),
5726
- /** Reuse a successful result for `ttl` seconds per distinct value of the `key` payload fields, while the files `inputs` matches are unchanged. A hit is silent unless `replay` is set. */
5727
- cache: strictObject({
5728
- ttl: positive,
5729
- key: array(string()).optional(),
5730
- inputs: array(string()).optional(),
5731
- replay: boolean().optional()
5732
- }).optional(),
5733
- /** Drop output identical to what the handler last emitted to the session within the window; `ignore_digits` treats texts differing only in numbers as identical. */
5734
- repeat: strictObject({
5735
- window_seconds: positive,
5736
- ignore_digits: boolean().optional()
5737
- }).optional()
5738
- };
5739
- const handler = discriminatedUnion("type", [strictObject({
5740
- type: literal("command"),
5741
- command: string().min(1),
5742
- args: array(string()).optional(),
5743
- commandWindows: string().min(1).optional(),
5744
- shell: _enum(["bash", "powershell"]).optional(),
5745
- async: boolean().optional(),
5746
- asyncRewake: boolean().optional(),
5747
- additionalContextLimit: int().min(0).optional(),
5748
- ...common
5749
- }), strictObject({
5750
- type: literal("http"),
5751
- url: url({ protocol: /^https?$/u }),
5752
- headers: record(string(), string()).optional(),
5753
- allowedEnvVars: array(string()).refine((names) => new Set(names).size === names.length, "repeats a name").optional(),
5754
- ...common
5755
- })]);
5756
- const selection = {
5757
- harnesses: array(_enum(harnesses)).min(1).refine((names) => new Set(names).size === names.length, "repeats a harness"),
5758
- matcher: string().optional(),
5759
- env: environment.optional()
5760
- };
5761
- const group = union([strictObject({
5762
- ...selection,
5763
- hooks: array(handler).min(1)
5764
- }), strictObject({
5765
- ...selection,
5766
- command: string().min(1),
5767
- timeout: positive.optional()
5768
- })]);
5769
- const groups = array(group).optional();
5770
- const events = Object.fromEntries([...new Set(harnesses.flatMap((harness) => eventNames(harness)))].map((event) => [event, groups]));
5771
- const schemaPointer = { $schema: string().optional() };
5772
- /** A registry written with its events at the top level or under `hooks`. */
5773
- const registryDocument = union([strictObject({
5774
- ...schemaPointer,
5775
- config: strictObject({ env: environment.optional() }).optional(),
5776
- hooks: strictObject(events)
5777
- }), strictObject({
5778
- ...schemaPointer,
5779
- env: environment.optional(),
5780
- ...events
5781
- })]);
5782
- const eventGroups = record(string(), array(group));
5783
- /**
5784
- * Validates a parsed registry document and returns its events and shared environment.
5785
- * @throws z.ZodError when the document does not match the schema.
5786
- */
5787
- function parseRegistry(value) {
5788
- const document = registryDocument.parse(value);
5789
- if ("hooks" in document) return {
5790
- events: eventGroups.parse(document.hooks),
5791
- env: document.config?.env ?? {}
5792
- };
5793
- const entries = Object.entries(document).filter(([key]) => key !== "$schema" && key !== "env");
5794
- return {
5795
- events: eventGroups.parse(Object.fromEntries(entries)),
5796
- env: environment.parse(document.env ?? {})
5797
- };
5798
- }
5799
- /** The handlers of a group, with the single-command shorthand written out. */
5800
- function handlersOf(entry) {
5801
- if ("hooks" in entry) return entry.hooks;
5802
- return [{
5803
- type: "command",
5804
- command: entry.command,
5805
- ...entry.timeout === void 0 ? {} : { timeout: entry.timeout }
5806
- }];
5807
- }
5808
- export { array as a, object as c, string as d, unknown as f, _enum as i, record as l, harnesses as m, parseRegistry as n, boolean as o, eventContract as p, registryDocument as r, number as s, handlersOf as t, strictObject as u };
5578
+ export { int as a, number as c, strictObject as d, string as f, url as h, discriminatedUnion as i, object as l, unknown as m, array as n, literal as o, union as p, boolean as r, looseObject as s, _enum as t, record as u };
@@ -1,4 +1,3 @@
1
- import { posix } from "node:path";
2
1
  // src/dispatch/payload.ts
3
2
  function isRecord(value) {
4
3
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -68,6 +67,8 @@ function skipTimeout(rest) {
68
67
  var Unsplittable = class extends Error {};
69
68
  var Scanner = class {
70
69
  commands = [];
70
+ words = [];
71
+ prefixes = [];
71
72
  expands = false;
72
73
  position = 0;
73
74
  source;
@@ -215,9 +216,15 @@ var Scanner = class {
215
216
  }
216
217
  const first = words[index];
217
218
  const last = words.at(-1);
218
- if (first !== void 0 && last !== void 0) this.commands.push(this.source.slice(first.start, last.end));
219
+ if (first === void 0 || last === void 0) return;
220
+ this.commands.push(this.source.slice(first.start, last.end));
221
+ this.words.push(texts.slice(index).map(unquoted));
222
+ this.prefixes.push(texts.slice(0, index).map(unquoted));
219
223
  }
220
224
  };
225
+ function unquoted(word) {
226
+ return word.replaceAll(/'([^']*)'|"((?:\\.|[^"\\])*)"|\\(.)/gsu, (_match, single, double, escaped) => single ?? double?.replaceAll(/\\([$`"\\\n])/gu, "$1") ?? escaped ?? "");
227
+ }
221
228
  /** The simple commands of a command line, or `undefined` when it cannot be split. */
222
229
  function splitCommand(command) {
223
230
  const scanner = new Scanner(command);
@@ -229,127 +236,9 @@ function splitCommand(command) {
229
236
  }
230
237
  return {
231
238
  commands: scanner.commands,
239
+ words: scanner.words,
240
+ prefixes: scanner.prefixes,
232
241
  expands: scanner.expands
233
242
  };
234
243
  }
235
- // src/dispatch/permission-rule.ts
236
- /**
237
- * Evaluates the permission rule a handler's `if` field holds against a tool call, following https://code.claude.com/docs/en/permissions and the hook-specific behaviour at https://code.claude.com/docs/en/hooks.
238
- */
239
- const COMMAND_TOOLS = /* @__PURE__ */ new Set([
240
- "Bash",
241
- "Monitor",
242
- "PowerShell"
243
- ]);
244
- const FILE_TOOLS = /* @__PURE__ */ new Map([["Edit", /* @__PURE__ */ new Set([
245
- "Edit",
246
- "Write",
247
- "NotebookEdit",
248
- "MultiEdit"
249
- ])], ["Read", /* @__PURE__ */ new Set(["Read"])]]);
250
- const PATH_RULES_NEVER_MATCHED = /* @__PURE__ */ new Set([
251
- "Write",
252
- "NotebookEdit",
253
- "MultiEdit",
254
- "Glob",
255
- "Grep"
256
- ]);
257
- const PARAMETER = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/u;
258
- function parsePermissionRule(rule) {
259
- const match = /^([^()\s]+)(?:\((.*)\))?$/su.exec(rule);
260
- const tool = match?.[1];
261
- if (tool === void 0) return void 0;
262
- const specifier = match?.[2];
263
- return specifier === void 0 || specifier === "*" ? { tool } : {
264
- tool,
265
- specifier
266
- };
267
- }
268
- /** Why a rule cannot be evaluated, or `undefined` when it can. */
269
- function permissionRuleProblem(rule) {
270
- const parsed = parsePermissionRule(rule);
271
- if (parsed === void 0) return `${JSON.stringify(rule)} is not a permission rule`;
272
- const { tool, specifier } = parsed;
273
- if (specifier === void 0 || COMMAND_TOOLS.has(tool) || FILE_TOOLS.has(tool)) return void 0;
274
- if (PATH_RULES_NEVER_MATCHED.has(tool)) return `Claude Code never matches a ${tool}(...) path rule; write an Edit or Read rule`;
275
- if (tool.startsWith("mcp__")) return "Claude Code skips an MCP rule that has parentheses";
276
- if (!PARAMETER.test(specifier)) return `cannot evaluate the specifier of a ${tool} rule`;
277
- }
278
- function escaped(text) {
279
- return text.replaceAll(/[.*+?^${}()|[\]\\]/gu, "\\$&");
280
- }
281
- /** Whether `text` matches a pattern in which `*` stands for any text. */
282
- function wildcard(pattern, text) {
283
- return new RegExp(`^${pattern.split("*").map(escaped).join(".*")}$`, "su").test(text);
284
- }
285
- function commandMatches(specifier, command) {
286
- const pattern = specifier.endsWith(":*") ? `${specifier.slice(0, -2)} *` : specifier;
287
- return command === (pattern.endsWith(" *") && pattern.indexOf("*") === pattern.length - 1 ? pattern.slice(0, -2) : void 0) || wildcard(pattern, command);
288
- }
289
- function commandRuleMatches(specifier, command) {
290
- const split = splitCommand(command);
291
- if (split === void 0) return true;
292
- const namesMoreThanTheProgram = specifier.replace(/(?: \*|:\*)$/u, "").includes(" ");
293
- if (split.expands && namesMoreThanTheProgram) return true;
294
- return split.commands.some((simple) => commandMatches(specifier, simple));
295
- }
296
- function globSource(pattern) {
297
- return pattern.split(/(\*\*\/|\*\*|\*|\?)/u).map((part) => {
298
- if (part === "**/") return "(?:[^/]*/)*";
299
- if (part === "**") return ".*";
300
- if (part === "*") return "[^/]*";
301
- return part === "?" ? "[^/]" : escaped(part);
302
- }).join("");
303
- }
304
- function posixPath(path) {
305
- return path.replaceAll("\\", "/").replace(/^([A-Za-z]):/u, (_drive, letter) => `/${letter.toLowerCase()}`);
306
- }
307
- function pathMatches(specifier, path, directories) {
308
- const target = posix.resolve(posixPath(directories.cwd), posixPath(path));
309
- let anchor = posixPath(directories.cwd);
310
- let pattern = specifier;
311
- if (specifier.startsWith("//")) {
312
- anchor = "";
313
- pattern = specifier.slice(2);
314
- } else if (specifier.startsWith("~/")) {
315
- anchor = posixPath(directories.home);
316
- pattern = specifier.slice(2);
317
- } else if (specifier.startsWith("/")) {
318
- anchor = posixPath(directories.settings);
319
- pattern = specifier.slice(1);
320
- } else if (specifier.startsWith("./")) pattern = specifier.slice(2);
321
- const anyDepth = !specifier.startsWith("./") && !specifier.startsWith("/") && !specifier.startsWith("~/") && !pattern.includes("/") ? "(?:[^/]*/)*" : "";
322
- const prefix = escaped(anchor.replace(/\/$/u, ""));
323
- return new RegExp(`^${prefix}/${anyDepth}${globSource(pattern.replace(/\/$/u, ""))}(?:/.*)?$`, "su").test(target);
324
- }
325
- function parameterMatches(specifier, payload, tool) {
326
- const match = PARAMETER.exec(specifier);
327
- const [name, expected] = [match?.[1], match?.[2]?.trim()];
328
- if (name === void 0 || expected === void 0) return false;
329
- const input = toolInput(payload);
330
- if (tool === "WebFetch" && name === "domain") {
331
- const url = input["url"];
332
- return typeof url === "string" && URL.canParse(url) && wildcard(expected, new URL(url).hostname);
333
- }
334
- const value = input[name];
335
- return (typeof value === "string" || typeof value === "number" || typeof value === "boolean") && wildcard(expected, String(value));
336
- }
337
- /** Whether a tool call satisfies a rule. A payload that describes no tool call satisfies none. */
338
- function permissionRuleMatches(rule, payload, directories) {
339
- const tool = stringField(payload, "tool_name");
340
- if (tool === void 0) return false;
341
- const covered = FILE_TOOLS.get(rule.tool);
342
- const named = rule.tool.includes("*") ? wildcard(rule.tool, tool) : tool === rule.tool;
343
- if (rule.specifier === void 0) return named;
344
- const input = toolInput(payload);
345
- if (COMMAND_TOOLS.has(rule.tool)) {
346
- const command = input["command"];
347
- return named && typeof command === "string" && commandRuleMatches(rule.specifier, command);
348
- }
349
- if (covered !== void 0) {
350
- const path = input["file_path"] ?? input["notebook_path"];
351
- return covered.has(tool) && typeof path === "string" && pathMatches(rule.specifier, path, directories);
352
- }
353
- return named && parameterMatches(rule.specifier, payload, tool);
354
- }
355
- export { namedField as a, toolInput as c, isRecord as i, permissionRuleMatches as n, parsePayload as o, permissionRuleProblem as r, stringField as s, parsePermissionRule as t };
244
+ export { stringField as a, parsePayload as i, isRecord as n, toolInput as o, namedField as r, splitCommand as t };
@@ -0,0 +1,51 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync, readdirSync, rmSync, statSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { t as atomicWrite } from "./files-CBn-xAo2.mjs";
5
+ import { a as stringField, n as isRecord } from "./shell-4WSaabze.mjs";
6
+ // src/dispatch/state.ts
7
+ /**
8
+ * Small JSON records the dispatcher keeps between events. Losing one only means a handler runs or speaks once more, so an unreadable record counts as absent.
9
+ */
10
+ function digest(identity) {
11
+ return createHash("sha256").update(JSON.stringify(identity)).digest("hex");
12
+ }
13
+ function readRecord(path) {
14
+ try {
15
+ const value = JSON.parse(readFileSync(path, "utf8"));
16
+ return isRecord(value) ? value : void 0;
17
+ } catch {
18
+ return;
19
+ }
20
+ }
21
+ /** Records state if it can: a write that fails is dropped, never turned into a hook failure. */
22
+ function writeRecord(path, record) {
23
+ try {
24
+ atomicWrite(path, JSON.stringify(record));
25
+ } catch {
26
+ return;
27
+ }
28
+ }
29
+ /** The names of the JSON files in a directory, none when it does not exist. */
30
+ function records(directory) {
31
+ try {
32
+ return readdirSync(directory).filter((name) => name.endsWith(".json")).map((name) => join(directory, name));
33
+ } catch {
34
+ return [];
35
+ }
36
+ }
37
+ function removeOlderThan(directory, milliseconds) {
38
+ const cutoff = Date.now() - milliseconds;
39
+ for (const path of records(directory)) {
40
+ const status = statSync(path, { throwIfNoEntry: false });
41
+ if (status !== void 0 && status.mtimeMs < cutoff) rmSync(path, { force: true });
42
+ }
43
+ }
44
+ /** Identifies the session, and the subagent within it, that an input belongs to; `undefined` when the harness gave no session id. */
45
+ function sessionKey(payload) {
46
+ const session = stringField(payload, "session_id");
47
+ if (session === void 0 || session === "") return void 0;
48
+ const agent = stringField(payload, "agent_id");
49
+ return agent === void 0 || agent === "" ? session : `${session}/${agent}`;
50
+ }
51
+ export { sessionKey as a, removeOlderThan as i, readRecord as n, writeRecord as o, records as r, digest as t };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "hookloom",
3
3
  "description": "One hook registry for Claude Code and Codex: a plugin that dispatches every lifecycle event to your hooks, with a CLI to set up, migrate and roll back",
4
- "version": "1.0.0",
4
+ "version": "1.1.0",
5
5
  "author": "Joseph Mearman <joseph@mearman.co.uk>",
6
6
  "bin": {
7
7
  "hookloom": "./dist/cli.mjs"
@@ -1 +0,0 @@
1
- export { t as checkRegistry } from "./check-D6B_qnUy.mjs";