@librechat/agents 3.1.83 → 3.1.85
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/agents/AgentContext.cjs +26 -3
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +1 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/events.cjs +2 -1
- package/dist/cjs/events.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +5 -1
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +3 -2
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/main.cjs +4 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +5 -2
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +26 -24
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +28 -2
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +130 -56
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +7 -5
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs +52 -13
- package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ptcTimeout.cjs +56 -0
- package/dist/cjs/tools/ptcTimeout.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +27 -4
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +1 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/events.mjs +2 -1
- package/dist/esm/events.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +5 -1
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +3 -2
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/main.mjs +3 -3
- package/dist/esm/tools/BashExecutor.mjs +6 -3
- package/dist/esm/tools/BashExecutor.mjs.map +1 -1
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +26 -25
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +27 -3
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +131 -58
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +7 -5
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs +54 -15
- package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ptcTimeout.mjs +50 -0
- package/dist/esm/tools/ptcTimeout.mjs.map +1 -0
- package/dist/types/agents/AgentContext.d.ts +3 -1
- package/dist/types/common/enum.d.ts +2 -1
- package/dist/types/tools/BashProgrammaticToolCalling.d.ts +4 -36
- package/dist/types/tools/CodeExecutor.d.ts +5 -0
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +18 -39
- package/dist/types/tools/ptcTimeout.d.ts +25 -0
- package/dist/types/types/tools.d.ts +8 -0
- package/package.json +1 -1
- package/src/agents/AgentContext.ts +32 -3
- package/src/agents/__tests__/AgentContext.test.ts +36 -3
- package/src/common/enum.ts +1 -0
- package/src/events.ts +4 -1
- package/src/graphs/MultiAgentGraph.ts +3 -2
- package/src/graphs/__tests__/composition.smoke.test.ts +84 -2
- package/src/tools/BashExecutor.ts +14 -3
- package/src/tools/BashProgrammaticToolCalling.ts +37 -25
- package/src/tools/CodeExecutor.ts +36 -2
- package/src/tools/ProgrammaticToolCalling.ts +206 -53
- package/src/tools/ToolNode.ts +3 -4
- package/src/tools/__tests__/CodeApiAuthHeaders.test.ts +424 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +31 -1
- package/src/tools/local/LocalProgrammaticToolCalling.ts +94 -13
- package/src/tools/ptcTimeout.ts +89 -0
- package/src/types/tools.ts +12 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BashProgrammaticToolCalling.mjs","sources":["../../../src/tools/BashProgrammaticToolCalling.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport {\n makeRequest,\n executeTools,\n formatCompletedResponse,\n} from './ProgrammaticToolCalling';\nimport { getCodeBaseURL } from './CodeExecutor';\nimport { Constants } from '@/common';\n\nconfig();\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\nconst DEFAULT_TIMEOUT = 60000;\n\n/** Bash reserved words that get `_tool` suffix when used as function names */\nconst BASH_RESERVED = new Set([\n 'if',\n 'then',\n 'else',\n 'elif',\n 'fi',\n 'case',\n 'esac',\n 'for',\n 'while',\n 'until',\n 'do',\n 'done',\n 'in',\n 'function',\n 'select',\n 'time',\n 'coproc',\n 'declare',\n 'typeset',\n 'local',\n 'readonly',\n 'export',\n 'unset',\n]);\n\n// ============================================================================\n// Description Components\n// ============================================================================\n\nconst STATELESS_WARNING = `CRITICAL - STATELESS EXECUTION:\nEach call is a fresh bash shell. Variables and state do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block.\nDO NOT split work across multiple calls expecting to reuse variables.`;\n\nconst CORE_RULES = `Rules:\n- EVERYTHING in one call—no state persists between executions\n- Tools are pre-defined as bash functions—DO NOT redefine them\n- Each tool function accepts a JSON string argument\n- Only echo/printf output returns to the model\n- Generated files are automatically available in /mnt/data/ for subsequent executions`;\n\nconst ADDITIONAL_RULES =\n '- Tool names normalized: hyphens→underscores, reserved words get `_tool` suffix';\n\nconst EXAMPLES = `Example (Complete workflow in one call):\n # Query data and process\n data=$(query_database '{\"sql\": \"SELECT * FROM users\"}')\n echo \"$data\" | jq '.[] | .name'\n\nExample (Parallel calls):\n web_search '{\"query\": \"SF weather\"}' > /tmp/sf.txt &\n web_search '{\"query\": \"NY weather\"}' > /tmp/ny.txt &\n wait\n echo \"SF: $(cat /tmp/sf.txt)\"\n echo \"NY: $(cat /tmp/ny.txt)\"`;\n\nconst CODE_PARAM_DESCRIPTION = `Bash code that calls tools programmatically. Tools are available as bash functions.\n\n${STATELESS_WARNING}\n\nEach tool function accepts a JSON string as its argument.\nExample: tool_name '{\"key\": \"value\"}'\n\n${EXAMPLES}\n\n${CORE_RULES}`;\n\n// ============================================================================\n// Schema\n// ============================================================================\n\nexport const BashProgrammaticToolCallingSchema = {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n minLength: 1,\n description: CODE_PARAM_DESCRIPTION,\n },\n timeout: {\n type: 'integer',\n minimum: 1000,\n maximum: 300000,\n default: DEFAULT_TIMEOUT,\n description:\n 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.',\n },\n },\n required: ['code'],\n} as const;\n\nexport const BashProgrammaticToolCallingName =\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING;\n\nexport const BashProgrammaticToolCallingDescription = `\nRun tools via bash code. Tools are available as bash functions that accept JSON string arguments.\n\n${STATELESS_WARNING}\n\n${CORE_RULES}\n${ADDITIONAL_RULES}\n\nWhen to use: shell pipelines, parallel execution (& and wait), file processing, text manipulation.\n\n${EXAMPLES}\n`.trim();\n\nexport const BashProgrammaticToolCallingDefinition = {\n name: BashProgrammaticToolCallingName,\n description: BashProgrammaticToolCallingDescription,\n schema: BashProgrammaticToolCallingSchema,\n} as const;\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Normalizes a tool name to a valid bash function identifier.\n * 1. Replace hyphens, spaces, dots with underscores\n * 2. Remove any other invalid characters\n * 3. Prefix with underscore if starts with number\n * 4. Append `_tool` if it's a bash reserved word\n */\nexport function normalizeToBashIdentifier(name: string): string {\n let normalized = name.replace(/[-\\s.]/g, '_');\n normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');\n\n if (/^[0-9]/.test(normalized)) {\n normalized = '_' + normalized;\n }\n\n if (BASH_RESERVED.has(normalized)) {\n normalized = normalized + '_tool';\n }\n\n return normalized;\n}\n\n/**\n * Extracts tool names that are actually called in the bash code.\n * Bash functions are invoked as commands (no parentheses), so we match\n * the normalized name as a word boundary.\n */\nexport function extractUsedBashToolNames(\n code: string,\n toolNameMap: Map<string, string>\n): Set<string> {\n const usedTools = new Set<string>();\n\n for (const [bashName, originalName] of toolNameMap) {\n const escapedName = bashName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const pattern = new RegExp(`\\\\b${escapedName}\\\\b`, 'g');\n\n if (pattern.test(code)) {\n usedTools.add(originalName);\n }\n }\n\n return usedTools;\n}\n\n/**\n * Filters tool definitions to only include tools actually used in the bash code.\n */\nexport function filterBashToolsByUsage(\n toolDefs: t.LCTool[],\n code: string,\n debug = false\n): t.LCTool[] {\n const toolNameMap = new Map<string, string>();\n for (const def of toolDefs) {\n const bashName = normalizeToBashIdentifier(def.name);\n toolNameMap.set(bashName, def.name);\n }\n\n const usedToolNames = extractUsedBashToolNames(code, toolNameMap);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`\n );\n if (usedToolNames.size > 0) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`\n );\n }\n }\n\n if (usedToolNames.size === 0) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[BashPTC Debug] No tools detected in code - sending all tools as fallback'\n );\n }\n return toolDefs;\n }\n\n return toolDefs.filter((def) => usedToolNames.has(def.name));\n}\n\n// ============================================================================\n// Tool Factory\n// ============================================================================\n\n/**\n * Creates a Bash Programmatic Tool Calling tool for multi-tool orchestration.\n *\n * This tool enables AI agents to write bash scripts that orchestrate multiple\n * tool calls programmatically via the remote Code API, reducing LLM round-trips.\n *\n * The tool map must be provided at runtime via config.toolCall (injected by ToolNode).\n */\nexport function createBashProgrammaticToolCallingTool(\n initParams: t.BashProgrammaticToolCallingParams = {}\n): DynamicStructuredTool {\n const baseUrl = initParams.baseUrl ?? getCodeBaseURL();\n const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;\n const proxy = initParams.proxy ?? process.env.PROXY;\n const debug = initParams.debug ?? process.env.BASH_PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n return tool(\n async (rawParams, config) => {\n const params = rawParams as { code: string; timeout?: number };\n const { code, timeout = DEFAULT_TIMEOUT } = params;\n\n const toolCall = (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache> & {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n const { toolMap, toolDefs, session_id, _injected_files } = toolCall;\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error(\n 'No toolMap provided. ' +\n 'ToolNode should inject this from AgentContext when invoked through the graph.'\n );\n }\n\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided. ' +\n 'Either pass tools in the input or ensure ToolNode injects toolDefs.'\n );\n }\n\n let roundTrip = 0;\n\n try {\n // ====================================================================\n // Phase 1: Filter tools and make initial request\n // ====================================================================\n\n const effectiveTools = filterBashToolsByUsage(toolDefs, code, debug);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Sending ${effectiveTools.length} tools to API ` +\n `(filtered from ${toolDefs.length})`\n );\n }\n\n /* `/files/<session_id>` HTTP fallback removed — codeapi's\n * sessionAuth requires kind/id query params unavailable at\n * this point. See `CodeExecutor.ts` for full rationale. */\n let files: t.CodeEnvFile[] | undefined;\n if (_injected_files && _injected_files.length > 0) {\n files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n // eslint-disable-next-line no-console\n console.debug(\n `[BashProgrammaticToolCalling] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n {\n lang: 'bash',\n code,\n tools: effectiveTools,\n session_id,\n timeout,\n ...(files && files.length > 0 ? { files } : {}),\n },\n proxy\n );\n\n // ====================================================================\n // Phase 2: Handle response loop\n // ====================================================================\n\n while (response.status === 'tool_call_required') {\n roundTrip++;\n\n if (roundTrip > maxRoundTrips) {\n throw new Error(\n `Exceeded maximum round trips (${maxRoundTrips}). ` +\n 'This may indicate an infinite loop, excessive tool calls, ' +\n 'or a logic error in your code.'\n );\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`\n );\n }\n\n const toolResults = await executeTools(\n response.tool_calls ?? [],\n toolMap\n );\n\n response = await makeRequest(\n EXEC_ENDPOINT,\n {\n continuation_token: response.continuation_token,\n tool_results: toolResults,\n },\n proxy\n );\n }\n\n // ====================================================================\n // Phase 3: Handle final state\n // ====================================================================\n\n if (response.status === 'completed') {\n return formatCompletedResponse(response);\n }\n\n if (response.status === 'error') {\n throw new Error(\n `Execution error: ${response.error}` +\n (response.stderr != null && response.stderr !== ''\n ? `\\n\\nStderr:\\n${response.stderr}`\n : '')\n );\n }\n\n throw new Error(`Unexpected response status: ${response.status}`);\n } catch (error) {\n throw new Error(\n `Bash programmatic execution failed: ${(error as Error).message}`\n );\n }\n },\n {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n description: BashProgrammaticToolCallingDescription,\n schema: BashProgrammaticToolCallingSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"names":[],"mappings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uBAAuB,CAAC,QAAQ,CAAC;YAC1C;AAEA,YAAA,IAAI,QAAQ,CAAC,MAAM,KAAK,OAAO,EAAE;AAC/B,gBAAA,MAAM,IAAI,KAAK,CACb,oBAAoB,QAAQ,CAAC,KAAK,CAAA,CAAE;qBACjC,QAAQ,CAAC,MAAM,IAAI,IAAI,IAAI,QAAQ,CAAC,MAAM,KAAK;AAC9C,0BAAE,CAAA,aAAA,EAAgB,QAAQ,CAAC,MAAM,CAAA;AACjC,0BAAE,EAAE,CAAC,CACV;YACH;YAEA,MAAM,IAAI,KAAK,CAAC,CAAA,4BAAA,EAA+B,QAAQ,CAAC,MAAM,CAAA,CAAE,CAAC;QACnE;QAAE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,oCAAA,EAAwC,KAAe,CAAC,OAAO,CAAA,CAAE,CAClE;QACH;AACF,IAAA,CAAC,EACD;QACE,IAAI,EAAE,SAAS,CAAC,8BAA8B;AAC9C,QAAA,WAAW,EAAE,sCAAsC;AACnD,QAAA,MAAM,EAAE,iCAAiC;QACzC,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"BashProgrammaticToolCalling.mjs","sources":["../../../src/tools/BashProgrammaticToolCalling.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { ProgrammaticToolCallingJsonSchema } from './ptcTimeout';\nimport type * as t from '@/types';\nimport {\n makeRequest,\n executeTools,\n formatCompletedResponse,\n} from './ProgrammaticToolCalling';\nimport { getCodeBaseURL } from './CodeExecutor';\nimport {\n clampCodeApiRunTimeoutMs,\n createCodeApiRunTimeoutSchema,\n resolveCodeApiRunTimeoutMs,\n} from './ptcTimeout';\nimport { Constants } from '@/common';\n\nconfig();\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\nconst DEFAULT_RUN_TIMEOUT_MS = resolveCodeApiRunTimeoutMs();\n\n/** Bash reserved words that get `_tool` suffix when used as function names */\nconst BASH_RESERVED = new Set([\n 'if',\n 'then',\n 'else',\n 'elif',\n 'fi',\n 'case',\n 'esac',\n 'for',\n 'while',\n 'until',\n 'do',\n 'done',\n 'in',\n 'function',\n 'select',\n 'time',\n 'coproc',\n 'declare',\n 'typeset',\n 'local',\n 'readonly',\n 'export',\n 'unset',\n]);\n\n// ============================================================================\n// Description Components\n// ============================================================================\n\nconst STATELESS_WARNING = `CRITICAL - STATELESS EXECUTION:\nEach call is a fresh bash shell. Variables and state do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block.\nDO NOT split work across multiple calls expecting to reuse variables.`;\n\nconst CORE_RULES = `Rules:\n- EVERYTHING in one call—no state persists between executions\n- Tools are pre-defined as bash functions—DO NOT redefine them\n- Each tool function accepts a JSON string argument\n- Only echo/printf output returns to the model\n- Generated files are automatically available in /mnt/data/ for subsequent executions\n- timeout caps one sandbox run/replay iteration, not the total multi-round-trip workflow`;\n\nconst ADDITIONAL_RULES =\n '- Tool names normalized: hyphens→underscores, reserved words get `_tool` suffix';\n\nconst EXAMPLES = `Example (Complete workflow in one call):\n # Query data and process\n data=$(query_database '{\"sql\": \"SELECT * FROM users\"}')\n echo \"$data\" | jq '.[] | .name'\n\nExample (Parallel calls):\n web_search '{\"query\": \"SF weather\"}' > /tmp/sf.txt &\n web_search '{\"query\": \"NY weather\"}' > /tmp/ny.txt &\n wait\n echo \"SF: $(cat /tmp/sf.txt)\"\n echo \"NY: $(cat /tmp/ny.txt)\"`;\n\nconst CODE_PARAM_DESCRIPTION = `Bash code that calls tools programmatically. Tools are available as bash functions.\n\n${STATELESS_WARNING}\n\nEach tool function accepts a JSON string as its argument.\nExample: tool_name '{\"key\": \"value\"}'\n\n${EXAMPLES}\n\n${CORE_RULES}`;\n\n// ============================================================================\n// Schema\n// ============================================================================\n\nexport function createBashProgrammaticToolCallingSchema(\n maxRunTimeoutMs = DEFAULT_RUN_TIMEOUT_MS\n): ProgrammaticToolCallingJsonSchema {\n return {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n minLength: 1,\n description: CODE_PARAM_DESCRIPTION,\n },\n timeout: createCodeApiRunTimeoutSchema(maxRunTimeoutMs),\n },\n required: ['code'],\n } as const;\n}\n\nexport const BashProgrammaticToolCallingSchema =\n createBashProgrammaticToolCallingSchema();\n\nexport const BashProgrammaticToolCallingName =\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING;\n\nexport const BashProgrammaticToolCallingDescription = `\nRun tools via bash code. Tools are available as bash functions that accept JSON string arguments.\n\n${STATELESS_WARNING}\n\n${CORE_RULES}\n${ADDITIONAL_RULES}\n\nWhen to use: shell pipelines, parallel execution (& and wait), file processing, text manipulation.\n\n${EXAMPLES}\n`.trim();\n\nexport const BashProgrammaticToolCallingDefinition = {\n name: BashProgrammaticToolCallingName,\n description: BashProgrammaticToolCallingDescription,\n schema: BashProgrammaticToolCallingSchema,\n} as const;\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Normalizes a tool name to a valid bash function identifier.\n * 1. Replace hyphens, spaces, dots with underscores\n * 2. Remove any other invalid characters\n * 3. Prefix with underscore if starts with number\n * 4. Append `_tool` if it's a bash reserved word\n */\nexport function normalizeToBashIdentifier(name: string): string {\n let normalized = name.replace(/[-\\s.]/g, '_');\n normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');\n\n if (/^[0-9]/.test(normalized)) {\n normalized = '_' + normalized;\n }\n\n if (BASH_RESERVED.has(normalized)) {\n normalized = normalized + '_tool';\n }\n\n return normalized;\n}\n\n/**\n * Extracts tool names that are actually called in the bash code.\n * Bash functions are invoked as commands (no parentheses), so we match\n * the normalized name as a word boundary.\n */\nexport function extractUsedBashToolNames(\n code: string,\n toolNameMap: Map<string, string>\n): Set<string> {\n const usedTools = new Set<string>();\n\n for (const [bashName, originalName] of toolNameMap) {\n const escapedName = bashName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const pattern = new RegExp(`\\\\b${escapedName}\\\\b`, 'g');\n\n if (pattern.test(code)) {\n usedTools.add(originalName);\n }\n }\n\n return usedTools;\n}\n\n/**\n * Filters tool definitions to only include tools actually used in the bash code.\n */\nexport function filterBashToolsByUsage(\n toolDefs: t.LCTool[],\n code: string,\n debug = false\n): t.LCTool[] {\n const toolNameMap = new Map<string, string>();\n for (const def of toolDefs) {\n const bashName = normalizeToBashIdentifier(def.name);\n toolNameMap.set(bashName, def.name);\n }\n\n const usedToolNames = extractUsedBashToolNames(code, toolNameMap);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`\n );\n if (usedToolNames.size > 0) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`\n );\n }\n }\n\n if (usedToolNames.size === 0) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[BashPTC Debug] No tools detected in code - sending all tools as fallback'\n );\n }\n return toolDefs;\n }\n\n return toolDefs.filter((def) => usedToolNames.has(def.name));\n}\n\n// ============================================================================\n// Tool Factory\n// ============================================================================\n\n/**\n * Creates a Bash Programmatic Tool Calling tool for multi-tool orchestration.\n *\n * This tool enables AI agents to write bash scripts that orchestrate multiple\n * tool calls programmatically via the remote Code API, reducing LLM round-trips.\n *\n * The tool map must be provided at runtime via config.toolCall (injected by ToolNode).\n */\nexport function createBashProgrammaticToolCallingTool(\n initParams: t.BashProgrammaticToolCallingParams = {}\n): DynamicStructuredTool {\n const baseUrl = initParams.baseUrl ?? getCodeBaseURL();\n const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;\n const maxRunTimeoutMs = resolveCodeApiRunTimeoutMs(initParams.runTimeoutMs);\n const proxy = initParams.proxy ?? process.env.PROXY;\n const debug = initParams.debug ?? process.env.BASH_PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n return tool(\n async (rawParams, config) => {\n const params = rawParams as { code: string; timeout?: number };\n const { code } = params;\n const timeout = clampCodeApiRunTimeoutMs(params.timeout, maxRunTimeoutMs);\n\n const toolCall = (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache> & {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n const { toolMap, toolDefs, session_id, _injected_files } = toolCall;\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error(\n 'No toolMap provided. ' +\n 'ToolNode should inject this from AgentContext when invoked through the graph.'\n );\n }\n\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided. ' +\n 'Either pass tools in the input or ensure ToolNode injects toolDefs.'\n );\n }\n\n let roundTrip = 0;\n\n try {\n // ====================================================================\n // Phase 1: Filter tools and make initial request\n // ====================================================================\n\n const effectiveTools = filterBashToolsByUsage(toolDefs, code, debug);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Sending ${effectiveTools.length} tools to API ` +\n `(filtered from ${toolDefs.length})`\n );\n }\n\n /* `/files/<session_id>` HTTP fallback removed — codeapi's\n * sessionAuth requires kind/id query params unavailable at\n * this point. See `CodeExecutor.ts` for full rationale. */\n let files: t.CodeEnvFile[] | undefined;\n if (_injected_files && _injected_files.length > 0) {\n files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n // eslint-disable-next-line no-console\n console.debug(\n `[BashProgrammaticToolCalling] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n {\n lang: 'bash',\n code,\n tools: effectiveTools,\n session_id,\n timeout,\n ...(files && files.length > 0 ? { files } : {}),\n },\n proxy,\n initParams.authHeaders\n );\n\n // ====================================================================\n // Phase 2: Handle response loop\n // ====================================================================\n\n while (response.status === 'tool_call_required') {\n roundTrip++;\n\n if (roundTrip > maxRoundTrips) {\n throw new Error(\n `Exceeded maximum round trips (${maxRoundTrips}). ` +\n 'This may indicate an infinite loop, excessive tool calls, ' +\n 'or a logic error in your code.'\n );\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`\n );\n }\n\n const toolResults = await executeTools(\n response.tool_calls ?? [],\n toolMap,\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING\n );\n\n response = await makeRequest(\n EXEC_ENDPOINT,\n {\n continuation_token: response.continuation_token,\n tool_results: toolResults,\n },\n proxy,\n initParams.authHeaders\n );\n }\n\n // ====================================================================\n // Phase 3: Handle final state\n // ====================================================================\n\n if (response.status === 'completed') {\n return formatCompletedResponse(response);\n }\n\n if (response.status === 'error') {\n throw new Error(\n `Execution error: ${response.error}` +\n (response.stderr != null && response.stderr !== ''\n ? `\\n\\nStderr:\\n${response.stderr}`\n : '')\n );\n }\n\n throw new Error(`Unexpected response status: ${response.status}`);\n } catch (error) {\n throw new Error(\n `Bash programmatic execution failed: ${(error as Error).message}`\n );\n }\n },\n {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n description: BashProgrammaticToolCallingDescription,\n schema: createBashProgrammaticToolCallingSchema(maxRunTimeoutMs),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"names":[],"mappings":";;;;;;;AAkBA,MAAM,EAAE;AAER;AACA;AACA;AAEA,MAAM,uBAAuB,GAAG,EAAE;AAClC,MAAM,sBAAsB,GAAG,0BAA0B,EAAE;AAE3D;AACA,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC;IAC5B,IAAI;IACJ,MAAM;IACN,MAAM;IACN,MAAM;IACN,IAAI;IACJ,MAAM;IACN,MAAM;IACN,KAAK;IACL,OAAO;IACP,OAAO;IACP,IAAI;IACJ,MAAM;IACN,IAAI;IACJ,UAAU;IACV,QAAQ;IACR,MAAM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BACjC,QAAQ,CAAC,MAAM,IAAI,IAAI,IAAI,QAAQ,CAAC,MAAM,KAAK;AAC9C,0BAAE,CAAA,aAAA,EAAgB,QAAQ,CAAC,MAAM,CAAA;AACjC,0BAAE,EAAE,CAAC,CACV;YACH;YAEA,MAAM,IAAI,KAAK,CAAC,CAAA,4BAAA,EAA+B,QAAQ,CAAC,MAAM,CAAA,CAAE,CAAC;QACnE;QAAE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,oCAAA,EAAwC,KAAe,CAAC,OAAO,CAAA,CAAE,CAClE;QACH;AACF,IAAA,CAAC,EACD;QACE,IAAI,EAAE,SAAS,CAAC,8BAA8B;AAC9C,QAAA,WAAW,EAAE,sCAAsC;AACnD,QAAA,MAAM,EAAE,uCAAuC,CAAC,eAAe,CAAC;QAChE,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
|
|
@@ -57,6 +57,27 @@ const CodeExecutionToolSchema = {
|
|
|
57
57
|
};
|
|
58
58
|
const baseEndpoint = getCodeBaseURL();
|
|
59
59
|
const EXEC_ENDPOINT = `${baseEndpoint}/exec`;
|
|
60
|
+
async function resolveCodeApiAuthHeaders(authHeaders) {
|
|
61
|
+
if (authHeaders == null) {
|
|
62
|
+
return {};
|
|
63
|
+
}
|
|
64
|
+
if (typeof authHeaders === 'function') {
|
|
65
|
+
return authHeaders();
|
|
66
|
+
}
|
|
67
|
+
return authHeaders;
|
|
68
|
+
}
|
|
69
|
+
async function buildCodeApiHttpErrorMessage(method, endpoint, response) {
|
|
70
|
+
let responseBody = '';
|
|
71
|
+
try {
|
|
72
|
+
responseBody = await response.text();
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
responseBody = '';
|
|
76
|
+
}
|
|
77
|
+
const body = responseBody.trim();
|
|
78
|
+
const bodySuffix = body === '' ? '' : `, body: ${body.slice(0, 1000)}`;
|
|
79
|
+
return `CodeAPI request failed: ${method} ${endpoint} returned ${response.status}${bodySuffix}`;
|
|
80
|
+
}
|
|
60
81
|
const CodeExecutionToolDescription = `
|
|
61
82
|
Runs code and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.
|
|
62
83
|
|
|
@@ -73,6 +94,7 @@ const CodeExecutionToolDefinition = {
|
|
|
73
94
|
};
|
|
74
95
|
function createCodeExecutionTool(params = {}) {
|
|
75
96
|
return tool(async (rawInput, config) => {
|
|
97
|
+
const { authHeaders, ...executionParams } = params ?? {};
|
|
76
98
|
const { lang, code, ...rest } = rawInput;
|
|
77
99
|
/**
|
|
78
100
|
* Extract session context from config.toolCall (injected by ToolNode).
|
|
@@ -84,7 +106,7 @@ function createCodeExecutionTool(params = {}) {
|
|
|
84
106
|
lang,
|
|
85
107
|
code,
|
|
86
108
|
...rest,
|
|
87
|
-
...
|
|
109
|
+
...executionParams,
|
|
88
110
|
};
|
|
89
111
|
/* File injection: `_injected_files` from ToolNode (set when host
|
|
90
112
|
* primes a CodeSessionContext) or `params.files` from tool
|
|
@@ -103,11 +125,13 @@ function createCodeExecutionTool(params = {}) {
|
|
|
103
125
|
console.debug(`[CodeExecutor] No injected files for session_id=${session_id} — exec will run without input files`);
|
|
104
126
|
}
|
|
105
127
|
try {
|
|
128
|
+
const resolvedAuthHeaders = await resolveCodeApiAuthHeaders(authHeaders);
|
|
106
129
|
const fetchOptions = {
|
|
107
130
|
method: 'POST',
|
|
108
131
|
headers: {
|
|
109
132
|
'Content-Type': 'application/json',
|
|
110
133
|
'User-Agent': 'LibreChat/1.0',
|
|
134
|
+
...resolvedAuthHeaders,
|
|
111
135
|
},
|
|
112
136
|
body: JSON.stringify(postData),
|
|
113
137
|
};
|
|
@@ -116,7 +140,7 @@ function createCodeExecutionTool(params = {}) {
|
|
|
116
140
|
}
|
|
117
141
|
const response = await fetch(EXEC_ENDPOINT, fetchOptions);
|
|
118
142
|
if (!response.ok) {
|
|
119
|
-
throw new Error(
|
|
143
|
+
throw new Error(await buildCodeApiHttpErrorMessage('POST', EXEC_ENDPOINT, response));
|
|
120
144
|
}
|
|
121
145
|
const result = await response.json();
|
|
122
146
|
/* Output is stdout/stderr only — file listings were removed
|
|
@@ -156,5 +180,5 @@ function createCodeExecutionTool(params = {}) {
|
|
|
156
180
|
});
|
|
157
181
|
}
|
|
158
182
|
|
|
159
|
-
export { CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, createCodeExecutionTool, emptyOutputMessage, getCodeBaseURL };
|
|
183
|
+
export { CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, buildCodeApiHttpErrorMessage, createCodeExecutionTool, emptyOutputMessage, getCodeBaseURL, resolveCodeApiAuthHeaders };
|
|
160
184
|
//# sourceMappingURL=CodeExecutor.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodeExecutor.mjs","sources":["../../../src/tools/CodeExecutor.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport type * as t from '@/types';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\nexport const getCodeBaseURL = (): string =>\n getEnvironmentVariable(EnvVar.CODE_BASEURL) ??\n Constants.OFFICIAL_CODE_BASEURL;\n\nexport const emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\nconst SUPPORTED_LANGUAGES = [\n 'py',\n 'js',\n 'ts',\n 'c',\n 'cpp',\n 'java',\n 'php',\n 'rs',\n 'go',\n 'd',\n 'f90',\n 'r',\n 'bash',\n] as const;\n\nexport const CodeExecutionToolSchema = {\n type: 'object',\n properties: {\n lang: {\n type: 'string',\n enum: SUPPORTED_LANGUAGES,\n description:\n 'The programming language or runtime to execute the code in.',\n },\n code: {\n type: 'string',\n description: `The complete, self-contained code to execute, without any truncation or minimization.\n- The environment is stateless; variables and imports don't persist between executions.\n- Generated files from previous executions are automatically available in \"/mnt/data/\".\n- Files from previous executions are automatically available and can be modified in place.\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- py: This is not a Jupyter notebook environment. Use \\`print()\\` for all outputs.\n- py: Matplotlib: Use \\`plt.savefig()\\` to save plots as files.\n- js: use the \\`console\\` or \\`process\\` methods for all outputs.\n- r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).\n- Other languages: use appropriate output functions.`,\n },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Additional arguments to execute the code with. This should only be used if the input code requires additional arguments to run.',\n },\n },\n required: ['lang', 'code'],\n} as const;\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\ntype SupportedLanguage = (typeof SUPPORTED_LANGUAGES)[number];\n\nexport const CodeExecutionToolDescription = `\nRuns code and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- NEVER use this tool to execute malicious code.\n`.trim();\n\nexport const CodeExecutionToolName = Constants.EXECUTE_CODE;\n\nexport const CodeExecutionToolDefinition = {\n name: CodeExecutionToolName,\n description: CodeExecutionToolDescription,\n schema: CodeExecutionToolSchema,\n} as const;\n\nfunction createCodeExecutionTool(\n params: t.CodeExecutionToolParams = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput, config) => {\n const { lang, code, ...rest } = rawInput as {\n lang: SupportedLanguage;\n code: string;\n args?: string[];\n };\n /**\n * Extract session context from config.toolCall (injected by ToolNode).\n * - session_id: associates with the previous run.\n * - _injected_files: File refs to pass directly (avoids /files endpoint race condition).\n */\n const { session_id, _injected_files } = (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n const postData: Record<string, unknown> = {\n lang,\n code,\n ...rest,\n ...params,\n };\n\n /* File injection: `_injected_files` from ToolNode (set when host\n * primes a CodeSessionContext) or `params.files` from tool\n * factory (set by hosts that pre-resolve at construction time).\n * The legacy `/files/<session_id>` HTTP fallback was removed —\n * codeapi's `sessionAuth` middleware now requires kind/id query\n * params the tool can't supply at this point, so the fetch 400'd\n * silently and the catch swallowed the failure. */\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (\n session_id != null &&\n session_id.length > 0 &&\n !Array.isArray(postData.files)\n ) {\n // eslint-disable-next-line no-console\n console.debug(\n `[CodeExecutor] No injected files for session_id=${session_id} — exec will run without input files`\n );\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 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 /* Output is stdout/stderr only — file listings were removed\n * because the LLM-facing summary (split inherited/generated\n * with prescriptive notes) caused more confusion than help,\n * especially for bash where models naturally explore\n * `/mnt/data/` themselves. The artifact still carries every\n * file so the host's session map stays in sync; the LLM\n * doesn't see them in the tool result text. */\n let formattedOutput = '';\n if (result.stdout) {\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\n } else {\n formattedOutput += emptyOutputMessage;\n }\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\n\n const hasFiles = result.files != null && result.files.length > 0;\n return [\n formattedOutput.trim(),\n (hasFiles\n ? { session_id: result.session_id, files: result.files }\n : {\n session_id: result.session_id,\n }) satisfies t.CodeExecutionArtifact,\n ];\n } catch (error) {\n throw new Error(\n `Execution error:\\n\\n${(error as Error | undefined)?.message}`\n );\n }\n },\n {\n name: CodeExecutionToolName,\n description: CodeExecutionToolDescription,\n schema: CodeExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createCodeExecutionTool };\n"],"names":[],"mappings":";;;;;;;AAQA,MAAM,EAAE;AAED,MAAM,cAAc,GAAG,MAC5B,sBAAsB,CAAC,MAAM,CAAC,YAAY,CAAC;IAC3C,SAAS,CAAC;AAEL,MAAM,kBAAkB,GAC7B;AAEF,MAAM,mBAAmB,GAAG;IAC1B,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,GAAG;IACH,KAAK;IACL,MAAM;IACN,KAAK;IACL,IAAI;IACJ,IAAI;IACJ,GAAG;IACH,KAAK;IACL,GAAG;IACH,MAAM;CACE;AAEH,MAAM,uBAAuB,GAAG;AACrC,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,IAAI,EAAE,mBAAmB;AACzB,YAAA,WAAW,EACT,6DAA6D;AAChE,SAAA;AACD,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EAAE,CAAA;;;;;;;;;;;AAWkC,oDAAA,CAAA;AAChD,SAAA;AACD,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,OAAO;AACb,YAAA,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;AACzB,YAAA,WAAW,EACT,iIAAiI;AACpI,SAAA;AACF,KAAA;AACD,IAAA,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC;;AAG5B,MAAM,YAAY,GAAG,cAAc,EAAE;AACrC,MAAM,aAAa,GAAG,CAAA,EAAG,YAAY,OAAO;AAIrC,MAAM,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AAqB;AAC3B,QAAA,WAAW,EAAE,4BAA4B;AACzC,QAAA,MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"CodeExecutor.mjs","sources":["../../../src/tools/CodeExecutor.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport type * as t from '@/types';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\nexport const getCodeBaseURL = (): string =>\n getEnvironmentVariable(EnvVar.CODE_BASEURL) ??\n Constants.OFFICIAL_CODE_BASEURL;\n\nexport const emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\nconst SUPPORTED_LANGUAGES = [\n 'py',\n 'js',\n 'ts',\n 'c',\n 'cpp',\n 'java',\n 'php',\n 'rs',\n 'go',\n 'd',\n 'f90',\n 'r',\n 'bash',\n] as const;\n\nexport const CodeExecutionToolSchema = {\n type: 'object',\n properties: {\n lang: {\n type: 'string',\n enum: SUPPORTED_LANGUAGES,\n description:\n 'The programming language or runtime to execute the code in.',\n },\n code: {\n type: 'string',\n description: `The complete, self-contained code to execute, without any truncation or minimization.\n- The environment is stateless; variables and imports don't persist between executions.\n- Generated files from previous executions are automatically available in \"/mnt/data/\".\n- Files from previous executions are automatically available and can be modified in place.\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- py: This is not a Jupyter notebook environment. Use \\`print()\\` for all outputs.\n- py: Matplotlib: Use \\`plt.savefig()\\` to save plots as files.\n- js: use the \\`console\\` or \\`process\\` methods for all outputs.\n- r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).\n- Other languages: use appropriate output functions.`,\n },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Additional arguments to execute the code with. This should only be used if the input code requires additional arguments to run.',\n },\n },\n required: ['lang', 'code'],\n} as const;\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\ntype SupportedLanguage = (typeof SUPPORTED_LANGUAGES)[number];\n\nexport async function resolveCodeApiAuthHeaders(\n authHeaders?: t.CodeApiAuthHeaders\n): Promise<t.CodeApiAuthHeaderMap> {\n if (authHeaders == null) {\n return {};\n }\n if (typeof authHeaders === 'function') {\n return authHeaders();\n }\n return authHeaders;\n}\n\nexport async function buildCodeApiHttpErrorMessage(\n method: string,\n endpoint: string,\n response: { status: number; text: () => Promise<string> }\n): Promise<string> {\n let responseBody = '';\n try {\n responseBody = await response.text();\n } catch {\n responseBody = '';\n }\n const body = responseBody.trim();\n const bodySuffix = body === '' ? '' : `, body: ${body.slice(0, 1000)}`;\n return `CodeAPI request failed: ${method} ${endpoint} returned ${response.status}${bodySuffix}`;\n}\n\nexport const CodeExecutionToolDescription = `\nRuns code and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- NEVER use this tool to execute malicious code.\n`.trim();\n\nexport const CodeExecutionToolName = Constants.EXECUTE_CODE;\n\nexport const CodeExecutionToolDefinition = {\n name: CodeExecutionToolName,\n description: CodeExecutionToolDescription,\n schema: CodeExecutionToolSchema,\n} as const;\n\nfunction createCodeExecutionTool(\n params: t.CodeExecutionToolParams = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput, config) => {\n const { authHeaders, ...executionParams } = params ?? {};\n const { lang, code, ...rest } = rawInput as {\n lang: SupportedLanguage;\n code: string;\n args?: string[];\n };\n /**\n * Extract session context from config.toolCall (injected by ToolNode).\n * - session_id: associates with the previous run.\n * - _injected_files: File refs to pass directly (avoids /files endpoint race condition).\n */\n const { session_id, _injected_files } = (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n const postData: Record<string, unknown> = {\n lang,\n code,\n ...rest,\n ...executionParams,\n };\n\n /* File injection: `_injected_files` from ToolNode (set when host\n * primes a CodeSessionContext) or `params.files` from tool\n * factory (set by hosts that pre-resolve at construction time).\n * The legacy `/files/<session_id>` HTTP fallback was removed —\n * codeapi's `sessionAuth` middleware now requires kind/id query\n * params the tool can't supply at this point, so the fetch 400'd\n * silently and the catch swallowed the failure. */\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (\n session_id != null &&\n session_id.length > 0 &&\n !Array.isArray(postData.files)\n ) {\n // eslint-disable-next-line no-console\n console.debug(\n `[CodeExecutor] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n try {\n const resolvedAuthHeaders =\n await resolveCodeApiAuthHeaders(authHeaders);\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n ...resolvedAuthHeaders,\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 const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(\n await buildCodeApiHttpErrorMessage('POST', EXEC_ENDPOINT, response)\n );\n }\n\n const result: t.ExecuteResult = await response.json();\n /* Output is stdout/stderr only — file listings were removed\n * because the LLM-facing summary (split inherited/generated\n * with prescriptive notes) caused more confusion than help,\n * especially for bash where models naturally explore\n * `/mnt/data/` themselves. The artifact still carries every\n * file so the host's session map stays in sync; the LLM\n * doesn't see them in the tool result text. */\n let formattedOutput = '';\n if (result.stdout) {\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\n } else {\n formattedOutput += emptyOutputMessage;\n }\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\n\n const hasFiles = result.files != null && result.files.length > 0;\n return [\n formattedOutput.trim(),\n (hasFiles\n ? { session_id: result.session_id, files: result.files }\n : {\n session_id: result.session_id,\n }) satisfies t.CodeExecutionArtifact,\n ];\n } catch (error) {\n throw new Error(\n `Execution error:\\n\\n${(error as Error | undefined)?.message}`\n );\n }\n },\n {\n name: CodeExecutionToolName,\n description: CodeExecutionToolDescription,\n schema: CodeExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createCodeExecutionTool };\n"],"names":[],"mappings":";;;;;;;AAQA,MAAM,EAAE;AAED,MAAM,cAAc,GAAG,MAC5B,sBAAsB,CAAC,MAAM,CAAC,YAAY,CAAC;IAC3C,SAAS,CAAC;AAEL,MAAM,kBAAkB,GAC7B;AAEF,MAAM,mBAAmB,GAAG;IAC1B,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,GAAG;IACH,KAAK;IACL,MAAM;IACN,KAAK;IACL,IAAI;IACJ,IAAI;IACJ,GAAG;IACH,KAAK;IACL,GAAG;IACH,MAAM;CACE;AAEH,MAAM,uBAAuB,GAAG;AACrC,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,IAAI,EAAE,mBAAmB;AACzB,YAAA,WAAW,EACT,6DAA6D;AAChE,SAAA;AACD,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EAAE,CAAA;;;;;;;;;;;AAWkC,oDAAA,CAAA;AAChD,SAAA;AACD,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,OAAO;AACb,YAAA,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;AACzB,YAAA,WAAW,EACT,iIAAiI;AACpI,SAAA;AACF,KAAA;AACD,IAA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|
@@ -2,15 +2,15 @@ import { config } from 'dotenv';
|
|
|
2
2
|
import fetch from 'node-fetch';
|
|
3
3
|
import { HttpsProxyAgent } from 'https-proxy-agent';
|
|
4
4
|
import { tool } from '@langchain/core/tools';
|
|
5
|
-
import { getCodeBaseURL, emptyOutputMessage } from './CodeExecutor.mjs';
|
|
5
|
+
import { getCodeBaseURL, resolveCodeApiAuthHeaders, buildCodeApiHttpErrorMessage, emptyOutputMessage } from './CodeExecutor.mjs';
|
|
6
|
+
import { resolveCodeApiRunTimeoutMs, createCodeApiRunTimeoutSchema, clampCodeApiRunTimeoutMs } from './ptcTimeout.mjs';
|
|
6
7
|
import { Constants } from '../common/enum.mjs';
|
|
7
8
|
|
|
8
9
|
// src/tools/ProgrammaticToolCalling.ts
|
|
9
10
|
config();
|
|
10
11
|
/** Default max round-trips to prevent infinite loops */
|
|
11
12
|
const DEFAULT_MAX_ROUND_TRIPS = 20;
|
|
12
|
-
|
|
13
|
-
const DEFAULT_TIMEOUT = 60000;
|
|
13
|
+
const DEFAULT_RUN_TIMEOUT_MS = resolveCodeApiRunTimeoutMs();
|
|
14
14
|
// ============================================================================
|
|
15
15
|
// Description Components (Single Source of Truth)
|
|
16
16
|
// ============================================================================
|
|
@@ -23,7 +23,8 @@ const CORE_RULES = `Rules:
|
|
|
23
23
|
- Just write code with await—auto-wrapped in async context
|
|
24
24
|
- DO NOT define async def main() or call asyncio.run()
|
|
25
25
|
- Tools are pre-defined—DO NOT write function definitions
|
|
26
|
-
- Only print() output returns to the model
|
|
26
|
+
- Only print() output returns to the model
|
|
27
|
+
- timeout caps one sandbox run/replay iteration, not the total multi-round-trip workflow`;
|
|
27
28
|
const ADDITIONAL_RULES = `- Generated files are automatically available in /mnt/data/ for subsequent executions
|
|
28
29
|
- Tool names normalized: hyphens→underscores, keywords get \`_tool\` suffix`;
|
|
29
30
|
const EXAMPLES = `Example (Complete workflow in one call):
|
|
@@ -51,24 +52,21 @@ Your code is auto-wrapped in async context. Just write logic with await—no boi
|
|
|
51
52
|
${EXAMPLES}
|
|
52
53
|
|
|
53
54
|
${CORE_RULES}`;
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
minimum: 1000,
|
|
65
|
-
maximum: 300000,
|
|
66
|
-
default: DEFAULT_TIMEOUT,
|
|
67
|
-
description: 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.',
|
|
55
|
+
function createProgrammaticToolCallingSchema(maxRunTimeoutMs = DEFAULT_RUN_TIMEOUT_MS) {
|
|
56
|
+
return {
|
|
57
|
+
type: 'object',
|
|
58
|
+
properties: {
|
|
59
|
+
code: {
|
|
60
|
+
type: 'string',
|
|
61
|
+
minLength: 1,
|
|
62
|
+
description: CODE_PARAM_DESCRIPTION,
|
|
63
|
+
},
|
|
64
|
+
timeout: createCodeApiRunTimeoutSchema(maxRunTimeoutMs),
|
|
68
65
|
},
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
}
|
|
66
|
+
required: ['code'],
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
const ProgrammaticToolCallingSchema = createProgrammaticToolCallingSchema();
|
|
72
70
|
const ProgrammaticToolCallingName = Constants.PROGRAMMATIC_TOOL_CALLING;
|
|
73
71
|
const ProgrammaticToolCallingDescription = `
|
|
74
72
|
Run tools via Python code. Auto-wrapped in async context—just use \`await\` directly.
|
|
@@ -128,6 +126,71 @@ const PYTHON_KEYWORDS = new Set([
|
|
|
128
126
|
'with',
|
|
129
127
|
'yield',
|
|
130
128
|
]);
|
|
129
|
+
function isFetchSessionFilesScope(value) {
|
|
130
|
+
if (value == null || typeof value !== 'object') {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
const scope = value;
|
|
134
|
+
if ((scope.kind === 'agent' || scope.kind === 'user') &&
|
|
135
|
+
typeof scope.id === 'string') {
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
return (scope.kind === 'skill' &&
|
|
139
|
+
typeof scope.id === 'string' &&
|
|
140
|
+
typeof scope.version === 'number');
|
|
141
|
+
}
|
|
142
|
+
function isCodeApiAuthHeaders(value) {
|
|
143
|
+
return value != null && typeof value !== 'string';
|
|
144
|
+
}
|
|
145
|
+
function isCodeApiSessionFileWire(value) {
|
|
146
|
+
return value != null && typeof value === 'object';
|
|
147
|
+
}
|
|
148
|
+
function isCodeApiSessionFileMetadata(value) {
|
|
149
|
+
return value != null && typeof value === 'object';
|
|
150
|
+
}
|
|
151
|
+
function normalizeSessionFile(file, sessionId, scope) {
|
|
152
|
+
const metadata = isCodeApiSessionFileMetadata(file.metadata)
|
|
153
|
+
? file.metadata
|
|
154
|
+
: undefined;
|
|
155
|
+
const rawName = typeof file.name === 'string' ? file.name : '';
|
|
156
|
+
const nameParts = rawName.split('/');
|
|
157
|
+
const fallbackId = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';
|
|
158
|
+
const id = typeof file.id === 'string' && file.id !== '' ? file.id : fallbackId;
|
|
159
|
+
const originalFilename = metadata?.['original-filename'];
|
|
160
|
+
const name = typeof originalFilename === 'string' ? originalFilename : rawName;
|
|
161
|
+
const storage_session_id = typeof file.storage_session_id === 'string'
|
|
162
|
+
? file.storage_session_id
|
|
163
|
+
: sessionId;
|
|
164
|
+
const resource_id = typeof file.resource_id === 'string' && file.resource_id !== ''
|
|
165
|
+
? file.resource_id
|
|
166
|
+
: (scope?.id ?? id);
|
|
167
|
+
if (scope?.kind === 'skill') {
|
|
168
|
+
return {
|
|
169
|
+
storage_session_id,
|
|
170
|
+
kind: 'skill',
|
|
171
|
+
id,
|
|
172
|
+
resource_id,
|
|
173
|
+
name,
|
|
174
|
+
version: scope.version,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
if (scope != null) {
|
|
178
|
+
return {
|
|
179
|
+
storage_session_id,
|
|
180
|
+
kind: scope.kind,
|
|
181
|
+
id,
|
|
182
|
+
resource_id,
|
|
183
|
+
name,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
storage_session_id,
|
|
188
|
+
kind: 'user',
|
|
189
|
+
id,
|
|
190
|
+
resource_id: id,
|
|
191
|
+
name,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
131
194
|
/**
|
|
132
195
|
* Normalizes a tool name to Python identifier format.
|
|
133
196
|
* Must match the Code API's `normalizePythonFunctionName` exactly:
|
|
@@ -199,21 +262,41 @@ function filterToolsByUsage(toolDefs, code, debug = false) {
|
|
|
199
262
|
}
|
|
200
263
|
return toolDefs.filter((tool) => usedToolNames.has(tool.name));
|
|
201
264
|
}
|
|
202
|
-
|
|
203
|
-
* Fetches files from a previous session to make them available for the current execution.
|
|
204
|
-
* Files are returned as CodeEnvFile references to be included in the request.
|
|
205
|
-
* @param baseUrl - The base URL for the Code API
|
|
206
|
-
* @param sessionId - The session ID to fetch files from
|
|
207
|
-
* @param proxy - Optional HTTP proxy URL
|
|
208
|
-
* @returns Array of CodeEnvFile references, or empty array if fetch fails
|
|
209
|
-
*/
|
|
210
|
-
async function fetchSessionFiles(baseUrl, sessionId, proxy) {
|
|
265
|
+
async function fetchSessionFiles(baseUrl, sessionId, scopeOrProxy, proxyOrAuthHeaders, scopedAuthHeaders) {
|
|
211
266
|
try {
|
|
212
|
-
const
|
|
267
|
+
const scope = isFetchSessionFilesScope(scopeOrProxy)
|
|
268
|
+
? scopeOrProxy
|
|
269
|
+
: undefined;
|
|
270
|
+
let proxy;
|
|
271
|
+
let authHeaders;
|
|
272
|
+
if (scope == null) {
|
|
273
|
+
proxy = typeof scopeOrProxy === 'string' ? scopeOrProxy : undefined;
|
|
274
|
+
authHeaders = isCodeApiAuthHeaders(proxyOrAuthHeaders)
|
|
275
|
+
? proxyOrAuthHeaders
|
|
276
|
+
: undefined;
|
|
277
|
+
}
|
|
278
|
+
else if (typeof proxyOrAuthHeaders === 'string') {
|
|
279
|
+
proxy = proxyOrAuthHeaders;
|
|
280
|
+
authHeaders = scopedAuthHeaders;
|
|
281
|
+
}
|
|
282
|
+
else {
|
|
283
|
+
authHeaders = proxyOrAuthHeaders ?? scopedAuthHeaders;
|
|
284
|
+
}
|
|
285
|
+
const query = new URLSearchParams({ detail: 'full' });
|
|
286
|
+
if (scope != null) {
|
|
287
|
+
query.set('kind', scope.kind);
|
|
288
|
+
query.set('id', scope.id);
|
|
289
|
+
if (scope.kind === 'skill') {
|
|
290
|
+
query.set('version', String(scope.version));
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
const filesEndpoint = `${baseUrl}/files/${encodeURIComponent(sessionId)}?${query.toString()}`;
|
|
294
|
+
const resolvedAuthHeaders = await resolveCodeApiAuthHeaders(authHeaders);
|
|
213
295
|
const fetchOptions = {
|
|
214
296
|
method: 'GET',
|
|
215
297
|
headers: {
|
|
216
298
|
'User-Agent': 'LibreChat/1.0',
|
|
299
|
+
...resolvedAuthHeaders,
|
|
217
300
|
},
|
|
218
301
|
};
|
|
219
302
|
if (proxy != null && proxy !== '') {
|
|
@@ -221,28 +304,15 @@ async function fetchSessionFiles(baseUrl, sessionId, proxy) {
|
|
|
221
304
|
}
|
|
222
305
|
const response = await fetch(filesEndpoint, fetchOptions);
|
|
223
306
|
if (!response.ok) {
|
|
224
|
-
throw new Error(
|
|
307
|
+
throw new Error(await buildCodeApiHttpErrorMessage('GET', filesEndpoint, response));
|
|
225
308
|
}
|
|
226
309
|
const files = await response.json();
|
|
227
310
|
if (!Array.isArray(files) || files.length === 0) {
|
|
228
311
|
return [];
|
|
229
312
|
}
|
|
230
|
-
return files
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';
|
|
234
|
-
return {
|
|
235
|
-
storage_session_id: sessionId,
|
|
236
|
-
/* `/files` fallback returns code-output files belonging to
|
|
237
|
-
* the user; tag them user-private. */
|
|
238
|
-
kind: 'user',
|
|
239
|
-
id,
|
|
240
|
-
/* `resource_id` informational for `kind: 'user'` —
|
|
241
|
-
* codeapi derives sessionKey from auth context. */
|
|
242
|
-
resource_id: id,
|
|
243
|
-
name: file.metadata['original-filename'],
|
|
244
|
-
};
|
|
245
|
-
});
|
|
313
|
+
return files
|
|
314
|
+
.filter(isCodeApiSessionFileWire)
|
|
315
|
+
.map((file) => normalizeSessionFile(file, sessionId, scope));
|
|
246
316
|
}
|
|
247
317
|
catch (error) {
|
|
248
318
|
// eslint-disable-next-line no-console
|
|
@@ -257,12 +327,14 @@ async function fetchSessionFiles(baseUrl, sessionId, proxy) {
|
|
|
257
327
|
* @param proxy - Optional HTTP proxy URL
|
|
258
328
|
* @returns The parsed API response
|
|
259
329
|
*/
|
|
260
|
-
async function makeRequest(endpoint, body, proxy) {
|
|
330
|
+
async function makeRequest(endpoint, body, proxy, authHeaders) {
|
|
331
|
+
const resolvedAuthHeaders = await resolveCodeApiAuthHeaders(authHeaders);
|
|
261
332
|
const fetchOptions = {
|
|
262
333
|
method: 'POST',
|
|
263
334
|
headers: {
|
|
264
335
|
'Content-Type': 'application/json',
|
|
265
336
|
'User-Agent': 'LibreChat/1.0',
|
|
337
|
+
...resolvedAuthHeaders,
|
|
266
338
|
},
|
|
267
339
|
body: JSON.stringify(body),
|
|
268
340
|
};
|
|
@@ -271,8 +343,7 @@ async function makeRequest(endpoint, body, proxy) {
|
|
|
271
343
|
}
|
|
272
344
|
const response = await fetch(endpoint, fetchOptions);
|
|
273
345
|
if (!response.ok) {
|
|
274
|
-
|
|
275
|
-
throw new Error(`HTTP error! status: ${response.status}, body: ${errorText}`);
|
|
346
|
+
throw new Error(await buildCodeApiHttpErrorMessage('POST', endpoint, response));
|
|
276
347
|
}
|
|
277
348
|
return (await response.json());
|
|
278
349
|
}
|
|
@@ -397,7 +468,7 @@ function unwrapToolResponse(result, isMCPTool) {
|
|
|
397
468
|
* @param toolMap - Map of tool names to executable tools
|
|
398
469
|
* @returns Array of tool results
|
|
399
470
|
*/
|
|
400
|
-
async function executeTools(toolCalls, toolMap) {
|
|
471
|
+
async function executeTools(toolCalls, toolMap, programmaticToolName = Constants.PROGRAMMATIC_TOOL_CALLING) {
|
|
401
472
|
const executions = toolCalls.map(async (call) => {
|
|
402
473
|
const tool = toolMap.get(call.name);
|
|
403
474
|
if (!tool) {
|
|
@@ -410,7 +481,7 @@ async function executeTools(toolCalls, toolMap) {
|
|
|
410
481
|
}
|
|
411
482
|
try {
|
|
412
483
|
const result = await tool.invoke(call.input, {
|
|
413
|
-
metadata: { [
|
|
484
|
+
metadata: { [programmaticToolName]: true },
|
|
414
485
|
});
|
|
415
486
|
const isMCPTool = tool.mcp === true;
|
|
416
487
|
const unwrappedResult = unwrapToolResponse(result, isMCPTool);
|
|
@@ -485,12 +556,14 @@ function formatCompletedResponse(response) {
|
|
|
485
556
|
function createProgrammaticToolCallingTool(initParams = {}) {
|
|
486
557
|
const baseUrl = initParams.baseUrl ?? getCodeBaseURL();
|
|
487
558
|
const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;
|
|
559
|
+
const maxRunTimeoutMs = resolveCodeApiRunTimeoutMs(initParams.runTimeoutMs);
|
|
488
560
|
const proxy = initParams.proxy ?? process.env.PROXY;
|
|
489
561
|
const debug = initParams.debug ?? process.env.PTC_DEBUG === 'true';
|
|
490
562
|
const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;
|
|
491
563
|
return tool(async (rawParams, config) => {
|
|
492
564
|
const params = rawParams;
|
|
493
|
-
const { code
|
|
565
|
+
const { code } = params;
|
|
566
|
+
const timeout = clampCodeApiRunTimeoutMs(params.timeout, maxRunTimeoutMs);
|
|
494
567
|
// Extra params injected by ToolNode (follows web_search pattern).
|
|
495
568
|
const toolCall = (config.toolCall ?? {});
|
|
496
569
|
const { toolMap, toolDefs, session_id, _injected_files } = toolCall;
|
|
@@ -533,7 +606,7 @@ function createProgrammaticToolCallingTool(initParams = {}) {
|
|
|
533
606
|
session_id,
|
|
534
607
|
timeout,
|
|
535
608
|
...(files && files.length > 0 ? { files } : {}),
|
|
536
|
-
}, proxy);
|
|
609
|
+
}, proxy, initParams.authHeaders);
|
|
537
610
|
// ====================================================================
|
|
538
611
|
// Phase 2: Handle response loop
|
|
539
612
|
// ====================================================================
|
|
@@ -552,7 +625,7 @@ function createProgrammaticToolCallingTool(initParams = {}) {
|
|
|
552
625
|
response = await makeRequest(EXEC_ENDPOINT, {
|
|
553
626
|
continuation_token: response.continuation_token,
|
|
554
627
|
tool_results: toolResults,
|
|
555
|
-
}, proxy);
|
|
628
|
+
}, proxy, initParams.authHeaders);
|
|
556
629
|
}
|
|
557
630
|
// ====================================================================
|
|
558
631
|
// Phase 3: Handle final state
|
|
@@ -574,10 +647,10 @@ function createProgrammaticToolCallingTool(initParams = {}) {
|
|
|
574
647
|
}, {
|
|
575
648
|
name: Constants.PROGRAMMATIC_TOOL_CALLING,
|
|
576
649
|
description: ProgrammaticToolCallingDescription,
|
|
577
|
-
schema:
|
|
650
|
+
schema: createProgrammaticToolCallingSchema(maxRunTimeoutMs),
|
|
578
651
|
responseFormat: Constants.CONTENT_AND_ARTIFACT,
|
|
579
652
|
});
|
|
580
653
|
}
|
|
581
654
|
|
|
582
|
-
export { ProgrammaticToolCallingDefinition, ProgrammaticToolCallingDescription, ProgrammaticToolCallingName, ProgrammaticToolCallingSchema, createProgrammaticToolCallingTool, executeTools, extractUsedToolNames, fetchSessionFiles, filterToolsByUsage, formatCompletedResponse, makeRequest, normalizeToPythonIdentifier, unwrapToolResponse };
|
|
655
|
+
export { ProgrammaticToolCallingDefinition, ProgrammaticToolCallingDescription, ProgrammaticToolCallingName, ProgrammaticToolCallingSchema, createProgrammaticToolCallingSchema, createProgrammaticToolCallingTool, executeTools, extractUsedToolNames, fetchSessionFiles, filterToolsByUsage, formatCompletedResponse, makeRequest, normalizeToPythonIdentifier, unwrapToolResponse };
|
|
583
656
|
//# sourceMappingURL=ProgrammaticToolCalling.mjs.map
|