@librechat/agents 3.0.74 → 3.0.76

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 (37) hide show
  1. package/dist/cjs/graphs/Graph.cjs +34 -0
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/tools/CodeExecutor.cjs +22 -21
  4. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  5. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +14 -11
  6. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  7. package/dist/cjs/tools/ToolNode.cjs +28 -1
  8. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  9. package/dist/cjs/tools/ToolSearch.cjs +12 -2
  10. package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
  11. package/dist/esm/graphs/Graph.mjs +35 -1
  12. package/dist/esm/graphs/Graph.mjs.map +1 -1
  13. package/dist/esm/tools/CodeExecutor.mjs +22 -21
  14. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  15. package/dist/esm/tools/ProgrammaticToolCalling.mjs +14 -11
  16. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  17. package/dist/esm/tools/ToolNode.mjs +28 -1
  18. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  19. package/dist/esm/tools/ToolSearch.mjs +12 -2
  20. package/dist/esm/tools/ToolSearch.mjs.map +1 -1
  21. package/dist/types/graphs/Graph.d.ts +6 -0
  22. package/dist/types/tools/CodeExecutor.d.ts +0 -3
  23. package/dist/types/tools/ProgrammaticToolCalling.d.ts +0 -3
  24. package/dist/types/tools/ToolNode.d.ts +3 -1
  25. package/dist/types/types/tools.d.ts +32 -0
  26. package/package.json +3 -2
  27. package/src/graphs/Graph.ts +44 -0
  28. package/src/scripts/code_exec_files.ts +58 -15
  29. package/src/scripts/code_exec_session.ts +282 -0
  30. package/src/scripts/test_code_api.ts +361 -0
  31. package/src/tools/CodeExecutor.ts +26 -23
  32. package/src/tools/ProgrammaticToolCalling.ts +18 -14
  33. package/src/tools/ToolNode.ts +33 -0
  34. package/src/tools/ToolSearch.ts +12 -2
  35. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -2
  36. package/src/tools/__tests__/ToolSearch.test.ts +84 -0
  37. package/src/types/tools.ts +40 -0
@@ -17,7 +17,7 @@ export const getCodeBaseURL = (): string =>
17
17
  const imageMessage = 'Image is already displayed to the user';
18
18
  const otherMessage = 'File is already downloaded by the user';
19
19
  const accessMessage =
20
- 'Note: Files are READ-ONLY. Save changes to NEW filenames. To access these files in future executions, provide the `session_id` as a parameter (not in your code).';
20
+ 'Note: Files from previous executions are automatically available and can be modified.';
21
21
  const emptyOutputMessage =
22
22
  'stdout: Empty. Ensure you\'re writing output explicitly.\n';
23
23
 
@@ -41,7 +41,8 @@ const CodeExecutionToolSchema = z.object({
41
41
  code: z.string()
42
42
  .describe(`The complete, self-contained code to execute, without any truncation or minimization.
43
43
  - The environment is stateless; variables and imports don't persist between executions.
44
- - When using \`session_id\`: Don't hardcode it in \`code\`, and write file modifications to NEW filenames (files are READ-ONLY).
44
+ - Generated files from previous executions are automatically available in "/mnt/data/".
45
+ - Files from previous executions are automatically available and can be modified in place.
45
46
  - Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.
46
47
  - Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.
47
48
  - IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.
@@ -50,17 +51,6 @@ const CodeExecutionToolSchema = z.object({
50
51
  - js: use the \`console\` or \`process\` methods for all outputs.
51
52
  - r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).
52
53
  - Other languages: use appropriate output functions.`),
53
- session_id: z
54
- .string()
55
- .optional()
56
- .describe(
57
- `Session ID from a previous response to access generated files.
58
- - Files load into the current working directory ("/mnt/data/")
59
- - Use relative paths ONLY
60
- - Files are READ-ONLY and cannot be modified in-place
61
- - To modify: read original file, write to NEW filename
62
- `.trim()
63
- ),
64
54
  args: z
65
55
  .array(z.string())
66
56
  .optional()
@@ -94,15 +84,33 @@ Usage:
94
84
  `.trim();
95
85
 
96
86
  return tool<typeof CodeExecutionToolSchema>(
97
- async ({ lang, code, session_id, ...rest }) => {
98
- const postData = {
87
+ async ({ lang, code, ...rest }, config) => {
88
+ /**
89
+ * Extract session context from config.toolCall (injected by ToolNode).
90
+ * - session_id: For API to associate with previous session
91
+ * - _injected_files: File refs to pass directly (avoids /files endpoint race condition)
92
+ */
93
+ const { session_id, _injected_files } = (config.toolCall ?? {}) as {
94
+ session_id?: string;
95
+ _injected_files?: t.CodeEnvFile[];
96
+ };
97
+
98
+ const postData: Record<string, unknown> = {
99
99
  lang,
100
100
  code,
101
101
  ...rest,
102
102
  ...params,
103
103
  };
104
104
 
105
- if (session_id != null && session_id.length > 0) {
105
+ /**
106
+ * File injection priority:
107
+ * 1. Use _injected_files from ToolNode (avoids /files endpoint race condition)
108
+ * 2. Fall back to fetching from /files endpoint if session_id provided but no injected files
109
+ */
110
+ if (_injected_files && _injected_files.length > 0) {
111
+ postData.files = _injected_files;
112
+ } else if (session_id != null && session_id.length > 0) {
113
+ /** Fallback: fetch from /files endpoint (may have race condition issues) */
106
114
  try {
107
115
  const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;
108
116
  const fetchOptions: RequestInit = {
@@ -127,7 +135,6 @@ Usage:
127
135
  const files = await response.json();
128
136
  if (Array.isArray(files) && files.length > 0) {
129
137
  const fileReferences: t.CodeEnvFile[] = files.map((file) => {
130
- // Extract the ID from the file name (part after session ID prefix and before extension)
131
138
  const nameParts = file.name.split('/');
132
139
  const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';
133
140
 
@@ -138,11 +145,7 @@ Usage:
138
145
  };
139
146
  });
140
147
 
141
- if (!postData.files) {
142
- postData.files = fileReferences;
143
- } else if (Array.isArray(postData.files)) {
144
- postData.files = [...postData.files, ...fileReferences];
145
- }
148
+ postData.files = fileReferences;
146
149
  }
147
150
  } catch {
148
151
  // eslint-disable-next-line no-console
@@ -191,7 +194,7 @@ Usage:
191
194
  }
192
195
  }
193
196
 
194
- formattedOutput += `\nsession_id: ${result.session_id}\n\n${accessMessage}`;
197
+ formattedOutput += `\n\n${accessMessage}`;
195
198
  return [
196
199
  formattedOutput.trim(),
197
200
  {
@@ -19,7 +19,7 @@ config();
19
19
  const imageMessage = 'Image is already displayed to the user';
20
20
  const otherMessage = 'File is already downloaded by the user';
21
21
  const accessMessage =
22
- 'Note: Files are READ-ONLY. Save changes to NEW filenames. To access these files in future executions, provide the `session_id` as a parameter (not in your code).';
22
+ 'Note: Files from previous executions are automatically available and can be modified.';
23
23
  const emptyOutputMessage =
24
24
  'stdout: Empty. Ensure you\'re writing output explicitly.\n';
25
25
 
@@ -68,12 +68,6 @@ Rules:
68
68
  - Tools are pre-defined—DO NOT write function definitions
69
69
  - Only print() output returns to the model`
70
70
  ),
71
- session_id: z
72
- .string()
73
- .optional()
74
- .describe(
75
- 'Session ID for file access (same as regular code execution). Files load into /mnt/data/ and are READ-ONLY.'
76
- ),
77
71
  timeout: z
78
72
  .number()
79
73
  .int()
@@ -542,7 +536,7 @@ export function formatCompletedResponse(
542
536
  }
543
537
  }
544
538
 
545
- formatted += `\nsession_id: ${response.session_id}\n\n${accessMessage}`;
539
+ formatted += `\n\n${accessMessage}`;
546
540
  }
547
541
 
548
542
  return [
@@ -613,7 +607,7 @@ Rules:
613
607
  - Do NOT define \`async def main()\` or call \`asyncio.run()\`—just write code with await
614
608
  - Tools are pre-defined—DO NOT write function definitions
615
609
  - Only \`print()\` output returns; tool results are raw dicts/lists/strings
616
- - Use \`session_id\` param for file persistence across calls
610
+ - Generated files are automatically available in /mnt/data/ for subsequent executions
617
611
  - Tool names normalized: hyphens→underscores, keywords get \`_tool\` suffix
618
612
 
619
613
  When to use: loops, conditionals, parallel (\`asyncio.gather\`), multi-step pipelines.
@@ -624,11 +618,15 @@ Example (complete pipeline):
624
618
 
625
619
  return tool<typeof ProgrammaticToolCallingSchema>(
626
620
  async (params, config) => {
627
- const { code, session_id, timeout = DEFAULT_TIMEOUT } = params;
621
+ const { code, timeout = DEFAULT_TIMEOUT } = params;
628
622
 
629
623
  // Extra params injected by ToolNode (follows web_search pattern)
630
- const { toolMap, toolDefs } = (config.toolCall ?? {}) as ToolCall &
631
- Partial<t.ProgrammaticCache>;
624
+ const { toolMap, toolDefs, session_id, _injected_files } =
625
+ (config.toolCall ?? {}) as ToolCall &
626
+ Partial<t.ProgrammaticCache> & {
627
+ session_id?: string;
628
+ _injected_files?: t.CodeEnvFile[];
629
+ };
632
630
 
633
631
  if (toolMap == null || toolMap.size === 0) {
634
632
  throw new Error(
@@ -661,9 +659,15 @@ Example (complete pipeline):
661
659
  );
662
660
  }
663
661
 
664
- // Fetch files from previous session if session_id is provided
662
+ /**
663
+ * File injection priority:
664
+ * 1. Use _injected_files from ToolNode (avoids /files endpoint race condition)
665
+ * 2. Fall back to fetching from /files endpoint if session_id provided but no injected files
666
+ */
665
667
  let files: t.CodeEnvFile[] | undefined;
666
- if (session_id != null && session_id.length > 0) {
668
+ if (_injected_files && _injected_files.length > 0) {
669
+ files = _injected_files;
670
+ } else if (session_id != null && session_id.length > 0) {
667
671
  files = await fetchSessionFiles(baseUrl, apiKey, session_id, proxy);
668
672
  }
669
673
 
@@ -42,6 +42,8 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
42
42
  private toolRegistry?: t.LCToolRegistry;
43
43
  /** Cached programmatic tools (computed once on first PTC call) */
44
44
  private programmaticCache?: t.ProgrammaticCache;
45
+ /** Reference to Graph's sessions map for automatic session injection */
46
+ private sessions?: t.ToolSessionMap;
45
47
 
46
48
  constructor({
47
49
  tools,
@@ -53,6 +55,7 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
53
55
  handleToolErrors,
54
56
  loadRuntimeTools,
55
57
  toolRegistry,
58
+ sessions,
56
59
  }: t.ToolNodeConstructorParams) {
57
60
  super({ name, tags, func: (input, config) => this.run(input, config) });
58
61
  this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));
@@ -62,6 +65,7 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
62
65
  this.errorHandler = errorHandler;
63
66
  this.toolUsageCount = new Map<string, number>();
64
67
  this.toolRegistry = toolRegistry;
68
+ this.sessions = sessions;
65
69
  }
66
70
 
67
71
  /**
@@ -139,6 +143,35 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
139
143
  };
140
144
  }
141
145
 
146
+ /**
147
+ * Inject session context for code execution tools when available.
148
+ * Both session_id and _injected_files are injected directly to invokeParams
149
+ * (not inside args) so they bypass Zod schema validation and reach config.toolCall.
150
+ * This avoids /files endpoint race conditions.
151
+ */
152
+ if (
153
+ call.name === Constants.EXECUTE_CODE ||
154
+ call.name === Constants.PROGRAMMATIC_TOOL_CALLING
155
+ ) {
156
+ const codeSession = this.sessions?.get(Constants.EXECUTE_CODE) as
157
+ | t.CodeSessionContext
158
+ | undefined;
159
+ if (codeSession?.session_id != null && codeSession.files.length > 0) {
160
+ /** Convert tracked files to CodeEnvFile format for the API */
161
+ const fileRefs: t.CodeEnvFile[] = codeSession.files.map((file) => ({
162
+ session_id: codeSession.session_id,
163
+ id: file.id,
164
+ name: file.name,
165
+ }));
166
+ /** Inject session_id and files directly - bypasses Zod, reaches config.toolCall */
167
+ invokeParams = {
168
+ ...invokeParams,
169
+ session_id: codeSession.session_id,
170
+ _injected_files: fileRefs,
171
+ };
172
+ }
173
+ }
174
+
142
175
  const output = await tool.invoke(invokeParams, config);
143
176
  if (
144
177
  (isBaseMessage(output) && output._getType() === 'tool') ||
@@ -303,13 +303,14 @@ function simplifyParametersForSearch(
303
303
 
304
304
  /**
305
305
  * Tokenizes a string into lowercase words for BM25.
306
+ * Splits on underscores and non-alphanumeric characters for consistent matching.
306
307
  * @param text - The text to tokenize
307
308
  * @returns Array of lowercase tokens
308
309
  */
309
310
  function tokenize(text: string): string[] {
310
311
  return text
311
312
  .toLowerCase()
312
- .replace(/[^a-z0-9_]/g, ' ')
313
+ .replace(/[^a-z0-9]/g, ' ')
313
314
  .split(/\s+/)
314
315
  .filter((token) => token.length > 0);
315
316
  }
@@ -426,6 +427,7 @@ function performLocalSearch(
426
427
  const scores = BM25(documents, queryTokens, { k1: 1.5, b: 0.75 }) as number[];
427
428
 
428
429
  const maxScore = Math.max(...scores.filter((s) => s > 0), 1);
430
+ const queryLower = query.toLowerCase().trim();
429
431
 
430
432
  const results: t.ToolSearchResult[] = [];
431
433
  for (let i = 0; i < tools.length; i++) {
@@ -435,7 +437,15 @@ function performLocalSearch(
435
437
  queryTokens,
436
438
  fields
437
439
  );
438
- const normalizedScore = Math.min(scores[i] / maxScore, 1.0);
440
+ let normalizedScore = Math.min(scores[i] / maxScore, 1.0);
441
+
442
+ // Boost score for exact base name match
443
+ const baseName = getBaseToolName(tools[i].name).toLowerCase();
444
+ if (baseName === queryLower) {
445
+ normalizedScore = 1.0;
446
+ } else if (baseName.startsWith(queryLower)) {
447
+ normalizedScore = Math.max(normalizedScore, 0.95);
448
+ }
439
449
 
440
450
  results.push({
441
451
  tool_name: tools[i].name,
@@ -643,7 +643,6 @@ for member in team:
643
643
  expect(output).toContain('Generated files:');
644
644
  expect(output).toContain('report.pdf');
645
645
  expect(output).toContain('data.csv');
646
- expect(output).toContain('session_id: sess_abc123');
647
646
  expect(artifact.files).toHaveLength(2);
648
647
  expect(artifact.files).toEqual(response.files);
649
648
  });
@@ -881,7 +880,6 @@ for member in team:
881
880
  expect(output).toContain('Generated files:');
882
881
  expect(output).toContain('report.csv');
883
882
  expect(output).toContain('chart.png');
884
- expect(output).toContain('session_id: sess_xyz');
885
883
  expect(output).toContain('File is already downloaded');
886
884
  expect(output).toContain('Image is already displayed');
887
885
  expect(artifact.files).toHaveLength(2);
@@ -806,6 +806,90 @@ describe('ToolSearch', () => {
806
806
  'get_weather'
807
807
  );
808
808
  });
809
+
810
+ it('finds tools when query contains underscores', () => {
811
+ // Underscores in query should be tokenized the same as in tool names
812
+ const tools: ToolMetadata[] = [
813
+ {
814
+ name: 'convert_time_mcp_time',
815
+ description: 'Convert time between timezones',
816
+ parameters: undefined,
817
+ },
818
+ ];
819
+
820
+ const result = performLocalSearch(tools, 'convert_time', ['name'], 10);
821
+
822
+ expect(result.tool_references.length).toBe(1);
823
+ expect(result.tool_references[0].tool_name).toBe('convert_time_mcp_time');
824
+ expect(result.tool_references[0].match_score).toBeGreaterThan(0.5);
825
+ });
826
+
827
+ it('finds tools with partial underscore query', () => {
828
+ const tools: ToolMetadata[] = [
829
+ {
830
+ name: 'get_current_time_mcp_time',
831
+ description: 'Get current time',
832
+ parameters: undefined,
833
+ },
834
+ {
835
+ name: 'convert_time_mcp_time',
836
+ description: 'Convert time between timezones',
837
+ parameters: undefined,
838
+ },
839
+ ];
840
+
841
+ // "current_time" should match "get_current_time_mcp_time"
842
+ const result = performLocalSearch(tools, 'current_time', ['name'], 10);
843
+
844
+ expect(result.tool_references.length).toBeGreaterThan(0);
845
+ expect(result.tool_references[0].tool_name).toBe(
846
+ 'get_current_time_mcp_time'
847
+ );
848
+ });
849
+
850
+ it('gives exact base name match a perfect score', () => {
851
+ const tools: ToolMetadata[] = [
852
+ {
853
+ name: 'convert_time_mcp_time',
854
+ description: 'Convert time between timezones',
855
+ parameters: undefined,
856
+ },
857
+ {
858
+ name: 'get_current_time_mcp_time',
859
+ description: 'Get current time',
860
+ parameters: undefined,
861
+ },
862
+ ];
863
+
864
+ // Exact match on base name should get score of 1.0
865
+ const result = performLocalSearch(tools, 'convert_time', ['name'], 10);
866
+
867
+ expect(result.tool_references[0].tool_name).toBe('convert_time_mcp_time');
868
+ expect(result.tool_references[0].match_score).toBe(1.0);
869
+ });
870
+
871
+ it('boosts starts-with matches on base name', () => {
872
+ const tools: ToolMetadata[] = [
873
+ {
874
+ name: 'send_email_mcp_gmail',
875
+ description: 'Send email',
876
+ parameters: undefined,
877
+ },
878
+ {
879
+ name: 'read_email_mcp_gmail',
880
+ description: 'Read email',
881
+ parameters: undefined,
882
+ },
883
+ ];
884
+
885
+ // "send" starts-with "send_email", should get boosted score
886
+ const result = performLocalSearch(tools, 'send', ['name'], 10);
887
+
888
+ expect(result.tool_references[0].tool_name).toBe('send_email_mcp_gmail');
889
+ expect(result.tool_references[0].match_score).toBeGreaterThanOrEqual(
890
+ 0.95
891
+ );
892
+ });
809
893
  });
810
894
 
811
895
  describe('formatServerListing', () => {
@@ -39,6 +39,8 @@ export type ToolNodeOptions = {
39
39
  ) => Promise<void>;
40
40
  /** Tool registry for lazy computation of programmatic tools and tool search */
41
41
  toolRegistry?: LCToolRegistry;
42
+ /** Reference to Graph's sessions map for automatic session injection */
43
+ sessions?: ToolSessionMap;
42
44
  };
43
45
 
44
46
  export type ToolNodeConstructorParams = ToolRefs & ToolNodeOptions;
@@ -253,3 +255,41 @@ export type ProgrammaticToolCallingParams = {
253
255
  /** Environment variable key for API key */
254
256
  [key: string]: unknown;
255
257
  };
258
+
259
+ // ============================================================================
260
+ // Tool Session Context Types
261
+ // ============================================================================
262
+
263
+ /**
264
+ * Tracks code execution session state for automatic file persistence.
265
+ * Stored in Graph.sessions and injected into subsequent tool invocations.
266
+ */
267
+ export type CodeSessionContext = {
268
+ /** Session ID from the code execution environment */
269
+ session_id: string;
270
+ /** Files generated in this session (for context/tracking) */
271
+ files: FileRefs;
272
+ /** Timestamp of last update */
273
+ lastUpdated: number;
274
+ };
275
+
276
+ /**
277
+ * Artifact structure returned by code execution tools (CodeExecutor, PTC).
278
+ * Used to extract session context after tool completion.
279
+ */
280
+ export type CodeExecutionArtifact = {
281
+ session_id?: string;
282
+ files?: FileRefs;
283
+ };
284
+
285
+ /**
286
+ * Generic session context union type for different tool types.
287
+ * Extend this as new tool session types are added.
288
+ */
289
+ export type ToolSessionContext = CodeSessionContext;
290
+
291
+ /**
292
+ * Map of tool names to their session contexts.
293
+ * Keys are tool constants (e.g., Constants.EXECUTE_CODE, Constants.PROGRAMMATIC_TOOL_CALLING).
294
+ */
295
+ export type ToolSessionMap = Map<string, ToolSessionContext>;