@librechat/agents 3.1.68 → 3.1.71-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 (192) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +23 -3
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +16 -1
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +136 -0
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/hooks/HookRegistry.cjs +162 -0
  8. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -0
  9. package/dist/cjs/hooks/executeHooks.cjs +276 -0
  10. package/dist/cjs/hooks/executeHooks.cjs.map +1 -0
  11. package/dist/cjs/hooks/matchers.cjs +256 -0
  12. package/dist/cjs/hooks/matchers.cjs.map +1 -0
  13. package/dist/cjs/hooks/types.cjs +27 -0
  14. package/dist/cjs/hooks/types.cjs.map +1 -0
  15. package/dist/cjs/main.cjs +57 -0
  16. package/dist/cjs/main.cjs.map +1 -1
  17. package/dist/cjs/messages/format.cjs +74 -12
  18. package/dist/cjs/messages/format.cjs.map +1 -1
  19. package/dist/cjs/messages/prune.cjs +9 -2
  20. package/dist/cjs/messages/prune.cjs.map +1 -1
  21. package/dist/cjs/run.cjs +115 -0
  22. package/dist/cjs/run.cjs.map +1 -1
  23. package/dist/cjs/summarization/node.cjs +44 -0
  24. package/dist/cjs/summarization/node.cjs.map +1 -1
  25. package/dist/cjs/tools/BashExecutor.cjs +208 -0
  26. package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
  27. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +287 -0
  28. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
  29. package/dist/cjs/tools/CodeExecutor.cjs +0 -9
  30. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  31. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +7 -23
  32. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  33. package/dist/cjs/tools/ReadFile.cjs +43 -0
  34. package/dist/cjs/tools/ReadFile.cjs.map +1 -0
  35. package/dist/cjs/tools/SkillTool.cjs +50 -0
  36. package/dist/cjs/tools/SkillTool.cjs.map +1 -0
  37. package/dist/cjs/tools/SubagentTool.cjs +92 -0
  38. package/dist/cjs/tools/SubagentTool.cjs.map +1 -0
  39. package/dist/cjs/tools/ToolNode.cjs +746 -174
  40. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  41. package/dist/cjs/tools/ToolSearch.cjs +2 -13
  42. package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
  43. package/dist/cjs/tools/skillCatalog.cjs +84 -0
  44. package/dist/cjs/tools/skillCatalog.cjs.map +1 -0
  45. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +511 -0
  46. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -0
  47. package/dist/cjs/tools/toolOutputReferences.cjs +475 -0
  48. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -0
  49. package/dist/cjs/utils/truncation.cjs +28 -0
  50. package/dist/cjs/utils/truncation.cjs.map +1 -1
  51. package/dist/esm/agents/AgentContext.mjs +23 -3
  52. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  53. package/dist/esm/common/enum.mjs +15 -2
  54. package/dist/esm/common/enum.mjs.map +1 -1
  55. package/dist/esm/graphs/Graph.mjs +136 -0
  56. package/dist/esm/graphs/Graph.mjs.map +1 -1
  57. package/dist/esm/hooks/HookRegistry.mjs +160 -0
  58. package/dist/esm/hooks/HookRegistry.mjs.map +1 -0
  59. package/dist/esm/hooks/executeHooks.mjs +273 -0
  60. package/dist/esm/hooks/executeHooks.mjs.map +1 -0
  61. package/dist/esm/hooks/matchers.mjs +251 -0
  62. package/dist/esm/hooks/matchers.mjs.map +1 -0
  63. package/dist/esm/hooks/types.mjs +25 -0
  64. package/dist/esm/hooks/types.mjs.map +1 -0
  65. package/dist/esm/main.mjs +13 -2
  66. package/dist/esm/main.mjs.map +1 -1
  67. package/dist/esm/messages/format.mjs +66 -4
  68. package/dist/esm/messages/format.mjs.map +1 -1
  69. package/dist/esm/messages/prune.mjs +9 -2
  70. package/dist/esm/messages/prune.mjs.map +1 -1
  71. package/dist/esm/run.mjs +115 -0
  72. package/dist/esm/run.mjs.map +1 -1
  73. package/dist/esm/summarization/node.mjs +44 -0
  74. package/dist/esm/summarization/node.mjs.map +1 -1
  75. package/dist/esm/tools/BashExecutor.mjs +200 -0
  76. package/dist/esm/tools/BashExecutor.mjs.map +1 -0
  77. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +278 -0
  78. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
  79. package/dist/esm/tools/CodeExecutor.mjs +0 -9
  80. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  81. package/dist/esm/tools/ProgrammaticToolCalling.mjs +8 -24
  82. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  83. package/dist/esm/tools/ReadFile.mjs +38 -0
  84. package/dist/esm/tools/ReadFile.mjs.map +1 -0
  85. package/dist/esm/tools/SkillTool.mjs +45 -0
  86. package/dist/esm/tools/SkillTool.mjs.map +1 -0
  87. package/dist/esm/tools/SubagentTool.mjs +85 -0
  88. package/dist/esm/tools/SubagentTool.mjs.map +1 -0
  89. package/dist/esm/tools/ToolNode.mjs +748 -176
  90. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  91. package/dist/esm/tools/ToolSearch.mjs +3 -14
  92. package/dist/esm/tools/ToolSearch.mjs.map +1 -1
  93. package/dist/esm/tools/skillCatalog.mjs +82 -0
  94. package/dist/esm/tools/skillCatalog.mjs.map +1 -0
  95. package/dist/esm/tools/subagent/SubagentExecutor.mjs +505 -0
  96. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -0
  97. package/dist/esm/tools/toolOutputReferences.mjs +468 -0
  98. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -0
  99. package/dist/esm/utils/truncation.mjs +27 -1
  100. package/dist/esm/utils/truncation.mjs.map +1 -1
  101. package/dist/types/agents/AgentContext.d.ts +6 -0
  102. package/dist/types/common/enum.d.ts +10 -2
  103. package/dist/types/graphs/Graph.d.ts +23 -0
  104. package/dist/types/hooks/HookRegistry.d.ts +56 -0
  105. package/dist/types/hooks/executeHooks.d.ts +79 -0
  106. package/dist/types/hooks/index.d.ts +6 -0
  107. package/dist/types/hooks/matchers.d.ts +95 -0
  108. package/dist/types/hooks/types.d.ts +320 -0
  109. package/dist/types/index.d.ts +8 -0
  110. package/dist/types/messages/format.d.ts +2 -1
  111. package/dist/types/run.d.ts +2 -0
  112. package/dist/types/summarization/node.d.ts +2 -0
  113. package/dist/types/tools/BashExecutor.d.ts +76 -0
  114. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +72 -0
  115. package/dist/types/tools/ProgrammaticToolCalling.d.ts +4 -9
  116. package/dist/types/tools/ReadFile.d.ts +28 -0
  117. package/dist/types/tools/SkillTool.d.ts +40 -0
  118. package/dist/types/tools/SubagentTool.d.ts +36 -0
  119. package/dist/types/tools/ToolNode.d.ts +109 -4
  120. package/dist/types/tools/ToolSearch.d.ts +2 -2
  121. package/dist/types/tools/skillCatalog.d.ts +19 -0
  122. package/dist/types/tools/subagent/SubagentExecutor.d.ts +137 -0
  123. package/dist/types/tools/subagent/index.d.ts +2 -0
  124. package/dist/types/tools/toolOutputReferences.d.ts +205 -0
  125. package/dist/types/types/graph.d.ts +61 -2
  126. package/dist/types/types/index.d.ts +1 -0
  127. package/dist/types/types/run.d.ts +28 -0
  128. package/dist/types/types/skill.d.ts +9 -0
  129. package/dist/types/types/tools.d.ts +108 -10
  130. package/dist/types/utils/truncation.d.ts +21 -0
  131. package/package.json +5 -1
  132. package/src/agents/AgentContext.ts +26 -2
  133. package/src/common/enum.ts +15 -1
  134. package/src/graphs/Graph.ts +161 -0
  135. package/src/hooks/HookRegistry.ts +208 -0
  136. package/src/hooks/__tests__/HookRegistry.test.ts +190 -0
  137. package/src/hooks/__tests__/compactHooks.test.ts +214 -0
  138. package/src/hooks/__tests__/executeHooks.test.ts +1013 -0
  139. package/src/hooks/__tests__/integration.test.ts +337 -0
  140. package/src/hooks/__tests__/matchers.test.ts +238 -0
  141. package/src/hooks/__tests__/toolHooks.test.ts +669 -0
  142. package/src/hooks/executeHooks.ts +375 -0
  143. package/src/hooks/index.ts +57 -0
  144. package/src/hooks/matchers.ts +280 -0
  145. package/src/hooks/types.ts +404 -0
  146. package/src/index.ts +10 -0
  147. package/src/messages/format.ts +74 -4
  148. package/src/messages/formatAgentMessages.skills.test.ts +334 -0
  149. package/src/messages/prune.ts +9 -2
  150. package/src/run.ts +130 -0
  151. package/src/scripts/multi-agent-subagent.ts +246 -0
  152. package/src/scripts/programmatic_exec.ts +1 -10
  153. package/src/scripts/subagent-event-driven-debug.ts +190 -0
  154. package/src/scripts/subagent-tools-debug.ts +160 -0
  155. package/src/scripts/test_code_api.ts +0 -7
  156. package/src/scripts/tool_search.ts +1 -10
  157. package/src/specs/prune.test.ts +413 -0
  158. package/src/specs/subagent.test.ts +305 -0
  159. package/src/summarization/node.ts +53 -0
  160. package/src/tools/BashExecutor.ts +238 -0
  161. package/src/tools/BashProgrammaticToolCalling.ts +381 -0
  162. package/src/tools/CodeExecutor.ts +0 -11
  163. package/src/tools/ProgrammaticToolCalling.ts +4 -29
  164. package/src/tools/ReadFile.ts +39 -0
  165. package/src/tools/SkillTool.ts +46 -0
  166. package/src/tools/SubagentTool.ts +100 -0
  167. package/src/tools/ToolNode.ts +999 -214
  168. package/src/tools/ToolSearch.ts +3 -19
  169. package/src/tools/__tests__/BashExecutor.test.ts +36 -0
  170. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +7 -8
  171. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -1
  172. package/src/tools/__tests__/ReadFile.test.ts +44 -0
  173. package/src/tools/__tests__/SkillTool.test.ts +442 -0
  174. package/src/tools/__tests__/SubagentExecutor.test.ts +1148 -0
  175. package/src/tools/__tests__/SubagentTool.test.ts +149 -0
  176. package/src/tools/__tests__/ToolNode.outputReferences.test.ts +1395 -0
  177. package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
  178. package/src/tools/__tests__/ToolSearch.integration.test.ts +7 -8
  179. package/src/tools/__tests__/skillCatalog.test.ts +161 -0
  180. package/src/tools/__tests__/subagentHooks.test.ts +215 -0
  181. package/src/tools/__tests__/toolOutputReferences.test.ts +415 -0
  182. package/src/tools/skillCatalog.ts +126 -0
  183. package/src/tools/subagent/SubagentExecutor.ts +676 -0
  184. package/src/tools/subagent/index.ts +13 -0
  185. package/src/tools/toolOutputReferences.ts +590 -0
  186. package/src/types/graph.ts +80 -1
  187. package/src/types/index.ts +1 -0
  188. package/src/types/run.ts +28 -0
  189. package/src/types/skill.ts +11 -0
  190. package/src/types/tools.ts +112 -10
  191. package/src/utils/__tests__/truncation.test.ts +66 -0
  192. package/src/utils/truncation.ts +30 -0
@@ -55,6 +55,8 @@ export class AgentContext {
55
55
  contextPruningConfig,
56
56
  maxToolResultChars,
57
57
  toolSchemaTokens,
58
+ subagentConfigs,
59
+ maxSubagentDepth,
58
60
  } = agentConfig;
59
61
 
60
62
  const agentContext = new AgentContext({
@@ -82,6 +84,10 @@ export class AgentContext {
82
84
  maxToolResultChars,
83
85
  });
84
86
 
87
+ agentContext._sourceInputs = agentConfig;
88
+ agentContext.subagentConfigs = subagentConfigs;
89
+ agentContext.maxSubagentDepth = maxSubagentDepth;
90
+
85
91
  if (initialSummary?.text != null && initialSummary.text !== '') {
86
92
  agentContext.setInitialSummary(
87
93
  initialSummary.text,
@@ -198,6 +204,12 @@ export class AgentContext {
198
204
  toolDefinitions?: t.LCTool[];
199
205
  /** Set of tool names discovered via tool search (to be loaded) */
200
206
  discoveredToolNames: Set<string> = new Set();
207
+ /** Original AgentInputs used to create this context — used for self-spawn subagent resolution. */
208
+ _sourceInputs?: t.AgentInputs;
209
+ /** Subagent configurations for hierarchical delegation. */
210
+ subagentConfigs?: t.SubagentConfig[];
211
+ /** Maximum subagent nesting depth. */
212
+ maxSubagentDepth?: number;
201
213
  /** Instructions for this agent */
202
214
  instructions?: string;
203
215
  /** Additional instructions for this agent */
@@ -685,8 +697,20 @@ export class AgentContext {
685
697
  let toolTokens = 0;
686
698
  const countedToolNames = new Set<string>();
687
699
 
688
- if (this.tools && this.tools.length > 0) {
689
- for (const tool of this.tools) {
700
+ /**
701
+ * Iterate both `tools` (user-provided instance tools) and `graphTools`
702
+ * (graph-managed tools like handoff + subagent). `graphTools` is often
703
+ * populated after `fromConfig()` kicks off the initial calculation, so
704
+ * callers that mutate `graphTools` must re-trigger this method to
705
+ * refresh `toolSchemaTokens`.
706
+ */
707
+ const instanceTools: t.GraphTools = [
708
+ ...((this.tools as t.GenericTool[] | undefined) ?? []),
709
+ ...((this.graphTools as t.GenericTool[] | undefined) ?? []),
710
+ ];
711
+
712
+ if (instanceTools.length > 0) {
713
+ for (const tool of instanceTools) {
690
714
  const genericTool = tool as Record<string, unknown>;
691
715
  if (
692
716
  genericTool.schema != null &&
@@ -27,6 +27,8 @@ export enum GraphEvents {
27
27
  ON_SUMMARIZE_DELTA = 'on_summarize_delta',
28
28
  /** [Custom] Emitted when the summarize node completes with the final summary */
29
29
  ON_SUMMARIZE_COMPLETE = 'on_summarize_complete',
30
+ /** [Custom] Progress update from a running subagent (wraps child-graph events so hosts can display activity separately from parent). */
31
+ ON_SUBAGENT_UPDATE = 'on_subagent_update',
30
32
  /** [Custom] Diagnostic logging event for context management observability */
31
33
  ON_AGENT_LOG = 'on_agent_log',
32
34
 
@@ -182,8 +184,21 @@ export enum Constants {
182
184
  MCP_DELIMITER = '_mcp_',
183
185
  /** Anthropic server tool ID prefix (web_search, code_execution, etc.) */
184
186
  ANTHROPIC_SERVER_TOOL_PREFIX = 'srvtoolu_',
187
+ SKILL_TOOL = 'skill',
188
+ READ_FILE = 'read_file',
189
+ BASH_TOOL = 'bash_tool',
190
+ BASH_PROGRAMMATIC_TOOL_CALLING = 'run_tools_with_bash',
191
+ SUBAGENT = 'subagent',
185
192
  }
186
193
 
194
+ /** Tool names that use the code execution environment (shared session, file tracking). */
195
+ export const CODE_EXECUTION_TOOLS: ReadonlySet<string> = new Set([
196
+ Constants.EXECUTE_CODE,
197
+ Constants.BASH_TOOL,
198
+ Constants.PROGRAMMATIC_TOOL_CALLING,
199
+ Constants.BASH_PROGRAMMATIC_TOOL_CALLING,
200
+ ]);
201
+
187
202
  export enum TitleMethod {
188
203
  STRUCTURED = 'structured',
189
204
  FUNCTIONS = 'functions',
@@ -191,6 +206,5 @@ export enum TitleMethod {
191
206
  }
192
207
 
193
208
  export enum EnvVar {
194
- CODE_API_KEY = 'LIBRECHAT_CODE_API_KEY',
195
209
  CODE_BASEURL = 'LIBRECHAT_CODE_BASEURL',
196
210
  }
@@ -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,7 +40,10 @@ 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';
46
+ import { ToolOutputReferenceRegistry } from '@/tools/toolOutputReferences';
43
47
  import { safeDispatchCustomEvent, emitAgentLog } from '@/utils/events';
44
48
  import { attemptInvoke, tryFallbackProviders } from '@/llm/invoke';
45
49
  import { shouldTriggerSummarization } from '@/summarization';
@@ -53,6 +57,7 @@ import { isThinkingEnabled } from '@/llm/request';
53
57
  import { initializeModel } from '@/llm/init';
54
58
  import { HandlerRegistry } from '@/events';
55
59
  import { ChatOpenAI } from '@/llm/openai';
60
+ import type { HookRegistry } from '@/hooks';
56
61
 
57
62
  const { AGENT, TOOLS, SUMMARIZE } = GraphNodeKeys;
58
63
 
@@ -123,6 +128,20 @@ export abstract class Graph<
123
128
  /** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */
124
129
  invokedToolIds?: Set<string>;
125
130
  handlerRegistry: HandlerRegistry | undefined;
131
+ hookRegistry: HookRegistry | undefined;
132
+ /**
133
+ * Run-scoped config for the tool output reference registry. Threaded
134
+ * from `RunConfig.toolOutputReferences` down into every ToolNode this
135
+ * graph compiles.
136
+ */
137
+ toolOutputReferences: t.ToolOutputReferencesConfig | undefined;
138
+ /**
139
+ * Shared registry instance used by every ToolNode compiled from this
140
+ * graph. Lazily constructed on first access so multi-agent graphs
141
+ * produce one registry per run (not one per agent), letting cross-
142
+ * agent `{{tool<i>turn<n>}}` substitutions resolve.
143
+ */
144
+ private _toolOutputRegistry?: ToolOutputReferenceRegistry;
126
145
  /**
127
146
  * Tool session contexts for automatic state persistence across tool invocations.
128
147
  * Keyed by tool name (e.g., Constants.EXECUTE_CODE).
@@ -147,8 +166,41 @@ export abstract class Graph<
147
166
  this.prelimMessageIdsByStepKey = new Map();
148
167
  this.invokedToolIds = undefined;
149
168
  this.handlerRegistry = undefined;
169
+ this.hookRegistry = undefined;
170
+ this.toolOutputReferences = undefined;
171
+ /**
172
+ * ToolNodes compiled from this graph captured the registry
173
+ * instance at construction time, so simply dropping the Graph's
174
+ * own reference would leave their captured reference — and every
175
+ * stored `tool<i>turn<n>` entry, plus up to `maxTotalSize` of raw
176
+ * output — alive across subsequent `processStream()` calls. Wipe
177
+ * the registry's contents first so subsequent runs start fresh.
178
+ */
179
+ this._toolOutputRegistry?.clear();
180
+ this._toolOutputRegistry = undefined;
150
181
  this.sessions.clear();
151
182
  }
183
+
184
+ /**
185
+ * Returns the shared `ToolOutputReferenceRegistry` for this run,
186
+ * constructing it on first access. Returns `undefined` when the
187
+ * feature is disabled. All ToolNodes compiled from this graph share
188
+ * this single instance so cross-agent `{{…}}` references resolve.
189
+ */
190
+ protected getOrCreateToolOutputRegistry():
191
+ | ToolOutputReferenceRegistry
192
+ | undefined {
193
+ if (this.toolOutputReferences?.enabled !== true) {
194
+ return undefined;
195
+ }
196
+ if (this._toolOutputRegistry == null) {
197
+ this._toolOutputRegistry = new ToolOutputReferenceRegistry({
198
+ maxOutputSize: this.toolOutputReferences.maxOutputSize,
199
+ maxTotalSize: this.toolOutputReferences.maxTotalSize,
200
+ });
201
+ }
202
+ return this._toolOutputRegistry;
203
+ }
152
204
  }
153
205
 
154
206
  export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
@@ -506,9 +558,11 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
506
558
  agentId: agentContext?.agentId,
507
559
  toolCallStepIds: this.toolCallStepIds,
508
560
  toolRegistry: agentContext?.toolRegistry,
561
+ hookRegistry: this.hookRegistry,
509
562
  directToolNames: directToolNames.size > 0 ? directToolNames : undefined,
510
563
  maxContextTokens: agentContext?.maxContextTokens,
511
564
  maxToolResultChars: agentContext?.maxToolResultChars,
565
+ toolOutputRegistry: this.getOrCreateToolOutputRegistry(),
512
566
  errorHandler: (data, metadata) =>
513
567
  StandardGraph.handleToolCallErrorStatic(this, data, metadata),
514
568
  });
@@ -540,6 +594,7 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
540
594
  sessions: this.sessions,
541
595
  maxContextTokens: agentContext?.maxContextTokens,
542
596
  maxToolResultChars: agentContext?.maxToolResultChars,
597
+ toolOutputRegistry: this.getOrCreateToolOutputRegistry(),
543
598
  });
544
599
  }
545
600
 
@@ -1148,6 +1203,111 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1148
1203
  throw new Error(`Agent context not found for agentId: ${agentId}`);
1149
1204
  }
1150
1205
 
1206
+ /**
1207
+ * Depth countdown across graph boundaries: the parent's `maxSubagentDepth`
1208
+ * becomes this executor's `maxDepth`. When the child graph is constructed,
1209
+ * `buildChildInputs()` decrements `maxSubagentDepth` on the child's
1210
+ * `AgentInputs` (only when `allowNested: true`; otherwise subagentConfigs
1211
+ * are stripped entirely). The child graph's own `createAgentNode()` then
1212
+ * reads the decremented value here and creates a narrower executor —
1213
+ * recursion is bounded even though each graph has its own separate
1214
+ * executor instance.
1215
+ */
1216
+ const effectiveSubagentDepth = agentContext.maxSubagentDepth ?? 1;
1217
+ if (
1218
+ agentContext.subagentConfigs != null &&
1219
+ agentContext.subagentConfigs.length > 0 &&
1220
+ effectiveSubagentDepth > 0
1221
+ ) {
1222
+ const resolvedConfigs = resolveSubagentConfigs(
1223
+ agentContext.subagentConfigs,
1224
+ agentContext
1225
+ );
1226
+ if (resolvedConfigs.length > 0) {
1227
+ const getParentHandlerRegistry = (): HandlerRegistry | undefined =>
1228
+ this.handlerRegistry;
1229
+ const executor = new SubagentExecutor({
1230
+ configs: new Map(resolvedConfigs.map((c) => [c.type, c])),
1231
+ parentSignal: this.signal,
1232
+ hookRegistry: this.hookRegistry,
1233
+ /** Lazy — Run wires the registry onto the graph AFTER
1234
+ * `createWorkflow()` runs, so a direct capture here would be
1235
+ * `undefined` at construction time. */
1236
+ parentHandlerRegistry: getParentHandlerRegistry,
1237
+ parentRunId: this.runId ?? '',
1238
+ parentAgentId: agentContext.agentId,
1239
+ tokenCounter: agentContext.tokenCounter,
1240
+ maxDepth: effectiveSubagentDepth,
1241
+ createChildGraph: (input): StandardGraph => new StandardGraph(input),
1242
+ });
1243
+
1244
+ const subagentTool = tool(async (rawInput, config) => {
1245
+ const input = rawInput as {
1246
+ description?: string;
1247
+ subagent_type?: string;
1248
+ };
1249
+ const description =
1250
+ typeof input.description === 'string' &&
1251
+ input.description.trim().length > 0
1252
+ ? input.description
1253
+ : 'No task description provided';
1254
+ const subagentType =
1255
+ typeof input.subagent_type === 'string' ? input.subagent_type : '';
1256
+ const threadId = config.configurable?.thread_id as string | undefined;
1257
+ /**
1258
+ * When the tool is dispatched from an LLM's `tool_call`, LangChain
1259
+ * threads the originating `ToolCall` onto the RunnableConfig as
1260
+ * `config.toolCall` (see `ToolRunnableConfig` in
1261
+ * `@langchain/core/tools` — internal but stable since ≥0.3.x).
1262
+ * Surfacing its id lets hosts correlate `SubagentUpdateEvent`s
1263
+ * back to the parent's `tool_call_id` deterministically — no
1264
+ * temporal heuristics needed. If a future LangChain version
1265
+ * changes the threading, the type-guarded read falls back to
1266
+ * `undefined` and the correlation degrades gracefully.
1267
+ */
1268
+ const toolCall = (config as { toolCall?: { id?: string } }).toolCall;
1269
+ const parentToolCallId =
1270
+ typeof toolCall?.id === 'string' ? toolCall.id : undefined;
1271
+ const result = await executor.execute({
1272
+ description,
1273
+ subagentType,
1274
+ threadId,
1275
+ parentToolCallId,
1276
+ });
1277
+ return result.content;
1278
+ }, buildSubagentToolParams(resolvedConfigs));
1279
+
1280
+ if (!agentContext.graphTools) {
1281
+ agentContext.graphTools = [];
1282
+ }
1283
+ (agentContext.graphTools as t.GenericTool[]).push(subagentTool);
1284
+
1285
+ /**
1286
+ * Refresh toolSchemaTokens to include the subagent tool's schema.
1287
+ * `calculateInstructionTokens()` was kicked off in `fromConfig()`
1288
+ * before graphTools was populated, so its result did not count this
1289
+ * tool. Without this retrigger, token-budget/pruning logic
1290
+ * underestimates prompt overhead.
1291
+ */
1292
+ if (agentContext.tokenCounter) {
1293
+ const { tokenCounter, baseIndexTokenCountMap } = agentContext;
1294
+ agentContext.tokenCalculationPromise = agentContext
1295
+ .calculateInstructionTokens(tokenCounter)
1296
+ .then(() => {
1297
+ agentContext.updateTokenMapWithInstructions(
1298
+ baseIndexTokenCountMap
1299
+ );
1300
+ })
1301
+ .catch((err) => {
1302
+ console.error(
1303
+ 'Error recalculating instruction tokens after subagent tool injection:',
1304
+ err
1305
+ );
1306
+ });
1307
+ }
1308
+ }
1309
+ }
1310
+
1151
1311
  const agentNode = `${AGENT}${agentId}` as const;
1152
1312
  const toolNode = `${TOOLS}${agentId}` as const;
1153
1313
  const summarizeNode = `${SUMMARIZE}${agentId}` as const;
@@ -1203,6 +1363,7 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1203
1363
  },
1204
1364
  runId: this.runId,
1205
1365
  isMultiAgent: this.isMultiAgentGraph(),
1366
+ hookRegistry: this.hookRegistry,
1206
1367
  dispatchRunStep: async (runStep, nodeConfig) => {
1207
1368
  this.contentData.push(runStep);
1208
1369
  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
+ }