hookloom 0.0.0 → 1.0.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/.claude-plugin/plugin.json +11 -0
- package/.codex-plugin/plugin.json +12 -0
- package/LICENSE +21 -0
- package/README.md +125 -0
- package/dist/check-C4-tOQXQ.mjs +1 -0
- package/dist/check-DiQUS1CB.mjs +65 -0
- package/dist/cli.mjs +893 -0
- package/dist/command-line-ByzwzoIt.mjs +109 -0
- package/dist/dispatcher.mjs +838 -0
- package/dist/permission-rule-DXm-Jvfg.mjs +355 -0
- package/dist/registry.schema.json +25812 -0
- package/dist/schema-78xAlSN_.mjs +5816 -0
- package/dist/schema-DR7G3z1u.mjs +1 -0
- package/hooks/codex.json +172 -0
- package/hooks/hooks.json +345 -0
- package/launcher/hook.sh +10 -0
- package/package.json +66 -2
|
@@ -0,0 +1,838 @@
|
|
|
1
|
+
import { text } from "node:stream/consumers";
|
|
2
|
+
import { h as harnesses, m as eventContract, t as handlersOf } from "./schema-78xAlSN_.mjs";
|
|
3
|
+
import { closeSync, existsSync, fstatSync, globSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
import { a as cacheDirectory, c as registryPath, i as atomicWrite, n as invocation, o as claudeDirectory, r as version } from "./command-line-ByzwzoIt.mjs";
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import { a as namedField, c as toolInput, i as isRecord, n as permissionRuleMatches, o as parsePayload, s as stringField, t as parsePermissionRule } from "./permission-rule-DXm-Jvfg.mjs";
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
10
|
+
// src/registry/load.ts
|
|
11
|
+
/**
|
|
12
|
+
* Reads the registry for a dispatch. Every tool call dispatches an event, so a document is validated once per content and version and the outcome remembered.
|
|
13
|
+
*/
|
|
14
|
+
const MEMO_PREFIX = "registry-";
|
|
15
|
+
var RegistryError = class extends Error {};
|
|
16
|
+
async function validate(text, path) {
|
|
17
|
+
const [{ parseRegistry }, { checkRegistry }] = await Promise.all([import("./schema-DR7G3z1u.mjs"), import("./check-C4-tOQXQ.mjs")]);
|
|
18
|
+
const registry = parseRegistry(JSON.parse(text));
|
|
19
|
+
const problems = checkRegistry(registry);
|
|
20
|
+
if (problems.length > 0) throw new RegistryError(`${path} cannot run:\n${problems.map((problem) => `${problem.harness} ${problem.event}: ${problem.message}`).join("\n")}`);
|
|
21
|
+
return registry;
|
|
22
|
+
}
|
|
23
|
+
function isRemembered(value) {
|
|
24
|
+
return isRecord(value) && isRecord(value["events"]) && isRecord(value["env"]);
|
|
25
|
+
}
|
|
26
|
+
function forgetOthers(directory, keep) {
|
|
27
|
+
for (const name of readdirSync(directory)) if (name.startsWith(MEMO_PREFIX) && name !== keep) rmSync(join(directory, name), { force: true });
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Loads and validates the registry file.
|
|
31
|
+
* @throws RegistryError when a harness could not run it, and the underlying error when it cannot be read or does not match the schema.
|
|
32
|
+
*/
|
|
33
|
+
async function loadRegistry(path, cache) {
|
|
34
|
+
const text = readFileSync(path, "utf8");
|
|
35
|
+
const name = `${MEMO_PREFIX}${createHash("sha256").update(`${version}\0${text}`).digest("hex")}.memo`;
|
|
36
|
+
const memo = join(cache, name);
|
|
37
|
+
try {
|
|
38
|
+
const remembered = JSON.parse(readFileSync(memo, "utf8"));
|
|
39
|
+
if (isRemembered(remembered)) return remembered;
|
|
40
|
+
} catch (error) {
|
|
41
|
+
if (!(error instanceof SyntaxError || error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
|
|
42
|
+
}
|
|
43
|
+
const registry = await validate(text, path);
|
|
44
|
+
atomicWrite(memo, JSON.stringify(registry));
|
|
45
|
+
forgetOthers(cache, name);
|
|
46
|
+
return registry;
|
|
47
|
+
}
|
|
48
|
+
// src/dispatch/result.ts
|
|
49
|
+
const silent = {
|
|
50
|
+
code: 0,
|
|
51
|
+
stdout: "",
|
|
52
|
+
stderr: "",
|
|
53
|
+
failed: false,
|
|
54
|
+
timedOut: false
|
|
55
|
+
};
|
|
56
|
+
// src/dispatch/state.ts
|
|
57
|
+
/**
|
|
58
|
+
* 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.
|
|
59
|
+
*/
|
|
60
|
+
function digest(identity) {
|
|
61
|
+
return createHash("sha256").update(JSON.stringify(identity)).digest("hex");
|
|
62
|
+
}
|
|
63
|
+
function readRecord(path) {
|
|
64
|
+
try {
|
|
65
|
+
const value = JSON.parse(readFileSync(path, "utf8"));
|
|
66
|
+
return isRecord(value) ? value : void 0;
|
|
67
|
+
} catch {
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/** Records state if it can: a write that fails is dropped, never turned into a hook failure. */
|
|
72
|
+
function writeRecord(path, record) {
|
|
73
|
+
try {
|
|
74
|
+
atomicWrite(path, JSON.stringify(record));
|
|
75
|
+
} catch {
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** The names of the JSON files in a directory, none when it does not exist. */
|
|
80
|
+
function records(directory) {
|
|
81
|
+
try {
|
|
82
|
+
return readdirSync(directory).filter((name) => name.endsWith(".json")).map((name) => join(directory, name));
|
|
83
|
+
} catch {
|
|
84
|
+
return [];
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function removeOlderThan(directory, milliseconds) {
|
|
88
|
+
const cutoff = Date.now() - milliseconds;
|
|
89
|
+
for (const path of records(directory)) {
|
|
90
|
+
const status = statSync(path, { throwIfNoEntry: false });
|
|
91
|
+
if (status !== void 0 && status.mtimeMs < cutoff) rmSync(path, { force: true });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/** Identifies the session, and the subagent within it, that an input belongs to; `undefined` when the harness gave no session id. */
|
|
95
|
+
function sessionKey(payload) {
|
|
96
|
+
const session = stringField(payload, "session_id");
|
|
97
|
+
if (session === void 0 || session === "") return void 0;
|
|
98
|
+
const agent = stringField(payload, "agent_id");
|
|
99
|
+
return agent === void 0 || agent === "" ? session : `${session}/${agent}`;
|
|
100
|
+
}
|
|
101
|
+
// src/dispatch/cache.ts
|
|
102
|
+
/**
|
|
103
|
+
* Reuses a handler's successful result for the window its `cache` field names, so it runs at most once per window and key without tracking that itself.
|
|
104
|
+
*/
|
|
105
|
+
const MILLISECONDS_PER_SECOND$2 = 1e3;
|
|
106
|
+
const ANCESTORS = "{chain}/";
|
|
107
|
+
function selfAndAncestors(directory) {
|
|
108
|
+
const parent = dirname(directory);
|
|
109
|
+
return parent === directory ? [directory] : [directory, ...selfAndAncestors(parent)];
|
|
110
|
+
}
|
|
111
|
+
function fingerprint(patterns, payload) {
|
|
112
|
+
const cwd = resolve(namedField(payload, "cwd") || ".");
|
|
113
|
+
return digest(patterns.flatMap((pattern) => {
|
|
114
|
+
if (pattern.startsWith(ANCESTORS)) return selfAndAncestors(cwd).map((directory) => join(directory, pattern.slice(8)));
|
|
115
|
+
return [pattern === "~" || pattern.startsWith("~/") ? join(homedir(), pattern.slice(1)) : pattern];
|
|
116
|
+
}).flatMap((pattern) => globSync(pattern.replaceAll("\\", "/")).toSorted().flatMap((path) => {
|
|
117
|
+
const status = statSync(path, { throwIfNoEntry: false });
|
|
118
|
+
return status?.isFile() === true ? [[
|
|
119
|
+
path,
|
|
120
|
+
status.size,
|
|
121
|
+
status.mtimeMs
|
|
122
|
+
]] : [];
|
|
123
|
+
})));
|
|
124
|
+
}
|
|
125
|
+
function entryPath(handler, cache, context) {
|
|
126
|
+
const identity = [
|
|
127
|
+
context.harness,
|
|
128
|
+
context.event,
|
|
129
|
+
handler.type === "command" ? [handler.command, handler.args] : [handler.url],
|
|
130
|
+
...(cache.key ?? ["cwd"]).map((name) => namedField(context.payload, name)),
|
|
131
|
+
...cache.inputs === void 0 ? [] : [fingerprint(cache.inputs, context.payload)]
|
|
132
|
+
];
|
|
133
|
+
return join(context.directory, `${digest(identity)}.json`);
|
|
134
|
+
}
|
|
135
|
+
function prune(directory) {
|
|
136
|
+
for (const path of records(directory)) {
|
|
137
|
+
const expires = readRecord(path)?.["expires_at"];
|
|
138
|
+
if (typeof expires !== "number" || expires <= Date.now()) rmSync(path, { force: true });
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
/** Runs a handler, or answers from its cache while the window for this key is open: silently, unless `replay` re-emits the stored output. A failed run is not stored. */
|
|
142
|
+
async function cached(handler, context, run) {
|
|
143
|
+
const { cache } = handler;
|
|
144
|
+
if (cache === void 0) return run();
|
|
145
|
+
const path = entryPath(handler, cache, context);
|
|
146
|
+
const { expires_at: expires, stdout, stderr } = readRecord(path) ?? {};
|
|
147
|
+
if (typeof expires === "number" && expires > Date.now() && typeof stdout === "string" && typeof stderr === "string") return cache.replay === true ? {
|
|
148
|
+
...silent,
|
|
149
|
+
stdout,
|
|
150
|
+
stderr
|
|
151
|
+
} : silent;
|
|
152
|
+
const result = await run();
|
|
153
|
+
if (result.code === 0) {
|
|
154
|
+
writeRecord(path, {
|
|
155
|
+
expires_at: Date.now() + cache.ttl * MILLISECONDS_PER_SECOND$2,
|
|
156
|
+
stdout: result.stdout,
|
|
157
|
+
stderr: result.stderr
|
|
158
|
+
});
|
|
159
|
+
prune(context.directory);
|
|
160
|
+
}
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
// src/dispatch/combine.ts
|
|
164
|
+
/**
|
|
165
|
+
* Applies each handler's failure policy and folds their results into the one response a harness reads from a hook.
|
|
166
|
+
*/
|
|
167
|
+
const POLICY_EXEMPT = /* @__PURE__ */ new Set([
|
|
168
|
+
"Stop",
|
|
169
|
+
"SubagentStop",
|
|
170
|
+
"TaskCompleted",
|
|
171
|
+
"TeammateIdle"
|
|
172
|
+
]);
|
|
173
|
+
const PLAIN_TEXT_EVENTS = /* @__PURE__ */ new Set([
|
|
174
|
+
"SessionStart",
|
|
175
|
+
"Setup",
|
|
176
|
+
"UserPromptSubmit",
|
|
177
|
+
"UserPromptExpansion",
|
|
178
|
+
"SubagentStart",
|
|
179
|
+
"PreCompact"
|
|
180
|
+
]);
|
|
181
|
+
const PERMISSION_ORDER = [
|
|
182
|
+
"allow",
|
|
183
|
+
"ask",
|
|
184
|
+
"defer",
|
|
185
|
+
"deny"
|
|
186
|
+
];
|
|
187
|
+
const BEHAVIOUR_ORDER = ["allow", "deny"];
|
|
188
|
+
function parseObject(text) {
|
|
189
|
+
try {
|
|
190
|
+
const value = JSON.parse(text);
|
|
191
|
+
return isRecord(value) ? value : void 0;
|
|
192
|
+
} catch {
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
function invalidJson(text) {
|
|
197
|
+
return text.startsWith("{") && parseObject(text) === void 0;
|
|
198
|
+
}
|
|
199
|
+
function applyPolicy(event, outcome) {
|
|
200
|
+
const { result, onFailure } = outcome;
|
|
201
|
+
const failure = result.failed || result.code !== 0 && result.code !== 2 || result.code === 0 && invalidJson(result.stdout.trim());
|
|
202
|
+
if (result.timedOut && event === "PreModelSwitch") return {
|
|
203
|
+
...result,
|
|
204
|
+
code: 2
|
|
205
|
+
};
|
|
206
|
+
if (!failure || outcome.background || onFailure === void 0) return result;
|
|
207
|
+
if (onFailure === "continue") return {
|
|
208
|
+
...result,
|
|
209
|
+
code: 0,
|
|
210
|
+
stdout: ""
|
|
211
|
+
};
|
|
212
|
+
if (POLICY_EXEMPT.has(event)) return result;
|
|
213
|
+
const message = result.stderr.trim() === "" ? `${event} handler failed and is configured to block.\n` : result.stderr;
|
|
214
|
+
if (event === "PermissionRequest") {
|
|
215
|
+
const denial = { hookSpecificOutput: {
|
|
216
|
+
hookEventName: event,
|
|
217
|
+
decision: {
|
|
218
|
+
behavior: "deny",
|
|
219
|
+
message: message.trim()
|
|
220
|
+
}
|
|
221
|
+
} };
|
|
222
|
+
return {
|
|
223
|
+
...result,
|
|
224
|
+
code: 0,
|
|
225
|
+
stdout: JSON.stringify(denial),
|
|
226
|
+
stderr: ""
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
return {
|
|
230
|
+
...result,
|
|
231
|
+
code: 2,
|
|
232
|
+
stdout: "",
|
|
233
|
+
stderr: message
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
function specific(output) {
|
|
237
|
+
const value = output["hookSpecificOutput"];
|
|
238
|
+
return isRecord(value) ? value : {};
|
|
239
|
+
}
|
|
240
|
+
function without(object, ...keys) {
|
|
241
|
+
return Object.fromEntries(Object.entries(object).filter(([key]) => !keys.includes(key)));
|
|
242
|
+
}
|
|
243
|
+
function restrict(output) {
|
|
244
|
+
const inner = specific(output);
|
|
245
|
+
if (Object.keys(inner).length === 0) return output;
|
|
246
|
+
const kept = without(inner, "updatedInput");
|
|
247
|
+
return {
|
|
248
|
+
...output,
|
|
249
|
+
hookSpecificOutput: kept["permissionDecision"] === "allow" ? without(kept, "permissionDecision", "permissionDecisionReason") : kept
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
function dropOverruled(outputs) {
|
|
253
|
+
const permission = Math.max(...outputs.map((output) => PERMISSION_ORDER.indexOf(specific(output)["permissionDecision"])));
|
|
254
|
+
const blocked = outputs.some((output) => output["decision"] === "block");
|
|
255
|
+
return outputs.map((output) => {
|
|
256
|
+
const inner = specific(output);
|
|
257
|
+
const rank = PERMISSION_ORDER.indexOf(inner["permissionDecision"]);
|
|
258
|
+
const ruled = rank >= 0 && rank < permission ? {
|
|
259
|
+
...output,
|
|
260
|
+
hookSpecificOutput: without(inner, "permissionDecision", "permissionDecisionReason")
|
|
261
|
+
} : output;
|
|
262
|
+
return blocked && ruled["decision"] !== void 0 && ruled["decision"] !== "block" ? without(ruled, "decision", "reason") : ruled;
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
function strictest(order, left, right) {
|
|
266
|
+
return order.indexOf(right) > order.indexOf(left) ? right : left;
|
|
267
|
+
}
|
|
268
|
+
function isList$1(value) {
|
|
269
|
+
return Array.isArray(value);
|
|
270
|
+
}
|
|
271
|
+
function merge(left, right, key) {
|
|
272
|
+
if (key === "updatedInput") return right;
|
|
273
|
+
if (key === "behavior") return strictest(BEHAVIOUR_ORDER, left, right);
|
|
274
|
+
if (key === "permissionDecision") return strictest(PERMISSION_ORDER, left, right);
|
|
275
|
+
if (key === "continue") return left !== false && right !== false;
|
|
276
|
+
if (isRecord(left) && isRecord(right)) return mergeObjects(left, right);
|
|
277
|
+
if (isList$1(left) && isList$1(right)) return [...left, ...right];
|
|
278
|
+
if (key !== "decision" && key !== "hookEventName" && typeof left === "string" && typeof right === "string") return left === right ? left : `${left}\n${right}`;
|
|
279
|
+
return right;
|
|
280
|
+
}
|
|
281
|
+
function mergeObjects(left, right) {
|
|
282
|
+
const merged = { ...left };
|
|
283
|
+
for (const [key, value] of Object.entries(right)) merged[key] = key in merged ? merge(merged[key], value, key) : value;
|
|
284
|
+
return merged;
|
|
285
|
+
}
|
|
286
|
+
function withText(event, combined, text) {
|
|
287
|
+
if (!PLAIN_TEXT_EVENTS.has(event)) return combined;
|
|
288
|
+
const inner = specific(combined);
|
|
289
|
+
const prior = inner["additionalContext"];
|
|
290
|
+
return {
|
|
291
|
+
...combined,
|
|
292
|
+
hookSpecificOutput: {
|
|
293
|
+
...inner,
|
|
294
|
+
hookEventName: event,
|
|
295
|
+
additionalContext: typeof prior === "string" ? `${prior}\n${text}` : text
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
function structured(event, harness, successful) {
|
|
300
|
+
const outputs = [];
|
|
301
|
+
const plain = [];
|
|
302
|
+
for (const outcome of successful) {
|
|
303
|
+
const text = outcome.result.stdout.trim();
|
|
304
|
+
if (text === "") continue;
|
|
305
|
+
const object = parseObject(text);
|
|
306
|
+
if (object === void 0) plain.push(text);
|
|
307
|
+
else outputs.push(outcome.restricted ? restrict(object) : object);
|
|
308
|
+
}
|
|
309
|
+
const [first, ...rest] = dropOverruled(outputs);
|
|
310
|
+
if (first === void 0) return plain.length === 0 ? "" : `${plain.join("\n")}\n`;
|
|
311
|
+
const combined = rest.reduce((accumulated, output) => mergeObjects(accumulated, output), first);
|
|
312
|
+
const contract = eventContract(harness, event);
|
|
313
|
+
return `${JSON.stringify(plain.length > 0 && contract !== void 0 ? withText(event, combined, plain.join("\n")) : combined)}\n`;
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* The response for an event. A block (exit 2) wins over everything but a request to stop altogether; a handler that merely failed never discards another's decision.
|
|
317
|
+
*/
|
|
318
|
+
function combine(harness, event, outcomes) {
|
|
319
|
+
const settled = outcomes.map((outcome) => ({
|
|
320
|
+
...outcome,
|
|
321
|
+
result: applyPolicy(event, outcome)
|
|
322
|
+
}));
|
|
323
|
+
const successful = settled.filter(({ result }) => result.code === 0);
|
|
324
|
+
const blocking = settled.filter(({ result }) => result.code === 2);
|
|
325
|
+
const stdout = structured(event, harness, successful);
|
|
326
|
+
const stderr = settled.map(({ result }) => result.stderr).join("");
|
|
327
|
+
const stops = parseObject(stdout)?.["continue"] === false;
|
|
328
|
+
if (blocking.length > 0 && !stops) return {
|
|
329
|
+
code: 2,
|
|
330
|
+
stdout: "",
|
|
331
|
+
stderr: blocking.map(({ result }) => result.stderr).join("")
|
|
332
|
+
};
|
|
333
|
+
if (stdout !== "") return {
|
|
334
|
+
code: 0,
|
|
335
|
+
stdout,
|
|
336
|
+
stderr
|
|
337
|
+
};
|
|
338
|
+
return {
|
|
339
|
+
code: settled.find(({ result }) => result.code !== 0 && result.code !== 2)?.result.code ?? 0,
|
|
340
|
+
stdout,
|
|
341
|
+
stderr
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
// src/dispatch/execute.ts
|
|
345
|
+
/**
|
|
346
|
+
* Runs one handler: a command with the event's input on standard input, or an HTTP request carrying it.
|
|
347
|
+
*/
|
|
348
|
+
const MILLISECONDS_PER_SECOND$1 = 1e3;
|
|
349
|
+
const TIMED_OUT_CODE = 124;
|
|
350
|
+
const NOT_STARTED_CODE = 127;
|
|
351
|
+
function environment(execution) {
|
|
352
|
+
return {
|
|
353
|
+
...process.env,
|
|
354
|
+
...execution.env
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
function stop(pid, windows) {
|
|
358
|
+
if (windows) {
|
|
359
|
+
spawn("taskkill", [
|
|
360
|
+
"/pid",
|
|
361
|
+
String(pid),
|
|
362
|
+
"/T",
|
|
363
|
+
"/F"
|
|
364
|
+
], { stdio: "ignore" });
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
try {
|
|
368
|
+
process.kill(-pid, "SIGKILL");
|
|
369
|
+
} catch (error) {
|
|
370
|
+
if (!(error instanceof Error && "code" in error && error.code === "ESRCH")) throw error;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
async function runInBackground(command, execution) {
|
|
374
|
+
return new Promise((resolve) => {
|
|
375
|
+
const child = spawn(command.program, [...command.args], {
|
|
376
|
+
env: environment(execution),
|
|
377
|
+
stdio: [
|
|
378
|
+
"pipe",
|
|
379
|
+
"ignore",
|
|
380
|
+
"ignore"
|
|
381
|
+
],
|
|
382
|
+
detached: true,
|
|
383
|
+
windowsHide: true
|
|
384
|
+
});
|
|
385
|
+
child.once("error", (error) => {
|
|
386
|
+
resolve({
|
|
387
|
+
...silent,
|
|
388
|
+
code: NOT_STARTED_CODE,
|
|
389
|
+
stderr: `${error.message}\n`,
|
|
390
|
+
failed: true
|
|
391
|
+
});
|
|
392
|
+
});
|
|
393
|
+
child.stdin.once("error", () => void 0);
|
|
394
|
+
child.once("spawn", () => {
|
|
395
|
+
child.stdin.end(execution.input, () => {
|
|
396
|
+
child.unref();
|
|
397
|
+
resolve(silent);
|
|
398
|
+
});
|
|
399
|
+
});
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
async function runToCompletion(command, execution, description) {
|
|
403
|
+
const windows = process.platform === "win32";
|
|
404
|
+
return new Promise((resolve) => {
|
|
405
|
+
const child = spawn(command.program, [...command.args], {
|
|
406
|
+
env: environment(execution),
|
|
407
|
+
stdio: "pipe",
|
|
408
|
+
detached: !windows,
|
|
409
|
+
windowsHide: true
|
|
410
|
+
});
|
|
411
|
+
const stdout = [];
|
|
412
|
+
const stderr = [];
|
|
413
|
+
let timedOut = false;
|
|
414
|
+
const timer = setTimeout(() => {
|
|
415
|
+
timedOut = true;
|
|
416
|
+
if (child.pid !== void 0) stop(child.pid, windows);
|
|
417
|
+
}, execution.timeoutSeconds * MILLISECONDS_PER_SECOND$1);
|
|
418
|
+
const finish = (result) => {
|
|
419
|
+
clearTimeout(timer);
|
|
420
|
+
resolve(result);
|
|
421
|
+
};
|
|
422
|
+
child.stdout.on("data", (chunk) => {
|
|
423
|
+
stdout.push(chunk);
|
|
424
|
+
});
|
|
425
|
+
child.stderr.on("data", (chunk) => {
|
|
426
|
+
stderr.push(chunk);
|
|
427
|
+
});
|
|
428
|
+
child.stdin.once("error", () => void 0);
|
|
429
|
+
child.once("error", (error) => {
|
|
430
|
+
finish({
|
|
431
|
+
...silent,
|
|
432
|
+
code: NOT_STARTED_CODE,
|
|
433
|
+
stderr: `${error.message}\n`,
|
|
434
|
+
failed: true
|
|
435
|
+
});
|
|
436
|
+
});
|
|
437
|
+
child.once("close", (code) => {
|
|
438
|
+
const errors = Buffer.concat(stderr).toString("utf8");
|
|
439
|
+
finish({
|
|
440
|
+
code: timedOut ? TIMED_OUT_CODE : code ?? 1,
|
|
441
|
+
stdout: Buffer.concat(stdout).toString("utf8"),
|
|
442
|
+
stderr: timedOut ? `${errors}Hook command timed out after ${String(execution.timeoutSeconds)} seconds: ${description}\n` : errors,
|
|
443
|
+
failed: timedOut || code === null || code === NOT_STARTED_CODE,
|
|
444
|
+
timedOut
|
|
445
|
+
});
|
|
446
|
+
});
|
|
447
|
+
child.stdin.end(execution.input);
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
function expandAllowed(value, allowed, env) {
|
|
451
|
+
return value.replaceAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/gu, (_reference, name) => allowed.includes(name) ? env[name] ?? "" : "");
|
|
452
|
+
}
|
|
453
|
+
function isJsonObject(text) {
|
|
454
|
+
try {
|
|
455
|
+
const value = JSON.parse(text);
|
|
456
|
+
return isRecord(value);
|
|
457
|
+
} catch {
|
|
458
|
+
return false;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
async function post(handler, execution) {
|
|
462
|
+
const env = environment(execution);
|
|
463
|
+
const headers = new Headers({ "Content-Type": "application/json" });
|
|
464
|
+
for (const [name, value] of Object.entries(handler.headers ?? {})) headers.set(name, expandAllowed(value, handler.allowedEnvVars ?? [], env));
|
|
465
|
+
const failure = (stderr, timedOut = false) => ({
|
|
466
|
+
code: 1,
|
|
467
|
+
stdout: "",
|
|
468
|
+
stderr: `${stderr}\n`,
|
|
469
|
+
failed: true,
|
|
470
|
+
timedOut
|
|
471
|
+
});
|
|
472
|
+
try {
|
|
473
|
+
const response = await fetch(handler.url, {
|
|
474
|
+
method: "POST",
|
|
475
|
+
headers,
|
|
476
|
+
body: execution.input,
|
|
477
|
+
signal: AbortSignal.timeout(execution.timeoutSeconds * MILLISECONDS_PER_SECOND$1)
|
|
478
|
+
});
|
|
479
|
+
const body = await response.text();
|
|
480
|
+
if (!response.ok) return failure(`HTTP hook returned status ${String(response.status)}`);
|
|
481
|
+
if (body.trim() === "") return silent;
|
|
482
|
+
if (!isJsonObject(body)) return failure("HTTP hook response is not a JSON object");
|
|
483
|
+
return {
|
|
484
|
+
...silent,
|
|
485
|
+
stdout: body
|
|
486
|
+
};
|
|
487
|
+
} catch (error) {
|
|
488
|
+
const timedOut = error instanceof Error && error.name === "TimeoutError";
|
|
489
|
+
return failure(`HTTP hook request failed: ${error instanceof Error ? error.message : String(error)}`, timedOut);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
async function runCommand(handler, execution) {
|
|
493
|
+
const command = invocation(execution.harness, handler, {
|
|
494
|
+
windows: process.platform === "win32",
|
|
495
|
+
env: environment(execution)
|
|
496
|
+
});
|
|
497
|
+
return handler.async === true ? runInBackground(command, execution) : runToCompletion(command, execution, handler.command);
|
|
498
|
+
}
|
|
499
|
+
async function execute(handler, execution) {
|
|
500
|
+
return handler.type === "http" ? post(handler, execution) : runCommand(handler, execution);
|
|
501
|
+
}
|
|
502
|
+
// src/dispatch/prompt-text.ts
|
|
503
|
+
/**
|
|
504
|
+
* Separates what a person wrote in a prompt from what the harness put there: other sessions' messages, background-task notices and the harness's own wrappers arrive through the same field as typing.
|
|
505
|
+
*/
|
|
506
|
+
const MESSAGE_BLOCK = /<(?<tag>agent-message|teammate-message|cross-session-message|task-notification)(?=[\s/>])[^>\n]*>(?:[^\n]*?<\/\k<tag>>|[\s\S]*?^[ \t]*<\/\k<tag>>)/gmu;
|
|
507
|
+
const NOTICE_BLOCK = /<(?<tag>system-reminder|codex_internal_context)(?=[\s/>])[^>]*>[\s\S]*?<\/\k<tag>>|<artifact-content-authored-by-others\s*\/>/gu;
|
|
508
|
+
const CROSS_SESSION_NOTICE = /^\[Cross-session idle notice\](?:[\s\S]*?This is an automated notice from that session's harness[^\n]*|[^\n]*)|^\[Cross-session delivery notice\][^\n]*$/gmu;
|
|
509
|
+
const HARNESS_LINES = new RegExp([
|
|
510
|
+
"^Another Claude session sent a message(?: while you were working)?:[ \\t]*$",
|
|
511
|
+
"^This came from another Claude session\\b[^\\n]*\\bnot typed by your user\\b[^\\n]*$",
|
|
512
|
+
"^That \"[^\\n]*?\" is an agent working inside this same session\\b[^\\n]*$",
|
|
513
|
+
"^\\[SYSTEM NOTIFICATION - NOT USER INPUT\\][ \\t]*(?:\\n(?:This is an automated background-task event|Do NOT interpret this as|No human input has been received)[^\\n]*)*",
|
|
514
|
+
"^Goal check-in: «(?:[\\s\\S]*?^Check on their progress[^\\n]*|[^\\n]*)",
|
|
515
|
+
"^\\[Earlier usage-limit notes no longer apply\\.[^\\n]*$",
|
|
516
|
+
"^\\[Request interrupted by user[^\\n]*$",
|
|
517
|
+
"^This session is being continued from another machine\\. Application state may have changed\\.[^\\n]*$"
|
|
518
|
+
].join("|"), "gmu");
|
|
519
|
+
const HARNESS_PROMPT = /^\s*(?:Stop hook feedback:|Base directory for this skill:|This session is being continued from a previous conversation|The summarized conversation included Artifact content)/u;
|
|
520
|
+
/** The prompt without other sessions' messages and the harness's notices, keeping the user's commands and attachments; empty when nothing of the user's is left. */
|
|
521
|
+
function withoutHarnessMessages(prompt) {
|
|
522
|
+
const stripped = [
|
|
523
|
+
MESSAGE_BLOCK,
|
|
524
|
+
NOTICE_BLOCK,
|
|
525
|
+
CROSS_SESSION_NOTICE,
|
|
526
|
+
HARNESS_LINES
|
|
527
|
+
].reduce((text, pattern) => text.replaceAll(pattern, " "), prompt);
|
|
528
|
+
return HARNESS_PROMPT.test(stripped) ? "" : stripped.trim();
|
|
529
|
+
}
|
|
530
|
+
// src/dispatch/repeat.ts
|
|
531
|
+
/**
|
|
532
|
+
* Keeps hooks from saying the same thing again: a handler's `repeat` window, and a Stop block that repeats with no work done since.
|
|
533
|
+
*/
|
|
534
|
+
const MILLISECONDS_PER_SECOND = 1e3;
|
|
535
|
+
const RECORD_MAX_AGE_MILLISECONDS = 1728e5;
|
|
536
|
+
const TRANSCRIPT_TAIL_BYTES = 4e5;
|
|
537
|
+
const STOP_EVENTS = /* @__PURE__ */ new Set(["Stop", "SubagentStop"]);
|
|
538
|
+
function save(path, directory, record) {
|
|
539
|
+
const fresh = !existsSync(path);
|
|
540
|
+
writeRecord(path, record);
|
|
541
|
+
if (fresh) removeOlderThan(directory, RECORD_MAX_AGE_MILLISECONDS);
|
|
542
|
+
}
|
|
543
|
+
function parsed(text) {
|
|
544
|
+
try {
|
|
545
|
+
const value = JSON.parse(text);
|
|
546
|
+
return isRecord(value) ? value : void 0;
|
|
547
|
+
} catch {
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
function carriesDecision(text) {
|
|
552
|
+
const value = parsed(text);
|
|
553
|
+
if (value === void 0) return false;
|
|
554
|
+
const inner = value["hookSpecificOutput"];
|
|
555
|
+
return "decision" in value || value["continue"] === false || isRecord(inner) && ("permissionDecision" in inner || "decision" in inner);
|
|
556
|
+
}
|
|
557
|
+
/** Drops a successful handler's output when it emitted the same text to this session within its window, which runs from the last emission. */
|
|
558
|
+
function suppressRepeat(handler, context, result) {
|
|
559
|
+
const { repeat } = handler;
|
|
560
|
+
const session = sessionKey(context.payload);
|
|
561
|
+
if (repeat === void 0 || session === void 0 || result.code !== 0 || result.stdout.trim() === "" || carriesDecision(result.stdout)) return result;
|
|
562
|
+
const text = repeat.ignore_digits === true ? result.stdout.replaceAll(/\d+(?:[.,:]\d+)*/gu, "#") : result.stdout;
|
|
563
|
+
const target = handler.type === "command" ? [handler.command, handler.args] : [handler.url];
|
|
564
|
+
const path = join(context.directory, `${digest([
|
|
565
|
+
"repeat",
|
|
566
|
+
context.harness,
|
|
567
|
+
context.event,
|
|
568
|
+
target,
|
|
569
|
+
session
|
|
570
|
+
])}.json`);
|
|
571
|
+
const previous = readRecord(path);
|
|
572
|
+
const emitted = previous?.["at"];
|
|
573
|
+
const hash = digest(text);
|
|
574
|
+
if (previous?.["digest"] === hash && typeof emitted === "number" && Date.now() - emitted < repeat.window_seconds * MILLISECONDS_PER_SECOND) return silent;
|
|
575
|
+
save(path, context.directory, {
|
|
576
|
+
digest: hash,
|
|
577
|
+
at: Date.now()
|
|
578
|
+
});
|
|
579
|
+
return result;
|
|
580
|
+
}
|
|
581
|
+
function stopPath(directory, session) {
|
|
582
|
+
return join(directory, `${digest(["stop", session])}.json`);
|
|
583
|
+
}
|
|
584
|
+
/** A prompt from the user starts a new stretch of work, so the last Stop block is forgotten. Prompts the harness or another agent wrote keep it. */
|
|
585
|
+
function notePrompt(directory, event, payload) {
|
|
586
|
+
const session = sessionKey(payload);
|
|
587
|
+
const prompt = stringField(payload, "prompt");
|
|
588
|
+
if (event !== "UserPromptSubmit" || session === void 0 || prompt === void 0 || withoutHarnessMessages(prompt) === "") return;
|
|
589
|
+
rmSync(stopPath(directory, session), { force: true });
|
|
590
|
+
}
|
|
591
|
+
function isList(value) {
|
|
592
|
+
return Array.isArray(value);
|
|
593
|
+
}
|
|
594
|
+
function latestToolCall(transcript) {
|
|
595
|
+
const descriptor = openSync(transcript, "r");
|
|
596
|
+
try {
|
|
597
|
+
const { size } = fstatSync(descriptor);
|
|
598
|
+
const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
|
|
599
|
+
const buffer = Buffer.alloc(length);
|
|
600
|
+
readSync(descriptor, buffer, 0, length, size - length);
|
|
601
|
+
for (const line of buffer.toString("utf8").split("\n").toReversed()) {
|
|
602
|
+
const record = parsed(line);
|
|
603
|
+
const message = record?.["message"];
|
|
604
|
+
const content = isRecord(message) ? message["content"] : void 0;
|
|
605
|
+
if (record?.["type"] !== "assistant" || !isList(content)) continue;
|
|
606
|
+
const call = content.findLast((block) => isRecord(block) && block["type"] === "tool_use");
|
|
607
|
+
if (isRecord(call)) return String(call["id"]);
|
|
608
|
+
}
|
|
609
|
+
return null;
|
|
610
|
+
} finally {
|
|
611
|
+
closeSync(descriptor);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
function blockReason(response) {
|
|
615
|
+
if (response.code === 2) return response.stderr.trim();
|
|
616
|
+
const value = parsed(response.stdout);
|
|
617
|
+
if (value?.["decision"] !== "block") return void 0;
|
|
618
|
+
const reason = value["reason"];
|
|
619
|
+
return typeof reason === "string" ? reason : "";
|
|
620
|
+
}
|
|
621
|
+
/** Drops a Stop block identical to the previous one when no tool has run since, because the forced turn could only repeat itself. Anything unreadable leaves the response as it was, so a new block is never hidden. */
|
|
622
|
+
function dropStalledStop(directory, event, payload, response) {
|
|
623
|
+
const session = sessionKey(payload);
|
|
624
|
+
if (!STOP_EVENTS.has(event) || session === void 0) return response;
|
|
625
|
+
const reason = blockReason(response);
|
|
626
|
+
if (reason === void 0) return response;
|
|
627
|
+
const transcript = stringField(payload, "transcript_path");
|
|
628
|
+
let toolCall = null;
|
|
629
|
+
try {
|
|
630
|
+
if (transcript !== void 0) toolCall = latestToolCall(transcript);
|
|
631
|
+
} catch {
|
|
632
|
+
return response;
|
|
633
|
+
}
|
|
634
|
+
const path = stopPath(directory, session);
|
|
635
|
+
const previous = readRecord(path);
|
|
636
|
+
const hash = digest(reason);
|
|
637
|
+
if (previous?.["digest"] === hash && previous["tool_id"] === toolCall) return {
|
|
638
|
+
code: 0,
|
|
639
|
+
stdout: "",
|
|
640
|
+
stderr: ""
|
|
641
|
+
};
|
|
642
|
+
save(path, directory, {
|
|
643
|
+
digest: hash,
|
|
644
|
+
tool_id: toolCall
|
|
645
|
+
});
|
|
646
|
+
return response;
|
|
647
|
+
}
|
|
648
|
+
// src/matcher.ts
|
|
649
|
+
const CLAUDE_EXACT = /^[A-Za-z0-9_\- ,|]*$/u;
|
|
650
|
+
const CLAUDE_NARROW_EXACT = /^[A-Za-z0-9_|]*$/u;
|
|
651
|
+
const CODEX_EXACT = /^[A-Za-z0-9_|]*$/u;
|
|
652
|
+
const CLAUDE_NARROW_EVENTS = /* @__PURE__ */ new Set(["FileChanged", "StopFailure"]);
|
|
653
|
+
function alternatives(harness, event, matcher) {
|
|
654
|
+
if (harness === "codex") return CODEX_EXACT.test(matcher) ? matcher.split("|") : void 0;
|
|
655
|
+
if (CLAUDE_NARROW_EVENTS.has(event)) return CLAUDE_NARROW_EXACT.test(matcher) ? matcher.split("|") : void 0;
|
|
656
|
+
return CLAUDE_EXACT.test(matcher) ? matcher.split(/[|,]/u).map((name) => name.trim()) : void 0;
|
|
657
|
+
}
|
|
658
|
+
/** Whether a matcher selects every occurrence of an event. */
|
|
659
|
+
function matchesEverything(matcher) {
|
|
660
|
+
return matcher === "" || matcher === "*";
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* Whether a matcher selects an occurrence described by `values`: the value of the event's match field, followed by any other names the harness accepts for it.
|
|
664
|
+
* @throws SyntaxError when the matcher is on the regular-expression path and is not a valid regular expression.
|
|
665
|
+
*/
|
|
666
|
+
function matchesMatcher(harness, event, matcher, values) {
|
|
667
|
+
if (matchesEverything(matcher)) return true;
|
|
668
|
+
const exact = alternatives(harness, event, matcher);
|
|
669
|
+
if (exact !== void 0) return values.some((value) => exact.includes(value));
|
|
670
|
+
const pattern = new RegExp(matcher);
|
|
671
|
+
return values.some((value) => pattern.test(value));
|
|
672
|
+
}
|
|
673
|
+
// src/dispatch/select.ts
|
|
674
|
+
/**
|
|
675
|
+
* Chooses the registry handlers one occurrence of an event runs, and the input each receives.
|
|
676
|
+
*/
|
|
677
|
+
const CODEX_ALIASES = /* @__PURE__ */ new Map([["apply_patch", ["Write", "Edit"]], ["spawn_agent", ["Agent"]]]);
|
|
678
|
+
const MONITOR_EVENTS = /* @__PURE__ */ new Set(["PreToolUse", "PermissionRequest"]);
|
|
679
|
+
const MODEL_EVENTS = /* @__PURE__ */ new Set(["PreModelSwitch", "PostModelSwitch"]);
|
|
680
|
+
function matchValues({ harness, event }, field, payload) {
|
|
681
|
+
const value = stringField(payload, field);
|
|
682
|
+
if (value === void 0) throw new TypeError(`${event} has a matcher but its input has no ${field}`);
|
|
683
|
+
const compared = MODEL_EVENTS.has(event) ? value.replace(/\[1m\]$/u, "") : value;
|
|
684
|
+
return harness === "codex" && field === "tool_name" ? [compared, ...CODEX_ALIASES.get(compared) ?? []] : [compared];
|
|
685
|
+
}
|
|
686
|
+
function matcherSelects(context, matcher, payload) {
|
|
687
|
+
const { harness, event, contract } = context;
|
|
688
|
+
if (matchesEverything(matcher) || contract.matchField === void 0) return true;
|
|
689
|
+
return matchesMatcher(harness, event, matcher, matchValues(context, contract.matchField, payload));
|
|
690
|
+
}
|
|
691
|
+
/** A shell command started by Claude Code's Monitor tool, presented as the Bash call a Bash matcher or rule expects; `undefined` for anything else. */
|
|
692
|
+
function monitorAsBash({ harness, event, payload }) {
|
|
693
|
+
if (harness !== "claude" || !MONITOR_EVENTS.has(event) || stringField(payload, "tool_name") !== "Monitor") return void 0;
|
|
694
|
+
const { command, description } = toolInput(payload);
|
|
695
|
+
if (typeof command !== "string") return void 0;
|
|
696
|
+
return {
|
|
697
|
+
...payload,
|
|
698
|
+
tool_name: "Bash",
|
|
699
|
+
tool_input: {
|
|
700
|
+
command,
|
|
701
|
+
...description === void 0 ? {} : { description }
|
|
702
|
+
}
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
function whenSelects(handler, payload) {
|
|
706
|
+
return handler.when === void 0 || new RegExp(handler.when.pattern, "u").test(namedField(payload, handler.when.field));
|
|
707
|
+
}
|
|
708
|
+
function selectHandler(context, group, handler, matched) {
|
|
709
|
+
const { contract, payload, asBash, directories } = context;
|
|
710
|
+
const input = matched ? payload : asBash ?? payload;
|
|
711
|
+
let restricted = !matched;
|
|
712
|
+
if (handler.if !== void 0 && contract.evaluatesIf) {
|
|
713
|
+
const rule = parsePermissionRule(handler.if);
|
|
714
|
+
if (rule === void 0) return void 0;
|
|
715
|
+
if (rule.tool === "Bash" && asBash !== void 0) {
|
|
716
|
+
if (!permissionRuleMatches(rule, asBash, directories)) return void 0;
|
|
717
|
+
restricted = true;
|
|
718
|
+
} else if (rule.tool === "Monitor" && !matched || !permissionRuleMatches(rule, input, directories)) return;
|
|
719
|
+
}
|
|
720
|
+
return whenSelects(handler, input) ? {
|
|
721
|
+
group,
|
|
722
|
+
handler,
|
|
723
|
+
input,
|
|
724
|
+
restricted
|
|
725
|
+
} : void 0;
|
|
726
|
+
}
|
|
727
|
+
/**
|
|
728
|
+
* Every handler of the registry that applies to this occurrence, in registry order.
|
|
729
|
+
* @throws TypeError when a group has a matcher and the input lacks the field it is compared with.
|
|
730
|
+
*/
|
|
731
|
+
function selectHandlers(registry, occurrence) {
|
|
732
|
+
const { harness, event, payload } = occurrence;
|
|
733
|
+
const contract = eventContract(harness, event);
|
|
734
|
+
if (contract === void 0) return [];
|
|
735
|
+
const context = {
|
|
736
|
+
...occurrence,
|
|
737
|
+
contract,
|
|
738
|
+
asBash: monitorAsBash(occurrence)
|
|
739
|
+
};
|
|
740
|
+
return (registry.events[event] ?? []).filter((group) => group.harnesses.includes(harness)).flatMap((group) => {
|
|
741
|
+
const matcher = group.matcher ?? "";
|
|
742
|
+
const matched = matcherSelects(context, matcher, payload);
|
|
743
|
+
if (!matched && (context.asBash === void 0 || !matcherSelects(context, matcher, context.asBash))) return [];
|
|
744
|
+
return handlersOf(group).flatMap((handler) => selectHandler(context, group, handler, matched) ?? []);
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
// src/dispatch/run.ts
|
|
748
|
+
/**
|
|
749
|
+
* Handles one occurrence of one event: selects the registry's handlers, runs them together and answers the harness.
|
|
750
|
+
*/
|
|
751
|
+
const nothing = {
|
|
752
|
+
code: 0,
|
|
753
|
+
stdout: "",
|
|
754
|
+
stderr: ""
|
|
755
|
+
};
|
|
756
|
+
async function runOne(occurrence, selection, raw, payload) {
|
|
757
|
+
const { harness, event, registry, cache } = occurrence;
|
|
758
|
+
const { handler, group, restricted } = selection;
|
|
759
|
+
const input = selection.input === payload ? raw : JSON.stringify(selection.input);
|
|
760
|
+
const timeoutSeconds = handler.timeout ?? eventContract(harness, event)?.defaultTimeoutSeconds ?? 0;
|
|
761
|
+
const env = {
|
|
762
|
+
...registry.env,
|
|
763
|
+
...group.env,
|
|
764
|
+
...handler.env
|
|
765
|
+
};
|
|
766
|
+
const state = {
|
|
767
|
+
harness,
|
|
768
|
+
event,
|
|
769
|
+
payload: selection.input
|
|
770
|
+
};
|
|
771
|
+
const result = await cached(handler, {
|
|
772
|
+
...state,
|
|
773
|
+
directory: cache
|
|
774
|
+
}, async () => execute(handler, {
|
|
775
|
+
harness,
|
|
776
|
+
input,
|
|
777
|
+
env,
|
|
778
|
+
timeoutSeconds
|
|
779
|
+
}));
|
|
780
|
+
const background = handler.type === "command" && (handler.async === true || handler.asyncRewake === true);
|
|
781
|
+
return {
|
|
782
|
+
result: suppressRepeat(handler, {
|
|
783
|
+
...state,
|
|
784
|
+
directory: join(cache, "repeat")
|
|
785
|
+
}, result),
|
|
786
|
+
onFailure: handler.onFailure,
|
|
787
|
+
background,
|
|
788
|
+
restricted
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* Dispatches a hook input. A user who has registered nothing has no registry file, and every event then answers silently; a registry named by `HOOKLOOM_REGISTRY` must exist.
|
|
793
|
+
* @throws when the input is not a hook input or the registry cannot be read or run.
|
|
794
|
+
*/
|
|
795
|
+
async function dispatch(harness, raw, env) {
|
|
796
|
+
const payload = parsePayload(raw);
|
|
797
|
+
const event = stringField(payload, "hook_event_name");
|
|
798
|
+
if (event === void 0) throw new TypeError("hook input has no hook_event_name");
|
|
799
|
+
const path = registryPath(env);
|
|
800
|
+
if (env["HOOKLOOM_REGISTRY"] === void 0 && !existsSync(path)) return nothing;
|
|
801
|
+
const cache = cacheDirectory(env);
|
|
802
|
+
const registry = await loadRegistry(path, cache);
|
|
803
|
+
const selected = selectHandlers(registry, {
|
|
804
|
+
harness,
|
|
805
|
+
event,
|
|
806
|
+
payload,
|
|
807
|
+
directories: {
|
|
808
|
+
cwd: stringField(payload, "cwd") ?? process.cwd(),
|
|
809
|
+
home: homedir(),
|
|
810
|
+
settings: claudeDirectory(env)
|
|
811
|
+
}
|
|
812
|
+
});
|
|
813
|
+
const outcomes = await Promise.all(selected.map(async (selection) => runOne({
|
|
814
|
+
harness,
|
|
815
|
+
event,
|
|
816
|
+
registry,
|
|
817
|
+
cache
|
|
818
|
+
}, selection, raw, payload)));
|
|
819
|
+
const memory = join(cache, "repeat");
|
|
820
|
+
notePrompt(memory, event, payload);
|
|
821
|
+
return dropStalledStop(memory, event, payload, combine(harness, event, outcomes));
|
|
822
|
+
}
|
|
823
|
+
// src/dispatcher.ts
|
|
824
|
+
/**
|
|
825
|
+
* The program the plugin's hook entries run: `dispatcher.js <claude|codex>` with the hook input on standard input.
|
|
826
|
+
*/
|
|
827
|
+
const harness = harnesses.find((name) => name === process.argv[2]);
|
|
828
|
+
try {
|
|
829
|
+
if (harness === void 0) throw new Error(`expected one of ${harnesses.join(", ")} as the argument`);
|
|
830
|
+
const response = await dispatch(harness, await text(process.stdin), process.env);
|
|
831
|
+
process.stdout.write(response.stdout);
|
|
832
|
+
process.stderr.write(response.stderr);
|
|
833
|
+
process.exitCode = response.code;
|
|
834
|
+
} catch (error) {
|
|
835
|
+
process.stderr.write(`hookloom: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
836
|
+
process.exitCode = 1;
|
|
837
|
+
}
|
|
838
|
+
export {};
|