illuma-agents 1.0.16 → 1.0.18

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 (114) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +3 -1
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +18 -0
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +79 -32
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/llm/bedrock/index.cjs +5 -3
  8. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  9. package/dist/cjs/llm/openai/index.cjs +1 -0
  10. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  11. package/dist/cjs/llm/openrouter/index.cjs +10 -1
  12. package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
  13. package/dist/cjs/llm/vertexai/index.cjs +7 -8
  14. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  15. package/dist/cjs/main.cjs +15 -0
  16. package/dist/cjs/main.cjs.map +1 -1
  17. package/dist/cjs/messages/cache.cjs +11 -6
  18. package/dist/cjs/messages/cache.cjs.map +1 -1
  19. package/dist/cjs/messages/core.cjs +16 -8
  20. package/dist/cjs/messages/core.cjs.map +1 -1
  21. package/dist/cjs/messages/format.cjs +9 -2
  22. package/dist/cjs/messages/format.cjs.map +1 -1
  23. package/dist/cjs/messages/tools.cjs +17 -10
  24. package/dist/cjs/messages/tools.cjs.map +1 -1
  25. package/dist/cjs/stream.cjs +30 -16
  26. package/dist/cjs/stream.cjs.map +1 -1
  27. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +209 -47
  28. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  29. package/dist/cjs/tools/ToolNode.cjs +73 -3
  30. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  31. package/dist/cjs/tools/handlers.cjs +1 -0
  32. package/dist/cjs/tools/handlers.cjs.map +1 -1
  33. package/dist/cjs/tools/search/search.cjs.map +1 -1
  34. package/dist/cjs/tools/search/tool.cjs +3 -1
  35. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  36. package/dist/cjs/utils/contextAnalytics.cjs +66 -0
  37. package/dist/cjs/utils/contextAnalytics.cjs.map +1 -0
  38. package/dist/cjs/utils/run.cjs.map +1 -1
  39. package/dist/cjs/utils/toonFormat.cjs +388 -0
  40. package/dist/cjs/utils/toonFormat.cjs.map +1 -0
  41. package/dist/esm/agents/AgentContext.mjs +3 -1
  42. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  43. package/dist/esm/common/enum.mjs +19 -1
  44. package/dist/esm/common/enum.mjs.map +1 -1
  45. package/dist/esm/graphs/Graph.mjs +81 -34
  46. package/dist/esm/graphs/Graph.mjs.map +1 -1
  47. package/dist/esm/llm/bedrock/index.mjs +5 -3
  48. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  49. package/dist/esm/llm/openai/index.mjs +1 -0
  50. package/dist/esm/llm/openai/index.mjs.map +1 -1
  51. package/dist/esm/llm/openrouter/index.mjs +10 -1
  52. package/dist/esm/llm/openrouter/index.mjs.map +1 -1
  53. package/dist/esm/llm/vertexai/index.mjs +7 -8
  54. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  55. package/dist/esm/main.mjs +4 -2
  56. package/dist/esm/main.mjs.map +1 -1
  57. package/dist/esm/messages/cache.mjs +11 -6
  58. package/dist/esm/messages/cache.mjs.map +1 -1
  59. package/dist/esm/messages/core.mjs +18 -10
  60. package/dist/esm/messages/core.mjs.map +1 -1
  61. package/dist/esm/messages/format.mjs +10 -3
  62. package/dist/esm/messages/format.mjs.map +1 -1
  63. package/dist/esm/messages/tools.mjs +19 -12
  64. package/dist/esm/messages/tools.mjs.map +1 -1
  65. package/dist/esm/stream.mjs +30 -16
  66. package/dist/esm/stream.mjs.map +1 -1
  67. package/dist/esm/tools/ProgrammaticToolCalling.mjs +208 -48
  68. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  69. package/dist/esm/tools/ToolNode.mjs +73 -3
  70. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  71. package/dist/esm/tools/handlers.mjs +1 -0
  72. package/dist/esm/tools/handlers.mjs.map +1 -1
  73. package/dist/esm/tools/search/search.mjs.map +1 -1
  74. package/dist/esm/tools/search/tool.mjs +3 -1
  75. package/dist/esm/tools/search/tool.mjs.map +1 -1
  76. package/dist/esm/utils/contextAnalytics.mjs +64 -0
  77. package/dist/esm/utils/contextAnalytics.mjs.map +1 -0
  78. package/dist/esm/utils/run.mjs.map +1 -1
  79. package/dist/esm/utils/toonFormat.mjs +381 -0
  80. package/dist/esm/utils/toonFormat.mjs.map +1 -0
  81. package/dist/types/common/enum.d.ts +17 -0
  82. package/dist/types/graphs/Graph.d.ts +8 -0
  83. package/dist/types/tools/ProgrammaticToolCalling.d.ts +19 -0
  84. package/dist/types/types/tools.d.ts +3 -1
  85. package/dist/types/utils/contextAnalytics.d.ts +37 -0
  86. package/dist/types/utils/index.d.ts +2 -0
  87. package/dist/types/utils/toonFormat.d.ts +111 -0
  88. package/package.json +3 -2
  89. package/src/agents/AgentContext.ts +28 -20
  90. package/src/common/enum.ts +18 -0
  91. package/src/graphs/Graph.ts +152 -62
  92. package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +495 -473
  93. package/src/llm/bedrock/index.ts +47 -35
  94. package/src/llm/openrouter/index.ts +11 -1
  95. package/src/llm/vertexai/index.ts +9 -10
  96. package/src/messages/cache.ts +104 -55
  97. package/src/messages/core.ts +29 -19
  98. package/src/messages/format.ts +14 -3
  99. package/src/messages/tools.ts +20 -13
  100. package/src/scripts/simple.ts +1 -1
  101. package/src/specs/emergency-prune.test.ts +407 -355
  102. package/src/stream.ts +28 -20
  103. package/src/tools/ProgrammaticToolCalling.ts +246 -52
  104. package/src/tools/ToolNode.ts +78 -5
  105. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +155 -0
  106. package/src/tools/search/jina-reranker.test.ts +32 -28
  107. package/src/tools/search/search.ts +3 -1
  108. package/src/tools/search/tool.ts +16 -7
  109. package/src/types/tools.ts +3 -1
  110. package/src/utils/contextAnalytics.ts +103 -0
  111. package/src/utils/index.ts +2 -0
  112. package/src/utils/llmConfig.ts +8 -1
  113. package/src/utils/run.ts +5 -4
  114. package/src/utils/toonFormat.ts +475 -0
@@ -29,42 +29,35 @@ const ProgrammaticToolCallingSchema = zod.z.object({
29
29
  code: zod.z
30
30
  .string()
31
31
  .min(1)
32
- .describe(`Python code that calls tools programmatically. Tools are automatically available as async Python functions - DO NOT define them yourself.
32
+ .describe(`Python code that calls tools programmatically. Tools are available as async functions.
33
33
 
34
- The Code API generates async function stubs from the tool definitions. Just call them directly:
34
+ CRITICAL - STATELESS EXECUTION:
35
+ Each call is a fresh Python interpreter. Variables, imports, and data do NOT persist between calls.
36
+ You MUST complete your entire workflow in ONE code block: query → process → output.
37
+ DO NOT split work across multiple calls expecting to reuse variables.
35
38
 
36
- Example (Simple call):
37
- result = await get_weather(city="San Francisco")
38
- print(result)
39
+ Your code is auto-wrapped in async context. Just write logic with await—no boilerplate needed.
39
40
 
40
- Example (Parallel - Fastest):
41
- results = await asyncio.gather(
42
- get_weather(city="SF"),
43
- get_weather(city="NYC"),
44
- get_weather(city="London")
45
- )
46
- for city, weather in zip(["SF", "NYC", "London"], results):
47
- print(f"{city}: {weather['temperature']}°F")
41
+ Example (Complete workflow in one call):
42
+ # Query data
43
+ data = await query_database(sql="SELECT * FROM users")
44
+ # Process it
45
+ df = pd.DataFrame(data)
46
+ summary = df.groupby('region').sum()
47
+ # Output results
48
+ await write_to_sheet(spreadsheet_id=sid, data=summary.to_dict())
49
+ print(f"Wrote {len(summary)} rows")
48
50
 
49
- Example (Loop with processing):
50
- team = await get_team_members()
51
- for member in team:
52
- expenses = await get_expenses(user_id=member['id'])
53
- total = sum(e['amount'] for e in expenses)
54
- print(f"{member['name']}: \${total:.2f}")
51
+ Example (Parallel calls):
52
+ sf, ny = await asyncio.gather(get_weather(city="SF"), get_weather(city="NY"))
53
+ print(f"SF: {sf}, NY: {ny}")
55
54
 
56
- Example (Conditional logic):
57
- data = await fetch_data(source="primary")
58
- if not data:
59
- data = await fetch_data(source="backup")
60
- print(f"Got {len(data)} records")
61
-
62
- Requirements:
63
- - Tools are pre-defined as async functions - DO NOT write function definitions
64
- - Use await for all tool calls
65
- - Use asyncio.gather() for parallel execution of independent calls
66
- - Only print() output flows back to the context window
67
- - Tool results from programmatic calls do NOT consume context tokens`),
55
+ Rules:
56
+ - EVERYTHING in one call—no state persists between executions
57
+ - Just write code with await—auto-wrapped in async context
58
+ - DO NOT define async def main() or call asyncio.run()
59
+ - Tools are pre-defined—DO NOT write function definitions
60
+ - Only print() output returns to the model`),
68
61
  session_id: zod.z
69
62
  .string()
70
63
  .optional()
@@ -190,6 +183,53 @@ function filterToolsByUsage(toolDefs, code, debug = false) {
190
183
  }
191
184
  return toolDefs.filter((tool) => usedToolNames.has(tool.name));
192
185
  }
186
+ /**
187
+ * Fetches files from a previous session to make them available for the current execution.
188
+ * Files are returned as CodeEnvFile references to be included in the request.
189
+ * @param baseUrl - The base URL for the Code API
190
+ * @param apiKey - The API key for authentication
191
+ * @param sessionId - The session ID to fetch files from
192
+ * @param proxy - Optional HTTP proxy URL
193
+ * @returns Array of CodeEnvFile references, or empty array if fetch fails
194
+ */
195
+ async function fetchSessionFiles(baseUrl, apiKey, sessionId, proxy) {
196
+ try {
197
+ const filesEndpoint = `${baseUrl}/files/${sessionId}?detail=full`;
198
+ const fetchOptions = {
199
+ method: 'GET',
200
+ headers: {
201
+ 'User-Agent': 'LibreChat/1.0',
202
+ 'X-API-Key': apiKey,
203
+ },
204
+ };
205
+ if (proxy != null && proxy !== '') {
206
+ fetchOptions.agent = new httpsProxyAgent.HttpsProxyAgent(proxy);
207
+ }
208
+ const response = await fetch(filesEndpoint, fetchOptions);
209
+ if (!response.ok) {
210
+ throw new Error(`Failed to fetch files for session: ${response.status}`);
211
+ }
212
+ const files = await response.json();
213
+ if (!Array.isArray(files) || files.length === 0) {
214
+ return [];
215
+ }
216
+ return files.map((file) => {
217
+ // Extract the ID from the file name (part after session ID prefix and before extension)
218
+ const nameParts = file.name.split('/');
219
+ const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';
220
+ return {
221
+ session_id: sessionId,
222
+ id,
223
+ name: file.metadata['original-filename'],
224
+ };
225
+ });
226
+ }
227
+ catch (error) {
228
+ // eslint-disable-next-line no-console
229
+ console.warn(`Failed to fetch files for session: ${sessionId}, ${error.message}`);
230
+ return [];
231
+ }
232
+ }
193
233
  /**
194
234
  * Makes an HTTP request to the Code API.
195
235
  * @param endpoint - The API endpoint URL
@@ -218,9 +258,123 @@ async function makeRequest(endpoint, apiKey, body, proxy) {
218
258
  }
219
259
  return (await response.json());
220
260
  }
261
+ /**
262
+ * Unwraps tool responses that may be formatted as tuples or content blocks.
263
+ * MCP tools return [content, artifacts], we need to extract the raw data.
264
+ * @param result - The raw result from tool.invoke()
265
+ * @param isMCPTool - Whether this is an MCP tool (has mcp property)
266
+ * @returns Unwrapped raw data (string, object, or parsed JSON)
267
+ */
268
+ function unwrapToolResponse(result, isMCPTool) {
269
+ // Only unwrap if this is an MCP tool and result is a tuple
270
+ if (!isMCPTool) {
271
+ return result;
272
+ }
273
+ /**
274
+ * Checks if a value is a content block object (has type and text).
275
+ */
276
+ const isContentBlock = (value) => {
277
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
278
+ return false;
279
+ }
280
+ const obj = value;
281
+ return typeof obj.type === 'string';
282
+ };
283
+ /**
284
+ * Checks if an array is an array of content blocks.
285
+ */
286
+ const isContentBlockArray = (arr) => {
287
+ return arr.length > 0 && arr.every(isContentBlock);
288
+ };
289
+ /**
290
+ * Extracts text from a single content block object.
291
+ * Returns the text if it's a text block, otherwise returns null.
292
+ */
293
+ const extractTextFromBlock = (block) => {
294
+ if (typeof block !== 'object' || block === null)
295
+ return null;
296
+ const b = block;
297
+ if (b.type === 'text' && typeof b.text === 'string') {
298
+ return b.text;
299
+ }
300
+ return null;
301
+ };
302
+ /**
303
+ * Extracts text from content blocks (array or single object).
304
+ * Returns combined text or null if no text blocks found.
305
+ */
306
+ const extractTextFromContent = (content) => {
307
+ // Single content block object: { type: 'text', text: '...' }
308
+ if (typeof content === 'object' &&
309
+ content !== null &&
310
+ !Array.isArray(content)) {
311
+ const text = extractTextFromBlock(content);
312
+ if (text !== null)
313
+ return text;
314
+ }
315
+ // Array of content blocks: [{ type: 'text', text: '...' }, ...]
316
+ if (Array.isArray(content) && content.length > 0) {
317
+ const texts = content
318
+ .map(extractTextFromBlock)
319
+ .filter((t) => t !== null);
320
+ if (texts.length > 0) {
321
+ return texts.join('\n');
322
+ }
323
+ }
324
+ return null;
325
+ };
326
+ /**
327
+ * Tries to parse a string as JSON if it looks like JSON.
328
+ */
329
+ const maybeParseJSON = (str) => {
330
+ const trimmed = str.trim();
331
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
332
+ try {
333
+ return JSON.parse(trimmed);
334
+ }
335
+ catch {
336
+ return str;
337
+ }
338
+ }
339
+ return str;
340
+ };
341
+ // Handle array of content blocks at top level FIRST
342
+ // (before checking for tuple, since both are arrays)
343
+ if (Array.isArray(result) && isContentBlockArray(result)) {
344
+ const extractedText = extractTextFromContent(result);
345
+ if (extractedText !== null) {
346
+ return maybeParseJSON(extractedText);
347
+ }
348
+ }
349
+ // Check if result is a tuple/array with [content, artifacts]
350
+ if (Array.isArray(result) && result.length >= 1) {
351
+ const [content] = result;
352
+ // If first element is a string, return it (possibly parsed as JSON)
353
+ if (typeof content === 'string') {
354
+ return maybeParseJSON(content);
355
+ }
356
+ // Try to extract text from content blocks
357
+ const extractedText = extractTextFromContent(content);
358
+ if (extractedText !== null) {
359
+ return maybeParseJSON(extractedText);
360
+ }
361
+ // If first element is an object (but not a text block), return it
362
+ if (typeof content === 'object' && content !== null) {
363
+ return content;
364
+ }
365
+ }
366
+ // Handle single content block object at top level (not in tuple)
367
+ const extractedText = extractTextFromContent(result);
368
+ if (extractedText !== null) {
369
+ return maybeParseJSON(extractedText);
370
+ }
371
+ // Not a formatted response, return as-is
372
+ return result;
373
+ }
221
374
  /**
222
375
  * Executes tools in parallel when requested by the API.
223
376
  * Uses Promise.all for parallel execution, catching individual errors.
377
+ * Unwraps formatted responses (e.g., MCP tool tuples) to raw data.
224
378
  * @param toolCalls - Array of tool calls from the API
225
379
  * @param toolMap - Map of tool names to executable tools
226
380
  * @returns Array of tool results
@@ -240,9 +394,11 @@ async function executeTools(toolCalls, toolMap) {
240
394
  const result = await tool.invoke(call.input, {
241
395
  metadata: { [_enum.Constants.PROGRAMMATIC_TOOL_CALLING]: true },
242
396
  });
397
+ const isMCPTool = tool.mcp === true;
398
+ const unwrappedResult = unwrapToolResponse(result, isMCPTool);
243
399
  return {
244
400
  call_id: call.id,
245
- result,
401
+ result: unwrappedResult,
246
402
  is_error: false,
247
403
  };
248
404
  }
@@ -334,25 +490,23 @@ function createProgrammaticToolCallingTool(initParams = {}) {
334
490
  const debug = initParams.debug ?? process.env.PTC_DEBUG === 'true';
335
491
  const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;
336
492
  const description = `
337
- Run tools by writing Python code. Tools are available as async functions - just call them with await.
493
+ Run tools via Python code. Auto-wrapped in async context—just use \`await\` directly.
338
494
 
339
- This is different from execute_code: here you can call your tools (like get_weather, get_expenses, etc.) directly in Python code.
495
+ CRITICAL - STATELESS: Each call is a fresh interpreter. Variables/imports do NOT persist.
496
+ Complete your ENTIRE workflow in ONE call: fetch → process → save. No splitting across calls.
340
497
 
341
- Usage:
342
- - Tools are pre-defined as async functions - call them with await
343
- - Use asyncio.gather() to run multiple tools in parallel
344
- - Only print() output is returned - tool results stay in Python
498
+ Rules:
499
+ - Everything in ONE code block—no state carries over between executions
500
+ - Do NOT define \`async def main()\` or call \`asyncio.run()\`—just write code with await
501
+ - Tools are pre-defined—DO NOT write function definitions
502
+ - Only \`print()\` output returns; tool results are raw dicts/lists/strings
503
+ - Use \`session_id\` param for file persistence across calls
504
+ - Tool names normalized: hyphens→underscores, keywords get \`_tool\` suffix
345
505
 
346
- Examples:
347
- - Simple: result = await get_weather(city="NYC")
348
- - Loop: for user in users: data = await get_expenses(user_id=user['id'])
349
- - Parallel: sf, ny = await asyncio.gather(get_weather(city="SF"), get_weather(city="NY"))
506
+ When to use: loops, conditionals, parallel (\`asyncio.gather\`), multi-step pipelines.
350
507
 
351
- When to use this instead of calling tools directly:
352
- - You need to call tools in a loop (process many items)
353
- - You want parallel execution (asyncio.gather)
354
- - You need conditionals based on tool results
355
- - You want to aggregate/filter data before returning
508
+ Example (complete pipeline):
509
+ data = await query_db(sql="..."); df = process(data); await save_to_sheet(data=df); print("Done")
356
510
  `.trim();
357
511
  return tools.tool(async (params, config) => {
358
512
  const { code, session_id, timeout = DEFAULT_TIMEOUT } = params;
@@ -377,11 +531,17 @@ When to use this instead of calling tools directly:
377
531
  console.log(`[PTC Debug] Sending ${effectiveTools.length} tools to API ` +
378
532
  `(filtered from ${toolDefs.length})`);
379
533
  }
534
+ // Fetch files from previous session if session_id is provided
535
+ let files;
536
+ if (session_id != null && session_id.length > 0) {
537
+ files = await fetchSessionFiles(baseUrl, apiKey, session_id, proxy);
538
+ }
380
539
  let response = await makeRequest(EXEC_ENDPOINT, apiKey, {
381
540
  code,
382
541
  tools: effectiveTools,
383
542
  session_id,
384
543
  timeout,
544
+ ...(files && files.length > 0 ? { files } : {}),
385
545
  }, proxy);
386
546
  // ====================================================================
387
547
  // Phase 2: Handle response loop
@@ -431,8 +591,10 @@ When to use this instead of calling tools directly:
431
591
  exports.createProgrammaticToolCallingTool = createProgrammaticToolCallingTool;
432
592
  exports.executeTools = executeTools;
433
593
  exports.extractUsedToolNames = extractUsedToolNames;
594
+ exports.fetchSessionFiles = fetchSessionFiles;
434
595
  exports.filterToolsByUsage = filterToolsByUsage;
435
596
  exports.formatCompletedResponse = formatCompletedResponse;
436
597
  exports.makeRequest = makeRequest;
437
598
  exports.normalizeToPythonIdentifier = normalizeToPythonIdentifier;
599
+ exports.unwrapToolResponse = unwrapToolResponse;
438
600
  //# sourceMappingURL=ProgrammaticToolCalling.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ProgrammaticToolCalling.cjs","sources":["../../../src/tools/ProgrammaticToolCalling.ts"],"sourcesContent":["// src/tools/ProgrammaticToolCalling.ts\nimport { z } from 'zod';\nimport { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport { imageExtRegex, getCodeBaseURL } from './CodeExecutor';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst imageMessage = 'Image is already displayed to the user';\nconst otherMessage = 'File is already downloaded by the user';\nconst accessMessage =\n 'Note: Files are READ-ONLY. Save changes to NEW filenames. To access these files in future executions, provide the `session_id` as a parameter (not in your code).';\nconst emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\n/** Default max round-trips to prevent infinite loops */\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\n\n/** Default execution timeout in milliseconds */\nconst DEFAULT_TIMEOUT = 60000;\n\n// ============================================================================\n// Schema\n// ============================================================================\n\nconst ProgrammaticToolCallingSchema = z.object({\n code: z\n .string()\n .min(1)\n .describe(\n `Python code that calls tools programmatically. Tools are automatically available as async Python functions - DO NOT define them yourself.\n\nThe Code API generates async function stubs from the tool definitions. Just call them directly:\n\nExample (Simple call):\n result = await get_weather(city=\"San Francisco\")\n print(result)\n\nExample (Parallel - Fastest):\n results = await asyncio.gather(\n get_weather(city=\"SF\"),\n get_weather(city=\"NYC\"),\n get_weather(city=\"London\")\n )\n for city, weather in zip([\"SF\", \"NYC\", \"London\"], results):\n print(f\"{city}: {weather['temperature']}°F\")\n\nExample (Loop with processing):\n team = await get_team_members()\n for member in team:\n expenses = await get_expenses(user_id=member['id'])\n total = sum(e['amount'] for e in expenses)\n print(f\"{member['name']}: \\${total:.2f}\")\n\nExample (Conditional logic):\n data = await fetch_data(source=\"primary\")\n if not data:\n data = await fetch_data(source=\"backup\")\n print(f\"Got {len(data)} records\")\n\nRequirements:\n- Tools are pre-defined as async functions - DO NOT write function definitions\n- Use await for all tool calls\n- Use asyncio.gather() for parallel execution of independent calls\n- Only print() output flows back to the context window\n- Tool results from programmatic calls do NOT consume context tokens`\n ),\n session_id: z\n .string()\n .optional()\n .describe(\n 'Session ID for file access (same as regular code execution). Files load into /mnt/data/ and are READ-ONLY.'\n ),\n timeout: z\n .number()\n .int()\n .min(1000)\n .max(300000)\n .optional()\n .default(DEFAULT_TIMEOUT)\n .describe(\n 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.'\n ),\n});\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/** Python reserved keywords that get `_tool` suffix in Code API */\nconst PYTHON_KEYWORDS = new Set([\n 'False',\n 'None',\n 'True',\n 'and',\n 'as',\n 'assert',\n 'async',\n 'await',\n 'break',\n 'class',\n 'continue',\n 'def',\n 'del',\n 'elif',\n 'else',\n 'except',\n 'finally',\n 'for',\n 'from',\n 'global',\n 'if',\n 'import',\n 'in',\n 'is',\n 'lambda',\n 'nonlocal',\n 'not',\n 'or',\n 'pass',\n 'raise',\n 'return',\n 'try',\n 'while',\n 'with',\n 'yield',\n]);\n\n/**\n * Normalizes a tool name to Python identifier format.\n * Must match the Code API's `normalizePythonFunctionName` exactly:\n * 1. Replace hyphens and spaces 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 Python keyword\n * @param name - The tool name to normalize\n * @returns Normalized Python-safe identifier\n */\nexport function normalizeToPythonIdentifier(name: string): string {\n let normalized = name.replace(/[-\\s]/g, '_');\n\n normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');\n\n if (/^[0-9]/.test(normalized)) {\n normalized = '_' + normalized;\n }\n\n if (PYTHON_KEYWORDS.has(normalized)) {\n normalized = normalized + '_tool';\n }\n\n return normalized;\n}\n\n/**\n * Extracts tool names that are actually called in the Python code.\n * Handles hyphen/underscore conversion since Python identifiers use underscores.\n * @param code - The Python code to analyze\n * @param toolNameMap - Map from normalized Python name to original tool name\n * @returns Set of original tool names found in the code\n */\nexport function extractUsedToolNames(\n code: string,\n toolNameMap: Map<string, string>\n): Set<string> {\n const usedTools = new Set<string>();\n\n for (const [pythonName, originalName] of toolNameMap) {\n const escapedName = pythonName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const pattern = new RegExp(`\\\\b${escapedName}\\\\s*\\\\(`, '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 code.\n * Handles the hyphen-to-underscore conversion for Python compatibility.\n * @param toolDefs - All available tool definitions\n * @param code - The Python code to analyze\n * @param debug - Enable debug logging\n * @returns Filtered array of tool definitions\n */\nexport function filterToolsByUsage(\n toolDefs: t.LCTool[],\n code: string,\n debug = false\n): t.LCTool[] {\n const toolNameMap = new Map<string, string>();\n for (const tool of toolDefs) {\n const pythonName = normalizeToPythonIdentifier(tool.name);\n toolNameMap.set(pythonName, tool.name);\n }\n\n const usedToolNames = extractUsedToolNames(code, toolNameMap);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC 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 `[PTC 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 '[PTC Debug] No tools detected in code - sending all tools as fallback'\n );\n }\n return toolDefs;\n }\n\n return toolDefs.filter((tool) => usedToolNames.has(tool.name));\n}\n\n/**\n * Makes an HTTP request to the Code API.\n * @param endpoint - The API endpoint URL\n * @param apiKey - The API key for authentication\n * @param body - The request body\n * @param proxy - Optional HTTP proxy URL\n * @returns The parsed API response\n */\nexport async function makeRequest(\n endpoint: string,\n apiKey: string,\n body: Record<string, unknown>,\n proxy?: string\n): Promise<t.ProgrammaticExecutionResponse> {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'Illuma/1.0',\n 'X-API-Key': apiKey,\n },\n body: JSON.stringify(body),\n };\n\n if (proxy != null && proxy !== '') {\n fetchOptions.agent = new HttpsProxyAgent(proxy);\n }\n\n const response = await fetch(endpoint, fetchOptions);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `HTTP error! status: ${response.status}, body: ${errorText}`\n );\n }\n\n return (await response.json()) as t.ProgrammaticExecutionResponse;\n}\n\n/**\n * Executes tools in parallel when requested by the API.\n * Uses Promise.all for parallel execution, catching individual errors.\n * @param toolCalls - Array of tool calls from the API\n * @param toolMap - Map of tool names to executable tools\n * @returns Array of tool results\n */\nexport async function executeTools(\n toolCalls: t.PTCToolCall[],\n toolMap: t.ToolMap\n): Promise<t.PTCToolResult[]> {\n const executions = toolCalls.map(async (call): Promise<t.PTCToolResult> => {\n const tool = toolMap.get(call.name);\n\n if (!tool) {\n return {\n call_id: call.id,\n result: null,\n is_error: true,\n error_message: `Tool '${call.name}' not found. Available tools: ${Array.from(toolMap.keys()).join(', ')}`,\n };\n }\n\n try {\n const result = await tool.invoke(call.input, {\n metadata: { [Constants.PROGRAMMATIC_TOOL_CALLING]: true },\n });\n return {\n call_id: call.id,\n result,\n is_error: false,\n };\n } catch (error) {\n return {\n call_id: call.id,\n result: null,\n is_error: true,\n error_message: (error as Error).message || 'Tool execution failed',\n };\n }\n });\n\n return await Promise.all(executions);\n}\n\n/**\n * Formats the completed response for the agent.\n * @param response - The completed API response\n * @returns Tuple of [formatted string, artifact]\n */\nexport function formatCompletedResponse(\n response: t.ProgrammaticExecutionResponse\n): [string, t.ProgrammaticExecutionArtifact] {\n let formatted = '';\n\n if (response.stdout != null && response.stdout !== '') {\n formatted += `stdout:\\n${response.stdout}\\n`;\n } else {\n formatted += emptyOutputMessage;\n }\n\n if (response.stderr != null && response.stderr !== '') {\n formatted += `stderr:\\n${response.stderr}\\n`;\n }\n\n if (response.files && response.files.length > 0) {\n formatted += 'Generated files:\\n';\n\n const fileCount = response.files.length;\n for (let i = 0; i < fileCount; i++) {\n const file = response.files[i];\n const isImage = imageExtRegex.test(file.name);\n formatted += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\n\n if (i < fileCount - 1) {\n formatted += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n formatted += `\\nsession_id: ${response.session_id}\\n\\n${accessMessage}`;\n }\n\n return [\n formatted.trim(),\n {\n session_id: response.session_id,\n files: response.files,\n },\n ];\n}\n\n// ============================================================================\n// Tool Factory\n// ============================================================================\n\n/**\n * Creates a Programmatic Tool Calling tool for complex multi-tool workflows.\n *\n * This tool enables AI agents to write Python code that orchestrates multiple\n * tool calls programmatically, reducing LLM round-trips and token usage.\n *\n * The tool map must be provided at runtime via config.configurable.toolMap.\n *\n * @param params - Configuration parameters (apiKey, baseUrl, maxRoundTrips, proxy)\n * @returns A LangChain DynamicStructuredTool for programmatic tool calling\n *\n * @example\n * const ptcTool = createProgrammaticToolCallingTool({\n * apiKey: process.env.CODE_API_KEY,\n * maxRoundTrips: 20\n * });\n *\n * const [output, artifact] = await ptcTool.invoke(\n * { code, tools },\n * { configurable: { toolMap } }\n * );\n */\nexport function createProgrammaticToolCallingTool(\n initParams: t.ProgrammaticToolCallingParams = {}\n): DynamicStructuredTool<typeof ProgrammaticToolCallingSchema> {\n const apiKey =\n (initParams[EnvVar.CODE_API_KEY] as string | undefined) ??\n initParams.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n\n if (!apiKey) {\n throw new Error(\n 'No API key provided for programmatic tool calling. ' +\n 'Set CODE_API_KEY environment variable or pass apiKey in initParams.'\n );\n }\n\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.PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n const description = `\nRun tools by writing Python code. Tools are available as async functions - just call them with await.\n\nThis is different from execute_code: here you can call your tools (like get_weather, get_expenses, etc.) directly in Python code.\n\nUsage:\n- Tools are pre-defined as async functions - call them with await\n- Use asyncio.gather() to run multiple tools in parallel\n- Only print() output is returned - tool results stay in Python\n\nExamples:\n- Simple: result = await get_weather(city=\"NYC\")\n- Loop: for user in users: data = await get_expenses(user_id=user['id'])\n- Parallel: sf, ny = await asyncio.gather(get_weather(city=\"SF\"), get_weather(city=\"NY\"))\n\nWhen to use this instead of calling tools directly:\n- You need to call tools in a loop (process many items)\n- You want parallel execution (asyncio.gather)\n- You need conditionals based on tool results\n- You want to aggregate/filter data before returning\n`.trim();\n\n return tool<typeof ProgrammaticToolCallingSchema>(\n async (params, config) => {\n const { code, session_id, timeout = DEFAULT_TIMEOUT } = params;\n\n // Extra params injected by ToolNode (follows web_search pattern)\n const { toolMap, toolDefs } = (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache>;\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 = filterToolsByUsage(toolDefs, code, debug);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Sending ${effectiveTools.length} tools to API ` +\n `(filtered from ${toolDefs.length})`\n );\n }\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n apiKey,\n {\n code,\n tools: effectiveTools,\n session_id,\n timeout,\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 `[PTC 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 apiKey,\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 `Programmatic execution failed: ${(error as Error).message}`\n );\n }\n },\n {\n name: Constants.PROGRAMMATIC_TOOL_CALLING,\n description,\n schema: ProgrammaticToolCallingSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"names":["config","z","HttpsProxyAgent","Constants","imageExtRegex","EnvVar","getEnvironmentVariable","getCodeBaseURL","tool"],"mappings":";;;;;;;;;;;AAAA;AAYAA,a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9F;;AAGH,gBAAA,MAAM,WAAW,GAAG,MAAM,YAAY,CACpC,QAAQ,CAAC,UAAU,IAAI,EAAE,EACzB,OAAO,CACR;AAED,gBAAA,QAAQ,GAAG,MAAM,WAAW,CAC1B,aAAa,EACb,MAAM,EACN;oBACE,kBAAkB,EAAE,QAAQ,CAAC,kBAAkB;AAC/C,oBAAA,YAAY,EAAE,WAAW;iBAC1B,EACD,KAAK,CACN;;;;;AAOH,YAAA,IAAI,QAAQ,CAAC,MAAM,KAAK,WAAW,EAAE;AACnC,gBAAA,OAAO,uBAAuB,CAAC,QAAQ,CAAC;;AAG1C,YAAA,IAAI,QAAQ,CAAC,MAAM,KAAK,OAAO,EAAE;AAC/B,gBAAA,MAAM,IAAI,KAAK,CACb,oBAAoB,QAAQ,CAAC,KAAK,CAAE,CAAA;qBACjC,QAAQ,CAAC,MAAM,IAAI,IAAI,IAAI,QAAQ,CAAC,MAAM,KAAK;AAC9C,0BAAE,CAAA,aAAA,EAAgB,QAAQ,CAAC,MAAM,CAAE;AACnC,0BAAE,EAAE,CAAC,CACV;;YAGH,MAAM,IAAI,KAAK,CAAC,CAAA,4BAAA,EAA+B,QAAQ,CAAC,MAAM,CAAE,CAAA,CAAC;;QACjE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,+BAAA,EAAmC,KAAe,CAAC,OAAO,CAAE,CAAA,CAC7D;;AAEL,KAAC,EACD;QACE,IAAI,EAAEL,eAAS,CAAC,yBAAyB;QACzC,WAAW;AACX,QAAA,MAAM,EAAE,6BAA6B;QACrC,cAAc,EAAEA,eAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;;;;;;;"}
1
+ {"version":3,"file":"ProgrammaticToolCalling.cjs","sources":["../../../src/tools/ProgrammaticToolCalling.ts"],"sourcesContent":["// src/tools/ProgrammaticToolCalling.ts\nimport { z } from 'zod';\nimport { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport { imageExtRegex, getCodeBaseURL } from './CodeExecutor';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst imageMessage = 'Image is already displayed to the user';\nconst otherMessage = 'File is already downloaded by the user';\nconst accessMessage =\n 'Note: Files are READ-ONLY. Save changes to NEW filenames. To access these files in future executions, provide the `session_id` as a parameter (not in your code).';\nconst emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\n/** Default max round-trips to prevent infinite loops */\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\n\n/** Default execution timeout in milliseconds */\nconst DEFAULT_TIMEOUT = 60000;\n\n// ============================================================================\n// Schema\n// ============================================================================\n\nconst ProgrammaticToolCallingSchema = z.object({\n code: z\n .string()\n .min(1)\n .describe(\n `Python code that calls tools programmatically. Tools are available as async functions.\n\nCRITICAL - STATELESS EXECUTION:\nEach call is a fresh Python interpreter. Variables, imports, and data do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block: query → process → output.\nDO NOT split work across multiple calls expecting to reuse variables.\n\nYour code is auto-wrapped in async context. Just write logic with await—no boilerplate needed.\n\nExample (Complete workflow in one call):\n # Query data\n data = await query_database(sql=\"SELECT * FROM users\")\n # Process it\n df = pd.DataFrame(data)\n summary = df.groupby('region').sum()\n # Output results\n await write_to_sheet(spreadsheet_id=sid, data=summary.to_dict())\n print(f\"Wrote {len(summary)} rows\")\n\nExample (Parallel calls):\n sf, ny = await asyncio.gather(get_weather(city=\"SF\"), get_weather(city=\"NY\"))\n print(f\"SF: {sf}, NY: {ny}\")\n\nRules:\n- EVERYTHING in one call—no state persists between executions\n- Just write code with await—auto-wrapped in async context\n- DO NOT define async def main() or call asyncio.run()\n- Tools are pre-defined—DO NOT write function definitions\n- Only print() output returns to the model`\n ),\n session_id: z\n .string()\n .optional()\n .describe(\n 'Session ID for file access (same as regular code execution). Files load into /mnt/data/ and are READ-ONLY.'\n ),\n timeout: z\n .number()\n .int()\n .min(1000)\n .max(300000)\n .optional()\n .default(DEFAULT_TIMEOUT)\n .describe(\n 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.'\n ),\n});\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/** Python reserved keywords that get `_tool` suffix in Code API */\nconst PYTHON_KEYWORDS = new Set([\n 'False',\n 'None',\n 'True',\n 'and',\n 'as',\n 'assert',\n 'async',\n 'await',\n 'break',\n 'class',\n 'continue',\n 'def',\n 'del',\n 'elif',\n 'else',\n 'except',\n 'finally',\n 'for',\n 'from',\n 'global',\n 'if',\n 'import',\n 'in',\n 'is',\n 'lambda',\n 'nonlocal',\n 'not',\n 'or',\n 'pass',\n 'raise',\n 'return',\n 'try',\n 'while',\n 'with',\n 'yield',\n]);\n\n/**\n * Normalizes a tool name to Python identifier format.\n * Must match the Code API's `normalizePythonFunctionName` exactly:\n * 1. Replace hyphens and spaces 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 Python keyword\n * @param name - The tool name to normalize\n * @returns Normalized Python-safe identifier\n */\nexport function normalizeToPythonIdentifier(name: string): string {\n let normalized = name.replace(/[-\\s]/g, '_');\n\n normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');\n\n if (/^[0-9]/.test(normalized)) {\n normalized = '_' + normalized;\n }\n\n if (PYTHON_KEYWORDS.has(normalized)) {\n normalized = normalized + '_tool';\n }\n\n return normalized;\n}\n\n/**\n * Extracts tool names that are actually called in the Python code.\n * Handles hyphen/underscore conversion since Python identifiers use underscores.\n * @param code - The Python code to analyze\n * @param toolNameMap - Map from normalized Python name to original tool name\n * @returns Set of original tool names found in the code\n */\nexport function extractUsedToolNames(\n code: string,\n toolNameMap: Map<string, string>\n): Set<string> {\n const usedTools = new Set<string>();\n\n for (const [pythonName, originalName] of toolNameMap) {\n const escapedName = pythonName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const pattern = new RegExp(`\\\\b${escapedName}\\\\s*\\\\(`, '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 code.\n * Handles the hyphen-to-underscore conversion for Python compatibility.\n * @param toolDefs - All available tool definitions\n * @param code - The Python code to analyze\n * @param debug - Enable debug logging\n * @returns Filtered array of tool definitions\n */\nexport function filterToolsByUsage(\n toolDefs: t.LCTool[],\n code: string,\n debug = false\n): t.LCTool[] {\n const toolNameMap = new Map<string, string>();\n for (const tool of toolDefs) {\n const pythonName = normalizeToPythonIdentifier(tool.name);\n toolNameMap.set(pythonName, tool.name);\n }\n\n const usedToolNames = extractUsedToolNames(code, toolNameMap);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC 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 `[PTC 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 '[PTC Debug] No tools detected in code - sending all tools as fallback'\n );\n }\n return toolDefs;\n }\n\n return toolDefs.filter((tool) => usedToolNames.has(tool.name));\n}\n\n/**\n * Fetches files from a previous session to make them available for the current execution.\n * Files are returned as CodeEnvFile references to be included in the request.\n * @param baseUrl - The base URL for the Code API\n * @param apiKey - The API key for authentication\n * @param sessionId - The session ID to fetch files from\n * @param proxy - Optional HTTP proxy URL\n * @returns Array of CodeEnvFile references, or empty array if fetch fails\n */\nexport async function fetchSessionFiles(\n baseUrl: string,\n apiKey: string,\n sessionId: string,\n proxy?: string\n): Promise<t.CodeEnvFile[]> {\n try {\n const filesEndpoint = `${baseUrl}/files/${sessionId}?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 (proxy != null && proxy !== '') {\n fetchOptions.agent = new HttpsProxyAgent(proxy);\n }\n\n const response = await fetch(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(`Failed to fetch files for session: ${response.status}`);\n }\n\n const files = await response.json();\n if (!Array.isArray(files) || files.length === 0) {\n return [];\n }\n\n return files.map((file: Record<string, unknown>) => {\n // Extract the ID from the file name (part after session ID prefix and before extension)\n const nameParts = (file.name as string).split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id: sessionId,\n id,\n name: (file.metadata as Record<string, unknown>)[\n 'original-filename'\n ] as string,\n };\n });\n } catch (error) {\n // eslint-disable-next-line no-console\n console.warn(\n `Failed to fetch files for session: ${sessionId}, ${(error as Error).message}`\n );\n return [];\n }\n}\n\n/**\n * Makes an HTTP request to the Code API.\n * @param endpoint - The API endpoint URL\n * @param apiKey - The API key for authentication\n * @param body - The request body\n * @param proxy - Optional HTTP proxy URL\n * @returns The parsed API response\n */\nexport async function makeRequest(\n endpoint: string,\n apiKey: string,\n body: Record<string, unknown>,\n proxy?: string\n): Promise<t.ProgrammaticExecutionResponse> {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'Illuma/1.0',\n 'X-API-Key': apiKey,\n },\n body: JSON.stringify(body),\n };\n\n if (proxy != null && proxy !== '') {\n fetchOptions.agent = new HttpsProxyAgent(proxy);\n }\n\n const response = await fetch(endpoint, fetchOptions);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `HTTP error! status: ${response.status}, body: ${errorText}`\n );\n }\n\n return (await response.json()) as t.ProgrammaticExecutionResponse;\n}\n\n/**\n * Unwraps tool responses that may be formatted as tuples or content blocks.\n * MCP tools return [content, artifacts], we need to extract the raw data.\n * @param result - The raw result from tool.invoke()\n * @param isMCPTool - Whether this is an MCP tool (has mcp property)\n * @returns Unwrapped raw data (string, object, or parsed JSON)\n */\nexport function unwrapToolResponse(\n result: unknown,\n isMCPTool: boolean\n): unknown {\n // Only unwrap if this is an MCP tool and result is a tuple\n if (!isMCPTool) {\n return result;\n }\n\n /**\n * Checks if a value is a content block object (has type and text).\n */\n const isContentBlock = (value: unknown): boolean => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n const obj = value as Record<string, unknown>;\n return typeof obj.type === 'string';\n };\n\n /**\n * Checks if an array is an array of content blocks.\n */\n const isContentBlockArray = (arr: unknown[]): boolean => {\n return arr.length > 0 && arr.every(isContentBlock);\n };\n\n /**\n * Extracts text from a single content block object.\n * Returns the text if it's a text block, otherwise returns null.\n */\n const extractTextFromBlock = (block: unknown): string | null => {\n if (typeof block !== 'object' || block === null) return null;\n const b = block as Record<string, unknown>;\n if (b.type === 'text' && typeof b.text === 'string') {\n return b.text;\n }\n return null;\n };\n\n /**\n * Extracts text from content blocks (array or single object).\n * Returns combined text or null if no text blocks found.\n */\n const extractTextFromContent = (content: unknown): string | null => {\n // Single content block object: { type: 'text', text: '...' }\n if (\n typeof content === 'object' &&\n content !== null &&\n !Array.isArray(content)\n ) {\n const text = extractTextFromBlock(content);\n if (text !== null) return text;\n }\n\n // Array of content blocks: [{ type: 'text', text: '...' }, ...]\n if (Array.isArray(content) && content.length > 0) {\n const texts = content\n .map(extractTextFromBlock)\n .filter((t): t is string => t !== null);\n if (texts.length > 0) {\n return texts.join('\\n');\n }\n }\n\n return null;\n };\n\n /**\n * Tries to parse a string as JSON if it looks like JSON.\n */\n const maybeParseJSON = (str: string): unknown => {\n const trimmed = str.trim();\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return str;\n }\n }\n return str;\n };\n\n // Handle array of content blocks at top level FIRST\n // (before checking for tuple, since both are arrays)\n if (Array.isArray(result) && isContentBlockArray(result)) {\n const extractedText = extractTextFromContent(result);\n if (extractedText !== null) {\n return maybeParseJSON(extractedText);\n }\n }\n\n // Check if result is a tuple/array with [content, artifacts]\n if (Array.isArray(result) && result.length >= 1) {\n const [content] = result;\n\n // If first element is a string, return it (possibly parsed as JSON)\n if (typeof content === 'string') {\n return maybeParseJSON(content);\n }\n\n // Try to extract text from content blocks\n const extractedText = extractTextFromContent(content);\n if (extractedText !== null) {\n return maybeParseJSON(extractedText);\n }\n\n // If first element is an object (but not a text block), return it\n if (typeof content === 'object' && content !== null) {\n return content;\n }\n }\n\n // Handle single content block object at top level (not in tuple)\n const extractedText = extractTextFromContent(result);\n if (extractedText !== null) {\n return maybeParseJSON(extractedText);\n }\n\n // Not a formatted response, return as-is\n return result;\n}\n\n/**\n * Executes tools in parallel when requested by the API.\n * Uses Promise.all for parallel execution, catching individual errors.\n * Unwraps formatted responses (e.g., MCP tool tuples) to raw data.\n * @param toolCalls - Array of tool calls from the API\n * @param toolMap - Map of tool names to executable tools\n * @returns Array of tool results\n */\nexport async function executeTools(\n toolCalls: t.PTCToolCall[],\n toolMap: t.ToolMap\n): Promise<t.PTCToolResult[]> {\n const executions = toolCalls.map(async (call): Promise<t.PTCToolResult> => {\n const tool = toolMap.get(call.name);\n\n if (!tool) {\n return {\n call_id: call.id,\n result: null,\n is_error: true,\n error_message: `Tool '${call.name}' not found. Available tools: ${Array.from(toolMap.keys()).join(', ')}`,\n };\n }\n\n try {\n const result = await tool.invoke(call.input, {\n metadata: { [Constants.PROGRAMMATIC_TOOL_CALLING]: true },\n });\n\n const isMCPTool = tool.mcp === true;\n const unwrappedResult = unwrapToolResponse(result, isMCPTool);\n\n return {\n call_id: call.id,\n result: unwrappedResult,\n is_error: false,\n };\n } catch (error) {\n return {\n call_id: call.id,\n result: null,\n is_error: true,\n error_message: (error as Error).message || 'Tool execution failed',\n };\n }\n });\n\n return await Promise.all(executions);\n}\n\n/**\n * Formats the completed response for the agent.\n * @param response - The completed API response\n * @returns Tuple of [formatted string, artifact]\n */\nexport function formatCompletedResponse(\n response: t.ProgrammaticExecutionResponse\n): [string, t.ProgrammaticExecutionArtifact] {\n let formatted = '';\n\n if (response.stdout != null && response.stdout !== '') {\n formatted += `stdout:\\n${response.stdout}\\n`;\n } else {\n formatted += emptyOutputMessage;\n }\n\n if (response.stderr != null && response.stderr !== '') {\n formatted += `stderr:\\n${response.stderr}\\n`;\n }\n\n if (response.files && response.files.length > 0) {\n formatted += 'Generated files:\\n';\n\n const fileCount = response.files.length;\n for (let i = 0; i < fileCount; i++) {\n const file = response.files[i];\n const isImage = imageExtRegex.test(file.name);\n formatted += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\n\n if (i < fileCount - 1) {\n formatted += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n formatted += `\\nsession_id: ${response.session_id}\\n\\n${accessMessage}`;\n }\n\n return [\n formatted.trim(),\n {\n session_id: response.session_id,\n files: response.files,\n },\n ];\n}\n\n// ============================================================================\n// Tool Factory\n// ============================================================================\n\n/**\n * Creates a Programmatic Tool Calling tool for complex multi-tool workflows.\n *\n * This tool enables AI agents to write Python code that orchestrates multiple\n * tool calls programmatically, reducing LLM round-trips and token usage.\n *\n * The tool map must be provided at runtime via config.configurable.toolMap.\n *\n * @param params - Configuration parameters (apiKey, baseUrl, maxRoundTrips, proxy)\n * @returns A LangChain DynamicStructuredTool for programmatic tool calling\n *\n * @example\n * const ptcTool = createProgrammaticToolCallingTool({\n * apiKey: process.env.CODE_API_KEY,\n * maxRoundTrips: 20\n * });\n *\n * const [output, artifact] = await ptcTool.invoke(\n * { code, tools },\n * { configurable: { toolMap } }\n * );\n */\nexport function createProgrammaticToolCallingTool(\n initParams: t.ProgrammaticToolCallingParams = {}\n): DynamicStructuredTool<typeof ProgrammaticToolCallingSchema> {\n const apiKey =\n (initParams[EnvVar.CODE_API_KEY] as string | undefined) ??\n initParams.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n\n if (!apiKey) {\n throw new Error(\n 'No API key provided for programmatic tool calling. ' +\n 'Set CODE_API_KEY environment variable or pass apiKey in initParams.'\n );\n }\n\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.PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n const description = `\nRun tools via Python code. Auto-wrapped in async context—just use \\`await\\` directly.\n\nCRITICAL - STATELESS: Each call is a fresh interpreter. Variables/imports do NOT persist.\nComplete your ENTIRE workflow in ONE call: fetch → process → save. No splitting across calls.\n\nRules:\n- Everything in ONE code block—no state carries over between executions\n- Do NOT define \\`async def main()\\` or call \\`asyncio.run()\\`—just write code with await\n- Tools are pre-defined—DO NOT write function definitions\n- Only \\`print()\\` output returns; tool results are raw dicts/lists/strings\n- Use \\`session_id\\` param for file persistence across calls\n- Tool names normalized: hyphens→underscores, keywords get \\`_tool\\` suffix\n\nWhen to use: loops, conditionals, parallel (\\`asyncio.gather\\`), multi-step pipelines.\n\nExample (complete pipeline):\n data = await query_db(sql=\"...\"); df = process(data); await save_to_sheet(data=df); print(\"Done\")\n`.trim();\n\n return tool<typeof ProgrammaticToolCallingSchema>(\n async (params, config) => {\n const { code, session_id, timeout = DEFAULT_TIMEOUT } = params;\n\n // Extra params injected by ToolNode (follows web_search pattern)\n const { toolMap, toolDefs } = (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache>;\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 = filterToolsByUsage(toolDefs, code, debug);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Sending ${effectiveTools.length} tools to API ` +\n `(filtered from ${toolDefs.length})`\n );\n }\n\n // Fetch files from previous session if session_id is provided\n let files: t.CodeEnvFile[] | undefined;\n if (session_id != null && session_id.length > 0) {\n files = await fetchSessionFiles(baseUrl, apiKey, session_id, proxy);\n }\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n apiKey,\n {\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 `[PTC 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 apiKey,\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 `Programmatic execution failed: ${(error as Error).message}`\n );\n }\n },\n {\n name: Constants.PROGRAMMATIC_TOOL_CALLING,\n description,\n schema: ProgrammaticToolCallingSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"names":["config","z","HttpsProxyAgent","Constants","imageExtRegex","EnvVar","getEnvironmentVariable","getCodeBaseURL","tool"],"mappings":";;;;;;;;;;;AAAA;AAYAA,aAAM,EAAE;AAER;AACA;AACA;AAEA,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,aAAa,GACjB,mKAAmK;AACrK,MAAM,kBAAkB,GACtB,4DAA4D;AAE9D;AACA,MAAM,uBAAuB,GAAG,EAAE;AAElC;AACA,MAAM,eAAe,GAAG,KAAK;AAE7B;AACA;AACA;AAEA,MAAM,6BAA6B,GAAGC,KAAC,CAAC,MAAM,CAAC;AAC7C,IAAA,IAAI,EAAEA;AACH,SAAA,MAAM;SACN,GAAG,CAAC,CAAC;AACL,SAAA,QAAQ,CACP,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA4BqC,CACtC;AACH,IAAA,UAAU,EAAEA;AACT,SAAA,MAAM;AACN,SAAA,QAAQ;SACR,QAAQ,CACP,4GAA4G,CAC7G;AACH,IAAA,OAAO,EAAEA;AACN,SAAA,MAAM;AACN,SAAA,GAAG;SACH,GAAG,CAAC,IAAI;SACR,GAAG,CAAC,MAAM;AACV,SAAA,QAAQ;SACR,OAAO,CAAC,eAAe;SACvB,QAAQ,CACP,8EAA8E,CAC/E;AACJ,CAAA,CAAC;AAEF;AACA;AACA;AAEA;AACA,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC;IAC9B,OAAO;IACP,MAAM;IACN,MAAM;IACN,KAAK;IACL,IAAI;IACJ,QAAQ;IACR,OAAO;IACP,OAAO;IACP,OAAO;IACP,OAAO;IACP,UAAU;IACV,KAAK;IACL,KAAK;IACL,MAAM;IACN,MAAM;IACN,QAAQ;IACR,SAAS;IACT,KAAK;IACL,MAAM;IACN,QAAQ;IACR,IAAI;IACJ,QAAQ;IAC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IAAI,CAAC,CAAA,mBAAA,CAAqB,CAC9F;;AAGH,gBAAA,MAAM,WAAW,GAAG,MAAM,YAAY,CACpC,QAAQ,CAAC,UAAU,IAAI,EAAE,EACzB,OAAO,CACR;AAED,gBAAA,QAAQ,GAAG,MAAM,WAAW,CAC1B,aAAa,EACb,MAAM,EACN;oBACE,kBAAkB,EAAE,QAAQ,CAAC,kBAAkB;AAC/C,oBAAA,YAAY,EAAE,WAAW;iBAC1B,EACD,KAAK,CACN;;;;;AAOH,YAAA,IAAI,QAAQ,CAAC,MAAM,KAAK,WAAW,EAAE;AACnC,gBAAA,OAAO,uBAAuB,CAAC,QAAQ,CAAC;;AAG1C,YAAA,IAAI,QAAQ,CAAC,MAAM,KAAK,OAAO,EAAE;AAC/B,gBAAA,MAAM,IAAI,KAAK,CACb,oBAAoB,QAAQ,CAAC,KAAK,CAAE,CAAA;qBACjC,QAAQ,CAAC,MAAM,IAAI,IAAI,IAAI,QAAQ,CAAC,MAAM,KAAK;AAC9C,0BAAE,CAAA,aAAA,EAAgB,QAAQ,CAAC,MAAM,CAAE;AACnC,0BAAE,EAAE,CAAC,CACV;;YAGH,MAAM,IAAI,KAAK,CAAC,CAAA,4BAAA,EAA+B,QAAQ,CAAC,MAAM,CAAE,CAAA,CAAC;;QACjE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,+BAAA,EAAmC,KAAe,CAAC,OAAO,CAAE,CAAA,CAC7D;;AAEL,KAAC,EACD;QACE,IAAI,EAAEL,eAAS,CAAC,yBAAyB;QACzC,WAAW;AACX,QAAA,MAAM,EAAE,6BAA6B;QACrC,cAAc,EAAEA,eAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;;;;;;;;;"}
@@ -5,6 +5,7 @@ var langgraph = require('@langchain/langgraph');
5
5
  var _enum = require('../common/enum.cjs');
6
6
  require('nanoid');
7
7
  require('../messages/core.cjs');
8
+ var toonFormat = require('../utils/toonFormat.cjs');
8
9
  var run = require('../utils/run.cjs');
9
10
  require('js-tiktoken/lite');
10
11
 
@@ -14,6 +15,42 @@ require('js-tiktoken/lite');
14
15
  function isSend(value) {
15
16
  return value instanceof langgraph.Send;
16
17
  }
18
+ /**
19
+ * Extract text content from a ToolMessage content field.
20
+ * Handles both string and MessageContentComplex[] formats.
21
+ * For array content (e.g., from content_and_artifact tools), extracts text from text blocks.
22
+ */
23
+ function extractStringContent(content) {
24
+ // Already a string - return as is
25
+ if (typeof content === 'string') {
26
+ return content;
27
+ }
28
+ // Array of content blocks - extract text from each
29
+ if (Array.isArray(content)) {
30
+ const textParts = [];
31
+ for (const block of content) {
32
+ if (typeof block === 'string') {
33
+ textParts.push(block);
34
+ }
35
+ else if (block && typeof block === 'object') {
36
+ // Handle {type: 'text', text: '...'} format
37
+ const obj = block;
38
+ if (obj.type === 'text' && typeof obj.text === 'string') {
39
+ textParts.push(obj.text);
40
+ }
41
+ else if (typeof obj.text === 'string') {
42
+ // Just has 'text' property
43
+ textParts.push(obj.text);
44
+ }
45
+ }
46
+ }
47
+ if (textParts.length > 0) {
48
+ return textParts.join('\n');
49
+ }
50
+ }
51
+ // Fallback: stringify whatever it is
52
+ return JSON.stringify(content);
53
+ }
17
54
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
55
  class ToolNode extends run.RunnableCallable {
19
56
  toolMap;
@@ -103,15 +140,48 @@ class ToolNode extends run.RunnableCallable {
103
140
  };
104
141
  }
105
142
  const output = await tool.invoke(invokeParams, config);
106
- if ((messages.isBaseMessage(output) && output._getType() === 'tool') ||
107
- langgraph.isCommand(output)) {
143
+ // Handle Command outputs directly
144
+ if (langgraph.isCommand(output)) {
108
145
  return output;
109
146
  }
147
+ // ========================================================================
148
+ // TOOL OUTPUT PROCESSING - Single point for all tools (MCP and non-MCP)
149
+ // 1. Extract string content from any output format
150
+ // 2. Apply TOON conversion if content contains JSON
151
+ // 3. Apply truncation if still too large
152
+ // 4. Return ToolMessage with processed string content
153
+ // ========================================================================
154
+ // Step 1: Extract string content from the output
155
+ let rawContent;
156
+ if (messages.isBaseMessage(output) && output._getType() === 'tool') {
157
+ const toolMsg = output;
158
+ rawContent = extractStringContent(toolMsg.content);
159
+ }
160
+ else {
161
+ rawContent = extractStringContent(output);
162
+ }
163
+ // Step 2 & 3: Apply TOON conversion and truncation
164
+ const processed = toonFormat.processToolOutput(rawContent, {
165
+ maxLength: 100000, // 100K char limit
166
+ enableToon: true,
167
+ minSizeForToon: 1000,
168
+ minReductionPercent: 10, // Only apply TOON when clearly beneficial
169
+ });
170
+ // Step 4: Return ToolMessage with processed string content
171
+ if (messages.isBaseMessage(output) && output._getType() === 'tool') {
172
+ const toolMsg = output;
173
+ return new messages.ToolMessage({
174
+ status: toolMsg.status,
175
+ name: toolMsg.name,
176
+ content: processed.content,
177
+ tool_call_id: toolMsg.tool_call_id,
178
+ });
179
+ }
110
180
  else {
111
181
  return new messages.ToolMessage({
112
182
  status: 'success',
113
183
  name: tool.name,
114
- content: typeof output === 'string' ? output : JSON.stringify(output),
184
+ content: processed.content,
115
185
  tool_call_id: call.id,
116
186
  });
117
187
  }