@librechat/agents 3.1.67 → 3.1.68-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.
- package/dist/cjs/agents/AgentContext.cjs +23 -3
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +16 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +91 -0
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +36 -0
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/hooks/HookRegistry.cjs +162 -0
- package/dist/cjs/hooks/HookRegistry.cjs.map +1 -0
- package/dist/cjs/hooks/executeHooks.cjs +276 -0
- package/dist/cjs/hooks/executeHooks.cjs.map +1 -0
- package/dist/cjs/hooks/matchers.cjs +256 -0
- package/dist/cjs/hooks/matchers.cjs.map +1 -0
- package/dist/cjs/hooks/types.cjs +27 -0
- package/dist/cjs/hooks/types.cjs.map +1 -0
- package/dist/cjs/main.cjs +54 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +74 -12
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/run.cjs +111 -0
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/summarization/index.cjs +41 -0
- package/dist/cjs/summarization/index.cjs.map +1 -1
- package/dist/cjs/summarization/node.cjs +165 -19
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +175 -0
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +296 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
- package/dist/cjs/tools/ReadFile.cjs +43 -0
- package/dist/cjs/tools/ReadFile.cjs.map +1 -0
- package/dist/cjs/tools/SkillTool.cjs +50 -0
- package/dist/cjs/tools/SkillTool.cjs.map +1 -0
- package/dist/cjs/tools/SubagentTool.cjs +92 -0
- package/dist/cjs/tools/SubagentTool.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +304 -140
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/skillCatalog.cjs +84 -0
- package/dist/cjs/tools/skillCatalog.cjs.map +1 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +511 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +23 -3
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +15 -1
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +91 -0
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +36 -0
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/hooks/HookRegistry.mjs +160 -0
- package/dist/esm/hooks/HookRegistry.mjs.map +1 -0
- package/dist/esm/hooks/executeHooks.mjs +273 -0
- package/dist/esm/hooks/executeHooks.mjs.map +1 -0
- package/dist/esm/hooks/matchers.mjs +251 -0
- package/dist/esm/hooks/matchers.mjs.map +1 -0
- package/dist/esm/hooks/types.mjs +25 -0
- package/dist/esm/hooks/types.mjs.map +1 -0
- package/dist/esm/main.mjs +13 -2
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +66 -4
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/run.mjs +111 -0
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/summarization/index.mjs +41 -1
- package/dist/esm/summarization/index.mjs.map +1 -1
- package/dist/esm/summarization/node.mjs +165 -19
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +169 -0
- package/dist/esm/tools/BashExecutor.mjs.map +1 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +287 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
- package/dist/esm/tools/ReadFile.mjs +38 -0
- package/dist/esm/tools/ReadFile.mjs.map +1 -0
- package/dist/esm/tools/SkillTool.mjs +45 -0
- package/dist/esm/tools/SkillTool.mjs.map +1 -0
- package/dist/esm/tools/SubagentTool.mjs +85 -0
- package/dist/esm/tools/SubagentTool.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +306 -142
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/skillCatalog.mjs +82 -0
- package/dist/esm/tools/skillCatalog.mjs.map +1 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +505 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -0
- package/dist/types/agents/AgentContext.d.ts +6 -0
- package/dist/types/common/enum.d.ts +10 -1
- package/dist/types/graphs/Graph.d.ts +2 -0
- package/dist/types/graphs/MultiAgentGraph.d.ts +12 -0
- package/dist/types/hooks/HookRegistry.d.ts +56 -0
- package/dist/types/hooks/executeHooks.d.ts +79 -0
- package/dist/types/hooks/index.d.ts +6 -0
- package/dist/types/hooks/matchers.d.ts +95 -0
- package/dist/types/hooks/types.d.ts +320 -0
- package/dist/types/index.d.ts +8 -0
- package/dist/types/messages/format.d.ts +2 -1
- package/dist/types/run.d.ts +1 -0
- package/dist/types/summarization/index.d.ts +2 -0
- package/dist/types/summarization/node.d.ts +2 -0
- package/dist/types/tools/BashExecutor.d.ts +45 -0
- package/dist/types/tools/BashProgrammaticToolCalling.d.ts +72 -0
- package/dist/types/tools/ReadFile.d.ts +28 -0
- package/dist/types/tools/SkillTool.d.ts +40 -0
- package/dist/types/tools/SubagentTool.d.ts +36 -0
- package/dist/types/tools/ToolNode.d.ts +24 -2
- package/dist/types/tools/skillCatalog.d.ts +19 -0
- package/dist/types/tools/subagent/SubagentExecutor.d.ts +137 -0
- package/dist/types/tools/subagent/index.d.ts +2 -0
- package/dist/types/types/graph.d.ts +61 -2
- package/dist/types/types/index.d.ts +1 -0
- package/dist/types/types/run.d.ts +20 -0
- package/dist/types/types/skill.d.ts +9 -0
- package/dist/types/types/tools.d.ts +38 -1
- package/package.json +5 -1
- package/src/agents/AgentContext.ts +26 -2
- package/src/common/enum.ts +15 -0
- package/src/graphs/Graph.ts +113 -0
- package/src/graphs/MultiAgentGraph.ts +39 -0
- package/src/graphs/__tests__/MultiAgentGraph.test.ts +91 -0
- package/src/hooks/HookRegistry.ts +208 -0
- package/src/hooks/__tests__/HookRegistry.test.ts +190 -0
- package/src/hooks/__tests__/compactHooks.test.ts +214 -0
- package/src/hooks/__tests__/executeHooks.test.ts +1013 -0
- package/src/hooks/__tests__/integration.test.ts +337 -0
- package/src/hooks/__tests__/matchers.test.ts +238 -0
- package/src/hooks/__tests__/toolHooks.test.ts +669 -0
- package/src/hooks/executeHooks.ts +375 -0
- package/src/hooks/index.ts +57 -0
- package/src/hooks/matchers.ts +280 -0
- package/src/hooks/types.ts +404 -0
- package/src/index.ts +10 -0
- package/src/messages/format.ts +74 -4
- package/src/messages/formatAgentMessages.skills.test.ts +334 -0
- package/src/run.ts +126 -0
- package/src/scripts/multi-agent-subagent.ts +246 -0
- package/src/scripts/subagent-event-driven-debug.ts +190 -0
- package/src/scripts/subagent-tools-debug.ts +160 -0
- package/src/specs/subagent.test.ts +305 -0
- package/src/summarization/__tests__/node.test.ts +42 -0
- package/src/summarization/__tests__/trigger.test.ts +100 -1
- package/src/summarization/index.ts +47 -0
- package/src/summarization/node.ts +202 -24
- package/src/tools/BashExecutor.ts +205 -0
- package/src/tools/BashProgrammaticToolCalling.ts +397 -0
- package/src/tools/ReadFile.ts +39 -0
- package/src/tools/SkillTool.ts +46 -0
- package/src/tools/SubagentTool.ts +100 -0
- package/src/tools/ToolNode.ts +391 -169
- package/src/tools/__tests__/ReadFile.test.ts +44 -0
- package/src/tools/__tests__/SkillTool.test.ts +442 -0
- package/src/tools/__tests__/SubagentExecutor.test.ts +1148 -0
- package/src/tools/__tests__/SubagentTool.test.ts +149 -0
- package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
- package/src/tools/__tests__/skillCatalog.test.ts +161 -0
- package/src/tools/__tests__/subagentHooks.test.ts +215 -0
- package/src/tools/skillCatalog.ts +126 -0
- package/src/tools/subagent/SubagentExecutor.ts +676 -0
- package/src/tools/subagent/index.ts +13 -0
- package/src/types/graph.ts +80 -1
- package/src/types/index.ts +1 -0
- package/src/types/run.ts +20 -0
- package/src/types/skill.ts +11 -0
- package/src/types/tools.ts +41 -1
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var matchers = require('./matchers.cjs');
|
|
4
|
+
|
|
5
|
+
/** Default per-hook timeout when a matcher doesn't set its own. */
|
|
6
|
+
const DEFAULT_HOOK_TIMEOUT_MS = 30_000;
|
|
7
|
+
function freshResult() {
|
|
8
|
+
return {
|
|
9
|
+
additionalContexts: [],
|
|
10
|
+
errors: [],
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
function combineSignals(parent, timeoutMs) {
|
|
14
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
15
|
+
if (parent === undefined) {
|
|
16
|
+
return timeoutSignal;
|
|
17
|
+
}
|
|
18
|
+
return AbortSignal.any([parent, timeoutSignal]);
|
|
19
|
+
}
|
|
20
|
+
function isTimeout(err) {
|
|
21
|
+
if (err instanceof Error) {
|
|
22
|
+
return err.name === 'TimeoutError' || err.name === 'AbortError';
|
|
23
|
+
}
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
function describeError(err) {
|
|
27
|
+
if (err instanceof Error) {
|
|
28
|
+
return err.message !== '' ? err.message : err.name;
|
|
29
|
+
}
|
|
30
|
+
return String(err);
|
|
31
|
+
}
|
|
32
|
+
function makeAbortPromise(signal) {
|
|
33
|
+
let onAbort;
|
|
34
|
+
const promise = new Promise((_resolve, reject) => {
|
|
35
|
+
if (signal.aborted) {
|
|
36
|
+
reject(signal.reason instanceof Error ? signal.reason : new Error('aborted'));
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
onAbort = () => {
|
|
40
|
+
reject(signal.reason instanceof Error ? signal.reason : new Error('aborted'));
|
|
41
|
+
};
|
|
42
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
43
|
+
});
|
|
44
|
+
const cleanup = () => {
|
|
45
|
+
if (onAbort !== undefined) {
|
|
46
|
+
signal.removeEventListener('abort', onAbort);
|
|
47
|
+
onAbort = undefined;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
return { promise, cleanup };
|
|
51
|
+
}
|
|
52
|
+
async function runHook(hook, input, signal, matcher) {
|
|
53
|
+
const hookPromise = Promise.resolve().then(() => hook(input, signal));
|
|
54
|
+
const { promise: abortPromise, cleanup } = makeAbortPromise(signal);
|
|
55
|
+
try {
|
|
56
|
+
const output = await Promise.race([hookPromise, abortPromise]);
|
|
57
|
+
return { matcher, output, error: null, timedOut: false };
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
return {
|
|
61
|
+
matcher,
|
|
62
|
+
output: null,
|
|
63
|
+
error: describeError(err),
|
|
64
|
+
timedOut: isTimeout(err),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
cleanup();
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function reportErrors(outcomes, event, logger) {
|
|
72
|
+
for (const outcome of outcomes) {
|
|
73
|
+
if (outcome.error === null) {
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (outcome.matcher.internal === true) {
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
const label = outcome.timedOut ? 'timed out' : 'threw an error';
|
|
80
|
+
const message = `Hook for ${event} ${label}: ${outcome.error}`;
|
|
81
|
+
if (logger !== undefined) {
|
|
82
|
+
logger.warn(message);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
// eslint-disable-next-line no-console
|
|
86
|
+
console.warn(message);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function applyToolDecision(agg, decision, reason) {
|
|
90
|
+
if (decision === 'deny') {
|
|
91
|
+
if (agg.decision === 'deny') {
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
agg.decision = 'deny';
|
|
95
|
+
agg.reason = reason;
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (decision === 'ask') {
|
|
99
|
+
if (agg.decision === 'deny' || agg.decision === 'ask') {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
agg.decision = 'ask';
|
|
103
|
+
agg.reason = reason;
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (agg.decision === undefined) {
|
|
107
|
+
agg.decision = 'allow';
|
|
108
|
+
agg.reason = reason;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
function applyStopDecision(agg, decision, reason) {
|
|
112
|
+
if (decision === 'block') {
|
|
113
|
+
if (agg.stopDecision === 'block') {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
agg.stopDecision = 'block';
|
|
117
|
+
agg.reason = reason;
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (agg.stopDecision === undefined) {
|
|
121
|
+
agg.stopDecision = 'continue';
|
|
122
|
+
if (agg.reason === undefined) {
|
|
123
|
+
agg.reason = reason;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function applyDecision(agg, output) {
|
|
128
|
+
if (!('decision' in output) || output.decision === undefined) {
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
const decision = output.decision;
|
|
132
|
+
const reason = 'reason' in output && typeof output.reason === 'string'
|
|
133
|
+
? output.reason
|
|
134
|
+
: undefined;
|
|
135
|
+
if (decision === 'deny' || decision === 'ask' || decision === 'allow') {
|
|
136
|
+
applyToolDecision(agg, decision, reason);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
applyStopDecision(agg, decision, reason);
|
|
140
|
+
}
|
|
141
|
+
function applyContext(agg, output) {
|
|
142
|
+
if (typeof output.additionalContext === 'string' &&
|
|
143
|
+
output.additionalContext.length > 0) {
|
|
144
|
+
agg.additionalContexts.push(output.additionalContext);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function applyStopFlag(agg, output) {
|
|
148
|
+
if (output.preventContinuation !== true) {
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
agg.preventContinuation = true;
|
|
152
|
+
if (typeof output.stopReason === 'string' && agg.stopReason === undefined) {
|
|
153
|
+
agg.stopReason = output.stopReason;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
function applyUpdatedInput(agg, output) {
|
|
157
|
+
if (!('updatedInput' in output) || output.updatedInput === undefined) {
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
agg.updatedInput = output.updatedInput;
|
|
161
|
+
}
|
|
162
|
+
function applyUpdatedOutput(agg, output) {
|
|
163
|
+
if (!('updatedOutput' in output) || output.updatedOutput === undefined) {
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
agg.updatedOutput = output.updatedOutput;
|
|
167
|
+
}
|
|
168
|
+
function fold(outcomes) {
|
|
169
|
+
const agg = freshResult();
|
|
170
|
+
for (const outcome of outcomes) {
|
|
171
|
+
if (outcome.error !== null) {
|
|
172
|
+
if (outcome.matcher.internal !== true) {
|
|
173
|
+
agg.errors.push(outcome.error);
|
|
174
|
+
}
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
const output = outcome.output;
|
|
178
|
+
if (output === null) {
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
applyContext(agg, output);
|
|
182
|
+
applyStopFlag(agg, output);
|
|
183
|
+
applyDecision(agg, output);
|
|
184
|
+
applyUpdatedInput(agg, output);
|
|
185
|
+
applyUpdatedOutput(agg, output);
|
|
186
|
+
}
|
|
187
|
+
return agg;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Fires every matcher registered against `input.hook_event_name`, folding
|
|
191
|
+
* their results per `deny > ask > allow` precedence and accumulating
|
|
192
|
+
* context/errors.
|
|
193
|
+
*
|
|
194
|
+
* ## Parallelism and determinism
|
|
195
|
+
*
|
|
196
|
+
* All matching hooks fire simultaneously and are awaited via `Promise.all`,
|
|
197
|
+
* which preserves input-array order in its returned results. The fold
|
|
198
|
+
* therefore iterates outcomes in **registration order** — outer loop over
|
|
199
|
+
* matchers as they sit in the registry (global first, then session), inner
|
|
200
|
+
* loop over each matcher's `hooks` array. Last-writer-wins fields
|
|
201
|
+
* (`updatedInput`, `updatedOutput`) are deterministic in that order, even
|
|
202
|
+
* though hooks may complete in arbitrary wall-clock order.
|
|
203
|
+
*
|
|
204
|
+
* Consumers that need a single authoritative rewrite should still scope
|
|
205
|
+
* `updatedInput`/`updatedOutput` to one hook per matcher to avoid subtle
|
|
206
|
+
* precedence bugs when matchers are added in a different order than
|
|
207
|
+
* expected.
|
|
208
|
+
*
|
|
209
|
+
* ## Timeouts and cancellation
|
|
210
|
+
*
|
|
211
|
+
* Each matcher receives **one shared `AbortSignal`** derived from the
|
|
212
|
+
* caller's parent signal combined with `matcher.timeout` (falling back to
|
|
213
|
+
* `opts.timeoutMs`, default {@link DEFAULT_HOOK_TIMEOUT_MS}). Sharing the
|
|
214
|
+
* signal across hooks in a matcher collapses N timer allocations into
|
|
215
|
+
* one, which matters on the PreToolUse hot path where a matcher with
|
|
216
|
+
* several hooks fires on every tool call. Each hook call is raced
|
|
217
|
+
* against the shared signal, so even a hook that ignores the signal is
|
|
218
|
+
* force-unblocked when the timeout fires. Timeout/abort errors are
|
|
219
|
+
* swallowed into the aggregated result's `errors` array (non-fatal by
|
|
220
|
+
* default).
|
|
221
|
+
*
|
|
222
|
+
* ## Internal matchers
|
|
223
|
+
*
|
|
224
|
+
* A matcher with `internal: true` is excluded from both the `errors` array
|
|
225
|
+
* and the logger output. Use it for infrastructure hooks whose failures
|
|
226
|
+
* should not pollute user-visible diagnostics.
|
|
227
|
+
*
|
|
228
|
+
* ## Once semantics — atomic at-most-once
|
|
229
|
+
*
|
|
230
|
+
* A matcher with `once: true` is removed from the registry **before any
|
|
231
|
+
* hook runs**, inside the synchronous prefix of `executeHooks` (between
|
|
232
|
+
* `getMatchers` and the first `await`). Because Node's event loop serialises
|
|
233
|
+
* sync work, two concurrent `executeHooks` calls can never both observe
|
|
234
|
+
* and dispatch the same `once` matcher — whichever call runs its sync
|
|
235
|
+
* prefix first consumes it, and the loser sees an empty bucket.
|
|
236
|
+
*
|
|
237
|
+
* Trade-off: if every hook in a `once` matcher throws, the matcher is
|
|
238
|
+
* still gone. "Once" here means "at most one dispatch, ever", not "at
|
|
239
|
+
* most one successful execution with retry on failure". Hosts that need
|
|
240
|
+
* retry semantics should register a normal matcher and self-unregister
|
|
241
|
+
* via the `unregister` callback returned from `registry.register`.
|
|
242
|
+
*/
|
|
243
|
+
async function executeHooks(opts) {
|
|
244
|
+
const { registry, input, sessionId, matchQuery, signal, timeoutMs = DEFAULT_HOOK_TIMEOUT_MS, logger, } = opts;
|
|
245
|
+
const event = input.hook_event_name;
|
|
246
|
+
const matchers$1 = registry.getMatchers(event, sessionId);
|
|
247
|
+
if (matchers$1.length === 0) {
|
|
248
|
+
return freshResult();
|
|
249
|
+
}
|
|
250
|
+
// --- SYNC CRITICAL SECTION: once-matcher removal must complete before any await ---
|
|
251
|
+
const tasks = [];
|
|
252
|
+
for (const matcher of matchers$1) {
|
|
253
|
+
if (!matchers.matchesQuery(matcher.pattern, matchQuery)) {
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
if (matcher.once === true) {
|
|
257
|
+
registry.removeMatcher(event, matcher, sessionId);
|
|
258
|
+
}
|
|
259
|
+
const perHookTimeout = matcher.timeout ?? timeoutMs;
|
|
260
|
+
const matcherSignal = combineSignals(signal, perHookTimeout);
|
|
261
|
+
for (const hook of matcher.hooks) {
|
|
262
|
+
tasks.push(runHook(hook, input, matcherSignal, matcher));
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
// --- END SYNC CRITICAL SECTION ---
|
|
266
|
+
if (tasks.length === 0) {
|
|
267
|
+
return freshResult();
|
|
268
|
+
}
|
|
269
|
+
const outcomes = await Promise.all(tasks);
|
|
270
|
+
reportErrors(outcomes, event, logger);
|
|
271
|
+
return fold(outcomes);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
exports.DEFAULT_HOOK_TIMEOUT_MS = DEFAULT_HOOK_TIMEOUT_MS;
|
|
275
|
+
exports.executeHooks = executeHooks;
|
|
276
|
+
//# sourceMappingURL=executeHooks.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"executeHooks.cjs","sources":["../../../src/hooks/executeHooks.ts"],"sourcesContent":["// src/hooks/executeHooks.ts\nimport type { Logger } from 'winston';\nimport type { HookRegistry } from './HookRegistry';\nimport type {\n HookInput,\n HookEvent,\n HookOutput,\n HookMatcher,\n ToolDecision,\n StopDecision,\n HookCallback,\n AggregatedHookResult,\n} from './types';\nimport { matchesQuery } from './matchers';\n\n/** Default per-hook timeout when a matcher doesn't set its own. */\nexport const DEFAULT_HOOK_TIMEOUT_MS = 30_000;\n\n/**\n * Options for a single `executeHooks` call. The `input` drives everything —\n * the event name is read from `input.hook_event_name`, matchers are looked\n * up against that event, and each hook receives `input` directly.\n */\nexport interface ExecuteHooksOptions {\n registry: HookRegistry;\n input: HookInput;\n /** Scope lookup to this session (in addition to global matchers). */\n sessionId?: string;\n /** Query string matched against each matcher's pattern (tool name, etc.). */\n matchQuery?: string;\n /** Parent AbortSignal — combined with per-hook timeout into the hook signal. */\n signal?: AbortSignal;\n /** Default per-hook timeout; overridden by `matcher.timeout` when present. */\n timeoutMs?: number;\n /** Optional winston logger for non-internal hook errors. */\n logger?: Logger;\n}\n\ntype WideMatcher = HookMatcher<HookEvent>;\ntype WideCallback = HookCallback<HookEvent>;\n\ninterface HookOutcome {\n matcher: WideMatcher;\n output: HookOutput | null;\n error: string | null;\n timedOut: boolean;\n}\n\nfunction freshResult(): AggregatedHookResult {\n return {\n additionalContexts: [],\n errors: [],\n };\n}\n\nfunction combineSignals(\n parent: AbortSignal | undefined,\n timeoutMs: number\n): AbortSignal {\n const timeoutSignal = AbortSignal.timeout(timeoutMs);\n if (parent === undefined) {\n return timeoutSignal;\n }\n return AbortSignal.any([parent, timeoutSignal]);\n}\n\nfunction isTimeout(err: unknown): boolean {\n if (err instanceof Error) {\n return err.name === 'TimeoutError' || err.name === 'AbortError';\n }\n return false;\n}\n\nfunction describeError(err: unknown): string {\n if (err instanceof Error) {\n return err.message !== '' ? err.message : err.name;\n }\n return String(err);\n}\n\nfunction makeAbortPromise(signal: AbortSignal): {\n promise: Promise<never>;\n cleanup: () => void;\n} {\n let onAbort: (() => void) | undefined;\n const promise = new Promise<never>((_resolve, reject) => {\n if (signal.aborted) {\n reject(\n signal.reason instanceof Error ? signal.reason : new Error('aborted')\n );\n return;\n }\n onAbort = (): void => {\n reject(\n signal.reason instanceof Error ? signal.reason : new Error('aborted')\n );\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n const cleanup = (): void => {\n if (onAbort !== undefined) {\n signal.removeEventListener('abort', onAbort);\n onAbort = undefined;\n }\n };\n return { promise, cleanup };\n}\n\nasync function runHook(\n hook: WideCallback,\n input: HookInput,\n signal: AbortSignal,\n matcher: WideMatcher\n): Promise<HookOutcome> {\n const hookPromise = Promise.resolve().then(() => hook(input, signal));\n const { promise: abortPromise, cleanup } = makeAbortPromise(signal);\n try {\n const output = await Promise.race([hookPromise, abortPromise]);\n return { matcher, output, error: null, timedOut: false };\n } catch (err) {\n return {\n matcher,\n output: null,\n error: describeError(err),\n timedOut: isTimeout(err),\n };\n } finally {\n cleanup();\n }\n}\n\nfunction reportErrors(\n outcomes: readonly HookOutcome[],\n event: HookEvent,\n logger: Logger | undefined\n): void {\n for (const outcome of outcomes) {\n if (outcome.error === null) {\n continue;\n }\n if (outcome.matcher.internal === true) {\n continue;\n }\n const label = outcome.timedOut ? 'timed out' : 'threw an error';\n const message = `Hook for ${event} ${label}: ${outcome.error}`;\n if (logger !== undefined) {\n logger.warn(message);\n continue;\n }\n // eslint-disable-next-line no-console\n console.warn(message);\n }\n}\n\nfunction applyToolDecision(\n agg: AggregatedHookResult,\n decision: ToolDecision,\n reason: string | undefined\n): void {\n if (decision === 'deny') {\n if (agg.decision === 'deny') {\n return;\n }\n agg.decision = 'deny';\n agg.reason = reason;\n return;\n }\n if (decision === 'ask') {\n if (agg.decision === 'deny' || agg.decision === 'ask') {\n return;\n }\n agg.decision = 'ask';\n agg.reason = reason;\n return;\n }\n if (agg.decision === undefined) {\n agg.decision = 'allow';\n agg.reason = reason;\n }\n}\n\nfunction applyStopDecision(\n agg: AggregatedHookResult,\n decision: StopDecision,\n reason: string | undefined\n): void {\n if (decision === 'block') {\n if (agg.stopDecision === 'block') {\n return;\n }\n agg.stopDecision = 'block';\n agg.reason = reason;\n return;\n }\n if (agg.stopDecision === undefined) {\n agg.stopDecision = 'continue';\n if (agg.reason === undefined) {\n agg.reason = reason;\n }\n }\n}\n\nfunction applyDecision(agg: AggregatedHookResult, output: HookOutput): void {\n if (!('decision' in output) || output.decision === undefined) {\n return;\n }\n const decision = output.decision;\n const reason =\n 'reason' in output && typeof output.reason === 'string'\n ? output.reason\n : undefined;\n if (decision === 'deny' || decision === 'ask' || decision === 'allow') {\n applyToolDecision(agg, decision, reason);\n return;\n }\n applyStopDecision(agg, decision, reason);\n}\n\nfunction applyContext(agg: AggregatedHookResult, output: HookOutput): void {\n if (\n typeof output.additionalContext === 'string' &&\n output.additionalContext.length > 0\n ) {\n agg.additionalContexts.push(output.additionalContext);\n }\n}\n\nfunction applyStopFlag(agg: AggregatedHookResult, output: HookOutput): void {\n if (output.preventContinuation !== true) {\n return;\n }\n agg.preventContinuation = true;\n if (typeof output.stopReason === 'string' && agg.stopReason === undefined) {\n agg.stopReason = output.stopReason;\n }\n}\n\nfunction applyUpdatedInput(\n agg: AggregatedHookResult,\n output: HookOutput\n): void {\n if (!('updatedInput' in output) || output.updatedInput === undefined) {\n return;\n }\n agg.updatedInput = output.updatedInput;\n}\n\nfunction applyUpdatedOutput(\n agg: AggregatedHookResult,\n output: HookOutput\n): void {\n if (!('updatedOutput' in output) || output.updatedOutput === undefined) {\n return;\n }\n agg.updatedOutput = output.updatedOutput;\n}\n\nfunction fold(outcomes: readonly HookOutcome[]): AggregatedHookResult {\n const agg = freshResult();\n for (const outcome of outcomes) {\n if (outcome.error !== null) {\n if (outcome.matcher.internal !== true) {\n agg.errors.push(outcome.error);\n }\n continue;\n }\n const output = outcome.output;\n if (output === null) {\n continue;\n }\n applyContext(agg, output);\n applyStopFlag(agg, output);\n applyDecision(agg, output);\n applyUpdatedInput(agg, output);\n applyUpdatedOutput(agg, output);\n }\n return agg;\n}\n\n/**\n * Fires every matcher registered against `input.hook_event_name`, folding\n * their results per `deny > ask > allow` precedence and accumulating\n * context/errors.\n *\n * ## Parallelism and determinism\n *\n * All matching hooks fire simultaneously and are awaited via `Promise.all`,\n * which preserves input-array order in its returned results. The fold\n * therefore iterates outcomes in **registration order** — outer loop over\n * matchers as they sit in the registry (global first, then session), inner\n * loop over each matcher's `hooks` array. Last-writer-wins fields\n * (`updatedInput`, `updatedOutput`) are deterministic in that order, even\n * though hooks may complete in arbitrary wall-clock order.\n *\n * Consumers that need a single authoritative rewrite should still scope\n * `updatedInput`/`updatedOutput` to one hook per matcher to avoid subtle\n * precedence bugs when matchers are added in a different order than\n * expected.\n *\n * ## Timeouts and cancellation\n *\n * Each matcher receives **one shared `AbortSignal`** derived from the\n * caller's parent signal combined with `matcher.timeout` (falling back to\n * `opts.timeoutMs`, default {@link DEFAULT_HOOK_TIMEOUT_MS}). Sharing the\n * signal across hooks in a matcher collapses N timer allocations into\n * one, which matters on the PreToolUse hot path where a matcher with\n * several hooks fires on every tool call. Each hook call is raced\n * against the shared signal, so even a hook that ignores the signal is\n * force-unblocked when the timeout fires. Timeout/abort errors are\n * swallowed into the aggregated result's `errors` array (non-fatal by\n * default).\n *\n * ## Internal matchers\n *\n * A matcher with `internal: true` is excluded from both the `errors` array\n * and the logger output. Use it for infrastructure hooks whose failures\n * should not pollute user-visible diagnostics.\n *\n * ## Once semantics — atomic at-most-once\n *\n * A matcher with `once: true` is removed from the registry **before any\n * hook runs**, inside the synchronous prefix of `executeHooks` (between\n * `getMatchers` and the first `await`). Because Node's event loop serialises\n * sync work, two concurrent `executeHooks` calls can never both observe\n * and dispatch the same `once` matcher — whichever call runs its sync\n * prefix first consumes it, and the loser sees an empty bucket.\n *\n * Trade-off: if every hook in a `once` matcher throws, the matcher is\n * still gone. \"Once\" here means \"at most one dispatch, ever\", not \"at\n * most one successful execution with retry on failure\". Hosts that need\n * retry semantics should register a normal matcher and self-unregister\n * via the `unregister` callback returned from `registry.register`.\n */\nexport async function executeHooks(\n opts: ExecuteHooksOptions\n): Promise<AggregatedHookResult> {\n const {\n registry,\n input,\n sessionId,\n matchQuery,\n signal,\n timeoutMs = DEFAULT_HOOK_TIMEOUT_MS,\n logger,\n } = opts;\n const event = input.hook_event_name;\n const matchers = registry.getMatchers(event, sessionId);\n if (matchers.length === 0) {\n return freshResult();\n }\n\n // --- SYNC CRITICAL SECTION: once-matcher removal must complete before any await ---\n const tasks: Promise<HookOutcome>[] = [];\n for (const matcher of matchers) {\n if (!matchesQuery(matcher.pattern, matchQuery)) {\n continue;\n }\n if (matcher.once === true) {\n registry.removeMatcher(event, matcher, sessionId);\n }\n const perHookTimeout = matcher.timeout ?? timeoutMs;\n const matcherSignal = combineSignals(signal, perHookTimeout);\n for (const hook of matcher.hooks) {\n tasks.push(runHook(hook, input, matcherSignal, matcher));\n }\n }\n // --- END SYNC CRITICAL SECTION ---\n if (tasks.length === 0) {\n return freshResult();\n }\n\n const outcomes = await Promise.all(tasks);\n reportErrors(outcomes, event, logger);\n return fold(outcomes);\n}\n"],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AAO,CAAC,IAAI,EAAE,KAAK,EAAE,aAAa,EAAE,OAAO,CAAC,CAAC;QAC1D;IACF;;AAEA,IAAA,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;QACtB,OAAO,WAAW,EAAE;IACtB;IAEA,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC;AACzC,IAAA,YAAY,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,CAAC;AACrC,IAAA,OAAO,IAAI,CAAC,QAAQ,CAAC;AACvB;;;;;"}
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/hooks/matchers.ts
|
|
4
|
+
/**
|
|
5
|
+
* Upper bound on hook-matcher pattern length. Patterns longer than this
|
|
6
|
+
* are rejected outright — the goal is a cheap cap on pathological inputs
|
|
7
|
+
* (repeated quantifiers, huge alternation groups) without pulling in a
|
|
8
|
+
* safe-regex dependency.
|
|
9
|
+
*
|
|
10
|
+
* Legitimate matchers are almost always under 50 characters (tool names,
|
|
11
|
+
* short alternations, simple prefix anchors); 512 leaves generous
|
|
12
|
+
* headroom while preventing 10KB regexes.
|
|
13
|
+
*/
|
|
14
|
+
const MAX_PATTERN_LENGTH = 512;
|
|
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
|
+
const MAX_CACHE_SIZE = 256;
|
|
26
|
+
/**
|
|
27
|
+
* Module-level LRU cache keyed by pattern string. Map iteration order is
|
|
28
|
+
* insertion order in ECMAScript, so refreshing an entry's position means
|
|
29
|
+
* "delete then re-set". On overflow we evict the first key (least
|
|
30
|
+
* recently used).
|
|
31
|
+
*
|
|
32
|
+
* Failed compiles are cached as `{ regex: null }` so a malformed pattern
|
|
33
|
+
* does not re-enter the compiler — and so a tenant spamming bad patterns
|
|
34
|
+
* doesn't burn CPU on every call.
|
|
35
|
+
*/
|
|
36
|
+
const patternCache = new Map();
|
|
37
|
+
/**
|
|
38
|
+
* Threshold above which `touchCacheEntry` actually performs the LRU
|
|
39
|
+
* refresh. Below this watermark the cache has zero eviction pressure, so
|
|
40
|
+
* the delete+set on every hit would be pure overhead. Above it we refresh
|
|
41
|
+
* properly so hot patterns survive evictions. 75% of capacity is the
|
|
42
|
+
* standard sweet spot.
|
|
43
|
+
*/
|
|
44
|
+
const LRU_REFRESH_THRESHOLD = Math.floor((MAX_CACHE_SIZE * 3) / 4);
|
|
45
|
+
function touchCacheEntry(pattern, entry) {
|
|
46
|
+
if (patternCache.size < LRU_REFRESH_THRESHOLD) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
patternCache.delete(pattern);
|
|
50
|
+
patternCache.set(pattern, entry);
|
|
51
|
+
}
|
|
52
|
+
function setCacheEntry(pattern, entry) {
|
|
53
|
+
if (patternCache.size >= MAX_CACHE_SIZE) {
|
|
54
|
+
const oldestKey = patternCache.keys().next().value;
|
|
55
|
+
if (oldestKey !== undefined) {
|
|
56
|
+
patternCache.delete(oldestKey);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
patternCache.set(pattern, entry);
|
|
60
|
+
}
|
|
61
|
+
function skipGroupSyntaxPrefix(pattern, start) {
|
|
62
|
+
if (start >= pattern.length || pattern[start] !== '?') {
|
|
63
|
+
return start;
|
|
64
|
+
}
|
|
65
|
+
let i = start + 1;
|
|
66
|
+
if (i >= pattern.length) {
|
|
67
|
+
return i;
|
|
68
|
+
}
|
|
69
|
+
const modifier = pattern[i];
|
|
70
|
+
if (modifier === ':' || modifier === '=' || modifier === '!') {
|
|
71
|
+
return i + 1;
|
|
72
|
+
}
|
|
73
|
+
if (modifier !== '<') {
|
|
74
|
+
return i;
|
|
75
|
+
}
|
|
76
|
+
i++;
|
|
77
|
+
if (i < pattern.length && (pattern[i] === '=' || pattern[i] === '!')) {
|
|
78
|
+
return i + 1;
|
|
79
|
+
}
|
|
80
|
+
while (i < pattern.length && pattern[i] !== '>') {
|
|
81
|
+
i++;
|
|
82
|
+
}
|
|
83
|
+
if (i < pattern.length) {
|
|
84
|
+
i++;
|
|
85
|
+
}
|
|
86
|
+
return i;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Cheap syntactic detector for the most common catastrophic-backtracking
|
|
90
|
+
* shape: a quantified group that contains another quantifier (e.g.
|
|
91
|
+
* `(a+)+`, `(.*)*`, `(\w+)+$`, `(?:(a+))+`). This is the "nested
|
|
92
|
+
* quantifier" class of ReDoS — runs in polynomial-or-worse time on
|
|
93
|
+
* adversarial inputs.
|
|
94
|
+
*
|
|
95
|
+
* The scan walks the pattern linearly using an explicit stack of group
|
|
96
|
+
* frames. For each group it tracks whether the group's contents include
|
|
97
|
+
* "backtrack risk" — meaning a direct quantifier OR a nested group that
|
|
98
|
+
* carries risk up. When a group closes with a trailing quantifier AND its
|
|
99
|
+
* frame carries backtrack risk, the pattern is flagged. Risk propagates
|
|
100
|
+
* to the enclosing frame when a child group closes (whether the child
|
|
101
|
+
* itself was quantified or not), so `(?:(a+))+` — equivalent to `(a+)+`
|
|
102
|
+
* — is flagged correctly even though the outer non-capturing wrapper is
|
|
103
|
+
* one level removed from the inner quantifier.
|
|
104
|
+
*
|
|
105
|
+
* ## Group-syntax prefixes
|
|
106
|
+
*
|
|
107
|
+
* Non-capturing groups (`(?:`), lookaheads (`(?=`, `(?!`), lookbehinds
|
|
108
|
+
* (`(?<=`, `(?<!`), and named groups (`(?<name>`) are skipped over at
|
|
109
|
+
* the `(` so their `?` is not misread as a quantifier. Without this,
|
|
110
|
+
* `(?:pre_)?tool_name` would be incorrectly rejected because the scanner
|
|
111
|
+
* would see the group-syntax `?` as a quantifier at depth 1.
|
|
112
|
+
*
|
|
113
|
+
* ## Heuristic, not a proof
|
|
114
|
+
*
|
|
115
|
+
* This catches the common forms but not all. Ambiguous-alternation ReDoS
|
|
116
|
+
* like `(a|a)+` is not detected. Pathologically long patterns are also
|
|
117
|
+
* caught by {@link MAX_PATTERN_LENGTH}. Hosts that accept user-supplied
|
|
118
|
+
* patterns must still validate upstream.
|
|
119
|
+
*/
|
|
120
|
+
function hasNestedQuantifier(pattern) {
|
|
121
|
+
const stack = [];
|
|
122
|
+
let i = 0;
|
|
123
|
+
while (i < pattern.length) {
|
|
124
|
+
const ch = pattern[i];
|
|
125
|
+
if (ch === '\\') {
|
|
126
|
+
i += 2;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (ch === '[') {
|
|
130
|
+
i = findCharClassEnd(pattern, i) + 1;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (ch === '(') {
|
|
134
|
+
stack.push({ hasBacktrackRisk: false });
|
|
135
|
+
i = skipGroupSyntaxPrefix(pattern, i + 1);
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if (ch === ')') {
|
|
139
|
+
const frame = stack.pop();
|
|
140
|
+
if (frame === undefined) {
|
|
141
|
+
i++;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
const next = pattern[i + 1];
|
|
145
|
+
const isQuantifier = next === '*' || next === '+' || next === '?' || next === '{';
|
|
146
|
+
if (isQuantifier && frame.hasBacktrackRisk) {
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
if (stack.length > 0 && (frame.hasBacktrackRisk || isQuantifier)) {
|
|
150
|
+
stack[stack.length - 1].hasBacktrackRisk = true;
|
|
151
|
+
}
|
|
152
|
+
i++;
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (ch === '*' || ch === '+' || ch === '?' || ch === '{') {
|
|
156
|
+
if (stack.length > 0) {
|
|
157
|
+
stack[stack.length - 1].hasBacktrackRisk = true;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
i++;
|
|
161
|
+
}
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
function findCharClassEnd(pattern, start) {
|
|
165
|
+
let i = start + 1;
|
|
166
|
+
while (i < pattern.length) {
|
|
167
|
+
const ch = pattern[i];
|
|
168
|
+
if (ch === '\\') {
|
|
169
|
+
i += 2;
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (ch === ']') {
|
|
173
|
+
return i;
|
|
174
|
+
}
|
|
175
|
+
i++;
|
|
176
|
+
}
|
|
177
|
+
return pattern.length - 1;
|
|
178
|
+
}
|
|
179
|
+
function compile(pattern) {
|
|
180
|
+
const cached = patternCache.get(pattern);
|
|
181
|
+
if (cached !== undefined) {
|
|
182
|
+
touchCacheEntry(pattern, cached);
|
|
183
|
+
return cached.regex;
|
|
184
|
+
}
|
|
185
|
+
if (pattern.length > MAX_PATTERN_LENGTH) {
|
|
186
|
+
setCacheEntry(pattern, { regex: null });
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
if (hasNestedQuantifier(pattern)) {
|
|
190
|
+
setCacheEntry(pattern, { regex: null });
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
try {
|
|
194
|
+
const regex = new RegExp(pattern);
|
|
195
|
+
setCacheEntry(pattern, { regex });
|
|
196
|
+
return regex;
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
setCacheEntry(pattern, { regex: null });
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Tests whether a hook matcher pattern matches the given query string.
|
|
205
|
+
*
|
|
206
|
+
* ## Semantics
|
|
207
|
+
*
|
|
208
|
+
* - `undefined` or empty `pattern` matches any query (wildcard). This is
|
|
209
|
+
* the intended shape for events that do not supply a query string at
|
|
210
|
+
* all (`RunStart`, `Stop`, etc.) — register such matchers without a
|
|
211
|
+
* pattern.
|
|
212
|
+
* - `undefined` or empty `query` with a non-empty `pattern` never matches.
|
|
213
|
+
* Setting a pattern on a query-less event is therefore inert: the
|
|
214
|
+
* matcher will simply never fire. This is intentional — it keeps
|
|
215
|
+
* query-based filtering out of event types where "query" has no meaning,
|
|
216
|
+
* and is documented on `HookMatcher.pattern`.
|
|
217
|
+
* - Otherwise, the pattern is compiled once (via a bounded LRU cache) and
|
|
218
|
+
* tested against the query.
|
|
219
|
+
* - Invalid regex patterns never throw — a failed compile is cached as
|
|
220
|
+
* "never matches" so a single malformed pattern cannot take out a whole
|
|
221
|
+
* `executeHooks` batch.
|
|
222
|
+
*
|
|
223
|
+
* ## ReDoS mitigations
|
|
224
|
+
*
|
|
225
|
+
* Patterns compile through three cheap gates before reaching `new RegExp`:
|
|
226
|
+
*
|
|
227
|
+
* 1. {@link MAX_PATTERN_LENGTH} length cap rejects oversized inputs.
|
|
228
|
+
* 2. {@link hasNestedQuantifier} rejects the most common catastrophic-
|
|
229
|
+
* backtracking shape (quantified group containing a quantifier).
|
|
230
|
+
* 3. Successful compiles are cached in a bounded LRU so repeated calls
|
|
231
|
+
* never re-enter the regex compiler.
|
|
232
|
+
*
|
|
233
|
+
* These are a floor, not a ceiling. Hosts that accept user-supplied
|
|
234
|
+
* patterns should still validate upstream. The design report §3.8 routes
|
|
235
|
+
* persistable hooks through a host-side compiler before they reach this
|
|
236
|
+
* module.
|
|
237
|
+
*/
|
|
238
|
+
function matchesQuery(pattern, query) {
|
|
239
|
+
if (pattern === undefined || pattern === '') {
|
|
240
|
+
return true;
|
|
241
|
+
}
|
|
242
|
+
if (query === undefined || query === '') {
|
|
243
|
+
return false;
|
|
244
|
+
}
|
|
245
|
+
const regex = compile(pattern);
|
|
246
|
+
if (regex === null) {
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
249
|
+
return regex.test(query);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
exports.MAX_CACHE_SIZE = MAX_CACHE_SIZE;
|
|
253
|
+
exports.MAX_PATTERN_LENGTH = MAX_PATTERN_LENGTH;
|
|
254
|
+
exports.hasNestedQuantifier = hasNestedQuantifier;
|
|
255
|
+
exports.matchesQuery = matchesQuery;
|
|
256
|
+
//# sourceMappingURL=matchers.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"matchers.cjs","sources":["../../../src/hooks/matchers.ts"],"sourcesContent":["// src/hooks/matchers.ts\n\n/**\n * Upper bound on hook-matcher pattern length. Patterns longer than this\n * are rejected outright — the goal is a cheap cap on pathological inputs\n * (repeated quantifiers, huge alternation groups) without pulling in a\n * safe-regex dependency.\n *\n * Legitimate matchers are almost always under 50 characters (tool names,\n * short alternations, simple prefix anchors); 512 leaves generous\n * headroom while preventing 10KB regexes.\n */\nexport const MAX_PATTERN_LENGTH = 512;\n\n/**\n * Upper bound on the compilation cache. Chosen to comfortably hold every\n * distinct pattern a single multi-tenant run is likely to see (tools,\n * agent types, basename filters) without growing without bound.\n *\n * Under hosts that register unique patterns per tenant, LRU eviction\n * keeps the working set bounded — cold patterns are re-compiled on next\n * use, which is the correct cost trade-off for long-running processes\n * that must not leak memory.\n */\nexport const MAX_CACHE_SIZE = 256;\n\ninterface CacheEntry {\n regex: RegExp | null;\n}\n\n/**\n * Module-level LRU cache keyed by pattern string. Map iteration order is\n * insertion order in ECMAScript, so refreshing an entry's position means\n * \"delete then re-set\". On overflow we evict the first key (least\n * recently used).\n *\n * Failed compiles are cached as `{ regex: null }` so a malformed pattern\n * does not re-enter the compiler — and so a tenant spamming bad patterns\n * doesn't burn CPU on every call.\n */\nconst patternCache: Map<string, CacheEntry> = new Map();\n\n/**\n * Threshold above which `touchCacheEntry` actually performs the LRU\n * refresh. Below this watermark the cache has zero eviction pressure, so\n * the delete+set on every hit would be pure overhead. Above it we refresh\n * properly so hot patterns survive evictions. 75% of capacity is the\n * standard sweet spot.\n */\nconst LRU_REFRESH_THRESHOLD = Math.floor((MAX_CACHE_SIZE * 3) / 4);\n\nfunction touchCacheEntry(pattern: string, entry: CacheEntry): void {\n if (patternCache.size < LRU_REFRESH_THRESHOLD) {\n return;\n }\n patternCache.delete(pattern);\n patternCache.set(pattern, entry);\n}\n\nfunction setCacheEntry(pattern: string, entry: CacheEntry): void {\n if (patternCache.size >= MAX_CACHE_SIZE) {\n const oldestKey = patternCache.keys().next().value;\n if (oldestKey !== undefined) {\n patternCache.delete(oldestKey);\n }\n }\n patternCache.set(pattern, entry);\n}\n\ninterface QuantifierFrame {\n hasBacktrackRisk: boolean;\n}\n\nfunction skipGroupSyntaxPrefix(pattern: string, start: number): number {\n if (start >= pattern.length || pattern[start] !== '?') {\n return start;\n }\n let i = start + 1;\n if (i >= pattern.length) {\n return i;\n }\n const modifier = pattern[i];\n if (modifier === ':' || modifier === '=' || modifier === '!') {\n return i + 1;\n }\n if (modifier !== '<') {\n return i;\n }\n i++;\n if (i < pattern.length && (pattern[i] === '=' || pattern[i] === '!')) {\n return i + 1;\n }\n while (i < pattern.length && pattern[i] !== '>') {\n i++;\n }\n if (i < pattern.length) {\n i++;\n }\n return i;\n}\n\n/**\n * Cheap syntactic detector for the most common catastrophic-backtracking\n * shape: a quantified group that contains another quantifier (e.g.\n * `(a+)+`, `(.*)*`, `(\\w+)+$`, `(?:(a+))+`). This is the \"nested\n * quantifier\" class of ReDoS — runs in polynomial-or-worse time on\n * adversarial inputs.\n *\n * The scan walks the pattern linearly using an explicit stack of group\n * frames. For each group it tracks whether the group's contents include\n * \"backtrack risk\" — meaning a direct quantifier OR a nested group that\n * carries risk up. When a group closes with a trailing quantifier AND its\n * frame carries backtrack risk, the pattern is flagged. Risk propagates\n * to the enclosing frame when a child group closes (whether the child\n * itself was quantified or not), so `(?:(a+))+` — equivalent to `(a+)+`\n * — is flagged correctly even though the outer non-capturing wrapper is\n * one level removed from the inner quantifier.\n *\n * ## Group-syntax prefixes\n *\n * Non-capturing groups (`(?:`), lookaheads (`(?=`, `(?!`), lookbehinds\n * (`(?<=`, `(?<!`), and named groups (`(?<name>`) are skipped over at\n * the `(` so their `?` is not misread as a quantifier. Without this,\n * `(?:pre_)?tool_name` would be incorrectly rejected because the scanner\n * would see the group-syntax `?` as a quantifier at depth 1.\n *\n * ## Heuristic, not a proof\n *\n * This catches the common forms but not all. Ambiguous-alternation ReDoS\n * like `(a|a)+` is not detected. Pathologically long patterns are also\n * caught by {@link MAX_PATTERN_LENGTH}. Hosts that accept user-supplied\n * patterns must still validate upstream.\n */\nexport function hasNestedQuantifier(pattern: string): boolean {\n const stack: QuantifierFrame[] = [];\n let i = 0;\n while (i < pattern.length) {\n const ch = pattern[i];\n if (ch === '\\\\') {\n i += 2;\n continue;\n }\n if (ch === '[') {\n i = findCharClassEnd(pattern, i) + 1;\n continue;\n }\n if (ch === '(') {\n stack.push({ hasBacktrackRisk: false });\n i = skipGroupSyntaxPrefix(pattern, i + 1);\n continue;\n }\n if (ch === ')') {\n const frame = stack.pop();\n if (frame === undefined) {\n i++;\n continue;\n }\n const next = pattern[i + 1];\n const isQuantifier =\n next === '*' || next === '+' || next === '?' || next === '{';\n if (isQuantifier && frame.hasBacktrackRisk) {\n return true;\n }\n if (stack.length > 0 && (frame.hasBacktrackRisk || isQuantifier)) {\n stack[stack.length - 1].hasBacktrackRisk = true;\n }\n i++;\n continue;\n }\n if (ch === '*' || ch === '+' || ch === '?' || ch === '{') {\n if (stack.length > 0) {\n stack[stack.length - 1].hasBacktrackRisk = true;\n }\n }\n i++;\n }\n return false;\n}\n\nfunction findCharClassEnd(pattern: string, start: number): number {\n let i = start + 1;\n while (i < pattern.length) {\n const ch = pattern[i];\n if (ch === '\\\\') {\n i += 2;\n continue;\n }\n if (ch === ']') {\n return i;\n }\n i++;\n }\n return pattern.length - 1;\n}\n\nfunction compile(pattern: string): RegExp | null {\n const cached = patternCache.get(pattern);\n if (cached !== undefined) {\n touchCacheEntry(pattern, cached);\n return cached.regex;\n }\n if (pattern.length > MAX_PATTERN_LENGTH) {\n setCacheEntry(pattern, { regex: null });\n return null;\n }\n if (hasNestedQuantifier(pattern)) {\n setCacheEntry(pattern, { regex: null });\n return null;\n }\n try {\n const regex = new RegExp(pattern);\n setCacheEntry(pattern, { regex });\n return regex;\n } catch {\n setCacheEntry(pattern, { regex: null });\n return null;\n }\n}\n\n/**\n * Tests whether a hook matcher pattern matches the given query string.\n *\n * ## Semantics\n *\n * - `undefined` or empty `pattern` matches any query (wildcard). This is\n * the intended shape for events that do not supply a query string at\n * all (`RunStart`, `Stop`, etc.) — register such matchers without a\n * pattern.\n * - `undefined` or empty `query` with a non-empty `pattern` never matches.\n * Setting a pattern on a query-less event is therefore inert: the\n * matcher will simply never fire. This is intentional — it keeps\n * query-based filtering out of event types where \"query\" has no meaning,\n * and is documented on `HookMatcher.pattern`.\n * - Otherwise, the pattern is compiled once (via a bounded LRU cache) and\n * tested against the query.\n * - Invalid regex patterns never throw — a failed compile is cached as\n * \"never matches\" so a single malformed pattern cannot take out a whole\n * `executeHooks` batch.\n *\n * ## ReDoS mitigations\n *\n * Patterns compile through three cheap gates before reaching `new RegExp`:\n *\n * 1. {@link MAX_PATTERN_LENGTH} length cap rejects oversized inputs.\n * 2. {@link hasNestedQuantifier} rejects the most common catastrophic-\n * backtracking shape (quantified group containing a quantifier).\n * 3. Successful compiles are cached in a bounded LRU so repeated calls\n * never re-enter the regex compiler.\n *\n * These are a floor, not a ceiling. Hosts that accept user-supplied\n * patterns should still validate upstream. The design report §3.8 routes\n * persistable hooks through a host-side compiler before they reach this\n * module.\n */\nexport function matchesQuery(\n pattern: string | undefined,\n query: string | undefined\n): boolean {\n if (pattern === undefined || pattern === '') {\n return true;\n }\n if (query === undefined || query === '') {\n return false;\n }\n const regex = compile(pattern);\n if (regex === null) {\n return false;\n }\n return regex.test(query);\n}\n\n/** Clears the regex compilation cache. Intended for test isolation. */\nexport function clearMatcherCache(): void {\n patternCache.clear();\n}\n\n/** Returns the current size of the compilation cache. Intended for tests.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O,IAAI;IACb;IACA,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,EAAE,EAAE;AACvC,QAAA,OAAO,KAAK;IACd;AACA,IAAA,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC;AAC9B,IAAA,IAAI,KAAK,KAAK,IAAI,EAAE;AAClB,QAAA,OAAO,KAAK;IACd;AACA,IAAA,OAAO,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC;AAC1B;;;;;;;"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Closed set of hook lifecycle events supported by the hooks system.
|
|
5
|
+
*
|
|
6
|
+
* These mirror the subset of Claude Code's event surface that makes sense
|
|
7
|
+
* for a library context (no filesystem/CLI-specific events). See
|
|
8
|
+
* `docs/hooks-design-report.md` §3.2 for the mapping to existing
|
|
9
|
+
* `@librechat/agents` emission points.
|
|
10
|
+
*/
|
|
11
|
+
const HOOK_EVENTS = [
|
|
12
|
+
'RunStart',
|
|
13
|
+
'UserPromptSubmit',
|
|
14
|
+
'PreToolUse',
|
|
15
|
+
'PostToolUse',
|
|
16
|
+
'PostToolUseFailure',
|
|
17
|
+
'PermissionDenied',
|
|
18
|
+
'SubagentStart',
|
|
19
|
+
'SubagentStop',
|
|
20
|
+
'Stop',
|
|
21
|
+
'StopFailure',
|
|
22
|
+
'PreCompact',
|
|
23
|
+
'PostCompact',
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
exports.HOOK_EVENTS = HOOK_EVENTS;
|
|
27
|
+
//# sourceMappingURL=types.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.cjs","sources":["../../../src/hooks/types.ts"],"sourcesContent":["// src/hooks/types.ts\nimport type { BaseMessage } from '@langchain/core/messages';\n\n/**\n * Closed set of hook lifecycle events supported by the hooks system.\n *\n * These mirror the subset of Claude Code's event surface that makes sense\n * for a library context (no filesystem/CLI-specific events). See\n * `docs/hooks-design-report.md` §3.2 for the mapping to existing\n * `@librechat/agents` emission points.\n */\nexport const HOOK_EVENTS = [\n 'RunStart',\n 'UserPromptSubmit',\n 'PreToolUse',\n 'PostToolUse',\n 'PostToolUseFailure',\n 'PermissionDenied',\n 'SubagentStart',\n 'SubagentStop',\n 'Stop',\n 'StopFailure',\n 'PreCompact',\n 'PostCompact',\n] as const;\n\nexport type HookEvent = (typeof HOOK_EVENTS)[number];\n\n/** Tool-gating decision; executeHooks folds with `deny > ask > allow` precedence. */\nexport type ToolDecision = 'allow' | 'deny' | 'ask';\n\n/** Stop-loop decision; `block` means \"do not stop, run another turn\". Any `block` wins. */\nexport type StopDecision = 'continue' | 'block';\n\n/**\n * Fields shared by every `HookInput`. Discriminated by `hook_event_name`.\n *\n * - `runId` identifies the current agent run and is always present.\n * - `threadId` identifies the conversation thread when the host has one.\n * - `agentId` is only set when the hook fires inside a subagent scope.\n */\nexport interface BaseHookInput {\n runId: string;\n threadId?: string;\n agentId?: string;\n}\n\nexport interface RunStartHookInput extends BaseHookInput {\n hook_event_name: 'RunStart';\n messages: BaseMessage[];\n}\n\nexport interface UserPromptSubmitHookInput extends BaseHookInput {\n hook_event_name: 'UserPromptSubmit';\n prompt: string;\n attachments?: BaseMessage[];\n}\n\n/**\n * Fires before a tool is invoked. Hook may return `deny`/`ask`/`allow` and/or\n * an `updatedInput` that replaces the tool arguments before invocation.\n *\n * `toolInput` is intentionally typed as `Record<string, unknown>` because the\n * SDK is tool-agnostic — concrete tool argument shapes are only known at the\n * call site and are narrowed by the host. This is the one escape hatch in\n * the hook type system.\n */\nexport interface PreToolUseHookInput extends BaseHookInput {\n hook_event_name: 'PreToolUse';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n stepId?: string;\n /**\n * Number of times this tool has been invoked in prior batches within the\n * current run. Within a single batch of parallel calls, all calls to the\n * same tool share the same turn value — per-call discrimination within a\n * batch is not supported in v1.\n */\n turn?: number;\n}\n\nexport interface PostToolUseHookInput extends BaseHookInput {\n hook_event_name: 'PostToolUse';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolOutput: unknown;\n toolUseId: string;\n stepId?: string;\n turn?: number;\n}\n\nexport interface PostToolUseFailureHookInput extends BaseHookInput {\n hook_event_name: 'PostToolUseFailure';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n error: string;\n stepId?: string;\n turn?: number;\n}\n\nexport interface PermissionDeniedHookInput extends BaseHookInput {\n hook_event_name: 'PermissionDenied';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n reason: string;\n}\n\nexport interface SubagentStartHookInput extends BaseHookInput {\n hook_event_name: 'SubagentStart';\n parentAgentId?: string;\n agentId: string;\n agentType: string;\n inputs: BaseMessage[];\n}\n\nexport interface SubagentStopHookInput extends BaseHookInput {\n hook_event_name: 'SubagentStop';\n agentId: string;\n agentType: string;\n messages: BaseMessage[];\n}\n\nexport interface StopHookInput extends BaseHookInput {\n hook_event_name: 'Stop';\n messages: BaseMessage[];\n stopReason?: string;\n stopHookActive: boolean;\n}\n\nexport interface StopFailureHookInput extends BaseHookInput {\n hook_event_name: 'StopFailure';\n error: string;\n lastAssistantMessage?: BaseMessage;\n}\n\nexport interface PreCompactHookInput extends BaseHookInput {\n hook_event_name: 'PreCompact';\n messagesBeforeCount: number;\n /**\n * What triggered compaction. Matches `SummarizationTrigger.type` from the\n * agent's summarization config. `'default'` means no trigger was\n * configured and compaction fired because messages were pruned.\n */\n trigger:\n | 'token_ratio'\n | 'remaining_tokens'\n | 'messages_to_refine'\n | 'default'\n | (string & {});\n}\n\nexport interface PostCompactHookInput extends BaseHookInput {\n hook_event_name: 'PostCompact';\n summary: string;\n /**\n * Number of messages remaining after compaction. The summarize node\n * returns a `removeAll` signal that clears all messages from state;\n * the summary itself is injected into the system prompt, not as a\n * message. This is `0` at the point of hook dispatch.\n */\n messagesAfterCount: number;\n}\n\n/** Discriminated union of every hook input shape. */\nexport type HookInput =\n | RunStartHookInput\n | UserPromptSubmitHookInput\n | PreToolUseHookInput\n | PostToolUseHookInput\n | PostToolUseFailureHookInput\n | PermissionDeniedHookInput\n | SubagentStartHookInput\n | SubagentStopHookInput\n | StopHookInput\n | StopFailureHookInput\n | PreCompactHookInput\n | PostCompactHookInput;\n\n/** Compile-time map from event name to its input shape. */\nexport type HookInputByEvent = {\n RunStart: RunStartHookInput;\n UserPromptSubmit: UserPromptSubmitHookInput;\n PreToolUse: PreToolUseHookInput;\n PostToolUse: PostToolUseHookInput;\n PostToolUseFailure: PostToolUseFailureHookInput;\n PermissionDenied: PermissionDeniedHookInput;\n SubagentStart: SubagentStartHookInput;\n SubagentStop: SubagentStopHookInput;\n Stop: StopHookInput;\n StopFailure: StopFailureHookInput;\n PreCompact: PreCompactHookInput;\n PostCompact: PostCompactHookInput;\n};\n\n/**\n * Fields common to every hook output. Hooks that have nothing to say simply\n * return `{}` (or omit the fields below).\n */\nexport interface BaseHookOutput {\n /** Context string to inject into the conversation. Accumulated across hooks. */\n additionalContext?: string;\n /** True to prevent the next model turn. Any hook can set this. */\n preventContinuation?: boolean;\n /** Reason reported alongside `preventContinuation`. */\n stopReason?: string;\n}\n\nexport type RunStartHookOutput = BaseHookOutput;\n\nexport interface UserPromptSubmitHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n}\n\nexport interface PreToolUseHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n /**\n * Replacement tool input. Merged into the pending tool call by the host.\n *\n * When multiple hooks set `updatedInput` within a single `executeHooks`\n * call, the last writer in registration order wins (outer loop: matcher\n * registration order; inner loop: hook position within the matcher). The\n * winner is deterministic — `Promise.all` preserves input-array order.\n * Consumers that need a single authoritative rewrite should still scope\n * `updatedInput` to one hook per matcher to avoid confusing precedence.\n */\n updatedInput?: Record<string, unknown>;\n}\n\nexport interface PostToolUseHookOutput extends BaseHookOutput {\n /**\n * Replacement tool output. Flows through the aggregated result so the\n * host can substitute it before appending the tool result message.\n * Ordering semantics match `PreToolUseHookOutput.updatedInput`:\n * last-writer-wins in registration order.\n */\n updatedOutput?: unknown;\n}\n\nexport type PostToolUseFailureHookOutput = BaseHookOutput;\n\nexport type PermissionDeniedHookOutput = BaseHookOutput;\n\nexport interface SubagentStartHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n}\n\nexport type SubagentStopHookOutput = BaseHookOutput;\n\nexport interface StopHookOutput extends BaseHookOutput {\n decision?: StopDecision;\n reason?: string;\n}\n\nexport type StopFailureHookOutput = BaseHookOutput;\n\nexport type PreCompactHookOutput = BaseHookOutput;\n\nexport type PostCompactHookOutput = BaseHookOutput;\n\n/** Compile-time map from event name to its output shape. */\nexport type HookOutputByEvent = {\n RunStart: RunStartHookOutput;\n UserPromptSubmit: UserPromptSubmitHookOutput;\n PreToolUse: PreToolUseHookOutput;\n PostToolUse: PostToolUseHookOutput;\n PostToolUseFailure: PostToolUseFailureHookOutput;\n PermissionDenied: PermissionDeniedHookOutput;\n SubagentStart: SubagentStartHookOutput;\n SubagentStop: SubagentStopHookOutput;\n Stop: StopHookOutput;\n StopFailure: StopFailureHookOutput;\n PreCompact: PreCompactHookOutput;\n PostCompact: PostCompactHookOutput;\n};\n\n/** Superset output shape used by the executor's fold loop. */\nexport type HookOutput =\n | RunStartHookOutput\n | UserPromptSubmitHookOutput\n | PreToolUseHookOutput\n | PostToolUseHookOutput\n | PostToolUseFailureHookOutput\n | PermissionDeniedHookOutput\n | SubagentStartHookOutput\n | SubagentStopHookOutput\n | StopHookOutput\n | StopFailureHookOutput\n | PreCompactHookOutput\n | PostCompactHookOutput;\n\n/**\n * A hook callback is a plain async function registered against a specific\n * event. The `signal` is always supplied by `executeHooks` and combines the\n * batch's parent signal with the per-hook timeout — callbacks that perform\n * long-running work should observe it.\n */\nexport type HookCallback<E extends HookEvent = HookEvent> = (\n input: HookInputByEvent[E],\n signal: AbortSignal\n) => HookOutputByEvent[E] | Promise<HookOutputByEvent[E]>;\n\n/**\n * A matcher groups one or more callbacks under a shared regex filter and\n * shared timeout/once/internal flags. The generic `E` ties the callback\n * types to the event the matcher is registered against.\n */\nexport interface HookMatcher<E extends HookEvent = HookEvent> {\n /**\n * Regex pattern matched against the event's primary query string (e.g.\n * the tool name for `PreToolUse`, the agent type for `SubagentStart`).\n *\n * Omitted or empty means \"always match\". For events that do not supply a\n * query string (`RunStart`, `Stop`, etc.), only wildcard matchers fire —\n * a non-empty pattern on such events will never match.\n *\n * Patterns are treated as trusted input: `executeHooks` compiles them\n * with `new RegExp(pattern)` without any sandbox, and a pathological\n * pattern can block the event loop. Host registration code is expected\n * to validate or length-bound patterns that originate from user input.\n */\n pattern?: string;\n /** Callbacks that fire when the matcher hits. Executed in parallel. */\n hooks: HookCallback<E>[];\n /** Per-matcher timeout in ms. Defaults to the executor's batch timeout. */\n timeout?: number;\n /**\n * Atomically remove the matcher before its first dispatch.\n *\n * `executeHooks` claims `once: true` matchers synchronously — between\n * `getMatchers` and its first `await` — so two concurrent calls cannot\n * both dispatch the same matcher. Whichever call runs its sync prefix\n * first wins the matcher; the other sees an empty bucket.\n *\n * Semantics are \"at most one dispatch, ever\" — if every hook in the\n * matcher throws, the matcher is still gone. Use `once` for\n * fire-and-forget bootstrapping (registration, telemetry, setup). Hosts\n * that need retry semantics should register a normal matcher and\n * self-unregister via the callback returned from `registry.register`.\n */\n once?: boolean;\n /** Internal hooks are excluded from telemetry and non-fatal error logging. */\n internal?: boolean;\n}\n\n/**\n * Storage shape for matchers keyed by event. Each event's matcher list is\n * a generic array parameterized by that event type, so lookup via\n * `HooksByEvent[E]` preserves type-safe callback signatures.\n */\nexport type HooksByEvent = {\n [E in HookEvent]?: HookMatcher<E>[];\n};\n\n/**\n * Aggregated result of a single `executeHooks` call. Fields are populated\n * according to the fold rules in `executeHooks.ts`.\n */\nexport interface AggregatedHookResult {\n /** Folded tool-gating decision; `deny > ask > allow`. */\n decision?: ToolDecision;\n /** Folded stop decision; any `block` wins. */\n stopDecision?: StopDecision;\n /** Reason from the hook that set the winning decision. */\n reason?: string;\n /**\n * Replacement tool input from a `PreToolUse` hook.\n *\n * Last-writer-wins in **registration order**: `executeHooks` uses\n * `Promise.all`, which preserves input-array order, so the fold iterates\n * outcomes in the same order they were pushed — outer loop over matchers\n * as they sit in the registry, inner loop over each matcher's `hooks`\n * array. The winner is therefore deterministic but may not match the\n * order in which hooks actually completed. Consumers that want a single\n * authoritative rewrite should still register one `updatedInput`-setting\n * hook per matcher to avoid subtle precedence bugs.\n */\n updatedInput?: Record<string, unknown>;\n /**\n * Replacement tool output from a `PostToolUse` hook.\n *\n * Same last-writer-wins-in-registration-order semantics as\n * `updatedInput`. Present only when at least one hook set it; `undefined`\n * means \"use the original tool output\".\n */\n updatedOutput?: unknown;\n /** Accumulated `additionalContext` strings from every hook, in order. */\n additionalContexts: string[];\n /** True if any hook returned `preventContinuation`. */\n preventContinuation?: boolean;\n /**\n * Reason recorded alongside `preventContinuation`. First winner wins:\n * once a hook sets both flags, later hooks that also set\n * `preventContinuation` do not overwrite the reason.\n */\n stopReason?: string;\n /** Error messages from hooks that threw; always present (possibly empty). */\n errors: string[];\n}\n"],"names":[],"mappings":";;AAGA;;;;;;;AAOG;AACI,MAAM,WAAW,GAAG;IACzB,UAAU;IACV,kBAAkB;IAClB,YAAY;IACZ,aAAa;IACb,oBAAoB;IACpB,kBAAkB;IAClB,eAAe;IACf,cAAc;IACd,MAAM;IACN,aAAa;IACb,YAAY;IACZ,aAAa;;;;;"}
|