@agimon-ai/doompi-hook 0.0.1-alpha.7 → 0.0.1-alpha.71

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.
Files changed (130) hide show
  1. package/README.md +11 -4
  2. package/dist/apiContracts.cjs +17 -0
  3. package/dist/apiContracts.cjs.map +1 -0
  4. package/dist/apiContracts.d.mts +53 -0
  5. package/dist/apiContracts.d.mts.map +1 -0
  6. package/dist/apiContracts.mjs +13 -0
  7. package/dist/apiContracts.mjs.map +1 -0
  8. package/dist/extensions/mcp.cjs +26 -0
  9. package/dist/extensions/mcp.cjs.map +1 -0
  10. package/dist/extensions/mcp.d.mts +5 -0
  11. package/dist/extensions/mcp.d.mts.map +1 -0
  12. package/dist/extensions/mcp.mjs +21 -0
  13. package/dist/extensions/mcp.mjs.map +1 -0
  14. package/dist/extensions/pi.cjs +337 -1
  15. package/dist/extensions/pi.cjs.map +1 -0
  16. package/dist/extensions/pi.d.mts +6 -2
  17. package/dist/extensions/pi.d.mts.map +1 -0
  18. package/dist/extensions/pi.mjs +332 -1
  19. package/dist/extensions/pi.mjs.map +1 -0
  20. package/dist/extensions/server.cjs +83 -0
  21. package/dist/extensions/server.cjs.map +1 -0
  22. package/dist/extensions/server.d.mts +5 -0
  23. package/dist/extensions/server.d.mts.map +1 -0
  24. package/dist/extensions/server.mjs +78 -0
  25. package/dist/extensions/server.mjs.map +1 -0
  26. package/dist/hooks-CReMXrU9.cjs +615 -0
  27. package/dist/hooks-CReMXrU9.cjs.map +1 -0
  28. package/dist/hooks-D2s_5hzZ.mjs +473 -0
  29. package/dist/hooks-D2s_5hzZ.mjs.map +1 -0
  30. package/dist/index-LpLV04fM.d.mts +297 -0
  31. package/dist/index-LpLV04fM.d.mts.map +1 -0
  32. package/dist/index.cjs +22 -1
  33. package/dist/index.d.mts +2 -12
  34. package/dist/index.mjs +2 -1
  35. package/package.json +53 -14
  36. package/dist/_virtual/_rolldown/runtime.cjs +0 -1
  37. package/dist/adapters/hookDocuments.cjs +0 -2
  38. package/dist/adapters/hookDocuments.cjs.map +0 -1
  39. package/dist/adapters/hookDocuments.d.cts +0 -23
  40. package/dist/adapters/hookDocuments.d.cts.map +0 -1
  41. package/dist/adapters/hookDocuments.d.mts +0 -23
  42. package/dist/adapters/hookDocuments.d.mts.map +0 -1
  43. package/dist/adapters/hookDocuments.mjs +0 -2
  44. package/dist/adapters/hookDocuments.mjs.map +0 -1
  45. package/dist/adapters/hookRunner.cjs +0 -2
  46. package/dist/adapters/hookRunner.cjs.map +0 -1
  47. package/dist/adapters/hookRunner.d.cts +0 -22
  48. package/dist/adapters/hookRunner.d.cts.map +0 -1
  49. package/dist/adapters/hookRunner.d.mts +0 -22
  50. package/dist/adapters/hookRunner.d.mts.map +0 -1
  51. package/dist/adapters/hookRunner.mjs +0 -2
  52. package/dist/adapters/hookRunner.mjs.map +0 -1
  53. package/dist/adapters/pi/extension.cjs +0 -2
  54. package/dist/adapters/pi/extension.cjs.map +0 -1
  55. package/dist/adapters/pi/extension.d.cts +0 -14
  56. package/dist/adapters/pi/extension.d.cts.map +0 -1
  57. package/dist/adapters/pi/extension.d.mts +0 -14
  58. package/dist/adapters/pi/extension.d.mts.map +0 -1
  59. package/dist/adapters/pi/extension.mjs +0 -2
  60. package/dist/adapters/pi/extension.mjs.map +0 -1
  61. package/dist/adapters/pi/hookHandlers.cjs +0 -8
  62. package/dist/adapters/pi/hookHandlers.cjs.map +0 -1
  63. package/dist/adapters/pi/hookHandlers.mjs +0 -8
  64. package/dist/adapters/pi/hookHandlers.mjs.map +0 -1
  65. package/dist/adapters/telemetry/logSinkTelemetry.cjs +0 -2
  66. package/dist/adapters/telemetry/logSinkTelemetry.cjs.map +0 -1
  67. package/dist/adapters/telemetry/logSinkTelemetry.d.cts +0 -14
  68. package/dist/adapters/telemetry/logSinkTelemetry.d.cts.map +0 -1
  69. package/dist/adapters/telemetry/logSinkTelemetry.d.mts +0 -14
  70. package/dist/adapters/telemetry/logSinkTelemetry.d.mts.map +0 -1
  71. package/dist/adapters/telemetry/logSinkTelemetry.mjs +0 -2
  72. package/dist/adapters/telemetry/logSinkTelemetry.mjs.map +0 -1
  73. package/dist/extensions/pi.d.cts +0 -2
  74. package/dist/index.d.cts +0 -12
  75. package/dist/services/hookDecisions.cjs +0 -3
  76. package/dist/services/hookDecisions.cjs.map +0 -1
  77. package/dist/services/hookDecisions.d.cts +0 -19
  78. package/dist/services/hookDecisions.d.cts.map +0 -1
  79. package/dist/services/hookDecisions.d.mts +0 -19
  80. package/dist/services/hookDecisions.d.mts.map +0 -1
  81. package/dist/services/hookDecisions.mjs +0 -3
  82. package/dist/services/hookDecisions.mjs.map +0 -1
  83. package/dist/services/hookPayload.cjs +0 -2
  84. package/dist/services/hookPayload.cjs.map +0 -1
  85. package/dist/services/hookPayload.d.cts +0 -9
  86. package/dist/services/hookPayload.d.cts.map +0 -1
  87. package/dist/services/hookPayload.d.mts +0 -9
  88. package/dist/services/hookPayload.d.mts.map +0 -1
  89. package/dist/services/hookPayload.mjs +0 -2
  90. package/dist/services/hookPayload.mjs.map +0 -1
  91. package/dist/services/hookRegistry.cjs +0 -2
  92. package/dist/services/hookRegistry.cjs.map +0 -1
  93. package/dist/services/hookRegistry.d.cts +0 -37
  94. package/dist/services/hookRegistry.d.cts.map +0 -1
  95. package/dist/services/hookRegistry.d.mts +0 -37
  96. package/dist/services/hookRegistry.d.mts.map +0 -1
  97. package/dist/services/hookRegistry.mjs +0 -2
  98. package/dist/services/hookRegistry.mjs.map +0 -1
  99. package/dist/services/pluginHooks.cjs +0 -2
  100. package/dist/services/pluginHooks.cjs.map +0 -1
  101. package/dist/services/pluginHooks.d.cts +0 -13
  102. package/dist/services/pluginHooks.d.cts.map +0 -1
  103. package/dist/services/pluginHooks.d.mts +0 -13
  104. package/dist/services/pluginHooks.d.mts.map +0 -1
  105. package/dist/services/pluginHooks.mjs +0 -2
  106. package/dist/services/pluginHooks.mjs.map +0 -1
  107. package/dist/services/toolNames.cjs +0 -2
  108. package/dist/services/toolNames.cjs.map +0 -1
  109. package/dist/services/toolNames.d.cts +0 -8
  110. package/dist/services/toolNames.d.cts.map +0 -1
  111. package/dist/services/toolNames.d.mts +0 -8
  112. package/dist/services/toolNames.d.mts.map +0 -1
  113. package/dist/services/toolNames.mjs +0 -2
  114. package/dist/services/toolNames.mjs.map +0 -1
  115. package/dist/types/hooks.cjs +0 -2
  116. package/dist/types/hooks.cjs.map +0 -1
  117. package/dist/types/hooks.d.cts +0 -145
  118. package/dist/types/hooks.d.cts.map +0 -1
  119. package/dist/types/hooks.d.mts +0 -145
  120. package/dist/types/hooks.d.mts.map +0 -1
  121. package/dist/types/hooks.mjs +0 -2
  122. package/dist/types/hooks.mjs.map +0 -1
  123. package/dist/types/telemetry.cjs +0 -2
  124. package/dist/types/telemetry.cjs.map +0 -1
  125. package/dist/types/telemetry.d.cts +0 -20
  126. package/dist/types/telemetry.d.cts.map +0 -1
  127. package/dist/types/telemetry.d.mts +0 -20
  128. package/dist/types/telemetry.d.mts.map +0 -1
  129. package/dist/types/telemetry.mjs +0 -2
  130. package/dist/types/telemetry.mjs.map +0 -1
@@ -0,0 +1,615 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+ //#endregion
23
+ let node_fs = require("node:fs");
24
+ node_fs = __toESM(node_fs, 1);
25
+ let _agimon_ai_doompi_config_layeredConfig = require("@agimon-ai/doompi-config/layeredConfig");
26
+ let yaml = require("yaml");
27
+ let node_child_process = require("node:child_process");
28
+ let _agimon_ai_doompi_telemetry = require("@agimon-ai/doompi-telemetry");
29
+ //#endregion
30
+ //#region src/services/hookDecisions/index.ts
31
+ function decisionsFrom(outcomes) {
32
+ return outcomes.flatMap((outcome) => outcome.decision ? [outcome.decision] : []);
33
+ }
34
+ function failuresFrom(outcomes) {
35
+ return outcomes.flatMap((outcome) => outcome.failure ? [outcome.failure] : []);
36
+ }
37
+ /** Both spellings a hook may use to refuse the call it observed. */
38
+ function isDenied(decision) {
39
+ return decision?.decision === "block" || decision?.hookSpecificOutput?.permissionDecision === "deny";
40
+ }
41
+ function decisionReason(decision) {
42
+ return decision?.reason ?? decision?.hookSpecificOutput?.reason;
43
+ }
44
+ /** Context a hook wants added to the conversation rather than used to block. */
45
+ function additionalContextsFrom(decisions) {
46
+ return decisions.map((decision) => decision.hookSpecificOutput?.additionalContext).filter((value) => Boolean(value));
47
+ }
48
+ /** What a post-tool hook has to say, whichever field it said it in. */
49
+ function toolResultMessages(decisions) {
50
+ return decisions.map((decision) => decision.hookSpecificOutput?.additionalContext ?? decisionReason(decision)).filter((value) => Boolean(value));
51
+ }
52
+ /**
53
+ * A guardrail that never ran looks exactly like one that passed, so the agent is
54
+ * told which checks were missed and what its options are.
55
+ */
56
+ function hookFailureMessage(failures) {
57
+ return [
58
+ "One or more repository hooks did not complete, so their checks were not applied:",
59
+ ...failures.map((failure) => `- ${failure.command}: ${failure.message}`),
60
+ "Options:",
61
+ "- Inspect the hook command or configuration and rerun after correcting it.",
62
+ "- Continue only if the missed advisory check is acceptable.",
63
+ "- Ask the user before bypassing a hook that may enforce a guardrail."
64
+ ].join("\n");
65
+ }
66
+ //#endregion
67
+ //#region src/constants/hookDocuments.ts
68
+ const HOOKS_FILE = "hooks.yaml";
69
+ const FILE_NOT_FOUND_ERROR = "ENOENT";
70
+ const REGISTRY_SOURCE_ATTRIBUTE = "repository";
71
+ //#endregion
72
+ //#region src/constants/telemetry.ts
73
+ const HOOK_TELEMETRY_EVENT = {
74
+ hookFailed: "doom_pi_hook.failed",
75
+ hookRegistryReadFailed: "doom_pi_hook.registry_read_failed"
76
+ };
77
+ //#endregion
78
+ //#region src/services/toolNames/index.ts
79
+ /**
80
+ * Pi's tool names translated into the Claude names hook matchers are written
81
+ * against.
82
+ *
83
+ * Hook authors write `matcher: Bash`, and Pi reports `bash`, so a matcher would
84
+ * never fire without this. Only this direction belongs here: rewriting Claude
85
+ * names for Pi is an agent-definition concern the harness owns.
86
+ */
87
+ const PI_TO_CLAUDE = /* @__PURE__ */ new Map([
88
+ ["read", "Read"],
89
+ ["edit", "Edit"],
90
+ ["write", "Write"],
91
+ ["bash", "Bash"],
92
+ ["find", "Glob"],
93
+ ["grep", "Grep"],
94
+ ["subagent", "Agent"]
95
+ ]);
96
+ /** The Claude name a hook matcher expects for a tool Pi just ran. */
97
+ function toClaudeToolName(tool) {
98
+ return PI_TO_CLAUDE.get(tool) ?? tool;
99
+ }
100
+ /** Whether a matcher, if the row declares one, accepts the tool that fired. */
101
+ function matchesTool(matcher, toolName) {
102
+ if (!toolName || !matcher) return true;
103
+ return new RegExp(matcher).test(toClaudeToolName(toolName));
104
+ }
105
+ //#endregion
106
+ //#region src/services/hookRegistry/index.ts
107
+ /**
108
+ * Identity of a set of registry sources, for callers that cache the parse.
109
+ *
110
+ * Keyed on contents rather than mtime, so it stays correct for an in-place
111
+ * rewrite and needs no invalidation hook. Reading both files is cheap; parsing
112
+ * is what a cache built on this skips.
113
+ */
114
+ function registryCacheKey(sources) {
115
+ return sources.map((source) => `${source.baseDirectory} ${source.text}`).join(" ");
116
+ }
117
+ /**
118
+ * Flattens parsed registry documents into sorted rows, keeping only bindings
119
+ * that declare a `pi` frontend.
120
+ *
121
+ * A later source replaces the group of the same id outright rather than merging
122
+ * into it, so a repository that redefines a group owns it completely.
123
+ */
124
+ function registryEntries(sources) {
125
+ const groups = /* @__PURE__ */ new Map();
126
+ let position = 0;
127
+ for (const source of sources) for (const [groupId, group] of Object.entries(source.document.groups ?? {})) {
128
+ const entries = [];
129
+ for (const hook of group.hooks ?? []) {
130
+ position += 1;
131
+ if (!hook.pi) continue;
132
+ entries.push({
133
+ ...hook.pi,
134
+ event: hook.event,
135
+ order: hook.pi.order ?? 0,
136
+ position,
137
+ groupId,
138
+ core: group.core === true,
139
+ baseDirectory: source.baseDirectory
140
+ });
141
+ }
142
+ groups.set(groupId, entries);
143
+ }
144
+ const entries = [...groups.values()].flat();
145
+ entries.sort((left, right) => left.order - right.order || left.position - right.position);
146
+ return entries;
147
+ }
148
+ /**
149
+ * The rows one dispatch runs.
150
+ *
151
+ * Group selection changes when /mode switches mid-session, so inclusion is
152
+ * applied per call rather than being baked into a cached parse. Core groups
153
+ * always load; the rest are gated by the layers the harness resolved.
154
+ */
155
+ function selectRegistryHooks(entries, selection) {
156
+ const allowed = selection.allowedGroups === void 0 ? void 0 : new Set(selection.allowedGroups);
157
+ return entries.filter((entry) => entry.core || !allowed || allowed.has(entry.groupId)).filter((entry) => entry.event === selection.event).filter((entry) => !(entry.skipInSubagent && selection.inSubagent)).filter((entry) => matchesTool(entry.matcher, selection.toolName)).map((entry) => ({
158
+ hook: {
159
+ command: entry.command,
160
+ timeout: entry.timeout
161
+ },
162
+ root: entry.baseDirectory
163
+ }));
164
+ }
165
+ //#endregion
166
+ //#region src/services/hookDocuments/index.ts
167
+ function reason(error) {
168
+ return error instanceof Error ? error.message : String(error);
169
+ }
170
+ function isMissingFile(error) {
171
+ return error?.code === FILE_NOT_FOUND_ERROR;
172
+ }
173
+ /**
174
+ * Reads `.doom/hooks.yaml` from the global config directory and the repository,
175
+ * and the plugin hook configs the harness resolved.
176
+ *
177
+ * Every file is re-read on every dispatch: it costs almost nothing and keeps an
178
+ * in-place rewrite visible, which an mtime check would miss when two writes land
179
+ * inside the same filesystem timestamp granularity. Both caches are keyed on
180
+ * contents instead, so parsing — the expensive half — is what they skip.
181
+ */
182
+ function createHookDocumentReader(options = {}) {
183
+ const readFile = options.readFile ?? ((filePath) => node_fs.default.promises.readFile(filePath, "utf8"));
184
+ const telemetry = options.telemetry;
185
+ const warn = options.warn ?? ((message) => void process.stderr.write(message));
186
+ let cachedRegistryKey;
187
+ let cachedRegistryEntries = [];
188
+ const pluginConfigCache = /* @__PURE__ */ new Map();
189
+ const readSource = async (candidate) => {
190
+ try {
191
+ return {
192
+ baseDirectory: candidate.baseDirectory,
193
+ text: await readFile(candidate.filePath)
194
+ };
195
+ } catch (error) {
196
+ if (isMissingFile(error)) return void 0;
197
+ throw error;
198
+ }
199
+ };
200
+ const parseSources = (sources) => {
201
+ const key = registryCacheKey(sources);
202
+ if (cachedRegistryKey === key) return cachedRegistryEntries;
203
+ cachedRegistryEntries = registryEntries(sources.map((source) => ({
204
+ baseDirectory: source.baseDirectory,
205
+ document: (0, yaml.parse)(source.text) ?? {}
206
+ })));
207
+ cachedRegistryKey = key;
208
+ return cachedRegistryEntries;
209
+ };
210
+ return {
211
+ async registry(repoRoot) {
212
+ const candidates = (0, _agimon_ai_doompi_config_layeredConfig.doomConfigCandidates)(HOOKS_FILE, repoRoot, options.homeDirectory);
213
+ const registryPath = candidates.map((candidate) => candidate.filePath).join(" and ");
214
+ try {
215
+ const sources = (await Promise.all(candidates.map(readSource))).filter((source) => source !== void 0);
216
+ return { entries: parseSources(sources) };
217
+ } catch (error) {
218
+ telemetry?.recordError(HOOK_TELEMETRY_EVENT.hookRegistryReadFailed, error, { "hook.registry.source": REGISTRY_SOURCE_ATTRIBUTE });
219
+ warn(`[pi-hook] could not read ${registryPath}: ${reason(error)}\n`);
220
+ return {
221
+ entries: [],
222
+ failure: {
223
+ command: registryPath,
224
+ message: reason(error),
225
+ reason: "registry_read"
226
+ }
227
+ };
228
+ }
229
+ },
230
+ async plugins(sources) {
231
+ const documents = [];
232
+ const failures = [];
233
+ for (const source of sources) try {
234
+ const text = await readFile(source.configPath);
235
+ const cached = pluginConfigCache.get(source.configPath);
236
+ const config = cached?.source === text ? cached.config : JSON.parse(text);
237
+ pluginConfigCache.set(source.configPath, {
238
+ source: text,
239
+ config
240
+ });
241
+ documents.push({
242
+ pluginRoot: source.pluginRoot,
243
+ config
244
+ });
245
+ } catch (error) {
246
+ failures.push({
247
+ command: source.configPath,
248
+ message: reason(error),
249
+ reason: "plugin_config"
250
+ });
251
+ }
252
+ return {
253
+ documents,
254
+ failures
255
+ };
256
+ }
257
+ };
258
+ }
259
+ //#endregion
260
+ //#region src/services/hookPayload/index.ts
261
+ /** The payload shape a Claude Code session hook is written against. */
262
+ function toolHookPayload(event, hookEventName, repoRoot, sessionId) {
263
+ return {
264
+ session_id: sessionId,
265
+ transcript_path: "",
266
+ cwd: repoRoot,
267
+ hook_event_name: hookEventName,
268
+ tool_name: toClaudeToolName(event.toolName),
269
+ tool_input: event.input,
270
+ ...event.type === "tool_result" ? { tool_response: {
271
+ success: !event.isError,
272
+ content: event.content
273
+ } } : {}
274
+ };
275
+ }
276
+ /** Session lifecycle hooks observe no tool, so they only need where and who. */
277
+ function sessionHookPayload(sessionId, repoRoot) {
278
+ return {
279
+ session_id: sessionId,
280
+ cwd: repoRoot
281
+ };
282
+ }
283
+ //#endregion
284
+ //#region src/constants/hookRunner.ts
285
+ const HOOK_SHELL = "/bin/bash";
286
+ const HOOK_TERMINATION_GRACE_MS = 2e3;
287
+ const MILLISECONDS_PER_SECOND = 1e3;
288
+ const PROCESS_NOT_FOUND_ERROR = "ESRCH";
289
+ const WINDOWS_PLATFORM = "win32";
290
+ const LINE_BREAK = /\r?\n/;
291
+ //#endregion
292
+ //#region src/services/hookRunner/index.ts
293
+ function errorCode(error) {
294
+ return error instanceof Error && "code" in error ? String(error.code) : void 0;
295
+ }
296
+ /**
297
+ * Runs advisory hook commands through bash and reports what each one decided.
298
+ *
299
+ * A hook is a command the repository owns, so it is spawned in its own process
300
+ * group and terminated as one: a hook that starts a server and stalls should
301
+ * not leave the server behind when the timeout fires.
302
+ */
303
+ function createBashHookRunner(options = {}) {
304
+ const spawn = options.spawn ?? node_child_process.spawn;
305
+ const telemetry = options.telemetry;
306
+ const warn = options.warn ?? ((message) => void process.stderr.write(message));
307
+ const useProcessGroup = (options.platform ?? process.platform) !== WINDOWS_PLATFORM;
308
+ const signalOwnedProcess = (pid, kill) => {
309
+ return (signal) => {
310
+ try {
311
+ if (useProcessGroup && pid !== void 0) {
312
+ process.kill(-pid, signal);
313
+ return;
314
+ }
315
+ kill(signal);
316
+ } catch (error) {
317
+ if (errorCode(error) !== "ESRCH") process.emitWarning(`Could not signal repository hook process: ${String(error)}`);
318
+ }
319
+ };
320
+ };
321
+ return { run(hook, payload, runOptions) {
322
+ const timeoutSeconds = hook.timeout ?? 10;
323
+ const environment = options.env ?? process.env;
324
+ return new Promise((resolve) => {
325
+ const child = spawn(HOOK_SHELL, ["-c", hook.command], {
326
+ cwd: runOptions.repoRoot,
327
+ env: {
328
+ ...environment,
329
+ CLAUDE_PROJECT_DIR: runOptions.repoRoot,
330
+ CODEX_REPO_ROOT: runOptions.repoRoot,
331
+ ORIGINAL_REPO_PATH: environment.ORIGINAL_REPO_PATH ?? runOptions.repoRoot,
332
+ ...runOptions.pluginRoot ? { CLAUDE_PLUGIN_ROOT: runOptions.pluginRoot } : {}
333
+ },
334
+ stdio: [
335
+ "pipe",
336
+ "pipe",
337
+ "pipe"
338
+ ],
339
+ detached: useProcessGroup
340
+ });
341
+ let stdout = "";
342
+ let stderr = "";
343
+ let settled = false;
344
+ let timedOut = false;
345
+ let childExited = false;
346
+ let timeoutExitCode = null;
347
+ let escalationTimer;
348
+ const signal = signalOwnedProcess(child.pid, (value) => child.kill(value));
349
+ const ownedProcessIsAlive = () => {
350
+ if (!useProcessGroup || child.pid === void 0) return !childExited;
351
+ try {
352
+ process.kill(-child.pid, 0);
353
+ return true;
354
+ } catch (error) {
355
+ return errorCode(error) !== PROCESS_NOT_FOUND_ERROR;
356
+ }
357
+ };
358
+ const finish = (outcome = {}) => {
359
+ if (settled) return;
360
+ settled = true;
361
+ clearTimeout(timer);
362
+ if (escalationTimer) clearTimeout(escalationTimer);
363
+ resolve(outcome);
364
+ };
365
+ const finishTimeout = () => {
366
+ const message = `Hook timed out after ${timeoutSeconds} seconds.`;
367
+ telemetry?.recordWarning(HOOK_TELEMETRY_EVENT.hookFailed, message, {
368
+ "hook.reason": "timeout",
369
+ "hook.exit_code": timeoutExitCode ?? -1
370
+ });
371
+ warn(`[pi-hook] advisory hook timed out: ${hook.command}\n${stderr}`);
372
+ finish({ failure: {
373
+ command: hook.command,
374
+ message,
375
+ reason: "timeout"
376
+ } });
377
+ };
378
+ const timer = setTimeout(() => {
379
+ timedOut = true;
380
+ signal("SIGTERM");
381
+ escalationTimer = setTimeout(() => {
382
+ if (ownedProcessIsAlive()) signal("SIGKILL");
383
+ finishTimeout();
384
+ }, HOOK_TERMINATION_GRACE_MS);
385
+ }, timeoutSeconds * MILLISECONDS_PER_SECOND);
386
+ child.stdout?.on("data", (chunk) => {
387
+ stdout += chunk.toString();
388
+ });
389
+ child.stderr?.on("data", (chunk) => {
390
+ stderr += chunk.toString();
391
+ });
392
+ child.once("error", (error) => {
393
+ if (timedOut) return;
394
+ telemetry?.recordError(HOOK_TELEMETRY_EVENT.hookFailed, error, { "hook.reason": "spawn_failed" });
395
+ warn(`[pi-hook] advisory hook failed: ${error.message}\n`);
396
+ finish({ failure: {
397
+ command: hook.command,
398
+ message: error.message,
399
+ reason: "spawn_failed"
400
+ } });
401
+ });
402
+ child.once("exit", (code) => {
403
+ childExited = true;
404
+ timeoutExitCode = code;
405
+ if (timedOut) return;
406
+ if (code !== 0) {
407
+ const message = stderr.trim() || `Advisory hook exited with code ${code ?? "unknown"}`;
408
+ telemetry?.recordWarning(HOOK_TELEMETRY_EVENT.hookFailed, message, {
409
+ "hook.reason": "non_zero_exit",
410
+ "hook.exit_code": code ?? -1
411
+ });
412
+ warn(`[pi-hook] advisory hook failed (${code}): ${hook.command}\n${stderr}`);
413
+ finish({ failure: {
414
+ command: hook.command,
415
+ message,
416
+ reason: "non_zero_exit"
417
+ } });
418
+ return;
419
+ }
420
+ const jsonLine = stdout.trim().split(LINE_BREAK).reverse().find((line) => line.startsWith("{"));
421
+ if (!jsonLine) {
422
+ finish();
423
+ return;
424
+ }
425
+ try {
426
+ finish({ decision: JSON.parse(jsonLine) });
427
+ } catch (error) {
428
+ telemetry?.recordWarning(HOOK_TELEMETRY_EVENT.hookFailed, error, { "hook.reason": "invalid_json" });
429
+ warn(`[pi-hook] advisory hook returned invalid JSON: ${hook.command}\n`);
430
+ finish({ failure: {
431
+ command: hook.command,
432
+ message: error instanceof Error ? error.message : String(error),
433
+ reason: "invalid_json"
434
+ } });
435
+ }
436
+ });
437
+ child.stdin?.end(JSON.stringify(payload));
438
+ });
439
+ } };
440
+ }
441
+ //#endregion
442
+ //#region src/constants/hookTelemetry.ts
443
+ const SERVICE_NAME = "doom-pi-hook";
444
+ const PACKAGE_NAME = "@agimon-ai/doompi-hook";
445
+ //#endregion
446
+ //#region src/services/hookTelemetry/index.ts
447
+ function createHookTelemetry(options = {}) {
448
+ const telemetry = (0, _agimon_ai_doompi_telemetry.createDoomTelemetry)({
449
+ serviceName: SERVICE_NAME,
450
+ packageName: PACKAGE_NAME,
451
+ cwd: options.cwd,
452
+ workspaceRoot: options.workspaceRoot,
453
+ env: options.env,
454
+ telemetryFactory: options.telemetryFactory,
455
+ warn: options.warn,
456
+ enableLogs: true,
457
+ enableTraces: true
458
+ });
459
+ return {
460
+ recordError: (event, error, attributes) => telemetry.recordError(event, error, attributes),
461
+ recordWarning: (event, error, attributes) => telemetry.recordWarning(event, error, attributes)
462
+ };
463
+ }
464
+ //#endregion
465
+ //#region src/services/pluginHooks/index.ts
466
+ /**
467
+ * The plugin hooks one dispatch runs.
468
+ *
469
+ * Plugin configs are the Claude Code `hooks.json` shape verbatim: an event name
470
+ * maps to groups, each with an optional matcher and a list of commands. Order
471
+ * follows the declaration order of the plugins the harness resolved.
472
+ */
473
+ function selectPluginHooks(documents, eventName, toolName) {
474
+ const matches = [];
475
+ for (const document of documents) for (const group of document.config.hooks?.[eventName] ?? []) {
476
+ if (!matchesTool(group.matcher, toolName)) continue;
477
+ for (const hook of group.hooks ?? []) matches.push({
478
+ hook,
479
+ root: document.pluginRoot
480
+ });
481
+ }
482
+ return matches;
483
+ }
484
+ //#endregion
485
+ //#region src/constants/hooks.ts
486
+ const HOOK_EVENT = {
487
+ sessionStart: "SessionStart",
488
+ preToolUse: "PreToolUse",
489
+ postToolUse: "PostToolUse",
490
+ stop: "Stop",
491
+ sessionEnd: "SessionEnd"
492
+ };
493
+ //#endregion
494
+ Object.defineProperty(exports, "HOOK_EVENT", {
495
+ enumerable: true,
496
+ get: function() {
497
+ return HOOK_EVENT;
498
+ }
499
+ });
500
+ Object.defineProperty(exports, "HOOK_TELEMETRY_EVENT", {
501
+ enumerable: true,
502
+ get: function() {
503
+ return HOOK_TELEMETRY_EVENT;
504
+ }
505
+ });
506
+ Object.defineProperty(exports, "additionalContextsFrom", {
507
+ enumerable: true,
508
+ get: function() {
509
+ return additionalContextsFrom;
510
+ }
511
+ });
512
+ Object.defineProperty(exports, "createBashHookRunner", {
513
+ enumerable: true,
514
+ get: function() {
515
+ return createBashHookRunner;
516
+ }
517
+ });
518
+ Object.defineProperty(exports, "createHookDocumentReader", {
519
+ enumerable: true,
520
+ get: function() {
521
+ return createHookDocumentReader;
522
+ }
523
+ });
524
+ Object.defineProperty(exports, "createHookTelemetry", {
525
+ enumerable: true,
526
+ get: function() {
527
+ return createHookTelemetry;
528
+ }
529
+ });
530
+ Object.defineProperty(exports, "decisionReason", {
531
+ enumerable: true,
532
+ get: function() {
533
+ return decisionReason;
534
+ }
535
+ });
536
+ Object.defineProperty(exports, "decisionsFrom", {
537
+ enumerable: true,
538
+ get: function() {
539
+ return decisionsFrom;
540
+ }
541
+ });
542
+ Object.defineProperty(exports, "failuresFrom", {
543
+ enumerable: true,
544
+ get: function() {
545
+ return failuresFrom;
546
+ }
547
+ });
548
+ Object.defineProperty(exports, "hookFailureMessage", {
549
+ enumerable: true,
550
+ get: function() {
551
+ return hookFailureMessage;
552
+ }
553
+ });
554
+ Object.defineProperty(exports, "isDenied", {
555
+ enumerable: true,
556
+ get: function() {
557
+ return isDenied;
558
+ }
559
+ });
560
+ Object.defineProperty(exports, "matchesTool", {
561
+ enumerable: true,
562
+ get: function() {
563
+ return matchesTool;
564
+ }
565
+ });
566
+ Object.defineProperty(exports, "registryCacheKey", {
567
+ enumerable: true,
568
+ get: function() {
569
+ return registryCacheKey;
570
+ }
571
+ });
572
+ Object.defineProperty(exports, "registryEntries", {
573
+ enumerable: true,
574
+ get: function() {
575
+ return registryEntries;
576
+ }
577
+ });
578
+ Object.defineProperty(exports, "selectPluginHooks", {
579
+ enumerable: true,
580
+ get: function() {
581
+ return selectPluginHooks;
582
+ }
583
+ });
584
+ Object.defineProperty(exports, "selectRegistryHooks", {
585
+ enumerable: true,
586
+ get: function() {
587
+ return selectRegistryHooks;
588
+ }
589
+ });
590
+ Object.defineProperty(exports, "sessionHookPayload", {
591
+ enumerable: true,
592
+ get: function() {
593
+ return sessionHookPayload;
594
+ }
595
+ });
596
+ Object.defineProperty(exports, "toClaudeToolName", {
597
+ enumerable: true,
598
+ get: function() {
599
+ return toClaudeToolName;
600
+ }
601
+ });
602
+ Object.defineProperty(exports, "toolHookPayload", {
603
+ enumerable: true,
604
+ get: function() {
605
+ return toolHookPayload;
606
+ }
607
+ });
608
+ Object.defineProperty(exports, "toolResultMessages", {
609
+ enumerable: true,
610
+ get: function() {
611
+ return toolResultMessages;
612
+ }
613
+ });
614
+
615
+ //# sourceMappingURL=hooks-CReMXrU9.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks-CReMXrU9.cjs","names":["fs","parseYaml","doomConfigCandidates","spawnProcess","createDoomTelemetry"],"sources":["../src/constants/hookDecisions.ts","../src/services/hookDecisions/index.ts","../src/constants/hookDocuments.ts","../src/constants/telemetry.ts","../src/services/toolNames/index.ts","../src/services/hookRegistry/index.ts","../src/services/hookDocuments/index.ts","../src/constants/hookPayload.ts","../src/services/hookPayload/index.ts","../src/constants/hookRunner.ts","../src/services/hookRunner/index.ts","../src/constants/hookTelemetry.ts","../src/services/hookTelemetry/index.ts","../src/services/pluginHooks/index.ts","../src/constants/hooks.ts"],"sourcesContent":["export const BLOCK_DECISION = 'block';\nexport const DENY_PERMISSION = 'deny';\n","import { BLOCK_DECISION, DENY_PERMISSION } from '../../constants/hookDecisions';\nimport type { HookDecision, HookFailure, HookOutcome } from '../../types/hooks';\n\nexport function decisionsFrom(outcomes: ReadonlyArray<HookOutcome>): HookDecision[] {\n return outcomes.flatMap((outcome) => (outcome.decision ? [outcome.decision] : []));\n}\n\nexport function failuresFrom(outcomes: ReadonlyArray<HookOutcome>): HookFailure[] {\n return outcomes.flatMap((outcome) => (outcome.failure ? [outcome.failure] : []));\n}\n\n/** Both spellings a hook may use to refuse the call it observed. */\nexport function isDenied(decision: HookDecision | undefined): boolean {\n return decision?.decision === BLOCK_DECISION || decision?.hookSpecificOutput?.permissionDecision === DENY_PERMISSION;\n}\n\nexport function decisionReason(decision: HookDecision | undefined): string | undefined {\n return decision?.reason ?? decision?.hookSpecificOutput?.reason;\n}\n\n/** Context a hook wants added to the conversation rather than used to block. */\nexport function additionalContextsFrom(decisions: ReadonlyArray<HookDecision>): string[] {\n return decisions\n .map((decision) => decision.hookSpecificOutput?.additionalContext)\n .filter((value): value is string => Boolean(value));\n}\n\n/** What a post-tool hook has to say, whichever field it said it in. */\nexport function toolResultMessages(decisions: ReadonlyArray<HookDecision>): string[] {\n return decisions\n .map((decision) => decision.hookSpecificOutput?.additionalContext ?? decisionReason(decision))\n .filter((value): value is string => Boolean(value));\n}\n\n/**\n * A guardrail that never ran looks exactly like one that passed, so the agent is\n * told which checks were missed and what its options are.\n */\nexport function hookFailureMessage(failures: ReadonlyArray<HookFailure>): string {\n return [\n 'One or more repository hooks did not complete, so their checks were not applied:',\n ...failures.map((failure) => `- ${failure.command}: ${failure.message}`),\n 'Options:',\n '- Inspect the hook command or configuration and rerun after correcting it.',\n '- Continue only if the missed advisory check is acceptable.',\n '- Ask the user before bypassing a hook that may enforce a guardrail.',\n ].join('\\n');\n}\n","export const HOOKS_FILE = 'hooks.yaml';\nexport const FILE_ENCODING = 'utf8';\nexport const FILE_NOT_FOUND_ERROR = 'ENOENT';\nexport const REGISTRY_SOURCE_ATTRIBUTE = 'repository';\n","export const HOOK_TELEMETRY_EVENT = {\n hookFailed: 'doom_pi_hook.failed',\n hookRegistryReadFailed: 'doom_pi_hook.registry_read_failed',\n} as const;\n","/**\n * Pi's tool names translated into the Claude names hook matchers are written\n * against.\n *\n * Hook authors write `matcher: Bash`, and Pi reports `bash`, so a matcher would\n * never fire without this. Only this direction belongs here: rewriting Claude\n * names for Pi is an agent-definition concern the harness owns.\n */\nconst PI_TO_CLAUDE = new Map([\n ['read', 'Read'],\n ['edit', 'Edit'],\n ['write', 'Write'],\n ['bash', 'Bash'],\n ['find', 'Glob'],\n ['grep', 'Grep'],\n ['subagent', 'Agent'],\n]);\n\n/** The Claude name a hook matcher expects for a tool Pi just ran. */\nexport function toClaudeToolName(tool: string): string {\n return PI_TO_CLAUDE.get(tool) ?? tool;\n}\n\n/** Whether a matcher, if the row declares one, accepts the tool that fired. */\nexport function matchesTool(matcher: string | undefined, toolName: string | undefined): boolean {\n if (!toolName || !matcher) return true;\n return new RegExp(matcher).test(toClaudeToolName(toolName));\n}\n","import type { HookDocumentSource, ParsedRegistrySource, RegistryEntry, ResolvedHook } from '../../types/hooks';\nimport { matchesTool } from '../toolNames';\n\n/** Which rows a dispatch keeps, once the session's selection is known. */\nexport interface RegistrySelection {\n event: string;\n toolName?: string;\n /** Selected group ids, or undefined for \"every group\", the standalone default. */\n allowedGroups?: readonly string[];\n inSubagent: boolean;\n}\n\n/**\n * Identity of a set of registry sources, for callers that cache the parse.\n *\n * Keyed on contents rather than mtime, so it stays correct for an in-place\n * rewrite and needs no invalidation hook. Reading both files is cheap; parsing\n * is what a cache built on this skips.\n */\nexport function registryCacheKey(sources: ReadonlyArray<HookDocumentSource>): string {\n return sources.map((source) => `${source.baseDirectory} ${source.text}`).join(' ');\n}\n\n/**\n * Flattens parsed registry documents into sorted rows, keeping only bindings\n * that declare a `pi` frontend.\n *\n * A later source replaces the group of the same id outright rather than merging\n * into it, so a repository that redefines a group owns it completely.\n */\nexport function registryEntries(sources: ReadonlyArray<ParsedRegistrySource>): RegistryEntry[] {\n const groups = new Map<string, RegistryEntry[]>();\n let position = 0;\n for (const source of sources) {\n for (const [groupId, group] of Object.entries(source.document.groups ?? {})) {\n const entries: RegistryEntry[] = [];\n for (const hook of group.hooks ?? []) {\n // Every declared hook advances the position, whether or not it is kept,\n // so the sort tiebreaker stays the order the file declares them in.\n position += 1;\n if (!hook.pi) continue;\n entries.push({\n ...hook.pi,\n event: hook.event,\n order: hook.pi.order ?? 0,\n position,\n groupId,\n core: group.core === true,\n baseDirectory: source.baseDirectory,\n });\n }\n groups.set(groupId, entries);\n }\n }\n\n const entries = [...groups.values()].flat();\n entries.sort((left, right) => left.order - right.order || left.position - right.position);\n return entries;\n}\n\n/**\n * The rows one dispatch runs.\n *\n * Group selection changes when /mode switches mid-session, so inclusion is\n * applied per call rather than being baked into a cached parse. Core groups\n * always load; the rest are gated by the layers the harness resolved.\n */\nexport function selectRegistryHooks(\n entries: ReadonlyArray<RegistryEntry>,\n selection: RegistrySelection,\n): ResolvedHook[] {\n const allowed = selection.allowedGroups === undefined ? undefined : new Set(selection.allowedGroups);\n return entries\n .filter((entry) => entry.core || !allowed || allowed.has(entry.groupId))\n .filter((entry) => entry.event === selection.event)\n .filter((entry) => !(entry.skipInSubagent && selection.inSubagent))\n .filter((entry) => matchesTool(entry.matcher, selection.toolName))\n .map((entry) => ({\n hook: { command: entry.command, timeout: entry.timeout },\n // The declaring config's root, so a global hook can reach its own scripts\n // through CLAUDE_PLUGIN_ROOT while still running against this repository.\n root: entry.baseDirectory,\n }));\n}\n","import fs from 'node:fs';\n\nimport { doomConfigCandidates } from '@agimon-ai/doompi-config/layeredConfig';\nimport { parse as parseYaml } from 'yaml';\n\nimport {\n HOOKS_FILE,\n FILE_ENCODING,\n FILE_NOT_FOUND_ERROR,\n REGISTRY_SOURCE_ATTRIBUTE,\n} from '../../constants/hookDocuments';\nimport { HOOK_TELEMETRY_EVENT } from '../../constants/telemetry';\nimport type {\n HookDocumentReader,\n HookDocumentSource,\n PluginDocumentRead,\n PluginHookConfig,\n PluginHookDocument,\n PluginHookSourceRef,\n RegistryDocument,\n RegistryEntry,\n RegistryRead,\n} from '../../types/hooks';\nimport { type HookTelemetry } from '../../types/telemetry';\nimport { registryCacheKey, registryEntries } from '../hookRegistry';\n\nexport interface HookDocumentReaderOptions {\n telemetry?: HookTelemetry;\n /** Where the global `.doom` directory lives. Defaults to the user's home. */\n homeDirectory?: string;\n readFile?: (filePath: string) => Promise<string>;\n warn?: (message: string) => void;\n}\n\nfunction reason(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction isMissingFile(error: unknown): boolean {\n return (error as NodeJS.ErrnoException | undefined)?.code === FILE_NOT_FOUND_ERROR;\n}\n\n/**\n * Reads `.doom/hooks.yaml` from the global config directory and the repository,\n * and the plugin hook configs the harness resolved.\n *\n * Every file is re-read on every dispatch: it costs almost nothing and keeps an\n * in-place rewrite visible, which an mtime check would miss when two writes land\n * inside the same filesystem timestamp granularity. Both caches are keyed on\n * contents instead, so parsing — the expensive half — is what they skip.\n */\nexport function createHookDocumentReader(options: HookDocumentReaderOptions = {}): HookDocumentReader {\n const readFile = options.readFile ?? ((filePath: string) => fs.promises.readFile(filePath, FILE_ENCODING));\n const telemetry = options.telemetry;\n const warn = options.warn ?? ((message: string) => void process.stderr.write(message));\n let cachedRegistryKey: string | undefined;\n let cachedRegistryEntries: RegistryEntry[] = [];\n const pluginConfigCache = new Map<string, { source: string; config: PluginHookConfig }>();\n\n const readSource = async (candidate: {\n filePath: string;\n baseDirectory: string;\n }): Promise<HookDocumentSource | undefined> => {\n try {\n return { baseDirectory: candidate.baseDirectory, text: await readFile(candidate.filePath) };\n } catch (error) {\n if (isMissingFile(error)) return undefined;\n throw error;\n }\n };\n\n const parseSources = (sources: ReadonlyArray<HookDocumentSource>): RegistryEntry[] => {\n const key = registryCacheKey(sources);\n if (cachedRegistryKey === key) return cachedRegistryEntries;\n cachedRegistryEntries = registryEntries(\n sources.map((source) => ({\n baseDirectory: source.baseDirectory,\n document: (parseYaml(source.text) ?? {}) as RegistryDocument,\n })),\n );\n cachedRegistryKey = key;\n return cachedRegistryEntries;\n };\n\n return {\n async registry(repoRoot: string): Promise<RegistryRead> {\n const candidates = doomConfigCandidates(HOOKS_FILE, repoRoot, options.homeDirectory);\n // Named for the error path only. A registry absent from both locations is\n // a repository with no hooks, not a failure, so only a file that exists\n // and cannot be read or parsed reaches the catch below.\n const registryPath = candidates.map((candidate) => candidate.filePath).join(' and ');\n try {\n const sources = (await Promise.all(candidates.map(readSource))).filter(\n (source): source is HookDocumentSource => source !== undefined,\n );\n return { entries: parseSources(sources) };\n } catch (error) {\n // This empties the registry for the whole dispatch, so every repository\n // hook silently stops running rather than any one of them failing.\n void telemetry?.recordError(HOOK_TELEMETRY_EVENT.hookRegistryReadFailed, error, {\n 'hook.registry.source': REGISTRY_SOURCE_ATTRIBUTE,\n });\n warn(`[pi-hook] could not read ${registryPath}: ${reason(error)}\\n`);\n return { entries: [], failure: { command: registryPath, message: reason(error), reason: 'registry_read' } };\n }\n },\n\n async plugins(sources: readonly PluginHookSourceRef[]): Promise<PluginDocumentRead> {\n const documents: PluginHookDocument[] = [];\n const failures: PluginDocumentRead['failures'] = [];\n for (const source of sources) {\n try {\n const text = await readFile(source.configPath);\n const cached = pluginConfigCache.get(source.configPath);\n const config = cached?.source === text ? cached.config : (JSON.parse(text) as PluginHookConfig);\n pluginConfigCache.set(source.configPath, { source: text, config });\n documents.push({ pluginRoot: source.pluginRoot, config });\n } catch (error) {\n failures.push({ command: source.configPath, message: reason(error), reason: 'plugin_config' });\n }\n }\n return { documents, failures };\n },\n };\n}\n","export const TOOL_RESULT_EVENT = 'tool_result';\n","import { TOOL_RESULT_EVENT } from '../../constants/hookPayload';\nimport type { HookPayload, HookToolEvent } from '../../types/hooks';\nimport { toClaudeToolName } from '../toolNames';\n\n/** The payload shape a Claude Code session hook is written against. */\nexport function toolHookPayload(\n event: HookToolEvent,\n hookEventName: string,\n repoRoot: string,\n sessionId: string,\n): HookPayload {\n return {\n session_id: sessionId,\n transcript_path: '',\n cwd: repoRoot,\n hook_event_name: hookEventName,\n tool_name: toClaudeToolName(event.toolName),\n tool_input: event.input,\n ...(event.type === TOOL_RESULT_EVENT ? { tool_response: { success: !event.isError, content: event.content } } : {}),\n };\n}\n\n/** Session lifecycle hooks observe no tool, so they only need where and who. */\nexport function sessionHookPayload(sessionId: string, repoRoot: string): HookPayload {\n return { session_id: sessionId, cwd: repoRoot };\n}\n","export const HOOK_SHELL = '/bin/bash';\nexport const HOOK_SHELL_COMMAND_FLAG = '-c';\nexport const HOOK_TERMINATION_GRACE_MS = 2_000;\nexport const DEFAULT_HOOK_TIMEOUT_SECONDS = 10;\nexport const MILLISECONDS_PER_SECOND = 1_000;\nexport const PROCESS_NOT_FOUND_ERROR = 'ESRCH';\nexport const WINDOWS_PLATFORM = 'win32';\nexport const UNKNOWN_EXIT_CODE = -1;\nexport const JSON_LINE_START = '{';\nexport const LINE_BREAK = /\\r?\\n/;\n","import { spawn as spawnProcess } from 'node:child_process';\n\nimport {\n HOOK_SHELL,\n HOOK_SHELL_COMMAND_FLAG,\n HOOK_TERMINATION_GRACE_MS,\n DEFAULT_HOOK_TIMEOUT_SECONDS,\n MILLISECONDS_PER_SECOND,\n PROCESS_NOT_FOUND_ERROR,\n WINDOWS_PLATFORM,\n UNKNOWN_EXIT_CODE,\n JSON_LINE_START,\n LINE_BREAK,\n} from '../../constants/hookRunner';\nimport { HOOK_TELEMETRY_EVENT } from '../../constants/telemetry';\nimport type {\n HookCommand,\n HookDecision,\n HookOutcome,\n HookPayload,\n HookRunOptions,\n HookRunner,\n} from '../../types/hooks';\nimport { type HookTelemetry } from '../../types/telemetry';\n\nexport interface BashHookRunnerOptions {\n telemetry?: HookTelemetry;\n env?: NodeJS.ProcessEnv;\n platform?: NodeJS.Platform;\n spawn?: typeof spawnProcess;\n warn?: (message: string) => void;\n}\n\nfunction errorCode(error: unknown): string | undefined {\n return error instanceof Error && 'code' in error ? String(error.code) : undefined;\n}\n\n/**\n * Runs advisory hook commands through bash and reports what each one decided.\n *\n * A hook is a command the repository owns, so it is spawned in its own process\n * group and terminated as one: a hook that starts a server and stalls should\n * not leave the server behind when the timeout fires.\n */\nexport function createBashHookRunner(options: BashHookRunnerOptions = {}): HookRunner {\n const spawn = options.spawn ?? spawnProcess;\n const telemetry = options.telemetry;\n const warn = options.warn ?? ((message: string) => void process.stderr.write(message));\n const useProcessGroup = (options.platform ?? process.platform) !== WINDOWS_PLATFORM;\n\n const signalOwnedProcess = (\n pid: number | undefined,\n kill: (signal: NodeJS.Signals) => void,\n ): ((signal: NodeJS.Signals) => void) => {\n return (signal) => {\n try {\n if (useProcessGroup && pid !== undefined) {\n process.kill(-pid, signal);\n return;\n }\n kill(signal);\n } catch (error) {\n if (errorCode(error) !== PROCESS_NOT_FOUND_ERROR) {\n process.emitWarning(`Could not signal repository hook process: ${String(error)}`);\n }\n }\n };\n };\n\n return {\n run(hook: HookCommand, payload: HookPayload, runOptions: HookRunOptions): Promise<HookOutcome> {\n const timeoutSeconds = hook.timeout ?? DEFAULT_HOOK_TIMEOUT_SECONDS;\n const environment = options.env ?? process.env;\n return new Promise((resolve) => {\n // -c, not -lc. Hooks run on every tool call, and a login shell would\n // source the developer's profile each time: per-call latency plus hook\n // behavior that varies with their dotfiles. The child inherits the\n // environment below, so it keeps the PATH the launcher started with.\n const child = spawn(HOOK_SHELL, [HOOK_SHELL_COMMAND_FLAG, hook.command], {\n cwd: runOptions.repoRoot,\n env: {\n ...environment,\n CLAUDE_PROJECT_DIR: runOptions.repoRoot,\n CODEX_REPO_ROOT: runOptions.repoRoot,\n ORIGINAL_REPO_PATH: environment.ORIGINAL_REPO_PATH ?? runOptions.repoRoot,\n ...(runOptions.pluginRoot ? { CLAUDE_PLUGIN_ROOT: runOptions.pluginRoot } : {}),\n },\n stdio: ['pipe', 'pipe', 'pipe'],\n detached: useProcessGroup,\n });\n let stdout = '';\n let stderr = '';\n let settled = false;\n let timedOut = false;\n let childExited = false;\n let timeoutExitCode: number | null = null;\n let escalationTimer: NodeJS.Timeout | undefined;\n\n const signal = signalOwnedProcess(child.pid, (value) => child.kill(value));\n\n const ownedProcessIsAlive = (): boolean => {\n if (!useProcessGroup || child.pid === undefined) return !childExited;\n try {\n process.kill(-child.pid, 0);\n return true;\n } catch (error) {\n return errorCode(error) !== PROCESS_NOT_FOUND_ERROR;\n }\n };\n\n const finish = (outcome: HookOutcome = {}): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n if (escalationTimer) clearTimeout(escalationTimer);\n resolve(outcome);\n };\n\n const finishTimeout = (): void => {\n const message = `Hook timed out after ${timeoutSeconds} seconds.`;\n void telemetry?.recordWarning(HOOK_TELEMETRY_EVENT.hookFailed, message, {\n 'hook.reason': 'timeout',\n 'hook.exit_code': timeoutExitCode ?? UNKNOWN_EXIT_CODE,\n });\n warn(`[pi-hook] advisory hook timed out: ${hook.command}\\n${stderr}`);\n finish({ failure: { command: hook.command, message, reason: 'timeout' } });\n };\n\n const timer = setTimeout(() => {\n timedOut = true;\n signal('SIGTERM');\n escalationTimer = setTimeout(() => {\n if (ownedProcessIsAlive()) signal('SIGKILL');\n finishTimeout();\n }, HOOK_TERMINATION_GRACE_MS);\n }, timeoutSeconds * MILLISECONDS_PER_SECOND);\n\n child.stdout?.on('data', (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr += chunk.toString();\n });\n child.once('error', (error: Error) => {\n if (timedOut) return;\n // A guardrail that never ran is indistinguishable from one that\n // passed, which is the whole reason these are worth reporting.\n void telemetry?.recordError(HOOK_TELEMETRY_EVENT.hookFailed, error, { 'hook.reason': 'spawn_failed' });\n warn(`[pi-hook] advisory hook failed: ${error.message}\\n`);\n finish({ failure: { command: hook.command, message: error.message, reason: 'spawn_failed' } });\n });\n child.once('exit', (code: number | null) => {\n childExited = true;\n timeoutExitCode = code;\n if (timedOut) return;\n if (code !== 0) {\n const message = stderr.trim() || `Advisory hook exited with code ${code ?? 'unknown'}`;\n void telemetry?.recordWarning(HOOK_TELEMETRY_EVENT.hookFailed, message, {\n 'hook.reason': 'non_zero_exit',\n 'hook.exit_code': code ?? UNKNOWN_EXIT_CODE,\n });\n warn(`[pi-hook] advisory hook failed (${code}): ${hook.command}\\n${stderr}`);\n finish({ failure: { command: hook.command, message, reason: 'non_zero_exit' } });\n return;\n }\n const jsonLine = stdout\n .trim()\n .split(LINE_BREAK)\n .reverse()\n .find((line) => line.startsWith(JSON_LINE_START));\n if (!jsonLine) {\n finish();\n return;\n }\n try {\n finish({ decision: JSON.parse(jsonLine) as HookDecision });\n } catch (error) {\n // The hook ran and had an opinion, and it was dropped.\n void telemetry?.recordWarning(HOOK_TELEMETRY_EVENT.hookFailed, error, { 'hook.reason': 'invalid_json' });\n warn(`[pi-hook] advisory hook returned invalid JSON: ${hook.command}\\n`);\n finish({\n failure: {\n command: hook.command,\n message: error instanceof Error ? error.message : String(error),\n reason: 'invalid_json',\n },\n });\n }\n });\n child.stdin?.end(JSON.stringify(payload));\n });\n },\n };\n}\n","export const SERVICE_NAME = 'doom-pi-hook';\nexport const PACKAGE_NAME = '@agimon-ai/doompi-hook';\n","import { createDoomTelemetry, type DoomTelemetry, type DoomTelemetryOptions } from '@agimon-ai/doompi-telemetry';\n\nimport { SERVICE_NAME, PACKAGE_NAME } from '../../constants/hookTelemetry';\nimport type { HookTelemetry } from '../../types/telemetry';\n\nexport interface HookTelemetryOptions {\n cwd?: string;\n workspaceRoot?: string;\n env?: NodeJS.ProcessEnv;\n telemetryFactory?: NonNullable<DoomTelemetryOptions['telemetryFactory']>;\n warn?: (message: string) => void;\n}\n\nexport function createHookTelemetry(options: HookTelemetryOptions = {}): HookTelemetry {\n const telemetry: DoomTelemetry = createDoomTelemetry({\n serviceName: SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: options.env,\n telemetryFactory: options.telemetryFactory,\n warn: options.warn,\n enableLogs: true,\n enableTraces: true,\n });\n return {\n recordError: (event, error, attributes) => telemetry.recordError(event, error, attributes),\n recordWarning: (event, error, attributes) => telemetry.recordWarning(event, error, attributes),\n };\n}\n","import type { PluginHookDocument, ResolvedHook } from '../../types/hooks';\nimport { matchesTool } from '../toolNames';\n\n/**\n * The plugin hooks one dispatch runs.\n *\n * Plugin configs are the Claude Code `hooks.json` shape verbatim: an event name\n * maps to groups, each with an optional matcher and a list of commands. Order\n * follows the declaration order of the plugins the harness resolved.\n */\nexport function selectPluginHooks(\n documents: ReadonlyArray<PluginHookDocument>,\n eventName: string,\n toolName?: string,\n): ResolvedHook[] {\n const matches: ResolvedHook[] = [];\n for (const document of documents) {\n for (const group of document.config.hooks?.[eventName] ?? []) {\n if (!matchesTool(group.matcher, toolName)) continue;\n for (const hook of group.hooks ?? []) matches.push({ hook, root: document.pluginRoot });\n }\n }\n return matches;\n}\n","export const HOOK_EVENT = {\n sessionStart: 'SessionStart',\n preToolUse: 'PreToolUse',\n postToolUse: 'PostToolUse',\n stop: 'Stop',\n sessionEnd: 'SessionEn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