@librechat/agents 3.3.5 → 3.3.7

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 (127) hide show
  1. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs +1 -1
  2. package/dist/cjs/llm/openai/index.cjs +51 -6
  3. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  4. package/dist/cjs/main.cjs +16 -0
  5. package/dist/cjs/session/JsonlSessionStore.cjs +1 -1
  6. package/dist/cjs/stream.cjs +6 -1
  7. package/dist/cjs/stream.cjs.map +1 -1
  8. package/dist/cjs/tools/BashExecutor.cjs +3 -1
  9. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  10. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +2 -0
  11. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  12. package/dist/cjs/tools/CodeExecutor.cjs +19 -16
  13. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  14. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +2 -0
  15. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  16. package/dist/cjs/tools/ReadFile.cjs +8 -4
  17. package/dist/cjs/tools/ReadFile.cjs.map +1 -1
  18. package/dist/cjs/tools/SkillTool.cjs +2 -0
  19. package/dist/cjs/tools/SkillTool.cjs.map +1 -1
  20. package/dist/cjs/tools/SubagentTool.cjs +3 -0
  21. package/dist/cjs/tools/SubagentTool.cjs.map +1 -1
  22. package/dist/cjs/tools/ToolNode.cjs +88 -27
  23. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  24. package/dist/cjs/tools/ToolSearch.cjs +5 -1
  25. package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
  26. package/dist/cjs/tools/intentArg.cjs +256 -0
  27. package/dist/cjs/tools/intentArg.cjs.map +1 -0
  28. package/dist/cjs/tools/local/CompileCheckTool.cjs +3 -2
  29. package/dist/cjs/tools/local/CompileCheckTool.cjs.map +1 -1
  30. package/dist/cjs/tools/local/LocalCodingTools.cjs +13 -12
  31. package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -1
  32. package/dist/cjs/tools/local/LocalExecutionEngine.cjs +2 -2
  33. package/dist/cjs/tools/ptcTimeout.cjs.map +1 -1
  34. package/dist/cjs/tools/search/schema.cjs +2 -0
  35. package/dist/cjs/tools/search/schema.cjs.map +1 -1
  36. package/dist/cjs/tools/search/tool.cjs +31 -1
  37. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  38. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +1 -0
  39. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  40. package/dist/cjs/tools/toolOutputReferences.cjs +41 -7
  41. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
  42. package/dist/esm/hooks/createWorkspacePolicyHook.mjs +1 -1
  43. package/dist/esm/llm/openai/index.mjs +51 -6
  44. package/dist/esm/llm/openai/index.mjs.map +1 -1
  45. package/dist/esm/main.mjs +4 -3
  46. package/dist/esm/session/JsonlSessionStore.mjs +1 -1
  47. package/dist/esm/stream.mjs +6 -1
  48. package/dist/esm/stream.mjs.map +1 -1
  49. package/dist/esm/tools/BashExecutor.mjs +3 -1
  50. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  51. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +2 -0
  52. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  53. package/dist/esm/tools/CodeExecutor.mjs +19 -16
  54. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  55. package/dist/esm/tools/ProgrammaticToolCalling.mjs +2 -0
  56. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  57. package/dist/esm/tools/ReadFile.mjs +8 -4
  58. package/dist/esm/tools/ReadFile.mjs.map +1 -1
  59. package/dist/esm/tools/SkillTool.mjs +2 -0
  60. package/dist/esm/tools/SkillTool.mjs.map +1 -1
  61. package/dist/esm/tools/SubagentTool.mjs +3 -0
  62. package/dist/esm/tools/SubagentTool.mjs.map +1 -1
  63. package/dist/esm/tools/ToolNode.mjs +88 -28
  64. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  65. package/dist/esm/tools/ToolSearch.mjs +5 -1
  66. package/dist/esm/tools/ToolSearch.mjs.map +1 -1
  67. package/dist/esm/tools/intentArg.mjs +244 -0
  68. package/dist/esm/tools/intentArg.mjs.map +1 -0
  69. package/dist/esm/tools/local/CompileCheckTool.mjs +3 -2
  70. package/dist/esm/tools/local/CompileCheckTool.mjs.map +1 -1
  71. package/dist/esm/tools/local/LocalCodingTools.mjs +13 -12
  72. package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -1
  73. package/dist/esm/tools/local/LocalExecutionEngine.mjs +2 -2
  74. package/dist/esm/tools/ptcTimeout.mjs.map +1 -1
  75. package/dist/esm/tools/search/schema.mjs +2 -0
  76. package/dist/esm/tools/search/schema.mjs.map +1 -1
  77. package/dist/esm/tools/search/tool.mjs +31 -2
  78. package/dist/esm/tools/search/tool.mjs.map +1 -1
  79. package/dist/esm/tools/subagent/SubagentExecutor.mjs +1 -0
  80. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  81. package/dist/esm/tools/toolOutputReferences.mjs +41 -7
  82. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
  83. package/dist/types/index.d.ts +1 -0
  84. package/dist/types/llm/openai/index.d.ts +0 -11
  85. package/dist/types/tools/BashExecutor.d.ts +18 -0
  86. package/dist/types/tools/CodeExecutor.d.ts +18 -0
  87. package/dist/types/tools/ReadFile.d.ts +18 -0
  88. package/dist/types/tools/SkillTool.d.ts +18 -0
  89. package/dist/types/tools/SubagentTool.d.ts +9 -0
  90. package/dist/types/tools/ToolNode.d.ts +37 -5
  91. package/dist/types/tools/ToolSearch.d.ts +18 -0
  92. package/dist/types/tools/intentArg.d.ts +181 -0
  93. package/dist/types/tools/ptcTimeout.d.ts +2 -0
  94. package/dist/types/tools/search/schema.d.ts +18 -0
  95. package/dist/types/tools/search/tool.d.ts +18 -0
  96. package/dist/types/tools/toolOutputReferences.d.ts +12 -2
  97. package/dist/types/types/stream.d.ts +18 -0
  98. package/dist/types/types/tools.d.ts +27 -2
  99. package/package.json +1 -1
  100. package/src/index.ts +1 -0
  101. package/src/llm/openai/index.ts +74 -10
  102. package/src/llm/openai/llm.spec.ts +105 -0
  103. package/src/stream.ts +12 -1
  104. package/src/tools/BashExecutor.ts +6 -0
  105. package/src/tools/BashProgrammaticToolCalling.ts +2 -0
  106. package/src/tools/CodeExecutor.ts +6 -0
  107. package/src/tools/ProgrammaticToolCalling.ts +2 -0
  108. package/src/tools/ReadFile.ts +2 -0
  109. package/src/tools/SkillTool.ts +2 -0
  110. package/src/tools/SubagentTool.ts +3 -0
  111. package/src/tools/ToolNode.ts +190 -43
  112. package/src/tools/ToolSearch.ts +3 -0
  113. package/src/tools/__tests__/ToolNode.onResultCompletion.test.ts +174 -0
  114. package/src/tools/__tests__/intentArg.test.ts +357 -0
  115. package/src/tools/__tests__/intentCoverage.test.ts +139 -0
  116. package/src/tools/__tests__/toolOutputReferences.test.ts +83 -0
  117. package/src/tools/intentArg.ts +357 -0
  118. package/src/tools/local/CompileCheckTool.ts +4 -3
  119. package/src/tools/local/LocalCodingTools.ts +14 -13
  120. package/src/tools/ptcTimeout.ts +2 -0
  121. package/src/tools/search/outcome.test.ts +90 -0
  122. package/src/tools/search/schema.ts +3 -0
  123. package/src/tools/search/tool.ts +47 -1
  124. package/src/tools/subagent/SubagentExecutor.ts +2 -1
  125. package/src/tools/toolOutputReferences.ts +77 -9
  126. package/src/types/stream.ts +18 -0
  127. package/src/types/tools.ts +24 -2
@@ -1,5 +1,6 @@
1
1
  import "../common/enum.mjs";
2
2
  import "../common/index.mjs";
3
+ import { INTENT_PROPERTY } from "./intentArg.mjs";
3
4
  import { getCodeBaseURL } from "./CodeExecutor.mjs";
4
5
  import { tool } from "@langchain/core/tools";
5
6
  import { config } from "dotenv";
@@ -29,6 +30,7 @@ const MCP_SERVER_DESCRIPTION = "Filter to tools from specific MCP server(s). Can
29
30
  const ToolSearchToolSchema = {
30
31
  type: "object",
31
32
  properties: {
33
+ intent: { ...INTENT_PROPERTY },
32
34
  query: {
33
35
  type: "string",
34
36
  maxLength: MAX_PATTERN_LENGTH,
@@ -80,14 +82,16 @@ const SEARCH_TIMEOUT = 5e3;
80
82
  * @returns JSON schema for tool search parameters
81
83
  */
82
84
  function createToolSearchSchema(mode) {
85
+ const queryDescription = mode === "local" ? QUERY_DESCRIPTION_LOCAL : QUERY_DESCRIPTION_REGEX;
83
86
  return {
84
87
  type: "object",
85
88
  properties: {
89
+ intent: { ...INTENT_PROPERTY },
86
90
  query: {
87
91
  type: "string",
88
92
  maxLength: MAX_PATTERN_LENGTH,
89
93
  default: "",
90
- description: mode === "local" ? QUERY_DESCRIPTION_LOCAL : QUERY_DESCRIPTION_REGEX
94
+ description: queryDescription
91
95
  },
92
96
  fields: {
93
97
  type: "array",
@@ -1 +1 @@
1
- {"version":3,"file":"ToolSearch.mjs","names":["params"],"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,MAAM;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;AAQ7B,OAAO;;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,YAA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AM,MAAM,eAAe,YAAY;GACxD,IAAI,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,aAnOF,SAAS,UACL;;EAEN,UAAU,iBAAiB;EAC3B,KAAK,IACC;;EAEN,UAAU,iBAAiB;EAC3B,KAAK;EA4ND;EACA,gBAAA;CACF,CACF;AACF"}
1
+ {"version":3,"file":"ToolSearch.mjs","names":["params"],"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 { INTENT_PROPERTY } from '@/tools/intentArg';\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 intent: { ...INTENT_PROPERTY },\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 intent: { ...INTENT_PROPERTY },\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,MAAM;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;AAS7B,OAAO;;AAGP,MAAM,qBAAqB;AAE3B,MAAa,qBAAA;AAEb,MAA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AAE,OAAO,cAAc,EAAE,OAAO,WACpC;CAGA,OAAO;EACL,iBAHiB,QAAQ,MAAM,GAAG,UAAU,CAAC,CAAC,KAAK,EAAE,aAAa,MAGxC;EAC1B,sBAAsB,MAAM;EAC5B,cAAc;CAChB;AACF;;;;;;;;;;AAWA,SAAS,qBACP,eACA,QACA,YACA,kBACQ;CAiFR,OAAO;EA/EL;EACA,iBAAiB,KAAK,UAAU,aAAa,IAAI;EACjD,wBAAwB,KAAK,UAAU,MAAM,IAAI;EACjD,sBAAsB,aAAa;EACnC,mBAAmB,KAAK,UAAU,gBAAgB,IAAI;EACtD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CAES,CAAC,CAAC,KAAK,IAAI;AACxB;;;;;;AAOA,SAAS,mBAAmB,QAAsC;CAChE,MAAM,YAAY,OAAO,KAAK;CAE9B,OADe,KAAK,MAAM,SACd;AACd;;;;;;;AAQA,SAAS,oBACP,gBACA,aAA8B,QACtB;CACR,MAAM,EAAE,iBAAiB,sBAAsB,iBAC7C;CACF,MAAM,cAAc,eAAe;CAEnC,MAAM,SAAS;EACb,OAAO,gBAAgB;EACvB,OAAO,gBAAgB,KAAK,SAAS;GACnC,MAAM,cAAc,IAAI,YAAY,gBAAgB,IAAI,SAAS;GACjE,OAAO,OAAO,IAAI,YAAY,QAAQ,CAAC,CAAC;GACxC,YAAY,IAAI;GAChB,SAAS,IAAI;EACf,EAAE;EACF,gBAAgB;EAChB,OAAO;CACT;CAEA,OAAO,K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,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,aAnOF,SAAS,UACL;;EAEN,UAAU,iBAAiB;EAC3B,KAAK,IACC;;EAEN,UAAU,iBAAiB;EAC3B,KAAK;EA4ND;EACA,gBAAA;CACF,CACF;AACF"}
@@ -0,0 +1,244 @@
1
+ //#region src/tools/intentArg.ts
2
+ /** Argument carrying the model-authored label for a tool call. */
3
+ const INTENT_ARG = "intent";
4
+ /**
5
+ * Opening words of {@link INTENT_DESCRIPTION}, and the discriminator that
6
+ * tells the injected LABEL apart from a tool's own business parameter that
7
+ * merely shares the name `intent`.
8
+ *
9
+ * Exported because host applications reimplement the same strip/sanitize
10
+ * passes and would otherwise duplicate this as a string literal: if the two
11
+ * copies drift, the host silently stops recognizing SDK-native labels and
12
+ * fails OPEN (labels stay in schemas, opt-outs stop working) with no error.
13
+ * Any edit to the description must preserve this prefix verbatim.
14
+ */
15
+ const INTENT_LABEL_MARKER = "ALWAYS write this field FIRST";
16
+ /**
17
+ * Model-facing instruction for the injected `intent` property.
18
+ *
19
+ * Deliberately terse — it is repeated on every opted-in tool schema, on every
20
+ * request, so each sentence is paid for many times over. What remains is
21
+ * load-bearing: first-position placement (the entire streaming mechanism),
22
+ * the one-sentence present-progressive form, who reads it, and the sibling
23
+ * rule, without which models emit identical labels for parallel calls to one
24
+ * tool and defeat the feature's headline case.
25
+ */
26
+ const INTENT_DESCRIPTION = `${INTENT_LABEL_MARKER}, before any other argument. One present-progressive sentence saying what THIS call is about to do: "Searching for OAuth handling in the callback router". Shown to the user as this call's live status. Never name the tool. Sibling calls to one tool must differ.`;
27
+ /**
28
+ * Canonical (frozen) shape of the injected property. Always embed a COPY
29
+ * (`{ ...INTENT_PROPERTY }`): LangChain's JSON-schema validator stamps a
30
+ * `__absolute_uri__` marker onto every subschema it dereferences, which
31
+ * throws on a frozen object — and a single shared instance would be stamped
32
+ * with one schema's URI while embedded in many.
33
+ */
34
+ const INTENT_PROPERTY = Object.freeze({
35
+ type: "string",
36
+ description: INTENT_DESCRIPTION
37
+ });
38
+ /**
39
+ * Discriminates the intent LABEL property from a tool's own business
40
+ * parameter that merely shares the name: the label contract always opens
41
+ * with the same instruction. Removal/sanitize passes must never strip a
42
+ * parameter the tool actually needs.
43
+ */
44
+ function isIntentLabelProperty(property) {
45
+ if (property == null || typeof property !== "object") return false;
46
+ const record = property;
47
+ return record.type === "string" && typeof record.description === "string" && record.description.startsWith("ALWAYS write this field FIRST");
48
+ }
49
+ /**
50
+ * Returns a copy of `parameters` without the injected intent LABEL — the
51
+ * opt-out for consumers that render no status label and should not pay for
52
+ * the property.
53
+ *
54
+ * The SDK's native schemas carry the label unconditionally, so without this
55
+ * an embedder has no lever at all: `withIntent` is applied at module scope.
56
+ * Marker-guarded, so a tool's own business parameter named `intent` is never
57
+ * removed. Returns the input unchanged when there is nothing to strip.
58
+ *
59
+ * `required` is pruned alongside the property: a schema that lists `intent`
60
+ * as required (strict-mode normalization does exactly that, since OpenAI
61
+ * strict function schemas require every property to appear in `required`)
62
+ * would otherwise be left naming a property it no longer declares, which is
63
+ * invalid JSON Schema and gets rejected by the provider instead of quietly
64
+ * opting out.
65
+ */
66
+ function withoutIntent(parameters) {
67
+ const props = parameters?.properties;
68
+ if (parameters == null || props == null || !isIntentLabelProperty(props["intent"])) return parameters;
69
+ const { [INTENT_ARG]: _omit, ...rest } = props;
70
+ const next = {
71
+ ...parameters,
72
+ properties: rest
73
+ };
74
+ if (parameters.required != null) {
75
+ const required = parameters.required.filter((key) => key !== INTENT_ARG);
76
+ if (required.length > 0) next.required = required;
77
+ else delete next.required;
78
+ }
79
+ return next;
80
+ }
81
+ /**
82
+ * Returns a copy of the parameters schema with `intent` prepended as the
83
+ * FIRST property (object key order is insertion order and every provider
84
+ * serializer preserves it — first key in the schema means first key in the
85
+ * streamed input). Never mutates the input; no-op when the schema already
86
+ * declares `intent`. The property is not added to `required`.
87
+ */
88
+ function withIntent(parameters) {
89
+ const existingProps = parameters?.properties ?? {};
90
+ if ("intent" in existingProps) return parameters;
91
+ return {
92
+ ...parameters,
93
+ type: "object",
94
+ properties: {
95
+ [INTENT_ARG]: { ...INTENT_PROPERTY },
96
+ ...existingProps
97
+ }
98
+ };
99
+ }
100
+ /**
101
+ * Coerces tool-call args to an object, parsing a stringified JSON object
102
+ * (some providers deliver args as a string). Returns undefined otherwise.
103
+ */
104
+ function coerceArgsObject(args) {
105
+ if (typeof args === "object" && args !== null && !Array.isArray(args)) return args;
106
+ if (typeof args === "string" && args.trim().startsWith("{")) try {
107
+ const parsed = JSON.parse(args);
108
+ if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
109
+ } catch {
110
+ return;
111
+ }
112
+ }
113
+ /**
114
+ * Reads the model-authored intent from tool-call args (handles stringified
115
+ * args). Returns undefined when absent, empty, or not a string.
116
+ */
117
+ function readIntent(args) {
118
+ const value = coerceArgsObject(args)?.[INTENT_ARG];
119
+ if (typeof value !== "string") return;
120
+ const trimmed = value.trim();
121
+ return trimmed === "" ? void 0 : trimmed;
122
+ }
123
+ /**
124
+ * Returns the args without the `intent` key so downstream consumers that did
125
+ * not declare it never receive it. Parses stringified JSON object args;
126
+ * returns the value unchanged when the key is absent.
127
+ */
128
+ function stripIntent(args) {
129
+ const obj = coerceArgsObject(args);
130
+ if (!obj || !("intent" in obj)) return args;
131
+ const { [INTENT_ARG]: _omit, ...rest } = obj;
132
+ return rest;
133
+ }
134
+ /**
135
+ * Resolves the settled label for a call from its model-authored `intent` and
136
+ * the tool's result fields, in precedence order:
137
+ *
138
+ * 1. `outcome` — full replacement authored by the tool.
139
+ * 2. `outcome_patch` — first occurrence of `from` in the intent replaced
140
+ * with `to` (case-sensitive); no-op when `from` is absent or empty.
141
+ * 3. Otherwise the intent is returned UNCHANGED.
142
+ *
143
+ * There is deliberately no mechanical present-progressive→past-tense rewrite.
144
+ * Such a transform can only be a closed list of English verbs, which makes it
145
+ * wrong in three ways at once: it never fires for the non-English labels this
146
+ * feature expects (the model answers in the user's language), it fires for
147
+ * some sibling calls and not others inside one group — "Searched…" beside
148
+ * "Recording…" — and it quietly enumerates a vocabulary in a feature whose
149
+ * premise is that the sentence is free-form. Completion is conveyed by UI
150
+ * state (the shimmer stopping, the icon settling), which is language-neutral
151
+ * and always consistent; a tool that wants past tense says so explicitly via
152
+ * `outcome` or `outcome_patch`.
153
+ *
154
+ * Returns undefined when there is neither an intent nor an outcome, so
155
+ * callers fall back to their default label. Pure and dependency-free — host
156
+ * UIs needing identical logic can import or mirror it.
157
+ */
158
+ function applyOutcome(intent, result) {
159
+ const outcome = result?.outcome;
160
+ if (typeof outcome === "string" && outcome.trim() !== "") return outcome;
161
+ if (intent == null || intent === "") return;
162
+ const patch = result?.outcome_patch;
163
+ if (patch != null && patch.from !== "" && intent.includes(patch.from))
164
+ /** Replacement callback keeps `to` verbatim — a direct string second
165
+ * argument would interpret `$&`/`$'`-style tokens in tool-authored
166
+ * text (e.g. labels derived from shell syntax). */
167
+ return intent.replace(patch.from, () => patch.to);
168
+ return intent;
169
+ }
170
+ /**
171
+ * Hard cap on an emitted outcome label. The label is a single progress line
172
+ * in UI chrome; a tool that derives it from data (or a malformed patch)
173
+ * must not be able to inflate completion events or persisted parts.
174
+ */
175
+ const MAX_OUTCOME_CHARS = 256;
176
+ function boundOutcomeLabel(label) {
177
+ if (label == null) return;
178
+ const singleLine = label.replace(/\s+/g, " ").trim();
179
+ if (singleLine === "") return;
180
+ if (singleLine.length <= MAX_OUTCOME_CHARS) return singleLine;
181
+ return `${singleLine.slice(0, MAX_OUTCOME_CHARS - 1)}…`;
182
+ }
183
+ /**
184
+ * Resolves the settled label to emit on a completion event: only when the
185
+ * tool actually authored `outcome`/`outcome_patch` fields. Returns undefined
186
+ * otherwise, so the wire never carries a label the host already has — a bare
187
+ * intent needs no settled form, because it is displayed unchanged and the UI
188
+ * conveys completion through its own state. Hosts must NOT rewrite it (see
189
+ * {@link applyOutcome} for why a tense transform is deliberately absent). The
190
+ * result is collapsed to a bounded single line before emission.
191
+ *
192
+ * For failed calls (`isError`), only tool-AUTHORED text may label the call:
193
+ * an explicit `outcome`, or a patch whose `from` actually matches the intent.
194
+ * An unmatched patch resolves to undefined rather than silently reusing the
195
+ * in-flight intent, so a failure is never labelled as though it succeeded.
196
+ */
197
+ function resolveToolOutcome(args, fields, options) {
198
+ if (fields == null || fields.outcome == null && fields.outcome_patch == null) return;
199
+ if (options?.isError !== true) return boundOutcomeLabel(applyOutcome(readIntent(args), fields));
200
+ const outcome = fields.outcome;
201
+ if (typeof outcome === "string" && outcome.trim() !== "") return boundOutcomeLabel(outcome);
202
+ const intent = readIntent(args);
203
+ const patch = fields.outcome_patch;
204
+ if (intent != null && patch != null && patch.from !== "" && intent.includes(patch.from)) return boundOutcomeLabel(intent.replace(patch.from, () => patch.to));
205
+ }
206
+ /**
207
+ * Reads the outcome fields off a tool-execution result: the typed
208
+ * `outcome`/`outcome_patch` fields when present, else the artifact channel
209
+ * (see {@link readOutcomeFields}) — so a `content_and_artifact` tool authors
210
+ * its label the same way on the direct and event-driven paths.
211
+ */
212
+ function outcomeFieldsFromResult(result) {
213
+ if (result.outcome != null || result.outcome_patch != null) return result;
214
+ return readOutcomeFields(result.artifact);
215
+ }
216
+ /**
217
+ * Extracts validated `outcome`/`outcome_patch` fields from an arbitrary
218
+ * value — the artifact channel through which an in-process
219
+ * `content_and_artifact` tool authors its settled label. Returns undefined
220
+ * when neither field is usable.
221
+ */
222
+ function readOutcomeFields(source) {
223
+ if (source == null || typeof source !== "object" || Array.isArray(source)) return;
224
+ const record = source;
225
+ const outcome = typeof record.outcome === "string" && record.outcome.trim() !== "" ? record.outcome : void 0;
226
+ let outcome_patch;
227
+ const rawPatch = record.outcome_patch;
228
+ if (rawPatch != null && typeof rawPatch === "object" && !Array.isArray(rawPatch)) {
229
+ const patch = rawPatch;
230
+ if (typeof patch.from === "string" && typeof patch.to === "string") outcome_patch = {
231
+ from: patch.from,
232
+ to: patch.to
233
+ };
234
+ }
235
+ if (outcome == null && outcome_patch == null) return;
236
+ return {
237
+ outcome,
238
+ outcome_patch
239
+ };
240
+ }
241
+ //#endregion
242
+ export { INTENT_ARG, INTENT_DESCRIPTION, INTENT_LABEL_MARKER, INTENT_PROPERTY, applyOutcome, isIntentLabelProperty, outcomeFieldsFromResult, readIntent, readOutcomeFields, resolveToolOutcome, stripIntent, withIntent, withoutIntent };
243
+
244
+ //# sourceMappingURL=intentArg.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intentArg.mjs","names":[],"sources":["../../../src/tools/intentArg.ts"],"sourcesContent":["/**\n * @fileoverview Tool intent labels.\n *\n * Lets a tool declare, as the FIRST property of its input schema, an `intent`\n * string: one model-authored sentence stating what that specific call is about\n * to do (\"Searching for OAuth handling in the callback router\"). Because the\n * property is first, it is the first key providers stream in the tool-call\n * args, so a host UI can render it as the call's live status label before the\n * rest of the args exist. When the call settles, {@link applyOutcome} edits\n * the sentence in place into its outcome form — a tool-supplied replacement\n * (`outcome`) or a tool-supplied span edit (`outcome_patch`). Absent either,\n * the label is left exactly as the model wrote it: completion is a UI state\n * (the shimmer stopping, the icon settling), not a tense change.\n *\n * The arg is always optional (never listed in `required`): the same schemas\n * are callable from programmatic tool calling, where no UI renders a label\n * and forcing generated code to fabricate one would be pure cost. Tool bodies\n * must call {@link stripIntent} before using their args so no tool receives a\n * parameter it did not declare.\n */\n\nimport type { JsonSchemaType, OutcomePatch } from '@/types';\n\n/** Argument carrying the model-authored label for a tool call. */\nexport const INTENT_ARG = 'intent';\n\n/**\n * Opening words of {@link INTENT_DESCRIPTION}, and the discriminator that\n * tells the injected LABEL apart from a tool's own business parameter that\n * merely shares the name `intent`.\n *\n * Exported because host applications reimplement the same strip/sanitize\n * passes and would otherwise duplicate this as a string literal: if the two\n * copies drift, the host silently stops recognizing SDK-native labels and\n * fails OPEN (labels stay in schemas, opt-outs stop working) with no error.\n * Any edit to the description must preserve this prefix verbatim.\n */\nexport const INTENT_LABEL_MARKER = 'ALWAYS write this field FIRST';\n\n/**\n * Model-facing instruction for the injected `intent` property.\n *\n * Deliberately terse — it is repeated on every opted-in tool schema, on every\n * request, so each sentence is paid for many times over. What remains is\n * load-bearing: first-position placement (the entire streaming mechanism),\n * the one-sentence present-progressive form, who reads it, and the sibling\n * rule, without which models emit identical labels for parallel calls to one\n * tool and defeat the feature's headline case.\n */\nexport const INTENT_DESCRIPTION =\n `${INTENT_LABEL_MARKER}, before any other argument. One present-progressive ` +\n 'sentence saying what THIS call is about to do: \"Searching for OAuth handling ' +\n 'in the callback router\". Shown to the user as this call\\'s live status. ' +\n 'Never name the tool. Sibling calls to one tool must differ.';\n\n/**\n * Canonical (frozen) shape of the injected property. Always embed a COPY\n * (`{ ...INTENT_PROPERTY }`): LangChain's JSON-schema validator stamps a\n * `__absolute_uri__` marker onto every subschema it dereferences, which\n * throws on a frozen object — and a single shared instance would be stamped\n * with one schema's URI while embedded in many.\n */\nexport const INTENT_PROPERTY: JsonSchemaType = Object.freeze<JsonSchemaType>({\n type: 'string',\n description: INTENT_DESCRIPTION,\n});\n\n/**\n * Discriminates the intent LABEL property from a tool's own business\n * parameter that merely shares the name: the label contract always opens\n * with the same instruction. Removal/sanitize passes must never strip a\n * parameter the tool actually needs.\n */\nexport function isIntentLabelProperty(property: unknown): boolean {\n if (property == null || typeof property !== 'object') {\n return false;\n }\n const record = property as { type?: unknown; description?: unknown };\n return (\n record.type === 'string' &&\n typeof record.description === 'string' &&\n record.description.startsWith(INTENT_LABEL_MARKER)\n );\n}\n\n/**\n * Schema shape accepted by {@link withoutIntent}.\n *\n * `required` is widened to `readonly string[]` because the SDK's own native\n * schemas are declared `as const` — their `required` is a readonly tuple, and\n * a mutable `string[]` parameter would reject the very schemas this helper\n * exists for (TS2345), forcing embedders to cast to use the advertised API.\n */\nexport type IntentStrippableSchema = Omit<JsonSchemaType, 'required'> & {\n required?: readonly string[];\n};\n\n/**\n * Returns a copy of `parameters` without the injected intent LABEL — the\n * opt-out for consumers that render no status label and should not pay for\n * the property.\n *\n * The SDK's native schemas carry the label unconditionally, so without this\n * an embedder has no lever at all: `withIntent` is applied at module scope.\n * Marker-guarded, so a tool's own business parameter named `intent` is never\n * removed. Returns the input unchanged when there is nothing to strip.\n *\n * `required` is pruned alongside the property: a schema that lists `intent`\n * as required (strict-mode normalization does exactly that, since OpenAI\n * strict function schemas require every property to appear in `required`)\n * would otherwise be left naming a property it no longer declares, which is\n * invalid JSON Schema and gets rejected by the provider instead of quietly\n * opting out.\n */\nexport function withoutIntent(parameters?: IntentStrippableSchema): JsonSchemaType | undefined {\n const props = parameters?.properties;\n if (parameters == null || props == null || !isIntentLabelProperty(props[INTENT_ARG])) {\n return parameters as JsonSchemaType | undefined;\n }\n const { [INTENT_ARG]: _omit, ...rest } = props;\n const next: JsonSchemaType = {\n ...(parameters as JsonSchemaType),\n properties: rest,\n };\n if (parameters.required != null) {\n const required = parameters.required.filter((key) => key !== INTENT_ARG);\n if (required.length > 0) {\n next.required = required;\n } else {\n delete next.required;\n }\n }\n return next;\n}\n\n/**\n * Returns a copy of the parameters schema with `intent` prepended as the\n * FIRST property (object key order is insertion order and every provider\n * serializer preserves it — first key in the schema means first key in the\n * streamed input). Never mutates the input; no-op when the schema already\n * declares `intent`. The property is not added to `required`.\n */\nexport function withIntent(parameters?: JsonSchemaType): JsonSchemaType {\n const existingProps = parameters?.properties ?? {};\n if (INTENT_ARG in existingProps) {\n return parameters as JsonSchemaType;\n }\n return {\n ...parameters,\n type: 'object',\n properties: { [INTENT_ARG]: { ...INTENT_PROPERTY }, ...existingProps },\n };\n}\n\n/**\n * Coerces tool-call args to an object, parsing a stringified JSON object\n * (some providers deliver args as a string). Returns undefined otherwise.\n */\nfunction coerceArgsObject(args: unknown): Record<string, unknown> | undefined {\n if (typeof args === 'object' && args !== null && !Array.isArray(args)) {\n return args as Record<string, unknown>;\n }\n if (typeof args === 'string' && args.trim().startsWith('{')) {\n try {\n const parsed = JSON.parse(args) as unknown;\n if (parsed != null && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n return undefined;\n }\n }\n return undefined;\n}\n\n/**\n * Reads the model-authored intent from tool-call args (handles stringified\n * args). Returns undefined when absent, empty, or not a string.\n */\nexport function readIntent(args: unknown): string | undefined {\n const value = coerceArgsObject(args)?.[INTENT_ARG];\n if (typeof value !== 'string') {\n return undefined;\n }\n const trimmed = value.trim();\n return trimmed === '' ? undefined : trimmed;\n}\n\n/**\n * Returns the args without the `intent` key so downstream consumers that did\n * not declare it never receive it. Parses stringified JSON object args;\n * returns the value unchanged when the key is absent.\n */\nexport function stripIntent(args: unknown): unknown {\n const obj = coerceArgsObject(args);\n if (!obj || !(INTENT_ARG in obj)) {\n return args;\n }\n const { [INTENT_ARG]: _omit, ...rest } = obj;\n return rest;\n}\n\n/**\n * Resolves the settled label for a call from its model-authored `intent` and\n * the tool's result fields, in precedence order:\n *\n * 1. `outcome` — full replacement authored by the tool.\n * 2. `outcome_patch` — first occurrence of `from` in the intent replaced\n * with `to` (case-sensitive); no-op when `from` is absent or empty.\n * 3. Otherwise the intent is returned UNCHANGED.\n *\n * There is deliberately no mechanical present-progressive→past-tense rewrite.\n * Such a transform can only be a closed list of English verbs, which makes it\n * wrong in three ways at once: it never fires for the non-English labels this\n * feature expects (the model answers in the user's language), it fires for\n * some sibling calls and not others inside one group — \"Searched…\" beside\n * \"Recording…\" — and it quietly enumerates a vocabulary in a feature whose\n * premise is that the sentence is free-form. Completion is conveyed by UI\n * state (the shimmer stopping, the icon settling), which is language-neutral\n * and always consistent; a tool that wants past tense says so explicitly via\n * `outcome` or `outcome_patch`.\n *\n * Returns undefined when there is neither an intent nor an outcome, so\n * callers fall back to their default label. Pure and dependency-free — host\n * UIs needing identical logic can import or mirror it.\n */\nexport function applyOutcome(\n intent: string | undefined,\n result?: { outcome?: string; outcome_patch?: OutcomePatch },\n): string | undefined {\n const outcome = result?.outcome;\n if (typeof outcome === 'string' && outcome.trim() !== '') {\n return outcome;\n }\n if (intent == null || intent === '') {\n return undefined;\n }\n const patch = result?.outcome_patch;\n if (patch != null && patch.from !== '' && intent.includes(patch.from)) {\n /** Replacement callback keeps `to` verbatim — a direct string second\n * argument would interpret `$&`/`$'`-style tokens in tool-authored\n * text (e.g. labels derived from shell syntax). */\n return intent.replace(patch.from, () => patch.to);\n }\n return intent;\n}\n\n/**\n * Hard cap on an emitted outcome label. The label is a single progress line\n * in UI chrome; a tool that derives it from data (or a malformed patch)\n * must not be able to inflate completion events or persisted parts.\n */\nconst MAX_OUTCOME_CHARS = 256;\n\nfunction boundOutcomeLabel(label: string | undefined): string | undefined {\n if (label == null) {\n return undefined;\n }\n const singleLine = label.replace(/\\s+/g, ' ').trim();\n if (singleLine === '') {\n return undefined;\n }\n if (singleLine.length <= MAX_OUTCOME_CHARS) {\n return singleLine;\n }\n return `${singleLine.slice(0, MAX_OUTCOME_CHARS - 1)}…`;\n}\n\n/**\n * Resolves the settled label to emit on a completion event: only when the\n * tool actually authored `outcome`/`outcome_patch` fields. Returns undefined\n * otherwise, so the wire never carries a label the host already has — a bare\n * intent needs no settled form, because it is displayed unchanged and the UI\n * conveys completion through its own state. Hosts must NOT rewrite it (see\n * {@link applyOutcome} for why a tense transform is deliberately absent). The\n * result is collapsed to a bounded single line before emission.\n *\n * For failed calls (`isError`), only tool-AUTHORED text may label the call:\n * an explicit `outcome`, or a patch whose `from` actually matches the intent.\n * An unmatched patch resolves to undefined rather than silently reusing the\n * in-flight intent, so a failure is never labelled as though it succeeded.\n */\nexport function resolveToolOutcome(\n args: unknown,\n fields?: { outcome?: string; outcome_patch?: OutcomePatch } | null,\n options?: { isError?: boolean },\n): string | undefined {\n if (fields == null || (fields.outcome == null && fields.outcome_patch == null)) {\n return undefined;\n }\n if (options?.isError !== true) {\n return boundOutcomeLabel(applyOutcome(readIntent(args), fields));\n }\n const outcome = fields.outcome;\n if (typeof outcome === 'string' && outcome.trim() !== '') {\n return boundOutcomeLabel(outcome);\n }\n const intent = readIntent(args);\n const patch = fields.outcome_patch;\n if (\n intent != null &&\n patch != null &&\n patch.from !== '' &&\n intent.includes(patch.from)\n ) {\n return boundOutcomeLabel(intent.replace(patch.from, () => patch.to));\n }\n return undefined;\n}\n\n/**\n * Reads the outcome fields off a tool-execution result: the typed\n * `outcome`/`outcome_patch` fields when present, else the artifact channel\n * (see {@link readOutcomeFields}) — so a `content_and_artifact` tool authors\n * its label the same way on the direct and event-driven paths.\n */\nexport function outcomeFieldsFromResult(result: {\n outcome?: string;\n outcome_patch?: OutcomePatch;\n artifact?: unknown;\n}): { outcome?: string; outcome_patch?: OutcomePatch } | undefined {\n if (result.outcome != null || result.outcome_patch != null) {\n return result;\n }\n return readOutcomeFields(result.artifact);\n}\n\n/**\n * Extracts validated `outcome`/`outcome_patch` fields from an arbitrary\n * value — the artifact channel through which an in-process\n * `content_and_artifact` tool authors its settled label. Returns undefined\n * when neither field is usable.\n */\nexport function readOutcomeFields(\n source: unknown,\n): { outcome?: string; outcome_patch?: OutcomePatch } | undefined {\n if (source == null || typeof source !== 'object' || Array.isArray(source)) {\n return undefined;\n }\n const record = source as Record<string, unknown>;\n const outcome =\n typeof record.outcome === 'string' && record.outcome.trim() !== ''\n ? record.outcome\n : undefined;\n let outcome_patch: OutcomePatch | undefined;\n const rawPatch = record.outcome_patch;\n if (rawPatch != null && typeof rawPatch === 'object' && !Array.isArray(rawPatch)) {\n const patch = rawPatch as Record<string, unknown>;\n if (typeof patch.from === 'string' && typeof patch.to === 'string') {\n outcome_patch = { from: patch.from, to: patch.to };\n }\n }\n if (outcome == null && outcome_patch == null) {\n return undefined;\n }\n return { outcome, outcome_patch };\n}\n"],"mappings":";;AAwBA,MAAa,aAAa;;;;;;;;;;;;AAa1B,MAAa,sBAAsB;;;;;;;;;;;AAYnC,MAAa,qBACX,GAAG,oB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KAAK,MAAM,IACpD,OAAO,kBAAkB,OAAO;CAElC,MAAM,SAAS,WAAW,IAAI;CAC9B,MAAM,QAAQ,OAAO;CACrB,IACE,UAAU,QACV,SAAS,QACT,MAAM,SAAS,MACf,OAAO,SAAS,MAAM,IAAI,GAE1B,OAAO,kBAAkB,OAAO,QAAQ,MAAM,YAAY,MAAM,EAAE,CAAC;AAGvE;;;;;;;AAQA,SAAgB,wBAAwB,QAI2B;CACjE,IAAI,OAAO,WAAW,QAAQ,OAAO,iBAAiB,MACpD,OAAO;CAET,OAAO,kBAAkB,OAAO,QAAQ;AAC1C;;;;;;;AAQA,SAAgB,kBACd,QACgE;CAChE,IAAI,UAAU,QAAQ,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GACtE;CAEF,MAAM,SAAS;CACf,MAAM,UACJ,OAAO,OAAO,YAAY,YAAY,OAAO,QAAQ,KAAK,MAAM,KAC5D,OAAO,UACP,KAAA;CACN,IAAI;CACJ,MAAM,WAAW,OAAO;CACxB,IAAI,YAAY,QAAQ,OAAO,aAAa,YAAY,CAAC,MAAM,QAAQ,QAAQ,GAAG;EAChF,MAAM,QAAQ;EACd,IAAI,OAAO,MAAM,SAAS,YAAY,OAAO,MAAM,OAAO,UACxD,gBAAgB;GAAE,MAAM,MAAM;GAAM,IAAI,MAAM;EAAG;CAErD;CACA,IAAI,WAAW,QAAQ,iBAAiB,MACtC;CAEF,OAAO;EAAE;EAAS;CAAc;AAClC"}
@@ -1,5 +1,6 @@
1
1
  import "../../common/enum.mjs";
2
2
  import "../../common/index.mjs";
3
+ import { withIntent } from "../intentArg.mjs";
3
4
  import { isWorkspaceClientTimeoutError } from "./workspaceFS.mjs";
4
5
  import { getLocalCwd, getWorkspaceFS, spawnLocalProcess, truncateLocalOutput, validateBashCommand } from "./LocalExecutionEngine.mjs";
5
6
  import { tool } from "@langchain/core/tools";
@@ -31,7 +32,7 @@ import { resolve } from "path";
31
32
  */
32
33
  /** Back-compat alias; canonical name lives on `Constants.COMPILE_CHECK`. */
33
34
  const CompileCheckToolName = "compile_check";
34
- const CompileCheckSchema = {
35
+ const CompileCheckSchema = withIntent({
35
36
  type: "object",
36
37
  properties: {
37
38
  command: {
@@ -43,7 +44,7 @@ const CompileCheckSchema = {
43
44
  description: "Optional timeout in milliseconds. Defaults to 120000 (2 min)."
44
45
  }
45
46
  }
46
- };
47
+ });
47
48
  async function pathExists(fs, p) {
48
49
  try {
49
50
  await fs.stat(p);