hookloom 1.0.1 → 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.
@@ -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");
@@ -5706,111 +5575,4 @@ function refine(fn, _params = {}) {
5706
5575
  function superRefine(fn, params) {
5707
5576
  return /* @__PURE__ */ _superRefine(fn, params);
5708
5577
  }
5709
- // src/registry/schema.ts
5710
- /**
5711
- * 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`.
5712
- */
5713
- const environment = record(string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u), string().regex(/^[^\0]*$/u));
5714
- const positive = number().positive();
5715
- const regularExpression = string().refine((pattern) => {
5716
- try {
5717
- new RegExp(pattern);
5718
- return true;
5719
- } catch {
5720
- return false;
5721
- }
5722
- }, "is not a valid regular expression");
5723
- const common = {
5724
- timeout: positive.optional(),
5725
- statusMessage: string().optional(),
5726
- if: string().optional(),
5727
- onFailure: _enum(["block", "continue"]).optional(),
5728
- env: environment.optional(),
5729
- /** Run the handler only when the named payload field matches, so an event it would ignore starts no process. */
5730
- when: strictObject({
5731
- field: string(),
5732
- pattern: regularExpression
5733
- }).optional(),
5734
- /** 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. */
5735
- cache: strictObject({
5736
- ttl: positive,
5737
- key: array(string()).optional(),
5738
- inputs: array(string()).optional(),
5739
- replay: boolean().optional()
5740
- }).optional(),
5741
- /** 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. */
5742
- repeat: strictObject({
5743
- window_seconds: positive,
5744
- ignore_digits: boolean().optional()
5745
- }).optional()
5746
- };
5747
- const handler = discriminatedUnion("type", [strictObject({
5748
- type: literal("command"),
5749
- command: string().min(1),
5750
- args: array(string()).optional(),
5751
- commandWindows: string().min(1).optional(),
5752
- shell: _enum(["bash", "powershell"]).optional(),
5753
- async: boolean().optional(),
5754
- asyncRewake: boolean().optional(),
5755
- additionalContextLimit: int().min(0).optional(),
5756
- ...common
5757
- }), strictObject({
5758
- type: literal("http"),
5759
- url: url({ protocol: /^https?$/u }),
5760
- headers: record(string(), string()).optional(),
5761
- allowedEnvVars: array(string()).refine((names) => new Set(names).size === names.length, "repeats a name").optional(),
5762
- ...common
5763
- })]);
5764
- const selection = {
5765
- harnesses: array(_enum(harnesses)).min(1).refine((names) => new Set(names).size === names.length, "repeats a harness"),
5766
- matcher: string().optional(),
5767
- env: environment.optional()
5768
- };
5769
- const group = union([strictObject({
5770
- ...selection,
5771
- hooks: array(handler).min(1)
5772
- }), strictObject({
5773
- ...selection,
5774
- command: string().min(1),
5775
- timeout: positive.optional()
5776
- })]);
5777
- const groups = array(group).optional();
5778
- const events = Object.fromEntries([...new Set(harnesses.flatMap((harness) => eventNames(harness)))].map((event) => [event, groups]));
5779
- const schemaPointer = { $schema: string().optional() };
5780
- /** A registry written with its events at the top level or under `hooks`. */
5781
- const registryDocument = union([strictObject({
5782
- ...schemaPointer,
5783
- config: strictObject({ env: environment.optional() }).optional(),
5784
- hooks: strictObject(events)
5785
- }), strictObject({
5786
- ...schemaPointer,
5787
- env: environment.optional(),
5788
- ...events
5789
- })]);
5790
- const eventGroups = record(string(), array(group));
5791
- /**
5792
- * Validates a parsed registry document and returns its events and shared environment.
5793
- * @throws z.ZodError when the document does not match the schema.
5794
- */
5795
- function parseRegistry(value) {
5796
- const document = registryDocument.parse(value);
5797
- if ("hooks" in document) return {
5798
- events: eventGroups.parse(document.hooks),
5799
- env: document.config?.env ?? {}
5800
- };
5801
- const entries = Object.entries(document).filter(([key]) => key !== "$schema" && key !== "env");
5802
- return {
5803
- events: eventGroups.parse(Object.fromEntries(entries)),
5804
- env: environment.parse(document.env ?? {})
5805
- };
5806
- }
5807
- /** The handlers of a group, with the single-command shorthand written out. */
5808
- function handlersOf(entry) {
5809
- if ("hooks" in entry) return entry.hooks;
5810
- return [{
5811
- type: "command",
5812
- command: entry.command,
5813
- ...entry.timeout === void 0 ? {} : { timeout: entry.timeout }
5814
- }];
5815
- }
5816
- export { array as a, number as c, strictObject as d, string as f, harnesses as h, _enum as i, object as l, eventContract as m, parseRegistry as n, boolean as o, unknown as p, registryDocument as r, looseObject as s, handlersOf as t, record 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.1",
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-DiQUS1CB.mjs";
@@ -1,109 +0,0 @@
1
- import { existsSync, mkdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
- import { homedir } from "node:os";
3
- import { basename, delimiter, dirname, join } from "node:path";
4
- import { randomUUID } from "node:crypto";
5
- // src/paths.ts
6
- /**
7
- * Where hookloom keeps a user's registry and its own disposable state.
8
- */
9
- function base(env, windows, xdg, fallback) {
10
- const chosen = process.platform === "win32" ? env[windows] : env[xdg];
11
- return chosen === void 0 || chosen === "" ? join(homedir(), ...fallback) : chosen;
12
- }
13
- /** The user's hookloom directory in their configuration directory. */
14
- function configurationDirectory(env) {
15
- return join(base(env, "APPDATA", "XDG_CONFIG_HOME", [".config"]), "hookloom");
16
- }
17
- /** The registry file: `HOOKLOOM_REGISTRY` when set, otherwise `registry.json` in the configuration directory. */
18
- function registryPath(env) {
19
- return env["HOOKLOOM_REGISTRY"] ?? join(configurationDirectory(env), "registry.json");
20
- }
21
- /** Cached results and session state, all of which may be deleted at any time: `HOOKLOOM_CACHE_DIR` overrides it. */
22
- function cacheDirectory(env) {
23
- return env["HOOKLOOM_CACHE_DIR"] ?? join(base(env, "LOCALAPPDATA", "XDG_CACHE_HOME", [".cache"]), "hookloom");
24
- }
25
- /** The directory of Claude Code's user settings. */
26
- function claudeDirectory(env) {
27
- return env["CLAUDE_CONFIG_DIR"] ?? join(homedir(), ".claude");
28
- }
29
- // src/files.ts
30
- /**
31
- * File writes that a concurrent reader never sees half done.
32
- */
33
- const OWNER_ONLY = 384;
34
- const PERMISSION_BITS = 511;
35
- /** Replaces a file in one step, keeping its permissions; a new file is readable by its owner only. */
36
- function atomicWrite(path, content) {
37
- mkdirSync(dirname(path), { recursive: true });
38
- const existing = statSync(path, { throwIfNoEntry: false });
39
- const temporary = join(dirname(path), `.${basename(path)}.${randomUUID()}`);
40
- try {
41
- writeFileSync(temporary, content, {
42
- mode: existing === void 0 ? OWNER_ONLY : existing.mode & PERMISSION_BITS,
43
- flush: true
44
- });
45
- renameSync(temporary, path);
46
- } finally {
47
- rmSync(temporary, { force: true });
48
- }
49
- }
50
- // src/version.ts
51
- const version = "1.0.1";
52
- // src/dispatch/command-line.ts
53
- /**
54
- * The program and arguments with which each harness runs a command hook on each platform.
55
- */
56
- const GIT_BASH_INSTALLS = ["C:\\Program Files\\Git\\bin\\bash.exe", "C:\\Program Files (x86)\\Git\\bin\\bash.exe"];
57
- function gitBash(platform) {
58
- return platform.env["CLAUDE_CODE_GIT_BASH_PATH"] ?? GIT_BASH_INSTALLS.find((path) => existsSync(path));
59
- }
60
- /** Whether Claude Code would run a hook command through PowerShell: on Windows without Git Bash. */
61
- function claudeUsesPowerShell(platform) {
62
- return platform.windows && gitBash(platform) === void 0;
63
- }
64
- function onPath(platform, program) {
65
- return (platform.env["PATH"] ?? platform.env["Path"] ?? "").split(delimiter).some((directory) => directory !== "" && existsSync(join(directory, program)));
66
- }
67
- function powershell(platform, command) {
68
- return {
69
- program: onPath(platform, "pwsh.exe") ? "pwsh.exe" : "powershell.exe",
70
- args: [
71
- "-NoProfile",
72
- "-Command",
73
- command
74
- ]
75
- };
76
- }
77
- /**
78
- * Claude Code runs a command with `sh -c`, or on Windows with Git Bash and otherwise PowerShell. Codex runs it with the session's shell and no login: the user's shell, or PowerShell on Windows (`build_hooks_config` in `codex-rs/core/src/session/mod.rs`).
79
- * @throws Error when the handler asks for PowerShell outside Windows.
80
- */
81
- function invocation(harness, handler, platform) {
82
- if (handler.args !== void 0) return {
83
- program: handler.command,
84
- args: handler.args
85
- };
86
- const command = platform.windows ? handler.commandWindows ?? handler.command : handler.command;
87
- if (handler.shell === "powershell") {
88
- if (!platform.windows) throw new Error("PowerShell command hooks require Windows");
89
- return powershell(platform, command);
90
- }
91
- if (harness === "codex") return platform.windows ? powershell(platform, command) : {
92
- program: platform.env["SHELL"] ?? "/bin/sh",
93
- args: ["-c", command]
94
- };
95
- if (!platform.windows) return {
96
- program: handler.shell === "bash" ? "bash" : "/bin/sh",
97
- args: ["-c", command]
98
- };
99
- const bash = gitBash(platform);
100
- if (handler.shell === "bash") return {
101
- program: bash ?? "bash",
102
- args: ["-c", command]
103
- };
104
- return bash === void 0 ? powershell(platform, command) : {
105
- program: bash,
106
- args: ["-c", command]
107
- };
108
- }
109
- export { cacheDirectory as a, registryPath as c, atomicWrite as i, invocation as n, claudeDirectory as o, version as r, configurationDirectory as s, claudeUsesPowerShell as t };