@librechat/agents 3.2.66 → 3.2.68

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 (35) hide show
  1. package/dist/cjs/hooks/createToolPolicyHook.cjs +5 -5
  2. package/dist/cjs/hooks/createToolPolicyHook.cjs.map +1 -1
  3. package/dist/cjs/llm/google/index.cjs +2 -0
  4. package/dist/cjs/llm/google/index.cjs.map +1 -1
  5. package/dist/cjs/llm/google/utils/common.cjs +28 -0
  6. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  7. package/dist/cjs/tools/ToolSearch.cjs +59 -14
  8. package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
  9. package/dist/cjs/tools/search/tool.cjs +5 -3
  10. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  11. package/dist/esm/hooks/createToolPolicyHook.mjs +5 -5
  12. package/dist/esm/hooks/createToolPolicyHook.mjs.map +1 -1
  13. package/dist/esm/llm/google/index.mjs +3 -1
  14. package/dist/esm/llm/google/index.mjs.map +1 -1
  15. package/dist/esm/llm/google/utils/common.mjs +28 -1
  16. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  17. package/dist/esm/tools/ToolSearch.mjs +59 -14
  18. package/dist/esm/tools/ToolSearch.mjs.map +1 -1
  19. package/dist/esm/tools/search/tool.mjs +5 -3
  20. package/dist/esm/tools/search/tool.mjs.map +1 -1
  21. package/dist/types/hooks/createToolPolicyHook.d.ts +12 -15
  22. package/dist/types/llm/google/utils/common.d.ts +9 -0
  23. package/dist/types/tools/search/types.d.ts +2 -0
  24. package/package.json +1 -1
  25. package/src/hooks/__tests__/createToolPolicyHook.test.ts +13 -4
  26. package/src/hooks/createToolPolicyHook.ts +16 -19
  27. package/src/llm/google/index.ts +3 -0
  28. package/src/llm/google/utils/common.test.ts +57 -2
  29. package/src/llm/google/utils/common.ts +44 -0
  30. package/src/tools/ToolSearch.ts +81 -23
  31. package/src/tools/__tests__/ToolSearch.test.ts +151 -0
  32. package/src/tools/__tests__/hitl.test.ts +114 -1
  33. package/src/tools/search/source-processing.test.ts +57 -0
  34. package/src/tools/search/tool.ts +13 -1
  35. package/src/tools/search/types.ts +2 -0
@@ -1 +1 @@
1
- {"version":3,"file":"ToolSearch.cjs","names":["okapibm25Module","getCodeBaseURL","params","HttpsProxyAgent"],"sources":["../../../src/tools/ToolSearch.ts"],"sourcesContent":["// src/tools/ToolSearch.ts\nimport { config } from 'dotenv';\nimport * as okapibm25Module from 'okapibm25';\n\ntype BM25Fn = (\n documents: string[],\n keywords: string[],\n constants?: { k1?: number; b?: number }\n) => number[];\n\nfunction getBM25Function(): BM25Fn {\n const mod = okapibm25Module as unknown as {\n default: BM25Fn | { default: BM25Fn } | undefined;\n };\n if (typeof mod === 'function') return mod;\n if (typeof mod.default === 'function') return mod.default;\n if (mod.default != null && typeof mod.default.default === 'function')\n return mod.default.default;\n throw new Error('Could not resolve BM25 function from okapibm25 module');\n}\n\nconst BM25 = getBM25Function();\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { getCodeBaseURL } from './CodeExecutor';\nimport { Constants } from '@/common';\n\nconfig();\n\n/** Maximum allowed regex pattern length */\nconst MAX_PATTERN_LENGTH = 200;\n\nexport const ToolSearchToolName = Constants.TOOL_SEARCH;\n\nexport const ToolSearchToolDescription =\n 'Searches deferred tools using BM25 ranking. Multi-word queries supported. Use mcp_server param to filter by server.';\n\nconst QUERY_DESCRIPTION_LOCAL =\n 'Search term to find in tool names and descriptions. Case-insensitive substring matching. Optional if mcp_server is provided.';\nconst QUERY_DESCRIPTION_REGEX =\n 'Regex pattern to search tool names and descriptions. Optional if mcp_server is provided.';\nconst FIELDS_DESCRIPTION =\n 'Which fields to search. Default: name and description';\nconst MAX_RESULTS_DESCRIPTION = 'Maximum number of matching tools to return';\nconst DEFAULT_MAX_RESULTS = 5;\nconst MCP_SERVER_DESCRIPTION =\n 'Filter to tools from specific MCP server(s). Can be a single server name or array of names. If provided without a query, lists all tools from those servers.';\n\nexport const ToolSearchToolSchema = {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n maxLength: MAX_PATTERN_LENGTH,\n default: '',\n description: QUERY_DESCRIPTION_LOCAL,\n },\n fields: {\n type: 'array',\n items: { type: 'string', enum: ['name', 'description', 'parameters'] },\n default: ['name', 'description'],\n description: FIELDS_DESCRIPTION,\n },\n max_results: {\n type: 'integer',\n minimum: 1,\n maximum: 50,\n default: DEFAULT_MAX_RESULTS,\n description: MAX_RESULTS_DESCRIPTION,\n },\n mcp_server: {\n oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }],\n description: MCP_SERVER_DESCRIPTION,\n },\n },\n required: [],\n} as const;\n\nexport const ToolSearchToolDefinition = {\n name: ToolSearchToolName,\n description: ToolSearchToolDescription,\n schema: ToolSearchToolSchema,\n} as const;\n\n/** Maximum allowed regex nesting depth */\nconst MAX_REGEX_COMPLEXITY = 5;\n\n/** Default search timeout in milliseconds */\nconst SEARCH_TIMEOUT = 5000;\n\n/** JSON schema type for tool search parameters */\ninterface ToolSearchSchema {\n type: 'object';\n properties: Record<string, unknown>;\n required: string[];\n}\n\n/** Input params type for tool search */\ninterface ToolSearchParams {\n query?: string;\n fields?: ('name' | 'description' | 'parameters')[];\n max_results?: number;\n mcp_server?: string | string[];\n}\n\n/**\n * Creates the JSON schema with dynamic query description based on mode.\n * @param mode - The search mode determining query interpretation\n * @returns JSON schema for tool search parameters\n */\nfunction createToolSearchSchema(mode: t.ToolSearchMode): ToolSearchSchema {\n const queryDescription =\n mode === 'local' ? QUERY_DESCRIPTION_LOCAL : QUERY_DESCRIPTION_REGEX;\n\n return {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n maxLength: MAX_PATTERN_LENGTH,\n default: '',\n description: queryDescription,\n },\n fields: {\n type: 'array',\n items: { type: 'string', enum: ['name', 'description', 'parameters'] },\n default: ['name', 'description'],\n description: FIELDS_DESCRIPTION,\n },\n max_results: {\n type: 'integer',\n minimum: 1,\n maximum: 50,\n default: DEFAULT_MAX_RESULTS,\n description: MAX_RESULTS_DESCRIPTION,\n },\n mcp_server: {\n oneOf: [\n { type: 'string' },\n { type: 'array', items: { type: 'string' } },\n ],\n description: MCP_SERVER_DESCRIPTION,\n },\n },\n required: [],\n };\n}\n\n/**\n * Extracts the MCP server name from a tool name.\n * MCP tools follow the pattern: toolName_mcp_serverName\n * @param toolName - The full tool name\n * @returns The server name if it's an MCP tool, undefined otherwise\n */\nfunction extractMcpServerName(toolName: string): string | undefined {\n const delimiterIndex = toolName.indexOf(Constants.MCP_DELIMITER);\n if (delimiterIndex === -1) {\n return undefined;\n }\n return toolName.substring(delimiterIndex + Constants.MCP_DELIMITER.length);\n}\n\n/**\n * Checks if a tool belongs to a specific MCP server.\n * @param toolName - The full tool name\n * @param serverName - The server name to match\n * @returns True if the tool belongs to the specified server\n */\nfunction isFromMcpServer(toolName: string, serverName: string): boolean {\n const toolServer = extractMcpServerName(toolName);\n return toolServer === serverName;\n}\n\n/**\n * Checks if a tool belongs to any of the specified MCP servers.\n * @param toolName - The full tool name\n * @param serverNames - Array of server names to match\n * @returns True if the tool belongs to any of the specified servers\n */\nfunction isFromAnyMcpServer(toolName: string, serverNames: string[]): boolean {\n const toolServer = extractMcpServerName(toolName);\n if (toolServer === undefined) {\n return false;\n }\n return serverNames.includes(toolServer);\n}\n\n/**\n * Normalizes server filter input to always be an array.\n * @param serverFilter - String, array of strings, or undefined\n * @returns Array of server names (empty if none specified)\n */\nfunction normalizeServerFilter(\n serverFilter: string | string[] | undefined\n): string[] {\n if (serverFilter === undefined) {\n return [];\n }\n if (typeof serverFilter === 'string') {\n return serverFilter === '' ? [] : [serverFilter];\n }\n return serverFilter.filter((s) => s !== '');\n}\n\n/**\n * Extracts all unique MCP server names from a tool registry.\n * @param toolRegistry - The tool registry to scan\n * @param onlyDeferred - If true, only considers deferred tools\n * @returns Array of unique server names, sorted alphabetically\n */\nfunction getAvailableMcpServers(\n toolRegistry: t.LCToolRegistry | undefined,\n onlyDeferred: boolean = true\n): string[] {\n if (!toolRegistry) {\n return [];\n }\n\n const servers = new Set<string>();\n for (const [, toolDef] of toolRegistry) {\n if (onlyDeferred && toolDef.defer_loading !== true) {\n continue;\n }\n const server = extractMcpServerName(toolDef.name);\n if (server !== undefined && server !== '') {\n servers.add(server);\n }\n }\n\n return Array.from(servers).sort();\n}\n\n/**\n * Escapes special regex characters in a string to use as a literal pattern.\n * @param pattern - The string to escape\n * @returns The escaped string safe for use in a RegExp\n */\nfunction escapeRegexSpecialChars(pattern: string): string {\n return pattern.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Counts the maximum nesting depth of groups in a regex pattern.\n * @param pattern - The regex pattern to analyze\n * @returns The maximum nesting depth\n */\nfunction countNestedGroups(pattern: string): number {\n let maxDepth = 0;\n let currentDepth = 0;\n\n for (let i = 0; i < pattern.length; i++) {\n if (pattern[i] === '(' && (i === 0 || pattern[i - 1] !== '\\\\')) {\n currentDepth++;\n maxDepth = Math.max(maxDepth, currentDepth);\n } else if (pattern[i] === ')' && (i === 0 || pattern[i - 1] !== '\\\\')) {\n currentDepth = Math.max(0, currentDepth - 1);\n }\n }\n\n return maxDepth;\n}\n\n/**\n * Detects nested quantifiers that can cause catastrophic backtracking.\n * Patterns like (a+)+, (a*)*, (a+)*, etc.\n * @param pattern - The regex pattern to check\n * @returns True if nested quantifiers are detected\n */\nfunction hasNestedQuantifiers(pattern: string): boolean {\n const nestedQuantifierPattern = /\\([^)]*[+*][^)]*\\)[+*?]/;\n return nestedQuantifierPattern.test(pattern);\n}\n\n/**\n * Checks if a regex pattern contains potentially dangerous constructs.\n * @param pattern - The regex pattern to validate\n * @returns True if the pattern is dangerous\n */\nfunction isDangerousPattern(pattern: string): boolean {\n if (hasNestedQuantifiers(pattern)) {\n return true;\n }\n\n if (countNestedGroups(pattern) > MAX_REGEX_COMPLEXITY) {\n return true;\n }\n\n const dangerousPatterns = [\n /\\.\\{1000,\\}/, // Excessive wildcards\n /\\(\\?=\\.\\{100,\\}\\)/, // Runaway lookaheads\n /\\([^)]*\\|\\s*\\){20,}/, // Excessive alternation (rough check)\n /\\(\\.\\*\\)\\+/, // (.*)+\n /\\(\\.\\+\\)\\+/, // (.+)+\n /\\(\\.\\*\\)\\*/, // (.*)*\n /\\(\\.\\+\\)\\*/, // (.+)*\n ];\n\n for (const dangerous of dangerousPatterns) {\n if (dangerous.test(pattern)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Sanitizes a regex pattern for safe execution.\n * If the pattern is dangerous, it will be escaped to a literal string search.\n * @param pattern - The regex pattern to sanitize\n * @returns Object containing the safe pattern and whether it was escaped\n */\nfunction sanitizeRegex(pattern: string): { safe: string; wasEscaped: boolean } {\n if (isDangerousPattern(pattern)) {\n return {\n safe: escapeRegexSpecialChars(pattern),\n wasEscaped: true,\n };\n }\n\n try {\n new RegExp(pattern);\n return { safe: pattern, wasEscaped: false };\n } catch {\n return {\n safe: escapeRegexSpecialChars(pattern),\n wasEscaped: true,\n };\n }\n}\n\n/**\n * Simplifies tool parameters for search purposes.\n * Extracts only the essential structure needed for parameter name searching.\n * @param parameters - The tool's JSON schema parameters\n * @returns Simplified parameters object\n */\nfunction simplifyParametersForSearch(\n parameters?: t.JsonSchemaType\n): t.JsonSchemaType | undefined {\n if (!parameters) {\n return undefined;\n }\n\n if (parameters.properties) {\n return {\n type: parameters.type,\n properties: Object.fromEntries(\n Object.entries(parameters.properties).map(([key, value]) => [\n key,\n { type: (value as t.JsonSchemaType).type },\n ])\n ),\n } as t.JsonSchemaType;\n }\n\n return { type: parameters.type };\n}\n\n/**\n * Tokenizes a string into lowercase words for BM25.\n * Splits on underscores and non-alphanumeric characters for consistent matching.\n * @param text - The text to tokenize\n * @returns Array of lowercase tokens\n */\nfunction tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9]/g, ' ')\n .split(/\\s+/)\n .filter((token) => token.length > 0);\n}\n\n/**\n * Creates a searchable document string from tool metadata.\n * @param tool - The tool metadata\n * @param fields - Which fields to include\n * @returns Combined document string for BM25\n */\nfunction createToolDocument(tool: t.ToolMetadata, fields: string[]): string {\n const parts: string[] = [];\n\n if (fields.includes('name')) {\n const baseName = tool.name.replace(/_/g, ' ');\n parts.push(baseName, baseName);\n }\n\n if (fields.includes('description') && tool.description) {\n parts.push(tool.description);\n }\n\n if (fields.includes('parameters') && tool.parameters?.properties) {\n const paramNames = Object.keys(tool.parameters.properties).join(' ');\n parts.push(paramNames);\n }\n\n return parts.join(' ');\n}\n\n/**\n * Determines which field had the best match for a query.\n * @param tool - The tool to check\n * @param queryTokens - Tokenized query\n * @param fields - Fields to check\n * @returns The matched field and a snippet\n */\nfunction findMatchedField(\n tool: t.ToolMetadata,\n queryTokens: string[],\n fields: string[]\n): { field: string; snippet: string } {\n if (fields.includes('name')) {\n const nameLower = tool.name.toLowerCase();\n for (const token of queryTokens) {\n if (nameLower.includes(token)) {\n return { field: 'name', snippet: tool.name };\n }\n }\n }\n\n if (fields.includes('description') && tool.description) {\n const descLower = tool.description.toLowerCase();\n for (const token of queryTokens) {\n if (descLower.includes(token)) {\n return {\n field: 'description',\n snippet: tool.description.substring(0, 100),\n };\n }\n }\n }\n\n if (fields.includes('parameters') && tool.parameters?.properties) {\n const paramNames = Object.keys(tool.parameters.properties);\n const paramLower = paramNames.join(' ').toLowerCase();\n for (const token of queryTokens) {\n if (paramLower.includes(token)) {\n return { field: 'parameters', snippet: paramNames.join(', ') };\n }\n }\n }\n\n const fallbackSnippet = tool.description\n ? tool.description.substring(0, 100)\n : tool.name;\n return { field: 'unknown', snippet: fallbackSnippet };\n}\n\n/**\n * Performs BM25-based search for better relevance ranking.\n * Uses Okapi BM25 algorithm for term frequency and document length normalization.\n * If query is empty, returns all tools (up to maxResults) sorted alphabetically.\n * @param tools - Array of tool metadata to search\n * @param query - The search query (empty returns all tools)\n * @param fields - Which fields to search\n * @param maxResults - Maximum results to return\n * @returns Search response with matching tools ranked by BM25 score\n */\nfunction performLocalSearch(\n tools: t.ToolMetadata[],\n query: string,\n fields: string[],\n maxResults: number\n): t.ToolSearchResponse {\n if (tools.length === 0) {\n return {\n tool_references: [],\n total_tools_searched: 0,\n pattern_used: query,\n };\n }\n\n const queryTokens = tokenize(query);\n\n if (queryTokens.length === 0) {\n const allTools = tools\n .slice()\n .sort((a, b) => a.name.localeCompare(b.name))\n .slice(0, maxResults)\n .map((tool) => ({\n tool_name: tool.name,\n match_score: 1.0,\n matched_field: 'name',\n snippet: tool.description.substring(0, 100) || tool.name,\n }));\n\n return {\n tool_references: allTools,\n total_tools_searched: tools.length,\n pattern_used: query,\n };\n }\n\n const documents = tools.map((tool) => createToolDocument(tool, fields));\n const scores = BM25(documents, queryTokens, { k1: 1.5, b: 0.75 }) as number[];\n\n const maxScore = Math.max(...scores.filter((s) => s > 0), 1);\n const queryLower = query.toLowerCase().trim();\n\n const results: t.ToolSearchResult[] = [];\n for (let i = 0; i < tools.length; i++) {\n if (scores[i] > 0) {\n const { field, snippet } = findMatchedField(\n tools[i],\n queryTokens,\n fields\n );\n let normalizedScore = Math.min(scores[i] / maxScore, 1.0);\n\n const baseName = getBaseToolName(tools[i].name).toLowerCase();\n if (baseName === queryLower) {\n normalizedScore = 1.0;\n } else if (baseName.startsWith(queryLower)) {\n normalizedScore = Math.max(normalizedScore, 0.95);\n }\n\n results.push({\n tool_name: tools[i].name,\n match_score: normalizedScore,\n matched_field: field,\n snippet,\n });\n }\n }\n\n results.sort((a, b) => b.match_score - a.match_score);\n const topResults = results.slice(0, maxResults);\n\n return {\n tool_references: topResults,\n total_tools_searched: tools.length,\n pattern_used: query,\n };\n}\n\n/**\n * Generates the JavaScript search script to be executed in the sandbox.\n * Uses plain JavaScript for maximum compatibility with the Code API.\n * @param deferredTools - Array of tool metadata to search through\n * @param fields - Which fields to search\n * @param maxResults - Maximum number of results to return\n * @param sanitizedPattern - The sanitized regex pattern\n * @returns The JavaScript code string\n */\nfunction generateSearchScript(\n deferredTools: t.ToolMetadata[],\n fields: string[],\n maxResults: number,\n sanitizedPattern: string\n): string {\n const lines = [\n '// Tool definitions (injected)',\n 'var tools = ' + JSON.stringify(deferredTools) + ';',\n 'var searchFields = ' + JSON.stringify(fields) + ';',\n 'var maxResults = ' + maxResults + ';',\n 'var pattern = ' + JSON.stringify(sanitizedPattern) + ';',\n '',\n '// Compile regex (pattern is sanitized client-side)',\n 'var regex;',\n 'try {',\n ' regex = new RegExp(pattern, \\'i\\');',\n '} catch (e) {',\n ' regex = new RegExp(pattern.replace(/[.*+?^${}()[\\\\]\\\\\\\\|]/g, \"\\\\\\\\$&\"), \"i\");',\n '}',\n '',\n '// Search logic',\n 'var results = [];',\n '',\n 'for (var j = 0; j < tools.length; j++) {',\n ' var tool = tools[j];',\n ' var bestScore = 0;',\n ' var matchedField = \\'\\';',\n ' var snippet = \\'\\';',\n '',\n ' // Search name (highest priority)',\n ' if (searchFields.indexOf(\\'name\\') >= 0 && regex.test(tool.name)) {',\n ' bestScore = 0.95;',\n ' matchedField = \\'name\\';',\n ' snippet = tool.name;',\n ' }',\n '',\n ' // Search description (medium priority)',\n ' if (searchFields.indexOf(\\'description\\') >= 0 && tool.description && regex.test(tool.description)) {',\n ' if (bestScore === 0) {',\n ' bestScore = 0.75;',\n ' matchedField = \\'description\\';',\n ' snippet = tool.description.substring(0, 100);',\n ' }',\n ' }',\n '',\n ' // Search parameter names (lower priority)',\n ' if (searchFields.indexOf(\\'parameters\\') >= 0 && tool.parameters && tool.parameters.properties) {',\n ' var paramNames = Object.keys(tool.parameters.properties).join(\\' \\');',\n ' if (regex.test(paramNames)) {',\n ' if (bestScore === 0) {',\n ' bestScore = 0.60;',\n ' matchedField = \\'parameters\\';',\n ' snippet = paramNames;',\n ' }',\n ' }',\n ' }',\n '',\n ' if (bestScore > 0) {',\n ' results.push({',\n ' tool_name: tool.name,',\n ' match_score: bestScore,',\n ' matched_field: matchedField,',\n ' snippet: snippet',\n ' });',\n ' }',\n '}',\n '',\n '// Sort by score (descending) and limit results',\n 'results.sort(function(a, b) { return b.match_score - a.match_score; });',\n 'var topResults = results.slice(0, maxResults);',\n '',\n '// Output as JSON',\n 'console.log(JSON.stringify({',\n ' tool_references: topResults.map(function(r) {',\n ' return {',\n ' tool_name: r.tool_name,',\n ' match_score: r.match_score,',\n ' matched_field: r.matched_field,',\n ' snippet: r.snippet',\n ' };',\n ' }),',\n ' total_tools_searched: tools.length,',\n ' pattern_used: pattern',\n '}));',\n ];\n return lines.join('\\n');\n}\n\n/**\n * Parses the search results from stdout JSON.\n * @param stdout - The stdout string containing JSON results\n * @returns Parsed search response\n */\nfunction parseSearchResults(stdout: string): t.ToolSearchResponse {\n const jsonMatch = stdout.trim();\n const parsed = JSON.parse(jsonMatch) as t.ToolSearchResponse;\n return parsed;\n}\n\n/**\n * Formats search results as structured JSON for efficient parsing.\n * @param searchResponse - The parsed search response\n * @param nameFormat - Whether to show 'full' names (tool_mcp_server) or 'base' names (tool only)\n * @returns JSON string with search results\n */\nfunction formatSearchResults(\n searchResponse: t.ToolSearchResponse,\n nameFormat: t.McpNameFormat = 'full'\n): string {\n const { tool_references, total_tools_searched, pattern_used } =\n searchResponse;\n const useFullName = nameFormat === 'full';\n\n const output = {\n found: tool_references.length,\n tools: tool_references.map((ref) => ({\n name: useFullName ? ref.tool_name : getBaseToolName(ref.tool_name),\n score: Number(ref.match_score.toFixed(2)),\n matched_in: ref.matched_field,\n snippet: ref.snippet,\n })),\n total_searched: total_tools_searched,\n query: pattern_used,\n };\n\n return JSON.stringify(output, null, 2);\n}\n\n/**\n * Extracts the base tool name (without MCP server suffix) from a full tool name.\n * @param toolName - The full tool name\n * @returns The base tool name without server suffix\n */\nfunction getBaseToolName(toolName: string): string {\n const delimiterIndex = toolName.indexOf(Constants.MCP_DELIMITER);\n if (delimiterIndex === -1) {\n return toolName;\n }\n return toolName.substring(0, delimiterIndex);\n}\n\n/**\n * Checks whether a tool has any defined parameters in its JSON schema.\n * @param parameters - The tool's JSON schema parameters\n * @returns true if the tool has at least one parameter property\n */\nfunction hasParams(parameters?: t.JsonSchemaType): boolean {\n return (\n parameters?.properties != null &&\n Object.keys(parameters.properties).length > 0\n );\n}\n\n/**\n * Generates a compact listing of deferred tools grouped by server.\n * Format: \"server: tool1, tool2(\\u2026), tool3\"\n * Tools with parameters are annotated with (\\u2026) to signal\n * that the LLM should discover the schema via tool_search before calling.\n * Non-MCP tools are grouped under \"other\".\n * @param toolRegistry - The tool registry\n * @param onlyDeferred - Whether to only include deferred tools\n * @returns Formatted string with tools grouped by server\n */\nfunction getDeferredToolsListing(\n toolRegistry: t.LCToolRegistry | undefined,\n onlyDeferred: boolean\n): string {\n if (!toolRegistry) {\n return '';\n }\n\n const toolsByServer: Record<string, string[]> = {};\n\n for (const lcTool of toolRegistry.values()) {\n if (onlyDeferred && lcTool.defer_loading !== true) {\n continue;\n }\n\n const toolName = lcTool.name;\n const serverName = extractMcpServerName(toolName) ?? 'other';\n const baseName = getBaseToolName(toolName);\n const displayName = hasParams(lcTool.parameters)\n ? `${baseName}(\\u2026)`\n : baseName;\n\n if (!(serverName in toolsByServer)) {\n toolsByServer[serverName] = [];\n }\n toolsByServer[serverName].push(displayName);\n }\n\n const serverNames = Object.keys(toolsByServer).sort((a, b) => {\n if (a === 'other') return 1;\n if (b === 'other') return -1;\n return a.localeCompare(b);\n });\n\n if (serverNames.length === 0) {\n return '';\n }\n\n const lines = serverNames.map(\n (server) => `${server}: ${toolsByServer[server].join(', ')}`\n );\n\n return lines.join('\\n');\n}\n\n/**\n * Formats a server listing response as structured JSON.\n * NOTE: This is a PREVIEW only - tools are NOT discovered/loaded.\n * @param tools - Array of tool metadata from the server(s)\n * @param serverNames - The MCP server name(s)\n * @param nameFormat - Whether to show 'full' names (tool_mcp_server) or 'base' names (tool only)\n * @returns JSON string showing all tools grouped by server\n */\nfunction formatServerListing(\n tools: t.ToolMetadata[],\n serverNames: string | string[],\n nameFormat: t.McpNameFormat = 'full'\n): string {\n const servers = Array.isArray(serverNames) ? serverNames : [serverNames];\n const useFullName = nameFormat === 'full';\n\n if (tools.length === 0) {\n return JSON.stringify(\n {\n listing_mode: true,\n servers,\n total_tools: 0,\n tools_by_server: {},\n hint: 'No tools found from the specified MCP server(s).',\n },\n null,\n 2\n );\n }\n\n const toolsByServer: Record<\n string,\n Array<{ name: string; description: string }>\n > = {};\n for (const tool of tools) {\n const server = extractMcpServerName(tool.name) ?? 'unknown';\n if (!(server in toolsByServer)) {\n toolsByServer[server] = [];\n }\n toolsByServer[server].push({\n name: useFullName ? tool.name : getBaseToolName(tool.name),\n description:\n tool.description.length > 100\n ? tool.description.substring(0, 97) + '...'\n : tool.description,\n });\n }\n\n const exampleToolName = useFullName\n ? (tools[0]?.name ?? 'tool_name')\n : getBaseToolName(tools[0]?.name ?? 'tool_name');\n\n const output = {\n listing_mode: true,\n servers,\n total_tools: tools.length,\n tools_by_server: toolsByServer,\n hint: `To use a tool, search for it by name (e.g., query: \"${exampleToolName}\") to load it.`,\n };\n\n return JSON.stringify(output, null, 2);\n}\n\n/**\n * Creates a Tool Search tool for discovering tools from a large registry.\n *\n * This tool enables AI agents to dynamically discover tools from a large library\n * without loading all tool definitions into the LLM context window. The agent\n * can search for relevant tools on-demand.\n *\n * **Modes:**\n * - `code_interpreter` (default): Uses external sandbox for regex search. Safer for complex patterns.\n * - `local`: Uses safe substring matching locally. No network call, faster, completely safe from ReDoS.\n *\n * The tool registry can be provided either:\n * 1. At initialization time via params.toolRegistry\n * 2. At runtime via config.configurable.toolRegistry when invoking\n *\n * @param params - Configuration parameters for the tool (toolRegistry is optional)\n * @returns A LangChain DynamicStructuredTool for tool searching\n *\n * @example\n * // Option 1: Code interpreter mode (regex via sandbox)\n * const tool = createToolSearch({ toolRegistry });\n * await tool.invoke({ query: 'expense.*report' });\n *\n * @example\n * // Option 2: Local mode (safe substring search)\n * const tool = createToolSearch({ mode: 'local', toolRegistry });\n * await tool.invoke({ query: 'expense' });\n */\nfunction createToolSearch(\n initParams: t.ToolSearchParams = {}\n): DynamicStructuredTool {\n const mode: t.ToolSearchMode = initParams.mode ?? 'code_interpreter';\n const defaultOnlyDeferred = initParams.onlyDeferred ?? true;\n const mcpNameFormat: t.McpNameFormat = initParams.mcpNameFormat ?? 'full';\n const schema = createToolSearchSchema(mode);\n\n const baseEndpoint = initParams.baseUrl ?? getCodeBaseURL();\n const EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\n const deferredToolsListing = getDeferredToolsListing(\n initParams.toolRegistry,\n defaultOnlyDeferred\n );\n\n const toolsListSection =\n deferredToolsListing.length > 0\n ? `\n\nDeferred tools (search to load; \\u2026 = has params, search first):\n${deferredToolsListing}`\n : '';\n\n const mcpNote =\n deferredToolsListing.includes(Constants.MCP_DELIMITER) ||\n deferredToolsListing.split('\\n').some((line) => !line.startsWith('other:'))\n ? `\n- MCP tools use format: toolName${Constants.MCP_DELIMITER}serverName\n- Use mcp_server param to filter by server`\n : '';\n\n const description =\n mode === 'local'\n ? `\nSearches deferred tools using BM25 ranking. Multi-word queries supported.\n${mcpNote}${toolsListSection}\n`.trim()\n : `\nSearches deferred tools by regex pattern.\n${mcpNote}${toolsListSection}\n`.trim();\n\n return tool(\n async (rawParams, config) => {\n const params = rawParams as ToolSearchParams;\n const {\n query = '',\n fields = ['name', 'description'],\n max_results = DEFAULT_MAX_RESULTS,\n mcp_server,\n } = params;\n\n const {\n toolRegistry: paramToolRegistry,\n onlyDeferred: paramOnlyDeferred,\n mcpServer: paramMcpServer,\n } = config.toolCall ?? {};\n\n const toolRegistry = paramToolRegistry ?? initParams.toolRegistry;\n const onlyDeferred =\n paramOnlyDeferred !== undefined\n ? paramOnlyDeferred\n : defaultOnlyDeferred;\n const rawServerFilter =\n mcp_server ?? paramMcpServer ?? initParams.mcpServer;\n const serverFilters = normalizeServerFilter(rawServerFilter);\n const hasServerFilter = serverFilters.length > 0;\n\n if (toolRegistry == null) {\n return [\n 'Error: No tool registry provided. Configure toolRegistry at agent level or initialization.',\n {\n tool_references: [],\n metadata: {\n total_searched: 0,\n pattern: query,\n error: 'No tool registry provided',\n },\n },\n ];\n }\n\n const toolsArray: t.LCTool[] = Array.from(toolRegistry.values());\n const deferredTools: t.ToolMetadata[] = toolsArray\n .filter((lcTool) => {\n if (onlyDeferred === true && lcTool.defer_loading !== true) {\n return false;\n }\n if (\n hasServerFilter &&\n !isFromAnyMcpServer(lcTool.name, serverFilters)\n ) {\n return false;\n }\n return true;\n })\n .map((lcTool) => ({\n name: lcTool.name,\n description: lcTool.description ?? '',\n parameters: simplifyParametersForSearch(lcTool.parameters),\n }));\n\n if (deferredTools.length === 0) {\n const serverMsg = hasServerFilter\n ? ` from MCP server(s): ${serverFilters.join(', ')}`\n : '';\n return [\n `No tools available to search${serverMsg}. The tool registry is empty or no matching deferred tools are registered.`,\n {\n tool_references: [],\n metadata: {\n total_searched: 0,\n pattern: query,\n mcp_server: serverFilters,\n },\n },\n ];\n }\n\n const isServerListing = hasServerFilter && query === '';\n\n if (isServerListing) {\n const formattedOutput = formatServerListing(\n deferredTools,\n serverFilters,\n mcpNameFormat\n );\n\n return [\n formattedOutput,\n {\n tool_references: [],\n metadata: {\n total_available: deferredTools.length,\n mcp_server: serverFilters,\n listing_mode: true,\n },\n },\n ];\n }\n\n if (mode === 'local') {\n const searchResponse = performLocalSearch(\n deferredTools,\n query,\n fields,\n max_results\n );\n const formattedOutput = formatSearchResults(\n searchResponse,\n mcpNameFormat\n );\n\n return [\n formattedOutput,\n {\n tool_references: searchResponse.tool_references,\n metadata: {\n total_searched: searchResponse.total_tools_searched,\n pattern: searchResponse.pattern_used,\n mcp_server: serverFilters.length > 0 ? serverFilters : undefined,\n },\n },\n ];\n }\n\n const { safe: sanitizedPattern, wasEscaped } = sanitizeRegex(query);\n let warningMessage = '';\n if (wasEscaped) {\n warningMessage =\n 'Note: The provided pattern was converted to a literal search for safety.\\n\\n';\n }\n\n const searchScript = generateSearchScript(\n deferredTools,\n fields,\n max_results,\n sanitizedPattern\n );\n\n const postData = {\n lang: 'js',\n code: searchScript,\n timeout: SEARCH_TIMEOUT,\n };\n\n try {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const result: t.ExecuteResult = await response.json();\n\n if (result.stderr && result.stderr.trim()) {\n // eslint-disable-next-line no-console\n console.warn('[ToolSearch] stderr:', result.stderr);\n }\n\n if (!result.stdout || !result.stdout.trim()) {\n return [\n `${warningMessage}No tools matched the pattern \"${sanitizedPattern}\".\\nTotal tools searched: ${deferredTools.length}`,\n {\n tool_references: [],\n metadata: {\n total_searched: deferredTools.length,\n pattern: sanitizedPattern,\n },\n },\n ];\n }\n\n const searchResponse = parseSearchResults(result.stdout);\n const formattedOutput = `${warningMessage}${formatSearchResults(searchResponse, mcpNameFormat)}`;\n\n return [\n formattedOutput,\n {\n tool_references: searchResponse.tool_references,\n metadata: {\n total_searched: searchResponse.total_tools_searched,\n pattern: searchResponse.pattern_used,\n },\n },\n ];\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[ToolSearch] Error:', error);\n\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n return [\n `Tool search failed: ${errorMessage}\\n\\nSuggestion: Try a simpler search pattern or search for specific tool names.`,\n {\n tool_references: [],\n metadata: {\n total_searched: 0,\n pattern: sanitizedPattern,\n error: errorMessage,\n },\n },\n ];\n }\n },\n {\n name: Constants.TOOL_SEARCH,\n description,\n schema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport {\n createToolSearch,\n performLocalSearch,\n extractMcpServerName,\n isFromMcpServer,\n isFromAnyMcpServer,\n normalizeServerFilter,\n getAvailableMcpServers,\n getDeferredToolsListing,\n getBaseToolName,\n formatServerListing,\n sanitizeRegex,\n escapeRegexSpecialChars,\n isDangerousPattern,\n countNestedGroups,\n hasNestedQuantifiers,\n};\n"],"mappings":";;;;;;;;;;;;AAUA,SAAS,kBAA0B;CACjC,MAAM,MAAMA;CAGZ,IAAI,OAAO,QAAQ,YAAY,OAAO;CACtC,IAAI,OAAO,IAAI,YAAY,YAAY,OAAO,IAAI;CAClD,IAAI,IAAI,WAAW,QAAQ,OAAO,IAAI,QAAQ,YAAY,YACxD,OAAO,IAAI,QAAQ;CACrB,MAAM,IAAI,MAAM,uDAAuD;AACzE;AAEA,MAAM,OAAO,gBAAgB;mBAQtB;;AAGP,MAAM,qBAAqB;AAE3B,MAAa,qBAAA;AAEb,MAAa,4BACX;AAEF,MAAM,0BACJ;AACF,MAAM,0BACJ;AACF,MAAM,qBACJ;AACF,MAAM,0BAA0B;AAChC,MAAM,sBAAsB;AAC5B,MAAM,yBACJ;AAEF,MAAa,uBAAuB;CAClC,MAAM;CACN,YAAY;EACV,OAAO;GACL,MAAM;GACN,WAAW;GACX,SAAS;GACT,aAAa;EACf;EACA,QAAQ;GACN,MAAM;GACN,OAAO;IAAE,MAAM;IAAU,MAAM;KAAC;KAAQ;KAAe;IAAY;GAAE;GACrE,SAAS,CAAC,QAAQ,aAAa;GAC/B,aAAa;EACf;EACA,aAAa;GACX,MAAM;GACN,SAAS;GACT,SAAS;GACT,SAAS;GACT,aAAa;EACf;EACA,YAAY;GACV,OAAO,CAAC,EAAE,MAAM,SAAS,GAAG;IAAE,MAAM;IAAS,OAAO,EAAE,MAAM,SAAS;GAAE,CAAC;GACxE,aAAa;EACf;CACF;CACA,UAAU,CAAC;AACb;AAEA,MAAa,2BAA2B;CACtC,MAAM;CACN,aAAa;CACb,QAAQ;AACV;;AAGA,MAAM,uBAAuB;;AAG7B,M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,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,uBAAuB,SAAS,QAAQ;GAG1D,MAAM,SAA0B,MAAM,SAAS,KAAK;GAEpD,IAAI,OAAO,UAAU,OAAO,OAAO,KAAK,GAEtC,QAAQ,KAAK,wBAAwB,OAAO,MAAM;GAGpD,IAAI,CAAC,OAAO,UAAU,CAAC,OAAO,OAAO,KAAK,GACxC,OAAO,CACL,GAAG,eAAe,gCAAgC,iBAAiB,4BAA4B,cAAc,UAC7G;IACE,iBAAiB,CAAC;IAClB,UAAU;KACR,gBAAgB,cAAc;KAC9B,SAAS;IACX;GACF,CACF;GAGF,MAAM,iBAAiB,mBAAmB,OAAO,MAAM;GAGvD,OAAO,CACL,GAHyB,iBAAiB,oBAAoB,gBAAgB,aAAa,KAI3F;IACE,iBAAiB,eAAe;IAChC,UAAU;KACR,gBAAgB,eAAe;KAC/B,SAAS,eAAe;IAC1B;GACF,CACF;EACF,SAAS,OAAO;GAEd,QAAQ,MAAM,uBAAuB,KAAK;GAE1C,MAAM,eACJ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACvD,OAAO,CACL,uBAAuB,aAAa,kFACpC;IACE,iBAAiB,CAAC;IAClB,UAAU;KACR,gBAAgB;KAChB,SAAS;KACT,OAAO;IACT;GACF,CACF;EACF;CACF,GACA;EACE,MAAA;EACA;EACA;EACA,gBAAA;CACF,CACF;AACF"}
1
+ {"version":3,"file":"ToolSearch.cjs","names":["okapibm25Module","getCodeBaseURL","params","HttpsProxyAgent"],"sources":["../../../src/tools/ToolSearch.ts"],"sourcesContent":["// src/tools/ToolSearch.ts\nimport { config } from 'dotenv';\nimport * as okapibm25Module from 'okapibm25';\n\ntype BM25Fn = (\n documents: string[],\n keywords: string[],\n constants?: { k1?: number; b?: number }\n) => number[];\n\nfunction getBM25Function(): BM25Fn {\n const mod = okapibm25Module as unknown as {\n default: BM25Fn | { default: BM25Fn } | undefined;\n };\n if (typeof mod === 'function') return mod;\n if (typeof mod.default === 'function') return mod.default;\n if (mod.default != null && typeof mod.default.default === 'function')\n return mod.default.default;\n throw new Error('Could not resolve BM25 function from okapibm25 module');\n}\n\nconst BM25 = getBM25Function();\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { getCodeBaseURL } from './CodeExecutor';\nimport { Constants } from '@/common';\n\nconfig();\n\n/** Maximum allowed regex pattern length */\nconst MAX_PATTERN_LENGTH = 200;\n\nexport const ToolSearchToolName = Constants.TOOL_SEARCH;\n\nexport const ToolSearchToolDescription =\n 'Searches deferred tools using BM25 ranking. Multi-word queries supported. Use mcp_server param to filter by server.';\n\nconst QUERY_DESCRIPTION_LOCAL =\n 'Search term to find in tool names and descriptions. Case-insensitive substring matching. Optional if mcp_server is provided.';\nconst QUERY_DESCRIPTION_REGEX =\n 'Regex pattern to search tool names and descriptions. Optional if mcp_server is provided.';\nconst FIELDS_DESCRIPTION =\n 'Which fields to search. Default: name and description';\nconst MAX_RESULTS_DESCRIPTION = 'Maximum number of matching tools to return';\nconst DEFAULT_MAX_RESULTS = 5;\nconst MCP_SERVER_DESCRIPTION =\n 'Filter to tools from specific MCP server(s). Can be a single server name or array of names. If provided without a query, lists all tools from those servers.';\n\nexport const ToolSearchToolSchema = {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n maxLength: MAX_PATTERN_LENGTH,\n default: '',\n description: QUERY_DESCRIPTION_LOCAL,\n },\n fields: {\n type: 'array',\n items: { type: 'string', enum: ['name', 'description', 'parameters'] },\n default: ['name', 'description'],\n description: FIELDS_DESCRIPTION,\n },\n max_results: {\n type: 'integer',\n minimum: 1,\n maximum: 50,\n default: DEFAULT_MAX_RESULTS,\n description: MAX_RESULTS_DESCRIPTION,\n },\n mcp_server: {\n oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }],\n description: MCP_SERVER_DESCRIPTION,\n },\n },\n required: [],\n} as const;\n\nexport const ToolSearchToolDefinition = {\n name: ToolSearchToolName,\n description: ToolSearchToolDescription,\n schema: ToolSearchToolSchema,\n} as const;\n\n/** Maximum allowed regex nesting depth */\nconst MAX_REGEX_COMPLEXITY = 5;\n\n/** Default search timeout in milliseconds */\nconst SEARCH_TIMEOUT = 5000;\n\n/** JSON schema type for tool search parameters */\ninterface ToolSearchSchema {\n type: 'object';\n properties: Record<string, unknown>;\n required: string[];\n}\n\n/** Input params type for tool search */\ninterface ToolSearchParams {\n query?: string;\n fields?: ('name' | 'description' | 'parameters')[];\n max_results?: number;\n mcp_server?: string | string[];\n}\n\n/**\n * Creates the JSON schema with dynamic query description based on mode.\n * @param mode - The search mode determining query interpretation\n * @returns JSON schema for tool search parameters\n */\nfunction createToolSearchSchema(mode: t.ToolSearchMode): ToolSearchSchema {\n const queryDescription =\n mode === 'local' ? QUERY_DESCRIPTION_LOCAL : QUERY_DESCRIPTION_REGEX;\n\n return {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n maxLength: MAX_PATTERN_LENGTH,\n default: '',\n description: queryDescription,\n },\n fields: {\n type: 'array',\n items: { type: 'string', enum: ['name', 'description', 'parameters'] },\n default: ['name', 'description'],\n description: FIELDS_DESCRIPTION,\n },\n max_results: {\n type: 'integer',\n minimum: 1,\n maximum: 50,\n default: DEFAULT_MAX_RESULTS,\n description: MAX_RESULTS_DESCRIPTION,\n },\n mcp_server: {\n oneOf: [\n { type: 'string' },\n { type: 'array', items: { type: 'string' } },\n ],\n description: MCP_SERVER_DESCRIPTION,\n },\n },\n required: [],\n };\n}\n\n/**\n * Extracts the MCP server name from a tool name.\n * MCP tools follow the pattern: toolName_mcp_serverName\n * @param toolName - The full tool name\n * @returns The server name if it's an MCP tool, undefined otherwise\n */\nfunction extractMcpServerName(toolName: string): string | undefined {\n const delimiterIndex = toolName.indexOf(Constants.MCP_DELIMITER);\n if (delimiterIndex === -1) {\n return undefined;\n }\n return toolName.substring(delimiterIndex + Constants.MCP_DELIMITER.length);\n}\n\n/**\n * Checks if a tool belongs to a specific MCP server.\n * @param toolName - The full tool name\n * @param serverName - The server name to match\n * @returns True if the tool belongs to the specified server\n */\nfunction isFromMcpServer(toolName: string, serverName: string): boolean {\n const toolServer = extractMcpServerName(toolName);\n return toolServer === serverName;\n}\n\n/**\n * Checks if a tool belongs to any of the specified MCP servers.\n * @param toolName - The full tool name\n * @param serverNames - Array of server names to match\n * @returns True if the tool belongs to any of the specified servers\n */\nfunction isFromAnyMcpServer(toolName: string, serverNames: string[]): boolean {\n const toolServer = extractMcpServerName(toolName);\n if (toolServer === undefined) {\n return false;\n }\n return serverNames.includes(toolServer);\n}\n\n/**\n * Normalizes server filter input to always be an array.\n * @param serverFilter - String, array of strings, or undefined\n * @returns Array of server names (empty if none specified)\n */\nfunction normalizeServerFilter(\n serverFilter: string | string[] | undefined\n): string[] {\n if (serverFilter === undefined) {\n return [];\n }\n if (typeof serverFilter === 'string') {\n return serverFilter === '' ? [] : [serverFilter];\n }\n return serverFilter.filter((s) => s !== '');\n}\n\n/**\n * Extracts all unique MCP server names from a tool registry.\n * @param toolRegistry - The tool registry to scan\n * @param onlyDeferred - If true, only considers deferred tools\n * @returns Array of unique server names, sorted alphabetically\n */\nfunction getAvailableMcpServers(\n toolRegistry: t.LCToolRegistry | undefined,\n onlyDeferred: boolean = true\n): string[] {\n if (!toolRegistry) {\n return [];\n }\n\n const servers = new Set<string>();\n for (const [, toolDef] of toolRegistry) {\n if (onlyDeferred && toolDef.defer_loading !== true) {\n continue;\n }\n const server = extractMcpServerName(toolDef.name);\n if (server !== undefined && server !== '') {\n servers.add(server);\n }\n }\n\n return Array.from(servers).sort();\n}\n\n/**\n * Escapes special regex characters in a string to use as a literal pattern.\n * @param pattern - The string to escape\n * @returns The escaped string safe for use in a RegExp\n */\nfunction escapeRegexSpecialChars(pattern: string): string {\n return pattern.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Counts the maximum nesting depth of groups in a regex pattern.\n * @param pattern - The regex pattern to analyze\n * @returns The maximum nesting depth\n */\nfunction countNestedGroups(pattern: string): number {\n let maxDepth = 0;\n let currentDepth = 0;\n\n for (let i = 0; i < pattern.length; i++) {\n if (pattern[i] === '(' && (i === 0 || pattern[i - 1] !== '\\\\')) {\n currentDepth++;\n maxDepth = Math.max(maxDepth, currentDepth);\n } else if (pattern[i] === ')' && (i === 0 || pattern[i - 1] !== '\\\\')) {\n currentDepth = Math.max(0, currentDepth - 1);\n }\n }\n\n return maxDepth;\n}\n\n/**\n * Detects nested quantifiers that can cause catastrophic backtracking.\n * Patterns like (a+)+, (a*)*, (a+)*, etc.\n * @param pattern - The regex pattern to check\n * @returns True if nested quantifiers are detected\n */\nfunction hasNestedQuantifiers(pattern: string): boolean {\n const nestedQuantifierPattern = /\\([^)]*[+*][^)]*\\)[+*?]/;\n return nestedQuantifierPattern.test(pattern);\n}\n\n/**\n * Checks if a regex pattern contains potentially dangerous constructs.\n * @param pattern - The regex pattern to validate\n * @returns True if the pattern is dangerous\n */\nfunction isDangerousPattern(pattern: string): boolean {\n if (hasNestedQuantifiers(pattern)) {\n return true;\n }\n\n if (countNestedGroups(pattern) > MAX_REGEX_COMPLEXITY) {\n return true;\n }\n\n const dangerousPatterns = [\n /\\.\\{1000,\\}/, // Excessive wildcards\n /\\(\\?=\\.\\{100,\\}\\)/, // Runaway lookaheads\n /\\([^)]*\\|\\s*\\){20,}/, // Excessive alternation (rough check)\n /\\(\\.\\*\\)\\+/, // (.*)+\n /\\(\\.\\+\\)\\+/, // (.+)+\n /\\(\\.\\*\\)\\*/, // (.*)*\n /\\(\\.\\+\\)\\*/, // (.+)*\n ];\n\n for (const dangerous of dangerousPatterns) {\n if (dangerous.test(pattern)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Sanitizes a regex pattern for safe execution.\n * If the pattern is dangerous, it will be escaped to a literal string search.\n * @param pattern - The regex pattern to sanitize\n * @returns Object containing the safe pattern and whether it was escaped\n */\nfunction sanitizeRegex(pattern: string): { safe: string; wasEscaped: boolean } {\n if (isDangerousPattern(pattern)) {\n return {\n safe: escapeRegexSpecialChars(pattern),\n wasEscaped: true,\n };\n }\n\n try {\n new RegExp(pattern);\n return { safe: pattern, wasEscaped: false };\n } catch {\n return {\n safe: escapeRegexSpecialChars(pattern),\n wasEscaped: true,\n };\n }\n}\n\n/**\n * Simplifies tool parameters for search purposes.\n * Extracts only the essential structure needed for parameter name searching.\n * @param parameters - The tool's JSON schema parameters\n * @returns Simplified parameters object\n */\nfunction simplifyParametersForSearch(\n parameters?: t.JsonSchemaType\n): t.JsonSchemaType | undefined {\n if (!parameters) {\n return undefined;\n }\n\n if (parameters.properties) {\n return {\n type: parameters.type,\n properties: Object.fromEntries(\n Object.entries(parameters.properties).map(([key, value]) => [\n key,\n { type: (value as t.JsonSchemaType).type },\n ])\n ),\n } as t.JsonSchemaType;\n }\n\n return { type: parameters.type };\n}\n\n/**\n * Splits one alphanumeric identifier segment on case boundaries without\n * emitting artificial one-character acronym fragments.\n */\nfunction splitCaseSegment(segment: string): string[] {\n const splitTokens = segment\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .toLowerCase()\n .split(/\\s+/)\n .filter(Boolean);\n\n if (splitTokens.length < 2) return splitTokens;\n\n const mergedTokens: string[] = [];\n let prefix = '';\n for (const token of splitTokens) {\n if (token.length === 1) {\n prefix += token;\n continue;\n }\n mergedTokens.push(`${prefix}${token}`);\n prefix = '';\n }\n\n if (prefix && mergedTokens.length > 0) {\n mergedTokens[mergedTokens.length - 1] += prefix;\n }\n return mergedTokens.length > 0 ? mergedTokens : [prefix];\n}\n\n/**\n * Tokenizes a string into lowercase words for BM25.\n * Splits camelCase, underscores, and non-alphanumeric characters for consistent matching.\n * @param text - The text to tokenize\n * @returns Array of lowercase tokens\n */\nfunction tokenize(text: string): string[] {\n return text\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean)\n .flatMap(splitCaseSegment);\n}\n\n/**\n * Creates a searchable document string from tool metadata.\n * @param tool - The tool metadata\n * @param fields - Which fields to include\n * @returns Combined document string for BM25\n */\nfunction createToolDocument(tool: t.ToolMetadata, fields: string[]): string {\n const parts: string[] = [];\n\n if (fields.includes('name')) {\n const baseName = tool.name.replace(/_/g, ' ');\n parts.push(baseName, baseName);\n }\n\n if (fields.includes('description') && tool.description) {\n parts.push(tool.description);\n }\n\n if (fields.includes('parameters') && tool.parameters?.properties) {\n const paramNames = Object.keys(tool.parameters.properties).join(' ');\n parts.push(paramNames);\n }\n\n return tokenize(parts.join(' ')).join(' ');\n}\n\n/**\n * Determines which field had the best match for a query.\n * @param tool - The tool to check\n * @param queryTokens - Tokenized query\n * @param fields - Fields to check\n * @returns The matched field and a snippet\n */\nfunction findMatchedField(\n tool: t.ToolMetadata,\n queryTokens: string[],\n fields: string[]\n): { field: string; snippet: string } {\n if (fields.includes('name')) {\n const nameLower = tool.name.toLowerCase();\n for (const token of queryTokens) {\n if (nameLower.includes(token)) {\n return { field: 'name', snippet: tool.name };\n }\n }\n }\n\n if (fields.includes('description') && tool.description) {\n const descLower = tool.description.toLowerCase();\n for (const token of queryTokens) {\n if (descLower.includes(token)) {\n return {\n field: 'description',\n snippet: tool.description.substring(0, 100),\n };\n }\n }\n }\n\n if (fields.includes('parameters') && tool.parameters?.properties) {\n const paramNames = Object.keys(tool.parameters.properties);\n const paramLower = paramNames.join(' ').toLowerCase();\n for (const token of queryTokens) {\n if (paramLower.includes(token)) {\n return { field: 'parameters', snippet: paramNames.join(', ') };\n }\n }\n }\n\n const fallbackSnippet = tool.description\n ? tool.description.substring(0, 100)\n : tool.name;\n return { field: 'unknown', snippet: fallbackSnippet };\n}\n\n/**\n * Performs BM25-based search for better relevance ranking.\n * Uses Okapi BM25 algorithm for term frequency and document length normalization.\n * If query is empty, returns all tools (up to maxResults) sorted alphabetically.\n * @param tools - Array of tool metadata to search\n * @param query - The search query (empty returns all tools)\n * @param fields - Which fields to search\n * @param maxResults - Maximum results to return\n * @returns Search response with matching tools ranked by BM25 score\n */\nfunction performLocalSearch(\n tools: t.ToolMetadata[],\n query: string,\n fields: string[],\n maxResults: number\n): t.ToolSearchResponse {\n if (tools.length === 0) {\n return {\n tool_references: [],\n total_tools_searched: 0,\n pattern_used: query,\n };\n }\n\n const queryTokens = tokenize(query);\n\n if (queryTokens.length === 0) {\n const allTools = tools\n .slice()\n .sort((a, b) => a.name.localeCompare(b.name))\n .slice(0, maxResults)\n .map((tool) => ({\n tool_name: tool.name,\n match_score: 1.0,\n matched_field: 'name',\n snippet: tool.description.substring(0, 100) || tool.name,\n }));\n\n return {\n tool_references: allTools,\n total_tools_searched: tools.length,\n pattern_used: query,\n };\n }\n\n const documents = tools.map((tool) => createToolDocument(tool, fields));\n const scores = BM25(documents, queryTokens, { k1: 1.5, b: 0.75 }) as number[];\n\n const maxScore = Math.max(...scores.filter((s) => s > 0), 1);\n const queryLower = query.toLowerCase().trim();\n const queryIdentifier = queryTokens.join('');\n const matchesIdentifiers = fields.includes('name');\n\n const results: Array<{\n result: t.ToolSearchResult;\n identifierPriority: number;\n }> = [];\n for (let i = 0; i < tools.length; i++) {\n const score = scores[i];\n const hasSearchScore = Number.isFinite(score) && score > 0;\n let identifierPriority = 0;\n let normalizedScore = hasSearchScore ? Math.min(score / maxScore, 1.0) : 0;\n\n if (matchesIdentifiers) {\n const rawBaseName = getBaseToolName(tools[i].name).toLowerCase();\n const rawFullName = tools[i].name.toLowerCase();\n const baseIdentifier = tokenize(rawBaseName).join('');\n const fullIdentifier = tokenize(rawFullName).join('');\n\n if (rawFullName === queryLower) {\n identifierPriority = 4;\n normalizedScore = 1.0;\n } else if (rawBaseName === queryLower) {\n identifierPriority = 3;\n normalizedScore = 1.0;\n } else if (\n baseIdentifier === queryIdentifier ||\n fullIdentifier === queryIdentifier\n ) {\n identifierPriority = 2;\n normalizedScore = 1.0;\n } else if (baseIdentifier.startsWith(queryIdentifier)) {\n identifierPriority = 1;\n normalizedScore = Math.max(normalizedScore, 0.95);\n }\n }\n\n if (!hasSearchScore && identifierPriority === 0) continue;\n\n const { field, snippet } = findMatchedField(tools[i], queryTokens, fields);\n results.push({\n result: {\n tool_name: tools[i].name,\n match_score: normalizedScore,\n matched_field: field,\n snippet,\n },\n identifierPriority,\n });\n }\n\n results.sort(\n (a, b) =>\n b.identifierPriority - a.identifierPriority ||\n b.result.match_score - a.result.match_score\n );\n const topResults = results.slice(0, maxResults).map(({ result }) => result);\n\n return {\n tool_references: topResults,\n total_tools_searched: tools.length,\n pattern_used: query,\n };\n}\n\n/**\n * Generates the JavaScript search script to be executed in the sandbox.\n * Uses plain JavaScript for maximum compatibility with the Code API.\n * @param deferredTools - Array of tool metadata to search through\n * @param fields - Which fields to search\n * @param maxResults - Maximum number of results to return\n * @param sanitizedPattern - The sanitized regex pattern\n * @returns The JavaScript code string\n */\nfunction generateSearchScript(\n deferredTools: t.ToolMetadata[],\n fields: string[],\n maxResults: number,\n sanitizedPattern: string\n): string {\n const lines = [\n '// Tool definitions (injected)',\n 'var tools = ' + JSON.stringify(deferredTools) + ';',\n 'var searchFields = ' + JSON.stringify(fields) + ';',\n 'var maxResults = ' + maxResults + ';',\n 'var pattern = ' + JSON.stringify(sanitizedPattern) + ';',\n '',\n '// Compile regex (pattern is sanitized client-side)',\n 'var regex;',\n 'try {',\n ' regex = new RegExp(pattern, \\'i\\');',\n '} catch (e) {',\n ' regex = new RegExp(pattern.replace(/[.*+?^${}()[\\\\]\\\\\\\\|]/g, \"\\\\\\\\$&\"), \"i\");',\n '}',\n '',\n '// Search logic',\n 'var results = [];',\n '',\n 'for (var j = 0; j < tools.length; j++) {',\n ' var tool = tools[j];',\n ' var bestScore = 0;',\n ' var matchedField = \\'\\';',\n ' var snippet = \\'\\';',\n '',\n ' // Search name (highest priority)',\n ' if (searchFields.indexOf(\\'name\\') >= 0 && regex.test(tool.name)) {',\n ' bestScore = 0.95;',\n ' matchedField = \\'name\\';',\n ' snippet = tool.name;',\n ' }',\n '',\n ' // Search description (medium priority)',\n ' if (searchFields.indexOf(\\'description\\') >= 0 && tool.description && regex.test(tool.description)) {',\n ' if (bestScore === 0) {',\n ' bestScore = 0.75;',\n ' matchedField = \\'description\\';',\n ' snippet = tool.description.substring(0, 100);',\n ' }',\n ' }',\n '',\n ' // Search parameter names (lower priority)',\n ' if (searchFields.indexOf(\\'parameters\\') >= 0 && tool.parameters && tool.parameters.properties) {',\n ' var paramNames = Object.keys(tool.parameters.properties).join(\\' \\');',\n ' if (regex.test(paramNames)) {',\n ' if (bestScore === 0) {',\n ' bestScore = 0.60;',\n ' matchedField = \\'parameters\\';',\n ' snippet = paramNames;',\n ' }',\n ' }',\n ' }',\n '',\n ' if (bestScore > 0) {',\n ' results.push({',\n ' tool_name: tool.name,',\n ' match_score: bestScore,',\n ' matched_field: matchedField,',\n ' snippet: snippet',\n ' });',\n ' }',\n '}',\n '',\n '// Sort by score (descending) and limit results',\n 'results.sort(function(a, b) { return b.match_score - a.match_score; });',\n 'var topResults = results.slice(0, maxResults);',\n '',\n '// Output as JSON',\n 'console.log(JSON.stringify({',\n ' tool_references: topResults.map(function(r) {',\n ' return {',\n ' tool_name: r.tool_name,',\n ' match_score: r.match_score,',\n ' matched_field: r.matched_field,',\n ' snippet: r.snippet',\n ' };',\n ' }),',\n ' total_tools_searched: tools.length,',\n ' pattern_used: pattern',\n '}));',\n ];\n return lines.join('\\n');\n}\n\n/**\n * Parses the search results from stdout JSON.\n * @param stdout - The stdout string containing JSON results\n * @returns Parsed search response\n */\nfunction parseSearchResults(stdout: string): t.ToolSearchResponse {\n const jsonMatch = stdout.trim();\n const parsed = JSON.parse(jsonMatch) as t.ToolSearchResponse;\n return parsed;\n}\n\n/**\n * Formats search results as structured JSON for efficient parsing.\n * @param searchResponse - The parsed search response\n * @param nameFormat - Whether to show 'full' names (tool_mcp_server) or 'base' names (tool only)\n * @returns JSON string with search results\n */\nfunction formatSearchResults(\n searchResponse: t.ToolSearchResponse,\n nameFormat: t.McpNameFormat = 'full'\n): string {\n const { tool_references, total_tools_searched, pattern_used } =\n searchResponse;\n const useFullName = nameFormat === 'full';\n\n const output = {\n found: tool_references.length,\n tools: tool_references.map((ref) => ({\n name: useFullName ? ref.tool_name : getBaseToolName(ref.tool_name),\n score: Number(ref.match_score.toFixed(2)),\n matched_in: ref.matched_field,\n snippet: ref.snippet,\n })),\n total_searched: total_tools_searched,\n query: pattern_used,\n };\n\n return JSON.stringify(output, null, 2);\n}\n\n/**\n * Extracts the base tool name (without MCP server suffix) from a full tool name.\n * @param toolName - The full tool name\n * @returns The base tool name without server suffix\n */\nfunction getBaseToolName(toolName: string): string {\n const delimiterIndex = toolName.indexOf(Constants.MCP_DELIMITER);\n if (delimiterIndex === -1) {\n return toolName;\n }\n return toolName.substring(0, delimiterIndex);\n}\n\n/**\n * Checks whether a tool has any defined parameters in its JSON schema.\n * @param parameters - The tool's JSON schema parameters\n * @returns true if the tool has at least one parameter property\n */\nfunction hasParams(parameters?: t.JsonSchemaType): boolean {\n return (\n parameters?.properties != null &&\n Object.keys(parameters.properties).length > 0\n );\n}\n\n/**\n * Generates a compact listing of deferred tools grouped by server.\n * Format: \"server: tool1, tool2(\\u2026), tool3\"\n * Tools with parameters are annotated with (\\u2026) to signal\n * that the LLM should discover the schema via tool_search before calling.\n * Non-MCP tools are grouped under \"other\".\n * @param toolRegistry - The tool registry\n * @param onlyDeferred - Whether to only include deferred tools\n * @returns Formatted string with tools grouped by server\n */\nfunction getDeferredToolsListing(\n toolRegistry: t.LCToolRegistry | undefined,\n onlyDeferred: boolean\n): string {\n if (!toolRegistry) {\n return '';\n }\n\n const toolsByServer: Record<string, string[]> = {};\n\n for (const lcTool of toolRegistry.values()) {\n if (onlyDeferred && lcTool.defer_loading !== true) {\n continue;\n }\n\n const toolName = lcTool.name;\n const serverName = extractMcpServerName(toolName) ?? 'other';\n const baseName = getBaseToolName(toolName);\n const displayName = hasParams(lcTool.parameters)\n ? `${baseName}(\\u2026)`\n : baseName;\n\n if (!(serverName in toolsByServer)) {\n toolsByServer[serverName] = [];\n }\n toolsByServer[serverName].push(displayName);\n }\n\n const serverNames = Object.keys(toolsByServer).sort((a, b) => {\n if (a === 'other') return 1;\n if (b === 'other') return -1;\n return a.localeCompare(b);\n });\n\n if (serverNames.length === 0) {\n return '';\n }\n\n const lines = serverNames.map(\n (server) => `${server}: ${toolsByServer[server].join(', ')}`\n );\n\n return lines.join('\\n');\n}\n\n/**\n * Formats a server listing response as structured JSON.\n * NOTE: This is a PREVIEW only - tools are NOT discovered/loaded.\n * @param tools - Array of tool metadata from the server(s)\n * @param serverNames - The MCP server name(s)\n * @param nameFormat - Whether to show 'full' names (tool_mcp_server) or 'base' names (tool only)\n * @returns JSON string showing all tools grouped by server\n */\nfunction formatServerListing(\n tools: t.ToolMetadata[],\n serverNames: string | string[],\n nameFormat: t.McpNameFormat = 'full'\n): string {\n const servers = Array.isArray(serverNames) ? serverNames : [serverNames];\n const useFullName = nameFormat === 'full';\n\n if (tools.length === 0) {\n return JSON.stringify(\n {\n listing_mode: true,\n servers,\n total_tools: 0,\n tools_by_server: {},\n hint: 'No tools found from the specified MCP server(s).',\n },\n null,\n 2\n );\n }\n\n const toolsByServer: Record<\n string,\n Array<{ name: string; description: string }>\n > = {};\n for (const tool of tools) {\n const server = extractMcpServerName(tool.name) ?? 'unknown';\n if (!(server in toolsByServer)) {\n toolsByServer[server] = [];\n }\n toolsByServer[server].push({\n name: useFullName ? tool.name : getBaseToolName(tool.name),\n description:\n tool.description.length > 100\n ? tool.description.substring(0, 97) + '...'\n : tool.description,\n });\n }\n\n const exampleToolName = useFullName\n ? (tools[0]?.name ?? 'tool_name')\n : getBaseToolName(tools[0]?.name ?? 'tool_name');\n\n const output = {\n listing_mode: true,\n servers,\n total_tools: tools.length,\n tools_by_server: toolsByServer,\n hint: `To use a tool, search for it by name (e.g., query: \"${exampleToolName}\") to load it.`,\n };\n\n return JSON.stringify(output, null, 2);\n}\n\n/**\n * Creates a Tool Search tool for discovering tools from a large registry.\n *\n * This tool enables AI agents to dynamically discover tools from a large library\n * without loading all tool definitions into the LLM context window. The agent\n * can search for relevant tools on-demand.\n *\n * **Modes:**\n * - `code_interpreter` (default): Uses external sandbox for regex search. Safer for complex patterns.\n * - `local`: Uses safe substring matching locally. No network call, faster, completely safe from ReDoS.\n *\n * The tool registry can be provided either:\n * 1. At initialization time via params.toolRegistry\n * 2. At runtime via config.configurable.toolRegistry when invoking\n *\n * @param params - Configuration parameters for the tool (toolRegistry is optional)\n * @returns A LangChain DynamicStructuredTool for tool searching\n *\n * @example\n * // Option 1: Code interpreter mode (regex via sandbox)\n * const tool = createToolSearch({ toolRegistry });\n * await tool.invoke({ query: 'expense.*report' });\n *\n * @example\n * // Option 2: Local mode (safe substring search)\n * const tool = createToolSearch({ mode: 'local', toolRegistry });\n * await tool.invoke({ query: 'expense' });\n */\nfunction createToolSearch(\n initParams: t.ToolSearchParams = {}\n): DynamicStructuredTool {\n const mode: t.ToolSearchMode = initParams.mode ?? 'code_interpreter';\n const defaultOnlyDeferred = initParams.onlyDeferred ?? true;\n const mcpNameFormat: t.McpNameFormat = initParams.mcpNameFormat ?? 'full';\n const schema = createToolSearchSchema(mode);\n\n const baseEndpoint = initParams.baseUrl ?? getCodeBaseURL();\n const EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\n const deferredToolsListing = getDeferredToolsListing(\n initParams.toolRegistry,\n defaultOnlyDeferred\n );\n\n const toolsListSection =\n deferredToolsListing.length > 0\n ? `\n\nDeferred tools (search to load; \\u2026 = has params, search first):\n${deferredToolsListing}`\n : '';\n\n const mcpNote =\n deferredToolsListing.includes(Constants.MCP_DELIMITER) ||\n deferredToolsListing.split('\\n').some((line) => !line.startsWith('other:'))\n ? `\n- MCP tools use format: toolName${Constants.MCP_DELIMITER}serverName\n- Use mcp_server param to filter by server`\n : '';\n\n const description =\n mode === 'local'\n ? `\nSearches deferred tools using BM25 ranking. Multi-word queries supported.\n${mcpNote}${toolsListSection}\n`.trim()\n : `\nSearches deferred tools by regex pattern.\n${mcpNote}${toolsListSection}\n`.trim();\n\n return tool(\n async (rawParams, config) => {\n const params = rawParams as ToolSearchParams;\n const {\n query = '',\n fields = ['name', 'description'],\n max_results = DEFAULT_MAX_RESULTS,\n mcp_server,\n } = params;\n\n const {\n toolRegistry: paramToolRegistry,\n onlyDeferred: paramOnlyDeferred,\n mcpServer: paramMcpServer,\n } = config.toolCall ?? {};\n\n const toolRegistry = paramToolRegistry ?? initParams.toolRegistry;\n const onlyDeferred =\n paramOnlyDeferred !== undefined\n ? paramOnlyDeferred\n : defaultOnlyDeferred;\n const rawServerFilter =\n mcp_server ?? paramMcpServer ?? initParams.mcpServer;\n const serverFilters = normalizeServerFilter(rawServerFilter);\n const hasServerFilter = serverFilters.length > 0;\n\n if (toolRegistry == null) {\n return [\n 'Error: No tool registry provided. Configure toolRegistry at agent level or initialization.',\n {\n tool_references: [],\n metadata: {\n total_searched: 0,\n pattern: query,\n error: 'No tool registry provided',\n },\n },\n ];\n }\n\n const toolsArray: t.LCTool[] = Array.from(toolRegistry.values());\n const deferredTools: t.ToolMetadata[] = toolsArray\n .filter((lcTool) => {\n if (onlyDeferred === true && lcTool.defer_loading !== true) {\n return false;\n }\n if (\n hasServerFilter &&\n !isFromAnyMcpServer(lcTool.name, serverFilters)\n ) {\n return false;\n }\n return true;\n })\n .map((lcTool) => ({\n name: lcTool.name,\n description: lcTool.description ?? '',\n parameters: simplifyParametersForSearch(lcTool.parameters),\n }));\n\n if (deferredTools.length === 0) {\n const serverMsg = hasServerFilter\n ? ` from MCP server(s): ${serverFilters.join(', ')}`\n : '';\n return [\n `No tools available to search${serverMsg}. The tool registry is empty or no matching deferred tools are registered.`,\n {\n tool_references: [],\n metadata: {\n total_searched: 0,\n pattern: query,\n mcp_server: serverFilters,\n },\n },\n ];\n }\n\n const isServerListing = hasServerFilter && query === '';\n\n if (isServerListing) {\n const formattedOutput = formatServerListing(\n deferredTools,\n serverFilters,\n mcpNameFormat\n );\n\n return [\n formattedOutput,\n {\n tool_references: [],\n metadata: {\n total_available: deferredTools.length,\n mcp_server: serverFilters,\n listing_mode: true,\n },\n },\n ];\n }\n\n if (mode === 'local') {\n const searchResponse = performLocalSearch(\n deferredTools,\n query,\n fields,\n max_results\n );\n const formattedOutput = formatSearchResults(\n searchResponse,\n mcpNameFormat\n );\n\n return [\n formattedOutput,\n {\n tool_references: searchResponse.tool_references,\n metadata: {\n total_searched: searchResponse.total_tools_searched,\n pattern: searchResponse.pattern_used,\n mcp_server: serverFilters.length > 0 ? serverFilters : undefined,\n },\n },\n ];\n }\n\n const { safe: sanitizedPattern, wasEscaped } = sanitizeRegex(query);\n let warningMessage = '';\n if (wasEscaped) {\n warningMessage =\n 'Note: The provided pattern was converted to a literal search for safety.\\n\\n';\n }\n\n const searchScript = generateSearchScript(\n deferredTools,\n fields,\n max_results,\n sanitizedPattern\n );\n\n const postData = {\n lang: 'js',\n code: searchScript,\n timeout: SEARCH_TIMEOUT,\n };\n\n try {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const result: t.ExecuteResult = await response.json();\n\n if (result.stderr && result.stderr.trim()) {\n // eslint-disable-next-line no-console\n console.warn('[ToolSearch] stderr:', result.stderr);\n }\n\n if (!result.stdout || !result.stdout.trim()) {\n return [\n `${warningMessage}No tools matched the pattern \"${sanitizedPattern}\".\\nTotal tools searched: ${deferredTools.length}`,\n {\n tool_references: [],\n metadata: {\n total_searched: deferredTools.length,\n pattern: sanitizedPattern,\n },\n },\n ];\n }\n\n const searchResponse = parseSearchResults(result.stdout);\n const formattedOutput = `${warningMessage}${formatSearchResults(searchResponse, mcpNameFormat)}`;\n\n return [\n formattedOutput,\n {\n tool_references: searchResponse.tool_references,\n metadata: {\n total_searched: searchResponse.total_tools_searched,\n pattern: searchResponse.pattern_used,\n },\n },\n ];\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[ToolSearch] Error:', error);\n\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n return [\n `Tool search failed: ${errorMessage}\\n\\nSuggestion: Try a simpler search pattern or search for specific tool names.`,\n {\n tool_references: [],\n metadata: {\n total_searched: 0,\n pattern: sanitizedPattern,\n error: errorMessage,\n },\n },\n ];\n }\n },\n {\n name: Constants.TOOL_SEARCH,\n description,\n schema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport {\n createToolSearch,\n performLocalSearch,\n extractMcpServerName,\n isFromMcpServer,\n isFromAnyMcpServer,\n normalizeServerFilter,\n getAvailableMcpServers,\n getDeferredToolsListing,\n getBaseToolName,\n formatServerListing,\n sanitizeRegex,\n escapeRegexSpecialChars,\n isDangerousPattern,\n countNestedGroups,\n hasNestedQuantifiers,\n};\n"],"mappings":";;;;;;;;;;;;AAUA,SAAS,kBAA0B;CACjC,MAAM,MAAMA;CAGZ,IAAI,OAAO,QAAQ,YAAY,OAAO;CACtC,IAAI,OAAO,IAAI,YAAY,YAAY,OAAO,IAAI;CAClD,IAAI,IAAI,WAAW,QAAQ,OAAO,IAAI,QAAQ,YAAY,YACxD,OAAO,IAAI,QAAQ;CACrB,MAAM,IAAI,MAAM,uDAAuD;AACzE;AAEA,MAAM,OAAO,gBAAgB;mBAQtB;;AAGP,MAAM,qBAAqB;AAE3B,MAAa,qBAAA;AAEb,MAAa,4BACX;AAEF,MAAM,0BACJ;AACF,MAAM,0BACJ;AACF,MAAM,qBACJ;AACF,MAAM,0BAA0B;AAChC,MAAM,sBAAsB;AAC5B,MAAM,yBACJ;AAEF,MAAa,uBAAuB;CAClC,MAAM;CACN,YAAY;EACV,OAAO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AAS;KACT,OAAO;IACT;GACF,CACF;EACF;CACF,GACA;EACE,MAAA;EACA;EACA;EACA,gBAAA;CACF,CACF;AACF"}
@@ -107,7 +107,7 @@ async function executeParallelSearches({ searchAPI, query, date, country, safeSe
107
107
  data: mergedResults
108
108
  };
109
109
  }
110
- function createSearchProcessor({ searchAPI, safeSearch, supportsImages, supportsVideos, supportsNews, sourceProcessor, onGetHighlights, logger }) {
110
+ function createSearchProcessor({ searchAPI, safeSearch, supportsImages, supportsVideos, supportsNews, sourceProcessor, onGetHighlights, mainExpandBy, separatorExpandBy, logger }) {
111
111
  return async function({ query, date, country, proMode = true, maxSources = 5, onSearchResults, images = false, videos = false, news = false }) {
112
112
  try {
113
113
  const searchResult = await executeParallelSearches({
@@ -129,7 +129,7 @@ function createSearchProcessor({ searchAPI, safeSearch, supportsImages, supports
129
129
  proMode,
130
130
  onGetHighlights,
131
131
  numElements: maxSources
132
- }));
132
+ }), mainExpandBy, separatorExpandBy);
133
133
  } catch (error) {
134
134
  logger.error("Error in search:", error);
135
135
  return {
@@ -181,7 +181,7 @@ function createTool({ schema, search, maxOutputChars, onSearchResults: _onSearch
181
181
  });
182
182
  }
183
183
  const createSearchTool = (config = {}) => {
184
- const { searchProvider = "serper", serperApiKey, searxngInstanceUrl, searxngApiKey, tavilyApiKey, tavilySearchUrl, tavilyExtractUrl, tavilySearchOptions, keenableApiKey, keenableApiUrl, keenableSearchOptions, rerankerType = "cohere", rerankerTimeout, topResults = 5, maxContentLength, chunkSize, chunkOverlap, maxOutputChars, strategies = ["no_extraction"], filterContent = true, safeSearch = 1, scraperProvider = "firecrawl", firecrawlApiKey, firecrawlApiUrl, firecrawlVersion, firecrawlOptions, serperScraperOptions, tavilyScraperOptions, crwApiKey, crwApiUrl, crwSearchOptions, crwScraperOptions, scraperTimeout, jinaApiKey, jinaApiUrl, cohereApiKey, onSearchResults: _onSearchResults, onGetHighlights } = config;
184
+ const { searchProvider = "serper", serperApiKey, searxngInstanceUrl, searxngApiKey, tavilyApiKey, tavilySearchUrl, tavilyExtractUrl, tavilySearchOptions, keenableApiKey, keenableApiUrl, keenableSearchOptions, rerankerType = "cohere", rerankerTimeout, topResults = 5, maxContentLength, chunkSize, chunkOverlap, mainExpandBy, separatorExpandBy, maxOutputChars, strategies = ["no_extraction"], filterContent = true, safeSearch = 1, scraperProvider = "firecrawl", firecrawlApiKey, firecrawlApiUrl, firecrawlVersion, firecrawlOptions, serperScraperOptions, tavilyScraperOptions, crwApiKey, crwApiUrl, crwSearchOptions, crwScraperOptions, scraperTimeout, jinaApiKey, jinaApiUrl, cohereApiKey, onSearchResults: _onSearchResults, onGetHighlights } = config;
185
185
  const logger = config.logger || require_utils.createDefaultLogger();
186
186
  const effectiveTavilySearchOptions = searchProvider === "tavily" && config.safeSearch != null ? {
187
187
  ...tavilySearchOptions,
@@ -275,6 +275,8 @@ const createSearchTool = (config = {}) => {
275
275
  supportsNews: searchProvider !== "keenable",
276
276
  sourceProcessor,
277
277
  onGetHighlights,
278
+ mainExpandBy,
279
+ separatorExpandBy,
278
280
  logger
279
281
  }),
280
282
  schema: toolSchema,
@@ -1 +1 @@
1
- {"version":3,"file":"tool.cjs","names":["expandHighlights","params","formatResultsForLLM","WebSearchToolName","WebSearchToolDescription","createDefaultLogger","querySchema","dateSchema","imagesSchema","videosSchema","newsSchema","countrySchema","createSearchAPI","createSerperScraper","createTavilyScraper","createCrwScraper","createFirecrawlScraper","createReranker","createSourceProcessor"],"sources":["../../../../src/tools/search/tool.ts"],"sourcesContent":["import { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type * as t from './types';\nimport {\n WebSearchToolDescription,\n WebSearchToolName,\n countrySchema,\n imagesSchema,\n videosSchema,\n querySchema,\n dateSchema,\n newsSchema,\n DATE_RANGE,\n} from './schema';\nimport { createSearchAPI, createSourceProcessor } from './search';\nimport { createSerperScraper } from './serper-scraper';\nimport { createTavilyScraper } from './tavily-scraper';\nimport { createFirecrawlScraper } from './firecrawl';\nimport { createCrwScraper } from './crw-scraper';\nimport { expandHighlights } from './highlights';\nimport { formatResultsForLLM } from './format';\nimport { createDefaultLogger } from './utils';\nimport { createReranker } from './rerankers';\nimport { Constants } from '@/common';\n\n/**\n * Executes parallel searches and merges the results,\n * deduplicating top stories by link\n */\nexport async function executeParallelSearches({\n searchAPI,\n query,\n date,\n country,\n safeSearch,\n images,\n videos,\n news,\n logger,\n}: {\n searchAPI: ReturnType<typeof createSearchAPI>;\n query: string;\n date?: DATE_RANGE;\n country?: string;\n safeSearch: t.SearchToolConfig['safeSearch'];\n images: boolean;\n videos: boolean;\n news: boolean;\n logger: t.Logger;\n}): Promise<t.SearchResult> {\n // Prepare all search tasks to run in parallel\n const searchTasks: Promise<t.SearchResult>[] = [\n // Main search\n searchAPI.getSources({\n query,\n date,\n country,\n safeSearch,\n }),\n ];\n\n if (images) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'images',\n })\n .catch((error) => {\n logger.error('Error fetching images:', error);\n return {\n success: false,\n error: `Images search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n if (videos) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'videos',\n })\n .catch((error) => {\n logger.error('Error fetching videos:', error);\n return {\n success: false,\n error: `Videos search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n if (news) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'news',\n })\n .catch((error) => {\n logger.error('Error fetching news:', error);\n return {\n success: false,\n error: `News search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n\n // Run all searches in parallel\n const results = await Promise.all(searchTasks);\n\n // Get the main search result (first result)\n const mainResult = results[0];\n if (!mainResult.success) {\n throw new Error(mainResult.error ?? 'Search failed');\n }\n\n // Merge additional results with the main results\n const mergedResults = { ...mainResult.data };\n\n // Convert existing news to topStories if present\n if (mergedResults.news !== undefined && mergedResults.news.length > 0) {\n const existingNewsAsTopStories = mergedResults.news\n .filter((newsItem) => newsItem.link !== undefined && newsItem.link !== '')\n .map((newsItem) => ({\n title: newsItem.title ?? '',\n link: newsItem.link ?? '',\n source: newsItem.source ?? '',\n date: newsItem.date ?? '',\n imageUrl: newsItem.imageUrl ?? '',\n processed: false,\n }));\n mergedResults.topStories = [\n ...(mergedResults.topStories ?? []),\n ...existingNewsAsTopStories,\n ];\n delete mergedResults.news;\n }\n\n results.slice(1).forEach((result) => {\n if (result.success && result.data !== undefined) {\n if (result.data.images !== undefined && result.data.images.length > 0) {\n mergedResults.images = [\n ...(mergedResults.images ?? []),\n ...result.data.images,\n ];\n }\n if (result.data.videos !== undefined && result.data.videos.length > 0) {\n mergedResults.videos = [\n ...(mergedResults.videos ?? []),\n ...result.data.videos,\n ];\n }\n if (result.data.news !== undefined && result.data.news.length > 0) {\n const newsAsTopStories = result.data.news.map((newsItem) => ({\n ...newsItem,\n link: newsItem.link ?? '',\n }));\n mergedResults.topStories = [\n ...(mergedResults.topStories ?? []),\n ...newsAsTopStories,\n ];\n }\n }\n });\n\n if (\n mergedResults.topStories !== undefined &&\n mergedResults.topStories.length > 1\n ) {\n /** The main search's own news results and the parallel news sub-search\n * frequently return the same stories — keep the first occurrence of each\n * link so duplicates aren't scraped, reranked, and formatted repeatedly */\n const seenLinks = new Set<string>();\n mergedResults.topStories = mergedResults.topStories.filter((story) => {\n if (!story.link || seenLinks.has(story.link)) {\n return false;\n }\n seenLinks.add(story.link);\n return true;\n });\n }\n\n return { success: true, data: mergedResults };\n}\n\nfunction createSearchProcessor({\n searchAPI,\n safeSearch,\n supportsImages,\n supportsVideos,\n supportsNews,\n sourceProcessor,\n onGetHighlights,\n logger,\n}: {\n safeSearch: t.SearchToolConfig['safeSearch'];\n supportsImages: boolean;\n supportsVideos: boolean;\n supportsNews: boolean;\n searchAPI: ReturnType<typeof createSearchAPI>;\n sourceProcessor: ReturnType<typeof createSourceProcessor>;\n onGetHighlights: t.SearchToolConfig['onGetHighlights'];\n logger: t.Logger;\n}) {\n return async function ({\n query,\n date,\n country,\n proMode = true,\n maxSources = 5,\n onSearchResults,\n images = false,\n videos = false,\n news = false,\n }: {\n query: string;\n country?: string;\n date?: DATE_RANGE;\n proMode?: boolean;\n maxSources?: number;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n images?: boolean;\n videos?: boolean;\n news?: boolean;\n }): Promise<t.SearchResultData> {\n try {\n // Execute parallel searches and merge results\n const searchResult = await executeParallelSearches({\n searchAPI,\n query,\n date,\n country,\n safeSearch,\n images: supportsImages && images,\n videos: supportsVideos && videos,\n news: supportsNews && news,\n logger,\n });\n\n onSearchResults?.(searchResult);\n\n const processedSources = await sourceProcessor.processSources({\n query,\n news,\n result: searchResult,\n proMode,\n onGetHighlights,\n numElements: maxSources,\n });\n\n return expandHighlights(processedSources);\n } catch (error) {\n logger.error('Error in search:', error);\n return {\n organic: [],\n topStories: [],\n images: [],\n videos: [],\n news: [],\n relatedSearches: [],\n error: error instanceof Error ? error.message : String(error),\n };\n }\n };\n}\n\nfunction createOnSearchResults({\n runnableConfig,\n onSearchResults,\n}: {\n runnableConfig: RunnableConfig;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n}) {\n return function (results: t.SearchResult): void {\n if (!onSearchResults) {\n return;\n }\n onSearchResults(results, runnableConfig);\n };\n}\n\nfunction createTool({\n schema,\n search,\n maxOutputChars,\n onSearchResults: _onSearchResults,\n}: {\n schema: Record<string, unknown>;\n search: ReturnType<typeof createSearchProcessor>;\n maxOutputChars?: number;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n}): DynamicStructuredTool {\n return tool(\n async (rawParams, runnableConfig) => {\n const params = rawParams as SearchToolParams;\n const { query, date, country: _c, images, videos, news } = params;\n const country = typeof _c === 'string' && _c ? _c : undefined;\n const searchResult = await search({\n query,\n date,\n country,\n images,\n videos,\n news,\n onSearchResults: createOnSearchResults({\n runnableConfig,\n onSearchResults: _onSearchResults,\n }),\n });\n const turn = runnableConfig.toolCall?.turn ?? 0;\n const { output, references } = formatResultsForLLM(\n turn,\n searchResult,\n maxOutputChars\n );\n const data: t.SearchResultData = { turn, ...searchResult, references };\n return [output, { [Constants.WEB_SEARCH]: data }];\n },\n {\n name: WebSearchToolName,\n description: WebSearchToolDescription,\n schema: schema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\n/**\n * Creates a search tool with configurable search and scraper providers.\n *\n * Search providers: Serper (Google results), SearXNG (self-hosted meta-search), Tavily (AI-optimized), fastCRW (Firecrawl-compatible, self-host or cloud).\n * Scraper providers: Firecrawl (default, full-featured), Serper (lightweight), Tavily (batch extraction), fastCRW (Firecrawl-compatible, self-host or cloud).\n *\n * The country schema field is exposed to the LLM for providers that support localized results.\n */\n/** Input params type for search tool */\ninterface SearchToolParams {\n query: string;\n date?: DATE_RANGE;\n country?: string;\n images?: boolean;\n videos?: boolean;\n news?: boolean;\n}\n\nexport const createSearchTool = (\n config: t.SearchToolConfig = {}\n): DynamicStructuredTool => {\n const {\n searchProvider = 'serper',\n serperApiKey,\n searxngInstanceUrl,\n searxngApiKey,\n tavilyApiKey,\n tavilySearchUrl,\n tavilyExtractUrl,\n tavilySearchOptions,\n keenableApiKey,\n keenableApiUrl,\n keenableSearchOptions,\n rerankerType = 'cohere',\n rerankerTimeout,\n topResults = 5,\n maxContentLength,\n chunkSize,\n chunkOverlap,\n maxOutputChars,\n strategies = ['no_extraction'],\n filterContent = true,\n safeSearch = 1,\n scraperProvider = 'firecrawl',\n firecrawlApiKey,\n firecrawlApiUrl,\n firecrawlVersion,\n firecrawlOptions,\n serperScraperOptions,\n tavilyScraperOptions,\n crwApiKey,\n crwApiUrl,\n crwSearchOptions,\n crwScraperOptions,\n scraperTimeout,\n jinaApiKey,\n jinaApiUrl,\n cohereApiKey,\n onSearchResults: _onSearchResults,\n onGetHighlights,\n } = config;\n\n const logger = config.logger || createDefaultLogger();\n const effectiveTavilySearchOptions =\n searchProvider === 'tavily' && config.safeSearch != null\n ? {\n ...tavilySearchOptions,\n safeSearch: config.safeSearch !== 0,\n }\n : tavilySearchOptions;\n\n const schemaProperties: Record<string, unknown> = {\n query: querySchema,\n date: dateSchema,\n images: imagesSchema,\n videos: videosSchema,\n news: newsSchema,\n };\n\n if (searchProvider === 'serper' || searchProvider === 'tavily') {\n schemaProperties.country = countrySchema;\n }\n\n const toolSchema = {\n type: 'object',\n properties: schemaProperties,\n required: ['query'],\n };\n\n const searchAPI = createSearchAPI({\n searchProvider,\n serperApiKey,\n searxngInstanceUrl,\n searxngApiKey,\n tavilyApiKey,\n tavilySearchUrl,\n tavilySearchOptions: effectiveTavilySearchOptions,\n keenableApiKey,\n keenableApiUrl,\n keenableSearchOptions,\n crwApiKey,\n crwApiUrl,\n crwSearchOptions,\n });\n\n /** Create scraper based on scraperProvider */\n let scraperInstance: t.BaseScraper;\n\n if (scraperProvider === 'serper') {\n scraperInstance = createSerperScraper({\n ...serperScraperOptions,\n apiKey: serperApiKey,\n timeout: scraperTimeout ?? serperScraperOptions?.timeout,\n logger,\n });\n } else if (scraperProvider === 'tavily') {\n scraperInstance = createTavilyScraper({\n ...tavilyScraperOptions,\n apiKey:\n tavilyScraperOptions?.apiKey ??\n tavilyApiKey ??\n process.env.TAVILY_API_KEY,\n apiUrl: tavilyScraperOptions?.apiUrl ?? tavilyExtractUrl,\n timeout: scraperTimeout ?? tavilyScraperOptions?.timeout,\n logger,\n });\n } else if (scraperProvider === 'crw') {\n scraperInstance = createCrwScraper({\n ...crwScraperOptions,\n apiKey:\n crwScraperOptions?.apiKey ?? crwApiKey ?? process.env.CRW_API_KEY,\n apiUrl: crwScraperOptions?.apiUrl ?? crwApiUrl,\n timeout: scraperTimeout ?? crwScraperOptions?.timeout,\n formats: crwScraperOptions?.formats ?? ['markdown', 'rawHtml'],\n logger,\n });\n } else {\n scraperInstance = createFirecrawlScraper({\n ...firecrawlOptions,\n apiKey: firecrawlApiKey ?? process.env.FIRECRAWL_API_KEY,\n apiUrl: firecrawlApiUrl,\n version: firecrawlVersion,\n timeout: scraperTimeout ?? firecrawlOptions?.timeout,\n formats: firecrawlOptions?.formats ?? ['markdown', 'rawHtml'],\n logger,\n });\n }\n\n const selectedReranker = createReranker({\n rerankerType,\n jinaApiKey,\n jinaApiUrl,\n cohereApiKey,\n rerankerTimeout,\n logger,\n });\n\n if (!selectedReranker) {\n logger.warn('No reranker selected. Using default ranking.');\n }\n\n const sourceProcessor = createSourceProcessor(\n {\n reranker: selectedReranker,\n topResults,\n maxContentLength,\n chunkSize,\n chunkOverlap,\n strategies,\n filterContent,\n logger,\n },\n scraperInstance\n );\n\n const search = createSearchProcessor({\n searchAPI,\n safeSearch,\n // Keenable is organic-only: its API ignores `type`, so image/news\n // sub-searches would spend rate limit and merge nothing.\n supportsImages: searchProvider !== 'keenable',\n supportsVideos:\n searchProvider !== 'tavily' &&\n searchProvider !== 'keenable' &&\n searchProvider !== 'crw',\n supportsNews: searchProvider !== 'keenable',\n sourceProcessor,\n onGetHighlights,\n logger,\n });\n\n return createTool({\n search,\n schema: toolSchema,\n maxOutputChars,\n onSearchResults: _onSearchResults,\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AA6BA,eAAsB,wBAAwB,EAC5C,WACA,OACA,MACA,SACA,YACA,QACA,QACA,MACA,UAW0B;CAE1B,MAAM,cAAyC,CAE7C,UAAU,WAAW;EACnB;EACA;EACA;EACA;CACF,CAAC,CACH;CAEA,IAAI,QACF,YAAY,KACV,UACG,WAAW;EACV;EACA;EACA;EACA;EACA,MAAM;CACR,CAAC,CAAC,CACD,OAAO,UAAU;EAChB,OAAO,MAAM,0BAA0B,KAAK;EAC5C,OAAO;GACL,SAAS;GACT,OAAO,yBAAyB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EACvF;CACF,CAAC,CACL;CAEF,IAAI,QACF,YAAY,KACV,UACG,WAAW;EACV;EACA;EACA;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;EACR,SAAS;EACT,SAAS,kBAAkB,kBAAkB;EAC7C,SAAS,kBAAkB,WAAW,CAAC,YAAY,SAAS;EAC5D;CACF,CAAC;CAGH,MAAM,mBAAmBC,kBAAAA,eAAe;EACtC;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CAED,IAAI,CAAC,kBACH,OAAO,KAAK,8CAA8C;CAG5D,MAAM,kBAAkBC,eAAAA,sBACtB;EACE,UAAU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;CACF,GACA,eACF;CAkBA,OAAO,WAAW;EAChB,QAjBa,sBAAsB;GACnC;GACA;GAGA,gBAAgB,mBAAmB;GACnC,gBACE,mBAAmB,YACnB,mBAAmB,cACnB,mBAAmB;GACrB,cAAc,mBAAmB;GACjC;GACA;GACA;EACF,CAGO;EACL,QAAQ;EACR;EACA,iBAAiB;CACnB,CAAC;AACH"}
1
+ {"version":3,"file":"tool.cjs","names":["expandHighlights","params","formatResultsForLLM","WebSearchToolName","WebSearchToolDescription","createDefaultLogger","querySchema","dateSchema","imagesSchema","videosSchema","newsSchema","countrySchema","createSearchAPI","createSerperScraper","createTavilyScraper","createCrwScraper","createFirecrawlScraper","createReranker","createSourceProcessor"],"sources":["../../../../src/tools/search/tool.ts"],"sourcesContent":["import { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type * as t from './types';\nimport {\n WebSearchToolDescription,\n WebSearchToolName,\n countrySchema,\n imagesSchema,\n videosSchema,\n querySchema,\n dateSchema,\n newsSchema,\n DATE_RANGE,\n} from './schema';\nimport { createSearchAPI, createSourceProcessor } from './search';\nimport { createSerperScraper } from './serper-scraper';\nimport { createTavilyScraper } from './tavily-scraper';\nimport { createFirecrawlScraper } from './firecrawl';\nimport { createCrwScraper } from './crw-scraper';\nimport { expandHighlights } from './highlights';\nimport { formatResultsForLLM } from './format';\nimport { createDefaultLogger } from './utils';\nimport { createReranker } from './rerankers';\nimport { Constants } from '@/common';\n\n/**\n * Executes parallel searches and merges the results,\n * deduplicating top stories by link\n */\nexport async function executeParallelSearches({\n searchAPI,\n query,\n date,\n country,\n safeSearch,\n images,\n videos,\n news,\n logger,\n}: {\n searchAPI: ReturnType<typeof createSearchAPI>;\n query: string;\n date?: DATE_RANGE;\n country?: string;\n safeSearch: t.SearchToolConfig['safeSearch'];\n images: boolean;\n videos: boolean;\n news: boolean;\n logger: t.Logger;\n}): Promise<t.SearchResult> {\n // Prepare all search tasks to run in parallel\n const searchTasks: Promise<t.SearchResult>[] = [\n // Main search\n searchAPI.getSources({\n query,\n date,\n country,\n safeSearch,\n }),\n ];\n\n if (images) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'images',\n })\n .catch((error) => {\n logger.error('Error fetching images:', error);\n return {\n success: false,\n error: `Images search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n if (videos) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'videos',\n })\n .catch((error) => {\n logger.error('Error fetching videos:', error);\n return {\n success: false,\n error: `Videos search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n if (news) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'news',\n })\n .catch((error) => {\n logger.error('Error fetching news:', error);\n return {\n success: false,\n error: `News search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n\n // Run all searches in parallel\n const results = await Promise.all(searchTasks);\n\n // Get the main search result (first result)\n const mainResult = results[0];\n if (!mainResult.success) {\n throw new Error(mainResult.error ?? 'Search failed');\n }\n\n // Merge additional results with the main results\n const mergedResults = { ...mainResult.data };\n\n // Convert existing news to topStories if present\n if (mergedResults.news !== undefined && mergedResults.news.length > 0) {\n const existingNewsAsTopStories = mergedResults.news\n .filter((newsItem) => newsItem.link !== undefined && newsItem.link !== '')\n .map((newsItem) => ({\n title: newsItem.title ?? '',\n link: newsItem.link ?? '',\n source: newsItem.source ?? '',\n date: newsItem.date ?? '',\n imageUrl: newsItem.imageUrl ?? '',\n processed: false,\n }));\n mergedResults.topStories = [\n ...(mergedResults.topStories ?? []),\n ...existingNewsAsTopStories,\n ];\n delete mergedResults.news;\n }\n\n results.slice(1).forEach((result) => {\n if (result.success && result.data !== undefined) {\n if (result.data.images !== undefined && result.data.images.length > 0) {\n mergedResults.images = [\n ...(mergedResults.images ?? []),\n ...result.data.images,\n ];\n }\n if (result.data.videos !== undefined && result.data.videos.length > 0) {\n mergedResults.videos = [\n ...(mergedResults.videos ?? []),\n ...result.data.videos,\n ];\n }\n if (result.data.news !== undefined && result.data.news.length > 0) {\n const newsAsTopStories = result.data.news.map((newsItem) => ({\n ...newsItem,\n link: newsItem.link ?? '',\n }));\n mergedResults.topStories = [\n ...(mergedResults.topStories ?? []),\n ...newsAsTopStories,\n ];\n }\n }\n });\n\n if (\n mergedResults.topStories !== undefined &&\n mergedResults.topStories.length > 1\n ) {\n /** The main search's own news results and the parallel news sub-search\n * frequently return the same stories — keep the first occurrence of each\n * link so duplicates aren't scraped, reranked, and formatted repeatedly */\n const seenLinks = new Set<string>();\n mergedResults.topStories = mergedResults.topStories.filter((story) => {\n if (!story.link || seenLinks.has(story.link)) {\n return false;\n }\n seenLinks.add(story.link);\n return true;\n });\n }\n\n return { success: true, data: mergedResults };\n}\n\nfunction createSearchProcessor({\n searchAPI,\n safeSearch,\n supportsImages,\n supportsVideos,\n supportsNews,\n sourceProcessor,\n onGetHighlights,\n mainExpandBy,\n separatorExpandBy,\n logger,\n}: {\n safeSearch: t.SearchToolConfig['safeSearch'];\n supportsImages: boolean;\n supportsVideos: boolean;\n supportsNews: boolean;\n searchAPI: ReturnType<typeof createSearchAPI>;\n sourceProcessor: ReturnType<typeof createSourceProcessor>;\n onGetHighlights: t.SearchToolConfig['onGetHighlights'];\n mainExpandBy: t.SearchToolConfig['mainExpandBy'];\n separatorExpandBy: t.SearchToolConfig['separatorExpandBy'];\n logger: t.Logger;\n}) {\n return async function ({\n query,\n date,\n country,\n proMode = true,\n maxSources = 5,\n onSearchResults,\n images = false,\n videos = false,\n news = false,\n }: {\n query: string;\n country?: string;\n date?: DATE_RANGE;\n proMode?: boolean;\n maxSources?: number;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n images?: boolean;\n videos?: boolean;\n news?: boolean;\n }): Promise<t.SearchResultData> {\n try {\n // Execute parallel searches and merge results\n const searchResult = await executeParallelSearches({\n searchAPI,\n query,\n date,\n country,\n safeSearch,\n images: supportsImages && images,\n videos: supportsVideos && videos,\n news: supportsNews && news,\n logger,\n });\n\n onSearchResults?.(searchResult);\n\n const processedSources = await sourceProcessor.processSources({\n query,\n news,\n result: searchResult,\n proMode,\n onGetHighlights,\n numElements: maxSources,\n });\n\n return expandHighlights(\n processedSources,\n mainExpandBy,\n separatorExpandBy\n );\n } catch (error) {\n logger.error('Error in search:', error);\n return {\n organic: [],\n topStories: [],\n images: [],\n videos: [],\n news: [],\n relatedSearches: [],\n error: error instanceof Error ? error.message : String(error),\n };\n }\n };\n}\n\nfunction createOnSearchResults({\n runnableConfig,\n onSearchResults,\n}: {\n runnableConfig: RunnableConfig;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n}) {\n return function (results: t.SearchResult): void {\n if (!onSearchResults) {\n return;\n }\n onSearchResults(results, runnableConfig);\n };\n}\n\nfunction createTool({\n schema,\n search,\n maxOutputChars,\n onSearchResults: _onSearchResults,\n}: {\n schema: Record<string, unknown>;\n search: ReturnType<typeof createSearchProcessor>;\n maxOutputChars?: number;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n}): DynamicStructuredTool {\n return tool(\n async (rawParams, runnableConfig) => {\n const params = rawParams as SearchToolParams;\n const { query, date, country: _c, images, videos, news } = params;\n const country = typeof _c === 'string' && _c ? _c : undefined;\n const searchResult = await search({\n query,\n date,\n country,\n images,\n videos,\n news,\n onSearchResults: createOnSearchResults({\n runnableConfig,\n onSearchResults: _onSearchResults,\n }),\n });\n const turn = runnableConfig.toolCall?.turn ?? 0;\n const { output, references } = formatResultsForLLM(\n turn,\n searchResult,\n maxOutputChars\n );\n const data: t.SearchResultData = { turn, ...searchResult, references };\n return [output, { [Constants.WEB_SEARCH]: data }];\n },\n {\n name: WebSearchToolName,\n description: WebSearchToolDescription,\n schema: schema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\n/**\n * Creates a search tool with configurable search and scraper providers.\n *\n * Search providers: Serper (Google results), SearXNG (self-hosted meta-search), Tavily (AI-optimized), fastCRW (Firecrawl-compatible, self-host or cloud).\n * Scraper providers: Firecrawl (default, full-featured), Serper (lightweight), Tavily (batch extraction), fastCRW (Firecrawl-compatible, self-host or cloud).\n *\n * The country schema field is exposed to the LLM for providers that support localized results.\n */\n/** Input params type for search tool */\ninterface SearchToolParams {\n query: string;\n date?: DATE_RANGE;\n country?: string;\n images?: boolean;\n videos?: boolean;\n news?: boolean;\n}\n\nexport const createSearchTool = (\n config: t.SearchToolConfig = {}\n): DynamicStructuredTool => {\n const {\n searchProvider = 'serper',\n serperApiKey,\n searxngInstanceUrl,\n searxngApiKey,\n tavilyApiKey,\n tavilySearchUrl,\n tavilyExtractUrl,\n tavilySearchOptions,\n keenableApiKey,\n keenableApiUrl,\n keenableSearchOptions,\n rerankerType = 'cohere',\n rerankerTimeout,\n topResults = 5,\n maxContentLength,\n chunkSize,\n chunkOverlap,\n mainExpandBy,\n separatorExpandBy,\n maxOutputChars,\n strategies = ['no_extraction'],\n filterContent = true,\n safeSearch = 1,\n scraperProvider = 'firecrawl',\n firecrawlApiKey,\n firecrawlApiUrl,\n firecrawlVersion,\n firecrawlOptions,\n serperScraperOptions,\n tavilyScraperOptions,\n crwApiKey,\n crwApiUrl,\n crwSearchOptions,\n crwScraperOptions,\n scraperTimeout,\n jinaApiKey,\n jinaApiUrl,\n cohereApiKey,\n onSearchResults: _onSearchResults,\n onGetHighlights,\n } = config;\n\n const logger = config.logger || createDefaultLogger();\n const effectiveTavilySearchOptions =\n searchProvider === 'tavily' && config.safeSearch != null\n ? {\n ...tavilySearchOptions,\n safeSearch: config.safeSearch !== 0,\n }\n : tavilySearchOptions;\n\n const schemaProperties: Record<string, unknown> = {\n query: querySchema,\n date: dateSchema,\n images: imagesSchema,\n videos: videosSchema,\n news: newsSchema,\n };\n\n if (searchProvider === 'serper' || searchProvider === 'tavily') {\n schemaProperties.country = countrySchema;\n }\n\n const toolSchema = {\n type: 'object',\n properties: schemaProperties,\n required: ['query'],\n };\n\n const searchAPI = createSearchAPI({\n searchProvider,\n serperApiKey,\n searxngInstanceUrl,\n searxngApiKey,\n tavilyApiKey,\n tavilySearchUrl,\n tavilySearchOptions: effectiveTavilySearchOptions,\n keenableApiKey,\n keenableApiUrl,\n keenableSearchOptions,\n crwApiKey,\n crwApiUrl,\n crwSearchOptions,\n });\n\n /** Create scraper based on scraperProvider */\n let scraperInstance: t.BaseScraper;\n\n if (scraperProvider === 'serper') {\n scraperInstance = createSerperScraper({\n ...serperScraperOptions,\n apiKey: serperApiKey,\n timeout: scraperTimeout ?? serperScraperOptions?.timeout,\n logger,\n });\n } else if (scraperProvider === 'tavily') {\n scraperInstance = createTavilyScraper({\n ...tavilyScraperOptions,\n apiKey:\n tavilyScraperOptions?.apiKey ??\n tavilyApiKey ??\n process.env.TAVILY_API_KEY,\n apiUrl: tavilyScraperOptions?.apiUrl ?? tavilyExtractUrl,\n timeout: scraperTimeout ?? tavilyScraperOptions?.timeout,\n logger,\n });\n } else if (scraperProvider === 'crw') {\n scraperInstance = createCrwScraper({\n ...crwScraperOptions,\n apiKey:\n crwScraperOptions?.apiKey ?? crwApiKey ?? process.env.CRW_API_KEY,\n apiUrl: crwScraperOptions?.apiUrl ?? crwApiUrl,\n timeout: scraperTimeout ?? crwScraperOptions?.timeout,\n formats: crwScraperOptions?.formats ?? ['markdown', 'rawHtml'],\n logger,\n });\n } else {\n scraperInstance = createFirecrawlScraper({\n ...firecrawlOptions,\n apiKey: firecrawlApiKey ?? process.env.FIRECRAWL_API_KEY,\n apiUrl: firecrawlApiUrl,\n version: firecrawlVersion,\n timeout: scraperTimeout ?? firecrawlOptions?.timeout,\n formats: firecrawlOptions?.formats ?? ['markdown', 'rawHtml'],\n logger,\n });\n }\n\n const selectedReranker = createReranker({\n rerankerType,\n jinaApiKey,\n jinaApiUrl,\n cohereApiKey,\n rerankerTimeout,\n logger,\n });\n\n if (!selectedReranker) {\n logger.warn('No reranker selected. Using default ranking.');\n }\n\n const sourceProcessor = createSourceProcessor(\n {\n reranker: selectedReranker,\n topResults,\n maxContentLength,\n chunkSize,\n chunkOverlap,\n strategies,\n filterContent,\n logger,\n },\n scraperInstance\n );\n\n const search = createSearchProcessor({\n searchAPI,\n safeSearch,\n // Keenable is organic-only: its API ignores `type`, so image/news\n // sub-searches would spend rate limit and merge nothing.\n supportsImages: searchProvider !== 'keenable',\n supportsVideos:\n searchProvider !== 'tavily' &&\n searchProvider !== 'keenable' &&\n searchProvider !== 'crw',\n supportsNews: searchProvider !== 'keenable',\n sourceProcessor,\n onGetHighlights,\n mainExpandBy,\n separatorExpandBy,\n logger,\n });\n\n return createTool({\n search,\n schema: toolSchema,\n maxOutputChars,\n onSearchResults: _onSearchResults,\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AA6BA,eAAsB,wBAAwB,EAC5C,WACA,OACA,MACA,SACA,YACA,QACA,QACA,MACA,UAW0B;CAE1B,MAAM,cAAyC,CAE7C,UAAU,WAAW;EACnB;EACA;EACA;EACA;CACF,CAAC,CACH;CAEA,IAAI,QACF,YAAY,KACV,UACG,WAAW;EACV;EACA;EACA;EACA;EACA,MAAM;CACR,CAAC,CAAC,CACD,OAAO,UAAU;EAChB,OAAO,MAAM,0BAA0B,KAAK;EAC5C,OAAO;GACL,SAAS;GACT,OAAO,yBAAyB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EACvF;CACF,CAAC,CACL;CAEF,IAAI,QACF,YAAY,KACV,UACG,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AAG;EACH,QAAQ,mBAAmB,QAAQ,IAAI;EACvC,QAAQ;EACR,SAAS;EACT,SAAS,kBAAkB,kBAAkB;EAC7C,SAAS,kBAAkB,WAAW,CAAC,YAAY,SAAS;EAC5D;CACF,CAAC;CAGH,MAAM,mBAAmBC,kBAAAA,eAAe;EACtC;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CAED,IAAI,CAAC,kBACH,OAAO,KAAK,8CAA8C;CAG5D,MAAM,kBAAkBC,eAAAA,sBACtB;EACE,UAAU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;CACF,GACA,eACF;CAoBA,OAAO,WAAW;EAChB,QAnBa,sBAAsB;GACnC;GACA;GAGA,gBAAgB,mBAAmB;GACnC,gBACE,mBAAmB,YACnB,mBAAmB,cACnB,mBAAmB;GACrB,cAAc,mBAAmB;GACjC;GACA;GACA;GACA;GACA;EACF,CAGO;EACL,QAAQ;EACR;EACA,iBAAiB;CACnB,CAAC;AACH"}
@@ -39,12 +39,12 @@ function formatReason(template, toolName) {
39
39
  * registry.register('PreToolUse', { hooks: [policyHook] });
40
40
  * ```
41
41
  *
42
- * Evaluation order matches Claude Code's permission flow:
42
+ * Explicit rules take precedence over fallback modes:
43
43
  *
44
44
  * 1. `deny` rule match → `'deny'` (always wins, even in `bypass`).
45
- * 2. `mode === 'bypass'` → `'allow'`.
45
+ * 2. `ask` rule match → `'ask'`.
46
46
  * 3. `allow` rule match → `'allow'`.
47
- * 4. `ask` rule match → `'ask'`.
47
+ * 4. `mode === 'bypass'` → `'allow'`.
48
48
  * 5. `mode === 'dontAsk'` → `'deny'`.
49
49
  * 6. fallthrough → `'ask'`.
50
50
  *
@@ -73,9 +73,9 @@ function createToolPolicyHook(config) {
73
73
  }
74
74
  function decide(toolName, mode, denyMatch, allowMatch, askMatch) {
75
75
  if (denyMatch(toolName)) return "deny";
76
- if (mode === "bypass") return "allow";
77
- if (allowMatch(toolName)) return "allow";
78
76
  if (askMatch(toolName)) return "ask";
77
+ if (allowMatch(toolName)) return "allow";
78
+ if (mode === "bypass") return "allow";
79
79
  if (mode === "dontAsk") return "deny";
80
80
  return "ask";
81
81
  }
@@ -1 +1 @@
1
- {"version":3,"file":"createToolPolicyHook.mjs","names":[],"sources":["../../../src/hooks/createToolPolicyHook.ts"],"sourcesContent":["/**\n * Declarative `PreToolUse` hook factory. Lets hosts express common\n * permission policies (allow / deny / ask lists + a global mode) without\n * hand-rolling matching, precedence, and decision logic per-host.\n *\n * Maps directly to the Claude Code Agent SDK permission vocabulary\n * (`allowed_tools` / `disallowed_tools` / `permissionMode`) so users of\n * either SDK can think in the same terms. See the README's HITL section\n * for the cross-walk and `docs/hooks-design-report.md` for the broader\n * hook system context.\n */\n\nimport type { HookCallback, PreToolUseHookOutput, ToolDecision } from './types';\n\n/**\n * Permission mode controlling how tool calls that match no rule are\n * resolved. Mirrors Claude Code's `permissionMode`.\n *\n * - `default` — unmatched tools fall through to `'ask'` (interrupt).\n * - `dontAsk` — unmatched tools are denied; the human is never\n * prompted. Useful for headless / API agents where a\n * silent denial is preferable to a hung interrupt.\n * - `bypass` — every tool is approved, except those matching `deny`\n * patterns. The kill switch you flip when you trust\n * the agent and want to stop being asked. Equivalent to\n * Claude Code's `bypassPermissions`.\n */\nexport type ToolPolicyMode = 'default' | 'dontAsk' | 'bypass';\n\nexport interface ToolPolicyConfig {\n /**\n * Global mode applied to tools that don't match any rule.\n * Defaults to `'default'` (ask the human).\n */\n mode?: ToolPolicyMode;\n /**\n * Tool name patterns that are auto-approved without a prompt.\n * Patterns support glob `*` wildcards: `read_file`, `mcp:github:*`,\n * `*search*`. Match is anchored (`^pattern$`).\n */\n allow?: readonly string[];\n /**\n * Tool name patterns that are blocked outright. Wins over `allow`\n * and `ask`, and overrides `mode: 'bypass'` — a deny rule always\n * holds, matching Claude Code's \"deny rules are checked first\" guarantee.\n */\n deny?: readonly string[];\n /**\n * Tool name patterns that always trigger human approval, regardless\n * of `mode: 'default'` vs `'dontAsk'`. In `mode: 'bypass'` these are\n * still bypassed (because that's what bypass means).\n */\n ask?: readonly string[];\n /**\n * Optional reason attached to the resulting `ask` / `deny` hook\n * decision so the host UI can render why approval is required.\n * The literal token `{tool}` is replaced with the tool name.\n */\n reason?: string;\n}\n\n/**\n * Compile a glob string with `*` wildcards into a single anchored\n * `RegExp`. Other regex metacharacters are escaped, so `read_file.md`\n * matches the literal dot. Patterns are short (tool names), so we do\n * not cache here — the registry's `matchesQuery` already caches its own\n * regex compilations and our patterns are evaluated once per ToolNode\n * batch, not once per stream chunk.\n */\nfunction globToRegex(pattern: string): RegExp {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp('^' + escaped.replace(/\\*/g, '.*') + '$');\n}\n\n/** Pre-compile a list of glob patterns into a single match function. */\nfunction compileMatchers(\n patterns: readonly string[] | undefined\n): (toolName: string) => boolean {\n if (patterns == null || patterns.length === 0) {\n return () => false;\n }\n const regexes = patterns.map(globToRegex);\n return (toolName: string): boolean => {\n for (const regex of regexes) {\n if (regex.test(toolName)) {\n return true;\n }\n }\n return false;\n };\n}\n\nfunction formatReason(\n template: string | undefined,\n toolName: string\n): string | undefined {\n if (template == null) {\n return undefined;\n }\n return template.replace(/\\{tool\\}/g, toolName);\n}\n\n/**\n * Build a `PreToolUse` hook callback that applies a declarative tool\n * permission policy. Register it with a `HookRegistry` and the SDK's\n * `humanInTheLoop` machinery handles the rest:\n *\n * ```ts\n * const policyHook = createToolPolicyHook({\n * mode: 'default',\n * allow: ['read_*', 'grep', 'glob'],\n * deny: ['delete_*'],\n * ask: ['execute_*', 'mcp:*'],\n * });\n * registry.register('PreToolUse', { hooks: [policyHook] });\n * ```\n *\n * Evaluation order matches Claude Code's permission flow:\n *\n * 1. `deny` rule match → `'deny'` (always wins, even in `bypass`).\n * 2. `mode === 'bypass'` → `'allow'`.\n * 3. `allow` rule match → `'allow'`.\n * 4. `ask` rule match → `'ask'`.\n * 5. `mode === 'dontAsk'` → `'deny'`.\n * 6. fallthrough → `'ask'`.\n *\n * The returned callback is a single `HookCallback`, not a `HookMatcher` —\n * register it under the matcher with the pattern you want (omit the\n * pattern to fire on every tool call, which is the typical case since\n * the policy itself does the filtering).\n */\nexport function createToolPolicyHook(\n config: ToolPolicyConfig\n): HookCallback<'PreToolUse'> {\n const denyMatcher = compileMatchers(config.deny);\n const allowMatcher = compileMatchers(config.allow);\n const askMatcher = compileMatchers(config.ask);\n const mode: ToolPolicyMode = config.mode ?? 'default';\n const reasonTemplate = config.reason;\n\n return async (input): Promise<PreToolUseHookOutput> => {\n const toolName = input.toolName;\n const decision = decide(\n toolName,\n mode,\n denyMatcher,\n allowMatcher,\n askMatcher\n );\n if (decision === 'allow') {\n return { decision };\n }\n const reason = formatReason(reasonTemplate, toolName);\n if (reason != null) {\n return { decision, reason };\n }\n return { decision };\n };\n}\n\nfunction decide(\n toolName: string,\n mode: ToolPolicyMode,\n denyMatch: (n: string) => boolean,\n allowMatch: (n: string) => boolean,\n askMatch: (n: string) => boolean\n): ToolDecision {\n if (denyMatch(toolName)) {\n return 'deny';\n }\n if (mode === 'bypass') {\n return 'allow';\n }\n if (allowMatch(toolName)) {\n return 'allow';\n }\n if (askMatch(toolName)) {\n return 'ask';\n }\n if (mode === 'dontAsk') {\n return 'deny';\n }\n return 'ask';\n}\n"],"mappings":";;;;;;;;;AAqEA,SAAS,YAAY,SAAyB;CAC5C,MAAM,UAAU,QAAQ,QAAQ,sBAAsB,MAAM;CAC5D,OAAO,IAAI,OAAO,MAAM,QAAQ,QAAQ,OAAO,IAAI,IAAI,GAAG;AAC5D;;AAGA,SAAS,gBACP,UAC+B;CAC/B,IAAI,YAAY,QAAQ,SAAS,WAAW,GAC1C,aAAa;CAEf,MAAM,UAAU,SAAS,IAAI,WAAW;CACxC,QAAQ,aAA8B;EACpC,KAAK,MAAM,SAAS,SAClB,IAAI,MAAM,KAAK,QAAQ,GACrB,OAAO;EAGX,OAAO;CACT;AACF;AAEA,SAAS,aACP,UACA,UACoB;CACpB,IAAI,YAAY,MACd;CAEF,OAAO,SAAS,QAAQ,aAAa,QAAQ;AAC/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,qBACd,QAC4B;CAC5B,MAAM,cAAc,gBAAgB,OAAO,IAAI;CAC/C,MAAM,eAAe,gBAAgB,OAAO,KAAK;CACjD,MAAM,aAAa,gBAAgB,OAAO,GAAG;CAC7C,MAAM,OAAuB,OAAO,QAAQ;CAC5C,MAAM,iBAAiB,OAAO;CAE9B,OAAO,OAAO,UAAyC;EACrD,MAAM,WAAW,MAAM;EACvB,MAAM,WAAW,OACf,UACA,MACA,aACA,cACA,UACF;EACA,IAAI,aAAa,SACf,OAAO,EAAE,SAAS;EAEpB,MAAM,SAAS,aAAa,gBAAgB,QAAQ;EACpD,IAAI,UAAU,MACZ,OAAO;GAAE;GAAU;EAAO;EAE5B,OAAO,EAAE,SAAS;CACpB;AACF;AAEA,SAAS,OACP,UACA,MACA,WACA,YACA,UACc;CACd,IAAI,UAAU,QAAQ,GACpB,OAAO;CAET,IAAI,SAAS,UACX,OAAO;CAET,IAAI,WAAW,QAAQ,GACrB,OAAO;CAET,IAAI,SAAS,QAAQ,GACnB,OAAO;CAET,IAAI,SAAS,WACX,OAAO;CAET,OAAO;AACT"}
1
+ {"version":3,"file":"createToolPolicyHook.mjs","names":[],"sources":["../../../src/hooks/createToolPolicyHook.ts"],"sourcesContent":["/**\n * Declarative `PreToolUse` hook factory. Lets hosts express common\n * permission policies (allow / deny / ask lists + a global mode) without\n * hand-rolling matching, precedence, and decision logic per-host.\n *\n * Uses the Claude Code Agent SDK permission vocabulary (`allowed_tools` /\n * `disallowed_tools` / `permissionMode`) while treating modes as fallbacks\n * for calls that match no explicit rule. See the README's HITL section for\n * the cross-walk and `docs/hooks-design-report.md` for the broader hook\n * system context.\n */\n\nimport type { HookCallback, PreToolUseHookOutput, ToolDecision } from './types';\n\n/**\n * Permission mode controlling how tool calls that match no rule are\n * resolved. Mirrors Claude Code's `permissionMode`.\n *\n * - `default` — unmatched tools fall through to `'ask'` (interrupt).\n * - `dontAsk` — unmatched tools are denied; the human is never\n * prompted. Useful for headless / API agents where a\n * silent denial is preferable to a hung interrupt.\n * - `bypass` — unmatched tools are approved. Explicit `deny` and `ask`\n * rules still apply.\n */\nexport type ToolPolicyMode = 'default' | 'dontAsk' | 'bypass';\n\nexport interface ToolPolicyConfig {\n /**\n * Global mode applied to tools that don't match any rule.\n * Defaults to `'default'` (ask the human).\n */\n mode?: ToolPolicyMode;\n /**\n * Tool name patterns that are auto-approved without a prompt.\n * Patterns support glob `*` wildcards: `read_file`, `mcp:github:*`,\n * `*search*`. Match is anchored (`^pattern$`).\n */\n allow?: readonly string[];\n /**\n * Tool name patterns that are blocked outright. Wins over `allow`\n * and `ask`, and overrides `mode: 'bypass'` — a deny rule always\n * holds, matching Claude Code's \"deny rules are checked first\" guarantee.\n */\n deny?: readonly string[];\n /**\n * Tool name patterns that always trigger human approval. Wins over\n * `allow` and every mode, but not `deny`.\n */\n ask?: readonly string[];\n /**\n * Optional reason attached to the resulting `ask` / `deny` hook\n * decision so the host UI can render why approval is required.\n * The literal token `{tool}` is replaced with the tool name.\n */\n reason?: string;\n}\n\n/**\n * Compile a glob string with `*` wildcards into a single anchored\n * `RegExp`. Other regex metacharacters are escaped, so `read_file.md`\n * matches the literal dot. Patterns are short (tool names), so we do\n * not cache here — the registry's `matchesQuery` already caches its own\n * regex compilations and our patterns are evaluated once per ToolNode\n * batch, not once per stream chunk.\n */\nfunction globToRegex(pattern: string): RegExp {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp('^' + escaped.replace(/\\*/g, '.*') + '$');\n}\n\n/** Pre-compile a list of glob patterns into a single match function. */\nfunction compileMatchers(\n patterns: readonly string[] | undefined\n): (toolName: string) => boolean {\n if (patterns == null || patterns.length === 0) {\n return () => false;\n }\n const regexes = patterns.map(globToRegex);\n return (toolName: string): boolean => {\n for (const regex of regexes) {\n if (regex.test(toolName)) {\n return true;\n }\n }\n return false;\n };\n}\n\nfunction formatReason(\n template: string | undefined,\n toolName: string\n): string | undefined {\n if (template == null) {\n return undefined;\n }\n return template.replace(/\\{tool\\}/g, toolName);\n}\n\n/**\n * Build a `PreToolUse` hook callback that applies a declarative tool\n * permission policy. Register it with a `HookRegistry` and the SDK's\n * `humanInTheLoop` machinery handles the rest:\n *\n * ```ts\n * const policyHook = createToolPolicyHook({\n * mode: 'default',\n * allow: ['read_*', 'grep', 'glob'],\n * deny: ['delete_*'],\n * ask: ['execute_*', 'mcp:*'],\n * });\n * registry.register('PreToolUse', { hooks: [policyHook] });\n * ```\n *\n * Explicit rules take precedence over fallback modes:\n *\n * 1. `deny` rule match → `'deny'` (always wins, even in `bypass`).\n * 2. `ask` rule match → `'ask'`.\n * 3. `allow` rule match → `'allow'`.\n * 4. `mode === 'bypass'` → `'allow'`.\n * 5. `mode === 'dontAsk'` → `'deny'`.\n * 6. fallthrough → `'ask'`.\n *\n * The returned callback is a single `HookCallback`, not a `HookMatcher` —\n * register it under the matcher with the pattern you want (omit the\n * pattern to fire on every tool call, which is the typical case since\n * the policy itself does the filtering).\n */\nexport function createToolPolicyHook(\n config: ToolPolicyConfig\n): HookCallback<'PreToolUse'> {\n const denyMatcher = compileMatchers(config.deny);\n const allowMatcher = compileMatchers(config.allow);\n const askMatcher = compileMatchers(config.ask);\n const mode: ToolPolicyMode = config.mode ?? 'default';\n const reasonTemplate = config.reason;\n\n return async (input): Promise<PreToolUseHookOutput> => {\n const toolName = input.toolName;\n const decision = decide(\n toolName,\n mode,\n denyMatcher,\n allowMatcher,\n askMatcher\n );\n if (decision === 'allow') {\n return { decision };\n }\n const reason = formatReason(reasonTemplate, toolName);\n if (reason != null) {\n return { decision, reason };\n }\n return { decision };\n };\n}\n\nfunction decide(\n toolName: string,\n mode: ToolPolicyMode,\n denyMatch: (n: string) => boolean,\n allowMatch: (n: string) => boolean,\n askMatch: (n: string) => boolean\n): ToolDecision {\n if (denyMatch(toolName)) {\n return 'deny';\n }\n if (askMatch(toolName)) {\n return 'ask';\n }\n if (allowMatch(toolName)) {\n return 'allow';\n }\n if (mode === 'bypass') {\n return 'allow';\n }\n if (mode === 'dontAsk') {\n return 'deny';\n }\n return 'ask';\n}\n"],"mappings":";;;;;;;;;AAkEA,SAAS,YAAY,SAAyB;CAC5C,MAAM,UAAU,QAAQ,QAAQ,sBAAsB,MAAM;CAC5D,OAAO,IAAI,OAAO,MAAM,QAAQ,QAAQ,OAAO,IAAI,IAAI,GAAG;AAC5D;;AAGA,SAAS,gBACP,UAC+B;CAC/B,IAAI,YAAY,QAAQ,SAAS,WAAW,GAC1C,aAAa;CAEf,MAAM,UAAU,SAAS,IAAI,WAAW;CACxC,QAAQ,aAA8B;EACpC,KAAK,MAAM,SAAS,SAClB,IAAI,MAAM,KAAK,QAAQ,GACrB,OAAO;EAGX,OAAO;CACT;AACF;AAEA,SAAS,aACP,UACA,UACoB;CACpB,IAAI,YAAY,MACd;CAEF,OAAO,SAAS,QAAQ,aAAa,QAAQ;AAC/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,qBACd,QAC4B;CAC5B,MAAM,cAAc,gBAAgB,OAAO,IAAI;CAC/C,MAAM,eAAe,gBAAgB,OAAO,KAAK;CACjD,MAAM,aAAa,gBAAgB,OAAO,GAAG;CAC7C,MAAM,OAAuB,OAAO,QAAQ;CAC5C,MAAM,iBAAiB,OAAO;CAE9B,OAAO,OAAO,UAAyC;EACrD,MAAM,WAAW,MAAM;EACvB,MAAM,WAAW,OACf,UACA,MACA,aACA,cACA,UACF;EACA,IAAI,aAAa,SACf,OAAO,EAAE,SAAS;EAEpB,MAAM,SAAS,aAAa,gBAAgB,QAAQ;EACpD,IAAI,UAAU,MACZ,OAAO;GAAE;GAAU;EAAO;EAE5B,OAAO,EAAE,SAAS;CACpB;AACF;AAEA,SAAS,OACP,UACA,MACA,WACA,YACA,UACc;CACd,IAAI,UAAU,QAAQ,GACpB,OAAO;CAET,IAAI,SAAS,QAAQ,GACnB,OAAO;CAET,IAAI,WAAW,QAAQ,GACrB,OAAO;CAET,IAAI,SAAS,UACX,OAAO;CAET,IAAI,SAAS,WACX,OAAO;CAET,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { convertBaseMessagesToContent, convertResponseContentToChatGenerationChunk, mapGenerateContentResultToChatResult } from "./utils/common.mjs";
1
+ import { convertBaseMessagesToContent, convertResponseContentToChatGenerationChunk, dropUnsupportedModelTurnPrefill, mapGenerateContentResultToChatResult } from "./utils/common.mjs";
2
2
  import { AIMessageChunk } from "@langchain/core/messages";
3
3
  import { ChatGenerationChunk } from "@langchain/core/outputs";
4
4
  import { getEnvironmentVariable } from "@langchain/core/utils/env";
@@ -120,6 +120,7 @@ var CustomChatGoogleGenerativeAI = class extends ChatGoogleGenerativeAI {
120
120
  this.client.systemInstruction = systemInstruction;
121
121
  actualPrompt = prompt.slice(1);
122
122
  }
123
+ actualPrompt = dropUnsupportedModelTurnPrefill(actualPrompt, this.model);
123
124
  const request = {
124
125
  ...this.invocationParams(options),
125
126
  contents: actualPrompt
@@ -143,6 +144,7 @@ var CustomChatGoogleGenerativeAI = class extends ChatGoogleGenerativeAI {
143
144
  this.client.systemInstruction = systemInstruction;
144
145
  actualPrompt = prompt.slice(1);
145
146
  }
147
+ actualPrompt = dropUnsupportedModelTurnPrefill(actualPrompt, this.model);
146
148
  const request = {
147
149
  ...this.invocationParams(options),
148
150
  contents: actualPrompt
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["GenerativeAI"],"sources":["../../../../src/llm/google/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/ban-ts-comment */\nimport { AIMessageChunk } from '@langchain/core/messages';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport { ChatGoogleGenerativeAI } from '@langchain/google-genai';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport {\n FunctionCallingMode,\n GoogleGenerativeAI as GenerativeAI,\n} from '@google/generative-ai';\nimport type {\n GenerateContentRequest,\n SafetySetting,\n ToolConfig,\n} from '@google/generative-ai';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport type { BaseMessage, UsageMetadata } from '@langchain/core/messages';\nimport type { GeminiApiUsageMetadata, InputTokenDetails } from './types';\nimport type { GoogleClientOptions, GoogleThinkingConfig } from '@/types';\nimport {\n convertResponseContentToChatGenerationChunk,\n convertBaseMessagesToContent,\n mapGenerateContentResultToChatResult,\n} from './utils/common';\n\ntype GoogleToolConfigWithServerSideInvocations = ToolConfig & {\n includeServerSideToolInvocations?: boolean;\n functionCallingConfig?: Omit<\n NonNullable<ToolConfig['functionCallingConfig']>,\n 'mode'\n > & {\n mode?:\n | NonNullable<ToolConfig['functionCallingConfig']>['mode']\n | 'VALIDATED';\n };\n};\n\nexport class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {\n thinkingConfig?: GoogleThinkingConfig;\n includeServerSideToolInvocations?: boolean;\n\n /**\n * Override to add gemini-3 model support for multimodal and function calling thought signatures\n */\n get _isMultimodalModel(): boolean {\n return (\n this.model.startsWith('gemini-1.5') ||\n this.model.startsWith('gemini-2') ||\n (this.model.startsWith('gemma-3-') &&\n !this.model.startsWith('gemma-3-1b')) ||\n this.model.startsWith('gemini-3')\n );\n }\n\n constructor(fields: GoogleClientOptions) {\n super(fields);\n\n this.model = fields.model.replace(/^models\\//, '');\n\n this.maxOutputTokens = fields.maxOutputTokens ?? this.maxOutputTokens;\n\n if (this.maxOutputTokens != null && this.maxOutputTokens < 0) {\n throw new Error('`maxOutputTokens` must be a positive integer');\n }\n\n this.temperature = fields.temperature ?? this.temperature;\n if (\n this.temperature != null &&\n (this.temperature < 0 || this.temperature > 2)\n ) {\n throw new Error('`temperature` must be in the range of [0.0,2.0]');\n }\n\n this.topP = fields.topP ?? this.topP;\n if (this.topP != null && this.topP < 0) {\n throw new Error('`topP` must be a positive integer');\n }\n\n if (this.topP != null && this.topP > 1) {\n throw new Error('`topP` must be below 1.');\n }\n\n this.topK = fields.topK ?? this.topK;\n if (this.topK != null && this.topK < 0) {\n throw new Error('`topK` must be a positive integer');\n }\n\n this.stopSequences = fields.stopSequences ?? this.stopSequences;\n\n this.apiKey = fields.apiKey ?? getEnvironmentVariable('GOOGLE_API_KEY');\n if (this.apiKey == null || this.apiKey === '') {\n throw new Error(\n 'Please set an API key for Google GenerativeAI ' +\n 'in the environment variable GOOGLE_API_KEY ' +\n 'or in the `apiKey` field of the ' +\n 'ChatGoogleGenerativeAI constructor'\n );\n }\n\n this.safetySettings = fields.safetySettings ?? this.safetySettings;\n if (this.safetySettings && this.safetySettings.length > 0) {\n const safetySettingsSet = new Set(\n this.safetySettings.map((s) => s.category)\n );\n if (safetySettingsSet.size !== this.safetySettings.length) {\n throw new Error(\n 'The categories in `safetySettings` array must be unique'\n );\n }\n }\n\n this.thinkingConfig = fields.thinkingConfig ?? this.thinkingConfig;\n this.includeServerSideToolInvocations =\n fields.includeServerSideToolInvocations ??\n this.includeServerSideToolInvocations;\n\n this.streaming = fields.streaming ?? this.streaming;\n this.json = fields.json;\n\n // @ts-ignore - Accessing private property from parent class\n this.client = new GenerativeAI(this.apiKey).getGenerativeModel(\n {\n model: this.model,\n safetySettings: this.safetySettings as SafetySetting[],\n generationConfig: {\n stopSequences: this.stopSequences,\n maxOutputTokens: this.maxOutputTokens,\n temperature: this.temperature,\n topP: this.topP,\n topK: this.topK,\n ...(this.json != null\n ? { responseMimeType: 'application/json' }\n : {}),\n },\n },\n {\n apiVersion: fields.apiVersion,\n baseUrl: fields.baseUrl,\n customHeaders: fields.customHeaders,\n }\n );\n this.streamUsage = fields.streamUsage ?? this.streamUsage;\n }\n\n static lc_name(): 'LibreChatGoogleGenerativeAI' {\n return 'LibreChatGoogleGenerativeAI';\n }\n\n /**\n * Helper function to convert Gemini API usage metadata to LangChain format\n * Includes support for cached tokens and tier-based tracking for gemini-3-pro-preview\n */\n private _convertToUsageMetadata(\n usageMetadata: GeminiApiUsageMetadata | undefined,\n model: string\n ): UsageMetadata | undefined {\n if (!usageMetadata) {\n return undefined;\n }\n\n const output: UsageMetadata = {\n input_tokens: usageMetadata.promptTokenCount ?? 0,\n output_tokens:\n (usageMetadata.candidatesTokenCount ?? 0) +\n (usageMetadata.thoughtsTokenCount ?? 0),\n total_tokens: usageMetadata.totalTokenCount ?? 0,\n };\n\n if (usageMetadata.cachedContentTokenCount) {\n output.input_token_details ??= {};\n output.input_token_details.cache_read =\n usageMetadata.cachedContentTokenCount;\n }\n\n // gemini-3-pro-preview has bracket based tracking of tokens per request\n if (model === 'gemini-3-pro-preview') {\n const over200k = Math.max(\n 0,\n (usageMetadata.promptTokenCount ?? 0) - 200000\n );\n const cachedOver200k = Math.max(\n 0,\n (usageMetadata.cachedContentTokenCount ?? 0) - 200000\n );\n if (over200k) {\n output.input_token_details = {\n ...output.input_token_details,\n over_200k: over200k,\n } as InputTokenDetails;\n }\n if (cachedOver200k) {\n output.input_token_details = {\n ...output.input_token_details,\n cache_read_over_200k: cachedOver200k,\n } as InputTokenDetails;\n }\n }\n\n return output;\n }\n\n invocationParams(\n options?: this['ParsedCallOptions']\n ): Omit<GenerateContentRequest, 'contents'> {\n const params = super.invocationParams(options);\n if (this.thinkingConfig) {\n /** @ts-ignore */\n this.client.generationConfig = {\n /** @ts-ignore */\n ...this.client.generationConfig,\n /** @ts-ignore */\n thinkingConfig: this.thinkingConfig,\n };\n }\n if (\n this.includeServerSideToolInvocations === true &&\n Array.isArray(params.tools) &&\n params.tools.length > 0\n ) {\n const toolConfig = params.toolConfig as\n | GoogleToolConfigWithServerSideInvocations\n | undefined;\n const functionCallingConfig = toolConfig?.functionCallingConfig;\n params.toolConfig = {\n ...toolConfig,\n ...(functionCallingConfig?.mode === FunctionCallingMode.AUTO\n ? {\n functionCallingConfig: {\n ...functionCallingConfig,\n mode: 'VALIDATED',\n },\n }\n : {}),\n includeServerSideToolInvocations: true,\n } as ToolConfig;\n }\n return params;\n }\n\n async _generate(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): Promise<import('@langchain/core/outputs').ChatResult> {\n const prompt = convertBaseMessagesToContent(\n messages,\n this._isMultimodalModel,\n this.useSystemInstruction,\n this.model\n );\n let actualPrompt = prompt;\n if (prompt?.[0].role === 'system') {\n const [systemInstruction] = prompt;\n /** @ts-ignore */\n this.client.systemInstruction = systemInstruction;\n actualPrompt = prompt.slice(1);\n }\n const parameters = this.invocationParams(options);\n const request = {\n ...parameters,\n contents: actualPrompt,\n };\n\n const res = await this.caller.callWithOptions(\n { signal: options.signal },\n async () =>\n /** @ts-ignore */\n this.client.generateContent(request)\n );\n\n const response = res.response;\n const usageMetadata = this._convertToUsageMetadata(\n /** @ts-ignore */\n response.usageMetadata,\n this.model\n );\n\n /** @ts-ignore */\n const generationResult = mapGenerateContentResultToChatResult(response, {\n usageMetadata,\n });\n\n await runManager?.handleLLMNewToken(\n generationResult.generations[0].text || '',\n undefined,\n undefined,\n undefined,\n undefined,\n undefined\n );\n return generationResult;\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const prompt = convertBaseMessagesToContent(\n messages,\n this._isMultimodalModel,\n this.useSystemInstruction,\n this.model\n );\n let actualPrompt = prompt;\n if (prompt?.[0].role === 'system') {\n const [systemInstruction] = prompt;\n /** @ts-ignore */\n this.client.systemInstruction = systemInstruction;\n actualPrompt = prompt.slice(1);\n }\n const parameters = this.invocationParams(options);\n const request = {\n ...parameters,\n contents: actualPrompt,\n };\n const stream = await this.caller.callWithOptions(\n { signal: options.signal },\n async () => {\n /** @ts-ignore */\n const { stream } = await this.client.generateContentStream(request);\n return stream;\n }\n );\n\n let index = 0;\n let lastUsageMetadata: UsageMetadata | undefined;\n for await (const response of stream) {\n if (\n 'usageMetadata' in response &&\n this.streamUsage !== false &&\n options.streamUsage !== false\n ) {\n lastUsageMetadata = this._convertToUsageMetadata(\n response.usageMetadata as GeminiApiUsageMetadata | undefined,\n this.model\n );\n }\n\n const chunk = convertResponseContentToChatGenerationChunk(response, {\n usageMetadata: undefined,\n index,\n });\n index += 1;\n if (!chunk) {\n continue;\n }\n\n yield chunk;\n await runManager?.handleLLMNewToken(\n chunk.text || '',\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk }\n );\n }\n\n if (lastUsageMetadata) {\n const finalChunk = new ChatGenerationChunk({\n text: '',\n message: new AIMessageChunk({\n content: '',\n usage_metadata: lastUsageMetadata,\n }),\n });\n yield finalChunk;\n await runManager?.handleLLMNewToken(\n finalChunk.text || '',\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: finalChunk }\n );\n }\n }\n}\n"],"mappings":";;;;;;;AAoCA,IAAa,+BAAb,cAAkD,uBAAuB;CACvE;CACA;;;;CAKA,IAAI,qBAA8B;EAChC,OACE,KAAK,MAAM,WAAW,YAAY,KAClC,KAAK,MAAM,WAAW,UAAU,KAC/B,KAAK,MAAM,WAAW,UAAU,KAC/B,CAAC,KAAK,MAAM,WAAW,YAAY,KACrC,KAAK,MAAM,WAAW,UAAU;CAEpC;CAEA,YAAY,QAA6B;EACvC,MAAM,MAAM;EAEZ,KAAK,QAAQ,OAAO,MAAM,QAAQ,aAAa,EAAE;EAEjD,KAAK,kBAAkB,OAAO,mBAAmB,KAAK;EAEtD,IAAI,KAAK,mBAAmB,QAAQ,KAAK,kBAAkB,GACzD,MAAM,IAAI,MAAM,8CAA8C;EAGhE,KAAK,cAAc,OAAO,eAAe,KAAK;EAC9C,IACE,KAAK,eAAe,SACnB,KAAK,cAAc,KAAK,KAAK,cAAc,IAE5C,MAAM,IAAI,MAAM,iDAAiD;EAGnE,KAAK,OAAO,OAAO,QAAQ,KAAK;EAChC,IAAI,KAAK,QAAQ,QAAQ,KAAK,OAAO,GACnC,MAAM,IAAI,MAAM,mCAAmC;EAGrD,IAAI,KAAK,QAAQ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EAAE,MAAM,CACV;EACF;EAEA,IAAI,mBAAmB;GACrB,MAAM,aAAa,IAAI,oBAAoB;IACzC,MAAM;IACN,SAAS,IAAI,eAAe;KAC1B,SAAS;KACT,gBAAgB;IAClB,CAAC;GACH,CAAC;GACD,MAAM;GACN,MAAM,YAAY,kBAChB,WAAW,QAAQ,IACnB,KAAA,GACA,KAAA,GACA,KAAA,GACA,KAAA,GACA,EAAE,OAAO,WAAW,CACtB;EACF;CACF;AACF"}
1
+ {"version":3,"file":"index.mjs","names":["GenerativeAI"],"sources":["../../../../src/llm/google/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/ban-ts-comment */\nimport { AIMessageChunk } from '@langchain/core/messages';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport { ChatGoogleGenerativeAI } from '@langchain/google-genai';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport {\n FunctionCallingMode,\n GoogleGenerativeAI as GenerativeAI,\n} from '@google/generative-ai';\nimport type {\n GenerateContentRequest,\n SafetySetting,\n ToolConfig,\n} from '@google/generative-ai';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport type { BaseMessage, UsageMetadata } from '@langchain/core/messages';\nimport type { GeminiApiUsageMetadata, InputTokenDetails } from './types';\nimport type { GoogleClientOptions, GoogleThinkingConfig } from '@/types';\nimport {\n convertResponseContentToChatGenerationChunk,\n convertBaseMessagesToContent,\n dropUnsupportedModelTurnPrefill,\n mapGenerateContentResultToChatResult,\n} from './utils/common';\n\ntype GoogleToolConfigWithServerSideInvocations = ToolConfig & {\n includeServerSideToolInvocations?: boolean;\n functionCallingConfig?: Omit<\n NonNullable<ToolConfig['functionCallingConfig']>,\n 'mode'\n > & {\n mode?:\n | NonNullable<ToolConfig['functionCallingConfig']>['mode']\n | 'VALIDATED';\n };\n};\n\nexport class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {\n thinkingConfig?: GoogleThinkingConfig;\n includeServerSideToolInvocations?: boolean;\n\n /**\n * Override to add gemini-3 model support for multimodal and function calling thought signatures\n */\n get _isMultimodalModel(): boolean {\n return (\n this.model.startsWith('gemini-1.5') ||\n this.model.startsWith('gemini-2') ||\n (this.model.startsWith('gemma-3-') &&\n !this.model.startsWith('gemma-3-1b')) ||\n this.model.startsWith('gemini-3')\n );\n }\n\n constructor(fields: GoogleClientOptions) {\n super(fields);\n\n this.model = fields.model.replace(/^models\\//, '');\n\n this.maxOutputTokens = fields.maxOutputTokens ?? this.maxOutputTokens;\n\n if (this.maxOutputTokens != null && this.maxOutputTokens < 0) {\n throw new Error('`maxOutputTokens` must be a positive integer');\n }\n\n this.temperature = fields.temperature ?? this.temperature;\n if (\n this.temperature != null &&\n (this.temperature < 0 || this.temperature > 2)\n ) {\n throw new Error('`temperature` must be in the range of [0.0,2.0]');\n }\n\n this.topP = fields.topP ?? this.topP;\n if (this.topP != null && this.topP < 0) {\n throw new Error('`topP` must be a positive integer');\n }\n\n if (this.topP != null && this.topP > 1) {\n throw new Error('`topP` must be below 1.');\n }\n\n this.topK = fields.topK ?? this.topK;\n if (this.topK != null && this.topK < 0) {\n throw new Error('`topK` must be a positive integer');\n }\n\n this.stopSequences = fields.stopSequences ?? this.stopSequences;\n\n this.apiKey = fields.apiKey ?? getEnvironmentVariable('GOOGLE_API_KEY');\n if (this.apiKey == null || this.apiKey === '') {\n throw new Error(\n 'Please set an API key for Google GenerativeAI ' +\n 'in the environment variable GOOGLE_API_KEY ' +\n 'or in the `apiKey` field of the ' +\n 'ChatGoogleGenerativeAI constructor'\n );\n }\n\n this.safetySettings = fields.safetySettings ?? this.safetySettings;\n if (this.safetySettings && this.safetySettings.length > 0) {\n const safetySettingsSet = new Set(\n this.safetySettings.map((s) => s.category)\n );\n if (safetySettingsSet.size !== this.safetySettings.length) {\n throw new Error(\n 'The categories in `safetySettings` array must be unique'\n );\n }\n }\n\n this.thinkingConfig = fields.thinkingConfig ?? this.thinkingConfig;\n this.includeServerSideToolInvocations =\n fields.includeServerSideToolInvocations ??\n this.includeServerSideToolInvocations;\n\n this.streaming = fields.streaming ?? this.streaming;\n this.json = fields.json;\n\n // @ts-ignore - Accessing private property from parent class\n this.client = new GenerativeAI(this.apiKey).getGenerativeModel(\n {\n model: this.model,\n safetySettings: this.safetySettings as SafetySetting[],\n generationConfig: {\n stopSequences: this.stopSequences,\n maxOutputTokens: this.maxOutputTokens,\n temperature: this.temperature,\n topP: this.topP,\n topK: this.topK,\n ...(this.json != null\n ? { responseMimeType: 'application/json' }\n : {}),\n },\n },\n {\n apiVersion: fields.apiVersion,\n baseUrl: fields.baseUrl,\n customHeaders: fields.customHeaders,\n }\n );\n this.streamUsage = fields.streamUsage ?? this.streamUsage;\n }\n\n static lc_name(): 'LibreChatGoogleGenerativeAI' {\n return 'LibreChatGoogleGenerativeAI';\n }\n\n /**\n * Helper function to convert Gemini API usage metadata to LangChain format\n * Includes support for cached tokens and tier-based tracking for gemini-3-pro-preview\n */\n private _convertToUsageMetadata(\n usageMetadata: GeminiApiUsageMetadata | undefined,\n model: string\n ): UsageMetadata | undefined {\n if (!usageMetadata) {\n return undefined;\n }\n\n const output: UsageMetadata = {\n input_tokens: usageMetadata.promptTokenCount ?? 0,\n output_tokens:\n (usageMetadata.candidatesTokenCount ?? 0) +\n (usageMetadata.thoughtsTokenCount ?? 0),\n total_tokens: usageMetadata.totalTokenCount ?? 0,\n };\n\n if (usageMetadata.cachedContentTokenCount) {\n output.input_token_details ??= {};\n output.input_token_details.cache_read =\n usageMetadata.cachedContentTokenCount;\n }\n\n // gemini-3-pro-preview has bracket based tracking of tokens per request\n if (model === 'gemini-3-pro-preview') {\n const over200k = Math.max(\n 0,\n (usageMetadata.promptTokenCount ?? 0) - 200000\n );\n const cachedOver200k = Math.max(\n 0,\n (usageMetadata.cachedContentTokenCount ?? 0) - 200000\n );\n if (over200k) {\n output.input_token_details = {\n ...output.input_token_details,\n over_200k: over200k,\n } as InputTokenDetails;\n }\n if (cachedOver200k) {\n output.input_token_details = {\n ...output.input_token_details,\n cache_read_over_200k: cachedOver200k,\n } as InputTokenDetails;\n }\n }\n\n return output;\n }\n\n invocationParams(\n options?: this['ParsedCallOptions']\n ): Omit<GenerateContentRequest, 'contents'> {\n const params = super.invocationParams(options);\n if (this.thinkingConfig) {\n /** @ts-ignore */\n this.client.generationConfig = {\n /** @ts-ignore */\n ...this.client.generationConfig,\n /** @ts-ignore */\n thinkingConfig: this.thinkingConfig,\n };\n }\n if (\n this.includeServerSideToolInvocations === true &&\n Array.isArray(params.tools) &&\n params.tools.length > 0\n ) {\n const toolConfig = params.toolConfig as\n | GoogleToolConfigWithServerSideInvocations\n | undefined;\n const functionCallingConfig = toolConfig?.functionCallingConfig;\n params.toolConfig = {\n ...toolConfig,\n ...(functionCallingConfig?.mode === FunctionCallingMode.AUTO\n ? {\n functionCallingConfig: {\n ...functionCallingConfig,\n mode: 'VALIDATED',\n },\n }\n : {}),\n includeServerSideToolInvocations: true,\n } as ToolConfig;\n }\n return params;\n }\n\n async _generate(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): Promise<import('@langchain/core/outputs').ChatResult> {\n const prompt = convertBaseMessagesToContent(\n messages,\n this._isMultimodalModel,\n this.useSystemInstruction,\n this.model\n );\n let actualPrompt = prompt;\n if (prompt?.[0].role === 'system') {\n const [systemInstruction] = prompt;\n /** @ts-ignore */\n this.client.systemInstruction = systemInstruction;\n actualPrompt = prompt.slice(1);\n }\n actualPrompt = dropUnsupportedModelTurnPrefill(actualPrompt, this.model);\n const parameters = this.invocationParams(options);\n const request = {\n ...parameters,\n contents: actualPrompt,\n };\n\n const res = await this.caller.callWithOptions(\n { signal: options.signal },\n async () =>\n /** @ts-ignore */\n this.client.generateContent(request)\n );\n\n const response = res.response;\n const usageMetadata = this._convertToUsageMetadata(\n /** @ts-ignore */\n response.usageMetadata,\n this.model\n );\n\n /** @ts-ignore */\n const generationResult = mapGenerateContentResultToChatResult(response, {\n usageMetadata,\n });\n\n await runManager?.handleLLMNewToken(\n generationResult.generations[0].text || '',\n undefined,\n undefined,\n undefined,\n undefined,\n undefined\n );\n return generationResult;\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const prompt = convertBaseMessagesToContent(\n messages,\n this._isMultimodalModel,\n this.useSystemInstruction,\n this.model\n );\n let actualPrompt = prompt;\n if (prompt?.[0].role === 'system') {\n const [systemInstruction] = prompt;\n /** @ts-ignore */\n this.client.systemInstruction = systemInstruction;\n actualPrompt = prompt.slice(1);\n }\n actualPrompt = dropUnsupportedModelTurnPrefill(actualPrompt, this.model);\n const parameters = this.invocationParams(options);\n const request = {\n ...parameters,\n contents: actualPrompt,\n };\n const stream = await this.caller.callWithOptions(\n { signal: options.signal },\n async () => {\n /** @ts-ignore */\n const { stream } = await this.client.generateContentStream(request);\n return stream;\n }\n );\n\n let index = 0;\n let lastUsageMetadata: UsageMetadata | undefined;\n for await (const response of stream) {\n if (\n 'usageMetadata' in response &&\n this.streamUsage !== false &&\n options.streamUsage !== false\n ) {\n lastUsageMetadata = this._convertToUsageMetadata(\n response.usageMetadata as GeminiApiUsageMetadata | undefined,\n this.model\n );\n }\n\n const chunk = convertResponseContentToChatGenerationChunk(response, {\n usageMetadata: undefined,\n index,\n });\n index += 1;\n if (!chunk) {\n continue;\n }\n\n yield chunk;\n await runManager?.handleLLMNewToken(\n chunk.text || '',\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk }\n );\n }\n\n if (lastUsageMetadata) {\n const finalChunk = new ChatGenerationChunk({\n text: '',\n message: new AIMessageChunk({\n content: '',\n usage_metadata: lastUsageMetadata,\n }),\n });\n yield finalChunk;\n await runManager?.handleLLMNewToken(\n finalChunk.text || '',\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: finalChunk }\n );\n }\n }\n}\n"],"mappings":";;;;;;;AAqCA,IAAa,+BAAb,cAAk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e;EACnB,IAAI,SAAS,EAAE,CAAC,SAAS,UAAU;GACjC,MAAM,CAAC,qBAAqB;;GAE5B,KAAK,OAAO,oBAAoB;GAChC,eAAe,OAAO,MAAM,CAAC;EAC/B;EACA,eAAe,gCAAgC,cAAc,KAAK,KAAK;EAEvE,MAAM,UAAU;GACd,GAFiB,KAAK,iBAAiB,OAE3B;GACZ,UAAU;EACZ;EACA,MAAM,SAAS,MAAM,KAAK,OAAO,gBAC/B,EAAE,QAAQ,QAAQ,OAAO,GACzB,YAAY;;GAEV,MAAM,EAAE,WAAW,MAAM,KAAK,OAAO,sBAAsB,OAAO;GAClE,OAAO;EACT,CACF;EAEA,IAAI,QAAQ;EACZ,IAAI;EACJ,WAAW,MAAM,YAAY,QAAQ;GACnC,IACE,mBAAmB,YACnB,KAAK,gBAAgB,SACrB,QAAQ,gBAAgB,OAExB,oBAAoB,KAAK,wBACvB,SAAS,eACT,KAAK,KACP;GAGF,MAAM,QAAQ,4CAA4C,UAAU;IAClE,eAAe,KAAA;IACf;GACF,CAAC;GACD,SAAS;GACT,IAAI,CAAC,OACH;GAGF,MAAM;GACN,MAAM,YAAY,kBAChB,MAAM,QAAQ,IACd,KAAA,GACA,KAAA,GACA,KAAA,GACA,KAAA,GACA,EAAE,MAAM,CACV;EACF;EAEA,IAAI,mBAAmB;GACrB,MAAM,aAAa,IAAI,oBAAoB;IACzC,MAAM;IACN,SAAS,IAAI,eAAe;KAC1B,SAAS;KACT,gBAAgB;IAClB,CAAC;GACH,CAAC;GACD,MAAM;GACN,MAAM,YAAY,kBAChB,WAAW,QAAQ,IACnB,KAAA,GACA,KAAA,GACA,KAAA,GACA,KAAA,GACA,EAAE,OAAO,WAAW,CACtB;EACF;CACF;AACF"}
@@ -277,6 +277,33 @@ function convertBaseMessagesToContent(messages, isMultimodalModel, convertSystem
277
277
  mergeWithPreviousContent: false
278
278
  }).content;
279
279
  }
280
+ /**
281
+ * Gemini models that reject a request whose `contents` end with a `model`-role
282
+ * turn (a "prefill"). Google enforces this on newer generations (Gemini 3.6
283
+ * Flash, Gemini 3.5 Flash-Lite) while older/sibling models still accept a
284
+ * trailing model turn, so the rule is model-scoped rather than version-wide.
285
+ * Extend this list as Google applies the restriction to further models.
286
+ * @see https://ai.google.dev/gemini-api/docs/latest-model#api-changes-and-parameter-updates
287
+ */
288
+ const NO_PREFILL_GEMINI_MODELS = ["gemini-3.6-flash", "gemini-3.5-flash-lite"];
289
+ function rejectsModelTurnPrefill(model) {
290
+ if (model == null || model === "") return false;
291
+ const modelId = model.toLowerCase().split("/").pop() ?? "";
292
+ return NO_PREFILL_GEMINI_MODELS.some((id) => modelId === id || modelId.startsWith(`${id}-`));
293
+ }
294
+ /**
295
+ * Drops trailing `model`-role turns for models that reject prefill (see
296
+ * {@link rejectsModelTurnPrefill}). Such a turn is only produced by prefill
297
+ * flows (e.g. editing an assistant reply and resubmitting); these models return
298
+ * HTTP 400 for it, so we drop it and let the model generate fresh from the
299
+ * preceding user turn. No-op for every other model, preserving working prefill.
300
+ */
301
+ function dropUnsupportedModelTurnPrefill(contents, model) {
302
+ if (contents == null || contents.length === 0 || !rejectsModelTurnPrefill(model)) return contents;
303
+ let end = contents.length;
304
+ while (end > 1 && contents[end - 1]?.role === "model") end -= 1;
305
+ return end === contents.length ? contents : contents.slice(0, end);
306
+ }
280
307
  function convertResponseContentToChatGenerationChunk(response, extra) {
281
308
  if (!response.candidates || response.candidates.length === 0) return null;
282
309
  const [candidate] = response.candidates;
@@ -432,6 +459,6 @@ function mapGenerateContentResultToChatResult(response, extra) {
432
459
  };
433
460
  }
434
461
  //#endregion
435
- export { convertBaseMessagesToContent, convertResponseContentToChatGenerationChunk, mapGenerateContentResultToChatResult };
462
+ export { convertBaseMessagesToContent, convertResponseContentToChatGenerationChunk, dropUnsupportedModelTurnPrefill, mapGenerateContentResultToChatResult };
436
463
 
437
464
  //# sourceMappingURL=common.mjs.map