@librechat/agents 3.1.67 → 3.1.68-dev.1

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 (185) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +23 -3
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +16 -1
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +91 -0
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/graphs/MultiAgentGraph.cjs +36 -0
  8. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  9. package/dist/cjs/hooks/HookRegistry.cjs +162 -0
  10. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -0
  11. package/dist/cjs/hooks/executeHooks.cjs +276 -0
  12. package/dist/cjs/hooks/executeHooks.cjs.map +1 -0
  13. package/dist/cjs/hooks/matchers.cjs +256 -0
  14. package/dist/cjs/hooks/matchers.cjs.map +1 -0
  15. package/dist/cjs/hooks/types.cjs +27 -0
  16. package/dist/cjs/hooks/types.cjs.map +1 -0
  17. package/dist/cjs/main.cjs +54 -0
  18. package/dist/cjs/main.cjs.map +1 -1
  19. package/dist/cjs/messages/format.cjs +74 -12
  20. package/dist/cjs/messages/format.cjs.map +1 -1
  21. package/dist/cjs/run.cjs +111 -0
  22. package/dist/cjs/run.cjs.map +1 -1
  23. package/dist/cjs/summarization/index.cjs +41 -0
  24. package/dist/cjs/summarization/index.cjs.map +1 -1
  25. package/dist/cjs/summarization/node.cjs +165 -19
  26. package/dist/cjs/summarization/node.cjs.map +1 -1
  27. package/dist/cjs/tools/BashExecutor.cjs +165 -0
  28. package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
  29. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +287 -0
  30. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
  31. package/dist/cjs/tools/CodeExecutor.cjs +0 -9
  32. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  33. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +7 -23
  34. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  35. package/dist/cjs/tools/ReadFile.cjs +43 -0
  36. package/dist/cjs/tools/ReadFile.cjs.map +1 -0
  37. package/dist/cjs/tools/SkillTool.cjs +50 -0
  38. package/dist/cjs/tools/SkillTool.cjs.map +1 -0
  39. package/dist/cjs/tools/SubagentTool.cjs +92 -0
  40. package/dist/cjs/tools/SubagentTool.cjs.map +1 -0
  41. package/dist/cjs/tools/ToolNode.cjs +304 -140
  42. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  43. package/dist/cjs/tools/ToolSearch.cjs +2 -13
  44. package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
  45. package/dist/cjs/tools/skillCatalog.cjs +84 -0
  46. package/dist/cjs/tools/skillCatalog.cjs.map +1 -0
  47. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +511 -0
  48. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -0
  49. package/dist/esm/agents/AgentContext.mjs +23 -3
  50. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  51. package/dist/esm/common/enum.mjs +15 -2
  52. package/dist/esm/common/enum.mjs.map +1 -1
  53. package/dist/esm/graphs/Graph.mjs +91 -0
  54. package/dist/esm/graphs/Graph.mjs.map +1 -1
  55. package/dist/esm/graphs/MultiAgentGraph.mjs +36 -0
  56. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  57. package/dist/esm/hooks/HookRegistry.mjs +160 -0
  58. package/dist/esm/hooks/HookRegistry.mjs.map +1 -0
  59. package/dist/esm/hooks/executeHooks.mjs +273 -0
  60. package/dist/esm/hooks/executeHooks.mjs.map +1 -0
  61. package/dist/esm/hooks/matchers.mjs +251 -0
  62. package/dist/esm/hooks/matchers.mjs.map +1 -0
  63. package/dist/esm/hooks/types.mjs +25 -0
  64. package/dist/esm/hooks/types.mjs.map +1 -0
  65. package/dist/esm/main.mjs +13 -2
  66. package/dist/esm/main.mjs.map +1 -1
  67. package/dist/esm/messages/format.mjs +66 -4
  68. package/dist/esm/messages/format.mjs.map +1 -1
  69. package/dist/esm/run.mjs +111 -0
  70. package/dist/esm/run.mjs.map +1 -1
  71. package/dist/esm/summarization/index.mjs +41 -1
  72. package/dist/esm/summarization/index.mjs.map +1 -1
  73. package/dist/esm/summarization/node.mjs +165 -19
  74. package/dist/esm/summarization/node.mjs.map +1 -1
  75. package/dist/esm/tools/BashExecutor.mjs +159 -0
  76. package/dist/esm/tools/BashExecutor.mjs.map +1 -0
  77. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +278 -0
  78. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
  79. package/dist/esm/tools/CodeExecutor.mjs +0 -9
  80. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  81. package/dist/esm/tools/ProgrammaticToolCalling.mjs +8 -24
  82. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  83. package/dist/esm/tools/ReadFile.mjs +38 -0
  84. package/dist/esm/tools/ReadFile.mjs.map +1 -0
  85. package/dist/esm/tools/SkillTool.mjs +45 -0
  86. package/dist/esm/tools/SkillTool.mjs.map +1 -0
  87. package/dist/esm/tools/SubagentTool.mjs +85 -0
  88. package/dist/esm/tools/SubagentTool.mjs.map +1 -0
  89. package/dist/esm/tools/ToolNode.mjs +306 -142
  90. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  91. package/dist/esm/tools/ToolSearch.mjs +3 -14
  92. package/dist/esm/tools/ToolSearch.mjs.map +1 -1
  93. package/dist/esm/tools/skillCatalog.mjs +82 -0
  94. package/dist/esm/tools/skillCatalog.mjs.map +1 -0
  95. package/dist/esm/tools/subagent/SubagentExecutor.mjs +505 -0
  96. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -0
  97. package/dist/types/agents/AgentContext.d.ts +6 -0
  98. package/dist/types/common/enum.d.ts +10 -2
  99. package/dist/types/graphs/Graph.d.ts +2 -0
  100. package/dist/types/graphs/MultiAgentGraph.d.ts +12 -0
  101. package/dist/types/hooks/HookRegistry.d.ts +56 -0
  102. package/dist/types/hooks/executeHooks.d.ts +79 -0
  103. package/dist/types/hooks/index.d.ts +6 -0
  104. package/dist/types/hooks/matchers.d.ts +95 -0
  105. package/dist/types/hooks/types.d.ts +320 -0
  106. package/dist/types/index.d.ts +8 -0
  107. package/dist/types/messages/format.d.ts +2 -1
  108. package/dist/types/run.d.ts +1 -0
  109. package/dist/types/summarization/index.d.ts +2 -0
  110. package/dist/types/summarization/node.d.ts +2 -0
  111. package/dist/types/tools/BashExecutor.d.ts +45 -0
  112. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +72 -0
  113. package/dist/types/tools/ProgrammaticToolCalling.d.ts +4 -9
  114. package/dist/types/tools/ReadFile.d.ts +28 -0
  115. package/dist/types/tools/SkillTool.d.ts +40 -0
  116. package/dist/types/tools/SubagentTool.d.ts +36 -0
  117. package/dist/types/tools/ToolNode.d.ts +24 -2
  118. package/dist/types/tools/ToolSearch.d.ts +2 -2
  119. package/dist/types/tools/skillCatalog.d.ts +19 -0
  120. package/dist/types/tools/subagent/SubagentExecutor.d.ts +137 -0
  121. package/dist/types/tools/subagent/index.d.ts +2 -0
  122. package/dist/types/types/graph.d.ts +61 -2
  123. package/dist/types/types/index.d.ts +1 -0
  124. package/dist/types/types/run.d.ts +20 -0
  125. package/dist/types/types/skill.d.ts +9 -0
  126. package/dist/types/types/tools.d.ts +38 -10
  127. package/package.json +5 -1
  128. package/src/agents/AgentContext.ts +26 -2
  129. package/src/common/enum.ts +15 -1
  130. package/src/graphs/Graph.ts +113 -0
  131. package/src/graphs/MultiAgentGraph.ts +39 -0
  132. package/src/graphs/__tests__/MultiAgentGraph.test.ts +91 -0
  133. package/src/hooks/HookRegistry.ts +208 -0
  134. package/src/hooks/__tests__/HookRegistry.test.ts +190 -0
  135. package/src/hooks/__tests__/compactHooks.test.ts +214 -0
  136. package/src/hooks/__tests__/executeHooks.test.ts +1013 -0
  137. package/src/hooks/__tests__/integration.test.ts +337 -0
  138. package/src/hooks/__tests__/matchers.test.ts +238 -0
  139. package/src/hooks/__tests__/toolHooks.test.ts +669 -0
  140. package/src/hooks/executeHooks.ts +375 -0
  141. package/src/hooks/index.ts +57 -0
  142. package/src/hooks/matchers.ts +280 -0
  143. package/src/hooks/types.ts +404 -0
  144. package/src/index.ts +10 -0
  145. package/src/messages/format.ts +74 -4
  146. package/src/messages/formatAgentMessages.skills.test.ts +334 -0
  147. package/src/run.ts +126 -0
  148. package/src/scripts/multi-agent-subagent.ts +246 -0
  149. package/src/scripts/programmatic_exec.ts +1 -10
  150. package/src/scripts/subagent-event-driven-debug.ts +190 -0
  151. package/src/scripts/subagent-tools-debug.ts +160 -0
  152. package/src/scripts/test_code_api.ts +0 -7
  153. package/src/scripts/tool_search.ts +1 -10
  154. package/src/specs/subagent.test.ts +305 -0
  155. package/src/summarization/__tests__/node.test.ts +42 -0
  156. package/src/summarization/__tests__/trigger.test.ts +100 -1
  157. package/src/summarization/index.ts +47 -0
  158. package/src/summarization/node.ts +202 -24
  159. package/src/tools/BashExecutor.ts +193 -0
  160. package/src/tools/BashProgrammaticToolCalling.ts +381 -0
  161. package/src/tools/CodeExecutor.ts +0 -11
  162. package/src/tools/ProgrammaticToolCalling.ts +4 -29
  163. package/src/tools/ReadFile.ts +39 -0
  164. package/src/tools/SkillTool.ts +46 -0
  165. package/src/tools/SubagentTool.ts +100 -0
  166. package/src/tools/ToolNode.ts +391 -169
  167. package/src/tools/ToolSearch.ts +3 -19
  168. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +7 -8
  169. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -1
  170. package/src/tools/__tests__/ReadFile.test.ts +44 -0
  171. package/src/tools/__tests__/SkillTool.test.ts +442 -0
  172. package/src/tools/__tests__/SubagentExecutor.test.ts +1148 -0
  173. package/src/tools/__tests__/SubagentTool.test.ts +149 -0
  174. package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
  175. package/src/tools/__tests__/ToolSearch.integration.test.ts +7 -8
  176. package/src/tools/__tests__/skillCatalog.test.ts +161 -0
  177. package/src/tools/__tests__/subagentHooks.test.ts +215 -0
  178. package/src/tools/skillCatalog.ts +126 -0
  179. package/src/tools/subagent/SubagentExecutor.ts +676 -0
  180. package/src/tools/subagent/index.ts +13 -0
  181. package/src/types/graph.ts +80 -1
  182. package/src/types/index.ts +1 -0
  183. package/src/types/run.ts +20 -0
  184. package/src/types/skill.ts +11 -0
  185. package/src/types/tools.ts +41 -10
@@ -0,0 +1,287 @@
1
+ 'use strict';
2
+
3
+ var dotenv = require('dotenv');
4
+ var tools = require('@langchain/core/tools');
5
+ var ProgrammaticToolCalling = require('./ProgrammaticToolCalling.cjs');
6
+ var CodeExecutor = require('./CodeExecutor.cjs');
7
+ var _enum = require('../common/enum.cjs');
8
+
9
+ dotenv.config();
10
+ // ============================================================================
11
+ // Constants
12
+ // ============================================================================
13
+ const DEFAULT_MAX_ROUND_TRIPS = 20;
14
+ const DEFAULT_TIMEOUT = 60000;
15
+ /** Bash reserved words that get `_tool` suffix when used as function names */
16
+ const BASH_RESERVED = new Set([
17
+ 'if',
18
+ 'then',
19
+ 'else',
20
+ 'elif',
21
+ 'fi',
22
+ 'case',
23
+ 'esac',
24
+ 'for',
25
+ 'while',
26
+ 'until',
27
+ 'do',
28
+ 'done',
29
+ 'in',
30
+ 'function',
31
+ 'select',
32
+ 'time',
33
+ 'coproc',
34
+ 'declare',
35
+ 'typeset',
36
+ 'local',
37
+ 'readonly',
38
+ 'export',
39
+ 'unset',
40
+ ]);
41
+ // ============================================================================
42
+ // Description Components
43
+ // ============================================================================
44
+ const STATELESS_WARNING = `CRITICAL - STATELESS EXECUTION:
45
+ Each call is a fresh bash shell. Variables and state do NOT persist between calls.
46
+ You MUST complete your entire workflow in ONE code block.
47
+ DO NOT split work across multiple calls expecting to reuse variables.`;
48
+ const CORE_RULES = `Rules:
49
+ - EVERYTHING in one call—no state persists between executions
50
+ - Tools are pre-defined as bash functions—DO NOT redefine them
51
+ - Each tool function accepts a JSON string argument
52
+ - Only echo/printf output returns to the model
53
+ - Generated files are automatically available in /mnt/data/ for subsequent executions`;
54
+ const ADDITIONAL_RULES = '- Tool names normalized: hyphens→underscores, reserved words get `_tool` suffix';
55
+ const EXAMPLES = `Example (Complete workflow in one call):
56
+ # Query data and process
57
+ data=$(query_database '{"sql": "SELECT * FROM users"}')
58
+ echo "$data" | jq '.[] | .name'
59
+
60
+ Example (Parallel calls):
61
+ web_search '{"query": "SF weather"}' > /tmp/sf.txt &
62
+ web_search '{"query": "NY weather"}' > /tmp/ny.txt &
63
+ wait
64
+ echo "SF: $(cat /tmp/sf.txt)"
65
+ echo "NY: $(cat /tmp/ny.txt)"`;
66
+ const CODE_PARAM_DESCRIPTION = `Bash code that calls tools programmatically. Tools are available as bash functions.
67
+
68
+ ${STATELESS_WARNING}
69
+
70
+ Each tool function accepts a JSON string as its argument.
71
+ Example: tool_name '{"key": "value"}'
72
+
73
+ ${EXAMPLES}
74
+
75
+ ${CORE_RULES}`;
76
+ // ============================================================================
77
+ // Schema
78
+ // ============================================================================
79
+ const BashProgrammaticToolCallingSchema = {
80
+ type: 'object',
81
+ properties: {
82
+ code: {
83
+ type: 'string',
84
+ minLength: 1,
85
+ description: CODE_PARAM_DESCRIPTION,
86
+ },
87
+ timeout: {
88
+ type: 'integer',
89
+ minimum: 1000,
90
+ maximum: 300000,
91
+ default: DEFAULT_TIMEOUT,
92
+ description: 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.',
93
+ },
94
+ },
95
+ required: ['code'],
96
+ };
97
+ const BashProgrammaticToolCallingName = _enum.Constants.BASH_PROGRAMMATIC_TOOL_CALLING;
98
+ const BashProgrammaticToolCallingDescription = `
99
+ Run tools via bash code. Tools are available as bash functions that accept JSON string arguments.
100
+
101
+ ${STATELESS_WARNING}
102
+
103
+ ${CORE_RULES}
104
+ ${ADDITIONAL_RULES}
105
+
106
+ When to use: shell pipelines, parallel execution (& and wait), file processing, text manipulation.
107
+
108
+ ${EXAMPLES}
109
+ `.trim();
110
+ const BashProgrammaticToolCallingDefinition = {
111
+ name: BashProgrammaticToolCallingName,
112
+ description: BashProgrammaticToolCallingDescription,
113
+ schema: BashProgrammaticToolCallingSchema,
114
+ };
115
+ // ============================================================================
116
+ // Helper Functions
117
+ // ============================================================================
118
+ /**
119
+ * Normalizes a tool name to a valid bash function identifier.
120
+ * 1. Replace hyphens, spaces, dots with underscores
121
+ * 2. Remove any other invalid characters
122
+ * 3. Prefix with underscore if starts with number
123
+ * 4. Append `_tool` if it's a bash reserved word
124
+ */
125
+ function normalizeToBashIdentifier(name) {
126
+ let normalized = name.replace(/[-\s.]/g, '_');
127
+ normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');
128
+ if (/^[0-9]/.test(normalized)) {
129
+ normalized = '_' + normalized;
130
+ }
131
+ if (BASH_RESERVED.has(normalized)) {
132
+ normalized = normalized + '_tool';
133
+ }
134
+ return normalized;
135
+ }
136
+ /**
137
+ * Extracts tool names that are actually called in the bash code.
138
+ * Bash functions are invoked as commands (no parentheses), so we match
139
+ * the normalized name as a word boundary.
140
+ */
141
+ function extractUsedBashToolNames(code, toolNameMap) {
142
+ const usedTools = new Set();
143
+ for (const [bashName, originalName] of toolNameMap) {
144
+ const escapedName = bashName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
145
+ const pattern = new RegExp(`\\b${escapedName}\\b`, 'g');
146
+ if (pattern.test(code)) {
147
+ usedTools.add(originalName);
148
+ }
149
+ }
150
+ return usedTools;
151
+ }
152
+ /**
153
+ * Filters tool definitions to only include tools actually used in the bash code.
154
+ */
155
+ function filterBashToolsByUsage(toolDefs, code, debug = false) {
156
+ const toolNameMap = new Map();
157
+ for (const def of toolDefs) {
158
+ const bashName = normalizeToBashIdentifier(def.name);
159
+ toolNameMap.set(bashName, def.name);
160
+ }
161
+ const usedToolNames = extractUsedBashToolNames(code, toolNameMap);
162
+ if (debug) {
163
+ // eslint-disable-next-line no-console
164
+ console.log(`[BashPTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`);
165
+ if (usedToolNames.size > 0) {
166
+ // eslint-disable-next-line no-console
167
+ console.log(`[BashPTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`);
168
+ }
169
+ }
170
+ if (usedToolNames.size === 0) {
171
+ if (debug) {
172
+ // eslint-disable-next-line no-console
173
+ console.log('[BashPTC Debug] No tools detected in code - sending all tools as fallback');
174
+ }
175
+ return toolDefs;
176
+ }
177
+ return toolDefs.filter((def) => usedToolNames.has(def.name));
178
+ }
179
+ // ============================================================================
180
+ // Tool Factory
181
+ // ============================================================================
182
+ /**
183
+ * Creates a Bash Programmatic Tool Calling tool for multi-tool orchestration.
184
+ *
185
+ * This tool enables AI agents to write bash scripts that orchestrate multiple
186
+ * tool calls programmatically via the remote Code API, reducing LLM round-trips.
187
+ *
188
+ * The tool map must be provided at runtime via config.toolCall (injected by ToolNode).
189
+ */
190
+ function createBashProgrammaticToolCallingTool(initParams = {}) {
191
+ const baseUrl = initParams.baseUrl ?? CodeExecutor.getCodeBaseURL();
192
+ const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;
193
+ const proxy = initParams.proxy ?? process.env.PROXY;
194
+ const debug = initParams.debug ?? process.env.BASH_PTC_DEBUG === 'true';
195
+ const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;
196
+ return tools.tool(async (rawParams, config) => {
197
+ const params = rawParams;
198
+ const { code, timeout = DEFAULT_TIMEOUT } = params;
199
+ const { toolMap, toolDefs, session_id, _injected_files } = (config.toolCall ?? {});
200
+ if (toolMap == null || toolMap.size === 0) {
201
+ throw new Error('No toolMap provided. ' +
202
+ 'ToolNode should inject this from AgentContext when invoked through the graph.');
203
+ }
204
+ if (toolDefs == null || toolDefs.length === 0) {
205
+ throw new Error('No tool definitions provided. ' +
206
+ 'Either pass tools in the input or ensure ToolNode injects toolDefs.');
207
+ }
208
+ let roundTrip = 0;
209
+ try {
210
+ // ====================================================================
211
+ // Phase 1: Filter tools and make initial request
212
+ // ====================================================================
213
+ const effectiveTools = filterBashToolsByUsage(toolDefs, code, debug);
214
+ if (debug) {
215
+ // eslint-disable-next-line no-console
216
+ console.log(`[BashPTC Debug] Sending ${effectiveTools.length} tools to API ` +
217
+ `(filtered from ${toolDefs.length})`);
218
+ }
219
+ let files;
220
+ if (_injected_files && _injected_files.length > 0) {
221
+ files = _injected_files;
222
+ }
223
+ else if (session_id != null && session_id.length > 0) {
224
+ files = await ProgrammaticToolCalling.fetchSessionFiles(baseUrl, session_id, proxy);
225
+ }
226
+ let response = await ProgrammaticToolCalling.makeRequest(EXEC_ENDPOINT, {
227
+ lang: 'bash',
228
+ code,
229
+ tools: effectiveTools,
230
+ session_id,
231
+ timeout,
232
+ ...(files && files.length > 0 ? { files } : {}),
233
+ }, proxy);
234
+ // ====================================================================
235
+ // Phase 2: Handle response loop
236
+ // ====================================================================
237
+ while (response.status === 'tool_call_required') {
238
+ roundTrip++;
239
+ if (roundTrip > maxRoundTrips) {
240
+ throw new Error(`Exceeded maximum round trips (${maxRoundTrips}). ` +
241
+ 'This may indicate an infinite loop, excessive tool calls, ' +
242
+ 'or a logic error in your code.');
243
+ }
244
+ if (debug) {
245
+ // eslint-disable-next-line no-console
246
+ console.log(`[BashPTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`);
247
+ }
248
+ const toolResults = await ProgrammaticToolCalling.executeTools(response.tool_calls ?? [], toolMap);
249
+ response = await ProgrammaticToolCalling.makeRequest(EXEC_ENDPOINT, {
250
+ continuation_token: response.continuation_token,
251
+ tool_results: toolResults,
252
+ }, proxy);
253
+ }
254
+ // ====================================================================
255
+ // Phase 3: Handle final state
256
+ // ====================================================================
257
+ if (response.status === 'completed') {
258
+ return ProgrammaticToolCalling.formatCompletedResponse(response);
259
+ }
260
+ if (response.status === 'error') {
261
+ throw new Error(`Execution error: ${response.error}` +
262
+ (response.stderr != null && response.stderr !== ''
263
+ ? `\n\nStderr:\n${response.stderr}`
264
+ : ''));
265
+ }
266
+ throw new Error(`Unexpected response status: ${response.status}`);
267
+ }
268
+ catch (error) {
269
+ throw new Error(`Bash programmatic execution failed: ${error.message}`);
270
+ }
271
+ }, {
272
+ name: _enum.Constants.BASH_PROGRAMMATIC_TOOL_CALLING,
273
+ description: BashProgrammaticToolCallingDescription,
274
+ schema: BashProgrammaticToolCallingSchema,
275
+ responseFormat: _enum.Constants.CONTENT_AND_ARTIFACT,
276
+ });
277
+ }
278
+
279
+ exports.BashProgrammaticToolCallingDefinition = BashProgrammaticToolCallingDefinition;
280
+ exports.BashProgrammaticToolCallingDescription = BashProgrammaticToolCallingDescription;
281
+ exports.BashProgrammaticToolCallingName = BashProgrammaticToolCallingName;
282
+ exports.BashProgrammaticToolCallingSchema = BashProgrammaticToolCallingSchema;
283
+ exports.createBashProgrammaticToolCallingTool = createBashProgrammaticToolCallingTool;
284
+ exports.extractUsedBashToolNames = extractUsedBashToolNames;
285
+ exports.filterBashToolsByUsage = filterBashToolsByUsage;
286
+ exports.normalizeToBashIdentifier = normalizeToBashIdentifier;
287
+ //# sourceMappingURL=BashProgrammaticToolCalling.cjs.map
@@ -0,0 +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 fetchSessionFiles,\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 { toolMap, toolDefs, session_id, _injected_files } =\n (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache> & {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\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 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 files = await fetchSessionFiles(baseUrl, session_id, proxy);\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","fetchSessionFiles","makeRequest","executeTools","formatCompletedResponse"],"mappings":";;;;;;;;AAaAA,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;;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F;AACH;;;;;;;;;;;"}
@@ -78,13 +78,6 @@ const CodeExecutionToolDefinition = {
78
78
  schema: CodeExecutionToolSchema,
79
79
  };
80
80
  function createCodeExecutionTool(params = {}) {
81
- const apiKey = params[_enum.EnvVar.CODE_API_KEY] ??
82
- params.apiKey ??
83
- env.getEnvironmentVariable(_enum.EnvVar.CODE_API_KEY) ??
84
- '';
85
- if (!apiKey) {
86
- throw new Error('No API key provided for code execution tool.');
87
- }
88
81
  return tools.tool(async (rawInput, config) => {
89
82
  const { lang, code, ...rest } = rawInput;
90
83
  /**
@@ -115,7 +108,6 @@ function createCodeExecutionTool(params = {}) {
115
108
  method: 'GET',
116
109
  headers: {
117
110
  'User-Agent': 'LibreChat/1.0',
118
- 'X-API-Key': apiKey,
119
111
  },
120
112
  };
121
113
  if (process.env.PROXY != null && process.env.PROXY !== '') {
@@ -150,7 +142,6 @@ function createCodeExecutionTool(params = {}) {
150
142
  headers: {
151
143
  'Content-Type': 'application/json',
152
144
  'User-Agent': 'LibreChat/1.0',
153
- 'X-API-Key': apiKey,
154
145
  },
155
146
  body: JSON.stringify(postData),
156
147
  };
@@ -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 imageExtRegex = /\\.(jpg|jpeg|png|gif|webp)$/i;\nexport const getCodeBaseURL = (): string =>\n getEnvironmentVariable(EnvVar.CODE_BASEURL) ??\n Constants.OFFICIAL_CODE_BASEURL;\n\nconst imageMessage = 'Image is already displayed to the user';\nconst otherMessage = 'File is already downloaded by the user';\nconst accessMessage =\n 'Note: Files from previous executions are automatically available and can be modified.';\nconst 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 const apiKey =\n params[EnvVar.CODE_API_KEY] ??\n params.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n if (!apiKey) {\n throw new Error('No API key provided for code execution tool.');\n }\n\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: For API to associate with previous session\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 /**\n * File injection priority:\n * 1. Use _injected_files from ToolNode (avoids /files endpoint race condition)\n * 2. Fall back to fetching from /files endpoint if session_id provided but no injected files\n */\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n /** Fallback: fetch from /files endpoint (may have race condition issues) */\n try {\n const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'LibreChat/1.0',\n 'X-API-Key': apiKey,\n },\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n\n const response = await fetch(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch files for session: ${response.status}`\n );\n }\n\n const files = await response.json();\n if (Array.isArray(files) && files.length > 0) {\n const fileReferences: t.CodeEnvFile[] = files.map((file) => {\n const nameParts = file.name.split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id,\n id,\n name: file.metadata['original-filename'],\n };\n });\n\n postData.files = fileReferences;\n }\n } catch {\n // eslint-disable-next-line no-console\n console.warn(`Failed to fetch files for session: ${session_id}`);\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 'X-API-Key': apiKey,\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n 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 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 if (result.files && result.files.length > 0) {\n formattedOutput += 'Generated files:\\n';\n\n const fileCount = result.files.length;\n for (let i = 0; i < fileCount; i++) {\n const file = result.files[i];\n const isImage = imageExtRegex.test(file.name);\n formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\n\n if (i < fileCount - 1) {\n formattedOutput += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n formattedOutput += `\\n\\n${accessMessage}`;\n return [\n formattedOutput.trim(),\n {\n session_id: result.session_id,\n files: result.files,\n },\n ];\n }\n\n return [formattedOutput.trim(), { session_id: result.session_id }];\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":";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ClC,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;oBAC5B,MAAM,OAAO,GAAG,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;AAC7C,oBAAA,eAAe,IAAI,CAAA,YAAA,EAAe,IAAI,CAAC,IAAI,MAAM,OAAO,GAAG,YAAY,GAAG,YAAY,EAAE;AAExF,oBAAA,IAAI,CAAC,GAAG,SAAS,GAAG,CAAC,EAAE;AACrB,wBAAA,eAAe,IAAI,SAAS,IAAI,CAAC,GAAG,IAAI,GAAG,KAAK;oBAClD;gBACF;AAEA,gBAAA,eAAe,IAAI,CAAA,IAAA,EAAO,aAAa,CAAA,CAAE;gBACzC,OAAO;oBACL,eAAe,CAAC,IAAI,EAAE;AACtB,oBAAA;wBACE,UAAU,EAAE,MAAM,CAAC,UAAU;wBAC7B,KAAK,EAAE,MAAM,CAAC,KAAK;AACpB,qBAAA;iBACF;YACH;AAEA,YAAA,OAAO,CAAC,eAAe,CAAC,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC;QACpE;QAAE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,oBAAA,EAAwB,KAA2B,EAAE,OAAO,CAAA,CAAE,CAC/D;QACH;AACF,IAAA,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 imageExtRegex = /\\.(jpg|jpeg|png|gif|webp)$/i;\nexport const getCodeBaseURL = (): string =>\n getEnvironmentVariable(EnvVar.CODE_BASEURL) ??\n Constants.OFFICIAL_CODE_BASEURL;\n\nconst imageMessage = 'Image is already displayed to the user';\nconst otherMessage = 'File is already downloaded by the user';\nconst accessMessage =\n 'Note: Files from previous executions are automatically available and can be modified.';\nconst 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: For API to associate with previous session\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 /**\n * File injection priority:\n * 1. Use _injected_files from ToolNode (avoids /files endpoint race condition)\n * 2. Fall back to fetching from /files endpoint if session_id provided but no injected files\n */\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n /** Fallback: fetch from /files endpoint (may have race condition issues) */\n try {\n const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'LibreChat/1.0',\n },\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n\n const response = await fetch(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch files for session: ${response.status}`\n );\n }\n\n const files = await response.json();\n if (Array.isArray(files) && files.length > 0) {\n const fileReferences: t.CodeEnvFile[] = files.map((file) => {\n const nameParts = file.name.split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id,\n id,\n name: file.metadata['original-filename'],\n };\n });\n\n postData.files = fileReferences;\n }\n } catch {\n // eslint-disable-next-line no-console\n console.warn(`Failed to fetch files for session: ${session_id}`);\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 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 if (result.files && result.files.length > 0) {\n formattedOutput += 'Generated files:\\n';\n\n const fileCount = result.files.length;\n for (let i = 0; i < fileCount; i++) {\n const file = result.files[i];\n const isImage = imageExtRegex.test(file.name);\n formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\n\n if (i < fileCount - 1) {\n formattedOutput += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n formattedOutput += `\\n\\n${accessMessage}`;\n return [\n formattedOutput.trim(),\n {\n session_id: result.session_id,\n files: result.files,\n },\n ];\n }\n\n return [formattedOutput.trim(), { session_id: result.session_id }];\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,aAAa,GAAG;AACtB,MAAM,cAAc,GAAG,MAC5BC,0BAAsB,CAACC,YAAM,CAAC,YAAY,CAAC;IAC3CC,eAAS,CAAC;AAEZ,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,aAAa,GACjB,uFAAuF;AACzF,MAAM,kBAAkB,GACtB,4DAA4D;AAE9D,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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,IAAI,MAAM,OAAO,GAAG,YAAY,GAAG,YAAY,EAAE;AAExF,oBAAA,IAAI,CAAC,GAAG,SAAS,GAAG,CAAC,EAAE;AACrB,wBAAA,eAAe,IAAI,SAAS,IAAI,CAAC,GAAG,IAAI,GAAG,KAAK;oBAClD;gBACF;AAEA,gBAAA,eAAe,IAAI,CAAA,IAAA,EAAO,aAAa,CAAA,CAAE;gBACzC,OAAO;oBACL,eAAe,CAAC,IAAI,EAAE;AACtB,oBAAA;wBACE,UAAU,EAAE,MAAM,CAAC,UAAU;wBAC7B,KAAK,EAAE,MAAM,CAAC,KAAK;AACpB,qBAAA;iBACF;YACH;AAEA,YAAA,OAAO,CAAC,eAAe,CAAC,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC;QACpE;QAAE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,oBAAA,EAAwB,KAA2B,EAAE,OAAO,CAAA,CAAE,CAC/D;QACH;AACF,IAAA,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;;;;;;;;;;"}
@@ -3,7 +3,6 @@
3
3
  var dotenv = require('dotenv');
4
4
  var fetch = require('node-fetch');
5
5
  var httpsProxyAgent = require('https-proxy-agent');
6
- var env = require('@langchain/core/utils/env');
7
6
  var tools = require('@langchain/core/tools');
8
7
  var CodeExecutor = require('./CodeExecutor.cjs');
9
8
  var _enum = require('../common/enum.cjs');
@@ -213,19 +212,17 @@ function filterToolsByUsage(toolDefs, code, debug = false) {
213
212
  * Fetches files from a previous session to make them available for the current execution.
214
213
  * Files are returned as CodeEnvFile references to be included in the request.
215
214
  * @param baseUrl - The base URL for the Code API
216
- * @param apiKey - The API key for authentication
217
215
  * @param sessionId - The session ID to fetch files from
218
216
  * @param proxy - Optional HTTP proxy URL
219
217
  * @returns Array of CodeEnvFile references, or empty array if fetch fails
220
218
  */
221
- async function fetchSessionFiles(baseUrl, apiKey, sessionId, proxy) {
219
+ async function fetchSessionFiles(baseUrl, sessionId, proxy) {
222
220
  try {
223
221
  const filesEndpoint = `${baseUrl}/files/${sessionId}?detail=full`;
224
222
  const fetchOptions = {
225
223
  method: 'GET',
226
224
  headers: {
227
225
  'User-Agent': 'LibreChat/1.0',
228
- 'X-API-Key': apiKey,
229
226
  },
230
227
  };
231
228
  if (proxy != null && proxy !== '') {
@@ -259,18 +256,16 @@ async function fetchSessionFiles(baseUrl, apiKey, sessionId, proxy) {
259
256
  /**
260
257
  * Makes an HTTP request to the Code API.
261
258
  * @param endpoint - The API endpoint URL
262
- * @param apiKey - The API key for authentication
263
259
  * @param body - The request body
264
260
  * @param proxy - Optional HTTP proxy URL
265
261
  * @returns The parsed API response
266
262
  */
267
- async function makeRequest(endpoint, apiKey, body, proxy) {
263
+ async function makeRequest(endpoint, body, proxy) {
268
264
  const fetchOptions = {
269
265
  method: 'POST',
270
266
  headers: {
271
267
  'Content-Type': 'application/json',
272
268
  'User-Agent': 'LibreChat/1.0',
273
- 'X-API-Key': apiKey,
274
269
  },
275
270
  body: JSON.stringify(body),
276
271
  };
@@ -487,14 +482,11 @@ function formatCompletedResponse(response) {
487
482
  *
488
483
  * The tool map must be provided at runtime via config.configurable.toolMap.
489
484
  *
490
- * @param params - Configuration parameters (apiKey, baseUrl, maxRoundTrips, proxy)
485
+ * @param params - Configuration parameters (baseUrl, maxRoundTrips, proxy)
491
486
  * @returns A LangChain DynamicStructuredTool for programmatic tool calling
492
487
  *
493
488
  * @example
494
- * const ptcTool = createProgrammaticToolCallingTool({
495
- * apiKey: process.env.CODE_API_KEY,
496
- * maxRoundTrips: 20
497
- * });
489
+ * const ptcTool = createProgrammaticToolCallingTool({ maxRoundTrips: 20 });
498
490
  *
499
491
  * const [output, artifact] = await ptcTool.invoke(
500
492
  * { code, tools },
@@ -502,14 +494,6 @@ function formatCompletedResponse(response) {
502
494
  * );
503
495
  */
504
496
  function createProgrammaticToolCallingTool(initParams = {}) {
505
- const apiKey = initParams[_enum.EnvVar.CODE_API_KEY] ??
506
- initParams.apiKey ??
507
- env.getEnvironmentVariable(_enum.EnvVar.CODE_API_KEY) ??
508
- '';
509
- if (!apiKey) {
510
- throw new Error('No API key provided for programmatic tool calling. ' +
511
- 'Set CODE_API_KEY environment variable or pass apiKey in initParams.');
512
- }
513
497
  const baseUrl = initParams.baseUrl ?? CodeExecutor.getCodeBaseURL();
514
498
  const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;
515
499
  const proxy = initParams.proxy ?? process.env.PROXY;
@@ -549,9 +533,9 @@ function createProgrammaticToolCallingTool(initParams = {}) {
549
533
  files = _injected_files;
550
534
  }
551
535
  else if (session_id != null && session_id.length > 0) {
552
- files = await fetchSessionFiles(baseUrl, apiKey, session_id, proxy);
536
+ files = await fetchSessionFiles(baseUrl, session_id, proxy);
553
537
  }
554
- let response = await makeRequest(EXEC_ENDPOINT, apiKey, {
538
+ let response = await makeRequest(EXEC_ENDPOINT, {
555
539
  code,
556
540
  tools: effectiveTools,
557
541
  session_id,
@@ -573,7 +557,7 @@ function createProgrammaticToolCallingTool(initParams = {}) {
573
557
  console.log(`[PTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`);
574
558
  }
575
559
  const toolResults = await executeTools(response.tool_calls ?? [], toolMap);
576
- response = await makeRequest(EXEC_ENDPOINT, apiKey, {
560
+ response = await makeRequest(EXEC_ENDPOINT, {
577
561
  continuation_token: response.continuation_token,
578
562
  tool_results: toolResults,
579
563
  }, proxy);