hookloom 0.0.0-stage → 1.0.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/dist/cli.mjs ADDED
@@ -0,0 +1,887 @@
1
+ #!/usr/bin/env node
2
+ import { isDeepStrictEqual, parseArgs } from "node:util";
3
+ import { accessSync, constants, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
4
+ import { delimiter, dirname, extname, isAbsolute, join, resolve } from "node:path";
5
+ import { a as array, c as object, d as string, f as unknown, i as _enum, l as record$1, m as harnesses, n as parseRegistry, o as boolean, p as eventContract, s as number, u as strictObject } from "./schema-ChV-yJDT.mjs";
6
+ import { c as registryPath, i as atomicWrite, n as invocation, o as claudeDirectory, r as version, s as configurationDirectory, t as claudeUsesPowerShell } from "./command-line-BBETAyPT.mjs";
7
+ import { createHash } from "node:crypto";
8
+ import { i as isRecord } from "./permission-rule-DXm-Jvfg.mjs";
9
+ import { t as checkRegistry } from "./check-D6B_qnUy.mjs";
10
+ import { execFile, spawn } from "node:child_process";
11
+ import { createInterface } from "node:readline";
12
+ import { homedir, tmpdir } from "node:os";
13
+ import { once } from "node:events";
14
+ // src/migrate/lock.ts
15
+ /**
16
+ * One migration at a time: a directory is created in a single step on every platform, so whoever creates it holds the lock.
17
+ */
18
+ var LockedError = class extends Error {};
19
+ function withLock(path, work) {
20
+ mkdirSync(dirname(path), { recursive: true });
21
+ try {
22
+ mkdirSync(path);
23
+ } catch (error) {
24
+ if (!(error instanceof Error && "code" in error && error.code === "EEXIST")) throw error;
25
+ throw new LockedError(`another hookloom is changing these files; if none is running, remove ${path}`);
26
+ }
27
+ try {
28
+ return work();
29
+ } finally {
30
+ rmSync(path, { recursive: true });
31
+ }
32
+ }
33
+ // src/migrate/plan.ts
34
+ /**
35
+ * Decides which native hooks the dispatcher can run exactly as the harness does, and which must stay where they are.
36
+ */
37
+ const MODEL_EVENTS = /* @__PURE__ */ new Set(["PreModelSwitch", "PostModelSwitch"]);
38
+ const DESCRIPTION_LENGTH = 80;
39
+ function describeHandler(handler) {
40
+ if (!isRecord(handler)) return "unreadable handler";
41
+ const { type, command, url } = handler;
42
+ if (typeof command === "string") return command.length > DESCRIPTION_LENGTH ? `${command.slice(0, DESCRIPTION_LENGTH)}...` : command;
43
+ if (typeof url === "string") return URL.canParse(url) ? `${String(type)} hook to ${new URL(url).host}` : `${String(type)} hook`;
44
+ return `${String(type)} hook`;
45
+ }
46
+ function convert(harness, event, matcher, handler) {
47
+ const contract = eventContract(harness, event);
48
+ if (contract === void 0) return `hookloom does not know a ${harness} ${event} event`;
49
+ if (!isRecord(handler)) return "the handler is not an object";
50
+ if (handler["type"] !== "command" && handler["type"] !== "http") return "hookloom runs command and HTTP hooks only";
51
+ if (handler["asyncRewake"] === true) return "asyncRewake wakes the session later, which a dispatcher cannot do";
52
+ const compared = contract.matchField === void 0 || matcher === void 0 || matcher === "" ? void 0 : matcher;
53
+ if (compared !== void 0 && MODEL_EVENTS.has(event)) return "Claude Code compares a model matcher with a canonical name the hook input does not carry";
54
+ const group = {
55
+ harnesses: [harness],
56
+ ...compared === void 0 ? {} : { matcher: compared },
57
+ hooks: [handler]
58
+ };
59
+ let registry;
60
+ try {
61
+ registry = parseRegistry({ hooks: { [event]: [group] } });
62
+ } catch {
63
+ return `it has a field or value the registry cannot hold (fields: ${Object.keys(handler).join(", ")})`;
64
+ }
65
+ const [problem] = checkRegistry(registry);
66
+ const parsed = registry.events[event]?.[0];
67
+ return problem?.message ?? parsed ?? "it could not be read";
68
+ }
69
+ function nativeGroup(value) {
70
+ if (!isRecord(value)) return void 0;
71
+ const { matcher, hooks, ...rest } = value;
72
+ if (!Array.isArray(hooks) || Object.keys(rest).length > 0 || !(matcher === void 0 || typeof matcher === "string")) return void 0;
73
+ return {
74
+ matcher,
75
+ handlers: hooks,
76
+ raw: value
77
+ };
78
+ }
79
+ function planGroup(harness, event, value) {
80
+ const group = nativeGroup(value);
81
+ if (group === void 0) return {
82
+ staying: [{
83
+ event,
84
+ handler: "matcher group",
85
+ reason: "it has fields hookloom does not know"
86
+ }],
87
+ kept: value
88
+ };
89
+ const converted = group.handlers.map((handler) => ({
90
+ handler,
91
+ outcome: convert(harness, event, group.matcher, handler)
92
+ }));
93
+ const staying = converted.flatMap(({ handler, outcome }) => typeof outcome === "string" ? [{
94
+ event,
95
+ handler: describeHandler(handler),
96
+ reason: outcome
97
+ }] : []);
98
+ const accepted = converted.flatMap(({ outcome }) => typeof outcome === "string" ? [] : [outcome]);
99
+ const [first] = accepted;
100
+ const rest = converted.filter(({ outcome }) => typeof outcome === "string").map(({ handler }) => handler);
101
+ return {
102
+ ...first === void 0 ? {} : { moved: {
103
+ event,
104
+ group: {
105
+ ...first,
106
+ hooks: accepted.flatMap((entry) => "hooks" in entry ? entry.hooks : [])
107
+ }
108
+ } },
109
+ staying,
110
+ ...rest.length === 0 ? {} : { kept: {
111
+ ...group.raw,
112
+ hooks: rest
113
+ } }
114
+ };
115
+ }
116
+ /**
117
+ * Plans the migration of one harness's native `hooks` object.
118
+ * @throws TypeError when an event does not hold a list of matcher groups.
119
+ */
120
+ function planImport(harness, hooks) {
121
+ const events = Object.entries(hooks).map(([event, groups]) => {
122
+ if (!Array.isArray(groups)) throw new TypeError(`${harness} ${event} is not a list of matcher groups`);
123
+ return {
124
+ event,
125
+ planned: groups.map((group) => planGroup(harness, event, group))
126
+ };
127
+ });
128
+ return {
129
+ moved: events.flatMap(({ planned }) => planned.flatMap(({ moved }) => moved ?? [])),
130
+ staying: events.flatMap(({ planned }) => planned.flatMap(({ staying }) => staying)),
131
+ remaining: Object.fromEntries(events.flatMap(({ event, planned }) => {
132
+ const kept = planned.flatMap((group) => group.kept === void 0 ? [] : [group.kept]);
133
+ return kept.length === 0 ? [] : [[event, kept]];
134
+ }))
135
+ };
136
+ }
137
+ // src/migrate/apply.ts
138
+ /**
139
+ * Writes a migration with a backup taken first, and undoes it. The backup's record is complete before any file changes, so an interrupted migration can always be rolled back.
140
+ */
141
+ const record = strictObject({
142
+ rolledBack: boolean(),
143
+ files: array(strictObject({
144
+ path: string(),
145
+ /** What the file held before, or `null` when it did not exist. */
146
+ before: string().nullable(),
147
+ afterHash: string()
148
+ })),
149
+ moved: array(strictObject({
150
+ harness: _enum(harnesses),
151
+ event: string(),
152
+ group: record$1(string(), unknown())
153
+ }))
154
+ });
155
+ const emptyRegistry = `${JSON.stringify({
156
+ $schema: "https://unpkg.com/hookloom/dist/registry.schema.json",
157
+ hooks: {}
158
+ }, null, 2)}\n`;
159
+ function read(path) {
160
+ return existsSync(path) ? readFileSync(path, "utf8") : null;
161
+ }
162
+ function hash(content) {
163
+ return content === null ? "" : createHash("sha256").update(content).digest("hex");
164
+ }
165
+ function document(path, content) {
166
+ const value = JSON.parse(content);
167
+ if (!isRecord(value)) throw new TypeError(`${path} does not hold a JSON object`);
168
+ return value;
169
+ }
170
+ function serialise(value) {
171
+ return `${JSON.stringify(value, null, 2)}\n`;
172
+ }
173
+ function nativeHooks(path, content) {
174
+ if (content === null) return {};
175
+ const hooks = document(path, content)["hooks"] ?? {};
176
+ if (!isRecord(hooks)) throw new TypeError(`${path}: hooks is not an object`);
177
+ return hooks;
178
+ }
179
+ /** What importing the selected harnesses' native hooks would do. Nothing is written. */
180
+ function plan(locations, selected) {
181
+ return { plans: selected.map((harness) => ({
182
+ harness,
183
+ ...planImport(harness, nativeHooks(locations.native[harness], read(locations.native[harness])))
184
+ })) };
185
+ }
186
+ function eventsOf(registry) {
187
+ const hooks = registry["hooks"];
188
+ return isRecord(hooks) ? hooks : registry;
189
+ }
190
+ function groupsOf(events, event) {
191
+ const groups = events[event];
192
+ return Array.isArray(groups) ? groups : [];
193
+ }
194
+ function withRegistry(registry, change) {
195
+ return isRecord(registry["hooks"]) ? {
196
+ ...registry,
197
+ hooks: change(registry["hooks"])
198
+ } : change(registry);
199
+ }
200
+ function addMissing(events, additions) {
201
+ return additions.reduce((accumulated, { event, group }) => {
202
+ const groups = groupsOf(accumulated, event);
203
+ return groups.some((existing) => isDeepStrictEqual(existing, group)) ? accumulated : {
204
+ ...accumulated,
205
+ [event]: [...groups, group]
206
+ };
207
+ }, events);
208
+ }
209
+ function backups(state) {
210
+ return join(state, "backups");
211
+ }
212
+ /**
213
+ * Moves the planned handlers into the registry and out of the native files.
214
+ * @returns the backup's name, or `undefined` when there is nothing to move.
215
+ * @throws when the resulting registry could not run, or a file changes while the migration is being prepared.
216
+ */
217
+ function apply(locations, selected, now) {
218
+ return withLock(join(locations.state, "lock"), () => {
219
+ const registryBefore = read(locations.registry);
220
+ const nativeBefore = new Map(selected.map((harness) => [harness, read(locations.native[harness])]));
221
+ const { plans } = plan(locations, selected);
222
+ const moved = plans.flatMap(({ harness, moved: groups }) => groups.map(({ event, group }) => ({
223
+ harness,
224
+ event,
225
+ group
226
+ })));
227
+ if (moved.length === 0) return void 0;
228
+ const registryAfter = serialise(withRegistry(document(locations.registry, registryBefore ?? emptyRegistry), (events) => addMissing(events, moved)));
229
+ const problems = checkRegistry(parseRegistry(JSON.parse(registryAfter)));
230
+ if (problems.length > 0) throw new Error(`the registry would not run: ${problems.map(({ event, message }) => `${event}: ${message}`).join("; ")}`);
231
+ const changes = [{
232
+ path: locations.registry,
233
+ before: registryBefore,
234
+ after: registryAfter
235
+ }, ...plans.flatMap(({ harness, moved: groups, remaining }) => {
236
+ const path = locations.native[harness];
237
+ const before = nativeBefore.get(harness) ?? null;
238
+ return groups.length === 0 || before === null ? [] : [{
239
+ path,
240
+ before,
241
+ after: serialise({
242
+ ...document(path, before),
243
+ hooks: remaining
244
+ })
245
+ }];
246
+ })];
247
+ const name = now.toISOString().replaceAll(":", "-");
248
+ const directory = join(backups(locations.state), name);
249
+ mkdirSync(directory, { recursive: true });
250
+ const backup = {
251
+ rolledBack: false,
252
+ files: changes.map(({ path, before, after }) => ({
253
+ path,
254
+ before,
255
+ afterHash: hash(after)
256
+ })),
257
+ moved
258
+ };
259
+ atomicWrite(join(directory, "backup.json"), serialise(backup));
260
+ for (const { path, before } of changes) if (read(path) !== before) throw new Error(`${path} changed while the migration was being prepared; run it again`);
261
+ for (const { path, after } of changes) atomicWrite(path, after);
262
+ return name;
263
+ });
264
+ }
265
+ function latest(state) {
266
+ if (!existsSync(backups(state))) return void 0;
267
+ return readdirSync(backups(state)).toSorted().toReversed().find((name) => !load(state, name).rolledBack);
268
+ }
269
+ function load(state, name) {
270
+ return record.parse(JSON.parse(readFileSync(join(backups(state), name, "backup.json"), "utf8")));
271
+ }
272
+ /**
273
+ * Undoes a migration, by default the latest one not yet undone. A file nobody has changed since gets its previous bytes back; a changed file keeps its changes, with the moved hooks returned to the native file and removed from the registry.
274
+ * @throws when there is no migration to undo.
275
+ */
276
+ function rollback(locations, requested) {
277
+ return withLock(join(locations.state, "lock"), () => {
278
+ const name = requested ?? latest(locations.state);
279
+ if (name === void 0) throw new Error("there is no migration to roll back");
280
+ const backup = load(locations.state, name);
281
+ if (backup.rolledBack) throw new Error(`${name} has already been rolled back`);
282
+ const files = backup.files.map(({ path, before, afterHash }) => {
283
+ const current = read(path);
284
+ if (current === before) return {
285
+ path,
286
+ how: "untouched"
287
+ };
288
+ if (hash(current) === afterHash || current === null) {
289
+ if (before === null) rmSync(path, { force: true });
290
+ else atomicWrite(path, before);
291
+ return {
292
+ path,
293
+ how: "restored"
294
+ };
295
+ }
296
+ const parsed = document(path, current);
297
+ if (path === locations.registry) {
298
+ const without = (events) => Object.fromEntries(Object.entries(events).map(([event, groups]) => [event, Array.isArray(groups) ? groups.filter((group) => !backup.moved.some((entry) => entry.event === event && isDeepStrictEqual(entry.group, group))) : groups]));
299
+ atomicWrite(path, serialise(withRegistry(parsed, without)));
300
+ } else {
301
+ const harness = harnesses.find((candidate) => locations.native[candidate] === path);
302
+ const returning = backup.moved.filter((entry) => entry.harness === harness).map(({ event, group }) => ({
303
+ event,
304
+ group: Object.fromEntries(Object.entries(group).filter(([key]) => key !== "harnesses"))
305
+ }));
306
+ atomicWrite(path, serialise({
307
+ ...parsed,
308
+ hooks: addMissing(eventsOf({ hooks: nativeHooks(path, current) }), returning)
309
+ }));
310
+ }
311
+ return {
312
+ path,
313
+ how: "merged"
314
+ };
315
+ });
316
+ atomicWrite(join(backups(locations.state), name, "backup.json"), serialise({
317
+ ...backup,
318
+ rolledBack: true
319
+ }));
320
+ return {
321
+ name,
322
+ files
323
+ };
324
+ });
325
+ }
326
+ // src/cli/codex.ts
327
+ /**
328
+ * Asks Codex which hooks it would run, through the protocol its app server speaks on standard input and output.
329
+ */
330
+ const RESPONSE_TIMEOUT_MILLISECONDS = 6e4;
331
+ const hook = object({
332
+ key: string(),
333
+ currentHash: string(),
334
+ pluginId: string().nullish(),
335
+ eventName: string(),
336
+ enabled: boolean(),
337
+ trustStatus: string()
338
+ });
339
+ const response = object({ data: array(object({ hooks: array(hook) })) });
340
+ const message = object({
341
+ id: number(),
342
+ result: unknown().optional(),
343
+ error: unknown().optional(),
344
+ method: string().optional()
345
+ });
346
+ const INITIALISE_ID = 1;
347
+ /**
348
+ * Starts Codex's app server, hands `use` a way to send it requests, and stops it afterwards.
349
+ * @throws when the server exits, refuses a request or does not answer.
350
+ */
351
+ async function withAppServer(program, cwd, env, use) {
352
+ const server = spawn(program.command, [...program.args, "app-server"], {
353
+ cwd,
354
+ env,
355
+ stdio: [
356
+ "pipe",
357
+ "pipe",
358
+ "ignore"
359
+ ],
360
+ shell: process.platform === "win32" && /\.(?:cmd|bat)$/iu.test(program.command)
361
+ });
362
+ const lines = createInterface({ input: server.stdout });
363
+ const waiting = /* @__PURE__ */ new Map();
364
+ const failAll = (error) => {
365
+ for (const request of waiting.values()) request.reject(error);
366
+ waiting.clear();
367
+ };
368
+ server.once("error", failAll);
369
+ server.once("exit", () => {
370
+ failAll(/* @__PURE__ */ new Error("Codex's app server exited before answering"));
371
+ });
372
+ server.stdin.on("error", failAll);
373
+ lines.on("line", (line) => {
374
+ const reply = message.safeParse(JSON.parse(line));
375
+ if (!reply.success || reply.data.method !== void 0) return;
376
+ const request = waiting.get(reply.data.id);
377
+ waiting.delete(reply.data.id);
378
+ if (reply.data.error === void 0) request?.resolve(reply.data.result);
379
+ else request?.reject(/* @__PURE__ */ new Error(`Codex refused the request: ${JSON.stringify(reply.data.error)}`));
380
+ });
381
+ const send = (body) => {
382
+ server.stdin.write(`${JSON.stringify(body)}\n`);
383
+ };
384
+ let sent = INITIALISE_ID;
385
+ const ask = async (id, method, params) => {
386
+ let timer;
387
+ try {
388
+ return await new Promise((resolve, reject) => {
389
+ timer = setTimeout(() => {
390
+ reject(/* @__PURE__ */ new Error("Codex's app server did not answer"));
391
+ }, RESPONSE_TIMEOUT_MILLISECONDS);
392
+ waiting.set(id, {
393
+ resolve,
394
+ reject
395
+ });
396
+ send({
397
+ id,
398
+ method,
399
+ params
400
+ });
401
+ });
402
+ } finally {
403
+ clearTimeout(timer);
404
+ }
405
+ };
406
+ try {
407
+ await ask(INITIALISE_ID, "initialize", { clientInfo: {
408
+ name: "hookloom",
409
+ version: "1"
410
+ } });
411
+ send({ method: "initialized" });
412
+ return await use(async (method, params) => {
413
+ sent += 1;
414
+ return ask(sent, method, params);
415
+ });
416
+ } finally {
417
+ server.removeAllListeners("exit");
418
+ server.kill();
419
+ lines.close();
420
+ }
421
+ }
422
+ /**
423
+ * The hooks Codex lists for a working directory.
424
+ * @throws when the app server does not answer.
425
+ */
426
+ async function listHooks(program, cwd, env) {
427
+ return withAppServer(program, cwd, env, async (request) => response.parse(await request("hooks/list", { cwds: [cwd] })).data.flatMap((entry) => entry.hooks));
428
+ }
429
+ // src/cli/programs.ts
430
+ /**
431
+ * Finds and runs the programs the commands drive.
432
+ */
433
+ const COMMAND_TIMEOUT_MILLISECONDS = 3e5;
434
+ const BATCH_EXTENSIONS = /* @__PURE__ */ new Set([".cmd", ".bat"]);
435
+ /** The absolute path of a program on the PATH, or `undefined` when there is none. */
436
+ function findProgram(name, env) {
437
+ const extensions = process.platform === "win32" ? (env["PATHEXT"] ?? ".EXE;.CMD;.BAT").split(";") : [""];
438
+ return (env["PATH"] ?? env["Path"] ?? "").split(delimiter).filter((directory) => directory !== "").flatMap((directory) => extensions.map((extension) => join(directory, `${name}${extension}`))).map((path) => isAbsolute(path) ? path : resolve(path)).find((path) => existsSync(path) && statSync(path).isFile());
439
+ }
440
+ function quoted(argument) {
441
+ return /^[A-Za-z0-9_@.:/\\=-]+$/u.test(argument) ? argument : `"${argument.replaceAll("\"", "\"\"")}"`;
442
+ }
443
+ async function runProgram(program, args, env) {
444
+ const batch = process.platform === "win32" && BATCH_EXTENSIONS.has(extname(program).toLowerCase());
445
+ return new Promise((resolveFinished) => {
446
+ execFile(batch ? quoted(program) : program, batch ? args.map(quoted) : [...args], {
447
+ env,
448
+ shell: batch,
449
+ timeout: COMMAND_TIMEOUT_MILLISECONDS
450
+ }, (error, stdout, stderr) => {
451
+ resolveFinished({
452
+ code: error === null ? 0 : typeof error.code === "number" ? error.code : 1,
453
+ stdout,
454
+ stderr
455
+ });
456
+ }).stdin?.end();
457
+ });
458
+ }
459
+ // src/cli/harnesses.ts
460
+ /**
461
+ * What the commands need to know about each installed harness: where it keeps things and how its plugin commands are run.
462
+ */
463
+ const PLUGIN_ID = "hookloom@hookloom";
464
+ function codexDirectory(env) {
465
+ return env["CODEX_HOME"] ?? join(homedir(), ".codex");
466
+ }
467
+ /** The file each harness reads a user's own hooks from. */
468
+ function nativeHookFiles(env) {
469
+ return {
470
+ claude: join(claudeDirectory(env), "settings.json"),
471
+ codex: join(codexDirectory(env), "hooks.json")
472
+ };
473
+ }
474
+ const claudeList = array(object({
475
+ id: string(),
476
+ version: string(),
477
+ installPath: string(),
478
+ enabled: boolean()
479
+ }));
480
+ const codexList = object({ installed: array(object({
481
+ pluginId: string(),
482
+ version: string(),
483
+ enabled: boolean()
484
+ })) });
485
+ const INSTALL = {
486
+ claude: (source) => [[
487
+ "plugin",
488
+ "marketplace",
489
+ "add",
490
+ source
491
+ ], [
492
+ "plugin",
493
+ "install",
494
+ PLUGIN_ID
495
+ ]],
496
+ codex: (source) => [[
497
+ "plugin",
498
+ "marketplace",
499
+ "add",
500
+ source
501
+ ], [
502
+ "plugin",
503
+ "add",
504
+ PLUGIN_ID
505
+ ]]
506
+ };
507
+ /** The commands that install the plugin from a marketplace source. */
508
+ function installCommands(harness, source) {
509
+ return INSTALL[harness](source);
510
+ }
511
+ /**
512
+ * The enabled hookloom plugin of a harness, or `undefined` when it has none.
513
+ * @throws when the harness is not on the PATH or cannot list its plugins.
514
+ */
515
+ async function installedPlugin(harness, env) {
516
+ const program = findProgram(harness, env);
517
+ if (program === void 0) throw new Error(`${harness} is not on the PATH`);
518
+ const listed = await runProgram(program, [
519
+ "plugin",
520
+ "list",
521
+ "--json"
522
+ ], env);
523
+ if (listed.code !== 0) throw new Error(`${harness} could not list its plugins: ${listed.stderr.trim()}`);
524
+ const document = JSON.parse(listed.stdout);
525
+ if (harness === "claude") {
526
+ const entry = claudeList.parse(document).find((plugin) => plugin.id === "hookloom@hookloom" && plugin.enabled);
527
+ return entry === void 0 ? void 0 : {
528
+ version: entry.version,
529
+ directory: entry.installPath
530
+ };
531
+ }
532
+ const entry = codexList.parse(document).installed.find((plugin) => plugin.pluginId === "hookloom@hookloom" && plugin.enabled);
533
+ return entry === void 0 ? void 0 : {
534
+ version: entry.version,
535
+ directory: join(codexDirectory(env), "plugins", "cache", "hookloom", "hookloom", entry.version)
536
+ };
537
+ }
538
+ // src/cli/in-order.ts
539
+ /** Applies an asynchronous step to each item in turn, each starting after the one before has finished, and resolves with their results. */
540
+ async function inOrder(items, step) {
541
+ return items.reduce(async (previous, item) => [...await previous, await step(item)], Promise.resolve([]));
542
+ }
543
+ // src/cli/round-trip.ts
544
+ /**
545
+ * Proves an installed plugin end to end: runs its own hook entry, as the harness would, against a throwaway registry whose one hook leaves a mark.
546
+ */
547
+ const HOOK_FILES = {
548
+ claude: "hooks.json",
549
+ codex: "codex.json"
550
+ };
551
+ const PROBE_EVENT = "UserPromptSubmit";
552
+ const entries = object({ hooks: record$1(string(), array(object({ hooks: array(object({
553
+ command: string(),
554
+ commandWindows: string().optional()
555
+ })) }))) });
556
+ function asHandedToTheShell(harness, command, root, platform) {
557
+ if (harness === "codex") return command.replaceAll("${PLUGIN_ROOT}", root.replaceAll("\\", "/"));
558
+ return claudeUsesPowerShell(platform) ? command.replaceAll("${CLAUDE_PLUGIN_ROOT}", "${env:CLAUDE_PLUGIN_ROOT}") : command;
559
+ }
560
+ /** Resolves when the installed entry ran the probe hook; rejects with what it printed otherwise. */
561
+ async function roundTrip(harness, plugin, env) {
562
+ const directory = mkdtempSync(join(tmpdir(), "hookloom-status-"));
563
+ try {
564
+ const marker = join(directory, "ran");
565
+ const probe = join(directory, "probe.mjs");
566
+ writeFileSync(probe, `import { writeFileSync } from "node:fs";\nwriteFileSync(${JSON.stringify(marker)}, "ran");\n`);
567
+ const registry = join(directory, "registry.json");
568
+ const command = process.platform === "win32" ? "node" : JSON.stringify(process.execPath);
569
+ writeFileSync(registry, JSON.stringify({ [PROBE_EVENT]: [{
570
+ harnesses: [harness],
571
+ command: `${command} ${JSON.stringify(probe.replaceAll("\\", "/"))}`
572
+ }] }));
573
+ const handler = entries.parse(JSON.parse(readFileSync(join(plugin.directory, "hooks", HOOK_FILES[harness]), "utf8"))).hooks[PROBE_EVENT]?.[0]?.hooks[0];
574
+ if (handler === void 0) throw new Error("the installed plugin has no prompt hook entry");
575
+ const childEnv = {
576
+ ...env,
577
+ HOOKLOOM_REGISTRY: registry,
578
+ HOOKLOOM_CACHE_DIR: join(directory, "cache"),
579
+ CLAUDE_PLUGIN_ROOT: plugin.directory,
580
+ PLUGIN_ROOT: plugin.directory
581
+ };
582
+ const windows = process.platform === "win32";
583
+ const platform = {
584
+ windows,
585
+ env: childEnv
586
+ };
587
+ const configured = windows ? handler.commandWindows ?? handler.command : handler.command;
588
+ const run = invocation(harness, { command: asHandedToTheShell(harness, configured, plugin.directory, platform) }, platform);
589
+ const child = spawn(run.program, [...run.args], {
590
+ env: childEnv,
591
+ stdio: "pipe"
592
+ });
593
+ const errors = [];
594
+ child.stderr.on("data", (chunk) => {
595
+ errors.push(chunk);
596
+ });
597
+ child.stdin.once("error", () => void 0);
598
+ child.stdin.end(JSON.stringify({
599
+ hook_event_name: PROBE_EVENT,
600
+ prompt: "hookloom status"
601
+ }));
602
+ await once(child, "close");
603
+ if (!existsSync(marker)) throw new Error(Buffer.concat(errors).toString("utf8").trim() || "the probe hook did not run");
604
+ } finally {
605
+ rmSync(directory, {
606
+ recursive: true,
607
+ force: true
608
+ });
609
+ }
610
+ }
611
+ // src/cli/commands.ts
612
+ /**
613
+ * The `hookloom` commands. Each returns the status the process should exit with.
614
+ */
615
+ const DEFAULT_SOURCE = "Mearman/hookloom";
616
+ const EXAMPLES_SHOWN = 3;
617
+ const APPROVAL_STEPS = "Approve the hooks in Codex before they run: start codex, enter /hooks and trust the hookloom entries. Codex asks again after each plugin update.";
618
+ function present(env) {
619
+ return harnesses.filter((harness) => findProgram(harness, env) !== void 0);
620
+ }
621
+ function chosen(io, requested) {
622
+ const selected = requested.length > 0 ? requested : present(io.env);
623
+ if (selected.length === 0) throw new Error("neither claude nor codex is on the PATH");
624
+ return selected;
625
+ }
626
+ function recordedNode(env) {
627
+ return join(configurationDirectory(env), "node");
628
+ }
629
+ async function install(io, harness, source) {
630
+ const program = findProgram(harness, io.env);
631
+ if (program === void 0) throw new Error(`${harness} is not on the PATH`);
632
+ await inOrder(installCommands(harness, source), async (args) => {
633
+ const finished = await runProgram(program, args, io.env);
634
+ if (finished.code !== 0) throw new Error(`${harness} ${args.join(" ")} failed: ${(finished.stderr || finished.stdout).trim()}`);
635
+ });
636
+ io.say(`${harness}: installed ${PLUGIN_ID} from ${source}`);
637
+ }
638
+ async function setup(io, options) {
639
+ const source = options.source ?? DEFAULT_SOURCE;
640
+ const selected = chosen(io, options.harnesses);
641
+ await inOrder(selected, async (harness) => install(io, harness, source));
642
+ const registry = registryPath(io.env);
643
+ if (existsSync(registry)) io.say(`registry: kept ${registry}`);
644
+ else {
645
+ atomicWrite(registry, emptyRegistry);
646
+ io.say(`registry: created ${registry}`);
647
+ }
648
+ if (process.platform !== "win32") {
649
+ const node = findProgram("node", io.env) ?? process.execPath;
650
+ atomicWrite(recordedNode(io.env), `${node}\n`);
651
+ io.say(`node: recorded ${node}`);
652
+ }
653
+ if (selected.includes("claude")) io.say("Restart open Claude Code sessions, or run /reload-plugins in each.");
654
+ if (selected.includes("codex")) io.say(`${APPROVAL_STEPS} Then restart open Codex sessions.`);
655
+ return 0;
656
+ }
657
+ function registryProblems(path) {
658
+ try {
659
+ return checkRegistry(parseRegistry(JSON.parse(readFileSync(path, "utf8")))).map((problem) => `${problem.harness} ${problem.event}: ${problem.message}`);
660
+ } catch (error) {
661
+ return [error instanceof Error ? error.message : String(error)];
662
+ }
663
+ }
664
+ function validate(io, path = registryPath(io.env)) {
665
+ const problems = registryProblems(path);
666
+ if (problems.length === 0) io.say(`${path}: valid`);
667
+ else for (const problem of problems) io.say(`${path}: ${problem}`);
668
+ return problems.length === 0 ? 0 : 1;
669
+ }
670
+ function codexCommand(env) {
671
+ const command = findProgram("codex", env);
672
+ if (command === void 0) throw new Error("codex is not on the PATH");
673
+ return {
674
+ command,
675
+ args: []
676
+ };
677
+ }
678
+ /** The hookloom hooks Codex would skip because nobody has approved them as they now are. */
679
+ async function unapproved(io) {
680
+ const hooks = (await listHooks(codexCommand(io.env), io.cwd, io.env)).filter((hook) => hook.pluginId === PLUGIN_ID);
681
+ if (hooks.length === 0) return ["Codex lists no hookloom hooks"];
682
+ return hooks.filter((hook) => hook.enabled && hook.trustStatus !== "trusted").map((hook) => `${hook.eventName} is ${hook.trustStatus}`);
683
+ }
684
+ async function harnessStatus(io, harness) {
685
+ const plugin = await installedPlugin(harness, io.env);
686
+ if (plugin === void 0) {
687
+ io.say(`${harness}: the plugin is not installed`);
688
+ return false;
689
+ }
690
+ io.say(`${harness}: installed ${plugin.version}`);
691
+ let healthy = true;
692
+ if (harness === "codex") {
693
+ const waiting = await unapproved(io);
694
+ if (waiting.length === 0) io.say("codex: hooks approved");
695
+ else {
696
+ healthy = false;
697
+ io.say(`codex: ${String(waiting.length)} hooks need approval (${waiting.slice(0, EXAMPLES_SHOWN).join(", ")}). ${APPROVAL_STEPS}`);
698
+ }
699
+ }
700
+ try {
701
+ await roundTrip(harness, plugin, io.env);
702
+ io.say(`${harness}: a test hook ran through the installed plugin`);
703
+ } catch (error) {
704
+ healthy = false;
705
+ io.say(`${harness}: the installed plugin did not run a test hook: ${error instanceof Error ? error.message : String(error)}`);
706
+ }
707
+ return healthy;
708
+ }
709
+ function nodeStatus(io) {
710
+ if (process.platform === "win32") return true;
711
+ const file = recordedNode(io.env);
712
+ if (!existsSync(file)) {
713
+ io.say("node: none recorded, so hooks start only where the harness's PATH has Node. Run hookloom setup.");
714
+ return true;
715
+ }
716
+ const node = readFileSync(file, "utf8").trim();
717
+ try {
718
+ accessSync(node, constants.X_OK);
719
+ io.say(`node: ${node}`);
720
+ return true;
721
+ } catch {
722
+ io.say(`node: the recorded ${node} cannot be run. Run hookloom setup.`);
723
+ return false;
724
+ }
725
+ }
726
+ async function status(io, requested) {
727
+ let healthy = nodeStatus(io);
728
+ const registry = registryPath(io.env);
729
+ if (existsSync(registry)) healthy = validate(io, registry) === 0 && healthy;
730
+ else io.say(`registry: none at ${registry}`);
731
+ const reports = await inOrder(chosen(io, requested), async (harness) => harnessStatus(io, harness));
732
+ return healthy && reports.every(Boolean) ? 0 : 1;
733
+ }
734
+ function locations(env) {
735
+ return {
736
+ state: configurationDirectory(env),
737
+ registry: registryPath(env),
738
+ native: nativeHookFiles(env)
739
+ };
740
+ }
741
+ async function preconditions(io, selected, options) {
742
+ const missing = [];
743
+ if (!options.acknowledgeRestart) missing.push("pass --acknowledge-restart: reload or restart Claude Code sessions and close Codex sessions first, because a Claude session that has not reloaded loses the moved hooks and an open Codex session runs them twice");
744
+ if (selected.includes("codex") && !options.acknowledgeCodexReview) missing.push("pass --acknowledge-codex-review: Codex approves the dispatcher once, not each hook, so later registry edits run without review");
745
+ const uninstalled = await inOrder(selected, async (harness) => {
746
+ if (await installedPlugin(harness, io.env) === void 0) return `${harness}: the plugin is not installed; run hookloom setup first`;
747
+ return harness === "codex" && (await unapproved(io)).length > 0 ? `codex: the plugin's hooks are not all approved. ${APPROVAL_STEPS}` : void 0;
748
+ });
749
+ return [...missing, ...uninstalled.flatMap((reason) => reason ?? [])];
750
+ }
751
+ function codexInlineHooks(env) {
752
+ const config = join(dirname(nativeHookFiles(env).codex), "config.toml");
753
+ return existsSync(config) && /^\s*\[\[hooks\./mu.test(readFileSync(config, "utf8"));
754
+ }
755
+ async function importHooks(io, options) {
756
+ const selected = chosen(io, options.harnesses);
757
+ const { plans } = plan(locations(io.env), selected);
758
+ for (const { harness, moved, staying } of plans) {
759
+ const count = moved.reduce((total, { group }) => total + ("hooks" in group ? group.hooks.length : 1), 0);
760
+ io.say(`${harness}: ${String(count)} hooks would move into the registry, ${String(staying.length)} stay in ${nativeHookFiles(io.env)[harness]}`);
761
+ for (const entry of staying) io.say(` stays: ${entry.event} ${entry.handler}: ${entry.reason}`);
762
+ }
763
+ if (selected.includes("codex") && codexInlineHooks(io.env)) io.say("codex: hooks written inline in config.toml are not imported and stay there");
764
+ if (!options.apply) {
765
+ io.say("Nothing was changed. Run again with --apply to migrate.");
766
+ return 0;
767
+ }
768
+ const missing = await preconditions(io, plans.filter(({ moved }) => moved.length > 0).map(({ harness }) => harness), options);
769
+ if (missing.length > 0) {
770
+ for (const reason of missing) io.say(reason);
771
+ return 1;
772
+ }
773
+ const name = apply(locations(io.env), selected, io.now());
774
+ io.say(name === void 0 ? "There was nothing to move." : `Migrated. Undo with: hookloom rollback ${name}`);
775
+ return 0;
776
+ }
777
+ function rollbackImport(io, name) {
778
+ const result = rollback(locations(io.env), name);
779
+ for (const { path, how } of result.files) io.say(`${path}: ${how === "merged" ? "kept later changes and undid the migration" : how}`);
780
+ io.say(`Rolled back ${result.name}. Reload or restart open sessions.`);
781
+ return 0;
782
+ }
783
+ // src/cli.ts
784
+ /**
785
+ * The `hookloom` command.
786
+ */
787
+ const USAGE = `hookloom ${version}: one hook registry for Claude Code and Codex
788
+
789
+ Examples:
790
+ hookloom setup install into every harness found
791
+ hookloom import report what would move, changing nothing
792
+ hookloom status --harness codex check one harness
793
+
794
+ Usage:
795
+ hookloom setup [--harness claude|codex]... [--source <marketplace>]
796
+ Install the plugin, create the registry and record where Node is.
797
+ hookloom status [--harness claude|codex]...
798
+ Report installation, Codex approval and the registry, and run a test hook.
799
+ hookloom validate [<registry file>]
800
+ Check that both harnesses can run a registry.
801
+ hookloom import [--harness claude|codex]... [--apply --acknowledge-restart [--acknowledge-codex-review]]
802
+ Move your own hooks into the registry. Without --apply, only report.
803
+ hookloom rollback [<migration>]
804
+ Undo a migration, by default the latest.
805
+
806
+ The registry is read from HOOKLOOM_REGISTRY, or hookloom/registry.json in your configuration directory.`;
807
+ function selectedHarnesses(values) {
808
+ return values.map((value) => {
809
+ const harness = harnesses.find((name) => name === value);
810
+ if (harness === void 0) throw new Error(`unknown harness ${value}`);
811
+ return harness;
812
+ });
813
+ }
814
+ async function main(argv, io) {
815
+ const { values, positionals } = parseArgs({
816
+ args: [...argv],
817
+ allowPositionals: true,
818
+ options: {
819
+ harness: {
820
+ type: "string",
821
+ multiple: true,
822
+ default: []
823
+ },
824
+ source: { type: "string" },
825
+ apply: {
826
+ type: "boolean",
827
+ default: false
828
+ },
829
+ "acknowledge-restart": {
830
+ type: "boolean",
831
+ default: false
832
+ },
833
+ "acknowledge-codex-review": {
834
+ type: "boolean",
835
+ default: false
836
+ },
837
+ help: {
838
+ type: "boolean",
839
+ short: "h",
840
+ default: false
841
+ },
842
+ version: {
843
+ type: "boolean",
844
+ default: false
845
+ }
846
+ }
847
+ });
848
+ const [command, argument] = positionals;
849
+ const requested = selectedHarnesses(values.harness);
850
+ if (values.version) {
851
+ io.say(version);
852
+ return 0;
853
+ }
854
+ if (values.help || command === void 0) {
855
+ io.say(USAGE);
856
+ return values.help ? 0 : 1;
857
+ }
858
+ if (command === "setup") return setup(io, {
859
+ harnesses: requested,
860
+ source: values.source
861
+ });
862
+ if (command === "status") return status(io, requested);
863
+ if (command === "validate") return validate(io, argument);
864
+ if (command === "import") return importHooks(io, {
865
+ harnesses: requested,
866
+ apply: values.apply,
867
+ acknowledgeRestart: values["acknowledge-restart"],
868
+ acknowledgeCodexReview: values["acknowledge-codex-review"]
869
+ });
870
+ if (command === "rollback") return rollbackImport(io, argument);
871
+ throw new Error(`unknown command ${command}; hookloom --help lists the commands`);
872
+ }
873
+ const io = {
874
+ env: process.env,
875
+ cwd: process.cwd(),
876
+ say: (line) => {
877
+ process.stdout.write(`${line}\n`);
878
+ },
879
+ now: () => /* @__PURE__ */ new Date()
880
+ };
881
+ try {
882
+ process.exitCode = await main(process.argv.slice(2), io);
883
+ } catch (error) {
884
+ process.stderr.write(`hookloom: ${error instanceof Error ? error.message : String(error)}\n`);
885
+ process.exitCode = 1;
886
+ }
887
+ export {};