illuma-agents 1.0.10 → 1.0.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/dist/cjs/agents/AgentContext.cjs +228 -27
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +2 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/events.cjs +3 -11
- package/dist/cjs/events.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +27 -18
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/instrumentation.cjs +1 -3
- package/dist/cjs/instrumentation.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/index.cjs +1 -1
- package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +122 -7
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/google/index.cjs +1 -1
- package/dist/cjs/llm/google/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +6 -6
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/openrouter/index.cjs +1 -1
- package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +18 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/cache.cjs +149 -54
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/cjs/messages/tools.cjs +85 -0
- package/dist/cjs/messages/tools.cjs.map +1 -0
- package/dist/cjs/run.cjs +0 -8
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +4 -0
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +438 -0
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +53 -15
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/ToolSearchRegex.cjs +455 -0
- package/dist/cjs/tools/ToolSearchRegex.cjs.map +1 -0
- package/dist/cjs/tools/search/schema.cjs +7 -9
- package/dist/cjs/tools/search/schema.cjs.map +1 -1
- package/dist/cjs/utils/run.cjs +5 -1
- package/dist/cjs/utils/run.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +228 -27
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +2 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/events.mjs +4 -12
- package/dist/esm/events.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +27 -18
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/instrumentation.mjs +1 -3
- package/dist/esm/instrumentation.mjs.map +1 -1
- package/dist/esm/llm/anthropic/index.mjs +1 -1
- package/dist/esm/llm/anthropic/index.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +122 -7
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/google/index.mjs +1 -1
- package/dist/esm/llm/google/index.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +6 -6
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/openrouter/index.mjs +1 -1
- package/dist/esm/llm/openrouter/index.mjs.map +1 -1
- package/dist/esm/main.mjs +3 -0
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/cache.mjs +149 -54
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/esm/messages/tools.mjs +82 -0
- package/dist/esm/messages/tools.mjs.map +1 -0
- package/dist/esm/run.mjs +0 -8
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +4 -0
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +430 -0
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +53 -15
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/ToolSearchRegex.mjs +448 -0
- package/dist/esm/tools/ToolSearchRegex.mjs.map +1 -0
- package/dist/esm/tools/search/schema.mjs +7 -9
- package/dist/esm/tools/search/schema.mjs.map +1 -1
- package/dist/esm/utils/run.mjs +5 -1
- package/dist/esm/utils/run.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +65 -5
- package/dist/types/common/enum.d.ts +2 -0
- package/dist/types/graphs/Graph.d.ts +3 -2
- package/dist/types/index.d.ts +2 -0
- package/dist/types/llm/anthropic/index.d.ts +1 -1
- package/dist/types/llm/bedrock/index.d.ts +31 -4
- package/dist/types/llm/google/index.d.ts +1 -1
- package/dist/types/llm/openai/index.d.ts +3 -3
- package/dist/types/llm/openrouter/index.d.ts +1 -1
- package/dist/types/messages/cache.d.ts +23 -8
- package/dist/types/messages/index.d.ts +1 -0
- package/dist/types/messages/tools.d.ts +17 -0
- package/dist/types/test/mockTools.d.ts +28 -0
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +91 -0
- package/dist/types/tools/ToolNode.d.ts +10 -2
- package/dist/types/tools/ToolSearchRegex.d.ts +80 -0
- package/dist/types/types/graph.d.ts +7 -1
- package/dist/types/types/tools.d.ts +138 -0
- package/package.json +7 -2
- package/src/agents/AgentContext.ts +267 -27
- package/src/agents/__tests__/AgentContext.test.ts +805 -0
- package/src/common/enum.ts +2 -0
- package/src/events.ts +5 -12
- package/src/graphs/Graph.ts +33 -19
- package/src/index.ts +2 -0
- package/src/instrumentation.ts +1 -4
- package/src/llm/anthropic/index.ts +2 -2
- package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +473 -0
- package/src/llm/bedrock/index.ts +150 -13
- package/src/llm/google/index.ts +2 -2
- package/src/llm/openai/index.ts +9 -9
- package/src/llm/openrouter/index.ts +2 -2
- package/src/messages/__tests__/tools.test.ts +473 -0
- package/src/messages/cache.ts +163 -61
- package/src/messages/index.ts +1 -0
- package/src/messages/tools.ts +99 -0
- package/src/run.ts +0 -9
- package/src/scripts/code_exec_ptc.ts +334 -0
- package/src/scripts/image.ts +178 -0
- package/src/scripts/programmatic_exec.ts +396 -0
- package/src/scripts/programmatic_exec_agent.ts +231 -0
- package/src/scripts/test-tools-before-handoff.ts +5 -1
- package/src/scripts/tool_search_regex.ts +162 -0
- package/src/scripts/tools.ts +4 -1
- package/src/specs/thinking-prune.test.ts +52 -118
- package/src/test/mockTools.ts +366 -0
- package/src/tools/CodeExecutor.ts +4 -0
- package/src/tools/ProgrammaticToolCalling.ts +558 -0
- package/src/tools/ToolNode.ts +59 -18
- package/src/tools/ToolSearchRegex.ts +535 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +318 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +853 -0
- package/src/tools/__tests__/ToolSearchRegex.integration.test.ts +161 -0
- package/src/tools/__tests__/ToolSearchRegex.test.ts +232 -0
- package/src/tools/search/jina-reranker.test.ts +16 -16
- package/src/tools/search/schema.ts +7 -9
- package/src/types/graph.ts +7 -1
- package/src/types/tools.ts +166 -0
- package/src/utils/run.ts +5 -1
- package/src/tools/search/direct-url.test.ts +0 -530
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ToolSearchRegex.cjs","sources":["../../../src/tools/ToolSearchRegex.ts"],"sourcesContent":["// src/tools/ToolSearchRegex.ts\nimport { z } from 'zod';\nimport { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { getCodeBaseURL } from './CodeExecutor';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\n/** Maximum allowed regex pattern length */\nconst MAX_PATTERN_LENGTH = 200;\n\n/** Maximum allowed regex nesting depth */\nconst MAX_REGEX_COMPLEXITY = 5;\n\n/** Default search timeout in milliseconds */\nconst SEARCH_TIMEOUT = 5000;\n\nconst ToolSearchRegexSchema = z.object({\n query: z\n .string()\n .min(1)\n .max(MAX_PATTERN_LENGTH)\n .describe(\n 'Regex pattern to search tool names and descriptions. Special regex characters will be sanitized for safety.'\n ),\n fields: z\n .array(z.enum(['name', 'description', 'parameters']))\n .optional()\n .default(['name', 'description'])\n .describe('Which fields to search. Default: name and description'),\n max_results: z\n .number()\n .int()\n .min(1)\n .max(50)\n .optional()\n .default(10)\n .describe('Maximum number of matching tools to return'),\n});\n\n/**\n * Escapes special regex characters in a string to use as a literal pattern.\n * @param pattern - The string to escape\n * @returns The escaped string safe for use in a RegExp\n */\nfunction escapeRegexSpecialChars(pattern: string): string {\n return pattern.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Counts the maximum nesting depth of groups in a regex pattern.\n * @param pattern - The regex pattern to analyze\n * @returns The maximum nesting depth\n */\nfunction countNestedGroups(pattern: string): number {\n let maxDepth = 0;\n let currentDepth = 0;\n\n for (let i = 0; i < pattern.length; i++) {\n if (pattern[i] === '(' && (i === 0 || pattern[i - 1] !== '\\\\')) {\n currentDepth++;\n maxDepth = Math.max(maxDepth, currentDepth);\n } else if (pattern[i] === ')' && (i === 0 || pattern[i - 1] !== '\\\\')) {\n currentDepth = Math.max(0, currentDepth - 1);\n }\n }\n\n return maxDepth;\n}\n\n/**\n * Detects nested quantifiers that can cause catastrophic backtracking.\n * Patterns like (a+)+, (a*)*, (a+)*, etc.\n * @param pattern - The regex pattern to check\n * @returns True if nested quantifiers are detected\n */\nfunction hasNestedQuantifiers(pattern: string): boolean {\n const nestedQuantifierPattern = /\\([^)]*[+*][^)]*\\)[+*?]/;\n return nestedQuantifierPattern.test(pattern);\n}\n\n/**\n * Checks if a regex pattern contains potentially dangerous constructs.\n * @param pattern - The regex pattern to validate\n * @returns True if the pattern is dangerous\n */\nfunction isDangerousPattern(pattern: string): boolean {\n if (hasNestedQuantifiers(pattern)) {\n return true;\n }\n\n if (countNestedGroups(pattern) > MAX_REGEX_COMPLEXITY) {\n return true;\n }\n\n const dangerousPatterns = [\n /\\.\\{1000,\\}/, // Excessive wildcards\n /\\(\\?=\\.\\{100,\\}\\)/, // Runaway lookaheads\n /\\([^)]*\\|\\s*\\){20,}/, // Excessive alternation (rough check)\n /\\(\\.\\*\\)\\+/, // (.*)+\n /\\(\\.\\+\\)\\+/, // (.+)+\n /\\(\\.\\*\\)\\*/, // (.*)*\n /\\(\\.\\+\\)\\*/, // (.+)*\n ];\n\n for (const dangerous of dangerousPatterns) {\n if (dangerous.test(pattern)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Sanitizes a regex pattern for safe execution.\n * If the pattern is dangerous, it will be escaped to a literal string search.\n * @param pattern - The regex pattern to sanitize\n * @returns Object containing the safe pattern and whether it was escaped\n */\nfunction sanitizeRegex(pattern: string): { safe: string; wasEscaped: boolean } {\n if (isDangerousPattern(pattern)) {\n return {\n safe: escapeRegexSpecialChars(pattern),\n wasEscaped: true,\n };\n }\n\n try {\n new RegExp(pattern);\n return { safe: pattern, wasEscaped: false };\n } catch {\n return {\n safe: escapeRegexSpecialChars(pattern),\n wasEscaped: true,\n };\n }\n}\n\n/**\n * Simplifies tool parameters for search purposes.\n * Extracts only the essential structure needed for parameter name searching.\n * @param parameters - The tool's JSON schema parameters\n * @returns Simplified parameters object\n */\nfunction simplifyParametersForSearch(\n parameters?: t.JsonSchemaType\n): t.JsonSchemaType | undefined {\n if (!parameters) {\n return undefined;\n }\n\n if (parameters.properties) {\n return {\n type: parameters.type,\n properties: Object.fromEntries(\n Object.entries(parameters.properties).map(([key, value]) => [\n key,\n { type: (value as t.JsonSchemaType).type },\n ])\n ),\n } as t.JsonSchemaType;\n }\n\n return { type: parameters.type };\n}\n\n/**\n * Generates the JavaScript search script to be executed in the sandbox.\n * Uses plain JavaScript for maximum compatibility with the Code API.\n * @param deferredTools - Array of tool metadata to search through\n * @param fields - Which fields to search\n * @param maxResults - Maximum number of results to return\n * @param sanitizedPattern - The sanitized regex pattern\n * @returns The JavaScript code string\n */\nfunction generateSearchScript(\n deferredTools: t.ToolMetadata[],\n fields: string[],\n maxResults: number,\n sanitizedPattern: string\n): string {\n const lines = [\n '// Tool definitions (injected)',\n 'var tools = ' + JSON.stringify(deferredTools) + ';',\n 'var searchFields = ' + JSON.stringify(fields) + ';',\n 'var maxResults = ' + maxResults + ';',\n 'var pattern = ' + JSON.stringify(sanitizedPattern) + ';',\n '',\n '// Compile regex (pattern is sanitized client-side)',\n 'var regex;',\n 'try {',\n ' regex = new RegExp(pattern, \\'i\\');',\n '} catch (e) {',\n ' regex = new RegExp(pattern.replace(/[.*+?^${}()[\\\\]\\\\\\\\|]/g, \"\\\\\\\\$&\"), \"i\");',\n '}',\n '',\n '// Search logic',\n 'var results = [];',\n '',\n 'for (var j = 0; j < tools.length; j++) {',\n ' var tool = tools[j];',\n ' var bestScore = 0;',\n ' var matchedField = \\'\\';',\n ' var snippet = \\'\\';',\n '',\n ' // Search name (highest priority)',\n ' if (searchFields.indexOf(\\'name\\') >= 0 && regex.test(tool.name)) {',\n ' bestScore = 0.95;',\n ' matchedField = \\'name\\';',\n ' snippet = tool.name;',\n ' }',\n '',\n ' // Search description (medium priority)',\n ' if (searchFields.indexOf(\\'description\\') >= 0 && tool.description && regex.test(tool.description)) {',\n ' if (bestScore === 0) {',\n ' bestScore = 0.75;',\n ' matchedField = \\'description\\';',\n ' snippet = tool.description.substring(0, 100);',\n ' }',\n ' }',\n '',\n ' // Search parameter names (lower priority)',\n ' if (searchFields.indexOf(\\'parameters\\') >= 0 && tool.parameters && tool.parameters.properties) {',\n ' var paramNames = Object.keys(tool.parameters.properties).join(\\' \\');',\n ' if (regex.test(paramNames)) {',\n ' if (bestScore === 0) {',\n ' bestScore = 0.60;',\n ' matchedField = \\'parameters\\';',\n ' snippet = paramNames;',\n ' }',\n ' }',\n ' }',\n '',\n ' if (bestScore > 0) {',\n ' results.push({',\n ' tool_name: tool.name,',\n ' match_score: bestScore,',\n ' matched_field: matchedField,',\n ' snippet: snippet',\n ' });',\n ' }',\n '}',\n '',\n '// Sort by score (descending) and limit results',\n 'results.sort(function(a, b) { return b.match_score - a.match_score; });',\n 'var topResults = results.slice(0, maxResults);',\n '',\n '// Output as JSON',\n 'console.log(JSON.stringify({',\n ' tool_references: topResults.map(function(r) {',\n ' return {',\n ' tool_name: r.tool_name,',\n ' match_score: r.match_score,',\n ' matched_field: r.matched_field,',\n ' snippet: r.snippet',\n ' };',\n ' }),',\n ' total_tools_searched: tools.length,',\n ' pattern_used: pattern',\n '}));',\n ];\n return lines.join('\\n');\n}\n\n/**\n * Parses the search results from stdout JSON.\n * @param stdout - The stdout string containing JSON results\n * @returns Parsed search response\n */\nfunction parseSearchResults(stdout: string): t.ToolSearchResponse {\n const jsonMatch = stdout.trim();\n const parsed = JSON.parse(jsonMatch) as t.ToolSearchResponse;\n return parsed;\n}\n\n/**\n * Formats search results into a human-readable string.\n * @param searchResponse - The parsed search response\n * @returns Formatted string for LLM consumption\n */\nfunction formatSearchResults(searchResponse: t.ToolSearchResponse): string {\n const { tool_references, total_tools_searched, pattern_used } =\n searchResponse;\n\n if (tool_references.length === 0) {\n return `No tools matched the pattern \"${pattern_used}\".\\nTotal tools searched: ${total_tools_searched}`;\n }\n\n let response = `Found ${tool_references.length} matching tools:\\n\\n`;\n\n for (const ref of tool_references) {\n response += `- ${ref.tool_name} (score: ${ref.match_score.toFixed(2)})\\n`;\n response += ` Matched in: ${ref.matched_field}\\n`;\n response += ` Snippet: ${ref.snippet}\\n\\n`;\n }\n\n response += `Total tools searched: ${total_tools_searched}\\n`;\n response += `Pattern used: ${pattern_used}`;\n\n return response;\n}\n\n/**\n * Creates a Tool Search Regex tool for discovering tools from a large registry.\n *\n * This tool enables AI agents to dynamically discover tools from a large library\n * without loading all tool definitions into the LLM context window. The agent\n * can search for relevant tools on-demand using regex patterns.\n *\n * The tool registry can be provided either:\n * 1. At initialization time via params.toolRegistry\n * 2. At runtime via config.configurable.toolRegistry when invoking\n *\n * @param params - Configuration parameters for the tool (toolRegistry is optional)\n * @returns A LangChain DynamicStructuredTool for tool searching\n *\n * @example\n * // Option 1: Registry at initialization\n * const tool = createToolSearchRegexTool({ apiKey, toolRegistry });\n * await tool.invoke({ query: 'expense' });\n *\n * @example\n * // Option 2: Registry at runtime\n * const tool = createToolSearchRegexTool({ apiKey });\n * await tool.invoke(\n * { query: 'expense' },\n * { configurable: { toolRegistry, onlyDeferred: true } }\n * );\n */\nfunction createToolSearchRegexTool(\n initParams: t.ToolSearchRegexParams = {}\n): DynamicStructuredTool<typeof ToolSearchRegexSchema> {\n const apiKey: string =\n (initParams[EnvVar.CODE_API_KEY] as string | undefined) ??\n initParams.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n\n if (!apiKey) {\n throw new Error('No API key provided for tool search regex tool.');\n }\n\n const baseEndpoint = initParams.baseUrl ?? getCodeBaseURL();\n const EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n const defaultOnlyDeferred = initParams.onlyDeferred ?? true;\n\n const description = `\nSearches through available tools to find ones matching your query pattern.\n\nUsage:\n- Provide a regex pattern to search tool names and descriptions.\n- Use this when you need to discover tools for a specific task.\n- Results include tool names, match quality scores, and snippets showing where the match occurred.\n- Higher scores (0.9+) indicate name matches, medium scores (0.7+) indicate description matches.\n`.trim();\n\n return tool<typeof ToolSearchRegexSchema>(\n async (params, config) => {\n const {\n query,\n fields = ['name', 'description'],\n max_results = 10,\n } = params;\n\n // Extra params injected by ToolNode (follows web_search pattern)\n const {\n toolRegistry: paramToolRegistry,\n onlyDeferred: paramOnlyDeferred,\n } = config.toolCall ?? {};\n\n const { safe: sanitizedPattern, wasEscaped } = sanitizeRegex(query);\n\n let warningMessage = '';\n if (wasEscaped) {\n warningMessage =\n 'Note: The provided pattern was converted to a literal search for safety.\\n\\n';\n }\n\n // Priority: ToolNode injection (via config.toolCall) > initialization params\n const toolRegistry = paramToolRegistry ?? initParams.toolRegistry;\n const onlyDeferred =\n paramOnlyDeferred !== undefined\n ? paramOnlyDeferred\n : defaultOnlyDeferred;\n\n if (toolRegistry == null) {\n return [\n `${warningMessage}Error: No tool registry provided. Configure toolRegistry at agent level or initialization.`,\n {\n tool_references: [],\n metadata: {\n total_searched: 0,\n pattern: sanitizedPattern,\n error: 'No tool registry provided',\n },\n },\n ];\n }\n\n const toolsArray: t.LCTool[] = Array.from(toolRegistry.values());\n\n const deferredTools: t.ToolMetadata[] = toolsArray\n .filter((lcTool) => {\n if (onlyDeferred === true) {\n return lcTool.defer_loading === true;\n }\n return true;\n })\n .map((lcTool) => ({\n name: lcTool.name,\n description: lcTool.description ?? '',\n parameters: simplifyParametersForSearch(lcTool.parameters),\n }));\n\n if (deferredTools.length === 0) {\n return [\n `${warningMessage}No tools available to search. The tool registry is empty or no deferred tools are registered.`,\n {\n tool_references: [],\n metadata: {\n total_searched: 0,\n pattern: sanitizedPattern,\n },\n },\n ];\n }\n\n const searchScript = generateSearchScript(\n deferredTools,\n fields,\n max_results,\n sanitizedPattern\n );\n\n const postData = {\n lang: 'js',\n code: searchScript,\n timeout: SEARCH_TIMEOUT,\n };\n\n try {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'Illuma/1.0',\n 'X-API-Key': apiKey,\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const result: t.ExecuteResult = await response.json();\n\n if (result.stderr && result.stderr.trim()) {\n // eslint-disable-next-line no-console\n console.warn('[ToolSearchRegex] stderr:', result.stderr);\n }\n\n if (!result.stdout || !result.stdout.trim()) {\n return [\n `${warningMessage}No tools matched the pattern \"${sanitizedPattern}\".\\nTotal tools searched: ${deferredTools.length}`,\n {\n tool_references: [],\n metadata: {\n total_searched: deferredTools.length,\n pattern: sanitizedPattern,\n },\n },\n ];\n }\n\n const searchResponse = parseSearchResults(result.stdout);\n const formattedOutput = `${warningMessage}${formatSearchResults(searchResponse)}`;\n\n return [\n formattedOutput,\n {\n tool_references: searchResponse.tool_references,\n metadata: {\n total_searched: searchResponse.total_tools_searched,\n pattern: searchResponse.pattern_used,\n },\n },\n ];\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[ToolSearchRegex] Error:', error);\n\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n return [\n `Tool search failed: ${errorMessage}\\n\\nSuggestion: Try a simpler search pattern or search for specific tool names.`,\n {\n tool_references: [],\n metadata: {\n total_searched: 0,\n pattern: sanitizedPattern,\n error: errorMessage,\n },\n },\n ];\n }\n },\n {\n name: Constants.TOOL_SEARCH_REGEX,\n description,\n schema: ToolSearchRegexSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport {\n createToolSearchRegexTool,\n sanitizeRegex,\n escapeRegexSpecialChars,\n isDangerousPattern,\n countNestedGroups,\n hasNestedQuantifiers,\n};\n"],"names":["config","z","EnvVar","getEnvironmentVariable","getCodeBaseURL","tool","HttpsProxyAgent","Constants"],"mappings":";;;;;;;;;;;AAAA;AAWAA,aAAM,EAAE;AAER;AACA,MAAM,kBAAkB,GAAG,GAAG;AAE9B;AACA,MAAM,oBAAoB,GAAG,CAAC;AAE9B;AACA,MAAM,cAAc,GAAG,IAAI;AAE3B,MAAM,qBAAqB,GAAGC,KAAC,CAAC,MAAM,CAAC;AACrC,IAAA,KAAK,EAAEA;AACJ,SAAA,MAAM;SACN,GAAG,CAAC,CAAC;SACL,GAAG,CAAC,kBAAkB;SACtB,QAAQ,CACP,6GAA6G,CAC9G;AACH,IAAA,MAAM,EAAEA;AACL,SAAA,KAAK,CAACA,KAAC,CAA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,wBAAA,OAAO,EAAE,gBAAgB;AACzB,wBAAA,KAAK,EAAE,YAAY;AACpB,qBAAA;AACF,iBAAA;aACF;;AAEL,KAAC,EACD;QACE,IAAI,EAAEC,eAAS,CAAC,iBAAiB;QACjC,WAAW;AACX,QAAA,MAAM,EAAE,qBAAqB;QAC7B,cAAc,EAAEA,eAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;;;;;;"}
|
|
@@ -11,17 +11,10 @@ exports.DATE_RANGE = void 0;
|
|
|
11
11
|
DATE_RANGE["PAST_YEAR"] = "y";
|
|
12
12
|
})(exports.DATE_RANGE || (exports.DATE_RANGE = {}));
|
|
13
13
|
const DEFAULT_QUERY_DESCRIPTION = `
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
**IMPORTANT - URL REQUESTS:**
|
|
17
|
-
If the user provides a URL to read, summarize, or analyze, you MUST include the complete URL in this field.
|
|
18
|
-
- User says: "Summarize https://example.com/article" → query: "https://example.com/article"
|
|
19
|
-
- User says: "What does this page say? https://news.site/story" → query: "https://news.site/story"
|
|
20
|
-
DO NOT convert URLs into search keywords. Pass the URL directly.
|
|
21
|
-
|
|
22
|
-
**SEARCH MODE GUIDELINES:**
|
|
14
|
+
GUIDELINES:
|
|
23
15
|
- Start broad, then narrow: Begin with key concepts, then refine with specifics
|
|
24
16
|
- Think like sources: Use terminology experts would use in the field
|
|
17
|
+
- Consider perspective: Frame queries from different viewpoints for better results
|
|
25
18
|
- Quality over quantity: A precise 3-4 word query often beats lengthy sentences
|
|
26
19
|
|
|
27
20
|
TECHNIQUES (combine for power searches):
|
|
@@ -30,6 +23,11 @@ TECHNIQUES (combine for power searches):
|
|
|
30
23
|
- SITE-SPECIFIC: Restrict to websites (site:edu research)
|
|
31
24
|
- FILETYPE: Find specific documents (filetype:pdf study)
|
|
32
25
|
- OR OPERATOR: Find alternatives (electric OR hybrid cars)
|
|
26
|
+
- DATE RANGE: Recent information (data after:2020)
|
|
27
|
+
- WILDCARDS: Use * for unknown terms (how to * bread)
|
|
28
|
+
- SPECIFIC QUESTIONS: Use who/what/when/where/why/how
|
|
29
|
+
- DOMAIN TERMS: Include technical terminology for specialized topics
|
|
30
|
+
- CONCISE TERMS: Prioritize keywords over sentences
|
|
33
31
|
`.trim();
|
|
34
32
|
const DEFAULT_COUNTRY_DESCRIPTION = `Country code to localize search results.
|
|
35
33
|
Use standard 2-letter country codes: "us", "uk", "ca", "de", "fr", "jp", "br", etc.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.cjs","sources":["../../../../src/tools/search/schema.ts"],"sourcesContent":["import { z } from 'zod';\n\nexport enum DATE_RANGE {\n PAST_HOUR = 'h',\n PAST_24_HOURS = 'd',\n PAST_WEEK = 'w',\n PAST_MONTH = 'm',\n PAST_YEAR = 'y',\n}\n\nexport const DEFAULT_QUERY_DESCRIPTION = `\
|
|
1
|
+
{"version":3,"file":"schema.cjs","sources":["../../../../src/tools/search/schema.ts"],"sourcesContent":["import { z } from 'zod';\n\nexport enum DATE_RANGE {\n PAST_HOUR = 'h',\n PAST_24_HOURS = 'd',\n PAST_WEEK = 'w',\n PAST_MONTH = 'm',\n PAST_YEAR = 'y',\n}\n\nexport const DEFAULT_QUERY_DESCRIPTION = `\nGUIDELINES:\n- Start broad, then narrow: Begin with key concepts, then refine with specifics\n- Think like sources: Use terminology experts would use in the field\n- Consider perspective: Frame queries from different viewpoints for better results\n- Quality over quantity: A precise 3-4 word query often beats lengthy sentences\n\nTECHNIQUES (combine for power searches):\n- EXACT PHRASES: Use quotes (\"climate change report\")\n- EXCLUDE TERMS: Use minus to remove unwanted results (-wikipedia)\n- SITE-SPECIFIC: Restrict to websites (site:edu research)\n- FILETYPE: Find specific documents (filetype:pdf study)\n- OR OPERATOR: Find alternatives (electric OR hybrid cars)\n- DATE RANGE: Recent information (data after:2020)\n- WILDCARDS: Use * for unknown terms (how to * bread)\n- SPECIFIC QUESTIONS: Use who/what/when/where/why/how\n- DOMAIN TERMS: Include technical terminology for specialized topics\n- CONCISE TERMS: Prioritize keywords over sentences\n`.trim();\n\nexport const DEFAULT_COUNTRY_DESCRIPTION =\n `Country code to localize search results.\nUse standard 2-letter country codes: \"us\", \"uk\", \"ca\", \"de\", \"fr\", \"jp\", \"br\", etc.\nProvide this when the search should return results specific to a particular country.\nExamples:\n- \"us\" for United States (default)\n- \"de\" for Germany\n- \"in\" for India\n`.trim();\n\nexport const querySchema = z.string().describe(DEFAULT_QUERY_DESCRIPTION);\nexport const dateSchema = z\n .nativeEnum(DATE_RANGE)\n .optional()\n .describe('Date range for search results.');\nexport const countrySchema = z\n .string()\n .optional()\n .describe(DEFAULT_COUNTRY_DESCRIPTION);\nexport const imagesSchema = z\n .boolean()\n .optional()\n .describe('Whether to also run an image search.');\n\nexport const videosSchema = z\n .boolean()\n .optional()\n .describe('Whether to also run a video search.');\n\nexport const newsSchema = z\n .boolean()\n .optional()\n .describe('Whether to also run a news search.');\n"],"names":["DATE_RANGE","z"],"mappings":";;;;AAEYA;AAAZ,CAAA,UAAY,UAAU,EAAA;AACpB,IAAA,UAAA,CAAA,WAAA,CAAA,GAAA,GAAe;AACf,IAAA,UAAA,CAAA,eAAA,CAAA,GAAA,GAAmB;AACnB,IAAA,UAAA,CAAA,WAAA,CAAA,GAAA,GAAe;AACf,IAAA,UAAA,CAAA,YAAA,CAAA,GAAA,GAAgB;AAChB,IAAA,UAAA,CAAA,WAAA,CAAA,GAAA,GAAe;AACjB,CAAC,EANWA,kBAAU,KAAVA,kBAAU,GAMrB,EAAA,CAAA,CAAA;AAEY,MAAA,yBAAyB,GAAG;;;;;;;;;;;;;;;;;;CAkBxC,CAAC,IAAI;AAEO,MAAA,2BAA2B,GACtC,CAAA;;;;;;;CAOD,CAAC,IAAI;AAEC,MAAM,WAAW,GAAGC,KAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,yBAAyB;AACjE,MAAM,UAAU,GAAGA;KACvB,UAAU,CAACD,kBAAU;AACrB,KAAA,QAAQ;KACR,QAAQ,CAAC,gCAAgC;AACrC,MAAM,aAAa,GAAGC;AAC1B,KAAA,MAAM;AACN,KAAA,QAAQ;KACR,QAAQ,CAAC,2BAA2B;AAChC,MAAM,YAAY,GAAGA;AACzB,KAAA,OAAO;AACP,KAAA,QAAQ;KACR,QAAQ,CAAC,sCAAsC;AAE3C,MAAM,YAAY,GAAGA;AACzB,KAAA,OAAO;AACP,KAAA,QAAQ;KACR,QAAQ,CAAC,qCAAqC;AAE1C,MAAM,UAAU,GAAGA;AACvB,KAAA,OAAO;AACP,KAAA,QAAQ;KACR,QAAQ,CAAC,oCAAoC;;;;;;;;;;;"}
|
package/dist/cjs/utils/run.cjs
CHANGED
|
@@ -30,8 +30,12 @@ class RunnableCallable extends runnables.Runnable {
|
|
|
30
30
|
}
|
|
31
31
|
async _tracedInvoke(input, config, runManager) {
|
|
32
32
|
return new Promise((resolve, reject) => {
|
|
33
|
+
// Defensive check: ensure runManager has getChild method before calling
|
|
34
|
+
const childCallbacks = typeof runManager?.getChild === 'function'
|
|
35
|
+
? runManager.getChild()
|
|
36
|
+
: undefined;
|
|
33
37
|
const childConfig = runnables.patchConfig(config, {
|
|
34
|
-
callbacks:
|
|
38
|
+
callbacks: childCallbacks,
|
|
35
39
|
});
|
|
36
40
|
void singletons.AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => {
|
|
37
41
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.cjs","sources":["../../../src/utils/run.ts"],"sourcesContent":["import { CallbackManagerForChainRun } from '@langchain/core/callbacks/manager';\nimport {\n mergeConfigs,\n patchConfig,\n Runnable,\n RunnableConfig,\n} from '@langchain/core/runnables';\nimport { AsyncLocalStorageProviderSingleton } from '@langchain/core/singletons';\n\n/**\n * Delays the execution for a specified number of milliseconds.\n *\n * @param {number} ms - The number of milliseconds to delay.\n * @return {Promise<void>} A promise that resolves after the specified delay.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface RunnableCallableArgs extends Partial<any> {\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n func: (...args: any[]) => any;\n tags?: string[];\n trace?: boolean;\n recurse?: boolean;\n}\n\nexport class RunnableCallable<I = unknown, O = unknown> extends Runnable<I, O> {\n lc_namespace: string[] = ['langgraph'];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n func: (...args: any[]) => any;\n\n tags?: string[];\n\n config?: RunnableConfig;\n\n trace: boolean = true;\n\n recurse: boolean = true;\n\n constructor(fields: RunnableCallableArgs) {\n super();\n this.name = fields.name ?? fields.func.name;\n this.func = fields.func;\n this.config = fields.tags ? { tags: fields.tags } : undefined;\n this.trace = fields.trace ?? this.trace;\n this.recurse = fields.recurse ?? this.recurse;\n }\n\n protected async _tracedInvoke(\n input: I,\n config?: Partial<RunnableConfig>,\n runManager?: CallbackManagerForChainRun\n ): Promise<O> {\n return new Promise<O>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks:
|
|
1
|
+
{"version":3,"file":"run.cjs","sources":["../../../src/utils/run.ts"],"sourcesContent":["import { CallbackManagerForChainRun } from '@langchain/core/callbacks/manager';\nimport {\n mergeConfigs,\n patchConfig,\n Runnable,\n RunnableConfig,\n} from '@langchain/core/runnables';\nimport { AsyncLocalStorageProviderSingleton } from '@langchain/core/singletons';\n\n/**\n * Delays the execution for a specified number of milliseconds.\n *\n * @param {number} ms - The number of milliseconds to delay.\n * @return {Promise<void>} A promise that resolves after the specified delay.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface RunnableCallableArgs extends Partial<any> {\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n func: (...args: any[]) => any;\n tags?: string[];\n trace?: boolean;\n recurse?: boolean;\n}\n\nexport class RunnableCallable<I = unknown, O = unknown> extends Runnable<I, O> {\n lc_namespace: string[] = ['langgraph'];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n func: (...args: any[]) => any;\n\n tags?: string[];\n\n config?: RunnableConfig;\n\n trace: boolean = true;\n\n recurse: boolean = true;\n\n constructor(fields: RunnableCallableArgs) {\n super();\n this.name = fields.name ?? fields.func.name;\n this.func = fields.func;\n this.config = fields.tags ? { tags: fields.tags } : undefined;\n this.trace = fields.trace ?? this.trace;\n this.recurse = fields.recurse ?? this.recurse;\n }\n\n protected async _tracedInvoke(\n input: I,\n config?: Partial<RunnableConfig>,\n runManager?: CallbackManagerForChainRun\n ): Promise<O> {\n return new Promise<O>((resolve, reject) => {\n // Defensive check: ensure runManager has getChild method before calling\n const childCallbacks = typeof runManager?.getChild === 'function' \n ? runManager.getChild() \n : undefined;\n const childConfig = patchConfig(config, {\n callbacks: childCallbacks,\n });\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n childConfig,\n async () => {\n try {\n const output = await this.func(input, childConfig);\n resolve(output);\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n }\n\n async invoke(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any,\n options?: Partial<RunnableConfig> | undefined\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let returnValue: any;\n\n if (this.trace) {\n returnValue = await this._callWithConfig(\n this._tracedInvoke,\n input,\n mergeConfigs(this.config, options)\n );\n } else {\n returnValue = await this.func(input, mergeConfigs(this.config, options));\n }\n\n if (Runnable.isRunnable(returnValue) && this.recurse) {\n return await returnValue.invoke(input, options);\n }\n\n return returnValue;\n }\n}"],"names":["Runnable","patchConfig","AsyncLocalStorageProviderSingleton","mergeConfigs"],"mappings":";;;;;AASA;;;;;AAKG;AACG,SAAU,KAAK,CAAC,EAAU,EAAA;AAC9B,IAAA,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,KAAK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;;gBACf,OAAO,CAAC,EAAE;oBACV,MAAM,CAAC,CAAC,CAAC;;AAEb,aAAC,CACF;AACH,SAAC,CAAC;;AAGJ,IAAA,MAAM,MAAM;;AAEV,IAAA,KAAU,EACV;;;;AAIA,QAAA,IAAI,WAAgB;AAEpB,QAAA,IAAI,IAAI,CAAC,KAAK,EAAE;YACd,WAAW,GAAG,MAAM,IAAI,CAAC,eAAe,CACtC,IAAI,CAAC,aAAa,EAClB,KAAK,EACLC,sBAAY,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CACnC;;aACI;AACL,YAAA,WAAW,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,EAAEA,sBAAY,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;;QAG1E,IAAIH,kBAAQ,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE;YACpD,OAAO,MAAM,WAAW,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC;;AAGjD,QAAA,OAAO,WAAW;;AAErB;;;;;"}
|
|
@@ -13,7 +13,7 @@ class AgentContext {
|
|
|
13
13
|
* Create an AgentContext from configuration with token accounting initialization
|
|
14
14
|
*/
|
|
15
15
|
static fromConfig(agentConfig, tokenCounter, indexTokenCountMap) {
|
|
16
|
-
const { agentId, provider, clientOptions, tools, toolMap, toolEnd, instructions, additional_instructions, streamBuffer, maxContextTokens, reasoningKey, useLegacyContent, } = agentConfig;
|
|
16
|
+
const { agentId, provider, clientOptions, tools, toolMap, toolEnd, toolRegistry, instructions, additional_instructions, streamBuffer, maxContextTokens, reasoningKey, useLegacyContent, } = agentConfig;
|
|
17
17
|
const agentContext = new AgentContext({
|
|
18
18
|
agentId,
|
|
19
19
|
provider,
|
|
@@ -22,6 +22,7 @@ class AgentContext {
|
|
|
22
22
|
streamBuffer,
|
|
23
23
|
tools,
|
|
24
24
|
toolMap,
|
|
25
|
+
toolRegistry,
|
|
25
26
|
instructions,
|
|
26
27
|
additionalInstructions: additional_instructions,
|
|
27
28
|
reasoningKey,
|
|
@@ -31,12 +32,16 @@ class AgentContext {
|
|
|
31
32
|
useLegacyContent,
|
|
32
33
|
});
|
|
33
34
|
if (tokenCounter) {
|
|
35
|
+
// Initialize system runnable BEFORE async tool token calculation
|
|
36
|
+
// This ensures system message tokens are in instructionTokens before
|
|
37
|
+
// updateTokenMapWithInstructions is called
|
|
38
|
+
agentContext.initializeSystemRunnable();
|
|
34
39
|
const tokenMap = indexTokenCountMap || {};
|
|
35
40
|
agentContext.indexTokenCountMap = tokenMap;
|
|
36
41
|
agentContext.tokenCalculationPromise = agentContext
|
|
37
42
|
.calculateInstructionTokens(tokenCounter)
|
|
38
43
|
.then(() => {
|
|
39
|
-
// Update token map with instruction tokens
|
|
44
|
+
// Update token map with instruction tokens (includes system + tool tokens)
|
|
40
45
|
agentContext.updateTokenMapWithInstructions(tokenMap);
|
|
41
46
|
})
|
|
42
47
|
.catch((err) => {
|
|
@@ -74,6 +79,13 @@ class AgentContext {
|
|
|
74
79
|
tools;
|
|
75
80
|
/** Tool map for this agent */
|
|
76
81
|
toolMap;
|
|
82
|
+
/**
|
|
83
|
+
* Tool definitions registry (includes deferred and programmatic tool metadata).
|
|
84
|
+
* Used for tool search and programmatic tool calling.
|
|
85
|
+
*/
|
|
86
|
+
toolRegistry;
|
|
87
|
+
/** Set of tool names discovered via tool search (to be loaded) */
|
|
88
|
+
discoveredToolNames = new Set();
|
|
77
89
|
/** Instructions for this agent */
|
|
78
90
|
instructions;
|
|
79
91
|
/** Additional instructions for this agent */
|
|
@@ -88,13 +100,17 @@ class AgentContext {
|
|
|
88
100
|
currentTokenType = ContentTypes.TEXT;
|
|
89
101
|
/** Whether tools should end the workflow */
|
|
90
102
|
toolEnd = false;
|
|
91
|
-
/**
|
|
92
|
-
|
|
103
|
+
/** Cached system runnable (created lazily) */
|
|
104
|
+
cachedSystemRunnable;
|
|
105
|
+
/** Whether system runnable needs rebuild (set when discovered tools change) */
|
|
106
|
+
systemRunnableStale = true;
|
|
107
|
+
/** Cached system message token count (separate from tool tokens) */
|
|
108
|
+
systemMessageTokens = 0;
|
|
93
109
|
/** Promise for token calculation initialization */
|
|
94
110
|
tokenCalculationPromise;
|
|
95
111
|
/** Format content blocks as strings (for legacy compatibility) */
|
|
96
112
|
useLegacyContent = false;
|
|
97
|
-
constructor({ agentId, provider, clientOptions, maxContextTokens, streamBuffer, tokenCounter, tools, toolMap, instructions, additionalInstructions, reasoningKey, toolEnd, instructionTokens, useLegacyContent, }) {
|
|
113
|
+
constructor({ agentId, provider, clientOptions, maxContextTokens, streamBuffer, tokenCounter, tools, toolMap, toolRegistry, instructions, additionalInstructions, reasoningKey, toolEnd, instructionTokens, useLegacyContent, }) {
|
|
98
114
|
this.agentId = agentId;
|
|
99
115
|
this.provider = provider;
|
|
100
116
|
this.clientOptions = clientOptions;
|
|
@@ -103,6 +119,7 @@ class AgentContext {
|
|
|
103
119
|
this.tokenCounter = tokenCounter;
|
|
104
120
|
this.tools = tools;
|
|
105
121
|
this.toolMap = toolMap;
|
|
122
|
+
this.toolRegistry = toolRegistry;
|
|
106
123
|
this.instructions = instructions;
|
|
107
124
|
this.additionalInstructions = additionalInstructions;
|
|
108
125
|
if (reasoningKey) {
|
|
@@ -115,24 +132,112 @@ class AgentContext {
|
|
|
115
132
|
this.instructionTokens = instructionTokens;
|
|
116
133
|
}
|
|
117
134
|
this.useLegacyContent = useLegacyContent ?? false;
|
|
118
|
-
this.systemRunnable = this.createSystemRunnable();
|
|
119
135
|
}
|
|
120
136
|
/**
|
|
121
|
-
*
|
|
137
|
+
* Builds instructions text for tools that are ONLY callable via programmatic code execution.
|
|
138
|
+
* These tools cannot be called directly by the LLM but are available through the
|
|
139
|
+
* run_tools_with_code tool.
|
|
140
|
+
*
|
|
141
|
+
* Includes:
|
|
142
|
+
* - Code_execution-only tools that are NOT deferred
|
|
143
|
+
* - Code_execution-only tools that ARE deferred but have been discovered via tool search
|
|
144
|
+
*/
|
|
145
|
+
buildProgrammaticOnlyToolsInstructions() {
|
|
146
|
+
if (!this.toolRegistry)
|
|
147
|
+
return '';
|
|
148
|
+
const programmaticOnlyTools = [];
|
|
149
|
+
for (const [name, toolDef] of this.toolRegistry) {
|
|
150
|
+
const allowedCallers = toolDef.allowed_callers ?? ['direct'];
|
|
151
|
+
const isCodeExecutionOnly = allowedCallers.includes('code_execution') &&
|
|
152
|
+
!allowedCallers.includes('direct');
|
|
153
|
+
if (!isCodeExecutionOnly)
|
|
154
|
+
continue;
|
|
155
|
+
// Include if: not deferred OR deferred but discovered
|
|
156
|
+
const isDeferred = toolDef.defer_loading === true;
|
|
157
|
+
const isDiscovered = this.discoveredToolNames.has(name);
|
|
158
|
+
if (!isDeferred || isDiscovered) {
|
|
159
|
+
programmaticOnlyTools.push(toolDef);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (programmaticOnlyTools.length === 0)
|
|
163
|
+
return '';
|
|
164
|
+
const toolDescriptions = programmaticOnlyTools
|
|
165
|
+
.map((tool) => {
|
|
166
|
+
let desc = `- **${tool.name}**`;
|
|
167
|
+
if (tool.description != null && tool.description !== '') {
|
|
168
|
+
desc += `: ${tool.description}`;
|
|
169
|
+
}
|
|
170
|
+
if (tool.parameters) {
|
|
171
|
+
desc += `\n Parameters: ${JSON.stringify(tool.parameters, null, 2).replace(/\n/g, '\n ')}`;
|
|
172
|
+
}
|
|
173
|
+
return desc;
|
|
174
|
+
})
|
|
175
|
+
.join('\n\n');
|
|
176
|
+
return ('\n\n## Programmatic-Only Tools\n\n' +
|
|
177
|
+
'The following tools are available exclusively through the `run_tools_with_code` tool. ' +
|
|
178
|
+
'You cannot call these tools directly; instead, use `run_tools_with_code` with Python code that invokes them.\n\n' +
|
|
179
|
+
toolDescriptions);
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Gets the system runnable, creating it lazily if needed.
|
|
183
|
+
* Includes instructions, additional instructions, and programmatic-only tools documentation.
|
|
184
|
+
* Only rebuilds when marked stale (via markToolsAsDiscovered).
|
|
122
185
|
*/
|
|
123
|
-
|
|
124
|
-
|
|
186
|
+
get systemRunnable() {
|
|
187
|
+
// Return cached if not stale
|
|
188
|
+
if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {
|
|
189
|
+
return this.cachedSystemRunnable;
|
|
190
|
+
}
|
|
191
|
+
// Stale or first access - rebuild
|
|
192
|
+
const instructionsString = this.buildInstructionsString();
|
|
193
|
+
this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);
|
|
194
|
+
this.systemRunnableStale = false;
|
|
195
|
+
return this.cachedSystemRunnable;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Explicitly initializes the system runnable.
|
|
199
|
+
* Call this before async token calculation to ensure system message tokens are counted first.
|
|
200
|
+
*/
|
|
201
|
+
initializeSystemRunnable() {
|
|
202
|
+
if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {
|
|
203
|
+
const instructionsString = this.buildInstructionsString();
|
|
204
|
+
this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);
|
|
205
|
+
this.systemRunnableStale = false;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Builds the raw instructions string (without creating SystemMessage).
|
|
210
|
+
*/
|
|
211
|
+
buildInstructionsString() {
|
|
212
|
+
let result = this.instructions ?? '';
|
|
125
213
|
if (this.additionalInstructions != null &&
|
|
126
214
|
this.additionalInstructions !== '') {
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
215
|
+
result = result
|
|
216
|
+
? `${result}\n\n${this.additionalInstructions}`
|
|
217
|
+
: this.additionalInstructions;
|
|
218
|
+
}
|
|
219
|
+
const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();
|
|
220
|
+
if (programmaticToolsDoc) {
|
|
221
|
+
result = result
|
|
222
|
+
? `${result}${programmaticToolsDoc}`
|
|
223
|
+
: programmaticToolsDoc;
|
|
224
|
+
}
|
|
225
|
+
return result;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Build system runnable from pre-built instructions string.
|
|
229
|
+
* Only called when content has actually changed.
|
|
230
|
+
*/
|
|
231
|
+
buildSystemRunnable(instructionsString) {
|
|
232
|
+
if (!instructionsString) {
|
|
233
|
+
// Remove previous tokens if we had a system message before
|
|
234
|
+
this.instructionTokens -= this.systemMessageTokens;
|
|
235
|
+
this.systemMessageTokens = 0;
|
|
236
|
+
return undefined;
|
|
237
|
+
}
|
|
238
|
+
let finalInstructions = instructionsString;
|
|
239
|
+
// Handle Anthropic prompt caching (Direct API)
|
|
240
|
+
if (this.provider === Providers.ANTHROPIC) {
|
|
136
241
|
const anthropicOptions = this.clientOptions;
|
|
137
242
|
const defaultHeaders = anthropicOptions?.clientOptions?.defaultHeaders;
|
|
138
243
|
const anthropicBeta = defaultHeaders?.['anthropic-beta'];
|
|
@@ -142,29 +247,56 @@ class AgentContext {
|
|
|
142
247
|
content: [
|
|
143
248
|
{
|
|
144
249
|
type: 'text',
|
|
145
|
-
text:
|
|
250
|
+
text: instructionsString,
|
|
146
251
|
cache_control: { type: 'ephemeral' },
|
|
147
252
|
},
|
|
148
253
|
],
|
|
149
254
|
};
|
|
150
255
|
}
|
|
151
256
|
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
257
|
+
// Handle Bedrock prompt caching (Converse API)
|
|
258
|
+
// Adds cachePoint block after text content for system message caching
|
|
259
|
+
// NOTE: Both Claude and Nova models support cachePoint in system and messages
|
|
260
|
+
// (Nova does NOT support cachePoint in tools - that check is in bedrock/index.ts)
|
|
261
|
+
if (this.provider === Providers.BEDROCK) {
|
|
262
|
+
const bedrockOptions = this.clientOptions;
|
|
263
|
+
const modelId = bedrockOptions?.model?.toLowerCase() ?? '';
|
|
264
|
+
const supportsCaching = modelId.includes('claude') || modelId.includes('anthropic') || modelId.includes('nova');
|
|
265
|
+
if (bedrockOptions?.promptCache === true && supportsCaching) {
|
|
266
|
+
// Always log system cache structure
|
|
267
|
+
console.log(`[Cache] 📝 System | chars=${instructionsString.length} | tokens=${this.systemMessageTokens} | model=${modelId}`);
|
|
268
|
+
finalInstructions = {
|
|
269
|
+
content: [
|
|
270
|
+
{
|
|
271
|
+
type: 'text',
|
|
272
|
+
text: instructionsString,
|
|
273
|
+
},
|
|
274
|
+
{
|
|
275
|
+
cachePoint: { type: 'default' },
|
|
276
|
+
},
|
|
277
|
+
],
|
|
278
|
+
};
|
|
156
279
|
}
|
|
157
|
-
return RunnableLambda.from((messages) => {
|
|
158
|
-
return [systemMessage, ...messages];
|
|
159
|
-
}).withConfig({ runName: 'prompt' });
|
|
160
280
|
}
|
|
161
|
-
|
|
281
|
+
const systemMessage = new SystemMessage(finalInstructions);
|
|
282
|
+
// Update token counts (subtract old, add new)
|
|
283
|
+
if (this.tokenCounter) {
|
|
284
|
+
this.instructionTokens -= this.systemMessageTokens;
|
|
285
|
+
this.systemMessageTokens = this.tokenCounter(systemMessage);
|
|
286
|
+
this.instructionTokens += this.systemMessageTokens;
|
|
287
|
+
}
|
|
288
|
+
return RunnableLambda.from((messages) => {
|
|
289
|
+
return [systemMessage, ...messages];
|
|
290
|
+
}).withConfig({ runName: 'prompt' });
|
|
162
291
|
}
|
|
163
292
|
/**
|
|
164
293
|
* Reset context for a new run
|
|
165
294
|
*/
|
|
166
295
|
reset() {
|
|
167
296
|
this.instructionTokens = 0;
|
|
297
|
+
this.systemMessageTokens = 0;
|
|
298
|
+
this.cachedSystemRunnable = undefined;
|
|
299
|
+
this.systemRunnableStale = true;
|
|
168
300
|
this.lastToken = undefined;
|
|
169
301
|
this.indexTokenCountMap = {};
|
|
170
302
|
this.currentUsage = undefined;
|
|
@@ -172,6 +304,7 @@ class AgentContext {
|
|
|
172
304
|
this.lastStreamCall = undefined;
|
|
173
305
|
this.tokenTypeSwitch = undefined;
|
|
174
306
|
this.currentTokenType = ContentTypes.TEXT;
|
|
307
|
+
this.discoveredToolNames.clear();
|
|
175
308
|
}
|
|
176
309
|
/**
|
|
177
310
|
* Update the token count map with instruction tokens
|
|
@@ -214,6 +347,74 @@ class AgentContext {
|
|
|
214
347
|
// Add tool tokens to existing instruction tokens (which may already include system message tokens)
|
|
215
348
|
this.instructionTokens += toolTokens;
|
|
216
349
|
}
|
|
350
|
+
/**
|
|
351
|
+
* Gets the tool registry for deferred tools (for tool search).
|
|
352
|
+
* @param onlyDeferred If true, only returns tools with defer_loading=true
|
|
353
|
+
* @returns LCToolRegistry with tool definitions
|
|
354
|
+
*/
|
|
355
|
+
getDeferredToolRegistry(onlyDeferred = true) {
|
|
356
|
+
const registry = new Map();
|
|
357
|
+
if (!this.toolRegistry) {
|
|
358
|
+
return registry;
|
|
359
|
+
}
|
|
360
|
+
for (const [name, toolDef] of this.toolRegistry) {
|
|
361
|
+
if (!onlyDeferred || toolDef.defer_loading === true) {
|
|
362
|
+
registry.set(name, toolDef);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
return registry;
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Marks tools as discovered via tool search.
|
|
369
|
+
* Discovered tools will be included in the next model binding.
|
|
370
|
+
* Only marks system runnable stale if NEW tools were actually added.
|
|
371
|
+
* @param toolNames - Array of discovered tool names
|
|
372
|
+
* @returns true if any new tools were discovered
|
|
373
|
+
*/
|
|
374
|
+
markToolsAsDiscovered(toolNames) {
|
|
375
|
+
let hasNewDiscoveries = false;
|
|
376
|
+
for (const name of toolNames) {
|
|
377
|
+
if (!this.discoveredToolNames.has(name)) {
|
|
378
|
+
this.discoveredToolNames.add(name);
|
|
379
|
+
hasNewDiscoveries = true;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
if (hasNewDiscoveries) {
|
|
383
|
+
this.systemRunnableStale = true;
|
|
384
|
+
}
|
|
385
|
+
return hasNewDiscoveries;
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Gets tools that should be bound to the LLM.
|
|
389
|
+
* Includes:
|
|
390
|
+
* 1. Non-deferred tools with allowed_callers: ['direct']
|
|
391
|
+
* 2. Discovered tools (from tool search)
|
|
392
|
+
* @returns Array of tools to bind to model
|
|
393
|
+
*/
|
|
394
|
+
getToolsForBinding() {
|
|
395
|
+
if (!this.tools || !this.toolRegistry) {
|
|
396
|
+
return this.tools;
|
|
397
|
+
}
|
|
398
|
+
const toolsToInclude = this.tools.filter((tool) => {
|
|
399
|
+
if (!('name' in tool)) {
|
|
400
|
+
return true; // No name, include by default
|
|
401
|
+
}
|
|
402
|
+
const toolDef = this.toolRegistry?.get(tool.name);
|
|
403
|
+
if (!toolDef) {
|
|
404
|
+
return true; // Not in registry, include by default
|
|
405
|
+
}
|
|
406
|
+
// Check if discovered (overrides defer_loading)
|
|
407
|
+
if (this.discoveredToolNames.has(tool.name)) {
|
|
408
|
+
// Discovered tools must still have allowed_callers: ['direct']
|
|
409
|
+
const allowedCallers = toolDef.allowed_callers ?? ['direct'];
|
|
410
|
+
return allowedCallers.includes('direct');
|
|
411
|
+
}
|
|
412
|
+
// Not discovered: must be direct-callable AND not deferred
|
|
413
|
+
const allowedCallers = toolDef.allowed_callers ?? ['direct'];
|
|
414
|
+
return (allowedCallers.includes('direct') && toolDef.defer_loading !== true);
|
|
415
|
+
});
|
|
416
|
+
return toolsToInclude;
|
|
417
|
+
}
|
|
217
418
|
}
|
|
218
419
|
|
|
219
420
|
export { AgentContext };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentContext.mjs","sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/agents/AgentContext.ts\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { SystemMessage } from '@langchain/core/messages';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type {\n UsageMetadata,\n BaseMessage,\n BaseMessageFields,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport type { createPruneMessages } from '@/messages';\nimport { ContentTypes, Providers } from '@/common';\n\n/**\n * Encapsulates agent-specific state that can vary between agents in a multi-agent system\n */\nexport class AgentContext {\n /**\n * Create an AgentContext from configuration with token accounting initialization\n */\n static fromConfig(\n agentConfig: t.AgentInputs,\n tokenCounter?: t.TokenCounter,\n indexTokenCountMap?: Record<string, number>\n ): AgentContext {\n const {\n agentId,\n provider,\n clientOptions,\n tools,\n toolMap,\n toolEnd,\n instructions,\n additional_instructions,\n streamBuffer,\n maxContextTokens,\n reasoningKey,\n useLegacyContent,\n } = agentConfig;\n\n const agentContext = new AgentContext({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tools,\n toolMap,\n instructions,\n additionalInstructions: additional_instructions,\n reasoningKey,\n toolEnd,\n instructionTokens: 0,\n tokenCounter,\n useLegacyContent,\n });\n\n if (tokenCounter) {\n const tokenMap = indexTokenCountMap || {};\n agentContext.indexTokenCountMap = tokenMap;\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n // Update token map with instruction tokens\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n } else if (indexTokenCountMap) {\n agentContext.indexTokenCountMap = indexTokenCountMap;\n }\n\n return agentContext;\n }\n\n /** Agent identifier */\n agentId: string;\n /** Provider for this specific agent */\n provider: Providers;\n /** Client options for this agent */\n clientOptions?: t.ClientOptions;\n /** Token count map indexed by message position */\n indexTokenCountMap: Record<string, number | undefined> = {};\n /** Maximum context tokens for this agent */\n maxContextTokens?: number;\n /** Current usage metadata for this agent */\n currentUsage?: Partial<UsageMetadata>;\n /** Prune messages function configured for this agent */\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** Token counter function for this agent */\n tokenCounter?: t.TokenCounter;\n /** Instructions/system message token count */\n instructionTokens: number = 0;\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer?: number;\n /** Last stream call timestamp for rate limiting */\n lastStreamCall?: number;\n /** Tools available to this agent */\n tools?: t.GraphTools;\n /** Tool map for this agent */\n toolMap?: t.ToolMap;\n /** Instructions for this agent */\n instructions?: string;\n /** Additional instructions for this agent */\n additionalInstructions?: string;\n /** Reasoning key for this agent */\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n /** Last token for reasoning detection */\n lastToken?: string;\n /** Token type switch state */\n tokenTypeSwitch?: 'reasoning' | 'content';\n /** Current token type being processed */\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK | 'think_and_text' =\n ContentTypes.TEXT;\n /** Whether tools should end the workflow */\n toolEnd: boolean = false;\n /** System runnable for this agent */\n systemRunnable?: Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >;\n /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n\n constructor({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n instructions,\n additionalInstructions,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n }: {\n agentId: string;\n provider: Providers;\n clientOptions?: t.ClientOptions;\n maxContextTokens?: number;\n streamBuffer?: number;\n tokenCounter?: t.TokenCounter;\n tools?: t.GraphTools;\n toolMap?: t.ToolMap;\n instructions?: string;\n additionalInstructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n }) {\n this.agentId = agentId;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.maxContextTokens = maxContextTokens;\n this.streamBuffer = streamBuffer;\n this.tokenCounter = tokenCounter;\n this.tools = tools;\n this.toolMap = toolMap;\n this.instructions = instructions;\n this.additionalInstructions = additionalInstructions;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.instructionTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n\n this.systemRunnable = this.createSystemRunnable();\n }\n\n /**\n * Create system runnable from instructions and calculate tokens if tokenCounter is available\n */\n private createSystemRunnable():\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n let finalInstructions: string | BaseMessageFields | undefined =\n this.instructions;\n\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n finalInstructions =\n finalInstructions != null && finalInstructions\n ? `${finalInstructions}\\n\\n${this.additionalInstructions}`\n : this.additionalInstructions;\n }\n\n // Handle Anthropic prompt caching\n if (\n finalInstructions != null &&\n finalInstructions !== '' &&\n this.provider === Providers.ANTHROPIC\n ) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n const defaultHeaders = anthropicOptions?.clientOptions?.defaultHeaders as\n | Record<string, string>\n | undefined;\n const anthropicBeta = defaultHeaders?.['anthropic-beta'];\n if (\n typeof anthropicBeta === 'string' &&\n anthropicBeta.includes('prompt-caching')\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: this.instructions,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n }\n\n if (finalInstructions != null && finalInstructions !== '') {\n const systemMessage = new SystemMessage(finalInstructions);\n\n if (this.tokenCounter) {\n this.instructionTokens += this.tokenCounter(systemMessage);\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n\n return undefined;\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.instructionTokens = 0;\n this.lastToken = undefined;\n this.indexTokenCountMap = {};\n this.currentUsage = undefined;\n this.pruneMessages = undefined;\n this.lastStreamCall = undefined;\n this.tokenTypeSwitch = undefined;\n this.currentTokenType = ContentTypes.TEXT;\n }\n\n /**\n * Update the token count map with instruction tokens\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n if (this.instructionTokens > 0) {\n // Shift all indices by the instruction token count\n const shiftedMap: Record<string, number> = {};\n for (const [key, value] of Object.entries(baseTokenMap)) {\n const index = parseInt(key, 10);\n if (!isNaN(index)) {\n shiftedMap[String(index)] =\n value + (index === 0 ? this.instructionTokens : 0);\n }\n }\n this.indexTokenCountMap = shiftedMap;\n } else {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n if (this.tools && this.tools.length > 0) {\n for (const tool of this.tools) {\n const genericTool = tool as Record<string, unknown>;\n if (\n genericTool.schema != null &&\n typeof genericTool.schema === 'object'\n ) {\n const schema = genericTool.schema as {\n describe: (desc: string) => unknown;\n };\n const describedSchema = schema.describe(\n (genericTool.description as string) || ''\n );\n const jsonSchema = zodToJsonSchema(\n describedSchema as Parameters<typeof zodToJsonSchema>[0],\n (genericTool.name as string) || ''\n );\n toolTokens += tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n }\n }\n }\n\n // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n this.instructionTokens += toolTokens;\n }\n}\n"],"names":[],"mappings":";;;;;AAAA;AACA;AAcA;;AAEG;MACU,YAAY,CAAA;AACvB;;AAEG;AACH,IAAA,OAAO,UAAU,CACf,WAA0B,EAC1B,YAA6B,EAC7B,kBAA2C,EAAA;QAE3C,MAAM,EACJ,OAAO,EACP,QAAQ,EACR,aAAa,EACb,KAAK,EACL,OAAO,EACP,OAAO,EACP,YAAY,EACZ,uBAAuB,EACvB,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,gBAAgB,GACjB,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EAAE;AACvC,YAAA,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE;gBAC7B,MAAM,WAAW,GAAG,IAA+B;AACnD,gBAAA,IACE,WAAW,CAAC,MAAM,IAAI,IAAI;AAC1B,oBAAA,OAAO,WAAW,CAAC,MAAM,KAAK,QAAQ,EACtC;AACA,oBAAA,MAAM,MAAM,GAAG,WAAW,CAAC,MAE1B;AACD,oBAAA,MAAM,eAAe,GAAG,MAAM,CAAC,QAAQ,CACpC,WAAW,CAAC,WAAsB,IAAI,EAAE,CAC1C;AACD,oBAAA,MAAM,UAAU,GAAG,eAAe,CAChC,eAAwD,EACvD,WAAW,CAAC,IAAe,IAAI,EAAE,CACnC;AACD,oBAAA,UAAU,IAAI,YAAY,CACxB,IAAI,aAAa,CAAC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC,CAC9C;;;;;AAMP,QAAA,IAAI,CAAC,iBAAiB,IAAI,UAAU;;AAEvC;;;;"}
|
|
1
|
+
{"version":3,"file":"AgentContext.mjs","sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/agents/AgentContext.ts\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { SystemMessage } from '@langchain/core/messages';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type {\n UsageMetadata,\n BaseMessage,\n BaseMessageFields,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport type { createPruneMessages } from '@/messages';\nimport { ContentTypes, Providers } from '@/common';\n\n/**\n * Encapsulates agent-specific state that can vary between agents in a multi-agent system\n */\nexport class AgentContext {\n /**\n * Create an AgentContext from configuration with token accounting initialization\n */\n static fromConfig(\n agentConfig: t.AgentInputs,\n tokenCounter?: t.TokenCounter,\n indexTokenCountMap?: Record<string, number>\n ): AgentContext {\n const {\n agentId,\n provider,\n clientOptions,\n tools,\n toolMap,\n toolEnd,\n toolRegistry,\n instructions,\n additional_instructions,\n streamBuffer,\n maxContextTokens,\n reasoningKey,\n useLegacyContent,\n } = agentConfig;\n\n const agentContext = new AgentContext({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions: additional_instructions,\n reasoningKey,\n toolEnd,\n instructionTokens: 0,\n tokenCounter,\n useLegacyContent,\n });\n\n if (tokenCounter) {\n // Initialize system runnable BEFORE async tool token calculation\n // This ensures system message tokens are in instructionTokens before\n // updateTokenMapWithInstructions is called\n agentContext.initializeSystemRunnable();\n\n const tokenMap = indexTokenCountMap || {};\n agentContext.indexTokenCountMap = tokenMap;\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n // Update token map with instruction tokens (includes system + tool tokens)\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n } else if (indexTokenCountMap) {\n agentContext.indexTokenCountMap = indexTokenCountMap;\n }\n\n return agentContext;\n }\n\n /** Agent identifier */\n agentId: string;\n /** Provider for this specific agent */\n provider: Providers;\n /** Client options for this agent */\n clientOptions?: t.ClientOptions;\n /** Token count map indexed by message position */\n indexTokenCountMap: Record<string, number | undefined> = {};\n /** Maximum context tokens for this agent */\n maxContextTokens?: number;\n /** Current usage metadata for this agent */\n currentUsage?: Partial<UsageMetadata>;\n /** Prune messages function configured for this agent */\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** Token counter function for this agent */\n tokenCounter?: t.TokenCounter;\n /** Instructions/system message token count */\n instructionTokens: number = 0;\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer?: number;\n /** Last stream call timestamp for rate limiting */\n lastStreamCall?: number;\n /** Tools available to this agent */\n tools?: t.GraphTools;\n /** Tool map for this agent */\n toolMap?: t.ToolMap;\n /**\n * Tool definitions registry (includes deferred and programmatic tool metadata).\n * Used for tool search and programmatic tool calling.\n */\n toolRegistry?: t.LCToolRegistry;\n /** Set of tool names discovered via tool search (to be loaded) */\n discoveredToolNames: Set<string> = new Set();\n /** Instructions for this agent */\n instructions?: string;\n /** Additional instructions for this agent */\n additionalInstructions?: string;\n /** Reasoning key for this agent */\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n /** Last token for reasoning detection */\n lastToken?: string;\n /** Token type switch state */\n tokenTypeSwitch?: 'reasoning' | 'content';\n /** Current token type being processed */\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK | 'think_and_text' =\n ContentTypes.TEXT;\n /** Whether tools should end the workflow */\n toolEnd: boolean = false;\n /** Cached system runnable (created lazily) */\n private cachedSystemRunnable?: Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >;\n /** Whether system runnable needs rebuild (set when discovered tools change) */\n private systemRunnableStale: boolean = true;\n /** Cached system message token count (separate from tool tokens) */\n private systemMessageTokens: number = 0;\n /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n\n constructor({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n }: {\n agentId: string;\n provider: Providers;\n clientOptions?: t.ClientOptions;\n maxContextTokens?: number;\n streamBuffer?: number;\n tokenCounter?: t.TokenCounter;\n tools?: t.GraphTools;\n toolMap?: t.ToolMap;\n toolRegistry?: t.LCToolRegistry;\n instructions?: string;\n additionalInstructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n }) {\n this.agentId = agentId;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.maxContextTokens = maxContextTokens;\n this.streamBuffer = streamBuffer;\n this.tokenCounter = tokenCounter;\n this.tools = tools;\n this.toolMap = toolMap;\n this.toolRegistry = toolRegistry;\n this.instructions = instructions;\n this.additionalInstructions = additionalInstructions;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.instructionTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n }\n\n /**\n * Builds instructions text for tools that are ONLY callable via programmatic code execution.\n * These tools cannot be called directly by the LLM but are available through the\n * run_tools_with_code tool.\n *\n * Includes:\n * - Code_execution-only tools that are NOT deferred\n * - Code_execution-only tools that ARE deferred but have been discovered via tool search\n */\n private buildProgrammaticOnlyToolsInstructions(): string {\n if (!this.toolRegistry) return '';\n\n const programmaticOnlyTools: t.LCTool[] = [];\n for (const [name, toolDef] of this.toolRegistry) {\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n const isCodeExecutionOnly =\n allowedCallers.includes('code_execution') &&\n !allowedCallers.includes('direct');\n\n if (!isCodeExecutionOnly) continue;\n\n // Include if: not deferred OR deferred but discovered\n const isDeferred = toolDef.defer_loading === true;\n const isDiscovered = this.discoveredToolNames.has(name);\n if (!isDeferred || isDiscovered) {\n programmaticOnlyTools.push(toolDef);\n }\n }\n\n if (programmaticOnlyTools.length === 0) return '';\n\n const toolDescriptions = programmaticOnlyTools\n .map((tool) => {\n let desc = `- **${tool.name}**`;\n if (tool.description != null && tool.description !== '') {\n desc += `: ${tool.description}`;\n }\n if (tool.parameters) {\n desc += `\\n Parameters: ${JSON.stringify(tool.parameters, null, 2).replace(/\\n/g, '\\n ')}`;\n }\n return desc;\n })\n .join('\\n\\n');\n\n return (\n '\\n\\n## Programmatic-Only Tools\\n\\n' +\n 'The following tools are available exclusively through the `run_tools_with_code` tool. ' +\n 'You cannot call these tools directly; instead, use `run_tools_with_code` with Python code that invokes them.\\n\\n' +\n toolDescriptions\n );\n }\n\n /**\n * Gets the system runnable, creating it lazily if needed.\n * Includes instructions, additional instructions, and programmatic-only tools documentation.\n * Only rebuilds when marked stale (via markToolsAsDiscovered).\n */\n get systemRunnable():\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n // Return cached if not stale\n if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {\n return this.cachedSystemRunnable;\n }\n\n // Stale or first access - rebuild\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n return this.cachedSystemRunnable;\n }\n\n /**\n * Explicitly initializes the system runnable.\n * Call this before async token calculation to ensure system message tokens are counted first.\n */\n initializeSystemRunnable(): void {\n if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n }\n }\n\n /**\n * Builds the raw instructions string (without creating SystemMessage).\n */\n private buildInstructionsString(): string {\n let result = this.instructions ?? '';\n\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n result = result\n ? `${result}\\n\\n${this.additionalInstructions}`\n : this.additionalInstructions;\n }\n\n const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();\n if (programmaticToolsDoc) {\n result = result\n ? `${result}${programmaticToolsDoc}`\n : programmaticToolsDoc;\n }\n\n return result;\n }\n\n /**\n * Build system runnable from pre-built instructions string.\n * Only called when content has actually changed.\n */\n private buildSystemRunnable(\n instructionsString: string\n ):\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n if (!instructionsString) {\n // Remove previous tokens if we had a system message before\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = 0;\n return undefined;\n }\n\n let finalInstructions: string | BaseMessageFields = instructionsString;\n\n // Handle Anthropic prompt caching (Direct API)\n if (this.provider === Providers.ANTHROPIC) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n const defaultHeaders = anthropicOptions?.clientOptions?.defaultHeaders as\n | Record<string, string>\n | undefined;\n const anthropicBeta = defaultHeaders?.['anthropic-beta'];\n if (\n typeof anthropicBeta === 'string' &&\n anthropicBeta.includes('prompt-caching')\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructionsString,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n }\n\n // Handle Bedrock prompt caching (Converse API)\n // Adds cachePoint block after text content for system message caching\n // NOTE: Both Claude and Nova models support cachePoint in system and messages\n // (Nova does NOT support cachePoint in tools - that check is in bedrock/index.ts)\n if (this.provider === Providers.BEDROCK) {\n const bedrockOptions = this.clientOptions as\n | t.BedrockAnthropicInput\n | undefined;\n const modelId = bedrockOptions?.model?.toLowerCase() ?? '';\n const supportsCaching = modelId.includes('claude') || modelId.includes('anthropic') || modelId.includes('nova');\n\n if (bedrockOptions?.promptCache === true && supportsCaching) {\n // Always log system cache structure\n console.log(`[Cache] 📝 System | chars=${instructionsString.length} | tokens=${this.systemMessageTokens} | model=${modelId}`);\n \n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructionsString,\n },\n {\n cachePoint: { type: 'default' },\n },\n ],\n };\n }\n }\n\n const systemMessage = new SystemMessage(finalInstructions);\n\n // Update token counts (subtract old, add new)\n if (this.tokenCounter) {\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = this.tokenCounter(systemMessage);\n this.instructionTokens += this.systemMessageTokens;\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.instructionTokens = 0;\n this.systemMessageTokens = 0;\n this.cachedSystemRunnable = undefined;\n this.systemRunnableStale = true;\n this.lastToken = undefined;\n this.indexTokenCountMap = {};\n this.currentUsage = undefined;\n this.pruneMessages = undefined;\n this.lastStreamCall = undefined;\n this.tokenTypeSwitch = undefined;\n this.currentTokenType = ContentTypes.TEXT;\n this.discoveredToolNames.clear();\n }\n\n /**\n * Update the token count map with instruction tokens\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n if (this.instructionTokens > 0) {\n // Shift all indices by the instruction token count\n const shiftedMap: Record<string, number> = {};\n for (const [key, value] of Object.entries(baseTokenMap)) {\n const index = parseInt(key, 10);\n if (!isNaN(index)) {\n shiftedMap[String(index)] =\n value + (index === 0 ? this.instructionTokens : 0);\n }\n }\n this.indexTokenCountMap = shiftedMap;\n } else {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n if (this.tools && this.tools.length > 0) {\n for (const tool of this.tools) {\n const genericTool = tool as Record<string, unknown>;\n if (\n genericTool.schema != null &&\n typeof genericTool.schema === 'object'\n ) {\n const schema = genericTool.schema as {\n describe: (desc: string) => unknown;\n };\n const describedSchema = schema.describe(\n (genericTool.description as string) || ''\n );\n const jsonSchema = zodToJsonSchema(\n describedSchema as Parameters<typeof zodToJsonSchema>[0],\n (genericTool.name as string) || ''\n );\n toolTokens += tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n }\n }\n }\n\n // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n this.instructionTokens += toolTokens;\n }\n\n /**\n * Gets the tool registry for deferred tools (for tool search).\n * @param onlyDeferred If true, only returns tools with defer_loading=true\n * @returns LCToolRegistry with tool definitions\n */\n getDeferredToolRegistry(onlyDeferred: boolean = true): t.LCToolRegistry {\n const registry: t.LCToolRegistry = new Map();\n\n if (!this.toolRegistry) {\n return registry;\n }\n\n for (const [name, toolDef] of this.toolRegistry) {\n if (!onlyDeferred || toolDef.defer_loading === true) {\n registry.set(name, toolDef);\n }\n }\n\n return registry;\n }\n\n /**\n * Marks tools as discovered via tool search.\n * Discovered tools will be included in the next model binding.\n * Only marks system runnable stale if NEW tools were actually added.\n * @param toolNames - Array of discovered tool names\n * @returns true if any new tools were discovered\n */\n markToolsAsDiscovered(toolNames: string[]): boolean {\n let hasNewDiscoveries = false;\n for (const name of toolNames) {\n if (!this.discoveredToolNames.has(name)) {\n this.discoveredToolNames.add(name);\n hasNewDiscoveries = true;\n }\n }\n if (hasNewDiscoveries) {\n this.systemRunnableStale = true;\n }\n return hasNewDiscoveries;\n }\n\n /**\n * Gets tools that should be bound to the LLM.\n * Includes:\n * 1. Non-deferred tools with allowed_callers: ['direct']\n * 2. Discovered tools (from tool search)\n * @returns Array of tools to bind to model\n */\n getToolsForBinding(): t.GraphTools | undefined {\n if (!this.tools || !this.toolRegistry) {\n return this.tools;\n }\n\n const toolsToInclude = this.tools.filter((tool) => {\n if (!('name' in tool)) {\n return true; // No name, include by default\n }\n\n const toolDef = this.toolRegistry?.get(tool.name);\n if (!toolDef) {\n return true; // Not in registry, include by default\n }\n\n // Check if discovered (overrides defer_loading)\n if (this.discoveredToolNames.has(tool.name)) {\n // Discovered tools must still have allowed_callers: ['direct']\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes('direct');\n }\n\n // Not discovered: must be direct-callable AND not deferred\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return (\n allowedCallers.includes('direct') && toolDef.defer_loading !== true\n );\n });\n\n return toolsToInclude;\n }\n}\n"],"names":[],"mappings":";;;;;AAAA;AACA;AAcA;;AAEG;MACU,YAAY,CAAA;AACvB;;AAEG;AACH,IAAA,OAAO,UAAU,CACf,WAA0B,EAC1B,YAA6B,EAC7B,kBAA2C,EAAA;AAE3C,QAAA,MAAM,EACJ,OAAO,EACP,QAAQ,EACR,aAAa,EACb,KAAK,EACL,OAAO,EACP,OAAO,EACP,YAAY,EACZ,YAAY,EACZ,uBAAuB,EACvB,YAAY,EACZ,gBAAgB,EAChB,YAAY,E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TE_CODE"] = "execute_code";
|
|
146
|
+
Constants["TOOL_SEARCH_REGEX"] = "tool_search_regex";
|
|
147
|
+
Constants["PROGRAMMATIC_TOOL_CALLING"] = "run_tools_with_code";
|
|
146
148
|
Constants["WEB_SEARCH"] = "web_search";
|
|
147
149
|
Constants["CONTENT_AND_ARTIFACT"] = "content_and_artifact";
|
|
148
150
|
Constants["LC_TRANSFER_TO_"] = "lc_transfer_to_";
|