@librechat/agents 3.0.36 → 3.0.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/agents/AgentContext.cjs +71 -2
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +2 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/events.cjs +3 -0
- package/dist/cjs/events.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +5 -1
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/main.cjs +12 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +329 -0
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +34 -3
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/ToolSearchRegex.cjs +455 -0
- package/dist/cjs/tools/ToolSearchRegex.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +71 -2
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +2 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/events.mjs +4 -1
- package/dist/esm/events.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +5 -1
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/main.mjs +2 -0
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +324 -0
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +34 -3
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/ToolSearchRegex.mjs +448 -0
- package/dist/esm/tools/ToolSearchRegex.mjs.map +1 -0
- package/dist/types/agents/AgentContext.d.ts +25 -1
- package/dist/types/common/enum.d.ts +2 -0
- package/dist/types/graphs/Graph.d.ts +2 -1
- package/dist/types/index.d.ts +2 -0
- package/dist/types/test/mockTools.d.ts +28 -0
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +86 -0
- package/dist/types/tools/ToolNode.d.ts +7 -1
- package/dist/types/tools/ToolSearchRegex.d.ts +80 -0
- package/dist/types/types/graph.d.ts +7 -1
- package/dist/types/types/tools.d.ts +136 -0
- package/package.json +5 -1
- package/src/agents/AgentContext.ts +86 -0
- package/src/common/enum.ts +2 -0
- package/src/events.ts +5 -1
- package/src/graphs/Graph.ts +6 -0
- package/src/index.ts +2 -0
- package/src/scripts/code_exec_ptc.ts +277 -0
- package/src/scripts/programmatic_exec.ts +396 -0
- package/src/scripts/programmatic_exec_agent.ts +231 -0
- package/src/scripts/tool_search_regex.ts +162 -0
- package/src/test/mockTools.ts +366 -0
- package/src/tools/ProgrammaticToolCalling.ts +423 -0
- package/src/tools/ToolNode.ts +38 -4
- package/src/tools/ToolSearchRegex.ts +535 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +318 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +613 -0
- package/src/tools/__tests__/ToolSearchRegex.integration.test.ts +161 -0
- package/src/tools/__tests__/ToolSearchRegex.test.ts +232 -0
- package/src/types/graph.ts +7 -1
- package/src/types/tools.ts +166 -0
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
// src/tools/ToolSearchRegex.ts
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { config } from 'dotenv';
|
|
4
|
+
import fetch, { RequestInit } from 'node-fetch';
|
|
5
|
+
import { HttpsProxyAgent } from 'https-proxy-agent';
|
|
6
|
+
import { getEnvironmentVariable } from '@langchain/core/utils/env';
|
|
7
|
+
import { tool, DynamicStructuredTool } from '@langchain/core/tools';
|
|
8
|
+
import type * as t from '@/types';
|
|
9
|
+
import { getCodeBaseURL } from './CodeExecutor';
|
|
10
|
+
import { EnvVar, Constants } from '@/common';
|
|
11
|
+
|
|
12
|
+
config();
|
|
13
|
+
|
|
14
|
+
/** Maximum allowed regex pattern length */
|
|
15
|
+
const MAX_PATTERN_LENGTH = 200;
|
|
16
|
+
|
|
17
|
+
/** Maximum allowed regex nesting depth */
|
|
18
|
+
const MAX_REGEX_COMPLEXITY = 5;
|
|
19
|
+
|
|
20
|
+
/** Default search timeout in milliseconds */
|
|
21
|
+
const SEARCH_TIMEOUT = 5000;
|
|
22
|
+
|
|
23
|
+
const ToolSearchRegexSchema = z.object({
|
|
24
|
+
query: z
|
|
25
|
+
.string()
|
|
26
|
+
.min(1)
|
|
27
|
+
.max(MAX_PATTERN_LENGTH)
|
|
28
|
+
.describe(
|
|
29
|
+
'Regex pattern to search tool names and descriptions. Special regex characters will be sanitized for safety.'
|
|
30
|
+
),
|
|
31
|
+
fields: z
|
|
32
|
+
.array(z.enum(['name', 'description', 'parameters']))
|
|
33
|
+
.optional()
|
|
34
|
+
.default(['name', 'description'])
|
|
35
|
+
.describe('Which fields to search. Default: name and description'),
|
|
36
|
+
max_results: z
|
|
37
|
+
.number()
|
|
38
|
+
.int()
|
|
39
|
+
.min(1)
|
|
40
|
+
.max(50)
|
|
41
|
+
.optional()
|
|
42
|
+
.default(10)
|
|
43
|
+
.describe('Maximum number of matching tools to return'),
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Escapes special regex characters in a string to use as a literal pattern.
|
|
48
|
+
* @param pattern - The string to escape
|
|
49
|
+
* @returns The escaped string safe for use in a RegExp
|
|
50
|
+
*/
|
|
51
|
+
function escapeRegexSpecialChars(pattern: string): string {
|
|
52
|
+
return pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Counts the maximum nesting depth of groups in a regex pattern.
|
|
57
|
+
* @param pattern - The regex pattern to analyze
|
|
58
|
+
* @returns The maximum nesting depth
|
|
59
|
+
*/
|
|
60
|
+
function countNestedGroups(pattern: string): number {
|
|
61
|
+
let maxDepth = 0;
|
|
62
|
+
let currentDepth = 0;
|
|
63
|
+
|
|
64
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
65
|
+
if (pattern[i] === '(' && (i === 0 || pattern[i - 1] !== '\\')) {
|
|
66
|
+
currentDepth++;
|
|
67
|
+
maxDepth = Math.max(maxDepth, currentDepth);
|
|
68
|
+
} else if (pattern[i] === ')' && (i === 0 || pattern[i - 1] !== '\\')) {
|
|
69
|
+
currentDepth = Math.max(0, currentDepth - 1);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return maxDepth;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Detects nested quantifiers that can cause catastrophic backtracking.
|
|
78
|
+
* Patterns like (a+)+, (a*)*, (a+)*, etc.
|
|
79
|
+
* @param pattern - The regex pattern to check
|
|
80
|
+
* @returns True if nested quantifiers are detected
|
|
81
|
+
*/
|
|
82
|
+
function hasNestedQuantifiers(pattern: string): boolean {
|
|
83
|
+
const nestedQuantifierPattern = /\([^)]*[+*][^)]*\)[+*?]/;
|
|
84
|
+
return nestedQuantifierPattern.test(pattern);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Checks if a regex pattern contains potentially dangerous constructs.
|
|
89
|
+
* @param pattern - The regex pattern to validate
|
|
90
|
+
* @returns True if the pattern is dangerous
|
|
91
|
+
*/
|
|
92
|
+
function isDangerousPattern(pattern: string): boolean {
|
|
93
|
+
if (hasNestedQuantifiers(pattern)) {
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (countNestedGroups(pattern) > MAX_REGEX_COMPLEXITY) {
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const dangerousPatterns = [
|
|
102
|
+
/\.\{1000,\}/, // Excessive wildcards
|
|
103
|
+
/\(\?=\.\{100,\}\)/, // Runaway lookaheads
|
|
104
|
+
/\([^)]*\|\s*\){20,}/, // Excessive alternation (rough check)
|
|
105
|
+
/\(\.\*\)\+/, // (.*)+
|
|
106
|
+
/\(\.\+\)\+/, // (.+)+
|
|
107
|
+
/\(\.\*\)\*/, // (.*)*
|
|
108
|
+
/\(\.\+\)\*/, // (.+)*
|
|
109
|
+
];
|
|
110
|
+
|
|
111
|
+
for (const dangerous of dangerousPatterns) {
|
|
112
|
+
if (dangerous.test(pattern)) {
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Sanitizes a regex pattern for safe execution.
|
|
122
|
+
* If the pattern is dangerous, it will be escaped to a literal string search.
|
|
123
|
+
* @param pattern - The regex pattern to sanitize
|
|
124
|
+
* @returns Object containing the safe pattern and whether it was escaped
|
|
125
|
+
*/
|
|
126
|
+
function sanitizeRegex(pattern: string): { safe: string; wasEscaped: boolean } {
|
|
127
|
+
if (isDangerousPattern(pattern)) {
|
|
128
|
+
return {
|
|
129
|
+
safe: escapeRegexSpecialChars(pattern),
|
|
130
|
+
wasEscaped: true,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
try {
|
|
135
|
+
new RegExp(pattern);
|
|
136
|
+
return { safe: pattern, wasEscaped: false };
|
|
137
|
+
} catch {
|
|
138
|
+
return {
|
|
139
|
+
safe: escapeRegexSpecialChars(pattern),
|
|
140
|
+
wasEscaped: true,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Simplifies tool parameters for search purposes.
|
|
147
|
+
* Extracts only the essential structure needed for parameter name searching.
|
|
148
|
+
* @param parameters - The tool's JSON schema parameters
|
|
149
|
+
* @returns Simplified parameters object
|
|
150
|
+
*/
|
|
151
|
+
function simplifyParametersForSearch(
|
|
152
|
+
parameters?: t.JsonSchemaType
|
|
153
|
+
): t.JsonSchemaType | undefined {
|
|
154
|
+
if (!parameters) {
|
|
155
|
+
return undefined;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (parameters.properties) {
|
|
159
|
+
return {
|
|
160
|
+
type: parameters.type,
|
|
161
|
+
properties: Object.fromEntries(
|
|
162
|
+
Object.entries(parameters.properties).map(([key, value]) => [
|
|
163
|
+
key,
|
|
164
|
+
{ type: (value as t.JsonSchemaType).type },
|
|
165
|
+
])
|
|
166
|
+
),
|
|
167
|
+
} as t.JsonSchemaType;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
return { type: parameters.type };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Generates the JavaScript search script to be executed in the sandbox.
|
|
175
|
+
* Uses plain JavaScript for maximum compatibility with the Code API.
|
|
176
|
+
* @param deferredTools - Array of tool metadata to search through
|
|
177
|
+
* @param fields - Which fields to search
|
|
178
|
+
* @param maxResults - Maximum number of results to return
|
|
179
|
+
* @param sanitizedPattern - The sanitized regex pattern
|
|
180
|
+
* @returns The JavaScript code string
|
|
181
|
+
*/
|
|
182
|
+
function generateSearchScript(
|
|
183
|
+
deferredTools: t.ToolMetadata[],
|
|
184
|
+
fields: string[],
|
|
185
|
+
maxResults: number,
|
|
186
|
+
sanitizedPattern: string
|
|
187
|
+
): string {
|
|
188
|
+
const lines = [
|
|
189
|
+
'// Tool definitions (injected)',
|
|
190
|
+
'var tools = ' + JSON.stringify(deferredTools) + ';',
|
|
191
|
+
'var searchFields = ' + JSON.stringify(fields) + ';',
|
|
192
|
+
'var maxResults = ' + maxResults + ';',
|
|
193
|
+
'var pattern = ' + JSON.stringify(sanitizedPattern) + ';',
|
|
194
|
+
'',
|
|
195
|
+
'// Compile regex (pattern is sanitized client-side)',
|
|
196
|
+
'var regex;',
|
|
197
|
+
'try {',
|
|
198
|
+
' regex = new RegExp(pattern, \'i\');',
|
|
199
|
+
'} catch (e) {',
|
|
200
|
+
' regex = new RegExp(pattern.replace(/[.*+?^${}()[\\]\\\\|]/g, "\\\\$&"), "i");',
|
|
201
|
+
'}',
|
|
202
|
+
'',
|
|
203
|
+
'// Search logic',
|
|
204
|
+
'var results = [];',
|
|
205
|
+
'',
|
|
206
|
+
'for (var j = 0; j < tools.length; j++) {',
|
|
207
|
+
' var tool = tools[j];',
|
|
208
|
+
' var bestScore = 0;',
|
|
209
|
+
' var matchedField = \'\';',
|
|
210
|
+
' var snippet = \'\';',
|
|
211
|
+
'',
|
|
212
|
+
' // Search name (highest priority)',
|
|
213
|
+
' if (searchFields.indexOf(\'name\') >= 0 && regex.test(tool.name)) {',
|
|
214
|
+
' bestScore = 0.95;',
|
|
215
|
+
' matchedField = \'name\';',
|
|
216
|
+
' snippet = tool.name;',
|
|
217
|
+
' }',
|
|
218
|
+
'',
|
|
219
|
+
' // Search description (medium priority)',
|
|
220
|
+
' if (searchFields.indexOf(\'description\') >= 0 && tool.description && regex.test(tool.description)) {',
|
|
221
|
+
' if (bestScore === 0) {',
|
|
222
|
+
' bestScore = 0.75;',
|
|
223
|
+
' matchedField = \'description\';',
|
|
224
|
+
' snippet = tool.description.substring(0, 100);',
|
|
225
|
+
' }',
|
|
226
|
+
' }',
|
|
227
|
+
'',
|
|
228
|
+
' // Search parameter names (lower priority)',
|
|
229
|
+
' if (searchFields.indexOf(\'parameters\') >= 0 && tool.parameters && tool.parameters.properties) {',
|
|
230
|
+
' var paramNames = Object.keys(tool.parameters.properties).join(\' \');',
|
|
231
|
+
' if (regex.test(paramNames)) {',
|
|
232
|
+
' if (bestScore === 0) {',
|
|
233
|
+
' bestScore = 0.60;',
|
|
234
|
+
' matchedField = \'parameters\';',
|
|
235
|
+
' snippet = paramNames;',
|
|
236
|
+
' }',
|
|
237
|
+
' }',
|
|
238
|
+
' }',
|
|
239
|
+
'',
|
|
240
|
+
' if (bestScore > 0) {',
|
|
241
|
+
' results.push({',
|
|
242
|
+
' tool_name: tool.name,',
|
|
243
|
+
' match_score: bestScore,',
|
|
244
|
+
' matched_field: matchedField,',
|
|
245
|
+
' snippet: snippet',
|
|
246
|
+
' });',
|
|
247
|
+
' }',
|
|
248
|
+
'}',
|
|
249
|
+
'',
|
|
250
|
+
'// Sort by score (descending) and limit results',
|
|
251
|
+
'results.sort(function(a, b) { return b.match_score - a.match_score; });',
|
|
252
|
+
'var topResults = results.slice(0, maxResults);',
|
|
253
|
+
'',
|
|
254
|
+
'// Output as JSON',
|
|
255
|
+
'console.log(JSON.stringify({',
|
|
256
|
+
' tool_references: topResults.map(function(r) {',
|
|
257
|
+
' return {',
|
|
258
|
+
' tool_name: r.tool_name,',
|
|
259
|
+
' match_score: r.match_score,',
|
|
260
|
+
' matched_field: r.matched_field,',
|
|
261
|
+
' snippet: r.snippet',
|
|
262
|
+
' };',
|
|
263
|
+
' }),',
|
|
264
|
+
' total_tools_searched: tools.length,',
|
|
265
|
+
' pattern_used: pattern',
|
|
266
|
+
'}));',
|
|
267
|
+
];
|
|
268
|
+
return lines.join('\n');
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Parses the search results from stdout JSON.
|
|
273
|
+
* @param stdout - The stdout string containing JSON results
|
|
274
|
+
* @returns Parsed search response
|
|
275
|
+
*/
|
|
276
|
+
function parseSearchResults(stdout: string): t.ToolSearchResponse {
|
|
277
|
+
const jsonMatch = stdout.trim();
|
|
278
|
+
const parsed = JSON.parse(jsonMatch) as t.ToolSearchResponse;
|
|
279
|
+
return parsed;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Formats search results into a human-readable string.
|
|
284
|
+
* @param searchResponse - The parsed search response
|
|
285
|
+
* @returns Formatted string for LLM consumption
|
|
286
|
+
*/
|
|
287
|
+
function formatSearchResults(searchResponse: t.ToolSearchResponse): string {
|
|
288
|
+
const { tool_references, total_tools_searched, pattern_used } =
|
|
289
|
+
searchResponse;
|
|
290
|
+
|
|
291
|
+
if (tool_references.length === 0) {
|
|
292
|
+
return `No tools matched the pattern "${pattern_used}".\nTotal tools searched: ${total_tools_searched}`;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
let response = `Found ${tool_references.length} matching tools:\n\n`;
|
|
296
|
+
|
|
297
|
+
for (const ref of tool_references) {
|
|
298
|
+
response += `- ${ref.tool_name} (score: ${ref.match_score.toFixed(2)})\n`;
|
|
299
|
+
response += ` Matched in: ${ref.matched_field}\n`;
|
|
300
|
+
response += ` Snippet: ${ref.snippet}\n\n`;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
response += `Total tools searched: ${total_tools_searched}\n`;
|
|
304
|
+
response += `Pattern used: ${pattern_used}`;
|
|
305
|
+
|
|
306
|
+
return response;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Creates a Tool Search Regex tool for discovering tools from a large registry.
|
|
311
|
+
*
|
|
312
|
+
* This tool enables AI agents to dynamically discover tools from a large library
|
|
313
|
+
* without loading all tool definitions into the LLM context window. The agent
|
|
314
|
+
* can search for relevant tools on-demand using regex patterns.
|
|
315
|
+
*
|
|
316
|
+
* The tool registry can be provided either:
|
|
317
|
+
* 1. At initialization time via params.toolRegistry
|
|
318
|
+
* 2. At runtime via config.configurable.toolRegistry when invoking
|
|
319
|
+
*
|
|
320
|
+
* @param params - Configuration parameters for the tool (toolRegistry is optional)
|
|
321
|
+
* @returns A LangChain DynamicStructuredTool for tool searching
|
|
322
|
+
*
|
|
323
|
+
* @example
|
|
324
|
+
* // Option 1: Registry at initialization
|
|
325
|
+
* const tool = createToolSearchRegexTool({ apiKey, toolRegistry });
|
|
326
|
+
* await tool.invoke({ query: 'expense' });
|
|
327
|
+
*
|
|
328
|
+
* @example
|
|
329
|
+
* // Option 2: Registry at runtime
|
|
330
|
+
* const tool = createToolSearchRegexTool({ apiKey });
|
|
331
|
+
* await tool.invoke(
|
|
332
|
+
* { query: 'expense' },
|
|
333
|
+
* { configurable: { toolRegistry, onlyDeferred: true } }
|
|
334
|
+
* );
|
|
335
|
+
*/
|
|
336
|
+
function createToolSearchRegexTool(
|
|
337
|
+
initParams: t.ToolSearchRegexParams = {}
|
|
338
|
+
): DynamicStructuredTool<typeof ToolSearchRegexSchema> {
|
|
339
|
+
const apiKey: string =
|
|
340
|
+
(initParams[EnvVar.CODE_API_KEY] as string | undefined) ??
|
|
341
|
+
initParams.apiKey ??
|
|
342
|
+
getEnvironmentVariable(EnvVar.CODE_API_KEY) ??
|
|
343
|
+
'';
|
|
344
|
+
|
|
345
|
+
if (!apiKey) {
|
|
346
|
+
throw new Error('No API key provided for tool search regex tool.');
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const baseEndpoint = initParams.baseUrl ?? getCodeBaseURL();
|
|
350
|
+
const EXEC_ENDPOINT = `${baseEndpoint}/exec`;
|
|
351
|
+
const defaultOnlyDeferred = initParams.onlyDeferred ?? true;
|
|
352
|
+
|
|
353
|
+
const description = `
|
|
354
|
+
Searches through available tools to find ones matching your query pattern.
|
|
355
|
+
|
|
356
|
+
Usage:
|
|
357
|
+
- Provide a regex pattern to search tool names and descriptions.
|
|
358
|
+
- Use this when you need to discover tools for a specific task.
|
|
359
|
+
- Results include tool names, match quality scores, and snippets showing where the match occurred.
|
|
360
|
+
- Higher scores (0.9+) indicate name matches, medium scores (0.7+) indicate description matches.
|
|
361
|
+
`.trim();
|
|
362
|
+
|
|
363
|
+
return tool<typeof ToolSearchRegexSchema>(
|
|
364
|
+
async (params, config) => {
|
|
365
|
+
const {
|
|
366
|
+
query,
|
|
367
|
+
fields = ['name', 'description'],
|
|
368
|
+
max_results = 10,
|
|
369
|
+
} = params;
|
|
370
|
+
|
|
371
|
+
// Extra params injected by ToolNode (follows web_search pattern)
|
|
372
|
+
const {
|
|
373
|
+
toolRegistry: paramToolRegistry,
|
|
374
|
+
onlyDeferred: paramOnlyDeferred,
|
|
375
|
+
} = config.toolCall ?? {};
|
|
376
|
+
|
|
377
|
+
const { safe: sanitizedPattern, wasEscaped } = sanitizeRegex(query);
|
|
378
|
+
|
|
379
|
+
let warningMessage = '';
|
|
380
|
+
if (wasEscaped) {
|
|
381
|
+
warningMessage =
|
|
382
|
+
'Note: The provided pattern was converted to a literal search for safety.\n\n';
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// Priority: ToolNode injection (via config.toolCall) > initialization params
|
|
386
|
+
const toolRegistry = paramToolRegistry ?? initParams.toolRegistry;
|
|
387
|
+
const onlyDeferred =
|
|
388
|
+
paramOnlyDeferred !== undefined
|
|
389
|
+
? paramOnlyDeferred
|
|
390
|
+
: defaultOnlyDeferred;
|
|
391
|
+
|
|
392
|
+
if (toolRegistry == null) {
|
|
393
|
+
return [
|
|
394
|
+
`${warningMessage}Error: No tool registry provided. Configure toolRegistry at agent level or initialization.`,
|
|
395
|
+
{
|
|
396
|
+
tool_references: [],
|
|
397
|
+
metadata: {
|
|
398
|
+
total_searched: 0,
|
|
399
|
+
pattern: sanitizedPattern,
|
|
400
|
+
error: 'No tool registry provided',
|
|
401
|
+
},
|
|
402
|
+
},
|
|
403
|
+
];
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const toolsArray: t.LCTool[] = Array.from(toolRegistry.values());
|
|
407
|
+
|
|
408
|
+
const deferredTools: t.ToolMetadata[] = toolsArray
|
|
409
|
+
.filter((lcTool) => {
|
|
410
|
+
if (onlyDeferred === true) {
|
|
411
|
+
return lcTool.defer_loading === true;
|
|
412
|
+
}
|
|
413
|
+
return true;
|
|
414
|
+
})
|
|
415
|
+
.map((lcTool) => ({
|
|
416
|
+
name: lcTool.name,
|
|
417
|
+
description: lcTool.description ?? '',
|
|
418
|
+
parameters: simplifyParametersForSearch(lcTool.parameters),
|
|
419
|
+
}));
|
|
420
|
+
|
|
421
|
+
if (deferredTools.length === 0) {
|
|
422
|
+
return [
|
|
423
|
+
`${warningMessage}No tools available to search. The tool registry is empty or no deferred tools are registered.`,
|
|
424
|
+
{
|
|
425
|
+
tool_references: [],
|
|
426
|
+
metadata: {
|
|
427
|
+
total_searched: 0,
|
|
428
|
+
pattern: sanitizedPattern,
|
|
429
|
+
},
|
|
430
|
+
},
|
|
431
|
+
];
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
const searchScript = generateSearchScript(
|
|
435
|
+
deferredTools,
|
|
436
|
+
fields,
|
|
437
|
+
max_results,
|
|
438
|
+
sanitizedPattern
|
|
439
|
+
);
|
|
440
|
+
|
|
441
|
+
const postData = {
|
|
442
|
+
lang: 'js',
|
|
443
|
+
code: searchScript,
|
|
444
|
+
timeout: SEARCH_TIMEOUT,
|
|
445
|
+
};
|
|
446
|
+
|
|
447
|
+
try {
|
|
448
|
+
const fetchOptions: RequestInit = {
|
|
449
|
+
method: 'POST',
|
|
450
|
+
headers: {
|
|
451
|
+
'Content-Type': 'application/json',
|
|
452
|
+
'User-Agent': 'LibreChat/1.0',
|
|
453
|
+
'X-API-Key': apiKey,
|
|
454
|
+
},
|
|
455
|
+
body: JSON.stringify(postData),
|
|
456
|
+
};
|
|
457
|
+
|
|
458
|
+
if (process.env.PROXY != null && process.env.PROXY !== '') {
|
|
459
|
+
fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
const response = await fetch(EXEC_ENDPOINT, fetchOptions);
|
|
463
|
+
if (!response.ok) {
|
|
464
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const result: t.ExecuteResult = await response.json();
|
|
468
|
+
|
|
469
|
+
if (result.stderr && result.stderr.trim()) {
|
|
470
|
+
// eslint-disable-next-line no-console
|
|
471
|
+
console.warn('[ToolSearchRegex] stderr:', result.stderr);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
if (!result.stdout || !result.stdout.trim()) {
|
|
475
|
+
return [
|
|
476
|
+
`${warningMessage}No tools matched the pattern "${sanitizedPattern}".\nTotal tools searched: ${deferredTools.length}`,
|
|
477
|
+
{
|
|
478
|
+
tool_references: [],
|
|
479
|
+
metadata: {
|
|
480
|
+
total_searched: deferredTools.length,
|
|
481
|
+
pattern: sanitizedPattern,
|
|
482
|
+
},
|
|
483
|
+
},
|
|
484
|
+
];
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
const searchResponse = parseSearchResults(result.stdout);
|
|
488
|
+
const formattedOutput = `${warningMessage}${formatSearchResults(searchResponse)}`;
|
|
489
|
+
|
|
490
|
+
return [
|
|
491
|
+
formattedOutput,
|
|
492
|
+
{
|
|
493
|
+
tool_references: searchResponse.tool_references,
|
|
494
|
+
metadata: {
|
|
495
|
+
total_searched: searchResponse.total_tools_searched,
|
|
496
|
+
pattern: searchResponse.pattern_used,
|
|
497
|
+
},
|
|
498
|
+
},
|
|
499
|
+
];
|
|
500
|
+
} catch (error) {
|
|
501
|
+
// eslint-disable-next-line no-console
|
|
502
|
+
console.error('[ToolSearchRegex] Error:', error);
|
|
503
|
+
|
|
504
|
+
const errorMessage =
|
|
505
|
+
error instanceof Error ? error.message : String(error);
|
|
506
|
+
return [
|
|
507
|
+
`Tool search failed: ${errorMessage}\n\nSuggestion: Try a simpler search pattern or search for specific tool names.`,
|
|
508
|
+
{
|
|
509
|
+
tool_references: [],
|
|
510
|
+
metadata: {
|
|
511
|
+
total_searched: 0,
|
|
512
|
+
pattern: sanitizedPattern,
|
|
513
|
+
error: errorMessage,
|
|
514
|
+
},
|
|
515
|
+
},
|
|
516
|
+
];
|
|
517
|
+
}
|
|
518
|
+
},
|
|
519
|
+
{
|
|
520
|
+
name: Constants.TOOL_SEARCH_REGEX,
|
|
521
|
+
description,
|
|
522
|
+
schema: ToolSearchRegexSchema,
|
|
523
|
+
responseFormat: Constants.CONTENT_AND_ARTIFACT,
|
|
524
|
+
}
|
|
525
|
+
);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
export {
|
|
529
|
+
createToolSearchRegexTool,
|
|
530
|
+
sanitizeRegex,
|
|
531
|
+
escapeRegexSpecialChars,
|
|
532
|
+
isDangerousPattern,
|
|
533
|
+
countNestedGroups,
|
|
534
|
+
hasNestedQuantifiers,
|
|
535
|
+
};
|