@librechat/agents 3.3.4 → 3.3.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/common/constants.cjs +21 -0
- package/dist/cjs/common/constants.cjs.map +1 -1
- package/dist/cjs/events.cjs +10 -1
- package/dist/cjs/events.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +456 -7
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/hooks/HookRegistry.cjs +25 -0
- package/dist/cjs/hooks/HookRegistry.cjs.map +1 -1
- package/dist/cjs/hooks/createWorkspacePolicyHook.cjs +1 -1
- package/dist/cjs/hooks/index.cjs +12 -0
- package/dist/cjs/hooks/index.cjs.map +1 -1
- package/dist/cjs/hooks/types.cjs +1 -0
- package/dist/cjs/hooks/types.cjs.map +1 -1
- package/dist/cjs/langfuse.cjs +8 -0
- package/dist/cjs/langfuse.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +1 -3
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/invoke.cjs +268 -3
- package/dist/cjs/llm/invoke.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +51 -6
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/preempt.cjs +132 -0
- package/dist/cjs/llm/preempt.cjs.map +1 -0
- package/dist/cjs/main.cjs +31 -3
- package/dist/cjs/messages/alternation.cjs +92 -0
- package/dist/cjs/messages/alternation.cjs.map +1 -0
- package/dist/cjs/messages/format.cjs +72 -0
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/handoffCue.cjs +63 -0
- package/dist/cjs/messages/handoffCue.cjs.map +1 -0
- package/dist/cjs/messages/index.cjs +3 -0
- package/dist/cjs/messages/injected.cjs +60 -0
- package/dist/cjs/messages/injected.cjs.map +1 -0
- package/dist/cjs/run.cjs +80 -7
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/session/JsonlSessionStore.cjs +1 -1
- package/dist/cjs/session/handlers.cjs +18 -9
- package/dist/cjs/session/handlers.cjs.map +1 -1
- package/dist/cjs/stream.cjs +34 -8
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +3 -1
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +2 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +19 -16
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +2 -0
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ReadFile.cjs +8 -4
- package/dist/cjs/tools/ReadFile.cjs.map +1 -1
- package/dist/cjs/tools/SkillTool.cjs +2 -0
- package/dist/cjs/tools/SkillTool.cjs.map +1 -1
- package/dist/cjs/tools/SubagentTool.cjs +3 -0
- package/dist/cjs/tools/SubagentTool.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +91 -50
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/ToolSearch.cjs +5 -1
- package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
- package/dist/cjs/tools/intentArg.cjs +230 -0
- package/dist/cjs/tools/intentArg.cjs.map +1 -0
- package/dist/cjs/tools/local/CompileCheckTool.cjs +3 -2
- package/dist/cjs/tools/local/CompileCheckTool.cjs.map +1 -1
- package/dist/cjs/tools/local/LocalCodingTools.cjs +13 -12
- package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -1
- package/dist/cjs/tools/local/LocalExecutionEngine.cjs +2 -2
- package/dist/cjs/tools/ptcTimeout.cjs.map +1 -1
- package/dist/cjs/tools/search/keenable-scraper.cjs +90 -0
- package/dist/cjs/tools/search/keenable-scraper.cjs.map +1 -0
- package/dist/cjs/tools/search/schema.cjs +2 -0
- package/dist/cjs/tools/search/schema.cjs.map +1 -1
- package/dist/cjs/tools/search/tool.cjs +40 -2
- package/dist/cjs/tools/search/tool.cjs.map +1 -1
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +1 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
- package/dist/cjs/tools/toolOutputReferences.cjs +41 -7
- package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
- package/dist/esm/common/constants.mjs +19 -1
- package/dist/esm/common/constants.mjs.map +1 -1
- package/dist/esm/events.mjs +10 -1
- package/dist/esm/events.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +455 -6
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/hooks/HookRegistry.mjs +25 -0
- package/dist/esm/hooks/HookRegistry.mjs.map +1 -1
- package/dist/esm/hooks/createWorkspacePolicyHook.mjs +1 -1
- package/dist/esm/hooks/index.mjs +12 -1
- package/dist/esm/hooks/index.mjs.map +1 -1
- package/dist/esm/hooks/types.mjs +1 -0
- package/dist/esm/hooks/types.mjs.map +1 -1
- package/dist/esm/langfuse.mjs +9 -1
- package/dist/esm/langfuse.mjs.map +1 -1
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs +1 -3
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/invoke.mjs +270 -6
- package/dist/esm/llm/invoke.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +51 -6
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/preempt.mjs +131 -0
- package/dist/esm/llm/preempt.mjs.map +1 -0
- package/dist/esm/main.mjs +11 -7
- package/dist/esm/messages/alternation.mjs +91 -0
- package/dist/esm/messages/alternation.mjs.map +1 -0
- package/dist/esm/messages/format.mjs +72 -0
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/handoffCue.mjs +61 -0
- package/dist/esm/messages/handoffCue.mjs.map +1 -0
- package/dist/esm/messages/index.mjs +3 -0
- package/dist/esm/messages/injected.mjs +60 -0
- package/dist/esm/messages/injected.mjs.map +1 -0
- package/dist/esm/run.mjs +80 -7
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/session/JsonlSessionStore.mjs +1 -1
- package/dist/esm/session/handlers.mjs +19 -10
- package/dist/esm/session/handlers.mjs.map +1 -1
- package/dist/esm/stream.mjs +33 -9
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +3 -1
- package/dist/esm/tools/BashExecutor.mjs.map +1 -1
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +2 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +19 -16
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +2 -0
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ReadFile.mjs +8 -4
- package/dist/esm/tools/ReadFile.mjs.map +1 -1
- package/dist/esm/tools/SkillTool.mjs +2 -0
- package/dist/esm/tools/SkillTool.mjs.map +1 -1
- package/dist/esm/tools/SubagentTool.mjs +3 -0
- package/dist/esm/tools/SubagentTool.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +91 -51
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/ToolSearch.mjs +5 -1
- package/dist/esm/tools/ToolSearch.mjs.map +1 -1
- package/dist/esm/tools/intentArg.mjs +220 -0
- package/dist/esm/tools/intentArg.mjs.map +1 -0
- package/dist/esm/tools/local/CompileCheckTool.mjs +3 -2
- package/dist/esm/tools/local/CompileCheckTool.mjs.map +1 -1
- package/dist/esm/tools/local/LocalCodingTools.mjs +13 -12
- package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -1
- package/dist/esm/tools/local/LocalExecutionEngine.mjs +2 -2
- package/dist/esm/tools/ptcTimeout.mjs.map +1 -1
- package/dist/esm/tools/search/keenable-scraper.mjs +88 -0
- package/dist/esm/tools/search/keenable-scraper.mjs.map +1 -0
- package/dist/esm/tools/search/schema.mjs +2 -0
- package/dist/esm/tools/search/schema.mjs.map +1 -1
- package/dist/esm/tools/search/tool.mjs +40 -3
- package/dist/esm/tools/search/tool.mjs.map +1 -1
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +1 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
- package/dist/esm/tools/toolOutputReferences.mjs +41 -7
- package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
- package/dist/types/common/constants.d.ts +18 -0
- package/dist/types/graphs/Graph.d.ts +138 -1
- package/dist/types/hooks/HookRegistry.d.ts +15 -0
- package/dist/types/hooks/index.d.ts +12 -1
- package/dist/types/hooks/types.d.ts +45 -6
- package/dist/types/index.d.ts +2 -1
- package/dist/types/llm/invoke.d.ts +7 -0
- package/dist/types/llm/openai/index.d.ts +0 -11
- package/dist/types/llm/preempt.d.ts +40 -0
- package/dist/types/messages/alternation.d.ts +23 -0
- package/dist/types/messages/handoffCue.d.ts +40 -0
- package/dist/types/messages/index.d.ts +3 -0
- package/dist/types/messages/injected.d.ts +3 -0
- package/dist/types/run.d.ts +7 -0
- package/dist/types/stream.d.ts +14 -0
- package/dist/types/tools/BashExecutor.d.ts +18 -0
- package/dist/types/tools/CodeExecutor.d.ts +18 -0
- package/dist/types/tools/ReadFile.d.ts +18 -0
- package/dist/types/tools/SkillTool.d.ts +18 -0
- package/dist/types/tools/SubagentTool.d.ts +9 -0
- package/dist/types/tools/ToolNode.d.ts +37 -12
- package/dist/types/tools/ToolSearch.d.ts +18 -0
- package/dist/types/tools/intentArg.d.ts +119 -0
- package/dist/types/tools/ptcTimeout.d.ts +2 -0
- package/dist/types/tools/search/keenable-scraper.d.ts +15 -0
- package/dist/types/tools/search/schema.d.ts +18 -0
- package/dist/types/tools/search/tool.d.ts +18 -0
- package/dist/types/tools/search/types.d.ts +31 -2
- package/dist/types/tools/toolOutputReferences.d.ts +12 -2
- package/dist/types/types/graph.d.ts +8 -1
- package/dist/types/types/run.d.ts +65 -0
- package/dist/types/types/stream.d.ts +12 -25
- package/dist/types/types/tools.d.ts +27 -2
- package/package.json +1 -1
- package/src/{splitStream.test.ts → aggregator.test.ts} +59 -666
- package/src/common/constants.ts +21 -0
- package/src/events.ts +15 -1
- package/src/graphs/Graph.ts +568 -3
- package/src/graphs/__tests__/Graph.contextOverflow.test.ts +18 -7
- package/src/graphs/__tests__/Graph.preemptSignal.test.ts +126 -0
- package/src/hooks/HookRegistry.ts +40 -0
- package/src/hooks/__tests__/preemptBoundary.test.ts +152 -0
- package/src/hooks/index.ts +16 -2
- package/src/hooks/types.ts +47 -3
- package/src/index.ts +2 -1
- package/src/langfuse.ts +26 -1
- package/src/llm/bedrock/utils/message_inputs.test.ts +82 -0
- package/src/llm/bedrock/utils/message_inputs.ts +14 -11
- package/src/llm/bedrock/utils/toolResultCachePoint.test.ts +15 -0
- package/src/llm/invoke.alternation.test.ts +87 -0
- package/src/llm/invoke.handoffCue.test.ts +112 -0
- package/src/llm/invoke.ts +417 -8
- package/src/llm/openai/index.ts +74 -10
- package/src/llm/openai/llm.spec.ts +105 -0
- package/src/llm/preempt.test.ts +323 -0
- package/src/llm/preempt.ts +178 -0
- package/src/messages/alternation.test.ts +212 -0
- package/src/messages/alternation.ts +112 -0
- package/src/messages/format.ts +91 -0
- package/src/messages/formatAgentMessages.steer.test.ts +267 -0
- package/src/messages/handoffCue.test.ts +96 -0
- package/src/messages/handoffCue.ts +78 -0
- package/src/messages/index.ts +3 -0
- package/src/messages/injected.test.ts +90 -0
- package/src/messages/injected.ts +74 -0
- package/src/run.ts +91 -6
- package/src/scripts/preempt-probe.ts +330 -0
- package/src/scripts/preempt-scenarios.ts +388 -0
- package/src/session/handlers.ts +32 -12
- package/src/specs/handoffCue.test.ts +165 -0
- package/src/specs/langfuse-callbacks.test.ts +352 -2
- package/src/specs/preemptSeal.test.ts +309 -0
- package/src/stream.dispatch.test.ts +63 -0
- package/src/stream.ts +48 -9
- package/src/tools/BashExecutor.ts +6 -0
- package/src/tools/BashProgrammaticToolCalling.ts +2 -0
- package/src/tools/CodeExecutor.ts +6 -0
- package/src/tools/ProgrammaticToolCalling.ts +2 -0
- package/src/tools/ReadFile.ts +2 -0
- package/src/tools/SkillTool.ts +2 -0
- package/src/tools/SubagentTool.ts +3 -0
- package/src/tools/ToolNode.ts +193 -74
- package/src/tools/ToolSearch.ts +3 -0
- package/src/tools/__tests__/ToolNode.onResultCompletion.test.ts +174 -0
- package/src/tools/__tests__/intentArg.test.ts +281 -0
- package/src/tools/__tests__/intentCoverage.test.ts +139 -0
- package/src/tools/__tests__/toolOutputReferences.test.ts +83 -0
- package/src/tools/intentArg.ts +323 -0
- package/src/tools/local/CompileCheckTool.ts +4 -3
- package/src/tools/local/LocalCodingTools.ts +14 -13
- package/src/tools/ptcTimeout.ts +2 -0
- package/src/tools/search/keenable-scraper.test.ts +153 -0
- package/src/tools/search/keenable-scraper.ts +137 -0
- package/src/tools/search/outcome.test.ts +90 -0
- package/src/tools/search/schema.ts +3 -0
- package/src/tools/search/tool.ts +60 -3
- package/src/tools/search/types.ts +50 -3
- package/src/tools/subagent/SubagentExecutor.ts +2 -1
- package/src/tools/toolOutputReferences.ts +77 -9
- package/src/types/graph.ts +12 -1
- package/src/types/run.ts +67 -0
- package/src/types/stream.ts +12 -41
- package/src/types/tools.ts +24 -2
- package/dist/cjs/splitStream.cjs +0 -151
- package/dist/cjs/splitStream.cjs.map +0 -1
- package/dist/esm/splitStream.mjs +0 -150
- package/dist/esm/splitStream.mjs.map +0 -1
- package/dist/types/mockStream.d.ts +0 -32
- package/dist/types/splitStream.d.ts +0 -37
- package/src/mockStream.ts +0 -99
- package/src/splitStream.ts +0 -234
|
@@ -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:
|
|
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,YAA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AAK;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,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AClD;EACF;EAEA,IAAI,CAAC,kBAAkB,uBAAuB,GAAG;EAEjD,MAAM,EAAE,OAAO,YAAY,iBAAiB,MAAM,IAAI,aAAa,MAAM;EACzE,QAAQ,KAAK;GACX,QAAQ;IACN,WAAW,MAAM,EAAE,CAAC;IACpB,aAAa;IACb,eAAe;IACf;GACF;GACA;EACF,CAAC;CACH;CAEA,QAAQ,MACL,GAAG,MACF,EAAE,qBAAqB,EAAE,sBACzB,EAAE,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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GF,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"}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
//#region src/tools/intentArg.ts
|
|
2
|
+
/** Argument carrying the model-authored label for a tool call. */
|
|
3
|
+
const INTENT_ARG = "intent";
|
|
4
|
+
/** Model-facing instruction for the injected `intent` property. */
|
|
5
|
+
const INTENT_DESCRIPTION = "ALWAYS write this field FIRST, before any other argument. One short sentence, present progressive, stating what this specific call is about to do: \"Searching for OAuth handling in the callback router\". It is shown to the user as the live status label for this call while it runs, so write it for a human reading a progress line. Do not restate the tool name. Do not exceed one sentence. When you make several calls to the same tool in one turn, each intent must distinguish that call from its siblings.";
|
|
6
|
+
/**
|
|
7
|
+
* Canonical (frozen) shape of the injected property. Always embed a COPY
|
|
8
|
+
* (`{ ...INTENT_PROPERTY }`): LangChain's JSON-schema validator stamps a
|
|
9
|
+
* `__absolute_uri__` marker onto every subschema it dereferences, which
|
|
10
|
+
* throws on a frozen object — and a single shared instance would be stamped
|
|
11
|
+
* with one schema's URI while embedded in many.
|
|
12
|
+
*/
|
|
13
|
+
const INTENT_PROPERTY = Object.freeze({
|
|
14
|
+
type: "string",
|
|
15
|
+
description: INTENT_DESCRIPTION
|
|
16
|
+
});
|
|
17
|
+
/**
|
|
18
|
+
* Discriminates the intent LABEL property from a tool's own business
|
|
19
|
+
* parameter that merely shares the name: the label contract always opens
|
|
20
|
+
* with the same instruction. Removal/sanitize passes must never strip a
|
|
21
|
+
* parameter the tool actually needs.
|
|
22
|
+
*/
|
|
23
|
+
function isIntentLabelProperty(property) {
|
|
24
|
+
if (property == null || typeof property !== "object") return false;
|
|
25
|
+
const record = property;
|
|
26
|
+
return record.type === "string" && typeof record.description === "string" && record.description.startsWith("ALWAYS write this field FIRST");
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Returns a copy of the parameters schema with `intent` prepended as the
|
|
30
|
+
* FIRST property (object key order is insertion order and every provider
|
|
31
|
+
* serializer preserves it — first key in the schema means first key in the
|
|
32
|
+
* streamed input). Never mutates the input; no-op when the schema already
|
|
33
|
+
* declares `intent`. The property is not added to `required`.
|
|
34
|
+
*/
|
|
35
|
+
function withIntent(parameters) {
|
|
36
|
+
const existingProps = parameters?.properties ?? {};
|
|
37
|
+
if ("intent" in existingProps) return parameters;
|
|
38
|
+
return {
|
|
39
|
+
...parameters,
|
|
40
|
+
type: "object",
|
|
41
|
+
properties: {
|
|
42
|
+
[INTENT_ARG]: { ...INTENT_PROPERTY },
|
|
43
|
+
...existingProps
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Coerces tool-call args to an object, parsing a stringified JSON object
|
|
49
|
+
* (some providers deliver args as a string). Returns undefined otherwise.
|
|
50
|
+
*/
|
|
51
|
+
function coerceArgsObject(args) {
|
|
52
|
+
if (typeof args === "object" && args !== null && !Array.isArray(args)) return args;
|
|
53
|
+
if (typeof args === "string" && args.trim().startsWith("{")) try {
|
|
54
|
+
const parsed = JSON.parse(args);
|
|
55
|
+
if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
|
|
56
|
+
} catch {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Reads the model-authored intent from tool-call args (handles stringified
|
|
62
|
+
* args). Returns undefined when absent, empty, or not a string.
|
|
63
|
+
*/
|
|
64
|
+
function readIntent(args) {
|
|
65
|
+
const value = coerceArgsObject(args)?.[INTENT_ARG];
|
|
66
|
+
if (typeof value !== "string") return;
|
|
67
|
+
const trimmed = value.trim();
|
|
68
|
+
return trimmed === "" ? void 0 : trimmed;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Returns the args without the `intent` key so downstream consumers that did
|
|
72
|
+
* not declare it never receive it. Parses stringified JSON object args;
|
|
73
|
+
* returns the value unchanged when the key is absent.
|
|
74
|
+
*/
|
|
75
|
+
function stripIntent(args) {
|
|
76
|
+
const obj = coerceArgsObject(args);
|
|
77
|
+
if (!obj || !("intent" in obj)) return args;
|
|
78
|
+
const { [INTENT_ARG]: _omit, ...rest } = obj;
|
|
79
|
+
return rest;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Leading-verb map for the mechanical outcome transform, keyed by the
|
|
83
|
+
* lowercased first word of the intent. Deliberately small: an unknown leading
|
|
84
|
+
* word leaves the intent unchanged rather than mangling it.
|
|
85
|
+
*/
|
|
86
|
+
const OUTCOME_VERB_MAP = new Map([
|
|
87
|
+
["searching", "Searched"],
|
|
88
|
+
["reading", "Read"],
|
|
89
|
+
["writing", "Wrote"],
|
|
90
|
+
["editing", "Edited"],
|
|
91
|
+
["running", "Ran"],
|
|
92
|
+
["creating", "Created"],
|
|
93
|
+
["checking", "Checked"],
|
|
94
|
+
["fetching", "Fetched"],
|
|
95
|
+
["listing", "Listed"],
|
|
96
|
+
["looking", "Looked"],
|
|
97
|
+
["building", "Built"],
|
|
98
|
+
["deleting", "Deleted"],
|
|
99
|
+
["updating", "Updated"],
|
|
100
|
+
["adding", "Added"],
|
|
101
|
+
["removing", "Removed"],
|
|
102
|
+
["verifying", "Verified"],
|
|
103
|
+
["analyzing", "Analyzed"],
|
|
104
|
+
["generating", "Generated"],
|
|
105
|
+
["delegating", "Delegated"],
|
|
106
|
+
["spawning", "Spawned"],
|
|
107
|
+
["compiling", "Compiled"],
|
|
108
|
+
["grepping", "Grepped"]
|
|
109
|
+
]);
|
|
110
|
+
function matchLeadingCase(replacement, original) {
|
|
111
|
+
if (original.charAt(0) === original.charAt(0).toLowerCase()) return replacement.charAt(0).toLowerCase() + replacement.slice(1);
|
|
112
|
+
return replacement;
|
|
113
|
+
}
|
|
114
|
+
function transformLeadingVerb(intent) {
|
|
115
|
+
const spaceIdx = intent.search(/\s/);
|
|
116
|
+
const leading = spaceIdx === -1 ? intent : intent.slice(0, spaceIdx);
|
|
117
|
+
const mapped = OUTCOME_VERB_MAP.get(leading.toLowerCase());
|
|
118
|
+
if (mapped == null) return intent;
|
|
119
|
+
return matchLeadingCase(mapped, leading) + intent.slice(leading.length);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Resolves the settled label for a call from its model-authored `intent` and
|
|
123
|
+
* the tool's result fields, in precedence order:
|
|
124
|
+
*
|
|
125
|
+
* 1. `outcome` — full replacement authored by the tool.
|
|
126
|
+
* 2. `outcome_patch` — first occurrence of `from` in the intent replaced
|
|
127
|
+
* with `to` (case-sensitive); no-op when `from` is absent or empty.
|
|
128
|
+
* 3. Mechanical transform — the leading word mapped present-progressive →
|
|
129
|
+
* past tense; an unknown leading word leaves the intent unchanged.
|
|
130
|
+
*
|
|
131
|
+
* Returns undefined when there is neither an intent nor an outcome, so
|
|
132
|
+
* callers fall back to their default label. Pure and dependency-free — host
|
|
133
|
+
* UIs needing identical logic can import or mirror it.
|
|
134
|
+
*/
|
|
135
|
+
function applyOutcome(intent, result) {
|
|
136
|
+
const outcome = result?.outcome;
|
|
137
|
+
if (typeof outcome === "string" && outcome.trim() !== "") return outcome;
|
|
138
|
+
if (intent == null || intent === "") return;
|
|
139
|
+
const patch = result?.outcome_patch;
|
|
140
|
+
if (patch != null && patch.from !== "" && intent.includes(patch.from))
|
|
141
|
+
/** Replacement callback keeps `to` verbatim — a direct string second
|
|
142
|
+
* argument would interpret `$&`/`$'`-style tokens in tool-authored
|
|
143
|
+
* text (e.g. labels derived from shell syntax). */
|
|
144
|
+
return intent.replace(patch.from, () => patch.to);
|
|
145
|
+
return transformLeadingVerb(intent);
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Hard cap on an emitted outcome label. The label is a single progress line
|
|
149
|
+
* in UI chrome; a tool that derives it from data (or a malformed patch)
|
|
150
|
+
* must not be able to inflate completion events or persisted parts.
|
|
151
|
+
*/
|
|
152
|
+
const MAX_OUTCOME_CHARS = 256;
|
|
153
|
+
function boundOutcomeLabel(label) {
|
|
154
|
+
if (label == null) return;
|
|
155
|
+
const singleLine = label.replace(/\s+/g, " ").trim();
|
|
156
|
+
if (singleLine === "") return;
|
|
157
|
+
if (singleLine.length <= MAX_OUTCOME_CHARS) return singleLine;
|
|
158
|
+
return `${singleLine.slice(0, MAX_OUTCOME_CHARS - 1)}…`;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Resolves the settled label to emit on a completion event: only when the
|
|
162
|
+
* tool actually authored `outcome`/`outcome_patch` fields. Returns undefined
|
|
163
|
+
* otherwise — the mechanical transform of a bare intent is left to the host
|
|
164
|
+
* so the wire never carries a label the host can derive itself. The result
|
|
165
|
+
* is collapsed to a bounded single line before emission.
|
|
166
|
+
*
|
|
167
|
+
* For failed calls (`isError`), only tool-AUTHORED text may label the call:
|
|
168
|
+
* an explicit `outcome`, or a patch whose `from` actually matches the
|
|
169
|
+
* intent. An unmatched patch must not fall through to the mechanical
|
|
170
|
+
* past-tense transform — wording drift in a failure patch would otherwise
|
|
171
|
+
* render a success-looking label for an error.
|
|
172
|
+
*/
|
|
173
|
+
function resolveToolOutcome(args, fields, options) {
|
|
174
|
+
if (fields == null || fields.outcome == null && fields.outcome_patch == null) return;
|
|
175
|
+
if (options?.isError !== true) return boundOutcomeLabel(applyOutcome(readIntent(args), fields));
|
|
176
|
+
const outcome = fields.outcome;
|
|
177
|
+
if (typeof outcome === "string" && outcome.trim() !== "") return boundOutcomeLabel(outcome);
|
|
178
|
+
const intent = readIntent(args);
|
|
179
|
+
const patch = fields.outcome_patch;
|
|
180
|
+
if (intent != null && patch != null && patch.from !== "" && intent.includes(patch.from)) return boundOutcomeLabel(intent.replace(patch.from, () => patch.to));
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Reads the outcome fields off a tool-execution result: the typed
|
|
184
|
+
* `outcome`/`outcome_patch` fields when present, else the artifact channel
|
|
185
|
+
* (see {@link readOutcomeFields}) — so a `content_and_artifact` tool authors
|
|
186
|
+
* its label the same way on the direct and event-driven paths.
|
|
187
|
+
*/
|
|
188
|
+
function outcomeFieldsFromResult(result) {
|
|
189
|
+
if (result.outcome != null || result.outcome_patch != null) return result;
|
|
190
|
+
return readOutcomeFields(result.artifact);
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Extracts validated `outcome`/`outcome_patch` fields from an arbitrary
|
|
194
|
+
* value — the artifact channel through which an in-process
|
|
195
|
+
* `content_and_artifact` tool authors its settled label. Returns undefined
|
|
196
|
+
* when neither field is usable.
|
|
197
|
+
*/
|
|
198
|
+
function readOutcomeFields(source) {
|
|
199
|
+
if (source == null || typeof source !== "object" || Array.isArray(source)) return;
|
|
200
|
+
const record = source;
|
|
201
|
+
const outcome = typeof record.outcome === "string" && record.outcome.trim() !== "" ? record.outcome : void 0;
|
|
202
|
+
let outcome_patch;
|
|
203
|
+
const rawPatch = record.outcome_patch;
|
|
204
|
+
if (rawPatch != null && typeof rawPatch === "object" && !Array.isArray(rawPatch)) {
|
|
205
|
+
const patch = rawPatch;
|
|
206
|
+
if (typeof patch.from === "string" && typeof patch.to === "string") outcome_patch = {
|
|
207
|
+
from: patch.from,
|
|
208
|
+
to: patch.to
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
if (outcome == null && outcome_patch == null) return;
|
|
212
|
+
return {
|
|
213
|
+
outcome,
|
|
214
|
+
outcome_patch
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
//#endregion
|
|
218
|
+
export { INTENT_ARG, INTENT_DESCRIPTION, INTENT_PROPERTY, applyOutcome, isIntentLabelProperty, outcomeFieldsFromResult, readIntent, readOutcomeFields, resolveToolOutcome, stripIntent, withIntent };
|
|
219
|
+
|
|
220
|
+
//# 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`), a tool-supplied span edit (`outcome_patch`), or a mechanical\n * present-progressive→past-tense transform of the leading verb.\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/** Model-facing instruction for the injected `intent` property. */\nexport const INTENT_DESCRIPTION =\n 'ALWAYS write this field FIRST, before any other argument. One short sentence, ' +\n 'present progressive, stating what this specific call is about to do: ' +\n '\"Searching for OAuth handling in the callback router\". It is shown to the user ' +\n 'as the live status label for this call while it runs, so write it for a human ' +\n 'reading a progress line. Do not restate the tool name. Do not exceed one sentence. ' +\n 'When you make several calls to the same tool in one turn, each intent must ' +\n 'distinguish that call from its siblings.';\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('ALWAYS write this field FIRST')\n );\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 * Leading-verb map for the mechanical outcome transform, keyed by the\n * lowercased first word of the intent. Deliberately small: an unknown leading\n * word leaves the intent unchanged rather than mangling it.\n */\nconst OUTCOME_VERB_MAP: ReadonlyMap<string, string> = new Map([\n ['searching', 'Searched'],\n ['reading', 'Read'],\n ['writing', 'Wrote'],\n ['editing', 'Edited'],\n ['running', 'Ran'],\n ['creating', 'Created'],\n ['checking', 'Checked'],\n ['fetching', 'Fetched'],\n ['listing', 'Listed'],\n ['looking', 'Looked'],\n ['building', 'Built'],\n ['deleting', 'Deleted'],\n ['updating', 'Updated'],\n ['adding', 'Added'],\n ['removing', 'Removed'],\n ['verifying', 'Verified'],\n ['analyzing', 'Analyzed'],\n ['generating', 'Generated'],\n ['delegating', 'Delegated'],\n ['spawning', 'Spawned'],\n ['compiling', 'Compiled'],\n ['grepping', 'Grepped'],\n]);\n\nfunction matchLeadingCase(replacement: string, original: string): string {\n if (original.charAt(0) === original.charAt(0).toLowerCase()) {\n return replacement.charAt(0).toLowerCase() + replacement.slice(1);\n }\n return replacement;\n}\n\nfunction transformLeadingVerb(intent: string): string {\n const spaceIdx = intent.search(/\\s/);\n const leading = spaceIdx === -1 ? intent : intent.slice(0, spaceIdx);\n const mapped = OUTCOME_VERB_MAP.get(leading.toLowerCase());\n if (mapped == null) {\n return intent;\n }\n return matchLeadingCase(mapped, leading) + intent.slice(leading.length);\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. Mechanical transform — the leading word mapped present-progressive →\n * past tense; an unknown leading word leaves the intent unchanged.\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 transformLeadingVerb(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 — the mechanical transform of a bare intent is left to the host\n * so the wire never carries a label the host can derive itself. The result\n * 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\n * intent. An unmatched patch must not fall through to the mechanical\n * past-tense transform — wording drift in a failure patch would otherwise\n * render a success-looking label for an error.\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":";;AAuBA,MAAa,aAAa;;AAG1B,MAAa,qBACX;;;;;;;;AAeF,MAAa,kBAAkC,OAAO,OAAuB;CAC3E,MAAM;CACN,aAAa;AACf,CAAC;;;;;;;AAQD,SAAgB,sBAAsB,UAA4B;CAChE,IAAI,YAAY,QAAQ,OAAO,aAAa,UAC1C,OAAO;CAET,MAAM,SAAS;CACf,OACE,OAAO,SAAS,YAChB,OAAO,OAAO,gBAAgB,YAC9B,OAAO,YAAY,WAAW,+BAA+B;AAEjE;;;;;;;;AASA,SAAgB,WAAW,YAA6C;CACtE,MAAM,gBAAgB,YAAY,cAAc,CAAC;CACjD,IAAA,YAAkB,eAChB,OAAO;CAET,OAAO;EACL,GAAG;EACH,MAAM;EACN,YAAY;IAAG,aAAa,EAAE,GAAG,gBAAgB;GAAG,GAAG;EAAc;CACvE;AACF;;;;;AAMA,SAAS,iBAAiB,MAAoD;CAC5E,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,CAAC,MAAM,QAAQ,IAAI,GAClE,OAAO;CAET,IAAI,OAAO,SAAS,YAAY,KAAK,KAAK,CAAC,CAAC,WAAW,GAAG,GACxD,IAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;EAC9B,IAAI,UAAU,QAAQ,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,MAAM,GACvE,OAAO;CAEX,QAAQ;EACN;CACF;AAGJ;;;;;AAMA,SAAgB,WAAW,MAAmC;CAC5D,MAAM,QAAQ,iBAAiB,IAAI,CAAC,GAAG;CACvC,IAAI,OAAO,UAAU,UACnB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AI,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);
|