@librechat/agents 3.1.68 → 3.1.70
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 -1
- 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/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 +53 -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/node.cjs +44 -0
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +165 -0
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +287 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
- package/dist/cjs/tools/CodeExecutor.cjs +0 -9
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +7 -23
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- 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/ToolSearch.cjs +2 -13
- package/dist/cjs/tools/ToolSearch.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 -2
- 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/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 +12 -1
- 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/node.mjs +44 -0
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +159 -0
- package/dist/esm/tools/BashExecutor.mjs.map +1 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +278 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
- package/dist/esm/tools/CodeExecutor.mjs +0 -9
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +8 -24
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- 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/ToolSearch.mjs +3 -14
- package/dist/esm/tools/ToolSearch.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 -2
- package/dist/types/graphs/Graph.d.ts +2 -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/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/ProgrammaticToolCalling.d.ts +4 -9
- 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/ToolSearch.d.ts +2 -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 -10
- package/package.json +5 -1
- package/src/agents/AgentContext.ts +26 -2
- package/src/common/enum.ts +15 -1
- package/src/graphs/Graph.ts +113 -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/programmatic_exec.ts +1 -10
- package/src/scripts/subagent-event-driven-debug.ts +190 -0
- package/src/scripts/subagent-tools-debug.ts +160 -0
- package/src/scripts/test_code_api.ts +0 -7
- package/src/scripts/tool_search.ts +1 -10
- package/src/specs/subagent.test.ts +305 -0
- package/src/summarization/node.ts +53 -0
- package/src/tools/BashExecutor.ts +193 -0
- package/src/tools/BashProgrammaticToolCalling.ts +381 -0
- package/src/tools/CodeExecutor.ts +0 -11
- package/src/tools/ProgrammaticToolCalling.ts +4 -29
- 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/ToolSearch.ts +3 -19
- package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +7 -8
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -1
- 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__/ToolSearch.integration.test.ts +7 -8
- 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 -10
package/src/graphs/Graph.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/* eslint-disable no-console */
|
|
2
2
|
import { nanoid } from 'nanoid';
|
|
3
|
+
import { tool } from '@langchain/core/tools';
|
|
3
4
|
import { ToolNode } from '@langchain/langgraph/prebuilt';
|
|
4
5
|
import { Runnable, RunnableConfig } from '@langchain/core/runnables';
|
|
5
6
|
import { ToolMessage, AIMessageChunk } from '@langchain/core/messages';
|
|
@@ -39,6 +40,8 @@ import {
|
|
|
39
40
|
joinKeys,
|
|
40
41
|
sleep,
|
|
41
42
|
} from '@/utils';
|
|
43
|
+
import { SubagentExecutor, resolveSubagentConfigs } from '@/tools/subagent';
|
|
44
|
+
import { buildSubagentToolParams } from '@/tools/SubagentTool';
|
|
42
45
|
import { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';
|
|
43
46
|
import { safeDispatchCustomEvent, emitAgentLog } from '@/utils/events';
|
|
44
47
|
import { attemptInvoke, tryFallbackProviders } from '@/llm/invoke';
|
|
@@ -53,6 +56,7 @@ import { isThinkingEnabled } from '@/llm/request';
|
|
|
53
56
|
import { initializeModel } from '@/llm/init';
|
|
54
57
|
import { HandlerRegistry } from '@/events';
|
|
55
58
|
import { ChatOpenAI } from '@/llm/openai';
|
|
59
|
+
import type { HookRegistry } from '@/hooks';
|
|
56
60
|
|
|
57
61
|
const { AGENT, TOOLS, SUMMARIZE } = GraphNodeKeys;
|
|
58
62
|
|
|
@@ -123,6 +127,7 @@ export abstract class Graph<
|
|
|
123
127
|
/** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */
|
|
124
128
|
invokedToolIds?: Set<string>;
|
|
125
129
|
handlerRegistry: HandlerRegistry | undefined;
|
|
130
|
+
hookRegistry: HookRegistry | undefined;
|
|
126
131
|
/**
|
|
127
132
|
* Tool session contexts for automatic state persistence across tool invocations.
|
|
128
133
|
* Keyed by tool name (e.g., Constants.EXECUTE_CODE).
|
|
@@ -147,6 +152,7 @@ export abstract class Graph<
|
|
|
147
152
|
this.prelimMessageIdsByStepKey = new Map();
|
|
148
153
|
this.invokedToolIds = undefined;
|
|
149
154
|
this.handlerRegistry = undefined;
|
|
155
|
+
this.hookRegistry = undefined;
|
|
150
156
|
this.sessions.clear();
|
|
151
157
|
}
|
|
152
158
|
}
|
|
@@ -506,6 +512,7 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
|
|
|
506
512
|
agentId: agentContext?.agentId,
|
|
507
513
|
toolCallStepIds: this.toolCallStepIds,
|
|
508
514
|
toolRegistry: agentContext?.toolRegistry,
|
|
515
|
+
hookRegistry: this.hookRegistry,
|
|
509
516
|
directToolNames: directToolNames.size > 0 ? directToolNames : undefined,
|
|
510
517
|
maxContextTokens: agentContext?.maxContextTokens,
|
|
511
518
|
maxToolResultChars: agentContext?.maxToolResultChars,
|
|
@@ -1148,6 +1155,111 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
|
|
|
1148
1155
|
throw new Error(`Agent context not found for agentId: ${agentId}`);
|
|
1149
1156
|
}
|
|
1150
1157
|
|
|
1158
|
+
/**
|
|
1159
|
+
* Depth countdown across graph boundaries: the parent's `maxSubagentDepth`
|
|
1160
|
+
* becomes this executor's `maxDepth`. When the child graph is constructed,
|
|
1161
|
+
* `buildChildInputs()` decrements `maxSubagentDepth` on the child's
|
|
1162
|
+
* `AgentInputs` (only when `allowNested: true`; otherwise subagentConfigs
|
|
1163
|
+
* are stripped entirely). The child graph's own `createAgentNode()` then
|
|
1164
|
+
* reads the decremented value here and creates a narrower executor —
|
|
1165
|
+
* recursion is bounded even though each graph has its own separate
|
|
1166
|
+
* executor instance.
|
|
1167
|
+
*/
|
|
1168
|
+
const effectiveSubagentDepth = agentContext.maxSubagentDepth ?? 1;
|
|
1169
|
+
if (
|
|
1170
|
+
agentContext.subagentConfigs != null &&
|
|
1171
|
+
agentContext.subagentConfigs.length > 0 &&
|
|
1172
|
+
effectiveSubagentDepth > 0
|
|
1173
|
+
) {
|
|
1174
|
+
const resolvedConfigs = resolveSubagentConfigs(
|
|
1175
|
+
agentContext.subagentConfigs,
|
|
1176
|
+
agentContext
|
|
1177
|
+
);
|
|
1178
|
+
if (resolvedConfigs.length > 0) {
|
|
1179
|
+
const getParentHandlerRegistry = (): HandlerRegistry | undefined =>
|
|
1180
|
+
this.handlerRegistry;
|
|
1181
|
+
const executor = new SubagentExecutor({
|
|
1182
|
+
configs: new Map(resolvedConfigs.map((c) => [c.type, c])),
|
|
1183
|
+
parentSignal: this.signal,
|
|
1184
|
+
hookRegistry: this.hookRegistry,
|
|
1185
|
+
/** Lazy — Run wires the registry onto the graph AFTER
|
|
1186
|
+
* `createWorkflow()` runs, so a direct capture here would be
|
|
1187
|
+
* `undefined` at construction time. */
|
|
1188
|
+
parentHandlerRegistry: getParentHandlerRegistry,
|
|
1189
|
+
parentRunId: this.runId ?? '',
|
|
1190
|
+
parentAgentId: agentContext.agentId,
|
|
1191
|
+
tokenCounter: agentContext.tokenCounter,
|
|
1192
|
+
maxDepth: effectiveSubagentDepth,
|
|
1193
|
+
createChildGraph: (input): StandardGraph => new StandardGraph(input),
|
|
1194
|
+
});
|
|
1195
|
+
|
|
1196
|
+
const subagentTool = tool(async (rawInput, config) => {
|
|
1197
|
+
const input = rawInput as {
|
|
1198
|
+
description?: string;
|
|
1199
|
+
subagent_type?: string;
|
|
1200
|
+
};
|
|
1201
|
+
const description =
|
|
1202
|
+
typeof input.description === 'string' &&
|
|
1203
|
+
input.description.trim().length > 0
|
|
1204
|
+
? input.description
|
|
1205
|
+
: 'No task description provided';
|
|
1206
|
+
const subagentType =
|
|
1207
|
+
typeof input.subagent_type === 'string' ? input.subagent_type : '';
|
|
1208
|
+
const threadId = config.configurable?.thread_id as string | undefined;
|
|
1209
|
+
/**
|
|
1210
|
+
* When the tool is dispatched from an LLM's `tool_call`, LangChain
|
|
1211
|
+
* threads the originating `ToolCall` onto the RunnableConfig as
|
|
1212
|
+
* `config.toolCall` (see `ToolRunnableConfig` in
|
|
1213
|
+
* `@langchain/core/tools` — internal but stable since ≥0.3.x).
|
|
1214
|
+
* Surfacing its id lets hosts correlate `SubagentUpdateEvent`s
|
|
1215
|
+
* back to the parent's `tool_call_id` deterministically — no
|
|
1216
|
+
* temporal heuristics needed. If a future LangChain version
|
|
1217
|
+
* changes the threading, the type-guarded read falls back to
|
|
1218
|
+
* `undefined` and the correlation degrades gracefully.
|
|
1219
|
+
*/
|
|
1220
|
+
const toolCall = (config as { toolCall?: { id?: string } }).toolCall;
|
|
1221
|
+
const parentToolCallId =
|
|
1222
|
+
typeof toolCall?.id === 'string' ? toolCall.id : undefined;
|
|
1223
|
+
const result = await executor.execute({
|
|
1224
|
+
description,
|
|
1225
|
+
subagentType,
|
|
1226
|
+
threadId,
|
|
1227
|
+
parentToolCallId,
|
|
1228
|
+
});
|
|
1229
|
+
return result.content;
|
|
1230
|
+
}, buildSubagentToolParams(resolvedConfigs));
|
|
1231
|
+
|
|
1232
|
+
if (!agentContext.graphTools) {
|
|
1233
|
+
agentContext.graphTools = [];
|
|
1234
|
+
}
|
|
1235
|
+
(agentContext.graphTools as t.GenericTool[]).push(subagentTool);
|
|
1236
|
+
|
|
1237
|
+
/**
|
|
1238
|
+
* Refresh toolSchemaTokens to include the subagent tool's schema.
|
|
1239
|
+
* `calculateInstructionTokens()` was kicked off in `fromConfig()`
|
|
1240
|
+
* before graphTools was populated, so its result did not count this
|
|
1241
|
+
* tool. Without this retrigger, token-budget/pruning logic
|
|
1242
|
+
* underestimates prompt overhead.
|
|
1243
|
+
*/
|
|
1244
|
+
if (agentContext.tokenCounter) {
|
|
1245
|
+
const { tokenCounter, baseIndexTokenCountMap } = agentContext;
|
|
1246
|
+
agentContext.tokenCalculationPromise = agentContext
|
|
1247
|
+
.calculateInstructionTokens(tokenCounter)
|
|
1248
|
+
.then(() => {
|
|
1249
|
+
agentContext.updateTokenMapWithInstructions(
|
|
1250
|
+
baseIndexTokenCountMap
|
|
1251
|
+
);
|
|
1252
|
+
})
|
|
1253
|
+
.catch((err) => {
|
|
1254
|
+
console.error(
|
|
1255
|
+
'Error recalculating instruction tokens after subagent tool injection:',
|
|
1256
|
+
err
|
|
1257
|
+
);
|
|
1258
|
+
});
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1151
1263
|
const agentNode = `${AGENT}${agentId}` as const;
|
|
1152
1264
|
const toolNode = `${TOOLS}${agentId}` as const;
|
|
1153
1265
|
const summarizeNode = `${SUMMARIZE}${agentId}` as const;
|
|
@@ -1203,6 +1315,7 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
|
|
|
1203
1315
|
},
|
|
1204
1316
|
runId: this.runId,
|
|
1205
1317
|
isMultiAgent: this.isMultiAgentGraph(),
|
|
1318
|
+
hookRegistry: this.hookRegistry,
|
|
1206
1319
|
dispatchRunStep: async (runStep, nodeConfig) => {
|
|
1207
1320
|
this.contentData.push(runStep);
|
|
1208
1321
|
this.contentIndexMap.set(runStep.id, runStep.index);
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// src/hooks/HookRegistry.ts
|
|
2
|
+
import type { HookEvent, HookMatcher } from './types';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Internal matcher storage type.
|
|
6
|
+
*
|
|
7
|
+
* Matchers registered via the public `register<E>` API are strictly typed
|
|
8
|
+
* to a single `E`, but the storage needs one uniform slot type per event.
|
|
9
|
+
* We store them as `HookMatcher<HookEvent>` and cast once at the variance
|
|
10
|
+
* boundary — see `ensureList` and `snapshot` below. The invariant (every
|
|
11
|
+
* matcher in `bucket[event]` was registered with that exact event) is
|
|
12
|
+
* enforced by the public API; breaking it requires bypassing the types.
|
|
13
|
+
*/
|
|
14
|
+
type MatcherBucket = Partial<Record<HookEvent, HookMatcher<HookEvent>[]>>;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Run-scoped storage for hook matchers with an additional layer for
|
|
18
|
+
* session-scoped matchers that should be cleaned up between sessions.
|
|
19
|
+
*
|
|
20
|
+
* Hosts construct one registry per `Run` (mirroring how `HandlerRegistry` is
|
|
21
|
+
* scoped) and register global matchers + per-session matchers against it.
|
|
22
|
+
* Registration is strictly additive — nothing in this class mutates a
|
|
23
|
+
* matcher's callbacks or flags after insertion.
|
|
24
|
+
*
|
|
25
|
+
* ## Why `Map<sessionId, MatcherBucket>` and not `Record`
|
|
26
|
+
*
|
|
27
|
+
* LibreChat runs thousands of parallel sessions in one Node process, and
|
|
28
|
+
* hook registration happens inside hot paths (tool loading, agent spawning).
|
|
29
|
+
* A `Record<sessionId, ...>` has to be spread on every insertion, which is
|
|
30
|
+
* O(n) per call and O(n²) total for a batch of parallel registrations. A
|
|
31
|
+
* Map mutates in place, keeping insertions O(1). This mirrors the reasoning
|
|
32
|
+
* Claude Code documents at `utils/hooks/sessionHooks.ts:62`.
|
|
33
|
+
*/
|
|
34
|
+
export class HookRegistry {
|
|
35
|
+
private readonly global: MatcherBucket = {};
|
|
36
|
+
private readonly sessions: Map<string, MatcherBucket> = new Map();
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Register a matcher for the lifetime of this registry (= one Run).
|
|
40
|
+
* Returns an unregister function that removes the matcher by reference.
|
|
41
|
+
*/
|
|
42
|
+
register<E extends HookEvent>(event: E, matcher: HookMatcher<E>): () => void {
|
|
43
|
+
const list = ensureList(this.global, event);
|
|
44
|
+
list.push(widen(matcher));
|
|
45
|
+
return () => {
|
|
46
|
+
removeFromList(list, matcher);
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Register a matcher for a specific session. Cleared automatically when
|
|
52
|
+
* `clearSession(sessionId)` is called, or can be removed directly via the
|
|
53
|
+
* returned unregister function.
|
|
54
|
+
*/
|
|
55
|
+
registerSession<E extends HookEvent>(
|
|
56
|
+
sessionId: string,
|
|
57
|
+
event: E,
|
|
58
|
+
matcher: HookMatcher<E>
|
|
59
|
+
): () => void {
|
|
60
|
+
const bucket = this.ensureSessionBucket(sessionId);
|
|
61
|
+
const list = ensureList(bucket, event);
|
|
62
|
+
list.push(widen(matcher));
|
|
63
|
+
return () => {
|
|
64
|
+
removeFromList(list, matcher);
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Returns all matchers registered for `event`, concatenating global first
|
|
70
|
+
* and then session-specific (when `sessionId` is supplied). The caller
|
|
71
|
+
* receives a fresh array, so iterating it is safe even if a matcher is
|
|
72
|
+
* removed mid-iteration (e.g. via `once: true`).
|
|
73
|
+
*/
|
|
74
|
+
getMatchers<E extends HookEvent>(
|
|
75
|
+
event: E,
|
|
76
|
+
sessionId?: string
|
|
77
|
+
): HookMatcher<E>[] {
|
|
78
|
+
const globalList = readList(this.global, event);
|
|
79
|
+
if (sessionId === undefined) {
|
|
80
|
+
return snapshot<E>(globalList);
|
|
81
|
+
}
|
|
82
|
+
const bucket = this.sessions.get(sessionId);
|
|
83
|
+
if (bucket === undefined) {
|
|
84
|
+
return snapshot<E>(globalList);
|
|
85
|
+
}
|
|
86
|
+
const sessionList = readList(bucket, event);
|
|
87
|
+
if (globalList.length === 0) {
|
|
88
|
+
return snapshot<E>(sessionList);
|
|
89
|
+
}
|
|
90
|
+
if (sessionList.length === 0) {
|
|
91
|
+
return snapshot<E>(globalList);
|
|
92
|
+
}
|
|
93
|
+
return snapshot<E>([...globalList, ...sessionList]);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Removes `matcher` by reference from global storage first, falling back
|
|
98
|
+
* to the session bucket when `sessionId` is supplied. Used by
|
|
99
|
+
* `executeHooks` to drop `once: true` matchers after they fire.
|
|
100
|
+
*/
|
|
101
|
+
removeMatcher<E extends HookEvent>(
|
|
102
|
+
event: E,
|
|
103
|
+
matcher: HookMatcher<E>,
|
|
104
|
+
sessionId?: string
|
|
105
|
+
): boolean {
|
|
106
|
+
if (removeFromList(readList(this.global, event), matcher)) {
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
if (sessionId === undefined) {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
const bucket = this.sessions.get(sessionId);
|
|
113
|
+
if (bucket === undefined) {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
return removeFromList(readList(bucket, event), matcher);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Drops every session-scoped matcher for `sessionId`. Call this in the
|
|
121
|
+
* `finally` block around a Run so a `once: true` hook that never fired
|
|
122
|
+
* cannot leak into the next session on the same registry.
|
|
123
|
+
*/
|
|
124
|
+
clearSession(sessionId: string): void {
|
|
125
|
+
this.sessions.delete(sessionId);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** True if at least one matcher exists for `event` (global + session). */
|
|
129
|
+
hasHookFor(event: HookEvent, sessionId?: string): boolean {
|
|
130
|
+
if (readList(this.global, event).length > 0) {
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
if (sessionId === undefined) {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
const bucket = this.sessions.get(sessionId);
|
|
137
|
+
if (bucket === undefined) {
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
return readList(bucket, event).length > 0;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
private ensureSessionBucket(sessionId: string): MatcherBucket {
|
|
144
|
+
const existing = this.sessions.get(sessionId);
|
|
145
|
+
if (existing !== undefined) {
|
|
146
|
+
return existing;
|
|
147
|
+
}
|
|
148
|
+
const fresh: MatcherBucket = {};
|
|
149
|
+
this.sessions.set(sessionId, fresh);
|
|
150
|
+
return fresh;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function ensureList(
|
|
155
|
+
bucket: MatcherBucket,
|
|
156
|
+
event: HookEvent
|
|
157
|
+
): HookMatcher<HookEvent>[] {
|
|
158
|
+
const existing = bucket[event];
|
|
159
|
+
if (existing !== undefined) {
|
|
160
|
+
return existing;
|
|
161
|
+
}
|
|
162
|
+
const fresh: HookMatcher<HookEvent>[] = [];
|
|
163
|
+
bucket[event] = fresh;
|
|
164
|
+
return fresh;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function readList(
|
|
168
|
+
bucket: MatcherBucket,
|
|
169
|
+
event: HookEvent
|
|
170
|
+
): HookMatcher<HookEvent>[] {
|
|
171
|
+
return bucket[event] ?? [];
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function removeFromList<E extends HookEvent>(
|
|
175
|
+
list: HookMatcher<HookEvent>[],
|
|
176
|
+
matcher: HookMatcher<E>
|
|
177
|
+
): boolean {
|
|
178
|
+
const idx = list.indexOf(widen(matcher));
|
|
179
|
+
if (idx < 0) {
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
list.splice(idx, 1);
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Widen a per-event matcher to the storage's uniform slot type. Unsound at
|
|
188
|
+
* the type level (function parameters are contravariant) but safe by
|
|
189
|
+
* construction: `HookRegistry.register<E>` only ever puts matchers into the
|
|
190
|
+
* bucket slot for their own event, and reads go through `snapshot<E>`
|
|
191
|
+
* which is only called with the same `E`.
|
|
192
|
+
*/
|
|
193
|
+
function widen<E extends HookEvent>(
|
|
194
|
+
matcher: HookMatcher<E>
|
|
195
|
+
): HookMatcher<HookEvent> {
|
|
196
|
+
return matcher as unknown as HookMatcher<HookEvent>;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Narrow a storage list back to a per-event matcher list on the way out.
|
|
201
|
+
* Sound counterpart to `widen`: the list only contains matchers that were
|
|
202
|
+
* registered against `E`, because the public API enforces it on insert.
|
|
203
|
+
*/
|
|
204
|
+
function snapshot<E extends HookEvent>(
|
|
205
|
+
list: readonly HookMatcher<HookEvent>[]
|
|
206
|
+
): HookMatcher<E>[] {
|
|
207
|
+
return list.slice() as unknown as HookMatcher<E>[];
|
|
208
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// src/hooks/__tests__/HookRegistry.test.ts
|
|
2
|
+
import { HookRegistry } from '../HookRegistry';
|
|
3
|
+
import type {
|
|
4
|
+
HookMatcher,
|
|
5
|
+
HookCallback,
|
|
6
|
+
PreToolUseHookOutput,
|
|
7
|
+
PostToolUseHookOutput,
|
|
8
|
+
} from '../types';
|
|
9
|
+
|
|
10
|
+
const noop: HookCallback<
|
|
11
|
+
'PreToolUse'
|
|
12
|
+
> = async (): Promise<PreToolUseHookOutput> => ({});
|
|
13
|
+
const noopPost: HookCallback<
|
|
14
|
+
'PostToolUse'
|
|
15
|
+
> = async (): Promise<PostToolUseHookOutput> => ({});
|
|
16
|
+
|
|
17
|
+
function makePreToolUseMatcher(pattern?: string): HookMatcher<'PreToolUse'> {
|
|
18
|
+
return {
|
|
19
|
+
pattern,
|
|
20
|
+
hooks: [noop],
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function makePostToolUseMatcher(): HookMatcher<'PostToolUse'> {
|
|
25
|
+
return {
|
|
26
|
+
hooks: [noopPost],
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
describe('HookRegistry', () => {
|
|
31
|
+
describe('global registration', () => {
|
|
32
|
+
it('stores a matcher and returns it via getMatchers', () => {
|
|
33
|
+
const registry = new HookRegistry();
|
|
34
|
+
const matcher = makePreToolUseMatcher('Bash');
|
|
35
|
+
registry.register('PreToolUse', matcher);
|
|
36
|
+
const matchers = registry.getMatchers('PreToolUse');
|
|
37
|
+
expect(matchers).toHaveLength(1);
|
|
38
|
+
expect(matchers[0]).toBe(matcher);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('keeps registrations isolated across events', () => {
|
|
42
|
+
const registry = new HookRegistry();
|
|
43
|
+
const pre = makePreToolUseMatcher('Bash');
|
|
44
|
+
const post = makePostToolUseMatcher();
|
|
45
|
+
registry.register('PreToolUse', pre);
|
|
46
|
+
registry.register('PostToolUse', post);
|
|
47
|
+
expect(registry.getMatchers('PreToolUse')).toEqual([pre]);
|
|
48
|
+
expect(registry.getMatchers('PostToolUse')).toEqual([post]);
|
|
49
|
+
expect(registry.getMatchers('Stop')).toEqual([]);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('unregister removes the matcher from the registry', () => {
|
|
53
|
+
const registry = new HookRegistry();
|
|
54
|
+
const matcher = makePreToolUseMatcher();
|
|
55
|
+
const unregister = registry.register('PreToolUse', matcher);
|
|
56
|
+
expect(registry.getMatchers('PreToolUse')).toHaveLength(1);
|
|
57
|
+
unregister();
|
|
58
|
+
expect(registry.getMatchers('PreToolUse')).toHaveLength(0);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('hasHookFor reflects registration state', () => {
|
|
62
|
+
const registry = new HookRegistry();
|
|
63
|
+
expect(registry.hasHookFor('PreToolUse')).toBe(false);
|
|
64
|
+
registry.register('PreToolUse', makePreToolUseMatcher());
|
|
65
|
+
expect(registry.hasHookFor('PreToolUse')).toBe(true);
|
|
66
|
+
expect(registry.hasHookFor('PostToolUse')).toBe(false);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('supports multiple matchers on the same event', () => {
|
|
70
|
+
const registry = new HookRegistry();
|
|
71
|
+
const a = makePreToolUseMatcher('Bash');
|
|
72
|
+
const b = makePreToolUseMatcher('Edit');
|
|
73
|
+
registry.register('PreToolUse', a);
|
|
74
|
+
registry.register('PreToolUse', b);
|
|
75
|
+
const matchers = registry.getMatchers('PreToolUse');
|
|
76
|
+
expect(matchers).toHaveLength(2);
|
|
77
|
+
expect(matchers).toContain(a);
|
|
78
|
+
expect(matchers).toContain(b);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('returns a fresh array on each getMatchers call', () => {
|
|
82
|
+
const registry = new HookRegistry();
|
|
83
|
+
registry.register('PreToolUse', makePreToolUseMatcher());
|
|
84
|
+
const first = registry.getMatchers('PreToolUse');
|
|
85
|
+
const second = registry.getMatchers('PreToolUse');
|
|
86
|
+
expect(first).not.toBe(second);
|
|
87
|
+
first.length = 0;
|
|
88
|
+
expect(registry.getMatchers('PreToolUse')).toHaveLength(1);
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
describe('session registration', () => {
|
|
93
|
+
it('scopes matchers to a single session', () => {
|
|
94
|
+
const registry = new HookRegistry();
|
|
95
|
+
const sessionA = makePreToolUseMatcher('Bash');
|
|
96
|
+
const sessionB = makePreToolUseMatcher('Edit');
|
|
97
|
+
registry.registerSession('run-a', 'PreToolUse', sessionA);
|
|
98
|
+
registry.registerSession('run-b', 'PreToolUse', sessionB);
|
|
99
|
+
|
|
100
|
+
expect(registry.getMatchers('PreToolUse', 'run-a')).toEqual([sessionA]);
|
|
101
|
+
expect(registry.getMatchers('PreToolUse', 'run-b')).toEqual([sessionB]);
|
|
102
|
+
expect(registry.getMatchers('PreToolUse')).toEqual([]);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('merges global matchers in front of session matchers', () => {
|
|
106
|
+
const registry = new HookRegistry();
|
|
107
|
+
const global = makePreToolUseMatcher('global');
|
|
108
|
+
const session = makePreToolUseMatcher('session');
|
|
109
|
+
registry.register('PreToolUse', global);
|
|
110
|
+
registry.registerSession('run-a', 'PreToolUse', session);
|
|
111
|
+
|
|
112
|
+
const matchers = registry.getMatchers('PreToolUse', 'run-a');
|
|
113
|
+
expect(matchers).toEqual([global, session]);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('clearSession drops only the given session', () => {
|
|
117
|
+
const registry = new HookRegistry();
|
|
118
|
+
const a = makePreToolUseMatcher('a');
|
|
119
|
+
const b = makePreToolUseMatcher('b');
|
|
120
|
+
registry.registerSession('run-a', 'PreToolUse', a);
|
|
121
|
+
registry.registerSession('run-b', 'PreToolUse', b);
|
|
122
|
+
|
|
123
|
+
registry.clearSession('run-a');
|
|
124
|
+
expect(registry.getMatchers('PreToolUse', 'run-a')).toEqual([]);
|
|
125
|
+
expect(registry.getMatchers('PreToolUse', 'run-b')).toEqual([b]);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it('removeMatcher removes from the correct scope', () => {
|
|
129
|
+
const registry = new HookRegistry();
|
|
130
|
+
const global = makePreToolUseMatcher('global');
|
|
131
|
+
const session = makePreToolUseMatcher('session');
|
|
132
|
+
registry.register('PreToolUse', global);
|
|
133
|
+
registry.registerSession('run-a', 'PreToolUse', session);
|
|
134
|
+
|
|
135
|
+
expect(registry.removeMatcher('PreToolUse', session, 'run-a')).toBe(true);
|
|
136
|
+
expect(registry.getMatchers('PreToolUse', 'run-a')).toEqual([global]);
|
|
137
|
+
|
|
138
|
+
expect(registry.removeMatcher('PreToolUse', global)).toBe(true);
|
|
139
|
+
expect(registry.getMatchers('PreToolUse', 'run-a')).toEqual([]);
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
it('removeMatcher returns false when the matcher is not found', () => {
|
|
143
|
+
const registry = new HookRegistry();
|
|
144
|
+
const orphan = makePreToolUseMatcher('orphan');
|
|
145
|
+
expect(registry.removeMatcher('PreToolUse', orphan)).toBe(false);
|
|
146
|
+
expect(registry.removeMatcher('PreToolUse', orphan, 'run-a')).toBe(false);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it('session unregister function removes only that matcher', () => {
|
|
150
|
+
const registry = new HookRegistry();
|
|
151
|
+
const a = makePreToolUseMatcher('a');
|
|
152
|
+
const b = makePreToolUseMatcher('b');
|
|
153
|
+
const unregisterA = registry.registerSession('run-a', 'PreToolUse', a);
|
|
154
|
+
registry.registerSession('run-a', 'PreToolUse', b);
|
|
155
|
+
|
|
156
|
+
unregisterA();
|
|
157
|
+
expect(registry.getMatchers('PreToolUse', 'run-a')).toEqual([b]);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
it('hasHookFor honours the sessionId parameter', () => {
|
|
161
|
+
const registry = new HookRegistry();
|
|
162
|
+
registry.registerSession('run-a', 'PreToolUse', makePreToolUseMatcher());
|
|
163
|
+
expect(registry.hasHookFor('PreToolUse')).toBe(false);
|
|
164
|
+
expect(registry.hasHookFor('PreToolUse', 'run-a')).toBe(true);
|
|
165
|
+
expect(registry.hasHookFor('PreToolUse', 'run-b')).toBe(false);
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
describe('session isolation under parallel registration', () => {
|
|
170
|
+
it('does not leak matchers between sessions registered in parallel', async () => {
|
|
171
|
+
const registry = new HookRegistry();
|
|
172
|
+
const sessions = Array.from({ length: 50 }, (_, i) => `run-${i}`);
|
|
173
|
+
await Promise.all(
|
|
174
|
+
sessions.map(async (sid): Promise<void> => {
|
|
175
|
+
registry.registerSession(
|
|
176
|
+
sid,
|
|
177
|
+
'PreToolUse',
|
|
178
|
+
makePreToolUseMatcher(sid)
|
|
179
|
+
);
|
|
180
|
+
})
|
|
181
|
+
);
|
|
182
|
+
|
|
183
|
+
for (const sid of sessions) {
|
|
184
|
+
const matchers = registry.getMatchers('PreToolUse', sid);
|
|
185
|
+
expect(matchers).toHaveLength(1);
|
|
186
|
+
expect(matchers[0]?.pattern).toBe(sid);
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
});
|
|
190
|
+
});
|