illuma-agents 1.0.9 → 1.0.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/dist/cjs/agents/AgentContext.cjs +228 -27
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +2 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/events.cjs +3 -0
- package/dist/cjs/events.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +29 -19
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/instrumentation.cjs +1 -1
- package/dist/cjs/instrumentation.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/index.cjs +1 -1
- package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +122 -7
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/google/index.cjs +1 -1
- package/dist/cjs/llm/google/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +108 -6
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/utils/index.cjs +87 -1
- package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
- package/dist/cjs/llm/openrouter/index.cjs +176 -2
- package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +18 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/cache.cjs +149 -54
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/cjs/messages/tools.cjs +85 -0
- package/dist/cjs/messages/tools.cjs.map +1 -0
- package/dist/cjs/stream.cjs +20 -0
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +4 -0
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +438 -0
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +54 -6
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/ToolSearchRegex.cjs +455 -0
- package/dist/cjs/tools/ToolSearchRegex.cjs.map +1 -0
- package/dist/cjs/tools/search/tool.cjs +21 -1
- package/dist/cjs/tools/search/tool.cjs.map +1 -1
- package/dist/cjs/utils/run.cjs +5 -1
- package/dist/cjs/utils/run.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +228 -27
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +2 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/events.mjs +4 -1
- package/dist/esm/events.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +29 -19
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/instrumentation.mjs +1 -1
- package/dist/esm/instrumentation.mjs.map +1 -1
- package/dist/esm/llm/anthropic/index.mjs +1 -1
- package/dist/esm/llm/anthropic/index.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +122 -7
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/google/index.mjs +1 -1
- package/dist/esm/llm/google/index.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +109 -7
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/openai/utils/index.mjs +88 -2
- package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
- package/dist/esm/llm/openrouter/index.mjs +176 -2
- package/dist/esm/llm/openrouter/index.mjs.map +1 -1
- package/dist/esm/main.mjs +3 -0
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/cache.mjs +149 -54
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/esm/messages/tools.mjs +82 -0
- package/dist/esm/messages/tools.mjs.map +1 -0
- package/dist/esm/stream.mjs +20 -0
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +4 -0
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +430 -0
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +54 -6
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/ToolSearchRegex.mjs +448 -0
- package/dist/esm/tools/ToolSearchRegex.mjs.map +1 -0
- package/dist/esm/tools/search/tool.mjs +21 -1
- package/dist/esm/tools/search/tool.mjs.map +1 -1
- package/dist/esm/utils/run.mjs +5 -1
- package/dist/esm/utils/run.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +65 -5
- package/dist/types/common/enum.d.ts +2 -0
- package/dist/types/graphs/Graph.d.ts +3 -2
- package/dist/types/index.d.ts +2 -0
- package/dist/types/llm/anthropic/index.d.ts +1 -1
- package/dist/types/llm/bedrock/index.d.ts +31 -4
- package/dist/types/llm/google/index.d.ts +1 -1
- package/dist/types/llm/openai/index.d.ts +4 -3
- package/dist/types/llm/openai/utils/index.d.ts +10 -1
- package/dist/types/llm/openrouter/index.d.ts +5 -2
- package/dist/types/messages/cache.d.ts +23 -8
- package/dist/types/messages/index.d.ts +1 -0
- package/dist/types/messages/tools.d.ts +17 -0
- package/dist/types/test/mockTools.d.ts +28 -0
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +91 -0
- package/dist/types/tools/ToolNode.d.ts +10 -2
- package/dist/types/tools/ToolSearchRegex.d.ts +80 -0
- package/dist/types/types/graph.d.ts +7 -1
- package/dist/types/types/tools.d.ts +138 -0
- package/package.json +8 -3
- package/src/agents/AgentContext.ts +267 -27
- package/src/agents/__tests__/AgentContext.test.ts +805 -0
- package/src/common/enum.ts +2 -0
- package/src/events.ts +5 -1
- package/src/graphs/Graph.ts +35 -20
- package/src/index.ts +2 -0
- package/src/instrumentation.ts +1 -1
- package/src/llm/anthropic/index.ts +2 -2
- package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +473 -0
- package/src/llm/bedrock/index.ts +150 -13
- package/src/llm/google/index.ts +2 -2
- package/src/llm/google/llm.spec.ts +3 -1
- package/src/llm/openai/index.ts +135 -9
- package/src/llm/openai/utils/index.ts +116 -1
- package/src/llm/openrouter/index.ts +224 -3
- package/src/messages/__tests__/tools.test.ts +473 -0
- package/src/messages/cache.ts +163 -61
- package/src/messages/index.ts +1 -0
- package/src/messages/tools.ts +99 -0
- package/src/scripts/code_exec_ptc.ts +334 -0
- package/src/scripts/programmatic_exec.ts +396 -0
- package/src/scripts/programmatic_exec_agent.ts +231 -0
- package/src/scripts/tool_search_regex.ts +162 -0
- package/src/specs/thinking-prune.test.ts +52 -118
- package/src/stream.ts +26 -0
- package/src/test/mockTools.ts +366 -0
- package/src/tools/CodeExecutor.ts +4 -0
- package/src/tools/ProgrammaticToolCalling.ts +558 -0
- package/src/tools/ToolNode.ts +60 -7
- package/src/tools/ToolSearchRegex.ts +535 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +318 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +853 -0
- package/src/tools/__tests__/ToolSearchRegex.integration.test.ts +161 -0
- package/src/tools/__tests__/ToolSearchRegex.test.ts +232 -0
- package/src/tools/search/jina-reranker.test.ts +16 -16
- package/src/tools/search/tool.ts +23 -1
- package/src/types/graph.ts +7 -1
- package/src/types/tools.ts +166 -0
- package/src/utils/llmConfig.ts +8 -2
- package/src/utils/run.ts +5 -1
- package/src/tools/search/direct-url.test.ts +0 -530
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolNode.cjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { ToolCall } from '@langchain/core/messages/tool';\nimport {\n ToolMessage,\n isAIMessage,\n isBaseMessage,\n} from '@langchain/core/messages';\nimport {\n END,\n Send,\n Command,\n isCommand,\n isGraphInterrupt,\n MessagesAnnotation,\n} from '@langchain/langgraph';\nimport type {\n RunnableConfig,\n RunnableToolLike,\n} from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { RunnableCallable } from '@/utils';\n\n/**\n * Helper to check if a value is a Send object\n */\nfunction isSend(value: unknown): value is Send {\n return value instanceof Send;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n tools: t.GenericTool[];\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n trace = false;\n toolCallStepIds?: Map<string, string>;\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\n private toolUsageCount: Map<string, number>;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.tools = tools;\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.toolCallStepIds = toolCallStepIds;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.loadRuntimeTools = loadRuntimeTools;\n this.errorHandler = errorHandler;\n this.toolUsageCount = new Map<string, number>();\n }\n\n /**\n * Returns a snapshot of the current tool usage counts.\n * @returns A ReadonlyMap where keys are tool names and values are their usage counts.\n */\n public getToolUsageCounts(): ReadonlyMap<string, number> {\n return new Map(this.toolUsageCount); // Return a copy\n }\n\n /**\n * Runs a single tool call with error handling\n */\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<BaseMessage | Command> {\n const tool = this.toolMap.get(call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n const args = call.args;\n const stepId = this.toolCallStepIds?.get(call.id!);\n const output = await tool.invoke(\n { ...call, args, type: 'tool_call', stepId, turn },\n config\n );\n if (\n (isBaseMessage(output) && output._getType() === 'tool') ||\n isCommand(output)\n ) {\n return output;\n } else {\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: typeof output === 'string' ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n }\n } catch (_e: unknown) {\n const e = _e as Error;\n if (!this.handleToolErrors) {\n throw e;\n }\n if (isGraphInterrupt(e)) {\n throw e;\n }\n if (this.errorHandler) {\n try {\n await this.errorHandler(\n {\n error: e,\n id: call.id!,\n name: call.name,\n input: call.args,\n },\n config.metadata\n );\n } catch (handlerError) {\n // eslint-disable-next-line no-console\n console.error('Error in errorHandler:', {\n toolName: call.name,\n toolCallId: call.id,\n toolArgs: call.args,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn: this.toolUsageCount.get(call.name),\n originalError: {\n message: e.message,\n stack: e.stack ?? undefined,\n },\n handlerError:\n handlerError instanceof Error\n ? {\n message: handlerError.message,\n stack: handlerError.stack ?? undefined,\n }\n : {\n message: String(handlerError),\n stack: undefined,\n },\n });\n }\n }\n return new ToolMessage({\n status: 'error',\n content: `Error: ${e.message}\\n Please fix your mistakes.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n outputs = [await this.runTool(input.lg_tool_call, config)];\n } else {\n let messages: BaseMessage[];\n if (Array.isArray(input)) {\n messages = input;\n } else if (this.isMessagesState(input)) {\n messages = input.messages;\n } else {\n throw new Error(\n 'ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.'\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg._getType() === 'tool')\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (isAIMessage(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (aiMessage == null || !isAIMessage(aiMessage)) {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n aiMessage.tool_calls ?? []\n );\n this.tools = tools;\n this.toolMap =\n toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n }\n\n outputs = await Promise.all(\n aiMessage.tool_calls\n ?.filter((call) => {\n /**\n * Filter out:\n * 1. Already processed tool calls (present in toolMessageIds)\n * 2. Server tool calls (e.g., web_search with IDs starting with 'srvtoolu_')\n * which are executed by the provider's API and don't require invocation\n */\n return (\n (call.id == null || !toolMessageIds.has(call.id)) &&\n !(call.id?.startsWith('srvtoolu_') ?? false)\n );\n })\n .map((call) => this.runTool(call, config)) ?? []\n );\n }\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send): send is Send => isSend(send))\n ) {\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else {\n combinedOutputs.push(output);\n }\n } else {\n combinedOutputs.push(\n Array.isArray(input) ? [output] : { messages: [output] }\n );\n }\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as T;\n }\n\n private isSendInput(input: unknown): input is { lg_tool_call: ToolCall } {\n return (\n typeof input === 'object' && input != null && 'lg_tool_call' in input\n );\n }\n\n private isMessagesState(\n input: unknown\n ): input is { messages: BaseMessage[] } {\n return (\n typeof input === 'object' &&\n input != null &&\n 'messages' in input &&\n Array.isArray((input as { messages: unknown }).messages) &&\n (input as { messages: unknown[] }).messages.every(isBaseMessage)\n );\n }\n}\n\nfunction areToolCallsInvoked(\n message: AIMessage,\n invokedToolIds?: Set<string>\n): boolean {\n if (!invokedToolIds || invokedToolIds.size === 0) return false;\n return (\n message.tool_calls?.every(\n (toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)\n ) ?? false\n );\n}\n\nexport function toolsCondition<T extends string>(\n state: BaseMessage[] | typeof MessagesAnnotation.State,\n toolNode: T,\n invokedToolIds?: Set<string>\n): T | typeof END {\n const message: AIMessage = Array.isArray(state)\n ? state[state.length - 1]\n : state.messages[state.messages.length - 1];\n\n if (\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n } else {\n return END;\n }\n}\n"],"names":["Send","RunnableCallable","isBaseMessage","isCommand","ToolMessage","isGraphInterrupt","messages","isAIMessage","Command","END"],"mappings":";;;;;;;;;;AAuBA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAYA,cAAI;AAC9B;AAEA;AACM,MAAO,QAAkB,SAAQC,oBAAsB,CAAA;AAC3D,IAAA,KAAK;AACG,IAAA,OAAO;AACP,IAAA,gBAAgB;IACxB,gBAAgB,GAAG,IAAI;IACvB,KAAK,GAAG,KAAK;AACb,IAAA,eAAe;AACf,IAAA,YAAY;AACJ,IAAA,cAAc;AAEtB,IAAA,WAAA,CAAY,EACV,KAAK,EACL,OAAO,EACP,IAAI,EACJ,IAAI,EACJ,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,gBAAgB,GACY,EAAA;QAC5B,KAAK,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,EAA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vB,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,IAAI,CAAC,IAAI,CAAC;AACrC,QAAA,CAAC,mBAAmB,CAAC,OAAO,EAAE,cAAc,CAAC,EAC7C;AACA,QAAA,OAAO,QAAQ;;SACV;AACL,QAAA,OAAOO,aAAG;;AAEd;;;;;"}
|
|
1
|
+
{"version":3,"file":"ToolNode.cjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { ToolCall } from '@langchain/core/messages/tool';\nimport {\n ToolMessage,\n isAIMessage,\n isBaseMessage,\n} from '@langchain/core/messages';\nimport {\n END,\n Send,\n Command,\n isCommand,\n isGraphInterrupt,\n MessagesAnnotation,\n} from '@langchain/langgraph';\nimport type {\n RunnableConfig,\n RunnableToolLike,\n} from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { RunnableCallable } from '@/utils';\nimport { Constants } from '@/common';\n\n/**\n * Helper to check if a value is a Send object\n */\nfunction isSend(value: unknown): value is Send {\n return value instanceof Send;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n trace = false;\n toolCallStepIds?: Map<string, string>;\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\n private toolUsageCount: Map<string, number>;\n /** Tool registry for filtering (lazy computation of programmatic maps) */\n private toolRegistry?: t.LCToolRegistry;\n /** Cached programmatic tools (computed once on first PTC call) */\n private programmaticCache?: t.ProgrammaticCache;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n toolRegistry,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.toolCallStepIds = toolCallStepIds;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.loadRuntimeTools = loadRuntimeTools;\n this.errorHandler = errorHandler;\n this.toolUsageCount = new Map<string, number>();\n this.toolRegistry = toolRegistry;\n }\n\n /**\n * Returns cached programmatic tools, computing once on first access.\n * Single iteration builds both toolMap and toolDefs simultaneously.\n */\n private getProgrammaticTools(): { toolMap: t.ToolMap; toolDefs: t.LCTool[] } {\n if (this.programmaticCache) return this.programmaticCache;\n\n const toolMap: t.ToolMap = new Map();\n const toolDefs: t.LCTool[] = [];\n\n if (this.toolRegistry) {\n for (const [name, toolDef] of this.toolRegistry) {\n if (\n (toolDef.allowed_callers ?? ['direct']).includes('code_execution')\n ) {\n toolDefs.push(toolDef);\n const tool = this.toolMap.get(name);\n if (tool) toolMap.set(name, tool);\n }\n }\n }\n\n this.programmaticCache = { toolMap, toolDefs };\n return this.programmaticCache;\n }\n\n /**\n * Returns a snapshot of the current tool usage counts.\n * @returns A ReadonlyMap where keys are tool names and values are their usage counts.\n */\n public getToolUsageCounts(): ReadonlyMap<string, number> {\n return new Map(this.toolUsageCount); // Return a copy\n }\n\n /**\n * Runs a single tool call with error handling\n */\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<BaseMessage | Command> {\n const tool = this.toolMap.get(call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n const args = call.args;\n const stepId = this.toolCallStepIds?.get(call.id!);\n\n // Build invoke params - LangChain extracts non-schema fields to config.toolCall\n let invokeParams: Record<string, unknown> = {\n ...call,\n args,\n type: 'tool_call',\n stepId,\n turn,\n };\n\n // Inject runtime data for special tools (becomes available at config.toolCall)\n if (call.name === Constants.PROGRAMMATIC_TOOL_CALLING) {\n const { toolMap, toolDefs } = this.getProgrammaticTools();\n invokeParams = {\n ...invokeParams,\n toolMap,\n toolDefs,\n };\n } else if (call.name === Constants.TOOL_SEARCH_REGEX) {\n invokeParams = {\n ...invokeParams,\n toolRegistry: this.toolRegistry,\n };\n }\n\n const output = await tool.invoke(invokeParams, config);\n if (\n (isBaseMessage(output) && output._getType() === 'tool') ||\n isCommand(output)\n ) {\n return output;\n } else {\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: typeof output === 'string' ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n }\n } catch (_e: unknown) {\n const e = _e as Error;\n if (!this.handleToolErrors) {\n throw e;\n }\n if (isGraphInterrupt(e)) {\n throw e;\n }\n if (this.errorHandler) {\n try {\n await this.errorHandler(\n {\n error: e,\n id: call.id!,\n name: call.name,\n input: call.args,\n },\n config.metadata\n );\n } catch (handlerError) {\n // eslint-disable-next-line no-console\n console.error('Error in errorHandler:', {\n toolName: call.name,\n toolCallId: call.id,\n toolArgs: call.args,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn: this.toolUsageCount.get(call.name),\n originalError: {\n message: e.message,\n stack: e.stack ?? undefined,\n },\n handlerError:\n handlerError instanceof Error\n ? {\n message: handlerError.message,\n stack: handlerError.stack ?? undefined,\n }\n : {\n message: String(handlerError),\n stack: undefined,\n },\n });\n }\n }\n return new ToolMessage({\n status: 'error',\n content: `Error: ${e.message}\\n Please fix your mistakes.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n outputs = [await this.runTool(input.lg_tool_call, config)];\n } else {\n let messages: BaseMessage[];\n if (Array.isArray(input)) {\n messages = input;\n } else if (this.isMessagesState(input)) {\n messages = input.messages;\n } else {\n throw new Error(\n 'ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.'\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg._getType() === 'tool')\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (isAIMessage(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (aiMessage == null || !isAIMessage(aiMessage)) {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n aiMessage.tool_calls ?? []\n );\n this.toolMap =\n toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.programmaticCache = undefined; // Invalidate cache on toolMap change\n }\n\n outputs = await Promise.all(\n aiMessage.tool_calls\n ?.filter((call) => {\n /**\n * Filter out:\n * 1. Already processed tool calls (present in toolMessageIds)\n * 2. Server tool calls (e.g., web_search with IDs starting with 'srvtoolu_')\n * which are executed by the provider's API and don't require invocation\n */\n return (\n (call.id == null || !toolMessageIds.has(call.id)) &&\n !(call.id?.startsWith('srvtoolu_') ?? false)\n );\n })\n .map((call) => this.runTool(call, config)) ?? []\n );\n }\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send): send is Send => isSend(send))\n ) {\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else {\n combinedOutputs.push(output);\n }\n } else {\n combinedOutputs.push(\n Array.isArray(input) ? [output] : { messages: [output] }\n );\n }\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as T;\n }\n\n private isSendInput(input: unknown): input is { lg_tool_call: ToolCall } {\n return (\n typeof input === 'object' && input != null && 'lg_tool_call' in input\n );\n }\n\n private isMessagesState(\n input: unknown\n ): input is { messages: BaseMessage[] } {\n return (\n typeof input === 'object' &&\n input != null &&\n 'messages' in input &&\n Array.isArray((input as { messages: unknown }).messages) &&\n (input as { messages: unknown[] }).messages.every(isBaseMessage)\n );\n }\n}\n\nfunction areToolCallsInvoked(\n message: AIMessage,\n invokedToolIds?: Set<string>\n): boolean {\n if (!invokedToolIds || invokedToolIds.size === 0) return false;\n return (\n message.tool_calls?.every(\n (toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)\n ) ?? false\n );\n}\n\nexport function toolsCondition<T extends string>(\n state: BaseMessage[] | typeof MessagesAnnotation.State,\n toolNode: T,\n invokedToolIds?: Set<string>\n): T | typeof END {\n const message: AIMessage = Array.isArray(state)\n ? state[state.length - 1]\n : state.messages[state.messages.length - 1];\n\n if (\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n } else {\n return END;\n }\n}\n"],"names":["Send","RunnableCallable","Constants","isBaseMessage","isCommand","ToolMessage","isGraphInterrupt","messages","isAIMessage","Command","END"],"mappings":";;;;;;;;;;AAwBA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAYA,cAAI;AAC9B;AAEA;AACM,MAAO,QAAkB,SAAQC,oBAAsB,CAAA;AACnD,IAAA,OAAO;AACP,IAAA,gBAAgB;IACxB,gBAAgB,GAAG,IAAI;IACvB,KAAK,GAAG,KAAK;AACb,IAAA,eAAe;AACf,IAAA,YAAY;AACJ,IAAA,cAAc;;AAEd,IAAA,YAAY;;AAEZ,IAAA,iBAAiB;AAEzB,IAAA,WAAA,CAAY,EACV,KAAK,EACL,OAAO,EACP,IAAI,EACJ,IAAI,EACJ,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,gBAAgB,EAChB,YAAY,GACgB,E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,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;IAE7C,IACE,YAAY,IAAI,OAAO;QACvB,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,IAAI,CAAC,IAAI,CAAC;AACrC,QAAA,CAAC,mBAAmB,CAAC,OAAO,EAAE,cAAc,CAAC,EAC7C;AACA,QAAA,OAAO,QAAQ;;SACV;AACL,QAAA,OAAOO,aAAG;;AAEd;;;;;"}
|
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var zod = require('zod');
|
|
4
|
+
var dotenv = require('dotenv');
|
|
5
|
+
var fetch = require('node-fetch');
|
|
6
|
+
var httpsProxyAgent = require('https-proxy-agent');
|
|
7
|
+
var env = require('@langchain/core/utils/env');
|
|
8
|
+
var tools = require('@langchain/core/tools');
|
|
9
|
+
var CodeExecutor = require('./CodeExecutor.cjs');
|
|
10
|
+
var _enum = require('../common/enum.cjs');
|
|
11
|
+
|
|
12
|
+
// src/tools/ToolSearchRegex.ts
|
|
13
|
+
dotenv.config();
|
|
14
|
+
/** Maximum allowed regex pattern length */
|
|
15
|
+
const MAX_PATTERN_LENGTH = 200;
|
|
16
|
+
/** Maximum allowed regex nesting depth */
|
|
17
|
+
const MAX_REGEX_COMPLEXITY = 5;
|
|
18
|
+
/** Default search timeout in milliseconds */
|
|
19
|
+
const SEARCH_TIMEOUT = 5000;
|
|
20
|
+
const ToolSearchRegexSchema = zod.z.object({
|
|
21
|
+
query: zod.z
|
|
22
|
+
.string()
|
|
23
|
+
.min(1)
|
|
24
|
+
.max(MAX_PATTERN_LENGTH)
|
|
25
|
+
.describe('Regex pattern to search tool names and descriptions. Special regex characters will be sanitized for safety.'),
|
|
26
|
+
fields: zod.z
|
|
27
|
+
.array(zod.z.enum(['name', 'description', 'parameters']))
|
|
28
|
+
.optional()
|
|
29
|
+
.default(['name', 'description'])
|
|
30
|
+
.describe('Which fields to search. Default: name and description'),
|
|
31
|
+
max_results: zod.z
|
|
32
|
+
.number()
|
|
33
|
+
.int()
|
|
34
|
+
.min(1)
|
|
35
|
+
.max(50)
|
|
36
|
+
.optional()
|
|
37
|
+
.default(10)
|
|
38
|
+
.describe('Maximum number of matching tools to return'),
|
|
39
|
+
});
|
|
40
|
+
/**
|
|
41
|
+
* Escapes special regex characters in a string to use as a literal pattern.
|
|
42
|
+
* @param pattern - The string to escape
|
|
43
|
+
* @returns The escaped string safe for use in a RegExp
|
|
44
|
+
*/
|
|
45
|
+
function escapeRegexSpecialChars(pattern) {
|
|
46
|
+
return pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Counts the maximum nesting depth of groups in a regex pattern.
|
|
50
|
+
* @param pattern - The regex pattern to analyze
|
|
51
|
+
* @returns The maximum nesting depth
|
|
52
|
+
*/
|
|
53
|
+
function countNestedGroups(pattern) {
|
|
54
|
+
let maxDepth = 0;
|
|
55
|
+
let currentDepth = 0;
|
|
56
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
57
|
+
if (pattern[i] === '(' && (i === 0 || pattern[i - 1] !== '\\')) {
|
|
58
|
+
currentDepth++;
|
|
59
|
+
maxDepth = Math.max(maxDepth, currentDepth);
|
|
60
|
+
}
|
|
61
|
+
else if (pattern[i] === ')' && (i === 0 || pattern[i - 1] !== '\\')) {
|
|
62
|
+
currentDepth = Math.max(0, currentDepth - 1);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return maxDepth;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Detects nested quantifiers that can cause catastrophic backtracking.
|
|
69
|
+
* Patterns like (a+)+, (a*)*, (a+)*, etc.
|
|
70
|
+
* @param pattern - The regex pattern to check
|
|
71
|
+
* @returns True if nested quantifiers are detected
|
|
72
|
+
*/
|
|
73
|
+
function hasNestedQuantifiers(pattern) {
|
|
74
|
+
const nestedQuantifierPattern = /\([^)]*[+*][^)]*\)[+*?]/;
|
|
75
|
+
return nestedQuantifierPattern.test(pattern);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Checks if a regex pattern contains potentially dangerous constructs.
|
|
79
|
+
* @param pattern - The regex pattern to validate
|
|
80
|
+
* @returns True if the pattern is dangerous
|
|
81
|
+
*/
|
|
82
|
+
function isDangerousPattern(pattern) {
|
|
83
|
+
if (hasNestedQuantifiers(pattern)) {
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
if (countNestedGroups(pattern) > MAX_REGEX_COMPLEXITY) {
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
const dangerousPatterns = [
|
|
90
|
+
/\.\{1000,\}/, // Excessive wildcards
|
|
91
|
+
/\(\?=\.\{100,\}\)/, // Runaway lookaheads
|
|
92
|
+
/\([^)]*\|\s*\){20,}/, // Excessive alternation (rough check)
|
|
93
|
+
/\(\.\*\)\+/, // (.*)+
|
|
94
|
+
/\(\.\+\)\+/, // (.+)+
|
|
95
|
+
/\(\.\*\)\*/, // (.*)*
|
|
96
|
+
/\(\.\+\)\*/, // (.+)*
|
|
97
|
+
];
|
|
98
|
+
for (const dangerous of dangerousPatterns) {
|
|
99
|
+
if (dangerous.test(pattern)) {
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Sanitizes a regex pattern for safe execution.
|
|
107
|
+
* If the pattern is dangerous, it will be escaped to a literal string search.
|
|
108
|
+
* @param pattern - The regex pattern to sanitize
|
|
109
|
+
* @returns Object containing the safe pattern and whether it was escaped
|
|
110
|
+
*/
|
|
111
|
+
function sanitizeRegex(pattern) {
|
|
112
|
+
if (isDangerousPattern(pattern)) {
|
|
113
|
+
return {
|
|
114
|
+
safe: escapeRegexSpecialChars(pattern),
|
|
115
|
+
wasEscaped: true,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
new RegExp(pattern);
|
|
120
|
+
return { safe: pattern, wasEscaped: false };
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return {
|
|
124
|
+
safe: escapeRegexSpecialChars(pattern),
|
|
125
|
+
wasEscaped: true,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Simplifies tool parameters for search purposes.
|
|
131
|
+
* Extracts only the essential structure needed for parameter name searching.
|
|
132
|
+
* @param parameters - The tool's JSON schema parameters
|
|
133
|
+
* @returns Simplified parameters object
|
|
134
|
+
*/
|
|
135
|
+
function simplifyParametersForSearch(parameters) {
|
|
136
|
+
if (!parameters) {
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
if (parameters.properties) {
|
|
140
|
+
return {
|
|
141
|
+
type: parameters.type,
|
|
142
|
+
properties: Object.fromEntries(Object.entries(parameters.properties).map(([key, value]) => [
|
|
143
|
+
key,
|
|
144
|
+
{ type: value.type },
|
|
145
|
+
])),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
return { type: parameters.type };
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Generates the JavaScript search script to be executed in the sandbox.
|
|
152
|
+
* Uses plain JavaScript for maximum compatibility with the Code API.
|
|
153
|
+
* @param deferredTools - Array of tool metadata to search through
|
|
154
|
+
* @param fields - Which fields to search
|
|
155
|
+
* @param maxResults - Maximum number of results to return
|
|
156
|
+
* @param sanitizedPattern - The sanitized regex pattern
|
|
157
|
+
* @returns The JavaScript code string
|
|
158
|
+
*/
|
|
159
|
+
function generateSearchScript(deferredTools, fields, maxResults, sanitizedPattern) {
|
|
160
|
+
const lines = [
|
|
161
|
+
'// Tool definitions (injected)',
|
|
162
|
+
'var tools = ' + JSON.stringify(deferredTools) + ';',
|
|
163
|
+
'var searchFields = ' + JSON.stringify(fields) + ';',
|
|
164
|
+
'var maxResults = ' + maxResults + ';',
|
|
165
|
+
'var pattern = ' + JSON.stringify(sanitizedPattern) + ';',
|
|
166
|
+
'',
|
|
167
|
+
'// Compile regex (pattern is sanitized client-side)',
|
|
168
|
+
'var regex;',
|
|
169
|
+
'try {',
|
|
170
|
+
' regex = new RegExp(pattern, \'i\');',
|
|
171
|
+
'} catch (e) {',
|
|
172
|
+
' regex = new RegExp(pattern.replace(/[.*+?^${}()[\\]\\\\|]/g, "\\\\$&"), "i");',
|
|
173
|
+
'}',
|
|
174
|
+
'',
|
|
175
|
+
'// Search logic',
|
|
176
|
+
'var results = [];',
|
|
177
|
+
'',
|
|
178
|
+
'for (var j = 0; j < tools.length; j++) {',
|
|
179
|
+
' var tool = tools[j];',
|
|
180
|
+
' var bestScore = 0;',
|
|
181
|
+
' var matchedField = \'\';',
|
|
182
|
+
' var snippet = \'\';',
|
|
183
|
+
'',
|
|
184
|
+
' // Search name (highest priority)',
|
|
185
|
+
' if (searchFields.indexOf(\'name\') >= 0 && regex.test(tool.name)) {',
|
|
186
|
+
' bestScore = 0.95;',
|
|
187
|
+
' matchedField = \'name\';',
|
|
188
|
+
' snippet = tool.name;',
|
|
189
|
+
' }',
|
|
190
|
+
'',
|
|
191
|
+
' // Search description (medium priority)',
|
|
192
|
+
' if (searchFields.indexOf(\'description\') >= 0 && tool.description && regex.test(tool.description)) {',
|
|
193
|
+
' if (bestScore === 0) {',
|
|
194
|
+
' bestScore = 0.75;',
|
|
195
|
+
' matchedField = \'description\';',
|
|
196
|
+
' snippet = tool.description.substring(0, 100);',
|
|
197
|
+
' }',
|
|
198
|
+
' }',
|
|
199
|
+
'',
|
|
200
|
+
' // Search parameter names (lower priority)',
|
|
201
|
+
' if (searchFields.indexOf(\'parameters\') >= 0 && tool.parameters && tool.parameters.properties) {',
|
|
202
|
+
' var paramNames = Object.keys(tool.parameters.properties).join(\' \');',
|
|
203
|
+
' if (regex.test(paramNames)) {',
|
|
204
|
+
' if (bestScore === 0) {',
|
|
205
|
+
' bestScore = 0.60;',
|
|
206
|
+
' matchedField = \'parameters\';',
|
|
207
|
+
' snippet = paramNames;',
|
|
208
|
+
' }',
|
|
209
|
+
' }',
|
|
210
|
+
' }',
|
|
211
|
+
'',
|
|
212
|
+
' if (bestScore > 0) {',
|
|
213
|
+
' results.push({',
|
|
214
|
+
' tool_name: tool.name,',
|
|
215
|
+
' match_score: bestScore,',
|
|
216
|
+
' matched_field: matchedField,',
|
|
217
|
+
' snippet: snippet',
|
|
218
|
+
' });',
|
|
219
|
+
' }',
|
|
220
|
+
'}',
|
|
221
|
+
'',
|
|
222
|
+
'// Sort by score (descending) and limit results',
|
|
223
|
+
'results.sort(function(a, b) { return b.match_score - a.match_score; });',
|
|
224
|
+
'var topResults = results.slice(0, maxResults);',
|
|
225
|
+
'',
|
|
226
|
+
'// Output as JSON',
|
|
227
|
+
'console.log(JSON.stringify({',
|
|
228
|
+
' tool_references: topResults.map(function(r) {',
|
|
229
|
+
' return {',
|
|
230
|
+
' tool_name: r.tool_name,',
|
|
231
|
+
' match_score: r.match_score,',
|
|
232
|
+
' matched_field: r.matched_field,',
|
|
233
|
+
' snippet: r.snippet',
|
|
234
|
+
' };',
|
|
235
|
+
' }),',
|
|
236
|
+
' total_tools_searched: tools.length,',
|
|
237
|
+
' pattern_used: pattern',
|
|
238
|
+
'}));',
|
|
239
|
+
];
|
|
240
|
+
return lines.join('\n');
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Parses the search results from stdout JSON.
|
|
244
|
+
* @param stdout - The stdout string containing JSON results
|
|
245
|
+
* @returns Parsed search response
|
|
246
|
+
*/
|
|
247
|
+
function parseSearchResults(stdout) {
|
|
248
|
+
const jsonMatch = stdout.trim();
|
|
249
|
+
const parsed = JSON.parse(jsonMatch);
|
|
250
|
+
return parsed;
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Formats search results into a human-readable string.
|
|
254
|
+
* @param searchResponse - The parsed search response
|
|
255
|
+
* @returns Formatted string for LLM consumption
|
|
256
|
+
*/
|
|
257
|
+
function formatSearchResults(searchResponse) {
|
|
258
|
+
const { tool_references, total_tools_searched, pattern_used } = searchResponse;
|
|
259
|
+
if (tool_references.length === 0) {
|
|
260
|
+
return `No tools matched the pattern "${pattern_used}".\nTotal tools searched: ${total_tools_searched}`;
|
|
261
|
+
}
|
|
262
|
+
let response = `Found ${tool_references.length} matching tools:\n\n`;
|
|
263
|
+
for (const ref of tool_references) {
|
|
264
|
+
response += `- ${ref.tool_name} (score: ${ref.match_score.toFixed(2)})\n`;
|
|
265
|
+
response += ` Matched in: ${ref.matched_field}\n`;
|
|
266
|
+
response += ` Snippet: ${ref.snippet}\n\n`;
|
|
267
|
+
}
|
|
268
|
+
response += `Total tools searched: ${total_tools_searched}\n`;
|
|
269
|
+
response += `Pattern used: ${pattern_used}`;
|
|
270
|
+
return response;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Creates a Tool Search Regex tool for discovering tools from a large registry.
|
|
274
|
+
*
|
|
275
|
+
* This tool enables AI agents to dynamically discover tools from a large library
|
|
276
|
+
* without loading all tool definitions into the LLM context window. The agent
|
|
277
|
+
* can search for relevant tools on-demand using regex patterns.
|
|
278
|
+
*
|
|
279
|
+
* The tool registry can be provided either:
|
|
280
|
+
* 1. At initialization time via params.toolRegistry
|
|
281
|
+
* 2. At runtime via config.configurable.toolRegistry when invoking
|
|
282
|
+
*
|
|
283
|
+
* @param params - Configuration parameters for the tool (toolRegistry is optional)
|
|
284
|
+
* @returns A LangChain DynamicStructuredTool for tool searching
|
|
285
|
+
*
|
|
286
|
+
* @example
|
|
287
|
+
* // Option 1: Registry at initialization
|
|
288
|
+
* const tool = createToolSearchRegexTool({ apiKey, toolRegistry });
|
|
289
|
+
* await tool.invoke({ query: 'expense' });
|
|
290
|
+
*
|
|
291
|
+
* @example
|
|
292
|
+
* // Option 2: Registry at runtime
|
|
293
|
+
* const tool = createToolSearchRegexTool({ apiKey });
|
|
294
|
+
* await tool.invoke(
|
|
295
|
+
* { query: 'expense' },
|
|
296
|
+
* { configurable: { toolRegistry, onlyDeferred: true } }
|
|
297
|
+
* );
|
|
298
|
+
*/
|
|
299
|
+
function createToolSearchRegexTool(initParams = {}) {
|
|
300
|
+
const apiKey = initParams[_enum.EnvVar.CODE_API_KEY] ??
|
|
301
|
+
initParams.apiKey ??
|
|
302
|
+
env.getEnvironmentVariable(_enum.EnvVar.CODE_API_KEY) ??
|
|
303
|
+
'';
|
|
304
|
+
if (!apiKey) {
|
|
305
|
+
throw new Error('No API key provided for tool search regex tool.');
|
|
306
|
+
}
|
|
307
|
+
const baseEndpoint = initParams.baseUrl ?? CodeExecutor.getCodeBaseURL();
|
|
308
|
+
const EXEC_ENDPOINT = `${baseEndpoint}/exec`;
|
|
309
|
+
const defaultOnlyDeferred = initParams.onlyDeferred ?? true;
|
|
310
|
+
const description = `
|
|
311
|
+
Searches through available tools to find ones matching your query pattern.
|
|
312
|
+
|
|
313
|
+
Usage:
|
|
314
|
+
- Provide a regex pattern to search tool names and descriptions.
|
|
315
|
+
- Use this when you need to discover tools for a specific task.
|
|
316
|
+
- Results include tool names, match quality scores, and snippets showing where the match occurred.
|
|
317
|
+
- Higher scores (0.9+) indicate name matches, medium scores (0.7+) indicate description matches.
|
|
318
|
+
`.trim();
|
|
319
|
+
return tools.tool(async (params, config) => {
|
|
320
|
+
const { query, fields = ['name', 'description'], max_results = 10, } = params;
|
|
321
|
+
// Extra params injected by ToolNode (follows web_search pattern)
|
|
322
|
+
const { toolRegistry: paramToolRegistry, onlyDeferred: paramOnlyDeferred, } = config.toolCall ?? {};
|
|
323
|
+
const { safe: sanitizedPattern, wasEscaped } = sanitizeRegex(query);
|
|
324
|
+
let warningMessage = '';
|
|
325
|
+
if (wasEscaped) {
|
|
326
|
+
warningMessage =
|
|
327
|
+
'Note: The provided pattern was converted to a literal search for safety.\n\n';
|
|
328
|
+
}
|
|
329
|
+
// Priority: ToolNode injection (via config.toolCall) > initialization params
|
|
330
|
+
const toolRegistry = paramToolRegistry ?? initParams.toolRegistry;
|
|
331
|
+
const onlyDeferred = paramOnlyDeferred !== undefined
|
|
332
|
+
? paramOnlyDeferred
|
|
333
|
+
: defaultOnlyDeferred;
|
|
334
|
+
if (toolRegistry == null) {
|
|
335
|
+
return [
|
|
336
|
+
`${warningMessage}Error: No tool registry provided. Configure toolRegistry at agent level or initialization.`,
|
|
337
|
+
{
|
|
338
|
+
tool_references: [],
|
|
339
|
+
metadata: {
|
|
340
|
+
total_searched: 0,
|
|
341
|
+
pattern: sanitizedPattern,
|
|
342
|
+
error: 'No tool registry provided',
|
|
343
|
+
},
|
|
344
|
+
},
|
|
345
|
+
];
|
|
346
|
+
}
|
|
347
|
+
const toolsArray = Array.from(toolRegistry.values());
|
|
348
|
+
const deferredTools = toolsArray
|
|
349
|
+
.filter((lcTool) => {
|
|
350
|
+
if (onlyDeferred === true) {
|
|
351
|
+
return lcTool.defer_loading === true;
|
|
352
|
+
}
|
|
353
|
+
return true;
|
|
354
|
+
})
|
|
355
|
+
.map((lcTool) => ({
|
|
356
|
+
name: lcTool.name,
|
|
357
|
+
description: lcTool.description ?? '',
|
|
358
|
+
parameters: simplifyParametersForSearch(lcTool.parameters),
|
|
359
|
+
}));
|
|
360
|
+
if (deferredTools.length === 0) {
|
|
361
|
+
return [
|
|
362
|
+
`${warningMessage}No tools available to search. The tool registry is empty or no deferred tools are registered.`,
|
|
363
|
+
{
|
|
364
|
+
tool_references: [],
|
|
365
|
+
metadata: {
|
|
366
|
+
total_searched: 0,
|
|
367
|
+
pattern: sanitizedPattern,
|
|
368
|
+
},
|
|
369
|
+
},
|
|
370
|
+
];
|
|
371
|
+
}
|
|
372
|
+
const searchScript = generateSearchScript(deferredTools, fields, max_results, sanitizedPattern);
|
|
373
|
+
const postData = {
|
|
374
|
+
lang: 'js',
|
|
375
|
+
code: searchScript,
|
|
376
|
+
timeout: SEARCH_TIMEOUT,
|
|
377
|
+
};
|
|
378
|
+
try {
|
|
379
|
+
const fetchOptions = {
|
|
380
|
+
method: 'POST',
|
|
381
|
+
headers: {
|
|
382
|
+
'Content-Type': 'application/json',
|
|
383
|
+
'User-Agent': 'Illuma/1.0',
|
|
384
|
+
'X-API-Key': apiKey,
|
|
385
|
+
},
|
|
386
|
+
body: JSON.stringify(postData),
|
|
387
|
+
};
|
|
388
|
+
if (process.env.PROXY != null && process.env.PROXY !== '') {
|
|
389
|
+
fetchOptions.agent = new httpsProxyAgent.HttpsProxyAgent(process.env.PROXY);
|
|
390
|
+
}
|
|
391
|
+
const response = await fetch(EXEC_ENDPOINT, fetchOptions);
|
|
392
|
+
if (!response.ok) {
|
|
393
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
|
394
|
+
}
|
|
395
|
+
const result = await response.json();
|
|
396
|
+
if (result.stderr && result.stderr.trim()) {
|
|
397
|
+
// eslint-disable-next-line no-console
|
|
398
|
+
console.warn('[ToolSearchRegex] stderr:', result.stderr);
|
|
399
|
+
}
|
|
400
|
+
if (!result.stdout || !result.stdout.trim()) {
|
|
401
|
+
return [
|
|
402
|
+
`${warningMessage}No tools matched the pattern "${sanitizedPattern}".\nTotal tools searched: ${deferredTools.length}`,
|
|
403
|
+
{
|
|
404
|
+
tool_references: [],
|
|
405
|
+
metadata: {
|
|
406
|
+
total_searched: deferredTools.length,
|
|
407
|
+
pattern: sanitizedPattern,
|
|
408
|
+
},
|
|
409
|
+
},
|
|
410
|
+
];
|
|
411
|
+
}
|
|
412
|
+
const searchResponse = parseSearchResults(result.stdout);
|
|
413
|
+
const formattedOutput = `${warningMessage}${formatSearchResults(searchResponse)}`;
|
|
414
|
+
return [
|
|
415
|
+
formattedOutput,
|
|
416
|
+
{
|
|
417
|
+
tool_references: searchResponse.tool_references,
|
|
418
|
+
metadata: {
|
|
419
|
+
total_searched: searchResponse.total_tools_searched,
|
|
420
|
+
pattern: searchResponse.pattern_used,
|
|
421
|
+
},
|
|
422
|
+
},
|
|
423
|
+
];
|
|
424
|
+
}
|
|
425
|
+
catch (error) {
|
|
426
|
+
// eslint-disable-next-line no-console
|
|
427
|
+
console.error('[ToolSearchRegex] Error:', error);
|
|
428
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
429
|
+
return [
|
|
430
|
+
`Tool search failed: ${errorMessage}\n\nSuggestion: Try a simpler search pattern or search for specific tool names.`,
|
|
431
|
+
{
|
|
432
|
+
tool_references: [],
|
|
433
|
+
metadata: {
|
|
434
|
+
total_searched: 0,
|
|
435
|
+
pattern: sanitizedPattern,
|
|
436
|
+
error: errorMessage,
|
|
437
|
+
},
|
|
438
|
+
},
|
|
439
|
+
];
|
|
440
|
+
}
|
|
441
|
+
}, {
|
|
442
|
+
name: _enum.Constants.TOOL_SEARCH_REGEX,
|
|
443
|
+
description,
|
|
444
|
+
schema: ToolSearchRegexSchema,
|
|
445
|
+
responseFormat: _enum.Constants.CONTENT_AND_ARTIFACT,
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
exports.countNestedGroups = countNestedGroups;
|
|
450
|
+
exports.createToolSearchRegexTool = createToolSearchRegexTool;
|
|
451
|
+
exports.escapeRegexSpecialChars = escapeRegexSpecialChars;
|
|
452
|
+
exports.hasNestedQuantifiers = hasNestedQuantifiers;
|
|
453
|
+
exports.isDangerousPattern = isDangerousPattern;
|
|
454
|
+
exports.sanitizeRegex = sanitizeRegex;
|
|
455
|
+
//# sourceMappingURL=ToolSearchRegex.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ToolSearchRegex.cjs","sources":["../../../src/tools/ToolSearchRegex.ts"],"sourcesContent":["// src/tools/ToolSearchRegex.ts\nimport { z } from 'zod';\nimport { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { getCodeBaseURL } from './CodeExecutor';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\n/** Maximum allowed regex pattern length */\nconst MAX_PATTERN_LENGTH = 200;\n\n/** Maximum allowed regex nesting depth */\nconst MAX_REGEX_COMPLEXITY = 5;\n\n/** Default search timeout in milliseconds */\nconst SEARCH_TIMEOUT = 5000;\n\nconst ToolSearchRegexSchema = z.object({\n query: z\n .string()\n .min(1)\n .max(MAX_PATTERN_LENGTH)\n .describe(\n 'Regex pattern to search tool names and descriptions. Special regex characters will be sanitized for safety.'\n ),\n fields: z\n .array(z.enum(['name', 'description', 'parameters']))\n .optional()\n .default(['name', 'description'])\n .describe('Which fields to search. Default: name and description'),\n max_results: z\n .number()\n .int()\n .min(1)\n .max(50)\n .optional()\n .default(10)\n .describe('Maximum number of matching tools to return'),\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 * 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 into a human-readable string.\n * @param searchResponse - The parsed search response\n * @returns Formatted string for LLM consumption\n */\nfunction formatSearchResults(searchResponse: t.ToolSearchResponse): string {\n const { tool_references, total_tools_searched, pattern_used } =\n searchResponse;\n\n if (tool_references.length === 0) {\n return `No tools matched the pattern \"${pattern_used}\".\\nTotal tools searched: ${total_tools_searched}`;\n }\n\n let response = `Found ${tool_references.length} matching tools:\\n\\n`;\n\n for (const ref of tool_references) {\n response += `- ${ref.tool_name} (score: ${ref.match_score.toFixed(2)})\\n`;\n response += ` Matched in: ${ref.matched_field}\\n`;\n response += ` Snippet: ${ref.snippet}\\n\\n`;\n }\n\n response += `Total tools searched: ${total_tools_searched}\\n`;\n response += `Pattern used: ${pattern_used}`;\n\n return response;\n}\n\n/**\n * Creates a Tool Search Regex 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 using regex patterns.\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: Registry at initialization\n * const tool = createToolSearchRegexTool({ apiKey, toolRegistry });\n * await tool.invoke({ query: 'expense' });\n *\n * @example\n * // Option 2: Registry at runtime\n * const tool = createToolSearchRegexTool({ apiKey });\n * await tool.invoke(\n * { query: 'expense' },\n * { configurable: { toolRegistry, onlyDeferred: true } }\n * );\n */\nfunction createToolSearchRegexTool(\n initParams: t.ToolSearchRegexParams = {}\n): DynamicStructuredTool<typeof ToolSearchRegexSchema> {\n const apiKey: string =\n (initParams[EnvVar.CODE_API_KEY] as string | undefined) ??\n initParams.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n\n if (!apiKey) {\n throw new Error('No API key provided for tool search regex tool.');\n }\n\n const baseEndpoint = initParams.baseUrl ?? getCodeBaseURL();\n const EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n const defaultOnlyDeferred = initParams.onlyDeferred ?? true;\n\n const description = `\nSearches through available tools to find ones matching your query pattern.\n\nUsage:\n- Provide a regex pattern to search tool names and descriptions.\n- Use this when you need to discover tools for a specific task.\n- Results include tool names, match quality scores, and snippets showing where the match occurred.\n- Higher scores (0.9+) indicate name matches, medium scores (0.7+) indicate description matches.\n`.trim();\n\n return tool<typeof ToolSearchRegexSchema>(\n async (params, config) => {\n const {\n query,\n fields = ['name', 'description'],\n max_results = 10,\n } = params;\n\n // Extra params injected by ToolNode (follows web_search pattern)\n const {\n toolRegistry: paramToolRegistry,\n onlyDeferred: paramOnlyDeferred,\n } = config.toolCall ?? {};\n\n const { safe: sanitizedPattern, wasEscaped } = sanitizeRegex(query);\n\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 // Priority: ToolNode injection (via config.toolCall) > initialization params\n const toolRegistry = paramToolRegistry ?? initParams.toolRegistry;\n const onlyDeferred =\n paramOnlyDeferred !== undefined\n ? paramOnlyDeferred\n : defaultOnlyDeferred;\n\n if (toolRegistry == null) {\n return [\n `${warningMessage}Error: No tool registry provided. Configure toolRegistry at agent level or initialization.`,\n {\n tool_references: [],\n metadata: {\n total_searched: 0,\n pattern: sanitizedPattern,\n error: 'No tool registry provided',\n },\n },\n ];\n }\n\n const toolsArray: t.LCTool[] = Array.from(toolRegistry.values());\n\n const deferredTools: t.ToolMetadata[] = toolsArray\n .filter((lcTool) => {\n if (onlyDeferred === true) {\n return lcTool.defer_loading === true;\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 return [\n `${warningMessage}No tools available to search. The tool registry is empty or no deferred tools are registered.`,\n {\n tool_references: [],\n metadata: {\n total_searched: 0,\n pattern: sanitizedPattern,\n },\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': 'Illuma/1.0',\n 'X-API-Key': apiKey,\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('[ToolSearchRegex] 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)}`;\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('[ToolSearchRegex] 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_REGEX,\n description,\n schema: ToolSearchRegexSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport {\n createToolSearchRegexTool,\n sanitizeRegex,\n escapeRegexSpecialChars,\n isDangerousPattern,\n countNestedGroups,\n hasNestedQuantifiers,\n};\n"],"names":["config","z","EnvVar","getEnvironmentVariable","getCodeBaseURL","tool","HttpsProxyAgent","Constants"],"mappings":";;;;;;;;;;;AAAA;AAWAA,aAAM,EAAE;AAER;AACA,MAAM,kBAAkB,GAAG,GAAG;AAE9B;AACA,MAAM,oBAAoB,GAAG,CAAC;AAE9B;AACA,MAAM,cAAc,GAAG,IAAI;AAE3B,MAAM,qBAAqB,GAAGC,KAAC,CAAC,MAAM,CAAC;AACrC,IAAA,KAAK,EAAEA;AACJ,SAAA,MAAM;SACN,GAAG,CAAC,CAAC;SACL,GAAG,CAAC,kBAAkB;SACtB,QAAQ,CACP,6GAA6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AAE;AACnB,oBAAA,QAAQ,EAAE;AACR,wBAAA,cAAc,EAAE,CAAC;AACjB,wBAAA,OAAO,EAAE,gBAAgB;AACzB,wBAAA,KAAK,EAAE,YAAY;AACpB,qBAAA;AACF,iBAAA;aACF;;AAEL,KAAC,EACD;QACE,IAAI,EAAEC,eAAS,CAAC,iBAAiB;QACjC,WAAW;AACX,QAAA,MAAM,EAAE,qBAAqB;QAC7B,cAAc,EAAEA,eAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;;;;;;"}
|
|
@@ -310,6 +310,13 @@ function createTool({ schema, search, onSearchResults: _onSearchResults, }) {
|
|
|
310
310
|
return tools.tool(async (params, runnableConfig) => {
|
|
311
311
|
const { query, date, country: _c, images, videos, news } = params;
|
|
312
312
|
const country = typeof _c === 'string' && _c ? _c : undefined;
|
|
313
|
+
// Log the incoming query for debugging URL detection
|
|
314
|
+
const toolLogger = utils.createDefaultLogger();
|
|
315
|
+
toolLogger.debug(`[web_search] Received query: "${query}"`);
|
|
316
|
+
const detectedUrls = extractUrlsFromQuery(query);
|
|
317
|
+
if (detectedUrls.length > 0) {
|
|
318
|
+
toolLogger.debug(`[web_search] Detected URLs in query: ${detectedUrls.join(', ')}`);
|
|
319
|
+
}
|
|
313
320
|
const searchResult = await search({
|
|
314
321
|
query,
|
|
315
322
|
date,
|
|
@@ -328,7 +335,20 @@ function createTool({ schema, search, onSearchResults: _onSearchResults, }) {
|
|
|
328
335
|
return [output, { [_enum.Constants.WEB_SEARCH]: data }];
|
|
329
336
|
}, {
|
|
330
337
|
name: _enum.Constants.WEB_SEARCH,
|
|
331
|
-
description: `Real-time search. Results have required citation anchors.
|
|
338
|
+
description: `Real-time web search and direct URL content extraction. Results have required citation anchors.
|
|
339
|
+
|
|
340
|
+
**CAPABILITIES:**
|
|
341
|
+
- Search: Query the web for information on any topic
|
|
342
|
+
- Direct URL: Fetch and extract content from a specific URL for summarization or analysis
|
|
343
|
+
|
|
344
|
+
**CRITICAL - URL HANDLING:**
|
|
345
|
+
When user provides a URL (e.g., "summarize https://example.com/article"), you MUST include the FULL URL in the query parameter.
|
|
346
|
+
- CORRECT: query = "https://example.com/article" or "summarize https://example.com/article"
|
|
347
|
+
- WRONG: query = "example article summary" (do NOT convert URLs to search terms)
|
|
348
|
+
|
|
349
|
+
**USAGE:**
|
|
350
|
+
- For search: Use concise search terms as query
|
|
351
|
+
- For URL extraction: Pass the complete URL in the query field
|
|
332
352
|
|
|
333
353
|
Note: Use ONCE per reply unless instructed otherwise.
|
|
334
354
|
|