@librechat/agents 3.1.64 → 3.1.66-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/dist/cjs/common/enum.cjs +13 -0
  2. package/dist/cjs/common/enum.cjs.map +1 -1
  3. package/dist/cjs/graphs/Graph.cjs +3 -0
  4. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  5. package/dist/cjs/hooks/HookRegistry.cjs +162 -0
  6. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -0
  7. package/dist/cjs/hooks/executeHooks.cjs +276 -0
  8. package/dist/cjs/hooks/executeHooks.cjs.map +1 -0
  9. package/dist/cjs/hooks/matchers.cjs +256 -0
  10. package/dist/cjs/hooks/matchers.cjs.map +1 -0
  11. package/dist/cjs/hooks/types.cjs +27 -0
  12. package/dist/cjs/hooks/types.cjs.map +1 -0
  13. package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
  14. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +69 -54
  15. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  16. package/dist/cjs/main.cjs +40 -0
  17. package/dist/cjs/main.cjs.map +1 -1
  18. package/dist/cjs/messages/core.cjs +8 -1
  19. package/dist/cjs/messages/core.cjs.map +1 -1
  20. package/dist/cjs/messages/format.cjs +74 -12
  21. package/dist/cjs/messages/format.cjs.map +1 -1
  22. package/dist/cjs/run.cjs +111 -0
  23. package/dist/cjs/run.cjs.map +1 -1
  24. package/dist/cjs/tools/BashExecutor.cjs +175 -0
  25. package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
  26. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +296 -0
  27. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
  28. package/dist/cjs/tools/ReadFile.cjs +43 -0
  29. package/dist/cjs/tools/ReadFile.cjs.map +1 -0
  30. package/dist/cjs/tools/SkillTool.cjs +50 -0
  31. package/dist/cjs/tools/SkillTool.cjs.map +1 -0
  32. package/dist/cjs/tools/ToolNode.cjs +304 -140
  33. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  34. package/dist/cjs/tools/skillCatalog.cjs +84 -0
  35. package/dist/cjs/tools/skillCatalog.cjs.map +1 -0
  36. package/dist/esm/common/enum.mjs +12 -1
  37. package/dist/esm/common/enum.mjs.map +1 -1
  38. package/dist/esm/graphs/Graph.mjs +3 -0
  39. package/dist/esm/graphs/Graph.mjs.map +1 -1
  40. package/dist/esm/hooks/HookRegistry.mjs +160 -0
  41. package/dist/esm/hooks/HookRegistry.mjs.map +1 -0
  42. package/dist/esm/hooks/executeHooks.mjs +273 -0
  43. package/dist/esm/hooks/executeHooks.mjs.map +1 -0
  44. package/dist/esm/hooks/matchers.mjs +251 -0
  45. package/dist/esm/hooks/matchers.mjs.map +1 -0
  46. package/dist/esm/hooks/types.mjs +25 -0
  47. package/dist/esm/hooks/types.mjs.map +1 -0
  48. package/dist/esm/llm/anthropic/types.mjs.map +1 -1
  49. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +69 -54
  50. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  51. package/dist/esm/main.mjs +10 -1
  52. package/dist/esm/main.mjs.map +1 -1
  53. package/dist/esm/messages/core.mjs +8 -1
  54. package/dist/esm/messages/core.mjs.map +1 -1
  55. package/dist/esm/messages/format.mjs +66 -4
  56. package/dist/esm/messages/format.mjs.map +1 -1
  57. package/dist/esm/run.mjs +111 -0
  58. package/dist/esm/run.mjs.map +1 -1
  59. package/dist/esm/tools/BashExecutor.mjs +169 -0
  60. package/dist/esm/tools/BashExecutor.mjs.map +1 -0
  61. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +287 -0
  62. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
  63. package/dist/esm/tools/ReadFile.mjs +38 -0
  64. package/dist/esm/tools/ReadFile.mjs.map +1 -0
  65. package/dist/esm/tools/SkillTool.mjs +45 -0
  66. package/dist/esm/tools/SkillTool.mjs.map +1 -0
  67. package/dist/esm/tools/ToolNode.mjs +306 -142
  68. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  69. package/dist/esm/tools/skillCatalog.mjs +82 -0
  70. package/dist/esm/tools/skillCatalog.mjs.map +1 -0
  71. package/dist/types/common/enum.d.ts +7 -1
  72. package/dist/types/graphs/Graph.d.ts +2 -0
  73. package/dist/types/hooks/HookRegistry.d.ts +56 -0
  74. package/dist/types/hooks/executeHooks.d.ts +79 -0
  75. package/dist/types/hooks/index.d.ts +6 -0
  76. package/dist/types/hooks/matchers.d.ts +95 -0
  77. package/dist/types/hooks/types.d.ts +309 -0
  78. package/dist/types/index.d.ts +6 -0
  79. package/dist/types/llm/anthropic/types.d.ts +1 -1
  80. package/dist/types/messages/format.d.ts +2 -1
  81. package/dist/types/run.d.ts +1 -0
  82. package/dist/types/tools/BashExecutor.d.ts +45 -0
  83. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +72 -0
  84. package/dist/types/tools/ReadFile.d.ts +28 -0
  85. package/dist/types/tools/SkillTool.d.ts +40 -0
  86. package/dist/types/tools/ToolNode.d.ts +24 -2
  87. package/dist/types/tools/skillCatalog.d.ts +19 -0
  88. package/dist/types/types/index.d.ts +1 -0
  89. package/dist/types/types/run.d.ts +20 -0
  90. package/dist/types/types/skill.d.ts +9 -0
  91. package/dist/types/types/tools.d.ts +38 -1
  92. package/package.json +2 -2
  93. package/src/common/enum.ts +12 -0
  94. package/src/graphs/Graph.ts +4 -0
  95. package/src/hooks/HookRegistry.ts +208 -0
  96. package/src/hooks/__tests__/HookRegistry.test.ts +190 -0
  97. package/src/hooks/__tests__/executeHooks.test.ts +1013 -0
  98. package/src/hooks/__tests__/integration.test.ts +337 -0
  99. package/src/hooks/__tests__/matchers.test.ts +238 -0
  100. package/src/hooks/__tests__/toolHooks.test.ts +669 -0
  101. package/src/hooks/executeHooks.ts +375 -0
  102. package/src/hooks/index.ts +55 -0
  103. package/src/hooks/matchers.ts +280 -0
  104. package/src/hooks/types.ts +388 -0
  105. package/src/index.ts +8 -0
  106. package/src/llm/anthropic/types.ts +1 -1
  107. package/src/llm/anthropic/utils/message_inputs.ts +93 -68
  108. package/src/llm/anthropic/utils/server-tool-inputs.test.ts +349 -0
  109. package/src/messages/core.ts +8 -1
  110. package/src/messages/format.ts +74 -4
  111. package/src/messages/formatAgentMessages.skills.test.ts +334 -0
  112. package/src/run.ts +126 -0
  113. package/src/tools/BashExecutor.ts +205 -0
  114. package/src/tools/BashProgrammaticToolCalling.ts +397 -0
  115. package/src/tools/ReadFile.ts +39 -0
  116. package/src/tools/SkillTool.ts +46 -0
  117. package/src/tools/ToolNode.ts +391 -169
  118. package/src/tools/__tests__/ReadFile.test.ts +44 -0
  119. package/src/tools/__tests__/SkillTool.test.ts +442 -0
  120. package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
  121. package/src/tools/__tests__/skillCatalog.test.ts +161 -0
  122. package/src/tools/skillCatalog.ts +126 -0
  123. package/src/types/index.ts +1 -0
  124. package/src/types/run.ts +20 -0
  125. package/src/types/skill.ts +11 -0
  126. package/src/types/tools.ts +41 -1
@@ -28,7 +28,9 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
28
28
  private directToolNames?;
29
29
  /** Maximum characters allowed in a single tool result before truncation. */
30
30
  private maxToolResultChars;
31
- constructor({ tools, toolMap, name, tags, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, toolRegistry, sessions, eventDrivenMode, agentId, directToolNames, maxContextTokens, maxToolResultChars, }: t.ToolNodeConstructorParams);
31
+ /** Hook registry for PreToolUse/PostToolUse lifecycle hooks */
32
+ private hookRegistry?;
33
+ constructor({ tools, toolMap, name, tags, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, toolRegistry, sessions, eventDrivenMode, agentId, directToolNames, maxContextTokens, maxToolResultChars, hookRegistry, }: t.ToolNodeConstructorParams);
32
34
  /**
33
35
  * Returns cached programmatic tools, computing once on first access.
34
36
  * Single iteration builds both toolMap and toolDefs simultaneously.
@@ -66,11 +68,31 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
66
68
  /**
67
69
  * Dispatches tool calls to the host via ON_TOOL_EXECUTE event and returns raw ToolMessages.
68
70
  * Core logic for event-driven execution, separated from output shaping.
71
+ *
72
+ * Hook lifecycle (when `hookRegistry` is set):
73
+ * 1. **PreToolUse** fires per call in parallel before dispatch. Denied
74
+ * calls produce error ToolMessages and fire **PermissionDenied**;
75
+ * surviving calls proceed with optional `updatedInput`.
76
+ * 2. Surviving calls are dispatched to the host via `ON_TOOL_EXECUTE`.
77
+ * 3. **PostToolUse** / **PostToolUseFailure** fire per result. Post hooks
78
+ * can replace tool output via `updatedOutput`.
79
+ * 4. Injected messages from results are collected and returned alongside
80
+ * ToolMessages (appended AFTER to respect provider ordering).
69
81
  */
70
82
  private dispatchToolEvents;
83
+ private dispatchStepCompleted;
84
+ /**
85
+ * Converts InjectedMessage instances to LangChain HumanMessage objects.
86
+ * Both 'user' and 'system' roles become HumanMessage to avoid provider
87
+ * rejections (Anthropic/Google reject non-leading SystemMessages).
88
+ * The original role is preserved in additional_kwargs for downstream consumers.
89
+ */
90
+ private convertInjectedMessages;
71
91
  /**
72
92
  * Execute all tool calls via ON_TOOL_EXECUTE event dispatch.
73
- * Used in event-driven mode where the host handles actual tool execution.
93
+ * Injected messages are placed AFTER ToolMessages to respect provider
94
+ * message ordering (AIMessage tool_calls must be immediately followed
95
+ * by their ToolMessage results).
74
96
  */
75
97
  private executeViaEvent;
76
98
  protected run(input: any, config: RunnableConfig): Promise<T>;
@@ -0,0 +1,19 @@
1
+ import type { SkillCatalogEntry } from '@/types';
2
+ export type SkillCatalogOptions = {
3
+ /** Total context window in tokens. Default: 200_000 */
4
+ contextWindowTokens?: number;
5
+ /** Fraction of context budget for catalog. Default: 0.01 (1%) */
6
+ budgetPercent?: number;
7
+ /** Max chars per entry description. Default: 250 */
8
+ maxEntryChars?: number;
9
+ /** Descriptions below this length trigger names-only fallback. Default: 20 */
10
+ minDescLength?: number;
11
+ /** Approximate chars per token for budget calculation. Default: 4 */
12
+ charsPerToken?: number;
13
+ };
14
+ /**
15
+ * Formats a skill catalog for injection into agent context.
16
+ * Uses a truncation ladder: full descriptions, proportional truncation, names-only.
17
+ * Returns empty string for empty input.
18
+ */
19
+ export declare function formatSkillCatalog(skills: SkillCatalogEntry[], opts?: SkillCatalogOptions): string;
@@ -1,6 +1,7 @@
1
1
  export * from './graph';
2
2
  export * from './llm';
3
3
  export * from './run';
4
+ export * from './skill';
4
5
  export * from './stream';
5
6
  export * from './tools';
6
7
  export * from './summarize';
@@ -7,6 +7,8 @@ import type * as s from '@/types/stream';
7
7
  import type * as e from '@/common/enum';
8
8
  import type * as g from '@/types/graph';
9
9
  import type * as l from '@/types/llm';
10
+ import type { ToolSessionMap } from '@/types/tools';
11
+ import type { HookRegistry } from '@/hooks';
10
12
  export type ZodObjectAny = z.ZodObject<any, any, any, any>;
11
13
  export type BaseGraphConfig = {
12
14
  llmConfig: l.LLMConfig;
@@ -100,6 +102,18 @@ export type RunConfig = {
100
102
  runId: string;
101
103
  graphConfig: LegacyGraphConfig | StandardGraphConfig | MultiAgentGraphConfig;
102
104
  customHandlers?: Record<string, g.EventHandler>;
105
+ /**
106
+ * Pre-constructed hook registry for this run. Hooks fire at lifecycle
107
+ * points in `processStream` (RunStart, UserPromptSubmit, Stop,
108
+ * StopFailure) and around tool calls (PreToolUse, PostToolUse,
109
+ * PostToolUseFailure, PermissionDenied).
110
+ *
111
+ * Pass `undefined` (the default) to skip all hook dispatch. When a
112
+ * registry is provided, the run attaches it to the `Graph` so internal
113
+ * nodes can fire hooks too, and clears the session in the `finally`
114
+ * block to prevent leaks.
115
+ */
116
+ hooks?: HookRegistry;
103
117
  returnContent?: boolean;
104
118
  tokenCounter?: TokenCounter;
105
119
  indexTokenCountMap?: Record<string, number>;
@@ -114,6 +128,12 @@ export type RunConfig = {
114
128
  calibrationRatio?: number;
115
129
  /** Skip post-stream cleanup (clearHeavyState) — useful for tests that inspect graph state after processStream */
116
130
  skipCleanup?: boolean;
131
+ /**
132
+ * Initial session state to seed the Graph's ToolSessionMap.
133
+ * Used to carry over code environment sessions from skill file priming
134
+ * at run start, so ToolNode can inject session_id + files into tool calls.
135
+ */
136
+ initialSessions?: ToolSessionMap;
117
137
  };
118
138
  export type ProvidedCallbacks = (BaseCallbackHandler | CallbackHandlerMethods)[] | undefined;
119
139
  export type TokenCounter = (message: BaseMessage) => number;
@@ -0,0 +1,9 @@
1
+ /** Minimal skill metadata for catalog assembly. The host provides these from its own data layer. */
2
+ export type SkillCatalogEntry = {
3
+ /** Kebab-case identifier (what the model passes to SkillTool) */
4
+ name: string;
5
+ /** One-line description for the catalog listing */
6
+ description: string;
7
+ /** Optional human-readable label (UI only, not shown to model) */
8
+ displayTitle?: string;
9
+ };
@@ -1,7 +1,8 @@
1
1
  import type { StructuredToolInterface } from '@langchain/core/tools';
2
2
  import type { RunnableToolLike } from '@langchain/core/runnables';
3
3
  import type { ToolCall } from '@langchain/core/messages/tool';
4
- import type { ToolErrorData } from './stream';
4
+ import type { HookRegistry } from '@/hooks';
5
+ import type { MessageContentComplex, ToolErrorData } from './stream';
5
6
  import { EnvVar } from '@/common';
6
7
  /** Replacement type for `import type { ToolCall } from '@langchain/core/messages/tool'` in order to have stringified args typed */
7
8
  export type CustomToolCall = {
@@ -39,6 +40,12 @@ export type ToolNodeOptions = {
39
40
  agentId?: string;
40
41
  /** Tool names that must be executed directly (via runTool) even in event-driven mode (e.g., graph-managed handoff tools) */
41
42
  directToolNames?: Set<string>;
43
+ /**
44
+ * Hook registry for PreToolUse/PostToolUse lifecycle hooks.
45
+ * Only fires for event-driven tool calls (`dispatchToolEvents`). Tools
46
+ * routed through `directToolNames` bypass hook dispatch entirely.
47
+ */
48
+ hookRegistry?: HookRegistry;
42
49
  /** Max context tokens for the agent — used to compute tool result truncation limits. */
43
50
  maxContextTokens?: number;
44
51
  /**
@@ -154,6 +161,25 @@ export type ToolExecuteBatchRequest = {
154
161
  /** Promise rejector - handler calls this on fatal error */
155
162
  reject: (error: Error) => void;
156
163
  };
164
+ /**
165
+ * A message injected into graph state by any tool execution handler.
166
+ * Generic mechanism: any tool returning `injectedMessages` in its `ToolExecuteResult`
167
+ * will have these appended to state after the ToolMessage for this call.
168
+ */
169
+ export type InjectedMessage = {
170
+ /** 'user' for skill body injection, 'system' for context hints.
171
+ * Both are converted to HumanMessage at runtime; the original role
172
+ * is preserved in additional_kwargs.role. */
173
+ role: 'user' | 'system';
174
+ /** Message content: string for simple text, array for complex multi-part content */
175
+ content: string | MessageContentComplex[];
176
+ /** When true, the message is framework-internal: not shown in UI, not counted as a user turn */
177
+ isMeta?: boolean;
178
+ /** Origin tag for downstream consumers (UI, pruner, compaction) */
179
+ source?: 'skill' | 'hook' | 'system';
180
+ /** Only set when source is 'skill', for compaction preservation */
181
+ skillName?: string;
182
+ };
157
183
  /** Result for a single tool call in event-driven execution */
158
184
  export type ToolExecuteResult = {
159
185
  /** Matches ToolCallRequest.id */
@@ -166,6 +192,13 @@ export type ToolExecuteResult = {
166
192
  status: 'success' | 'error';
167
193
  /** Error message if status is 'error' */
168
194
  errorMessage?: string;
195
+ /**
196
+ * Messages to inject into graph state after the ToolMessage for this call.
197
+ * Placed after tool results to respect provider message ordering (tool_call -> tool_result adjacency).
198
+ * The host's message formatter may merge injected user messages with the preceding tool_result turn.
199
+ * Generic mechanism: any tool execution handler can use this.
200
+ */
201
+ injectedMessages?: InjectedMessage[];
169
202
  };
170
203
  /** Map of tool names to tool definitions */
171
204
  export type LCToolRegistry = Map<string, LCTool>;
@@ -266,6 +299,10 @@ export type ProgrammaticExecutionArtifact = {
266
299
  session_id?: string;
267
300
  files?: FileRefs;
268
301
  };
302
+ /** Parameters for creating a bash execution tool (same API as CodeExecutor, bash-only) */
303
+ export type BashExecutionToolParams = CodeExecutionToolParams;
304
+ /** Parameters for creating a bash programmatic tool calling tool (same API as PTC, bash-only) */
305
+ export type BashProgrammaticToolCallingParams = ProgrammaticToolCallingParams;
269
306
  /**
270
307
  * Initialization parameters for the PTC tool
271
308
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@librechat/agents",
3
- "version": "3.1.64",
3
+ "version": "3.1.66-dev.0",
4
4
  "main": "./dist/cjs/main.cjs",
5
5
  "module": "./dist/esm/main.mjs",
6
6
  "types": "./dist/types/index.d.ts",
@@ -140,7 +140,7 @@
140
140
  "cheerio": "^1.0.0",
141
141
  "dotenv": "^16.4.7",
142
142
  "https-proxy-agent": "^7.0.6",
143
- "mathjs": "^15.1.0",
143
+ "mathjs": "^15.2.0",
144
144
  "nanoid": "^3.3.7",
145
145
  "okapibm25": "^1.4.1",
146
146
  "openai": "5.8.2"
@@ -182,8 +182,20 @@ export enum Constants {
182
182
  MCP_DELIMITER = '_mcp_',
183
183
  /** Anthropic server tool ID prefix (web_search, code_execution, etc.) */
184
184
  ANTHROPIC_SERVER_TOOL_PREFIX = 'srvtoolu_',
185
+ SKILL_TOOL = 'skill',
186
+ READ_FILE = 'read_file',
187
+ BASH_TOOL = 'bash_tool',
188
+ BASH_PROGRAMMATIC_TOOL_CALLING = 'run_tools_with_bash',
185
189
  }
186
190
 
191
+ /** Tool names that use the code execution environment (shared session, file tracking). */
192
+ export const CODE_EXECUTION_TOOLS: ReadonlySet<string> = new Set([
193
+ Constants.EXECUTE_CODE,
194
+ Constants.BASH_TOOL,
195
+ Constants.PROGRAMMATIC_TOOL_CALLING,
196
+ Constants.BASH_PROGRAMMATIC_TOOL_CALLING,
197
+ ]);
198
+
187
199
  export enum TitleMethod {
188
200
  STRUCTURED = 'structured',
189
201
  FUNCTIONS = 'functions',
@@ -53,6 +53,7 @@ import { isThinkingEnabled } from '@/llm/request';
53
53
  import { initializeModel } from '@/llm/init';
54
54
  import { HandlerRegistry } from '@/events';
55
55
  import { ChatOpenAI } from '@/llm/openai';
56
+ import type { HookRegistry } from '@/hooks';
56
57
 
57
58
  const { AGENT, TOOLS, SUMMARIZE } = GraphNodeKeys;
58
59
 
@@ -123,6 +124,7 @@ export abstract class Graph<
123
124
  /** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */
124
125
  invokedToolIds?: Set<string>;
125
126
  handlerRegistry: HandlerRegistry | undefined;
127
+ hookRegistry: HookRegistry | undefined;
126
128
  /**
127
129
  * Tool session contexts for automatic state persistence across tool invocations.
128
130
  * Keyed by tool name (e.g., Constants.EXECUTE_CODE).
@@ -147,6 +149,7 @@ export abstract class Graph<
147
149
  this.prelimMessageIdsByStepKey = new Map();
148
150
  this.invokedToolIds = undefined;
149
151
  this.handlerRegistry = undefined;
152
+ this.hookRegistry = undefined;
150
153
  this.sessions.clear();
151
154
  }
152
155
  }
@@ -506,6 +509,7 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
506
509
  agentId: agentContext?.agentId,
507
510
  toolCallStepIds: this.toolCallStepIds,
508
511
  toolRegistry: agentContext?.toolRegistry,
512
+ hookRegistry: this.hookRegistry,
509
513
  directToolNames: directToolNames.size > 0 ? directToolNames : undefined,
510
514
  maxContextTokens: agentContext?.maxContextTokens,
511
515
  maxToolResultChars: agentContext?.maxToolResultChars,
@@ -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
+ });