@librechat/agents 3.1.66 → 3.1.67-dev.4

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 (149) 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 -0
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +91 -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 +53 -0
  16. package/dist/cjs/main.cjs.map +1 -1
  17. package/dist/cjs/messages/format.cjs +74 -12
  18. package/dist/cjs/messages/format.cjs.map +1 -1
  19. package/dist/cjs/run.cjs +111 -0
  20. package/dist/cjs/run.cjs.map +1 -1
  21. package/dist/cjs/summarization/node.cjs +44 -0
  22. package/dist/cjs/summarization/node.cjs.map +1 -1
  23. package/dist/cjs/tools/BashExecutor.cjs +175 -0
  24. package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
  25. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +296 -0
  26. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
  27. package/dist/cjs/tools/ReadFile.cjs +43 -0
  28. package/dist/cjs/tools/ReadFile.cjs.map +1 -0
  29. package/dist/cjs/tools/SkillTool.cjs +50 -0
  30. package/dist/cjs/tools/SkillTool.cjs.map +1 -0
  31. package/dist/cjs/tools/SubagentTool.cjs +92 -0
  32. package/dist/cjs/tools/SubagentTool.cjs.map +1 -0
  33. package/dist/cjs/tools/ToolNode.cjs +304 -140
  34. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  35. package/dist/cjs/tools/skillCatalog.cjs +84 -0
  36. package/dist/cjs/tools/skillCatalog.cjs.map +1 -0
  37. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +511 -0
  38. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -0
  39. package/dist/esm/agents/AgentContext.mjs +23 -3
  40. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  41. package/dist/esm/common/enum.mjs +15 -1
  42. package/dist/esm/common/enum.mjs.map +1 -1
  43. package/dist/esm/graphs/Graph.mjs +91 -0
  44. package/dist/esm/graphs/Graph.mjs.map +1 -1
  45. package/dist/esm/hooks/HookRegistry.mjs +160 -0
  46. package/dist/esm/hooks/HookRegistry.mjs.map +1 -0
  47. package/dist/esm/hooks/executeHooks.mjs +273 -0
  48. package/dist/esm/hooks/executeHooks.mjs.map +1 -0
  49. package/dist/esm/hooks/matchers.mjs +251 -0
  50. package/dist/esm/hooks/matchers.mjs.map +1 -0
  51. package/dist/esm/hooks/types.mjs +25 -0
  52. package/dist/esm/hooks/types.mjs.map +1 -0
  53. package/dist/esm/main.mjs +12 -1
  54. package/dist/esm/main.mjs.map +1 -1
  55. package/dist/esm/messages/format.mjs +66 -4
  56. package/dist/esm/messages/format.mjs.map +1 -1
  57. package/dist/esm/run.mjs +111 -0
  58. package/dist/esm/run.mjs.map +1 -1
  59. package/dist/esm/summarization/node.mjs +44 -0
  60. package/dist/esm/summarization/node.mjs.map +1 -1
  61. package/dist/esm/tools/BashExecutor.mjs +169 -0
  62. package/dist/esm/tools/BashExecutor.mjs.map +1 -0
  63. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +287 -0
  64. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
  65. package/dist/esm/tools/ReadFile.mjs +38 -0
  66. package/dist/esm/tools/ReadFile.mjs.map +1 -0
  67. package/dist/esm/tools/SkillTool.mjs +45 -0
  68. package/dist/esm/tools/SkillTool.mjs.map +1 -0
  69. package/dist/esm/tools/SubagentTool.mjs +85 -0
  70. package/dist/esm/tools/SubagentTool.mjs.map +1 -0
  71. package/dist/esm/tools/ToolNode.mjs +306 -142
  72. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  73. package/dist/esm/tools/skillCatalog.mjs +82 -0
  74. package/dist/esm/tools/skillCatalog.mjs.map +1 -0
  75. package/dist/esm/tools/subagent/SubagentExecutor.mjs +505 -0
  76. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -0
  77. package/dist/types/agents/AgentContext.d.ts +6 -0
  78. package/dist/types/common/enum.d.ts +10 -1
  79. package/dist/types/graphs/Graph.d.ts +2 -0
  80. package/dist/types/hooks/HookRegistry.d.ts +56 -0
  81. package/dist/types/hooks/executeHooks.d.ts +79 -0
  82. package/dist/types/hooks/index.d.ts +6 -0
  83. package/dist/types/hooks/matchers.d.ts +95 -0
  84. package/dist/types/hooks/types.d.ts +320 -0
  85. package/dist/types/index.d.ts +8 -0
  86. package/dist/types/messages/format.d.ts +2 -1
  87. package/dist/types/run.d.ts +1 -0
  88. package/dist/types/summarization/node.d.ts +2 -0
  89. package/dist/types/tools/BashExecutor.d.ts +45 -0
  90. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +72 -0
  91. package/dist/types/tools/ReadFile.d.ts +28 -0
  92. package/dist/types/tools/SkillTool.d.ts +40 -0
  93. package/dist/types/tools/SubagentTool.d.ts +36 -0
  94. package/dist/types/tools/ToolNode.d.ts +24 -2
  95. package/dist/types/tools/skillCatalog.d.ts +19 -0
  96. package/dist/types/tools/subagent/SubagentExecutor.d.ts +137 -0
  97. package/dist/types/tools/subagent/index.d.ts +2 -0
  98. package/dist/types/types/graph.d.ts +61 -2
  99. package/dist/types/types/index.d.ts +1 -0
  100. package/dist/types/types/llm.d.ts +14 -2
  101. package/dist/types/types/run.d.ts +20 -0
  102. package/dist/types/types/skill.d.ts +9 -0
  103. package/dist/types/types/tools.d.ts +38 -1
  104. package/package.json +5 -1
  105. package/src/agents/AgentContext.ts +26 -2
  106. package/src/common/enum.ts +15 -0
  107. package/src/graphs/Graph.ts +113 -0
  108. package/src/hooks/HookRegistry.ts +208 -0
  109. package/src/hooks/__tests__/HookRegistry.test.ts +190 -0
  110. package/src/hooks/__tests__/compactHooks.test.ts +214 -0
  111. package/src/hooks/__tests__/executeHooks.test.ts +1013 -0
  112. package/src/hooks/__tests__/integration.test.ts +337 -0
  113. package/src/hooks/__tests__/matchers.test.ts +238 -0
  114. package/src/hooks/__tests__/toolHooks.test.ts +669 -0
  115. package/src/hooks/executeHooks.ts +375 -0
  116. package/src/hooks/index.ts +57 -0
  117. package/src/hooks/matchers.ts +280 -0
  118. package/src/hooks/types.ts +404 -0
  119. package/src/index.ts +10 -0
  120. package/src/messages/format.ts +74 -4
  121. package/src/messages/formatAgentMessages.skills.test.ts +334 -0
  122. package/src/run.ts +126 -0
  123. package/src/scripts/multi-agent-subagent.ts +246 -0
  124. package/src/scripts/subagent-event-driven-debug.ts +190 -0
  125. package/src/scripts/subagent-tools-debug.ts +160 -0
  126. package/src/specs/subagent.test.ts +305 -0
  127. package/src/summarization/node.ts +53 -0
  128. package/src/tools/BashExecutor.ts +205 -0
  129. package/src/tools/BashProgrammaticToolCalling.ts +397 -0
  130. package/src/tools/ReadFile.ts +39 -0
  131. package/src/tools/SkillTool.ts +46 -0
  132. package/src/tools/SubagentTool.ts +100 -0
  133. package/src/tools/ToolNode.ts +391 -169
  134. package/src/tools/__tests__/ReadFile.test.ts +44 -0
  135. package/src/tools/__tests__/SkillTool.test.ts +442 -0
  136. package/src/tools/__tests__/SubagentExecutor.test.ts +1148 -0
  137. package/src/tools/__tests__/SubagentTool.test.ts +149 -0
  138. package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
  139. package/src/tools/__tests__/skillCatalog.test.ts +161 -0
  140. package/src/tools/__tests__/subagentHooks.test.ts +215 -0
  141. package/src/tools/skillCatalog.ts +126 -0
  142. package/src/tools/subagent/SubagentExecutor.ts +676 -0
  143. package/src/tools/subagent/index.ts +13 -0
  144. package/src/types/graph.ts +80 -1
  145. package/src/types/index.ts +1 -0
  146. package/src/types/llm.ts +16 -2
  147. package/src/types/run.ts +20 -0
  148. package/src/types/skill.ts +11 -0
  149. package/src/types/tools.ts +41 -1
@@ -0,0 +1,305 @@
1
+ import { HumanMessage } from '@langchain/core/messages';
2
+ import { FakeListChatModel } from '@langchain/core/utils/testing';
3
+ import type { ToolCall } from '@langchain/core/messages/tool';
4
+ import type { RunnableConfig } from '@langchain/core/runnables';
5
+ import type * as t from '@/types';
6
+ import { Run } from '@/run';
7
+ import {
8
+ Constants,
9
+ GraphEvents,
10
+ Providers,
11
+ ToolEndHandler,
12
+ ModelEndHandler,
13
+ StandardGraph,
14
+ } from '@/index';
15
+ import * as providers from '@/llm/providers';
16
+
17
+ const CHILD_RESPONSE = 'Research result: Paris is the capital of France.';
18
+
19
+ const callerConfig: Partial<RunnableConfig> & {
20
+ version: 'v1' | 'v2';
21
+ streamMode: string;
22
+ } = {
23
+ configurable: { thread_id: 'subagent-test-thread' },
24
+ streamMode: 'values',
25
+ version: 'v2' as const,
26
+ };
27
+
28
+ const createParentAgent = (): t.AgentInputs => ({
29
+ agentId: 'parent',
30
+ provider: Providers.OPENAI,
31
+ clientOptions: { modelName: 'gpt-4o-mini', apiKey: 'test-key' },
32
+ instructions:
33
+ 'You are a supervisor. Delegate research tasks using the subagent tool.',
34
+ maxContextTokens: 8000,
35
+ subagentConfigs: [
36
+ {
37
+ type: 'researcher',
38
+ name: 'Research Agent',
39
+ description: 'Researches and summarizes information',
40
+ agentInputs: {
41
+ agentId: 'researcher',
42
+ provider: Providers.OPENAI,
43
+ clientOptions: { modelName: 'gpt-4o-mini', apiKey: 'test-key' },
44
+ instructions: 'You are a research agent. Answer concisely.',
45
+ maxContextTokens: 8000,
46
+ },
47
+ },
48
+ ],
49
+ });
50
+
51
+ describe('Subagent Integration', () => {
52
+ jest.setTimeout(30000);
53
+
54
+ let getChatModelClassSpy: jest.SpyInstance;
55
+ const originalGetChatModelClass = providers.getChatModelClass;
56
+
57
+ beforeEach(() => {
58
+ getChatModelClassSpy = jest
59
+ .spyOn(providers, 'getChatModelClass')
60
+ .mockImplementation(((provider: Providers) => {
61
+ if (provider === Providers.OPENAI) {
62
+ return class extends FakeListChatModel {
63
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
64
+ constructor(_options: any) {
65
+ super({ responses: [CHILD_RESPONSE] });
66
+ }
67
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
68
+ } as any;
69
+ }
70
+ return originalGetChatModelClass(provider);
71
+ }) as typeof providers.getChatModelClass);
72
+ });
73
+
74
+ afterEach(() => {
75
+ getChatModelClassSpy.mockRestore();
76
+ });
77
+
78
+ it('should create subagent tool on agent context', async () => {
79
+ const run = await Run.create<t.IState>({
80
+ runId: `subagent-test-${Date.now()}`,
81
+ graphConfig: {
82
+ type: 'standard',
83
+ agents: [createParentAgent()],
84
+ },
85
+ returnContent: true,
86
+ skipCleanup: true,
87
+ });
88
+
89
+ expect(run.Graph).toBeDefined();
90
+ const parentContext = (run.Graph as StandardGraph).agentContexts.get(
91
+ 'parent'
92
+ );
93
+ expect(parentContext).toBeDefined();
94
+ expect(parentContext?.graphTools).toBeDefined();
95
+
96
+ const subagentTool = (parentContext?.graphTools as t.GenericTool[]).find(
97
+ (t) => 'name' in t && t.name === Constants.SUBAGENT
98
+ );
99
+ expect(subagentTool).toBeDefined();
100
+ });
101
+
102
+ it('should execute subagent and return filtered result to parent', async () => {
103
+ const customHandlers: Record<string, t.EventHandler> = {
104
+ [GraphEvents.TOOL_END]: new ToolEndHandler(),
105
+ [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
106
+ };
107
+
108
+ const run = await Run.create<t.IState>({
109
+ runId: `subagent-exec-${Date.now()}`,
110
+ graphConfig: {
111
+ type: 'standard',
112
+ agents: [createParentAgent()],
113
+ },
114
+ returnContent: true,
115
+ skipCleanup: true,
116
+ customHandlers,
117
+ });
118
+
119
+ const subagentToolCall: ToolCall = {
120
+ id: 'call_subagent_1',
121
+ name: Constants.SUBAGENT,
122
+ args: {
123
+ description: 'What is the capital of France?',
124
+ subagent_type: 'researcher',
125
+ },
126
+ type: 'tool_call',
127
+ };
128
+
129
+ run.Graph?.overrideTestModel(
130
+ [
131
+ 'Let me delegate this research task.',
132
+ `Based on the research: ${CHILD_RESPONSE}`,
133
+ ],
134
+ 10,
135
+ [subagentToolCall]
136
+ );
137
+
138
+ const result = await run.processStream(
139
+ { messages: [new HumanMessage('What is the capital of France?')] },
140
+ callerConfig
141
+ );
142
+
143
+ expect(result).toBeDefined();
144
+
145
+ const runMessages = run.getRunMessages();
146
+ expect(runMessages).toBeDefined();
147
+ expect(runMessages!.length).toBeGreaterThan(0);
148
+
149
+ const toolMessages = runMessages!.filter(
150
+ (msg) => msg._getType() === 'tool'
151
+ );
152
+ const subagentResult = toolMessages.find(
153
+ (msg) => 'name' in msg && msg.name === Constants.SUBAGENT
154
+ );
155
+ expect(subagentResult).toBeDefined();
156
+ expect(String(subagentResult!.content)).toContain('Paris');
157
+ });
158
+
159
+ it('should not create subagent tool when no subagentConfigs', async () => {
160
+ const agentWithoutSubagents: t.AgentInputs = {
161
+ agentId: 'plain',
162
+ provider: Providers.OPENAI,
163
+ clientOptions: { modelName: 'gpt-4o-mini', apiKey: 'test-key' },
164
+ instructions: 'Plain agent without subagents.',
165
+ maxContextTokens: 8000,
166
+ };
167
+
168
+ const run = await Run.create<t.IState>({
169
+ runId: `no-subagent-${Date.now()}`,
170
+ graphConfig: {
171
+ type: 'standard',
172
+ agents: [agentWithoutSubagents],
173
+ },
174
+ returnContent: true,
175
+ skipCleanup: true,
176
+ });
177
+
178
+ const context = (run.Graph as StandardGraph).agentContexts.get('plain');
179
+ const tools = context?.graphTools as t.GenericTool[] | undefined;
180
+ const subagentTool = tools?.find(
181
+ (t) => 'name' in t && t.name === Constants.SUBAGENT
182
+ );
183
+ expect(subagentTool).toBeUndefined();
184
+ });
185
+
186
+ it('should handle self-spawn subagent config', async () => {
187
+ const agentWithSelfSpawn: t.AgentInputs = {
188
+ agentId: 'self-parent',
189
+ provider: Providers.OPENAI,
190
+ clientOptions: { modelName: 'gpt-4o-mini', apiKey: 'test-key' },
191
+ instructions: 'Agent with self-spawn for context isolation.',
192
+ maxContextTokens: 8000,
193
+ subagentConfigs: [
194
+ {
195
+ type: 'isolated',
196
+ name: 'Isolated Worker',
197
+ description: 'Runs a task with isolated context',
198
+ self: true,
199
+ },
200
+ ],
201
+ };
202
+
203
+ const run = await Run.create<t.IState>({
204
+ runId: `self-spawn-${Date.now()}`,
205
+ graphConfig: {
206
+ type: 'standard',
207
+ agents: [agentWithSelfSpawn],
208
+ },
209
+ returnContent: true,
210
+ skipCleanup: true,
211
+ });
212
+
213
+ const context = (run.Graph as StandardGraph).agentContexts.get(
214
+ 'self-parent'
215
+ );
216
+ const tools = context?.graphTools as t.GenericTool[] | undefined;
217
+ const subagentTool = tools?.find(
218
+ (t) => 'name' in t && t.name === Constants.SUBAGENT
219
+ );
220
+ expect(subagentTool).toBeDefined();
221
+ });
222
+
223
+ it('should not create subagent tool when maxSubagentDepth is 0', async () => {
224
+ const agentWithZeroDepth: t.AgentInputs = {
225
+ ...createParentAgent(),
226
+ agentId: 'zero-depth',
227
+ maxSubagentDepth: 0,
228
+ };
229
+
230
+ const run = await Run.create<t.IState>({
231
+ runId: `zero-depth-${Date.now()}`,
232
+ graphConfig: {
233
+ type: 'standard',
234
+ agents: [agentWithZeroDepth],
235
+ },
236
+ returnContent: true,
237
+ skipCleanup: true,
238
+ });
239
+
240
+ const context = (run.Graph as StandardGraph).agentContexts.get(
241
+ 'zero-depth'
242
+ );
243
+ const tools = context?.graphTools as t.GenericTool[] | undefined;
244
+ const subagentTool = tools?.find(
245
+ (t) => 'name' in t && t.name === Constants.SUBAGENT
246
+ );
247
+ expect(subagentTool).toBeUndefined();
248
+ });
249
+
250
+ it('should account for subagent tool schema in toolSchemaTokens', async () => {
251
+ /** Simple char-count tokenizer — deterministic, lets us assert presence. */
252
+ const tokenCounter: t.TokenCounter = (message) => {
253
+ const content = message.content;
254
+ if (typeof content === 'string') return content.length;
255
+ if (Array.isArray(content)) return JSON.stringify(content).length;
256
+ return JSON.stringify(content).length;
257
+ };
258
+
259
+ const agentWithSubagent = createParentAgent();
260
+ const runWith = await Run.create<t.IState>({
261
+ runId: `with-sub-${Date.now()}`,
262
+ graphConfig: {
263
+ type: 'standard',
264
+ agents: [agentWithSubagent],
265
+ },
266
+ tokenCounter,
267
+ returnContent: true,
268
+ skipCleanup: true,
269
+ });
270
+
271
+ const agentWithoutSubagent: t.AgentInputs = {
272
+ agentId: 'plain',
273
+ provider: Providers.OPENAI,
274
+ clientOptions: { modelName: 'gpt-4o-mini', apiKey: 'test-key' },
275
+ instructions:
276
+ 'You are a supervisor. Delegate research tasks using the subagent tool.',
277
+ maxContextTokens: 8000,
278
+ };
279
+ const runWithout = await Run.create<t.IState>({
280
+ runId: `without-sub-${Date.now()}`,
281
+ graphConfig: {
282
+ type: 'standard',
283
+ agents: [agentWithoutSubagent],
284
+ },
285
+ tokenCounter,
286
+ returnContent: true,
287
+ skipCleanup: true,
288
+ });
289
+
290
+ const contextWith = (runWith.Graph as StandardGraph).agentContexts.get(
291
+ 'parent'
292
+ );
293
+ const contextWithout = (
294
+ runWithout.Graph as StandardGraph
295
+ ).agentContexts.get('plain');
296
+
297
+ await contextWith?.tokenCalculationPromise;
298
+ await contextWithout?.tokenCalculationPromise;
299
+
300
+ /** Subagent tool schema is ~600 chars; expect measurable difference. */
301
+ expect(contextWith!.toolSchemaTokens).toBeGreaterThan(
302
+ contextWithout!.toolSchemaTokens
303
+ );
304
+ });
305
+ });
@@ -7,6 +7,7 @@ import {
7
7
  import type { RunnableConfig } from '@langchain/core/runnables';
8
8
  import type { UsageMetadata, BaseMessage } from '@langchain/core/messages';
9
9
  import type { AgentContext } from '@/agents/AgentContext';
10
+ import type { HookRegistry } from '@/hooks';
10
11
  import type { OnChunk } from '@/llm/invoke';
11
12
  import type * as t from '@/types';
12
13
  import { ContentTypes, GraphEvents, StepTypes, Providers } from '@/common';
@@ -17,6 +18,7 @@ import { getMaxOutputTokensKey } from '@/llm/request';
17
18
  import { addCacheControl } from '@/messages/cache';
18
19
  import { initializeModel } from '@/llm/init';
19
20
  import { getChunkContent } from '@/stream';
21
+ import { executeHooks } from '@/hooks';
20
22
 
21
23
  const SUMMARIZATION_PARAM_KEYS = new Set(['maxSummaryTokens']);
22
24
 
@@ -530,6 +532,35 @@ async function dispatchCompletionEvents(params: {
530
532
  );
531
533
  }
532
534
 
535
+ const sessionId = graph.runId ?? '';
536
+ if (graph.hookRegistry?.hasHookFor('PostCompact', sessionId) === true) {
537
+ const threadId = (
538
+ runnableConfig?.configurable as Record<string, unknown> | undefined
539
+ )?.thread_id as string | undefined;
540
+ const firstBlock = summaryBlock.content?.[0];
541
+ const summaryText =
542
+ firstBlock != null &&
543
+ typeof firstBlock === 'object' &&
544
+ 'text' in firstBlock &&
545
+ typeof firstBlock.text === 'string'
546
+ ? firstBlock.text
547
+ : '';
548
+ await executeHooks({
549
+ registry: graph.hookRegistry,
550
+ input: {
551
+ hook_event_name: 'PostCompact',
552
+ runId: sessionId,
553
+ threadId,
554
+ agentId,
555
+ summary: summaryText,
556
+ messagesAfterCount: 0,
557
+ },
558
+ sessionId,
559
+ }).catch(() => {
560
+ /* PostCompact is observational — swallow errors */
561
+ });
562
+ }
563
+
533
564
  agentContext.rebuildTokenMapAfterSummarization({});
534
565
  }
535
566
 
@@ -545,6 +576,7 @@ interface CreateSummarizeNodeParams {
545
576
  config?: RunnableConfig;
546
577
  runId?: string;
547
578
  isMultiAgent: boolean;
579
+ hookRegistry?: HookRegistry;
548
580
  dispatchRunStep: (
549
581
  runStep: t.RunStep,
550
582
  config?: RunnableConfig
@@ -650,6 +682,27 @@ export function createSummarizeNode({
650
682
  );
651
683
  }
652
684
 
685
+ const sessionId = graph.runId ?? '';
686
+ if (graph.hookRegistry?.hasHookFor('PreCompact', sessionId) === true) {
687
+ const threadId = (
688
+ runnableConfig?.configurable as Record<string, unknown> | undefined
689
+ )?.thread_id as string | undefined;
690
+ await executeHooks({
691
+ registry: graph.hookRegistry,
692
+ input: {
693
+ hook_event_name: 'PreCompact',
694
+ runId: sessionId,
695
+ threadId,
696
+ agentId: request.agentId,
697
+ messagesBeforeCount: messagesToRefine.length,
698
+ trigger: agentContext.summarizationConfig?.trigger?.type ?? 'default',
699
+ },
700
+ sessionId,
701
+ }).catch(() => {
702
+ /* PreCompact is observational — swallow errors */
703
+ });
704
+ }
705
+
653
706
  const isSelfSummarizeModel =
654
707
  clientConfig.provider === (agentContext.provider as string);
655
708
  const hasPromptCache =
@@ -0,0 +1,205 @@
1
+ import { config } from 'dotenv';
2
+ import fetch, { RequestInit } from 'node-fetch';
3
+ import { HttpsProxyAgent } from 'https-proxy-agent';
4
+ import { tool, DynamicStructuredTool } from '@langchain/core/tools';
5
+ import { getEnvironmentVariable } from '@langchain/core/utils/env';
6
+ import type * as t from '@/types';
7
+ import { imageExtRegex, getCodeBaseURL } from './CodeExecutor';
8
+ import { EnvVar, Constants } from '@/common';
9
+
10
+ config();
11
+
12
+ const imageMessage = 'Image is already displayed to the user';
13
+ const otherMessage = 'File is already downloaded by the user';
14
+ const accessMessage =
15
+ 'Note: Files from previous executions are automatically available and can be modified.';
16
+ const emptyOutputMessage =
17
+ 'stdout: Empty. Ensure you\'re writing output explicitly.\n';
18
+
19
+ const baseEndpoint = getCodeBaseURL();
20
+ const EXEC_ENDPOINT = `${baseEndpoint}/exec`;
21
+
22
+ export const BashExecutionToolSchema = {
23
+ type: 'object',
24
+ properties: {
25
+ command: {
26
+ type: 'string',
27
+ description: `The bash command or script to execute.
28
+ - The environment is stateless; variables and state don't persist between executions.
29
+ - Generated files from previous executions are automatically available in "/mnt/data/".
30
+ - Files from previous executions are automatically available and can be modified in place.
31
+ - Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.
32
+ - Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.
33
+ - IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.
34
+ - Use \`echo\`, \`printf\`, or \`cat\` for all outputs.`,
35
+ },
36
+ args: {
37
+ type: 'array',
38
+ items: { type: 'string' },
39
+ description:
40
+ 'Additional arguments to execute the command with. This should only be used if the input command requires additional arguments to run.',
41
+ },
42
+ },
43
+ required: ['command'],
44
+ } as const;
45
+
46
+ export const BashExecutionToolDescription = `
47
+ Runs bash commands and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.
48
+
49
+ Usage:
50
+ - No network access available.
51
+ - Generated files are automatically delivered; **DO NOT** provide download links.
52
+ - NEVER use this tool to execute malicious commands.
53
+ `.trim();
54
+
55
+ export const BashExecutionToolName = Constants.BASH_TOOL;
56
+
57
+ export const BashExecutionToolDefinition = {
58
+ name: BashExecutionToolName,
59
+ description: BashExecutionToolDescription,
60
+ schema: BashExecutionToolSchema,
61
+ } as const;
62
+
63
+ function createBashExecutionTool(
64
+ params: t.BashExecutionToolParams = {}
65
+ ): DynamicStructuredTool {
66
+ const apiKey =
67
+ params[EnvVar.CODE_API_KEY] ??
68
+ params.apiKey ??
69
+ getEnvironmentVariable(EnvVar.CODE_API_KEY) ??
70
+ '';
71
+ if (!apiKey) {
72
+ throw new Error('No API key provided for bash execution tool.');
73
+ }
74
+
75
+ return tool(
76
+ async (rawInput, config) => {
77
+ const { command, ...rest } = rawInput as {
78
+ command: string;
79
+ args?: string[];
80
+ };
81
+ const { session_id, _injected_files } = (config.toolCall ?? {}) as {
82
+ session_id?: string;
83
+ _injected_files?: t.CodeEnvFile[];
84
+ };
85
+
86
+ const postData: Record<string, unknown> = {
87
+ lang: 'bash',
88
+ code: command,
89
+ ...rest,
90
+ ...params,
91
+ };
92
+
93
+ if (_injected_files && _injected_files.length > 0) {
94
+ postData.files = _injected_files;
95
+ } else if (session_id != null && session_id.length > 0) {
96
+ try {
97
+ const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;
98
+ const fetchOptions: RequestInit = {
99
+ method: 'GET',
100
+ headers: {
101
+ 'User-Agent': 'LibreChat/1.0',
102
+ 'X-API-Key': apiKey,
103
+ },
104
+ };
105
+
106
+ if (process.env.PROXY != null && process.env.PROXY !== '') {
107
+ fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
108
+ }
109
+
110
+ const response = await fetch(filesEndpoint, fetchOptions);
111
+ if (!response.ok) {
112
+ throw new Error(
113
+ `Failed to fetch files for session: ${response.status}`
114
+ );
115
+ }
116
+
117
+ const files = await response.json();
118
+ if (Array.isArray(files) && files.length > 0) {
119
+ const fileReferences: t.CodeEnvFile[] = files.map((file) => {
120
+ const nameParts = file.name.split('/');
121
+ const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';
122
+
123
+ return {
124
+ session_id,
125
+ id,
126
+ name: file.metadata['original-filename'],
127
+ };
128
+ });
129
+
130
+ postData.files = fileReferences;
131
+ }
132
+ } catch {
133
+ // eslint-disable-next-line no-console
134
+ console.warn(`Failed to fetch files for session: ${session_id}`);
135
+ }
136
+ }
137
+
138
+ try {
139
+ const fetchOptions: RequestInit = {
140
+ method: 'POST',
141
+ headers: {
142
+ 'Content-Type': 'application/json',
143
+ 'User-Agent': 'LibreChat/1.0',
144
+ 'X-API-Key': apiKey,
145
+ },
146
+ body: JSON.stringify(postData),
147
+ };
148
+
149
+ if (process.env.PROXY != null && process.env.PROXY !== '') {
150
+ fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
151
+ }
152
+ const response = await fetch(EXEC_ENDPOINT, fetchOptions);
153
+ if (!response.ok) {
154
+ throw new Error(`HTTP error! status: ${response.status}`);
155
+ }
156
+
157
+ const result: t.ExecuteResult = await response.json();
158
+ let formattedOutput = '';
159
+ if (result.stdout) {
160
+ formattedOutput += `stdout:\n${result.stdout}\n`;
161
+ } else {
162
+ formattedOutput += emptyOutputMessage;
163
+ }
164
+ if (result.stderr) formattedOutput += `stderr:\n${result.stderr}\n`;
165
+ if (result.files && result.files.length > 0) {
166
+ formattedOutput += 'Generated files:\n';
167
+
168
+ const fileCount = result.files.length;
169
+ for (let i = 0; i < fileCount; i++) {
170
+ const file = result.files[i];
171
+ const isImage = imageExtRegex.test(file.name);
172
+ formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;
173
+
174
+ if (i < fileCount - 1) {
175
+ formattedOutput += fileCount <= 3 ? ', ' : ',\n';
176
+ }
177
+ }
178
+
179
+ formattedOutput += `\n\n${accessMessage}`;
180
+ return [
181
+ formattedOutput.trim(),
182
+ {
183
+ session_id: result.session_id,
184
+ files: result.files,
185
+ },
186
+ ];
187
+ }
188
+
189
+ return [formattedOutput.trim(), { session_id: result.session_id }];
190
+ } catch (error) {
191
+ throw new Error(
192
+ `Execution error:\n\n${(error as Error | undefined)?.message}`
193
+ );
194
+ }
195
+ },
196
+ {
197
+ name: BashExecutionToolName,
198
+ description: BashExecutionToolDescription,
199
+ schema: BashExecutionToolSchema,
200
+ responseFormat: Constants.CONTENT_AND_ARTIFACT,
201
+ }
202
+ );
203
+ }
204
+
205
+ export { createBashExecutionTool };