@librechat/agents 3.1.66 → 3.1.67-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +23 -3
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +14 -0
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +72 -0
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/hooks/HookRegistry.cjs +162 -0
  8. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -0
  9. package/dist/cjs/hooks/executeHooks.cjs +276 -0
  10. package/dist/cjs/hooks/executeHooks.cjs.map +1 -0
  11. package/dist/cjs/hooks/matchers.cjs +256 -0
  12. package/dist/cjs/hooks/matchers.cjs.map +1 -0
  13. package/dist/cjs/hooks/types.cjs +27 -0
  14. package/dist/cjs/hooks/types.cjs.map +1 -0
  15. package/dist/cjs/main.cjs +52 -0
  16. package/dist/cjs/main.cjs.map +1 -1
  17. package/dist/cjs/messages/format.cjs +74 -12
  18. package/dist/cjs/messages/format.cjs.map +1 -1
  19. package/dist/cjs/run.cjs +111 -0
  20. package/dist/cjs/run.cjs.map +1 -1
  21. package/dist/cjs/summarization/node.cjs +44 -0
  22. package/dist/cjs/summarization/node.cjs.map +1 -1
  23. package/dist/cjs/tools/BashExecutor.cjs +175 -0
  24. package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
  25. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +296 -0
  26. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
  27. package/dist/cjs/tools/ReadFile.cjs +43 -0
  28. package/dist/cjs/tools/ReadFile.cjs.map +1 -0
  29. package/dist/cjs/tools/SkillTool.cjs +50 -0
  30. package/dist/cjs/tools/SkillTool.cjs.map +1 -0
  31. package/dist/cjs/tools/SubagentTool.cjs +92 -0
  32. package/dist/cjs/tools/SubagentTool.cjs.map +1 -0
  33. package/dist/cjs/tools/ToolNode.cjs +304 -140
  34. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  35. package/dist/cjs/tools/skillCatalog.cjs +84 -0
  36. package/dist/cjs/tools/skillCatalog.cjs.map +1 -0
  37. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +261 -0
  38. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -0
  39. package/dist/esm/agents/AgentContext.mjs +23 -3
  40. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  41. package/dist/esm/common/enum.mjs +13 -1
  42. package/dist/esm/common/enum.mjs.map +1 -1
  43. package/dist/esm/graphs/Graph.mjs +72 -0
  44. package/dist/esm/graphs/Graph.mjs.map +1 -1
  45. package/dist/esm/hooks/HookRegistry.mjs +160 -0
  46. package/dist/esm/hooks/HookRegistry.mjs.map +1 -0
  47. package/dist/esm/hooks/executeHooks.mjs +273 -0
  48. package/dist/esm/hooks/executeHooks.mjs.map +1 -0
  49. package/dist/esm/hooks/matchers.mjs +251 -0
  50. package/dist/esm/hooks/matchers.mjs.map +1 -0
  51. package/dist/esm/hooks/types.mjs +25 -0
  52. package/dist/esm/hooks/types.mjs.map +1 -0
  53. package/dist/esm/main.mjs +12 -1
  54. package/dist/esm/main.mjs.map +1 -1
  55. package/dist/esm/messages/format.mjs +66 -4
  56. package/dist/esm/messages/format.mjs.map +1 -1
  57. package/dist/esm/run.mjs +111 -0
  58. package/dist/esm/run.mjs.map +1 -1
  59. package/dist/esm/summarization/node.mjs +44 -0
  60. package/dist/esm/summarization/node.mjs.map +1 -1
  61. package/dist/esm/tools/BashExecutor.mjs +169 -0
  62. package/dist/esm/tools/BashExecutor.mjs.map +1 -0
  63. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +287 -0
  64. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
  65. package/dist/esm/tools/ReadFile.mjs +38 -0
  66. package/dist/esm/tools/ReadFile.mjs.map +1 -0
  67. package/dist/esm/tools/SkillTool.mjs +45 -0
  68. package/dist/esm/tools/SkillTool.mjs.map +1 -0
  69. package/dist/esm/tools/SubagentTool.mjs +85 -0
  70. package/dist/esm/tools/SubagentTool.mjs.map +1 -0
  71. package/dist/esm/tools/ToolNode.mjs +306 -142
  72. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  73. package/dist/esm/tools/skillCatalog.mjs +82 -0
  74. package/dist/esm/tools/skillCatalog.mjs.map +1 -0
  75. package/dist/esm/tools/subagent/SubagentExecutor.mjs +256 -0
  76. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -0
  77. package/dist/types/agents/AgentContext.d.ts +6 -0
  78. package/dist/types/common/enum.d.ts +8 -1
  79. package/dist/types/graphs/Graph.d.ts +2 -0
  80. package/dist/types/hooks/HookRegistry.d.ts +56 -0
  81. package/dist/types/hooks/executeHooks.d.ts +79 -0
  82. package/dist/types/hooks/index.d.ts +6 -0
  83. package/dist/types/hooks/matchers.d.ts +95 -0
  84. package/dist/types/hooks/types.d.ts +320 -0
  85. package/dist/types/index.d.ts +8 -0
  86. package/dist/types/messages/format.d.ts +2 -1
  87. package/dist/types/run.d.ts +1 -0
  88. package/dist/types/summarization/node.d.ts +2 -0
  89. package/dist/types/tools/BashExecutor.d.ts +45 -0
  90. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +72 -0
  91. package/dist/types/tools/ReadFile.d.ts +28 -0
  92. package/dist/types/tools/SkillTool.d.ts +40 -0
  93. package/dist/types/tools/SubagentTool.d.ts +36 -0
  94. package/dist/types/tools/ToolNode.d.ts +24 -2
  95. package/dist/types/tools/skillCatalog.d.ts +19 -0
  96. package/dist/types/tools/subagent/SubagentExecutor.d.ts +83 -0
  97. package/dist/types/tools/subagent/index.d.ts +2 -0
  98. package/dist/types/types/graph.d.ts +25 -0
  99. package/dist/types/types/index.d.ts +1 -0
  100. package/dist/types/types/llm.d.ts +14 -2
  101. package/dist/types/types/run.d.ts +20 -0
  102. package/dist/types/types/skill.d.ts +9 -0
  103. package/dist/types/types/tools.d.ts +38 -1
  104. package/package.json +2 -1
  105. package/src/agents/AgentContext.ts +26 -2
  106. package/src/common/enum.ts +13 -0
  107. package/src/graphs/Graph.ts +92 -0
  108. package/src/hooks/HookRegistry.ts +208 -0
  109. package/src/hooks/__tests__/HookRegistry.test.ts +190 -0
  110. package/src/hooks/__tests__/compactHooks.test.ts +214 -0
  111. package/src/hooks/__tests__/executeHooks.test.ts +1013 -0
  112. package/src/hooks/__tests__/integration.test.ts +337 -0
  113. package/src/hooks/__tests__/matchers.test.ts +238 -0
  114. package/src/hooks/__tests__/toolHooks.test.ts +669 -0
  115. package/src/hooks/executeHooks.ts +375 -0
  116. package/src/hooks/index.ts +57 -0
  117. package/src/hooks/matchers.ts +280 -0
  118. package/src/hooks/types.ts +404 -0
  119. package/src/index.ts +10 -0
  120. package/src/messages/format.ts +74 -4
  121. package/src/messages/formatAgentMessages.skills.test.ts +334 -0
  122. package/src/run.ts +126 -0
  123. package/src/scripts/multi-agent-subagent.ts +246 -0
  124. package/src/specs/subagent.test.ts +305 -0
  125. package/src/summarization/node.ts +53 -0
  126. package/src/tools/BashExecutor.ts +205 -0
  127. package/src/tools/BashProgrammaticToolCalling.ts +397 -0
  128. package/src/tools/ReadFile.ts +39 -0
  129. package/src/tools/SkillTool.ts +46 -0
  130. package/src/tools/SubagentTool.ts +100 -0
  131. package/src/tools/ToolNode.ts +391 -169
  132. package/src/tools/__tests__/ReadFile.test.ts +44 -0
  133. package/src/tools/__tests__/SkillTool.test.ts +442 -0
  134. package/src/tools/__tests__/SubagentExecutor.test.ts +615 -0
  135. package/src/tools/__tests__/SubagentTool.test.ts +149 -0
  136. package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
  137. package/src/tools/__tests__/skillCatalog.test.ts +161 -0
  138. package/src/tools/__tests__/subagentHooks.test.ts +215 -0
  139. package/src/tools/skillCatalog.ts +126 -0
  140. package/src/tools/subagent/SubagentExecutor.ts +344 -0
  141. package/src/tools/subagent/index.ts +12 -0
  142. package/src/types/graph.ts +27 -0
  143. package/src/types/index.ts +1 -0
  144. package/src/types/llm.ts +16 -2
  145. package/src/types/run.ts +20 -0
  146. package/src/types/skill.ts +11 -0
  147. package/src/types/tools.ts +41 -1
@@ -0,0 +1,375 @@
1
+ // src/hooks/executeHooks.ts
2
+ import type { Logger } from 'winston';
3
+ import type { HookRegistry } from './HookRegistry';
4
+ import type {
5
+ HookInput,
6
+ HookEvent,
7
+ HookOutput,
8
+ HookMatcher,
9
+ ToolDecision,
10
+ StopDecision,
11
+ HookCallback,
12
+ AggregatedHookResult,
13
+ } from './types';
14
+ import { matchesQuery } from './matchers';
15
+
16
+ /** Default per-hook timeout when a matcher doesn't set its own. */
17
+ export const DEFAULT_HOOK_TIMEOUT_MS = 30_000;
18
+
19
+ /**
20
+ * Options for a single `executeHooks` call. The `input` drives everything —
21
+ * the event name is read from `input.hook_event_name`, matchers are looked
22
+ * up against that event, and each hook receives `input` directly.
23
+ */
24
+ export interface ExecuteHooksOptions {
25
+ registry: HookRegistry;
26
+ input: HookInput;
27
+ /** Scope lookup to this session (in addition to global matchers). */
28
+ sessionId?: string;
29
+ /** Query string matched against each matcher's pattern (tool name, etc.). */
30
+ matchQuery?: string;
31
+ /** Parent AbortSignal — combined with per-hook timeout into the hook signal. */
32
+ signal?: AbortSignal;
33
+ /** Default per-hook timeout; overridden by `matcher.timeout` when present. */
34
+ timeoutMs?: number;
35
+ /** Optional winston logger for non-internal hook errors. */
36
+ logger?: Logger;
37
+ }
38
+
39
+ type WideMatcher = HookMatcher<HookEvent>;
40
+ type WideCallback = HookCallback<HookEvent>;
41
+
42
+ interface HookOutcome {
43
+ matcher: WideMatcher;
44
+ output: HookOutput | null;
45
+ error: string | null;
46
+ timedOut: boolean;
47
+ }
48
+
49
+ function freshResult(): AggregatedHookResult {
50
+ return {
51
+ additionalContexts: [],
52
+ errors: [],
53
+ };
54
+ }
55
+
56
+ function combineSignals(
57
+ parent: AbortSignal | undefined,
58
+ timeoutMs: number
59
+ ): AbortSignal {
60
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
61
+ if (parent === undefined) {
62
+ return timeoutSignal;
63
+ }
64
+ return AbortSignal.any([parent, timeoutSignal]);
65
+ }
66
+
67
+ function isTimeout(err: unknown): boolean {
68
+ if (err instanceof Error) {
69
+ return err.name === 'TimeoutError' || err.name === 'AbortError';
70
+ }
71
+ return false;
72
+ }
73
+
74
+ function describeError(err: unknown): string {
75
+ if (err instanceof Error) {
76
+ return err.message !== '' ? err.message : err.name;
77
+ }
78
+ return String(err);
79
+ }
80
+
81
+ function makeAbortPromise(signal: AbortSignal): {
82
+ promise: Promise<never>;
83
+ cleanup: () => void;
84
+ } {
85
+ let onAbort: (() => void) | undefined;
86
+ const promise = new Promise<never>((_resolve, reject) => {
87
+ if (signal.aborted) {
88
+ reject(
89
+ signal.reason instanceof Error ? signal.reason : new Error('aborted')
90
+ );
91
+ return;
92
+ }
93
+ onAbort = (): void => {
94
+ reject(
95
+ signal.reason instanceof Error ? signal.reason : new Error('aborted')
96
+ );
97
+ };
98
+ signal.addEventListener('abort', onAbort, { once: true });
99
+ });
100
+ const cleanup = (): void => {
101
+ if (onAbort !== undefined) {
102
+ signal.removeEventListener('abort', onAbort);
103
+ onAbort = undefined;
104
+ }
105
+ };
106
+ return { promise, cleanup };
107
+ }
108
+
109
+ async function runHook(
110
+ hook: WideCallback,
111
+ input: HookInput,
112
+ signal: AbortSignal,
113
+ matcher: WideMatcher
114
+ ): Promise<HookOutcome> {
115
+ const hookPromise = Promise.resolve().then(() => hook(input, signal));
116
+ const { promise: abortPromise, cleanup } = makeAbortPromise(signal);
117
+ try {
118
+ const output = await Promise.race([hookPromise, abortPromise]);
119
+ return { matcher, output, error: null, timedOut: false };
120
+ } catch (err) {
121
+ return {
122
+ matcher,
123
+ output: null,
124
+ error: describeError(err),
125
+ timedOut: isTimeout(err),
126
+ };
127
+ } finally {
128
+ cleanup();
129
+ }
130
+ }
131
+
132
+ function reportErrors(
133
+ outcomes: readonly HookOutcome[],
134
+ event: HookEvent,
135
+ logger: Logger | undefined
136
+ ): void {
137
+ for (const outcome of outcomes) {
138
+ if (outcome.error === null) {
139
+ continue;
140
+ }
141
+ if (outcome.matcher.internal === true) {
142
+ continue;
143
+ }
144
+ const label = outcome.timedOut ? 'timed out' : 'threw an error';
145
+ const message = `Hook for ${event} ${label}: ${outcome.error}`;
146
+ if (logger !== undefined) {
147
+ logger.warn(message);
148
+ continue;
149
+ }
150
+ // eslint-disable-next-line no-console
151
+ console.warn(message);
152
+ }
153
+ }
154
+
155
+ function applyToolDecision(
156
+ agg: AggregatedHookResult,
157
+ decision: ToolDecision,
158
+ reason: string | undefined
159
+ ): void {
160
+ if (decision === 'deny') {
161
+ if (agg.decision === 'deny') {
162
+ return;
163
+ }
164
+ agg.decision = 'deny';
165
+ agg.reason = reason;
166
+ return;
167
+ }
168
+ if (decision === 'ask') {
169
+ if (agg.decision === 'deny' || agg.decision === 'ask') {
170
+ return;
171
+ }
172
+ agg.decision = 'ask';
173
+ agg.reason = reason;
174
+ return;
175
+ }
176
+ if (agg.decision === undefined) {
177
+ agg.decision = 'allow';
178
+ agg.reason = reason;
179
+ }
180
+ }
181
+
182
+ function applyStopDecision(
183
+ agg: AggregatedHookResult,
184
+ decision: StopDecision,
185
+ reason: string | undefined
186
+ ): void {
187
+ if (decision === 'block') {
188
+ if (agg.stopDecision === 'block') {
189
+ return;
190
+ }
191
+ agg.stopDecision = 'block';
192
+ agg.reason = reason;
193
+ return;
194
+ }
195
+ if (agg.stopDecision === undefined) {
196
+ agg.stopDecision = 'continue';
197
+ if (agg.reason === undefined) {
198
+ agg.reason = reason;
199
+ }
200
+ }
201
+ }
202
+
203
+ function applyDecision(agg: AggregatedHookResult, output: HookOutput): void {
204
+ if (!('decision' in output) || output.decision === undefined) {
205
+ return;
206
+ }
207
+ const decision = output.decision;
208
+ const reason =
209
+ 'reason' in output && typeof output.reason === 'string'
210
+ ? output.reason
211
+ : undefined;
212
+ if (decision === 'deny' || decision === 'ask' || decision === 'allow') {
213
+ applyToolDecision(agg, decision, reason);
214
+ return;
215
+ }
216
+ applyStopDecision(agg, decision, reason);
217
+ }
218
+
219
+ function applyContext(agg: AggregatedHookResult, output: HookOutput): void {
220
+ if (
221
+ typeof output.additionalContext === 'string' &&
222
+ output.additionalContext.length > 0
223
+ ) {
224
+ agg.additionalContexts.push(output.additionalContext);
225
+ }
226
+ }
227
+
228
+ function applyStopFlag(agg: AggregatedHookResult, output: HookOutput): void {
229
+ if (output.preventContinuation !== true) {
230
+ return;
231
+ }
232
+ agg.preventContinuation = true;
233
+ if (typeof output.stopReason === 'string' && agg.stopReason === undefined) {
234
+ agg.stopReason = output.stopReason;
235
+ }
236
+ }
237
+
238
+ function applyUpdatedInput(
239
+ agg: AggregatedHookResult,
240
+ output: HookOutput
241
+ ): void {
242
+ if (!('updatedInput' in output) || output.updatedInput === undefined) {
243
+ return;
244
+ }
245
+ agg.updatedInput = output.updatedInput;
246
+ }
247
+
248
+ function applyUpdatedOutput(
249
+ agg: AggregatedHookResult,
250
+ output: HookOutput
251
+ ): void {
252
+ if (!('updatedOutput' in output) || output.updatedOutput === undefined) {
253
+ return;
254
+ }
255
+ agg.updatedOutput = output.updatedOutput;
256
+ }
257
+
258
+ function fold(outcomes: readonly HookOutcome[]): AggregatedHookResult {
259
+ const agg = freshResult();
260
+ for (const outcome of outcomes) {
261
+ if (outcome.error !== null) {
262
+ if (outcome.matcher.internal !== true) {
263
+ agg.errors.push(outcome.error);
264
+ }
265
+ continue;
266
+ }
267
+ const output = outcome.output;
268
+ if (output === null) {
269
+ continue;
270
+ }
271
+ applyContext(agg, output);
272
+ applyStopFlag(agg, output);
273
+ applyDecision(agg, output);
274
+ applyUpdatedInput(agg, output);
275
+ applyUpdatedOutput(agg, output);
276
+ }
277
+ return agg;
278
+ }
279
+
280
+ /**
281
+ * Fires every matcher registered against `input.hook_event_name`, folding
282
+ * their results per `deny > ask > allow` precedence and accumulating
283
+ * context/errors.
284
+ *
285
+ * ## Parallelism and determinism
286
+ *
287
+ * All matching hooks fire simultaneously and are awaited via `Promise.all`,
288
+ * which preserves input-array order in its returned results. The fold
289
+ * therefore iterates outcomes in **registration order** — outer loop over
290
+ * matchers as they sit in the registry (global first, then session), inner
291
+ * loop over each matcher's `hooks` array. Last-writer-wins fields
292
+ * (`updatedInput`, `updatedOutput`) are deterministic in that order, even
293
+ * though hooks may complete in arbitrary wall-clock order.
294
+ *
295
+ * Consumers that need a single authoritative rewrite should still scope
296
+ * `updatedInput`/`updatedOutput` to one hook per matcher to avoid subtle
297
+ * precedence bugs when matchers are added in a different order than
298
+ * expected.
299
+ *
300
+ * ## Timeouts and cancellation
301
+ *
302
+ * Each matcher receives **one shared `AbortSignal`** derived from the
303
+ * caller's parent signal combined with `matcher.timeout` (falling back to
304
+ * `opts.timeoutMs`, default {@link DEFAULT_HOOK_TIMEOUT_MS}). Sharing the
305
+ * signal across hooks in a matcher collapses N timer allocations into
306
+ * one, which matters on the PreToolUse hot path where a matcher with
307
+ * several hooks fires on every tool call. Each hook call is raced
308
+ * against the shared signal, so even a hook that ignores the signal is
309
+ * force-unblocked when the timeout fires. Timeout/abort errors are
310
+ * swallowed into the aggregated result's `errors` array (non-fatal by
311
+ * default).
312
+ *
313
+ * ## Internal matchers
314
+ *
315
+ * A matcher with `internal: true` is excluded from both the `errors` array
316
+ * and the logger output. Use it for infrastructure hooks whose failures
317
+ * should not pollute user-visible diagnostics.
318
+ *
319
+ * ## Once semantics — atomic at-most-once
320
+ *
321
+ * A matcher with `once: true` is removed from the registry **before any
322
+ * hook runs**, inside the synchronous prefix of `executeHooks` (between
323
+ * `getMatchers` and the first `await`). Because Node's event loop serialises
324
+ * sync work, two concurrent `executeHooks` calls can never both observe
325
+ * and dispatch the same `once` matcher — whichever call runs its sync
326
+ * prefix first consumes it, and the loser sees an empty bucket.
327
+ *
328
+ * Trade-off: if every hook in a `once` matcher throws, the matcher is
329
+ * still gone. "Once" here means "at most one dispatch, ever", not "at
330
+ * most one successful execution with retry on failure". Hosts that need
331
+ * retry semantics should register a normal matcher and self-unregister
332
+ * via the `unregister` callback returned from `registry.register`.
333
+ */
334
+ export async function executeHooks(
335
+ opts: ExecuteHooksOptions
336
+ ): Promise<AggregatedHookResult> {
337
+ const {
338
+ registry,
339
+ input,
340
+ sessionId,
341
+ matchQuery,
342
+ signal,
343
+ timeoutMs = DEFAULT_HOOK_TIMEOUT_MS,
344
+ logger,
345
+ } = opts;
346
+ const event = input.hook_event_name;
347
+ const matchers = registry.getMatchers(event, sessionId);
348
+ if (matchers.length === 0) {
349
+ return freshResult();
350
+ }
351
+
352
+ // --- SYNC CRITICAL SECTION: once-matcher removal must complete before any await ---
353
+ const tasks: Promise<HookOutcome>[] = [];
354
+ for (const matcher of matchers) {
355
+ if (!matchesQuery(matcher.pattern, matchQuery)) {
356
+ continue;
357
+ }
358
+ if (matcher.once === true) {
359
+ registry.removeMatcher(event, matcher, sessionId);
360
+ }
361
+ const perHookTimeout = matcher.timeout ?? timeoutMs;
362
+ const matcherSignal = combineSignals(signal, perHookTimeout);
363
+ for (const hook of matcher.hooks) {
364
+ tasks.push(runHook(hook, input, matcherSignal, matcher));
365
+ }
366
+ }
367
+ // --- END SYNC CRITICAL SECTION ---
368
+ if (tasks.length === 0) {
369
+ return freshResult();
370
+ }
371
+
372
+ const outcomes = await Promise.all(tasks);
373
+ reportErrors(outcomes, event, logger);
374
+ return fold(outcomes);
375
+ }
@@ -0,0 +1,57 @@
1
+ // src/hooks/index.ts
2
+ //
3
+ // Hook lifecycle system for `@librechat/agents`. Re-exported from
4
+ // `src/index.ts` and consumed by `Run.processStream` (RunStart,
5
+ // UserPromptSubmit, Stop, StopFailure), `ToolNode.dispatchToolEvents`
6
+ // (PreToolUse, PostToolUse, PostToolUseFailure, PermissionDenied),
7
+ // `createSummarizeNode` (PreCompact, PostCompact), and
8
+ // `SubagentExecutor.execute` (SubagentStart, SubagentStop).
9
+ export { HookRegistry } from './HookRegistry';
10
+ export { executeHooks, DEFAULT_HOOK_TIMEOUT_MS } from './executeHooks';
11
+ export {
12
+ matchesQuery,
13
+ hasNestedQuantifier,
14
+ MAX_PATTERN_LENGTH,
15
+ MAX_CACHE_SIZE,
16
+ } from './matchers';
17
+ export { HOOK_EVENTS } from './types';
18
+ export type {
19
+ HookEvent,
20
+ HookInput,
21
+ HookOutput,
22
+ HookCallback,
23
+ HookMatcher,
24
+ HooksByEvent,
25
+ HookInputByEvent,
26
+ HookOutputByEvent,
27
+ BaseHookInput,
28
+ BaseHookOutput,
29
+ ToolDecision,
30
+ StopDecision,
31
+ AggregatedHookResult,
32
+ RunStartHookInput,
33
+ UserPromptSubmitHookInput,
34
+ PreToolUseHookInput,
35
+ PostToolUseHookInput,
36
+ PostToolUseFailureHookInput,
37
+ PermissionDeniedHookInput,
38
+ SubagentStartHookInput,
39
+ SubagentStopHookInput,
40
+ StopHookInput,
41
+ StopFailureHookInput,
42
+ PreCompactHookInput,
43
+ PostCompactHookInput,
44
+ RunStartHookOutput,
45
+ UserPromptSubmitHookOutput,
46
+ PreToolUseHookOutput,
47
+ PostToolUseHookOutput,
48
+ PostToolUseFailureHookOutput,
49
+ PermissionDeniedHookOutput,
50
+ SubagentStartHookOutput,
51
+ SubagentStopHookOutput,
52
+ StopHookOutput,
53
+ StopFailureHookOutput,
54
+ PreCompactHookOutput,
55
+ PostCompactHookOutput,
56
+ } from './types';
57
+ export type { ExecuteHooksOptions } from './executeHooks';
@@ -0,0 +1,280 @@
1
+ // src/hooks/matchers.ts
2
+
3
+ /**
4
+ * Upper bound on hook-matcher pattern length. Patterns longer than this
5
+ * are rejected outright — the goal is a cheap cap on pathological inputs
6
+ * (repeated quantifiers, huge alternation groups) without pulling in a
7
+ * safe-regex dependency.
8
+ *
9
+ * Legitimate matchers are almost always under 50 characters (tool names,
10
+ * short alternations, simple prefix anchors); 512 leaves generous
11
+ * headroom while preventing 10KB regexes.
12
+ */
13
+ export const MAX_PATTERN_LENGTH = 512;
14
+
15
+ /**
16
+ * Upper bound on the compilation cache. Chosen to comfortably hold every
17
+ * distinct pattern a single multi-tenant run is likely to see (tools,
18
+ * agent types, basename filters) without growing without bound.
19
+ *
20
+ * Under hosts that register unique patterns per tenant, LRU eviction
21
+ * keeps the working set bounded — cold patterns are re-compiled on next
22
+ * use, which is the correct cost trade-off for long-running processes
23
+ * that must not leak memory.
24
+ */
25
+ export const MAX_CACHE_SIZE = 256;
26
+
27
+ interface CacheEntry {
28
+ regex: RegExp | null;
29
+ }
30
+
31
+ /**
32
+ * Module-level LRU cache keyed by pattern string. Map iteration order is
33
+ * insertion order in ECMAScript, so refreshing an entry's position means
34
+ * "delete then re-set". On overflow we evict the first key (least
35
+ * recently used).
36
+ *
37
+ * Failed compiles are cached as `{ regex: null }` so a malformed pattern
38
+ * does not re-enter the compiler — and so a tenant spamming bad patterns
39
+ * doesn't burn CPU on every call.
40
+ */
41
+ const patternCache: Map<string, CacheEntry> = new Map();
42
+
43
+ /**
44
+ * Threshold above which `touchCacheEntry` actually performs the LRU
45
+ * refresh. Below this watermark the cache has zero eviction pressure, so
46
+ * the delete+set on every hit would be pure overhead. Above it we refresh
47
+ * properly so hot patterns survive evictions. 75% of capacity is the
48
+ * standard sweet spot.
49
+ */
50
+ const LRU_REFRESH_THRESHOLD = Math.floor((MAX_CACHE_SIZE * 3) / 4);
51
+
52
+ function touchCacheEntry(pattern: string, entry: CacheEntry): void {
53
+ if (patternCache.size < LRU_REFRESH_THRESHOLD) {
54
+ return;
55
+ }
56
+ patternCache.delete(pattern);
57
+ patternCache.set(pattern, entry);
58
+ }
59
+
60
+ function setCacheEntry(pattern: string, entry: CacheEntry): void {
61
+ if (patternCache.size >= MAX_CACHE_SIZE) {
62
+ const oldestKey = patternCache.keys().next().value;
63
+ if (oldestKey !== undefined) {
64
+ patternCache.delete(oldestKey);
65
+ }
66
+ }
67
+ patternCache.set(pattern, entry);
68
+ }
69
+
70
+ interface QuantifierFrame {
71
+ hasBacktrackRisk: boolean;
72
+ }
73
+
74
+ function skipGroupSyntaxPrefix(pattern: string, start: number): number {
75
+ if (start >= pattern.length || pattern[start] !== '?') {
76
+ return start;
77
+ }
78
+ let i = start + 1;
79
+ if (i >= pattern.length) {
80
+ return i;
81
+ }
82
+ const modifier = pattern[i];
83
+ if (modifier === ':' || modifier === '=' || modifier === '!') {
84
+ return i + 1;
85
+ }
86
+ if (modifier !== '<') {
87
+ return i;
88
+ }
89
+ i++;
90
+ if (i < pattern.length && (pattern[i] === '=' || pattern[i] === '!')) {
91
+ return i + 1;
92
+ }
93
+ while (i < pattern.length && pattern[i] !== '>') {
94
+ i++;
95
+ }
96
+ if (i < pattern.length) {
97
+ i++;
98
+ }
99
+ return i;
100
+ }
101
+
102
+ /**
103
+ * Cheap syntactic detector for the most common catastrophic-backtracking
104
+ * shape: a quantified group that contains another quantifier (e.g.
105
+ * `(a+)+`, `(.*)*`, `(\w+)+$`, `(?:(a+))+`). This is the "nested
106
+ * quantifier" class of ReDoS — runs in polynomial-or-worse time on
107
+ * adversarial inputs.
108
+ *
109
+ * The scan walks the pattern linearly using an explicit stack of group
110
+ * frames. For each group it tracks whether the group's contents include
111
+ * "backtrack risk" — meaning a direct quantifier OR a nested group that
112
+ * carries risk up. When a group closes with a trailing quantifier AND its
113
+ * frame carries backtrack risk, the pattern is flagged. Risk propagates
114
+ * to the enclosing frame when a child group closes (whether the child
115
+ * itself was quantified or not), so `(?:(a+))+` — equivalent to `(a+)+`
116
+ * — is flagged correctly even though the outer non-capturing wrapper is
117
+ * one level removed from the inner quantifier.
118
+ *
119
+ * ## Group-syntax prefixes
120
+ *
121
+ * Non-capturing groups (`(?:`), lookaheads (`(?=`, `(?!`), lookbehinds
122
+ * (`(?<=`, `(?<!`), and named groups (`(?<name>`) are skipped over at
123
+ * the `(` so their `?` is not misread as a quantifier. Without this,
124
+ * `(?:pre_)?tool_name` would be incorrectly rejected because the scanner
125
+ * would see the group-syntax `?` as a quantifier at depth 1.
126
+ *
127
+ * ## Heuristic, not a proof
128
+ *
129
+ * This catches the common forms but not all. Ambiguous-alternation ReDoS
130
+ * like `(a|a)+` is not detected. Pathologically long patterns are also
131
+ * caught by {@link MAX_PATTERN_LENGTH}. Hosts that accept user-supplied
132
+ * patterns must still validate upstream.
133
+ */
134
+ export function hasNestedQuantifier(pattern: string): boolean {
135
+ const stack: QuantifierFrame[] = [];
136
+ let i = 0;
137
+ while (i < pattern.length) {
138
+ const ch = pattern[i];
139
+ if (ch === '\\') {
140
+ i += 2;
141
+ continue;
142
+ }
143
+ if (ch === '[') {
144
+ i = findCharClassEnd(pattern, i) + 1;
145
+ continue;
146
+ }
147
+ if (ch === '(') {
148
+ stack.push({ hasBacktrackRisk: false });
149
+ i = skipGroupSyntaxPrefix(pattern, i + 1);
150
+ continue;
151
+ }
152
+ if (ch === ')') {
153
+ const frame = stack.pop();
154
+ if (frame === undefined) {
155
+ i++;
156
+ continue;
157
+ }
158
+ const next = pattern[i + 1];
159
+ const isQuantifier =
160
+ next === '*' || next === '+' || next === '?' || next === '{';
161
+ if (isQuantifier && frame.hasBacktrackRisk) {
162
+ return true;
163
+ }
164
+ if (stack.length > 0 && (frame.hasBacktrackRisk || isQuantifier)) {
165
+ stack[stack.length - 1].hasBacktrackRisk = true;
166
+ }
167
+ i++;
168
+ continue;
169
+ }
170
+ if (ch === '*' || ch === '+' || ch === '?' || ch === '{') {
171
+ if (stack.length > 0) {
172
+ stack[stack.length - 1].hasBacktrackRisk = true;
173
+ }
174
+ }
175
+ i++;
176
+ }
177
+ return false;
178
+ }
179
+
180
+ function findCharClassEnd(pattern: string, start: number): number {
181
+ let i = start + 1;
182
+ while (i < pattern.length) {
183
+ const ch = pattern[i];
184
+ if (ch === '\\') {
185
+ i += 2;
186
+ continue;
187
+ }
188
+ if (ch === ']') {
189
+ return i;
190
+ }
191
+ i++;
192
+ }
193
+ return pattern.length - 1;
194
+ }
195
+
196
+ function compile(pattern: string): RegExp | null {
197
+ const cached = patternCache.get(pattern);
198
+ if (cached !== undefined) {
199
+ touchCacheEntry(pattern, cached);
200
+ return cached.regex;
201
+ }
202
+ if (pattern.length > MAX_PATTERN_LENGTH) {
203
+ setCacheEntry(pattern, { regex: null });
204
+ return null;
205
+ }
206
+ if (hasNestedQuantifier(pattern)) {
207
+ setCacheEntry(pattern, { regex: null });
208
+ return null;
209
+ }
210
+ try {
211
+ const regex = new RegExp(pattern);
212
+ setCacheEntry(pattern, { regex });
213
+ return regex;
214
+ } catch {
215
+ setCacheEntry(pattern, { regex: null });
216
+ return null;
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Tests whether a hook matcher pattern matches the given query string.
222
+ *
223
+ * ## Semantics
224
+ *
225
+ * - `undefined` or empty `pattern` matches any query (wildcard). This is
226
+ * the intended shape for events that do not supply a query string at
227
+ * all (`RunStart`, `Stop`, etc.) — register such matchers without a
228
+ * pattern.
229
+ * - `undefined` or empty `query` with a non-empty `pattern` never matches.
230
+ * Setting a pattern on a query-less event is therefore inert: the
231
+ * matcher will simply never fire. This is intentional — it keeps
232
+ * query-based filtering out of event types where "query" has no meaning,
233
+ * and is documented on `HookMatcher.pattern`.
234
+ * - Otherwise, the pattern is compiled once (via a bounded LRU cache) and
235
+ * tested against the query.
236
+ * - Invalid regex patterns never throw — a failed compile is cached as
237
+ * "never matches" so a single malformed pattern cannot take out a whole
238
+ * `executeHooks` batch.
239
+ *
240
+ * ## ReDoS mitigations
241
+ *
242
+ * Patterns compile through three cheap gates before reaching `new RegExp`:
243
+ *
244
+ * 1. {@link MAX_PATTERN_LENGTH} length cap rejects oversized inputs.
245
+ * 2. {@link hasNestedQuantifier} rejects the most common catastrophic-
246
+ * backtracking shape (quantified group containing a quantifier).
247
+ * 3. Successful compiles are cached in a bounded LRU so repeated calls
248
+ * never re-enter the regex compiler.
249
+ *
250
+ * These are a floor, not a ceiling. Hosts that accept user-supplied
251
+ * patterns should still validate upstream. The design report §3.8 routes
252
+ * persistable hooks through a host-side compiler before they reach this
253
+ * module.
254
+ */
255
+ export function matchesQuery(
256
+ pattern: string | undefined,
257
+ query: string | undefined
258
+ ): boolean {
259
+ if (pattern === undefined || pattern === '') {
260
+ return true;
261
+ }
262
+ if (query === undefined || query === '') {
263
+ return false;
264
+ }
265
+ const regex = compile(pattern);
266
+ if (regex === null) {
267
+ return false;
268
+ }
269
+ return regex.test(query);
270
+ }
271
+
272
+ /** Clears the regex compilation cache. Intended for test isolation. */
273
+ export function clearMatcherCache(): void {
274
+ patternCache.clear();
275
+ }
276
+
277
+ /** Returns the current size of the compilation cache. Intended for tests. */
278
+ export function getMatcherCacheSize(): number {
279
+ return patternCache.size;
280
+ }