@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.
Files changed (75) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +26 -3
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +1 -0
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/events.cjs +2 -1
  6. package/dist/cjs/events.cjs.map +1 -1
  7. package/dist/cjs/graphs/Graph.cjs +5 -1
  8. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  9. package/dist/cjs/graphs/MultiAgentGraph.cjs +3 -2
  10. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  11. package/dist/cjs/main.cjs +4 -0
  12. package/dist/cjs/main.cjs.map +1 -1
  13. package/dist/cjs/tools/BashExecutor.cjs +5 -2
  14. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  15. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +26 -24
  16. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  17. package/dist/cjs/tools/CodeExecutor.cjs +28 -2
  18. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  19. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +130 -56
  20. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  21. package/dist/cjs/tools/ToolNode.cjs +7 -5
  22. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  23. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs +52 -13
  24. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs.map +1 -1
  25. package/dist/cjs/tools/ptcTimeout.cjs +56 -0
  26. package/dist/cjs/tools/ptcTimeout.cjs.map +1 -0
  27. package/dist/esm/agents/AgentContext.mjs +27 -4
  28. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  29. package/dist/esm/common/enum.mjs +1 -0
  30. package/dist/esm/common/enum.mjs.map +1 -1
  31. package/dist/esm/events.mjs +2 -1
  32. package/dist/esm/events.mjs.map +1 -1
  33. package/dist/esm/graphs/Graph.mjs +5 -1
  34. package/dist/esm/graphs/Graph.mjs.map +1 -1
  35. package/dist/esm/graphs/MultiAgentGraph.mjs +3 -2
  36. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  37. package/dist/esm/main.mjs +3 -3
  38. package/dist/esm/tools/BashExecutor.mjs +6 -3
  39. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  40. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +26 -25
  41. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  42. package/dist/esm/tools/CodeExecutor.mjs +27 -3
  43. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  44. package/dist/esm/tools/ProgrammaticToolCalling.mjs +131 -58
  45. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  46. package/dist/esm/tools/ToolNode.mjs +7 -5
  47. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  48. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs +54 -15
  49. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs.map +1 -1
  50. package/dist/esm/tools/ptcTimeout.mjs +50 -0
  51. package/dist/esm/tools/ptcTimeout.mjs.map +1 -0
  52. package/dist/types/agents/AgentContext.d.ts +3 -1
  53. package/dist/types/common/enum.d.ts +2 -1
  54. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +4 -36
  55. package/dist/types/tools/CodeExecutor.d.ts +5 -0
  56. package/dist/types/tools/ProgrammaticToolCalling.d.ts +18 -39
  57. package/dist/types/tools/ptcTimeout.d.ts +25 -0
  58. package/dist/types/types/tools.d.ts +8 -0
  59. package/package.json +1 -1
  60. package/src/agents/AgentContext.ts +32 -3
  61. package/src/agents/__tests__/AgentContext.test.ts +36 -3
  62. package/src/common/enum.ts +1 -0
  63. package/src/events.ts +4 -1
  64. package/src/graphs/MultiAgentGraph.ts +3 -2
  65. package/src/graphs/__tests__/composition.smoke.test.ts +84 -2
  66. package/src/tools/BashExecutor.ts +14 -3
  67. package/src/tools/BashProgrammaticToolCalling.ts +37 -25
  68. package/src/tools/CodeExecutor.ts +36 -2
  69. package/src/tools/ProgrammaticToolCalling.ts +206 -53
  70. package/src/tools/ToolNode.ts +3 -4
  71. package/src/tools/__tests__/CodeApiAuthHeaders.test.ts +424 -0
  72. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +31 -1
  73. package/src/tools/local/LocalProgrammaticToolCalling.ts +94 -13
  74. package/src/tools/ptcTimeout.ts +89 -0
  75. package/src/types/tools.ts +12 -0
@@ -1 +1 @@
1
- {"version":3,"file":"BashProgrammaticToolCalling.cjs","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":["config","Constants","getCodeBaseURL","tool","makeRequest","executeTools","formatCompletedResponse"],"mappings":";;;;;;;;AAYAA,aAAM,EAAE;AAER;AACA;AACA;AAEA,MAAM,uBAAuB,GAAG,EAAE;AAClC,MAAM,eAAe,GAAG,KAAK;AAE7B;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;IACN,QAAQ;IACR,SAAS;IACT,SAAS;IACT,OAAO;IACP,UAAU;IACV,QAAQ;IACR,OAAO;AACR,CAAA,CAAC;AAEF;AACA;AACA;AAEA,MAAM,iBAAiB,GAAG,CAAA;;;sEAG4C;AAEtE,MAAM,UAAU,GAAG,CAAA;;;;;sFAKmE;AAEtF,MAAM,gBAAgB,GACpB,iFAAiF;AAEnF,MAAM,QAAQ,GAAG,CAAA;;;;;;;;;;gCAUe;AAEhC,MAAM,sBAAsB,GAAG,CAAA;;EAE7B,iBAAiB;;;;;EAKjB,QAAQ;;AAER,EAAA,UAAU,EAAE;AAEd;AACA;AACA;AAEO,MAAM,iCAAiC,GAAG;AAC/C,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,SAAS,EAAE,CAAC;AACZ,YAAA,WAAW,EAAE,sBAAsB;AACpC,SAAA;AACD,QAAA,OAAO,EAAE;AACP,YAAA,IAAI,EAAE,SAAS;AACf,YAAA,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CACR;AAED,gBAAA,QAAQ,GAAG,MAAMD,mCAAW,CAC1B,aAAa,EACb;oBACE,kBAAkB,EAAE,QAAQ,CAAC,kBAAkB;AAC/C,oBAAA,YAAY,EAAE,WAAW;iBAC1B,EACD,KAAK,CACN;YACH;;;;AAMA,YAAA,IAAI,QAAQ,CAAC,MAAM,KAAK,WAAW,EAAE;AACnC,gBAAA,OAAOE,+CAAuB,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,EAAEL,eAAS,CAAC,8BAA8B;AAC9C,QAAA,WAAW,EAAE,sCAAsC;AACnD,QAAA,MAAM,EAAE,iCAAiC;QACzC,cAAc,EAAEA,eAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;;;;;;;;"}
1
+ {"version":3,"file":"BashProgrammaticToolCalling.cjs","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":["config","resolveCodeApiRunTimeoutMs","createCodeApiRunTimeoutSchema","Constants","getCodeBaseURL","tool","clampCodeApiRunTimeoutMs","makeRequest","executeTools","formatC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;oBACE,kBAAkB,EAAE,QAAQ,CAAC,kBAAkB;AAC/C,oBAAA,YAAY,EAAE,WAAW;AAC1B,iBAAA,EACD,KAAK,EACL,UAAU,CAAC,WAAW,CACvB;YACH;;;;AAMA,YAAA,IAAI,QAAQ,CAAC,MAAM,KAAK,WAAW,EAAE;AACnC,gBAAA,OAAOE,+CAAuB,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,EAAEN,eAAS,CAAC,8BAA8B;AAC9C,QAAA,WAAW,EAAE,sCAAsC;AACnD,QAAA,MAAM,EAAE,uCAAuC,CAAC,eAAe,CAAC;QAChE,cAAc,EAAEA,eAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;;;;;;;;;"}
@@ -59,6 +59,27 @@ const CodeExecutionToolSchema = {
59
59
  };
60
60
  const baseEndpoint = getCodeBaseURL();
61
61
  const EXEC_ENDPOINT = `${baseEndpoint}/exec`;
62
+ async function resolveCodeApiAuthHeaders(authHeaders) {
63
+ if (authHeaders == null) {
64
+ return {};
65
+ }
66
+ if (typeof authHeaders === 'function') {
67
+ return authHeaders();
68
+ }
69
+ return authHeaders;
70
+ }
71
+ async function buildCodeApiHttpErrorMessage(method, endpoint, response) {
72
+ let responseBody = '';
73
+ try {
74
+ responseBody = await response.text();
75
+ }
76
+ catch {
77
+ responseBody = '';
78
+ }
79
+ const body = responseBody.trim();
80
+ const bodySuffix = body === '' ? '' : `, body: ${body.slice(0, 1000)}`;
81
+ return `CodeAPI request failed: ${method} ${endpoint} returned ${response.status}${bodySuffix}`;
82
+ }
62
83
  const CodeExecutionToolDescription = `
63
84
  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.
64
85
 
@@ -75,6 +96,7 @@ const CodeExecutionToolDefinition = {
75
96
  };
76
97
  function createCodeExecutionTool(params = {}) {
77
98
  return tools.tool(async (rawInput, config) => {
99
+ const { authHeaders, ...executionParams } = params ?? {};
78
100
  const { lang, code, ...rest } = rawInput;
79
101
  /**
80
102
  * Extract session context from config.toolCall (injected by ToolNode).
@@ -86,7 +108,7 @@ function createCodeExecutionTool(params = {}) {
86
108
  lang,
87
109
  code,
88
110
  ...rest,
89
- ...params,
111
+ ...executionParams,
90
112
  };
91
113
  /* File injection: `_injected_files` from ToolNode (set when host
92
114
  * primes a CodeSessionContext) or `params.files` from tool
@@ -105,11 +127,13 @@ function createCodeExecutionTool(params = {}) {
105
127
  console.debug(`[CodeExecutor] No injected files for session_id=${session_id} — exec will run without input files`);
106
128
  }
107
129
  try {
130
+ const resolvedAuthHeaders = await resolveCodeApiAuthHeaders(authHeaders);
108
131
  const fetchOptions = {
109
132
  method: 'POST',
110
133
  headers: {
111
134
  'Content-Type': 'application/json',
112
135
  'User-Agent': 'LibreChat/1.0',
136
+ ...resolvedAuthHeaders,
113
137
  },
114
138
  body: JSON.stringify(postData),
115
139
  };
@@ -118,7 +142,7 @@ function createCodeExecutionTool(params = {}) {
118
142
  }
119
143
  const response = await fetch(EXEC_ENDPOINT, fetchOptions);
120
144
  if (!response.ok) {
121
- throw new Error(`HTTP error! status: ${response.status}`);
145
+ throw new Error(await buildCodeApiHttpErrorMessage('POST', EXEC_ENDPOINT, response));
122
146
  }
123
147
  const result = await response.json();
124
148
  /* Output is stdout/stderr only — file listings were removed
@@ -162,7 +186,9 @@ exports.CodeExecutionToolDefinition = CodeExecutionToolDefinition;
162
186
  exports.CodeExecutionToolDescription = CodeExecutionToolDescription;
163
187
  exports.CodeExecutionToolName = CodeExecutionToolName;
164
188
  exports.CodeExecutionToolSchema = CodeExecutionToolSchema;
189
+ exports.buildCodeApiHttpErrorMessage = buildCodeApiHttpErrorMessage;
165
190
  exports.createCodeExecutionTool = createCodeExecutionTool;
166
191
  exports.emptyOutputMessage = emptyOutputMessage;
167
192
  exports.getCodeBaseURL = getCodeBaseURL;
193
+ exports.resolveCodeApiAuthHeaders = resolveCodeApiAuthHeaders;
168
194
  //# sourceMappingURL=CodeExecutor.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"CodeExecutor.cjs","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":["config","getEnvironmentVariable","EnvVar","Constants","tool","HttpsProxyAgent"],"mappings":";;;;;;;;;AAQAA,aAAM,EAAE;AAED,MAAM,cAAc,GAAG,MAC5BC,0BAAsB,CAACC,YAAM,CAAC,YAAY,CAAC;IAC3CC,eAAS,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,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CAAC,EACD;AACE,QAAA,IAAI,EAAE,qBAAqB;AAC3B,QAAA,WAAW,EAAE,4BAA4B;AACzC,QAAA,MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAEF,eAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;;;;;;;"}
1
+ {"version":3,"file":"CodeExecutor.cjs","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":["config","getEnvironmentVariable","EnvVar","Constants","tool","HttpsProxyAgent"],"mappings":";;;;;;;;;AAQAA,aAAM,EAAE;AAED,MAAM,cAAc,GAAG,MAC5BC,0BAAsB,CAACC,YAAM,CAAC,YAAY,CAAC;IAC3CC,eAAS,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,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MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAEF,eAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;;;;;;;;;"}
@@ -5,14 +5,14 @@ var fetch = require('node-fetch');
5
5
  var httpsProxyAgent = require('https-proxy-agent');
6
6
  var tools = require('@langchain/core/tools');
7
7
  var CodeExecutor = require('./CodeExecutor.cjs');
8
+ var ptcTimeout = require('./ptcTimeout.cjs');
8
9
  var _enum = require('../common/enum.cjs');
9
10
 
10
11
  // src/tools/ProgrammaticToolCalling.ts
11
12
  dotenv.config();
12
13
  /** Default max round-trips to prevent infinite loops */
13
14
  const DEFAULT_MAX_ROUND_TRIPS = 20;
14
- /** Default execution timeout in milliseconds */
15
- const DEFAULT_TIMEOUT = 60000;
15
+ const DEFAULT_RUN_TIMEOUT_MS = ptcTimeout.resolveCodeApiRunTimeoutMs();
16
16
  // ============================================================================
17
17
  // Description Components (Single Source of Truth)
18
18
  // ============================================================================
@@ -25,7 +25,8 @@ const CORE_RULES = `Rules:
25
25
  - Just write code with await—auto-wrapped in async context
26
26
  - DO NOT define async def main() or call asyncio.run()
27
27
  - Tools are pre-defined—DO NOT write function definitions
28
- - Only print() output returns to the model`;
28
+ - Only print() output returns to the model
29
+ - timeout caps one sandbox run/replay iteration, not the total multi-round-trip workflow`;
29
30
  const ADDITIONAL_RULES = `- Generated files are automatically available in /mnt/data/ for subsequent executions
30
31
  - Tool names normalized: hyphens→underscores, keywords get \`_tool\` suffix`;
31
32
  const EXAMPLES = `Example (Complete workflow in one call):
@@ -53,24 +54,21 @@ Your code is auto-wrapped in async context. Just write logic with await—no boi
53
54
  ${EXAMPLES}
54
55
 
55
56
  ${CORE_RULES}`;
56
- const ProgrammaticToolCallingSchema = {
57
- type: 'object',
58
- properties: {
59
- code: {
60
- type: 'string',
61
- minLength: 1,
62
- description: CODE_PARAM_DESCRIPTION,
63
- },
64
- timeout: {
65
- type: 'integer',
66
- minimum: 1000,
67
- maximum: 300000,
68
- default: DEFAULT_TIMEOUT,
69
- description: 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.',
57
+ function createProgrammaticToolCallingSchema(maxRunTimeoutMs = DEFAULT_RUN_TIMEOUT_MS) {
58
+ return {
59
+ type: 'object',
60
+ properties: {
61
+ code: {
62
+ type: 'string',
63
+ minLength: 1,
64
+ description: CODE_PARAM_DESCRIPTION,
65
+ },
66
+ timeout: ptcTimeout.createCodeApiRunTimeoutSchema(maxRunTimeoutMs),
70
67
  },
71
- },
72
- required: ['code'],
73
- };
68
+ required: ['code'],
69
+ };
70
+ }
71
+ const ProgrammaticToolCallingSchema = createProgrammaticToolCallingSchema();
74
72
  const ProgrammaticToolCallingName = _enum.Constants.PROGRAMMATIC_TOOL_CALLING;
75
73
  const ProgrammaticToolCallingDescription = `
76
74
  Run tools via Python code. Auto-wrapped in async context—just use \`await\` directly.
@@ -130,6 +128,71 @@ const PYTHON_KEYWORDS = new Set([
130
128
  'with',
131
129
  'yield',
132
130
  ]);
131
+ function isFetchSessionFilesScope(value) {
132
+ if (value == null || typeof value !== 'object') {
133
+ return false;
134
+ }
135
+ const scope = value;
136
+ if ((scope.kind === 'agent' || scope.kind === 'user') &&
137
+ typeof scope.id === 'string') {
138
+ return true;
139
+ }
140
+ return (scope.kind === 'skill' &&
141
+ typeof scope.id === 'string' &&
142
+ typeof scope.version === 'number');
143
+ }
144
+ function isCodeApiAuthHeaders(value) {
145
+ return value != null && typeof value !== 'string';
146
+ }
147
+ function isCodeApiSessionFileWire(value) {
148
+ return value != null && typeof value === 'object';
149
+ }
150
+ function isCodeApiSessionFileMetadata(value) {
151
+ return value != null && typeof value === 'object';
152
+ }
153
+ function normalizeSessionFile(file, sessionId, scope) {
154
+ const metadata = isCodeApiSessionFileMetadata(file.metadata)
155
+ ? file.metadata
156
+ : undefined;
157
+ const rawName = typeof file.name === 'string' ? file.name : '';
158
+ const nameParts = rawName.split('/');
159
+ const fallbackId = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';
160
+ const id = typeof file.id === 'string' && file.id !== '' ? file.id : fallbackId;
161
+ const originalFilename = metadata?.['original-filename'];
162
+ const name = typeof originalFilename === 'string' ? originalFilename : rawName;
163
+ const storage_session_id = typeof file.storage_session_id === 'string'
164
+ ? file.storage_session_id
165
+ : sessionId;
166
+ const resource_id = typeof file.resource_id === 'string' && file.resource_id !== ''
167
+ ? file.resource_id
168
+ : (scope?.id ?? id);
169
+ if (scope?.kind === 'skill') {
170
+ return {
171
+ storage_session_id,
172
+ kind: 'skill',
173
+ id,
174
+ resource_id,
175
+ name,
176
+ version: scope.version,
177
+ };
178
+ }
179
+ if (scope != null) {
180
+ return {
181
+ storage_session_id,
182
+ kind: scope.kind,
183
+ id,
184
+ resource_id,
185
+ name,
186
+ };
187
+ }
188
+ return {
189
+ storage_session_id,
190
+ kind: 'user',
191
+ id,
192
+ resource_id: id,
193
+ name,
194
+ };
195
+ }
133
196
  /**
134
197
  * Normalizes a tool name to Python identifier format.
135
198
  * Must match the Code API's `normalizePythonFunctionName` exactly:
@@ -201,21 +264,41 @@ function filterToolsByUsage(toolDefs, code, debug = false) {
201
264
  }
202
265
  return toolDefs.filter((tool) => usedToolNames.has(tool.name));
203
266
  }
204
- /**
205
- * Fetches files from a previous session to make them available for the current execution.
206
- * Files are returned as CodeEnvFile references to be included in the request.
207
- * @param baseUrl - The base URL for the Code API
208
- * @param sessionId - The session ID to fetch files from
209
- * @param proxy - Optional HTTP proxy URL
210
- * @returns Array of CodeEnvFile references, or empty array if fetch fails
211
- */
212
- async function fetchSessionFiles(baseUrl, sessionId, proxy) {
267
+ async function fetchSessionFiles(baseUrl, sessionId, scopeOrProxy, proxyOrAuthHeaders, scopedAuthHeaders) {
213
268
  try {
214
- const filesEndpoint = `${baseUrl}/files/${sessionId}?detail=full`;
269
+ const scope = isFetchSessionFilesScope(scopeOrProxy)
270
+ ? scopeOrProxy
271
+ : undefined;
272
+ let proxy;
273
+ let authHeaders;
274
+ if (scope == null) {
275
+ proxy = typeof scopeOrProxy === 'string' ? scopeOrProxy : undefined;
276
+ authHeaders = isCodeApiAuthHeaders(proxyOrAuthHeaders)
277
+ ? proxyOrAuthHeaders
278
+ : undefined;
279
+ }
280
+ else if (typeof proxyOrAuthHeaders === 'string') {
281
+ proxy = proxyOrAuthHeaders;
282
+ authHeaders = scopedAuthHeaders;
283
+ }
284
+ else {
285
+ authHeaders = proxyOrAuthHeaders ?? scopedAuthHeaders;
286
+ }
287
+ const query = new URLSearchParams({ detail: 'full' });
288
+ if (scope != null) {
289
+ query.set('kind', scope.kind);
290
+ query.set('id', scope.id);
291
+ if (scope.kind === 'skill') {
292
+ query.set('version', String(scope.version));
293
+ }
294
+ }
295
+ const filesEndpoint = `${baseUrl}/files/${encodeURIComponent(sessionId)}?${query.toString()}`;
296
+ const resolvedAuthHeaders = await CodeExecutor.resolveCodeApiAuthHeaders(authHeaders);
215
297
  const fetchOptions = {
216
298
  method: 'GET',
217
299
  headers: {
218
300
  'User-Agent': 'LibreChat/1.0',
301
+ ...resolvedAuthHeaders,
219
302
  },
220
303
  };
221
304
  if (proxy != null && proxy !== '') {
@@ -223,28 +306,15 @@ async function fetchSessionFiles(baseUrl, sessionId, proxy) {
223
306
  }
224
307
  const response = await fetch(filesEndpoint, fetchOptions);
225
308
  if (!response.ok) {
226
- throw new Error(`Failed to fetch files for session: ${response.status}`);
309
+ throw new Error(await CodeExecutor.buildCodeApiHttpErrorMessage('GET', filesEndpoint, response));
227
310
  }
228
311
  const files = await response.json();
229
312
  if (!Array.isArray(files) || files.length === 0) {
230
313
  return [];
231
314
  }
232
- return files.map((file) => {
233
- // Extract the ID from the file name (part after session ID prefix and before extension)
234
- const nameParts = file.name.split('/');
235
- const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';
236
- return {
237
- storage_session_id: sessionId,
238
- /* `/files` fallback returns code-output files belonging to
239
- * the user; tag them user-private. */
240
- kind: 'user',
241
- id,
242
- /* `resource_id` informational for `kind: 'user'` —
243
- * codeapi derives sessionKey from auth context. */
244
- resource_id: id,
245
- name: file.metadata['original-filename'],
246
- };
247
- });
315
+ return files
316
+ .filter(isCodeApiSessionFileWire)
317
+ .map((file) => normalizeSessionFile(file, sessionId, scope));
248
318
  }
249
319
  catch (error) {
250
320
  // eslint-disable-next-line no-console
@@ -259,12 +329,14 @@ async function fetchSessionFiles(baseUrl, sessionId, proxy) {
259
329
  * @param proxy - Optional HTTP proxy URL
260
330
  * @returns The parsed API response
261
331
  */
262
- async function makeRequest(endpoint, body, proxy) {
332
+ async function makeRequest(endpoint, body, proxy, authHeaders) {
333
+ const resolvedAuthHeaders = await CodeExecutor.resolveCodeApiAuthHeaders(authHeaders);
263
334
  const fetchOptions = {
264
335
  method: 'POST',
265
336
  headers: {
266
337
  'Content-Type': 'application/json',
267
338
  'User-Agent': 'LibreChat/1.0',
339
+ ...resolvedAuthHeaders,
268
340
  },
269
341
  body: JSON.stringify(body),
270
342
  };
@@ -273,8 +345,7 @@ async function makeRequest(endpoint, body, proxy) {
273
345
  }
274
346
  const response = await fetch(endpoint, fetchOptions);
275
347
  if (!response.ok) {
276
- const errorText = await response.text();
277
- throw new Error(`HTTP error! status: ${response.status}, body: ${errorText}`);
348
+ throw new Error(await CodeExecutor.buildCodeApiHttpErrorMessage('POST', endpoint, response));
278
349
  }
279
350
  return (await response.json());
280
351
  }
@@ -399,7 +470,7 @@ function unwrapToolResponse(result, isMCPTool) {
399
470
  * @param toolMap - Map of tool names to executable tools
400
471
  * @returns Array of tool results
401
472
  */
402
- async function executeTools(toolCalls, toolMap) {
473
+ async function executeTools(toolCalls, toolMap, programmaticToolName = _enum.Constants.PROGRAMMATIC_TOOL_CALLING) {
403
474
  const executions = toolCalls.map(async (call) => {
404
475
  const tool = toolMap.get(call.name);
405
476
  if (!tool) {
@@ -412,7 +483,7 @@ async function executeTools(toolCalls, toolMap) {
412
483
  }
413
484
  try {
414
485
  const result = await tool.invoke(call.input, {
415
- metadata: { [_enum.Constants.PROGRAMMATIC_TOOL_CALLING]: true },
486
+ metadata: { [programmaticToolName]: true },
416
487
  });
417
488
  const isMCPTool = tool.mcp === true;
418
489
  const unwrappedResult = unwrapToolResponse(result, isMCPTool);
@@ -487,12 +558,14 @@ function formatCompletedResponse(response) {
487
558
  function createProgrammaticToolCallingTool(initParams = {}) {
488
559
  const baseUrl = initParams.baseUrl ?? CodeExecutor.getCodeBaseURL();
489
560
  const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;
561
+ const maxRunTimeoutMs = ptcTimeout.resolveCodeApiRunTimeoutMs(initParams.runTimeoutMs);
490
562
  const proxy = initParams.proxy ?? process.env.PROXY;
491
563
  const debug = initParams.debug ?? process.env.PTC_DEBUG === 'true';
492
564
  const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;
493
565
  return tools.tool(async (rawParams, config) => {
494
566
  const params = rawParams;
495
- const { code, timeout = DEFAULT_TIMEOUT } = params;
567
+ const { code } = params;
568
+ const timeout = ptcTimeout.clampCodeApiRunTimeoutMs(params.timeout, maxRunTimeoutMs);
496
569
  // Extra params injected by ToolNode (follows web_search pattern).
497
570
  const toolCall = (config.toolCall ?? {});
498
571
  const { toolMap, toolDefs, session_id, _injected_files } = toolCall;
@@ -535,7 +608,7 @@ function createProgrammaticToolCallingTool(initParams = {}) {
535
608
  session_id,
536
609
  timeout,
537
610
  ...(files && files.length > 0 ? { files } : {}),
538
- }, proxy);
611
+ }, proxy, initParams.authHeaders);
539
612
  // ====================================================================
540
613
  // Phase 2: Handle response loop
541
614
  // ====================================================================
@@ -554,7 +627,7 @@ function createProgrammaticToolCallingTool(initParams = {}) {
554
627
  response = await makeRequest(EXEC_ENDPOINT, {
555
628
  continuation_token: response.continuation_token,
556
629
  tool_results: toolResults,
557
- }, proxy);
630
+ }, proxy, initParams.authHeaders);
558
631
  }
559
632
  // ====================================================================
560
633
  // Phase 3: Handle final state
@@ -576,7 +649,7 @@ function createProgrammaticToolCallingTool(initParams = {}) {
576
649
  }, {
577
650
  name: _enum.Constants.PROGRAMMATIC_TOOL_CALLING,
578
651
  description: ProgrammaticToolCallingDescription,
579
- schema: ProgrammaticToolCallingSchema,
652
+ schema: createProgrammaticToolCallingSchema(maxRunTimeoutMs),
580
653
  responseFormat: _enum.Constants.CONTENT_AND_ARTIFACT,
581
654
  });
582
655
  }
@@ -585,6 +658,7 @@ exports.ProgrammaticToolCallingDefinition = ProgrammaticToolCallingDefinition;
585
658
  exports.ProgrammaticToolCallingDescription = ProgrammaticToolCallingDescription;
586
659
  exports.ProgrammaticToolCallingName = ProgrammaticToolCallingName;
587
660
  exports.ProgrammaticToolCallingSchema = ProgrammaticToolCallingSchema;
661
+ exports.createProgrammaticToolCallingSchema = createProgrammaticToolCallingSchema;
588
662
  exports.createProgrammaticToolCallingTool = createProgrammaticToolCallingTool;
589
663
  exports.executeTools = executeTools;
590
664
  exports.extractUsedToolNames = extractUsedToolNames;