@librechat/agents 3.3.0 → 3.3.2

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 (130) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +116 -2
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +2 -0
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +229 -48
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/graphs/MultiAgentGraph.cjs +102 -27
  8. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  9. package/dist/cjs/llm/bedrock/index.cjs +11 -2
  10. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  11. package/dist/cjs/llm/contextOverflowRecovery.cjs +132 -0
  12. package/dist/cjs/llm/contextOverflowRecovery.cjs.map +1 -0
  13. package/dist/cjs/llm/google/index.cjs +1 -1
  14. package/dist/cjs/llm/invoke.cjs +60 -3
  15. package/dist/cjs/llm/invoke.cjs.map +1 -1
  16. package/dist/cjs/main.cjs +20 -7
  17. package/dist/cjs/messages/prune.cjs +16 -5
  18. package/dist/cjs/messages/prune.cjs.map +1 -1
  19. package/dist/cjs/messages/recency.cjs +2 -0
  20. package/dist/cjs/messages/recency.cjs.map +1 -1
  21. package/dist/cjs/run.cjs +15 -2
  22. package/dist/cjs/run.cjs.map +1 -1
  23. package/dist/cjs/stream.cjs +205 -49
  24. package/dist/cjs/stream.cjs.map +1 -1
  25. package/dist/cjs/summarization/node.cjs +55 -7
  26. package/dist/cjs/summarization/node.cjs.map +1 -1
  27. package/dist/cjs/tools/BashExecutor.cjs +2 -2
  28. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  29. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +2 -2
  30. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  31. package/dist/cjs/tools/CodeExecutor.cjs +69 -8
  32. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  33. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +19 -15
  34. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  35. package/dist/cjs/tools/ToolNode.cjs +32 -3
  36. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  37. package/dist/cjs/utils/errors.cjs +317 -52
  38. package/dist/cjs/utils/errors.cjs.map +1 -1
  39. package/dist/esm/agents/AgentContext.mjs +117 -3
  40. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  41. package/dist/esm/common/enum.mjs +2 -0
  42. package/dist/esm/common/enum.mjs.map +1 -1
  43. package/dist/esm/graphs/Graph.mjs +227 -46
  44. package/dist/esm/graphs/Graph.mjs.map +1 -1
  45. package/dist/esm/graphs/MultiAgentGraph.mjs +102 -27
  46. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  47. package/dist/esm/llm/bedrock/index.mjs +11 -2
  48. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  49. package/dist/esm/llm/contextOverflowRecovery.mjs +130 -0
  50. package/dist/esm/llm/contextOverflowRecovery.mjs.map +1 -0
  51. package/dist/esm/llm/google/index.mjs +1 -1
  52. package/dist/esm/llm/invoke.mjs +59 -4
  53. package/dist/esm/llm/invoke.mjs.map +1 -1
  54. package/dist/esm/main.mjs +9 -9
  55. package/dist/esm/messages/prune.mjs +14 -6
  56. package/dist/esm/messages/prune.mjs.map +1 -1
  57. package/dist/esm/messages/recency.mjs +2 -1
  58. package/dist/esm/messages/recency.mjs.map +1 -1
  59. package/dist/esm/run.mjs +15 -2
  60. package/dist/esm/run.mjs.map +1 -1
  61. package/dist/esm/stream.mjs +205 -49
  62. package/dist/esm/stream.mjs.map +1 -1
  63. package/dist/esm/summarization/node.mjs +55 -7
  64. package/dist/esm/summarization/node.mjs.map +1 -1
  65. package/dist/esm/tools/BashExecutor.mjs +3 -3
  66. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  67. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +3 -3
  68. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  69. package/dist/esm/tools/CodeExecutor.mjs +62 -9
  70. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  71. package/dist/esm/tools/ProgrammaticToolCalling.mjs +20 -16
  72. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  73. package/dist/esm/tools/ToolNode.mjs +32 -3
  74. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  75. package/dist/esm/utils/errors.mjs +317 -53
  76. package/dist/esm/utils/errors.mjs.map +1 -1
  77. package/dist/types/agents/AgentContext.d.ts +62 -3
  78. package/dist/types/common/enum.d.ts +2 -0
  79. package/dist/types/graphs/Graph.d.ts +16 -2
  80. package/dist/types/graphs/MultiAgentGraph.d.ts +1 -0
  81. package/dist/types/llm/contextOverflowRecovery.d.ts +85 -0
  82. package/dist/types/llm/invoke.d.ts +35 -6
  83. package/dist/types/messages/prune.d.ts +10 -2
  84. package/dist/types/messages/recency.d.ts +1 -0
  85. package/dist/types/run.d.ts +2 -0
  86. package/dist/types/tools/CodeExecutor.d.ts +14 -1
  87. package/dist/types/types/llm.d.ts +7 -4
  88. package/dist/types/types/stream.d.ts +5 -4
  89. package/dist/types/types/summarize.d.ts +22 -0
  90. package/dist/types/utils/__tests__/fixtures/contextOverflowSignatures.d.ts +40 -0
  91. package/dist/types/utils/errors.d.ts +65 -16
  92. package/dist/types/utils/redactSecrets.d.ts +3 -0
  93. package/package.json +10 -11
  94. package/src/agents/AgentContext.ts +188 -7
  95. package/src/agents/__tests__/AgentContext.overflow.test.ts +205 -0
  96. package/src/common/enum.ts +2 -0
  97. package/src/graphs/Graph.ts +389 -58
  98. package/src/graphs/MultiAgentGraph.ts +184 -46
  99. package/src/graphs/__tests__/Graph.contextOverflow.test.ts +631 -0
  100. package/src/llm/__tests__/contextOverflowRecovery.test.ts +401 -0
  101. package/src/llm/__tests__/fallbackOverflow.test.ts +287 -0
  102. package/src/llm/anthropic/llm.spec.ts +8 -0
  103. package/src/llm/bedrock/index.ts +25 -12
  104. package/src/llm/contextOverflowRecovery.ts +292 -0
  105. package/src/llm/invoke.ts +119 -4
  106. package/src/messages/prune.ts +24 -11
  107. package/src/messages/recency.ts +3 -1
  108. package/src/run.ts +24 -1
  109. package/src/scripts/context-overflow-probe.ts +997 -0
  110. package/src/specs/agent-handoffs.test.ts +903 -1
  111. package/src/specs/context-overflow-recovery.live.test.ts +213 -0
  112. package/src/splitStream.test.ts +882 -0
  113. package/src/stream.ts +315 -51
  114. package/src/summarization/__tests__/aggregator.test.ts +83 -0
  115. package/src/summarization/__tests__/node.test.ts +139 -0
  116. package/src/summarization/node.ts +99 -14
  117. package/src/tools/BashExecutor.ts +4 -2
  118. package/src/tools/BashProgrammaticToolCalling.ts +4 -7
  119. package/src/tools/CodeExecutor.ts +119 -8
  120. package/src/tools/ProgrammaticToolCalling.ts +29 -27
  121. package/src/tools/ToolNode.ts +50 -8
  122. package/src/tools/__tests__/CodeApiAuthHeaders.test.ts +297 -3
  123. package/src/types/llm.ts +8 -1
  124. package/src/types/stream.ts +5 -4
  125. package/src/types/summarize.ts +22 -0
  126. package/src/utils/__tests__/errors.test.ts +270 -0
  127. package/src/utils/__tests__/fixtures/contextOverflowSignatures.ts +336 -0
  128. package/src/utils/__tests__/redactSecrets.test.ts +56 -0
  129. package/src/utils/errors.ts +484 -66
  130. package/src/utils/redactSecrets.ts +61 -0
@@ -3,11 +3,11 @@ require("../common/enum.cjs");
3
3
  require("../common/index.cjs");
4
4
  const require_CodeSessionFileSummary = require("./CodeSessionFileSummary.cjs");
5
5
  let _langchain_core_tools = require("@langchain/core/tools");
6
+ let _langchain_core_utils_env = require("@langchain/core/utils/env");
6
7
  let dotenv = require("dotenv");
7
8
  let node_fetch = require("node-fetch");
8
9
  node_fetch = require_runtime.__toESM(node_fetch, 1);
9
10
  let https_proxy_agent = require("https-proxy-agent");
10
- let _langchain_core_utils_env = require("@langchain/core/utils/env");
11
11
  //#region src/tools/CodeExecutor.ts
12
12
  (0, dotenv.config)();
13
13
  const getCodeBaseURL = () => (0, _langchain_core_utils_env.getEnvironmentVariable)("LIBRECHAT_CODE_BASEURL") ?? "https://api.librechat.ai/v1";
@@ -72,21 +72,74 @@ const CodeExecutionToolSchema = {
72
72
  required: ["lang", "code"]
73
73
  };
74
74
  const EXEC_ENDPOINT = `${getCodeBaseURL()}/exec`;
75
+ const MAX_RETRY_AFTER_SECONDS = 3600;
76
+ const CODE_API_UNAVAILABLE_ERROR_MESSAGE = "Code execution is temporarily unavailable. Please retry.";
77
+ const CODE_API_AUTHORIZATION_ERROR_MESSAGE = "Code execution is not authorized. Verify access before trying again.";
78
+ const CODE_API_EXECUTION_FAILED_ERROR_MESSAGE = "Code execution failed.";
79
+ const CODE_API_INVALID_REQUEST_ERROR_MESSAGE = "The code execution request was rejected. Please check the tool input and try again.";
80
+ const CODE_API_RATE_LIMITED_ERROR_MESSAGE = "Code execution is temporarily rate-limited. Please retry shortly.";
81
+ const SAFE_CODE_API_EXECUTION_ERROR_DETAILS = {
82
+ "Execution failed or timed out": "Execution failed or timed out.",
83
+ "Out of memory": "Execution exceeded the memory limit.",
84
+ "Time limit exceeded": "Execution exceeded the time limit.",
85
+ "sandbox emitted an empty pending tool call block; aborting to avoid a tight retry loop": "Generated code emitted an invalid empty tool request.",
86
+ "stderr length exceeded": "Execution error output exceeded the size limit.",
87
+ "stdout length exceeded": "Execution output exceeded the size limit."
88
+ };
89
+ var CodeApiRequestError = class extends Error {
90
+ constructor(message = CODE_API_UNAVAILABLE_ERROR_MESSAGE) {
91
+ super(message);
92
+ this.name = "CodeApiRequestError";
93
+ }
94
+ };
95
+ function getRetryAfterSeconds(responseBody) {
96
+ try {
97
+ const parsed = JSON.parse(responseBody);
98
+ if (parsed.error !== "rate_limited" || typeof parsed.retry_after_seconds !== "number" || !Number.isFinite(parsed.retry_after_seconds) || parsed.retry_after_seconds <= 0) return;
99
+ return Math.min(Math.ceil(parsed.retry_after_seconds), MAX_RETRY_AFTER_SECONDS);
100
+ } catch {
101
+ return;
102
+ }
103
+ }
104
+ function normalizeCodeApiRequestError(error) {
105
+ return error instanceof CodeApiRequestError ? error : new CodeApiRequestError();
106
+ }
107
+ function getSafeCodeApiExecutionErrorDetail(error) {
108
+ if (typeof error !== "string") return;
109
+ const exactMatch = SAFE_CODE_API_EXECUTION_ERROR_DETAILS[error];
110
+ if (exactMatch != null) return exactMatch;
111
+ if (/^Sandbox exited with code (?:-?\d{1,4}|unknown)$/.test(error)) return error.replace(/^Sandbox/, "Execution");
112
+ if (/^Sandbox requested an unregistered tool: .+$/.test(error)) return "Generated code requested a tool that is not available.";
113
+ }
114
+ function buildCodeApiExecutionErrorMessage(response) {
115
+ const safeDetail = getSafeCodeApiExecutionErrorDetail(response.error);
116
+ const message = safeDetail != null ? `${CODE_API_EXECUTION_FAILED_ERROR_MESSAGE} ${safeDetail}` : CODE_API_EXECUTION_FAILED_ERROR_MESSAGE;
117
+ if (typeof response.stderr === "string" && response.stderr !== "") return `${message}\n\nStderr:\n${response.stderr}`;
118
+ return message;
119
+ }
75
120
  async function resolveCodeApiAuthHeaders(authHeaders) {
76
121
  if (authHeaders == null) return {};
77
- if (typeof authHeaders === "function") return authHeaders();
122
+ if (typeof authHeaders === "function") try {
123
+ return await authHeaders();
124
+ } catch {
125
+ throw new CodeApiRequestError(CODE_API_AUTHORIZATION_ERROR_MESSAGE);
126
+ }
78
127
  return authHeaders;
79
128
  }
80
- async function buildCodeApiHttpErrorMessage(method, endpoint, response) {
129
+ async function buildCodeApiHttpErrorMessage(_method, _endpoint, response) {
81
130
  let responseBody = "";
82
131
  try {
83
132
  responseBody = await response.text();
84
133
  } catch {
85
134
  responseBody = "";
86
135
  }
87
- const body = responseBody.trim();
88
- const bodySuffix = body === "" ? "" : `, body: ${body.slice(0, 1e3)}`;
89
- return `CodeAPI request failed: ${method} ${endpoint} returned ${response.status}${bodySuffix}`;
136
+ if (response.status === 429) {
137
+ const retryAfterSeconds = getRetryAfterSeconds(responseBody);
138
+ return retryAfterSeconds != null ? `Code execution is temporarily rate-limited. Retry after ${retryAfterSeconds} seconds.` : CODE_API_RATE_LIMITED_ERROR_MESSAGE;
139
+ }
140
+ if (response.status === 401 || response.status === 403) return CODE_API_AUTHORIZATION_ERROR_MESSAGE;
141
+ if (response.status === 400 || response.status === 422) return CODE_API_INVALID_REQUEST_ERROR_MESSAGE;
142
+ return CODE_API_UNAVAILABLE_ERROR_MESSAGE;
90
143
  }
91
144
  const CodeExecutionToolDescription = `
92
145
  Runs code and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.
@@ -173,7 +226,7 @@ function createCodeExecutionTool(params = {}) {
173
226
  };
174
227
  if (process.env.PROXY != null && process.env.PROXY !== "") fetchOptions.agent = new https_proxy_agent.HttpsProxyAgent(process.env.PROXY);
175
228
  const response = await (0, node_fetch.default)(EXEC_ENDPOINT, fetchOptions);
176
- if (!response.ok) throw new Error(await buildCodeApiHttpErrorMessage("POST", EXEC_ENDPOINT, response));
229
+ if (!response.ok) throw new CodeApiRequestError(await buildCodeApiHttpErrorMessage("POST", EXEC_ENDPOINT, response));
177
230
  const result = await response.json();
178
231
  let formattedOutput = "";
179
232
  if (result.stdout) formattedOutput += `stdout:\n${result.stdout}\n`;
@@ -194,7 +247,7 @@ function createCodeExecutionTool(params = {}) {
194
247
  ...runtimeEcho
195
248
  }];
196
249
  } catch (error) {
197
- const messageWithReminder = appendFailedExecutionFileReminder(error?.message ?? "", code);
250
+ const messageWithReminder = appendFailedExecutionFileReminder(normalizeCodeApiRequestError(error).message, code);
198
251
  throw new Error(`Execution error:\n\n${messageWithReminder}`);
199
252
  }
200
253
  }, {
@@ -206,7 +259,13 @@ function createCodeExecutionTool(params = {}) {
206
259
  }
207
260
  //#endregion
208
261
  exports.BASH_SHELL_GUIDANCE = BASH_SHELL_GUIDANCE;
262
+ exports.CODE_API_AUTHORIZATION_ERROR_MESSAGE = CODE_API_AUTHORIZATION_ERROR_MESSAGE;
263
+ exports.CODE_API_EXECUTION_FAILED_ERROR_MESSAGE = CODE_API_EXECUTION_FAILED_ERROR_MESSAGE;
264
+ exports.CODE_API_INVALID_REQUEST_ERROR_MESSAGE = CODE_API_INVALID_REQUEST_ERROR_MESSAGE;
265
+ exports.CODE_API_RATE_LIMITED_ERROR_MESSAGE = CODE_API_RATE_LIMITED_ERROR_MESSAGE;
266
+ exports.CODE_API_UNAVAILABLE_ERROR_MESSAGE = CODE_API_UNAVAILABLE_ERROR_MESSAGE;
209
267
  exports.CODE_ARTIFACT_PATH_GUIDANCE = CODE_ARTIFACT_PATH_GUIDANCE;
268
+ exports.CodeApiRequestError = CodeApiRequestError;
210
269
  exports.CodeExecutionToolDefinition = CodeExecutionToolDefinition;
211
270
  exports.CodeExecutionToolDescription = CodeExecutionToolDescription;
212
271
  exports.CodeExecutionToolName = CodeExecutionToolName;
@@ -217,12 +276,14 @@ exports.StatefulCodeExecutionToolDescription = StatefulCodeExecutionToolDescript
217
276
  exports.TMP_SCRATCH_OUTPUT_REMINDER = TMP_SCRATCH_OUTPUT_REMINDER;
218
277
  exports.appendFailedExecutionFileReminder = appendFailedExecutionFileReminder;
219
278
  exports.appendTmpScratchReminder = appendTmpScratchReminder;
279
+ exports.buildCodeApiExecutionErrorMessage = buildCodeApiExecutionErrorMessage;
220
280
  exports.buildCodeApiHttpErrorMessage = buildCodeApiHttpErrorMessage;
221
281
  exports.buildCodeExecutionToolDescription = buildCodeExecutionToolDescription;
222
282
  exports.buildCodeExecutionToolSchema = buildCodeExecutionToolSchema;
223
283
  exports.createCodeExecutionTool = createCodeExecutionTool;
224
284
  exports.emptyOutputMessage = emptyOutputMessage;
225
285
  exports.getCodeBaseURL = getCodeBaseURL;
286
+ exports.normalizeCodeApiRequestError = normalizeCodeApiRequestError;
226
287
  exports.resolveCodeApiAuthHeaders = resolveCodeApiAuthHeaders;
227
288
 
228
289
  //# sourceMappingURL=CodeExecutor.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"CodeExecutor.cjs","names":["HttpsProxyAgent","appendCodeSessionFileSummary"],"sources":["../../../src/tools/CodeExecutor.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { appendCodeSessionFileSummary } from '@/tools/CodeSessionFileSummary';\nimport { EnvVar, Constants } from '@/common';\n\nexport {\n appendCodeSessionFileSummary,\n stripCodeSessionFileSummary,\n} from '@/tools/CodeSessionFileSummary';\n\nconfig();\n\nexport const getCodeBaseURL = (): string =>\n getEnvironmentVariable(EnvVar.CODE_BASEURL) ??\n Constants.OFFICIAL_CODE_BASEURL;\n\nexport const emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\nexport const CODE_ARTIFACT_PATH_GUIDANCE =\n 'Persist handoff artifacts in `/mnt/data` with standard extensions (.json/.txt/.csv/.tsv/.log/.parquet/.png/.jpg/.pdf/.xlsx); failed executions do not register new files; `/tmp` and odd extensions are same-call scratch only, not later-call storage.';\n\nexport const BASH_SHELL_GUIDANCE =\n 'Bash: multi-line files use heredoc/printf; run Python via python3 -c/heredoc, not bare Python.';\n\nconst TMP_PATH_PATTERN = /(^|[^A-Za-z0-9_])\\/tmp(?:\\/|\\b)/;\nconst MNT_DATA_PATH_PATTERN = /(^|[^A-Za-z0-9_])\\/mnt\\/data(?:\\/|\\b)/;\n\nexport const TMP_SCRATCH_OUTPUT_REMINDER =\n 'Note: /tmp files are same-call scratch only and were not persisted; use /mnt/data for files needed later.';\n\nexport const FAILED_EXECUTION_FILE_REMINDER =\n 'Note: any files written during this failed call were not registered for later calls; fix the error and rerun before relying on them.';\n\nexport function appendTmpScratchReminder(output: string, code: string): string {\n if (!TMP_PATH_PATTERN.test(code)) {\n return output;\n }\n return `${output.trimEnd()}\\n${TMP_SCRATCH_OUTPUT_REMINDER}\\n`;\n}\n\nexport function appendFailedExecutionFileReminder(\n output: string,\n code: string\n): string {\n if (\n !MNT_DATA_PATH_PATTERN.test(code) ||\n output.includes(FAILED_EXECUTION_FILE_REMINDER)\n ) {\n return output;\n }\n return `${output.trimEnd()}\\n${FAILED_EXECUTION_FILE_REMINDER}\\n`;\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- Prior /mnt/data files are available and can be modified in place.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- py: This is not a Jupyter notebook environment. Use \\`print()\\` for all outputs.\n- py: Matplotlib: Use \\`plt.savefig()\\` to save plots as files.\n- js: use the \\`console\\` or \\`process\\` methods for all outputs.\n- r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).\n- Other languages: use appropriate output functions.`,\n },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Additional arguments to execute the code with. This should only be used if the input code requires additional arguments to run.',\n },\n },\n required: ['lang', 'code'],\n} as const;\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\ntype SupportedLanguage = (typeof SUPPORTED_LANGUAGES)[number];\n\nexport async function resolveCodeApiAuthHeaders(\n authHeaders?: t.CodeApiAuthHeaders\n): Promise<t.CodeApiAuthHeaderMap> {\n if (authHeaders == null) {\n return {};\n }\n if (typeof authHeaders === 'function') {\n return authHeaders();\n }\n return authHeaders;\n}\n\nexport async function buildCodeApiHttpErrorMessage(\n method: string,\n endpoint: string,\n response: { status: number; text: () => Promise<string> }\n): Promise<string> {\n let responseBody = '';\n try {\n responseBody = await response.text();\n } catch {\n responseBody = '';\n }\n const body = responseBody.trim();\n const bodySuffix = body === '' ? '' : `, body: ${body.slice(0, 1000)}`;\n return `CodeAPI request failed: ${method} ${endpoint} returned ${response.status}${bodySuffix}`;\n}\n\nexport const CodeExecutionToolDescription = `\nRuns code and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- NEVER use this tool to execute malicious code.\n`.trim();\n\n/**\n * Statefulness here is FILESYSTEM-tier, not runtime-tier. Executions in a\n * session reuse one warm machine, so `/mnt/data` carries across calls — but\n * every execution is a brand-new interpreter process in a fresh sandbox, so\n * variables and imports never survive. The note must not imply otherwise: a\n * model told its in-memory state persists writes `df = ...` in one call and\n * `df.head()` in the next, then hits a NameError it was told to treat as rare.\n */\nexport const STATEFUL_ENV_NOTE =\n 'Session state: executions in this conversation run on the same warm machine, so files persist between calls — but each execution is a NEW process. Variables, imports, and in-memory data NEVER carry over: every call must re-import and rebuild the state it needs. Only /mnt/data is durable (the machine itself may also be reset at any time), so write anything that must survive there and read it back next call.';\n\nexport const StatefulCodeExecutionToolDescription = `\nRuns code and returns stdout/stderr output. Executions in this conversation share one warm machine with a persistent /mnt/data, but each execution runs as a separate process (not a notebook-style kernel).\n\n${STATEFUL_ENV_NOTE}\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- NEVER use this tool to execute malicious code.\n`.trim();\n\nexport function buildCodeExecutionToolDescription(opts?: {\n statefulSessions?: boolean;\n}): string {\n return opts?.statefulSessions === true\n ? StatefulCodeExecutionToolDescription\n : CodeExecutionToolDescription;\n}\n\nconst STATELESS_CODE_PARAM_NOTE =\n 'The environment is stateless; variables and imports don\\'t persist between executions.';\nconst STATEFUL_CODE_PARAM_NOTE =\n 'Executions in this conversation share one warm machine, so files written to /mnt/data persist between calls. Each execution is a new process: variables and imports do NOT carry over — re-import and reload from /mnt/data every call.';\n\nexport function buildCodeExecutionToolSchema(opts?: {\n statefulSessions?: boolean;\n}): typeof CodeExecutionToolSchema {\n const note =\n opts?.statefulSessions === true\n ? STATEFUL_CODE_PARAM_NOTE\n : STATELESS_CODE_PARAM_NOTE;\n const codeDescription =\n CodeExecutionToolSchema.properties.code.description.replace(\n STATELESS_CODE_PARAM_NOTE,\n note\n );\n return {\n ...CodeExecutionToolSchema,\n properties: {\n ...CodeExecutionToolSchema.properties,\n code: {\n ...CodeExecutionToolSchema.properties.code,\n description: codeDescription,\n },\n },\n } as typeof CodeExecutionToolSchema;\n}\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 | null = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput, config) => {\n /* `statefulSessions` is a prompt-only flag (drives the description);\n * keep it out of the wire body. */\n const {\n authHeaders,\n statefulSessions: _statefulSessions,\n ...executionParams\n } = params ?? {};\n void _statefulSessions;\n /* Drop any model-supplied `runtime_session_hint` from the raw args: the\n * hint is host-controlled and must only ever come from ToolNode's\n * injected `_runtime_session_hint` (below). Spreading `...rest` into\n * postData would otherwise let a tool call opt itself into / pick a\n * stateful runtime even when statefulSessions is off. */\n const {\n lang,\n code,\n runtime_session_hint: _ignoredModelHint,\n ...rest\n } = rawInput as {\n lang: SupportedLanguage;\n code: string;\n runtime_session_hint?: unknown;\n args?: string[];\n };\n void _ignoredModelHint;\n /**\n * Extract session context from config.toolCall (injected by ToolNode).\n * - session_id: associates with the previous run.\n * - _injected_files: File refs to pass directly (avoids /files endpoint race condition).\n */\n const { session_id, _injected_files, _runtime_session_hint } =\n (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n _runtime_session_hint?: string;\n };\n\n const postData: Record<string, unknown> = {\n lang,\n code,\n ...rest,\n ...executionParams,\n };\n\n /* Stateful sessions: forward the hint so the Code API can route this\n * execution to a warm per-session runtime. Additive — stateless\n * servers ignore the unknown field. */\n if (\n typeof _runtime_session_hint === 'string' &&\n _runtime_session_hint !== ''\n ) {\n postData.runtime_session_hint = _runtime_session_hint;\n }\n\n /* File injection: `_injected_files` from ToolNode (set when host\n * primes a CodeSessionContext) or `params.files` from tool\n * factory (set by hosts that pre-resolve at construction time).\n * The legacy `/files/<session_id>` HTTP fallback was removed —\n * codeapi's `sessionAuth` middleware now requires kind/id query\n * params the tool can't supply at this point, so the fetch 400'd\n * silently and the catch swallowed the failure. */\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (\n session_id != null &&\n session_id.length > 0 &&\n !Array.isArray(postData.files)\n ) {\n // eslint-disable-next-line no-console\n console.debug(\n `[CodeExecutor] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n try {\n const resolvedAuthHeaders =\n await resolveCodeApiAuthHeaders(authHeaders);\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n ...resolvedAuthHeaders,\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(\n await buildCodeApiHttpErrorMessage('POST', EXEC_ENDPOINT, response)\n );\n }\n\n const result: t.ExecuteResult = await response.json();\n let formattedOutput = '';\n if (result.stdout) {\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\n } else {\n formattedOutput += emptyOutputMessage;\n }\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\n\n const outputWithReminder = appendTmpScratchReminder(\n formattedOutput,\n code\n );\n const hasFiles = result.files != null && result.files.length > 0;\n /* Echo the durable runtime session (stateful backends only) so hosts\n * can surface a \"session active / was reset\" signal later. Additive:\n * absent on stateless servers. */\n const runtimeEcho =\n result.runtime_session_id != null\n ? {\n runtime_session_id: result.runtime_session_id,\n runtime_status: result.runtime_status,\n }\n : {};\n return [\n appendCodeSessionFileSummary(outputWithReminder, result.files),\n (hasFiles\n ? {\n session_id: result.session_id,\n files: result.files,\n ...runtimeEcho,\n }\n : {\n session_id: result.session_id,\n ...runtimeEcho,\n }) satisfies t.CodeExecutionArtifact,\n ];\n } catch (error) {\n const messageWithReminder = appendFailedExecutionFileReminder(\n (error as Error | undefined)?.message ?? '',\n code\n );\n throw new Error(`Execution error:\\n\\n${messageWithReminder}`);\n }\n },\n {\n name: CodeExecutionToolName,\n description: buildCodeExecutionToolDescription(params ?? undefined),\n schema: buildCodeExecutionToolSchema(params ?? undefined),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createCodeExecutionTool };\n"],"mappings":";;;;;;;;;;;mBAcO;AAEP,MAAa,wBAAA,GAAA,0BAAA,uBAAA,CAAA,wBAC+B,KAAA;AAG5C,MAAa,qBACX;AAEF,MAAa,8BACX;AAEF,MAAa,sBACX;AAEF,MAAM,mBAAmB;AACzB,MAAM,wBAAwB;AAE9B,MAAa,8BACX;AAEF,MAAa,iCACX;AAEF,SAAgB,yBAAyB,QAAgB,MAAsB;CAC7E,IAAI,CAAC,iBAAiB,KAAK,IAAI,GAC7B,OAAO;CAET,OAAO,GA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WAAA,QAAA,CAAY,eAAe,YAAY;GACxD,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MACR,MAAM,6BAA6B,QAAQ,eAAe,QAAQ,CACpE;GAGF,MAAM,SAA0B,MAAM,SAAS,KAAK;GACpD,IAAI,kBAAkB;GACtB,IAAI,OAAO,QACT,mBAAmB,YAAY,OAAO,OAAO;QAE7C,mBAAmB;GAErB,IAAI,OAAO,QAAQ,mBAAmB,YAAY,OAAO,OAAO;GAEhE,MAAM,qBAAqB,yBACzB,iBACA,IACF;GACA,MAAM,WAAW,OAAO,SAAS,QAAQ,OAAO,MAAM,SAAS;GAI/D,MAAM,cACJ,OAAO,sBAAsB,OACzB;IACA,oBAAoB,OAAO;IAC3B,gBAAgB,OAAO;GACzB,IACE,CAAC;GACP,OAAO,CACLC,+BAAAA,6BAA6B,oBAAoB,OAAO,KAAK,GAC5D,WACG;IACA,YAAY,OAAO;IACnB,OAAO,OAAO;IACd,GAAG;GACL,IACE;IACA,YAAY,OAAO;IACnB,GAAG;GACL,CACJ;EACF,SAAS,OAAO;GACd,MAAM,sBAAsB,kCACzB,OAA6B,WAAW,IACzC,IACF;GACA,MAAM,IAAI,MAAM,uBAAuB,qBAAqB;EAC9D;CACF,GACA;EACE,MAAM;EACN,aAAa,kCAAkC,UAAU,KAAA,CAAS;EAClE,QAAQ,6BAA6B,UAAU,KAAA,CAAS;EACxD,gBAAA;CACF,CACF;AACF"}
1
+ {"version":3,"file":"CodeExecutor.cjs","names":["HttpsProxyAgent","appendCodeSessionFileSummary"],"sources":["../../../src/tools/CodeExecutor.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { appendCodeSessionFileSummary } from '@/tools/CodeSessionFileSummary';\nimport { EnvVar, Constants } from '@/common';\n\nexport {\n appendCodeSessionFileSummary,\n stripCodeSessionFileSummary,\n} from '@/tools/CodeSessionFileSummary';\n\nconfig();\n\nexport const getCodeBaseURL = (): string =>\n getEnvironmentVariable(EnvVar.CODE_BASEURL) ??\n Constants.OFFICIAL_CODE_BASEURL;\n\nexport const emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\nexport const CODE_ARTIFACT_PATH_GUIDANCE =\n 'Persist handoff artifacts in `/mnt/data` with standard extensions (.json/.txt/.csv/.tsv/.log/.parquet/.png/.jpg/.pdf/.xlsx); failed executions do not register new files; `/tmp` and odd extensions are same-call scratch only, not later-call storage.';\n\nexport const BASH_SHELL_GUIDANCE =\n 'Bash: multi-line files use heredoc/printf; run Python via python3 -c/heredoc, not bare Python.';\n\nconst TMP_PATH_PATTERN = /(^|[^A-Za-z0-9_])\\/tmp(?:\\/|\\b)/;\nconst MNT_DATA_PATH_PATTERN = /(^|[^A-Za-z0-9_])\\/mnt\\/data(?:\\/|\\b)/;\n\nexport const TMP_SCRATCH_OUTPUT_REMINDER =\n 'Note: /tmp files are same-call scratch only and were not persisted; use /mnt/data for files needed later.';\n\nexport const FAILED_EXECUTION_FILE_REMINDER =\n 'Note: any files written during this failed call were not registered for later calls; fix the error and rerun before relying on them.';\n\nexport function appendTmpScratchReminder(output: string, code: string): string {\n if (!TMP_PATH_PATTERN.test(code)) {\n return output;\n }\n return `${output.trimEnd()}\\n${TMP_SCRATCH_OUTPUT_REMINDER}\\n`;\n}\n\nexport function appendFailedExecutionFileReminder(\n output: string,\n code: string\n): string {\n if (\n !MNT_DATA_PATH_PATTERN.test(code) ||\n output.includes(FAILED_EXECUTION_FILE_REMINDER)\n ) {\n return output;\n }\n return `${output.trimEnd()}\\n${FAILED_EXECUTION_FILE_REMINDER}\\n`;\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- Prior /mnt/data files are available and can be modified in place.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\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\nconst MAX_RETRY_AFTER_SECONDS = 3600;\n\nexport const CODE_API_UNAVAILABLE_ERROR_MESSAGE =\n 'Code execution is temporarily unavailable. Please retry.';\nexport const CODE_API_AUTHORIZATION_ERROR_MESSAGE =\n 'Code execution is not authorized. Verify access before trying again.';\nexport const CODE_API_EXECUTION_FAILED_ERROR_MESSAGE = 'Code execution failed.';\nexport const CODE_API_INVALID_REQUEST_ERROR_MESSAGE =\n 'The code execution request was rejected. Please check the tool input and try again.';\nexport const CODE_API_RATE_LIMITED_ERROR_MESSAGE =\n 'Code execution is temporarily rate-limited. Please retry shortly.';\n\nconst SAFE_CODE_API_EXECUTION_ERROR_DETAILS: Readonly<\n Partial<Record<string, string>>\n> = {\n 'Execution failed or timed out': 'Execution failed or timed out.',\n 'Out of memory': 'Execution exceeded the memory limit.',\n 'Time limit exceeded': 'Execution exceeded the time limit.',\n 'sandbox emitted an empty pending tool call block; aborting to avoid a tight retry loop':\n 'Generated code emitted an invalid empty tool request.',\n 'stderr length exceeded': 'Execution error output exceeded the size limit.',\n 'stdout length exceeded': 'Execution output exceeded the size limit.',\n};\n\nexport class CodeApiRequestError extends Error {\n constructor(message = CODE_API_UNAVAILABLE_ERROR_MESSAGE) {\n super(message);\n this.name = 'CodeApiRequestError';\n }\n}\n\nfunction getRetryAfterSeconds(responseBody: string): number | undefined {\n try {\n const parsed = JSON.parse(responseBody) as {\n error?: unknown;\n retry_after_seconds?: unknown;\n };\n if (\n parsed.error !== 'rate_limited' ||\n typeof parsed.retry_after_seconds !== 'number' ||\n !Number.isFinite(parsed.retry_after_seconds) ||\n parsed.retry_after_seconds <= 0\n ) {\n return undefined;\n }\n return Math.min(\n Math.ceil(parsed.retry_after_seconds),\n MAX_RETRY_AFTER_SECONDS\n );\n } catch {\n return undefined;\n }\n}\n\nexport function normalizeCodeApiRequestError(\n error: unknown\n): CodeApiRequestError {\n return error instanceof CodeApiRequestError\n ? error\n : new CodeApiRequestError();\n}\n\nfunction getSafeCodeApiExecutionErrorDetail(\n error: unknown\n): string | undefined {\n if (typeof error !== 'string') {\n return undefined;\n }\n const exactMatch = SAFE_CODE_API_EXECUTION_ERROR_DETAILS[error];\n if (exactMatch != null) {\n return exactMatch;\n }\n if (/^Sandbox exited with code (?:-?\\d{1,4}|unknown)$/.test(error)) {\n return error.replace(/^Sandbox/, 'Execution');\n }\n if (/^Sandbox requested an unregistered tool: .+$/.test(error)) {\n return 'Generated code requested a tool that is not available.';\n }\n return undefined;\n}\n\nexport function buildCodeApiExecutionErrorMessage(response: {\n error?: unknown;\n stderr?: unknown;\n}): string {\n const safeDetail = getSafeCodeApiExecutionErrorDetail(response.error);\n const message =\n safeDetail != null\n ? `${CODE_API_EXECUTION_FAILED_ERROR_MESSAGE} ${safeDetail}`\n : CODE_API_EXECUTION_FAILED_ERROR_MESSAGE;\n if (typeof response.stderr === 'string' && response.stderr !== '') {\n return `${message}\\n\\nStderr:\\n${response.stderr}`;\n }\n return message;\n}\n\nexport async function resolveCodeApiAuthHeaders(\n authHeaders?: t.CodeApiAuthHeaders\n): Promise<t.CodeApiAuthHeaderMap> {\n if (authHeaders == null) {\n return {};\n }\n if (typeof authHeaders === 'function') {\n try {\n const resolvedHeaders = await authHeaders();\n return resolvedHeaders;\n } catch {\n throw new CodeApiRequestError(CODE_API_AUTHORIZATION_ERROR_MESSAGE);\n }\n }\n return authHeaders;\n}\n\nexport async function buildCodeApiHttpErrorMessage(\n _method: string,\n _endpoint: string,\n response: { status: number; text: () => Promise<string> }\n): Promise<string> {\n let responseBody = '';\n try {\n responseBody = await response.text();\n } catch {\n responseBody = '';\n }\n if (response.status === 429) {\n const retryAfterSeconds = getRetryAfterSeconds(responseBody);\n return retryAfterSeconds != null\n ? `Code execution is temporarily rate-limited. Retry after ${retryAfterSeconds} seconds.`\n : CODE_API_RATE_LIMITED_ERROR_MESSAGE;\n }\n if (response.status === 401 || response.status === 403) {\n return CODE_API_AUTHORIZATION_ERROR_MESSAGE;\n }\n if (response.status === 400 || response.status === 422) {\n return CODE_API_INVALID_REQUEST_ERROR_MESSAGE;\n }\n return CODE_API_UNAVAILABLE_ERROR_MESSAGE;\n}\n\nexport const CodeExecutionToolDescription = `\nRuns code and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- NEVER use this tool to execute malicious code.\n`.trim();\n\n/**\n * Statefulness here is FILESYSTEM-tier, not runtime-tier. Executions in a\n * session reuse one warm machine, so `/mnt/data` carries across calls — but\n * every execution is a brand-new interpreter process in a fresh sandbox, so\n * variables and imports never survive. The note must not imply otherwise: a\n * model told its in-memory state persists writes `df = ...` in one call and\n * `df.head()` in the next, then hits a NameError it was told to treat as rare.\n */\nexport const STATEFUL_ENV_NOTE =\n 'Session state: executions in this conversation run on the same warm machine, so files persist between calls — but each execution is a NEW process. Variables, imports, and in-memory data NEVER carry over: every call must re-import and rebuild the state it needs. Only /mnt/data is durable (the machine itself may also be reset at any time), so write anything that must survive there and read it back next call.';\n\nexport const StatefulCodeExecutionToolDescription = `\nRuns code and returns stdout/stderr output. Executions in this conversation share one warm machine with a persistent /mnt/data, but each execution runs as a separate process (not a notebook-style kernel).\n\n${STATEFUL_ENV_NOTE}\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- NEVER use this tool to execute malicious code.\n`.trim();\n\nexport function buildCodeExecutionToolDescription(opts?: {\n statefulSessions?: boolean;\n}): string {\n return opts?.statefulSessions === true\n ? StatefulCodeExecutionToolDescription\n : CodeExecutionToolDescription;\n}\n\nconst STATELESS_CODE_PARAM_NOTE =\n 'The environment is stateless; variables and imports don\\'t persist between executions.';\nconst STATEFUL_CODE_PARAM_NOTE =\n 'Executions in this conversation share one warm machine, so files written to /mnt/data persist between calls. Each execution is a new process: variables and imports do NOT carry over — re-import and reload from /mnt/data every call.';\n\nexport function buildCodeExecutionToolSchema(opts?: {\n statefulSessions?: boolean;\n}): typeof CodeExecutionToolSchema {\n const note =\n opts?.statefulSessions === true\n ? STATEFUL_CODE_PARAM_NOTE\n : STATELESS_CODE_PARAM_NOTE;\n const codeDescription =\n CodeExecutionToolSchema.properties.code.description.replace(\n STATELESS_CODE_PARAM_NOTE,\n note\n );\n return {\n ...CodeExecutionToolSchema,\n properties: {\n ...CodeExecutionToolSchema.properties,\n code: {\n ...CodeExecutionToolSchema.properties.code,\n description: codeDescription,\n },\n },\n } as typeof CodeExecutionToolSchema;\n}\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 | null = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput, config) => {\n /* `statefulSessions` is a prompt-only flag (drives the description);\n * keep it out of the wire body. */\n const {\n authHeaders,\n statefulSessions: _statefulSessions,\n ...executionParams\n } = params ?? {};\n void _statefulSessions;\n /* Drop any model-supplied `runtime_session_hint` from the raw args: the\n * hint is host-controlled and must only ever come from ToolNode's\n * injected `_runtime_session_hint` (below). Spreading `...rest` into\n * postData would otherwise let a tool call opt itself into / pick a\n * stateful runtime even when statefulSessions is off. */\n const {\n lang,\n code,\n runtime_session_hint: _ignoredModelHint,\n ...rest\n } = rawInput as {\n lang: SupportedLanguage;\n code: string;\n runtime_session_hint?: unknown;\n args?: string[];\n };\n void _ignoredModelHint;\n /**\n * Extract session context from config.toolCall (injected by ToolNode).\n * - session_id: associates with the previous run.\n * - _injected_files: File refs to pass directly (avoids /files endpoint race condition).\n */\n const { session_id, _injected_files, _runtime_session_hint } =\n (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n _runtime_session_hint?: string;\n };\n\n const postData: Record<string, unknown> = {\n lang,\n code,\n ...rest,\n ...executionParams,\n };\n\n /* Stateful sessions: forward the hint so the Code API can route this\n * execution to a warm per-session runtime. Additive — stateless\n * servers ignore the unknown field. */\n if (\n typeof _runtime_session_hint === 'string' &&\n _runtime_session_hint !== ''\n ) {\n postData.runtime_session_hint = _runtime_session_hint;\n }\n\n /* File injection: `_injected_files` from ToolNode (set when host\n * primes a CodeSessionContext) or `params.files` from tool\n * factory (set by hosts that pre-resolve at construction time).\n * The legacy `/files/<session_id>` HTTP fallback was removed —\n * codeapi's `sessionAuth` middleware now requires kind/id query\n * params the tool can't supply at this point, so the fetch 400'd\n * silently and the catch swallowed the failure. */\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (\n session_id != null &&\n session_id.length > 0 &&\n !Array.isArray(postData.files)\n ) {\n // eslint-disable-next-line no-console\n console.debug(\n `[CodeExecutor] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n try {\n const resolvedAuthHeaders =\n await resolveCodeApiAuthHeaders(authHeaders);\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n ...resolvedAuthHeaders,\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new CodeApiRequestError(\n await buildCodeApiHttpErrorMessage('POST', EXEC_ENDPOINT, response)\n );\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\n const outputWithReminder = appendTmpScratchReminder(\n formattedOutput,\n code\n );\n const hasFiles = result.files != null && result.files.length > 0;\n /* Echo the durable runtime session (stateful backends only) so hosts\n * can surface a \"session active / was reset\" signal later. Additive:\n * absent on stateless servers. */\n const runtimeEcho =\n result.runtime_session_id != null\n ? {\n runtime_session_id: result.runtime_session_id,\n runtime_status: result.runtime_status,\n }\n : {};\n return [\n appendCodeSessionFileSummary(outputWithReminder, result.files),\n (hasFiles\n ? {\n session_id: result.session_id,\n files: result.files,\n ...runtimeEcho,\n }\n : {\n session_id: result.session_id,\n ...runtimeEcho,\n }) satisfies t.CodeExecutionArtifact,\n ];\n } catch (error) {\n const messageWithReminder = appendFailedExecutionFileReminder(\n normalizeCodeApiRequestError(error).message,\n code\n );\n throw new Error(`Execution error:\\n\\n${messageWithReminder}`);\n }\n },\n {\n name: CodeExecutionToolName,\n description: buildCodeExecutionToolDescription(params ?? undefined),\n schema: buildCodeExecutionToolSchema(params ?? undefined),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createCodeExecutionTool };\n"],"mappings":";;;;;;;;;;;mBAcO;AAEP,MAAa,wBAAA,GAAA,0BAAA,uBAAA,CAAA,wBAC+B,KAAA;AAG5C,MAAa,qBACX;AAEF,MAAa,8BACX;AAEF,MAAa,sBACX;AAEF,MAAM,mBAAmB;AACzB,MAAM,wBAAwB;AAE9B,MAAa,8BACX;AAEF,MAAa,iCACX;AAEF,SAAgB,yBAAyB,QAAgB,MAAsB;CAC7E,IAAI,CAAC,iBAAiB,KAAK,IAAI,GAC7B,OAAO;CAET,OAAO,GAAG,OAAO,QAAQ,EAAE,IAAI,4BAA4B;AAC7D;AAEA,SAAgB,kCACd,QACA,MACQ;CACR,IACE,CAAC,sBAAsB,KAAK,IAAI,KAChC,OAAO,SAAA,sIAAuC,GAE9C,OAAO;CAET,OAAO,GAAG,OAAO,QAAQ,EAAE,IAAI,+BAA+B;AAChE;AAkBA,MAAa,0BAA0B;CACrC,MAAM;CACN,YAAY;EACV,MAAM;GACJ,MAAM;GACN,MAAM;IApBV;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;GAQU;GACN,aACE;EACJ;EACA,MAAM;GACJ,MAAM;GACN,aAAa;;;IAGf,4BAA4B;;;;;;;;;EAS5B;EACA,MAAM;GACJ,MAAM;GACN,OAAO,EAAE,MAAM,SAAS;GACxB,aACE;EACJ;CACF;CACA,UAAU,CAAC,QAAQ,MAAM;AAC3B;AAGA,MAAM,gBAAgB,GADD,eACe,EAAE;AAItC,MAAM,0BAA0B;AAEhC,MAAa,qCACX;AACF,MAAa,uCACX;AACF,MAAa,0CAA0C;AACvD,MAAa,yCACX;AACF,MAAa,sCACX;AAEF,MAAM,wCAEF;CAC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F,SAAS,OAAO;GACd,MAAM,sBAAsB,kCAC1B,6BAA6B,KAAK,CAAC,CAAC,SACpC,IACF;GACA,MAAM,IAAI,MAAM,uBAAuB,qBAAqB;EAC9D;CACF,GACA;EACE,MAAM;EACN,aAAa,kCAAkC,UAAU,KAAA,CAAS;EAClE,QAAQ,6BAA6B,UAAU,KAAA,CAAS;EACxD,gBAAA;CACF,CACF;AACF"}
@@ -271,19 +271,23 @@ async function fetchSessionFiles(baseUrl, sessionId, scopeOrProxy, proxyOrAuthHe
271
271
  * @returns The parsed API response
272
272
  */
273
273
  async function makeRequest(endpoint, body, proxy, authHeaders) {
274
- const fetchOptions = {
275
- method: "POST",
276
- headers: {
277
- "Content-Type": "application/json",
278
- "User-Agent": "LibreChat/1.0",
279
- ...await require_CodeExecutor.resolveCodeApiAuthHeaders(authHeaders)
280
- },
281
- body: JSON.stringify(body)
282
- };
283
- if (proxy != null && proxy !== "") fetchOptions.agent = new https_proxy_agent.HttpsProxyAgent(proxy);
284
- const response = await (0, node_fetch.default)(endpoint, fetchOptions);
285
- if (!response.ok) throw new Error(await require_CodeExecutor.buildCodeApiHttpErrorMessage("POST", endpoint, response));
286
- return await response.json();
274
+ try {
275
+ const fetchOptions = {
276
+ method: "POST",
277
+ headers: {
278
+ "Content-Type": "application/json",
279
+ "User-Agent": "LibreChat/1.0",
280
+ ...await require_CodeExecutor.resolveCodeApiAuthHeaders(authHeaders)
281
+ },
282
+ body: JSON.stringify(body)
283
+ };
284
+ if (proxy != null && proxy !== "") fetchOptions.agent = new https_proxy_agent.HttpsProxyAgent(proxy);
285
+ const response = await (0, node_fetch.default)(endpoint, fetchOptions);
286
+ if (!response.ok) throw new require_CodeExecutor.CodeApiRequestError(await require_CodeExecutor.buildCodeApiHttpErrorMessage("POST", endpoint, response));
287
+ return await response.json();
288
+ } catch (error) {
289
+ throw require_CodeExecutor.normalizeCodeApiRequestError(error);
290
+ }
287
291
  }
288
292
  /**
289
293
  * Unwraps tool responses that may be formatted as tuples or content blocks.
@@ -543,8 +547,8 @@ function createProgrammaticToolCallingTool(initParams = {}) {
543
547
  }, proxy, initParams.authHeaders);
544
548
  }
545
549
  if (response.status === "completed") return formatCompletedResponse(response, code);
546
- if (response.status === "error") throw new Error(`Execution error: ${response.error}` + (response.stderr != null && response.stderr !== "" ? `\n\nStderr:\n${response.stderr}` : ""));
547
- throw new Error(`Unexpected response status: ${response.status}`);
550
+ if (response.status === "error") throw new Error(require_CodeExecutor.buildCodeApiExecutionErrorMessage(response));
551
+ throw new require_CodeExecutor.CodeApiRequestError();
548
552
  } catch (error) {
549
553
  const messageWithReminder = require_CodeExecutor.appendFailedExecutionFileReminder(error.message, code);
550
554
  throw new Error(`Programmatic execution failed: ${messageWithReminder}`);
@@ -1 +1 @@
1
- {"version":3,"file":"ProgrammaticToolCalling.cjs","names":["resolveCodeApiRunTimeoutMs","CODE_ARTIFACT_PATH_GUIDANCE","createCodeApiRunTimeoutSchema","resolveCodeApiAuthHeaders","HttpsProxyAgent","buildCodeApiHttpErrorMessage","obj","emptyOutputMessage","appendCodeSessionFileSummary","appendTmpScratchReminder","getCodeBaseURL","clampCodeApiRunTimeoutMs","appendFailedExecutionFileReminder"],"sources":["../../../src/tools/ProgrammaticToolCalling.ts"],"sourcesContent":["// src/tools/ProgrammaticToolCalling.ts\nimport { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { ProgrammaticToolCallingJsonSchema } from './ptcTimeout';\nimport type * as t from '@/types';\nimport {\n CODE_ARTIFACT_PATH_GUIDANCE,\n appendCodeSessionFileSummary,\n appendFailedExecutionFileReminder,\n buildCodeApiHttpErrorMessage,\n emptyOutputMessage,\n getCodeBaseURL,\n appendTmpScratchReminder,\n resolveCodeApiAuthHeaders,\n} from './CodeExecutor';\nimport {\n clampCodeApiRunTimeoutMs,\n createCodeApiRunTimeoutSchema,\n resolveCodeApiRunTimeoutMs,\n} from './ptcTimeout';\nimport { Constants } from '@/common';\n\nconfig();\n\n/** Default max round-trips to prevent infinite loops */\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\n\nconst DEFAULT_RUN_TIMEOUT_MS = resolveCodeApiRunTimeoutMs();\n\n// ============================================================================\n// Description Components (Single Source of Truth)\n// ============================================================================\n\nconst STATELESS_WARNING = `CRITICAL - 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\nconst CORE_RULES = `Rules:\n- One call: state does not persist\n- Auto-wrapped async; use await, no main()/asyncio.run()\n- Tools are pre-defined—DO NOT write function definitions\n- Call tools with keyword args only (await tool(arg=value), never pass a dict)\n- Tool results are decoded Python values (dict/list/str)\n- Only print() output returns to the model\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- timeout caps one sandbox run/replay iteration, not the total multi-round-trip workflow`;\n\nconst ADDITIONAL_RULES =\n '- Tool names normalized: hyphens→underscores, keywords get `_tool` suffix';\n\nconst EXAMPLES = `Example (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\n// ============================================================================\n// Schema\n// ============================================================================\n\nconst CODE_PARAM_DESCRIPTION = `Python code that calls tools programmatically. Tools are available as async functions.\n\n${STATELESS_WARNING}\n\nYour code is auto-wrapped in async context. Just write logic with await—no boilerplate needed.\n\n${EXAMPLES}\n\n${CORE_RULES}`;\n\nexport function createProgrammaticToolCallingSchema(\n maxRunTimeoutMs = DEFAULT_RUN_TIMEOUT_MS\n): ProgrammaticToolCallingJsonSchema {\n return {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n minLength: 1,\n description: CODE_PARAM_DESCRIPTION,\n },\n timeout: createCodeApiRunTimeoutSchema(maxRunTimeoutMs),\n },\n required: ['code'],\n } as const;\n}\n\nexport const ProgrammaticToolCallingSchema =\n createProgrammaticToolCallingSchema();\n\nexport const ProgrammaticToolCallingName = Constants.PROGRAMMATIC_TOOL_CALLING;\n\nexport const ProgrammaticToolCallingDescription = `\nRun tools via Python code. Auto-wrapped in async context—just use \\`await\\` directly.\n\n${STATELESS_WARNING}\n\n${CORE_RULES}\n${ADDITIONAL_RULES}\n\nWhen to use: loops, conditionals, parallel (\\`asyncio.gather\\`), multi-step pipelines.\n\n${EXAMPLES}\n`.trim();\n\nexport const ProgrammaticToolCallingDefinition = {\n name: ProgrammaticToolCallingName,\n description: ProgrammaticToolCallingDescription,\n schema: ProgrammaticToolCallingSchema,\n} as const;\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\nexport type FetchSessionFilesScope =\n | { kind: 'skill'; id: string; version: number }\n | { kind: 'agent' | 'user'; id: string; version?: never };\n\ntype CodeApiSessionFileWire = {\n id?: unknown;\n name?: unknown;\n metadata?: unknown;\n resource_id?: unknown;\n storage_session_id?: unknown;\n};\n\ntype CodeApiSessionFileMetadata = {\n 'original-filename'?: unknown;\n};\n\nfunction isFetchSessionFilesScope(\n value: unknown\n): value is FetchSessionFilesScope {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n const scope = value as { kind?: unknown; id?: unknown; version?: unknown };\n if (\n (scope.kind === 'agent' || scope.kind === 'user') &&\n typeof scope.id === 'string'\n ) {\n return true;\n }\n return (\n scope.kind === 'skill' &&\n typeof scope.id === 'string' &&\n typeof scope.version === 'number'\n );\n}\n\nfunction isCodeApiAuthHeaders(\n value: string | t.CodeApiAuthHeaders | undefined\n): value is t.CodeApiAuthHeaders {\n return value != null && typeof value !== 'string';\n}\n\nfunction isCodeApiSessionFileWire(\n value: unknown\n): value is CodeApiSessionFileWire {\n return value != null && typeof value === 'object';\n}\n\nfunction isCodeApiSessionFileMetadata(\n value: unknown\n): value is CodeApiSessionFileMetadata {\n return value != null && typeof value === 'object';\n}\n\nfunction normalizeSessionFile(\n file: CodeApiSessionFileWire,\n sessionId: string,\n scope?: FetchSessionFilesScope\n): t.CodeEnvFile {\n const metadata = isCodeApiSessionFileMetadata(file.metadata)\n ? file.metadata\n : undefined;\n const rawName = typeof file.name === 'string' ? file.name : '';\n const nameParts = rawName.split('/');\n const fallbackId = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n const id =\n typeof file.id === 'string' && file.id !== '' ? file.id : fallbackId;\n const originalFilename = metadata?.['original-filename'];\n const name =\n typeof originalFilename === 'string' ? originalFilename : rawName;\n const storage_session_id =\n typeof file.storage_session_id === 'string'\n ? file.storage_session_id\n : sessionId;\n const resource_id =\n typeof file.resource_id === 'string' && file.resource_id !== ''\n ? file.resource_id\n : (scope?.id ?? id);\n\n if (scope?.kind === 'skill') {\n return {\n storage_session_id,\n kind: 'skill',\n id,\n resource_id,\n name,\n version: scope.version,\n };\n }\n if (scope != null) {\n return {\n storage_session_id,\n kind: scope.kind,\n id,\n resource_id,\n name,\n };\n }\n return {\n storage_session_id,\n kind: 'user',\n id,\n resource_id: id,\n name,\n };\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 sessionId - The session ID to fetch files from\n * @param scope - Resource scope used by CodeAPI to authorize the session\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 sessionId: string,\n proxy?: string,\n authHeaders?: t.CodeApiAuthHeaders\n): Promise<t.CodeEnvFile[]>;\nexport async function fetchSessionFiles(\n baseUrl: string,\n sessionId: string,\n scope: FetchSessionFilesScope,\n proxyOrAuthHeaders?: string | t.CodeApiAuthHeaders,\n authHeaders?: t.CodeApiAuthHeaders\n): Promise<t.CodeEnvFile[]>;\nexport async function fetchSessionFiles(\n baseUrl: string,\n sessionId: string,\n scopeOrProxy?: FetchSessionFilesScope | string,\n proxyOrAuthHeaders?: string | t.CodeApiAuthHeaders,\n scopedAuthHeaders?: t.CodeApiAuthHeaders\n): Promise<t.CodeEnvFile[]> {\n try {\n const scope = isFetchSessionFilesScope(scopeOrProxy)\n ? scopeOrProxy\n : undefined;\n let proxy: string | undefined;\n let authHeaders: t.CodeApiAuthHeaders | undefined;\n if (scope == null) {\n proxy = typeof scopeOrProxy === 'string' ? scopeOrProxy : undefined;\n authHeaders = isCodeApiAuthHeaders(proxyOrAuthHeaders)\n ? proxyOrAuthHeaders\n : undefined;\n } else if (typeof proxyOrAuthHeaders === 'string') {\n proxy = proxyOrAuthHeaders;\n authHeaders = scopedAuthHeaders;\n } else {\n authHeaders = proxyOrAuthHeaders ?? scopedAuthHeaders;\n }\n const query = new URLSearchParams({ detail: 'full' });\n if (scope != null) {\n query.set('kind', scope.kind);\n query.set('id', scope.id);\n if (scope.kind === 'skill') {\n query.set('version', String(scope.version));\n }\n }\n const filesEndpoint = `${baseUrl}/files/${encodeURIComponent(sessionId)}?${query.toString()}`;\n const resolvedAuthHeaders = await resolveCodeApiAuthHeaders(authHeaders);\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'LibreChat/1.0',\n ...resolvedAuthHeaders,\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(\n await buildCodeApiHttpErrorMessage('GET', filesEndpoint, response)\n );\n }\n\n const files = await response.json();\n if (!Array.isArray(files) || files.length === 0) {\n return [];\n }\n\n return files\n .filter(isCodeApiSessionFileWire)\n .map((file) => normalizeSessionFile(file, sessionId, scope));\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 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 body: Record<string, unknown>,\n proxy?: string,\n authHeaders?: t.CodeApiAuthHeaders\n): Promise<t.ProgrammaticExecutionResponse> {\n const resolvedAuthHeaders = await resolveCodeApiAuthHeaders(authHeaders);\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n ...resolvedAuthHeaders,\n },\n body: JSON.stringify(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 throw new Error(\n await buildCodeApiHttpErrorMessage('POST', endpoint, response)\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\ntype ToolInputSchemaKind = {\n object: boolean;\n string: boolean;\n};\n\nfunction detectSchemaKind(schema: unknown): ToolInputSchemaKind {\n const kind: ToolInputSchemaKind = { object: false, string: false };\n\n if (!schema || typeof schema !== 'object') {\n return kind;\n }\n\n const jsonSchemaType = (schema as { type?: unknown }).type;\n if (jsonSchemaType === 'object') {\n kind.object = true;\n } else if (jsonSchemaType === 'string') {\n kind.string = true;\n } else if (Array.isArray(jsonSchemaType)) {\n kind.object = jsonSchemaType.includes('object');\n kind.string = jsonSchemaType.includes('string');\n }\n\n const zodDef = (schema as { _def?: unknown })._def;\n if (!zodDef || typeof zodDef !== 'object') {\n return kind;\n }\n\n const zodType = (zodDef as { type?: unknown; typeName?: unknown }).type;\n const zodTypeName = (zodDef as { type?: unknown; typeName?: unknown })\n .typeName;\n\n if (zodType === 'object' || zodTypeName === 'ZodObject') {\n kind.object = true;\n } else if (zodType === 'string' || zodTypeName === 'ZodString') {\n kind.string = true;\n }\n\n const innerSchema =\n (\n zodDef as {\n innerType?: unknown;\n schema?: unknown;\n type?: unknown;\n }\n ).innerType ?? (zodDef as { schema?: unknown }).schema;\n if (innerSchema) {\n const innerKind = detectSchemaKind(innerSchema);\n kind.object ||= innerKind.object;\n kind.string ||= innerKind.string;\n }\n\n const options = (zodDef as { options?: unknown }).options;\n if (Array.isArray(options)) {\n for (const option of options) {\n const optionKind = detectSchemaKind(option);\n kind.object ||= optionKind.object;\n kind.string ||= optionKind.string;\n }\n }\n\n return kind;\n}\n\nfunction getToolInputSchemaKind(tool: t.GenericTool): ToolInputSchemaKind {\n if (tool.constructor.name === 'DynamicTool') {\n return { object: false, string: true };\n }\n\n const schema = (tool as { schema?: unknown }).schema;\n return detectSchemaKind(schema);\n}\n\nfunction normalizeToolInput(\n input: t.PTCToolCall['input'],\n tool: t.GenericTool\n): t.PTCToolCall['input'] {\n const schemaKind = getToolInputSchemaKind(tool);\n\n if (typeof input !== 'string') {\n if (!schemaKind.string || schemaKind.object) {\n return input;\n }\n\n const inputValue = (input as { input?: unknown }).input;\n if (typeof inputValue === 'string') {\n return input;\n }\n\n return JSON.stringify(input);\n }\n\n if (!schemaKind.object || schemaKind.string) {\n return input;\n }\n\n const trimmed = input.trim();\n if (!trimmed.startsWith('{')) {\n return input;\n }\n\n try {\n const parsed: unknown = JSON.parse(trimmed);\n if (\n typeof parsed === 'object' &&\n parsed !== null &&\n !Array.isArray(parsed)\n ) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n return input;\n }\n\n return input;\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 programmaticToolName = Constants.PROGRAMMATIC_TOOL_CALLING\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(normalizeToolInput(call.input, tool), {\n metadata: { [programmaticToolName]: 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 *\n * Output includes stdout/stderr plus a compact session-file summary\n * when artifacts were persisted. The artifact still carries every\n * file so the host's session map stays in sync.\n *\n * @param response - The completed API response\n * @returns Tuple of [formatted string, artifact]\n */\nexport function formatCompletedResponse(\n response: t.ProgrammaticExecutionResponse,\n sourceCode = ''\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 const outputWithReminder = appendTmpScratchReminder(formatted, sourceCode);\n\n return [\n appendCodeSessionFileSummary(outputWithReminder, response.files),\n {\n session_id: response.session_id,\n files: response.files,\n ...(response.runtime_session_id != null\n ? {\n runtime_session_id: response.runtime_session_id,\n runtime_status: response.runtime_status,\n }\n : {}),\n } satisfies t.ProgrammaticExecutionArtifact,\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 (baseUrl, maxRoundTrips, proxy)\n * @returns A LangChain DynamicStructuredTool for programmatic tool calling\n *\n * @example\n * const ptcTool = createProgrammaticToolCallingTool({ maxRoundTrips: 20 });\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 {\n const baseUrl = initParams.baseUrl ?? getCodeBaseURL();\n const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;\n const maxRunTimeoutMs = resolveCodeApiRunTimeoutMs(initParams.runTimeoutMs);\n const proxy = initParams.proxy ?? process.env.PROXY;\n const debug = initParams.debug ?? process.env.PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n return tool(\n async (rawParams, config) => {\n const params = rawParams as { code: string; timeout?: number };\n const { code } = params;\n const timeout = clampCodeApiRunTimeoutMs(params.timeout, maxRunTimeoutMs);\n\n // Extra params injected by ToolNode (follows web_search pattern).\n const toolCall = (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache> & {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n _runtime_session_hint?: string;\n };\n const {\n toolMap,\n toolDefs,\n session_id,\n _injected_files,\n _runtime_session_hint,\n } = toolCall;\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error(\n 'No toolMap provided. ' +\n 'ToolNode should inject this from AgentContext when invoked through the graph.'\n );\n }\n\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided. ' +\n 'Either pass tools in the input or ensure ToolNode injects toolDefs.'\n );\n }\n\n let roundTrip = 0;\n\n try {\n // ====================================================================\n // Phase 1: Filter tools and make initial request\n // ====================================================================\n\n const effectiveTools = 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 /**\n * File injection: `_injected_files` from ToolNode session\n * context. The legacy `/files/<session_id>` HTTP fallback was\n * removed (see `CodeExecutor.ts`) — codeapi's sessionAuth now\n * requires kind/id query params unavailable at this point.\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 // eslint-disable-next-line no-console\n console.debug(\n `[ProgrammaticToolCalling] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n /* Stateful sessions: hint rides the INITIAL request only; the server\n * binds continuation round-trips to the same runtime via the\n * continuation_token. Additive — ignored by stateless servers. PTC\n * keeps its stateless prompt in v1; only the wire hint plumbs here. */\n const runtimeSessionHint =\n typeof _runtime_session_hint === 'string' &&\n _runtime_session_hint !== ''\n ? _runtime_session_hint\n : undefined;\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n {\n code,\n tools: effectiveTools,\n session_id,\n timeout,\n ...(files && files.length > 0 ? { files } : {}),\n ...(runtimeSessionHint != null\n ? { runtime_session_hint: runtimeSessionHint }\n : {}),\n },\n proxy,\n initParams.authHeaders\n );\n\n // ====================================================================\n // Phase 2: Handle response loop\n // ====================================================================\n\n while (response.status === 'tool_call_required') {\n roundTrip++;\n\n if (roundTrip > maxRoundTrips) {\n throw new Error(\n `Exceeded maximum round trips (${maxRoundTrips}). ` +\n 'This may indicate an infinite loop, excessive tool calls, ' +\n 'or a logic error in your code.'\n );\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[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 {\n continuation_token: response.continuation_token,\n tool_results: toolResults,\n },\n proxy,\n initParams.authHeaders\n );\n }\n\n // ====================================================================\n // Phase 3: Handle final state\n // ====================================================================\n\n if (response.status === 'completed') {\n return formatCompletedResponse(response, code);\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 const messageWithReminder = appendFailedExecutionFileReminder(\n (error as Error).message,\n code\n );\n throw new Error(\n `Programmatic execution failed: ${messageWithReminder}`\n );\n }\n },\n {\n name: Constants.PROGRAMMATIC_TOOL_CALLING,\n description: ProgrammaticToolCallingDescription,\n schema: createProgrammaticToolCallingSchema(maxRunTimeoutMs),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"mappings":";;;;;;;;;;;;mBAyBO;;AAGP,MAAM,0BAA0B;AAEhC,MAAM,yBAAyBA,mBAAAA,2BAA2B;AAM1D,MAAM,oBAAoB;;;;AAK1B,MAAM,aAAa;;;;;;;IAOfC,qBAAAA,4BAA4B;;AAGhC,MAAM,mBACJ;AAEF,MAAM,WAAW;;;;;;;;;;;;;AAkBjB,MAAM,yBAAyB;;EAE7B,kBAAkB;;;;EAIlB,SAAS;;EAET;AAEF,SAAgB,oCACd,kBAAkB,wBACiB;CACnC,OAAO;EACL,MAAM;EACN,YAAY;GACV,MAAM;IACJ,MAAM;IACN,WAAW;IACX,aAAa;GACf;GACA,SAASC,mBAAAA,8BAA8B,eAAe;EACxD;EACA,UAAU,CAAC,MAAM;CACnB;AACF;AAEA,MAAa,gCACX,oCAAoC;AAEtC,MAAa,8BAAA;AAEb,MAAa,qCAAqC;;;EAGhD,kBAAkB;;EAElB,WAAW;EACX,iBAAiB;;;;EAIjB,SAAS;EACT,KAAK;AAEP,MAAa,oCAAoC;CAC/C,MAAM;CACN,aAAa;CACb,QAAQ;AACV;;AAOA,MAAM,kBAAk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BAAsB,OACtB,EAAE,sBAAsB,mBAAmB,IAC3C,CAAC;GACP,GACA,OACA,WAAW,WACb;GAMA,OAAO,SAAS,WAAW,sBAAsB;IAC/C;IAEA,IAAI,YAAY,eACd,MAAM,IAAI,MACR,iCAAiC,cAAc,4FAGjD;IAGF,IAAI,OAEF,QAAQ,IACN,0BAA0B,UAAU,IAAI,SAAS,YAAY,UAAU,EAAE,oBAC3E;IAGF,MAAM,cAAc,MAAM,aACxB,SAAS,cAAc,CAAC,GACxB,OACF;IAEA,WAAW,MAAM,YACf,eACA;KACE,oBAAoB,SAAS;KAC7B,cAAc;IAChB,GACA,OACA,WAAW,WACb;GACF;GAMA,IAAI,SAAS,WAAW,aACtB,OAAO,wBAAwB,UAAU,IAAI;GAG/C,IAAI,SAAS,WAAW,SACtB,MAAM,IAAI,MACR,oBAAoB,SAAS,WAC1B,SAAS,UAAU,QAAQ,SAAS,WAAW,KAC5C,gBAAgB,SAAS,WACzB,GACR;GAGF,MAAM,IAAI,MAAM,+BAA+B,SAAS,QAAQ;EAClE,SAAS,OAAO;GACd,MAAM,sBAAsBC,qBAAAA,kCACzB,MAAgB,SACjB,IACF;GACA,MAAM,IAAI,MACR,kCAAkC,qBACpC;EACF;CACF,GACA;EACE,MAAA;EACA,aAAa;EACb,QAAQ,oCAAoC,eAAe;EAC3D,gBAAA;CACF,CACF;AACF"}
1
+ {"version":3,"file":"ProgrammaticToolCalling.cjs","names":["resolveCodeApiRunTimeoutMs","CODE_ARTIFACT_PATH_GUIDANCE","createCodeApiRunTimeoutSchema","resolveCodeApiAuthHeaders","HttpsProxyAgent","buildCodeApiHttpErrorMessage","CodeApiRequestError","normalizeCodeApiRequestError","obj","emptyOutputMessage","appendCodeSessionFileSummary","appendTmpScratchReminder","getCodeBaseURL","clampCodeApiRunTimeoutMs","buildCodeApiExecutionErrorMessage","appendFailedExecutionFileReminder"],"sources":["../../../src/tools/ProgrammaticToolCalling.ts"],"sourcesContent":["// src/tools/ProgrammaticToolCalling.ts\nimport { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { ProgrammaticToolCallingJsonSchema } from './ptcTimeout';\nimport type * as t from '@/types';\nimport {\n CODE_ARTIFACT_PATH_GUIDANCE,\n appendCodeSessionFileSummary,\n appendFailedExecutionFileReminder,\n buildCodeApiExecutionErrorMessage,\n buildCodeApiHttpErrorMessage,\n CodeApiRequestError,\n emptyOutputMessage,\n getCodeBaseURL,\n appendTmpScratchReminder,\n normalizeCodeApiRequestError,\n resolveCodeApiAuthHeaders,\n} from './CodeExecutor';\nimport {\n clampCodeApiRunTimeoutMs,\n createCodeApiRunTimeoutSchema,\n resolveCodeApiRunTimeoutMs,\n} from './ptcTimeout';\nimport { Constants } from '@/common';\n\nconfig();\n\n/** Default max round-trips to prevent infinite loops */\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\n\nconst DEFAULT_RUN_TIMEOUT_MS = resolveCodeApiRunTimeoutMs();\n\n// ============================================================================\n// Description Components (Single Source of Truth)\n// ============================================================================\n\nconst STATELESS_WARNING = `CRITICAL - 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\nconst CORE_RULES = `Rules:\n- One call: state does not persist\n- Auto-wrapped async; use await, no main()/asyncio.run()\n- Tools are pre-defined—DO NOT write function definitions\n- Call tools with keyword args only (await tool(arg=value), never pass a dict)\n- Tool results are decoded Python values (dict/list/str)\n- Only print() output returns to the model\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- timeout caps one sandbox run/replay iteration, not the total multi-round-trip workflow`;\n\nconst ADDITIONAL_RULES =\n '- Tool names normalized: hyphens→underscores, keywords get `_tool` suffix';\n\nconst EXAMPLES = `Example (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\n// ============================================================================\n// Schema\n// ============================================================================\n\nconst CODE_PARAM_DESCRIPTION = `Python code that calls tools programmatically. Tools are available as async functions.\n\n${STATELESS_WARNING}\n\nYour code is auto-wrapped in async context. Just write logic with await—no boilerplate needed.\n\n${EXAMPLES}\n\n${CORE_RULES}`;\n\nexport function createProgrammaticToolCallingSchema(\n maxRunTimeoutMs = DEFAULT_RUN_TIMEOUT_MS\n): ProgrammaticToolCallingJsonSchema {\n return {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n minLength: 1,\n description: CODE_PARAM_DESCRIPTION,\n },\n timeout: createCodeApiRunTimeoutSchema(maxRunTimeoutMs),\n },\n required: ['code'],\n } as const;\n}\n\nexport const ProgrammaticToolCallingSchema =\n createProgrammaticToolCallingSchema();\n\nexport const ProgrammaticToolCallingName = Constants.PROGRAMMATIC_TOOL_CALLING;\n\nexport const ProgrammaticToolCallingDescription = `\nRun tools via Python code. Auto-wrapped in async context—just use \\`await\\` directly.\n\n${STATELESS_WARNING}\n\n${CORE_RULES}\n${ADDITIONAL_RULES}\n\nWhen to use: loops, conditionals, parallel (\\`asyncio.gather\\`), multi-step pipelines.\n\n${EXAMPLES}\n`.trim();\n\nexport const ProgrammaticToolCallingDefinition = {\n name: ProgrammaticToolCallingName,\n description: ProgrammaticToolCallingDescription,\n schema: ProgrammaticToolCallingSchema,\n} as const;\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\nexport type FetchSessionFilesScope =\n | { kind: 'skill'; id: string; version: number }\n | { kind: 'agent' | 'user'; id: string; version?: never };\n\ntype CodeApiSessionFileWire = {\n id?: unknown;\n name?: unknown;\n metadata?: unknown;\n resource_id?: unknown;\n storage_session_id?: unknown;\n};\n\ntype CodeApiSessionFileMetadata = {\n 'original-filename'?: unknown;\n};\n\nfunction isFetchSessionFilesScope(\n value: unknown\n): value is FetchSessionFilesScope {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n const scope = value as { kind?: unknown; id?: unknown; version?: unknown };\n if (\n (scope.kind === 'agent' || scope.kind === 'user') &&\n typeof scope.id === 'string'\n ) {\n return true;\n }\n return (\n scope.kind === 'skill' &&\n typeof scope.id === 'string' &&\n typeof scope.version === 'number'\n );\n}\n\nfunction isCodeApiAuthHeaders(\n value: string | t.CodeApiAuthHeaders | undefined\n): value is t.CodeApiAuthHeaders {\n return value != null && typeof value !== 'string';\n}\n\nfunction isCodeApiSessionFileWire(\n value: unknown\n): value is CodeApiSessionFileWire {\n return value != null && typeof value === 'object';\n}\n\nfunction isCodeApiSessionFileMetadata(\n value: unknown\n): value is CodeApiSessionFileMetadata {\n return value != null && typeof value === 'object';\n}\n\nfunction normalizeSessionFile(\n file: CodeApiSessionFileWire,\n sessionId: string,\n scope?: FetchSessionFilesScope\n): t.CodeEnvFile {\n const metadata = isCodeApiSessionFileMetadata(file.metadata)\n ? file.metadata\n : undefined;\n const rawName = typeof file.name === 'string' ? file.name : '';\n const nameParts = rawName.split('/');\n const fallbackId = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n const id =\n typeof file.id === 'string' && file.id !== '' ? file.id : fallbackId;\n const originalFilename = metadata?.['original-filename'];\n const name =\n typeof originalFilename === 'string' ? originalFilename : rawName;\n const storage_session_id =\n typeof file.storage_session_id === 'string'\n ? file.storage_session_id\n : sessionId;\n const resource_id =\n typeof file.resource_id === 'string' && file.resource_id !== ''\n ? file.resource_id\n : (scope?.id ?? id);\n\n if (scope?.kind === 'skill') {\n return {\n storage_session_id,\n kind: 'skill',\n id,\n resource_id,\n name,\n version: scope.version,\n };\n }\n if (scope != null) {\n return {\n storage_session_id,\n kind: scope.kind,\n id,\n resource_id,\n name,\n };\n }\n return {\n storage_session_id,\n kind: 'user',\n id,\n resource_id: id,\n name,\n };\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 sessionId - The session ID to fetch files from\n * @param scope - Resource scope used by CodeAPI to authorize the session\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 sessionId: string,\n proxy?: string,\n authHeaders?: t.CodeApiAuthHeaders\n): Promise<t.CodeEnvFile[]>;\nexport async function fetchSessionFiles(\n baseUrl: string,\n sessionId: string,\n scope: FetchSessionFilesScope,\n proxyOrAuthHeaders?: string | t.CodeApiAuthHeaders,\n authHeaders?: t.CodeApiAuthHeaders\n): Promise<t.CodeEnvFile[]>;\nexport async function fetchSessionFiles(\n baseUrl: string,\n sessionId: string,\n scopeOrProxy?: FetchSessionFilesScope | string,\n proxyOrAuthHeaders?: string | t.CodeApiAuthHeaders,\n scopedAuthHeaders?: t.CodeApiAuthHeaders\n): Promise<t.CodeEnvFile[]> {\n try {\n const scope = isFetchSessionFilesScope(scopeOrProxy)\n ? scopeOrProxy\n : undefined;\n let proxy: string | undefined;\n let authHeaders: t.CodeApiAuthHeaders | undefined;\n if (scope == null) {\n proxy = typeof scopeOrProxy === 'string' ? scopeOrProxy : undefined;\n authHeaders = isCodeApiAuthHeaders(proxyOrAuthHeaders)\n ? proxyOrAuthHeaders\n : undefined;\n } else if (typeof proxyOrAuthHeaders === 'string') {\n proxy = proxyOrAuthHeaders;\n authHeaders = scopedAuthHeaders;\n } else {\n authHeaders = proxyOrAuthHeaders ?? scopedAuthHeaders;\n }\n const query = new URLSearchParams({ detail: 'full' });\n if (scope != null) {\n query.set('kind', scope.kind);\n query.set('id', scope.id);\n if (scope.kind === 'skill') {\n query.set('version', String(scope.version));\n }\n }\n const filesEndpoint = `${baseUrl}/files/${encodeURIComponent(sessionId)}?${query.toString()}`;\n const resolvedAuthHeaders = await resolveCodeApiAuthHeaders(authHeaders);\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'LibreChat/1.0',\n ...resolvedAuthHeaders,\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(\n await buildCodeApiHttpErrorMessage('GET', filesEndpoint, response)\n );\n }\n\n const files = await response.json();\n if (!Array.isArray(files) || files.length === 0) {\n return [];\n }\n\n return files\n .filter(isCodeApiSessionFileWire)\n .map((file) => normalizeSessionFile(file, sessionId, scope));\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 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 body: Record<string, unknown>,\n proxy?: string,\n authHeaders?: t.CodeApiAuthHeaders\n): Promise<t.ProgrammaticExecutionResponse> {\n try {\n const resolvedAuthHeaders = await resolveCodeApiAuthHeaders(authHeaders);\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n ...resolvedAuthHeaders,\n },\n body: JSON.stringify(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 throw new CodeApiRequestError(\n await buildCodeApiHttpErrorMessage('POST', endpoint, response)\n );\n }\n\n return (await response.json()) as t.ProgrammaticExecutionResponse;\n } catch (error) {\n throw normalizeCodeApiRequestError(error);\n }\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\ntype ToolInputSchemaKind = {\n object: boolean;\n string: boolean;\n};\n\nfunction detectSchemaKind(schema: unknown): ToolInputSchemaKind {\n const kind: ToolInputSchemaKind = { object: false, string: false };\n\n if (!schema || typeof schema !== 'object') {\n return kind;\n }\n\n const jsonSchemaType = (schema as { type?: unknown }).type;\n if (jsonSchemaType === 'object') {\n kind.object = true;\n } else if (jsonSchemaType === 'string') {\n kind.string = true;\n } else if (Array.isArray(jsonSchemaType)) {\n kind.object = jsonSchemaType.includes('object');\n kind.string = jsonSchemaType.includes('string');\n }\n\n const zodDef = (schema as { _def?: unknown })._def;\n if (!zodDef || typeof zodDef !== 'object') {\n return kind;\n }\n\n const zodType = (zodDef as { type?: unknown; typeName?: unknown }).type;\n const zodTypeName = (zodDef as { type?: unknown; typeName?: unknown })\n .typeName;\n\n if (zodType === 'object' || zodTypeName === 'ZodObject') {\n kind.object = true;\n } else if (zodType === 'string' || zodTypeName === 'ZodString') {\n kind.string = true;\n }\n\n const innerSchema =\n (\n zodDef as {\n innerType?: unknown;\n schema?: unknown;\n type?: unknown;\n }\n ).innerType ?? (zodDef as { schema?: unknown }).schema;\n if (innerSchema) {\n const innerKind = detectSchemaKind(innerSchema);\n kind.object ||= innerKind.object;\n kind.string ||= innerKind.string;\n }\n\n const options = (zodDef as { options?: unknown }).options;\n if (Array.isArray(options)) {\n for (const option of options) {\n const optionKind = detectSchemaKind(option);\n kind.object ||= optionKind.object;\n kind.string ||= optionKind.string;\n }\n }\n\n return kind;\n}\n\nfunction getToolInputSchemaKind(tool: t.GenericTool): ToolInputSchemaKind {\n if (tool.constructor.name === 'DynamicTool') {\n return { object: false, string: true };\n }\n\n const schema = (tool as { schema?: unknown }).schema;\n return detectSchemaKind(schema);\n}\n\nfunction normalizeToolInput(\n input: t.PTCToolCall['input'],\n tool: t.GenericTool\n): t.PTCToolCall['input'] {\n const schemaKind = getToolInputSchemaKind(tool);\n\n if (typeof input !== 'string') {\n if (!schemaKind.string || schemaKind.object) {\n return input;\n }\n\n const inputValue = (input as { input?: unknown }).input;\n if (typeof inputValue === 'string') {\n return input;\n }\n\n return JSON.stringify(input);\n }\n\n if (!schemaKind.object || schemaKind.string) {\n return input;\n }\n\n const trimmed = input.trim();\n if (!trimmed.startsWith('{')) {\n return input;\n }\n\n try {\n const parsed: unknown = JSON.parse(trimmed);\n if (\n typeof parsed === 'object' &&\n parsed !== null &&\n !Array.isArray(parsed)\n ) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n return input;\n }\n\n return input;\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 programmaticToolName = Constants.PROGRAMMATIC_TOOL_CALLING\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(normalizeToolInput(call.input, tool), {\n metadata: { [programmaticToolName]: 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 *\n * Output includes stdout/stderr plus a compact session-file summary\n * when artifacts were persisted. The artifact still carries every\n * file so the host's session map stays in sync.\n *\n * @param response - The completed API response\n * @returns Tuple of [formatted string, artifact]\n */\nexport function formatCompletedResponse(\n response: t.ProgrammaticExecutionResponse,\n sourceCode = ''\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 const outputWithReminder = appendTmpScratchReminder(formatted, sourceCode);\n\n return [\n appendCodeSessionFileSummary(outputWithReminder, response.files),\n {\n session_id: response.session_id,\n files: response.files,\n ...(response.runtime_session_id != null\n ? {\n runtime_session_id: response.runtime_session_id,\n runtime_status: response.runtime_status,\n }\n : {}),\n } satisfies t.ProgrammaticExecutionArtifact,\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 (baseUrl, maxRoundTrips, proxy)\n * @returns A LangChain DynamicStructuredTool for programmatic tool calling\n *\n * @example\n * const ptcTool = createProgrammaticToolCallingTool({ maxRoundTrips: 20 });\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 {\n const baseUrl = initParams.baseUrl ?? getCodeBaseURL();\n const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;\n const maxRunTimeoutMs = resolveCodeApiRunTimeoutMs(initParams.runTimeoutMs);\n const proxy = initParams.proxy ?? process.env.PROXY;\n const debug = initParams.debug ?? process.env.PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n return tool(\n async (rawParams, config) => {\n const params = rawParams as { code: string; timeout?: number };\n const { code } = params;\n const timeout = clampCodeApiRunTimeoutMs(params.timeout, maxRunTimeoutMs);\n\n // Extra params injected by ToolNode (follows web_search pattern).\n const toolCall = (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache> & {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n _runtime_session_hint?: string;\n };\n const {\n toolMap,\n toolDefs,\n session_id,\n _injected_files,\n _runtime_session_hint,\n } = toolCall;\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error(\n 'No toolMap provided. ' +\n 'ToolNode should inject this from AgentContext when invoked through the graph.'\n );\n }\n\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided. ' +\n 'Either pass tools in the input or ensure ToolNode injects toolDefs.'\n );\n }\n\n let roundTrip = 0;\n\n try {\n // ====================================================================\n // Phase 1: Filter tools and make initial request\n // ====================================================================\n\n const effectiveTools = 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 /**\n * File injection: `_injected_files` from ToolNode session\n * context. The legacy `/files/<session_id>` HTTP fallback was\n * removed (see `CodeExecutor.ts`) — codeapi's sessionAuth now\n * requires kind/id query params unavailable at this point.\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 // eslint-disable-next-line no-console\n console.debug(\n `[ProgrammaticToolCalling] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n /* Stateful sessions: hint rides the INITIAL request only; the server\n * binds continuation round-trips to the same runtime via the\n * continuation_token. Additive — ignored by stateless servers. PTC\n * keeps its stateless prompt in v1; only the wire hint plumbs here. */\n const runtimeSessionHint =\n typeof _runtime_session_hint === 'string' &&\n _runtime_session_hint !== ''\n ? _runtime_session_hint\n : undefined;\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n {\n code,\n tools: effectiveTools,\n session_id,\n timeout,\n ...(files && files.length > 0 ? { files } : {}),\n ...(runtimeSessionHint != null\n ? { runtime_session_hint: runtimeSessionHint }\n : {}),\n },\n proxy,\n initParams.authHeaders\n );\n\n // ====================================================================\n // Phase 2: Handle response loop\n // ====================================================================\n\n while (response.status === 'tool_call_required') {\n roundTrip++;\n\n if (roundTrip > maxRoundTrips) {\n throw new Error(\n `Exceeded maximum round trips (${maxRoundTrips}). ` +\n 'This may indicate an infinite loop, excessive tool calls, ' +\n 'or a logic error in your code.'\n );\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[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 {\n continuation_token: response.continuation_token,\n tool_results: toolResults,\n },\n proxy,\n initParams.authHeaders\n );\n }\n\n // ====================================================================\n // Phase 3: Handle final state\n // ====================================================================\n\n if (response.status === 'completed') {\n return formatCompletedResponse(response, code);\n }\n\n if (response.status === 'error') {\n throw new Error(buildCodeApiExecutionErrorMessage(response));\n }\n\n throw new CodeApiRequestError();\n } catch (error) {\n const messageWithReminder = appendFailedExecutionFileReminder(\n (error as Error).message,\n code\n );\n throw new Error(\n `Programmatic execution failed: ${messageWithReminder}`\n );\n }\n },\n {\n name: Constants.PROGRAMMATIC_TOOL_CALLING,\n description: ProgrammaticToolCallingDescription,\n schema: createProgrammaticToolCallingSchema(maxRunTimeoutMs),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"mappings":";;;;;;;;;;;;mBA4BO;;AAGP,MAAM,0BAA0B;AAEhC,MAAM,yBAAyBA,mBAAAA,2BAA2B;AAM1D,MAAM,oBAAoB;;;;AAK1B,MAAM,aAAa;;;;;;;IAOfC,qBAAAA,4BAA4B;;AAGhC,MAAM,mBACJ;AAEF,MAAM,WAAW;;;;;;;;;;;;;AAkBjB,MAA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BACpC;EACF;CACF,GACA;EACE,MAAA;EACA,aAAa;EACb,QAAQ,oCAAoC,eAAe;EAC3D,gBAAA;CACF,CACF;AACF"}
@@ -15,9 +15,12 @@ const require_resolveLocalExecutionTools = require("./local/resolveLocalExecutio
15
15
  require("./local/index.cjs");
16
16
  let _langchain_core_messages = require("@langchain/core/messages");
17
17
  let _langchain_langgraph = require("@langchain/langgraph");
18
+ let nanoid = require("nanoid");
18
19
  let _langchain_core_singletons = require("@langchain/core/singletons");
19
20
  //#region src/tools/ToolNode.ts
20
21
  const TOOL_NODE_RUN_NAME = "tool_batch";
22
+ const NANOID_URL_ALPHABET = "_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
23
+ const RUNTIME_HANDOFF_GROUP_OFFSET = 2 ** 48;
21
24
  /**
22
25
  * Helper to check if a value is a Send object
23
26
  */
@@ -28,6 +31,28 @@ function isHandoffToolName(name) {
28
31
  return name.startsWith("lc_transfer_to_");
29
32
  }
30
33
  /**
34
+ * Encodes 48 random bits from the persisted batch key into a safe integer.
35
+ * The high offset keeps runtime groups disjoint from low, structural group IDs.
36
+ */
37
+ function getRuntimeHandoffGroupId(batch) {
38
+ let value = 0;
39
+ for (const char of batch.slice(0, 8)) {
40
+ const digit = NANOID_URL_ALPHABET.indexOf(char);
41
+ value = value * 64 + Math.max(digit, 0);
42
+ }
43
+ return RUNTIME_HANDOFF_GROUP_OFFSET + value;
44
+ }
45
+ function findHandoffMessage(messages, destination) {
46
+ for (let i = messages.length - 1; i >= 0; i--) {
47
+ const message = messages[i];
48
+ if (message.getType() !== "tool") continue;
49
+ const toolMessage = message;
50
+ const isStandardHandoff = toolMessage.name === `lc_transfer_to_${destination}`;
51
+ const isConditionalHandoff = toolMessage.name === "conditional_transfer" && toolMessage.additional_kwargs.handoff_destination === destination;
52
+ if (isStandardHandoff || isConditionalHandoff) return toolMessage;
53
+ }
54
+ }
55
+ /**
31
56
  * Format a fail-closed diagnostic for malformed approval-decision
32
57
  * fields. Hosts deserialize resume payloads from untyped JSON, so
33
58
  * `responseText` and `updatedInput` can land here as anything; the
@@ -2334,14 +2359,18 @@ var ToolNode = class extends require_run.RunnableCallable {
2334
2359
  const goto = cmd.goto;
2335
2360
  return typeof goto === "string" ? goto : goto[0];
2336
2361
  });
2362
+ const parallelBatch = (0, nanoid.nanoid)();
2363
+ const parallelGroupId = getRuntimeHandoffGroupId(parallelBatch);
2337
2364
  const sends = handoffCommands.map((cmd, idx) => {
2338
2365
  const destination = allDestinations[idx];
2339
2366
  /** Get siblings (other destinations, not this one) */
2340
2367
  const siblings = allDestinations.filter((d) => d !== destination);
2341
- /** Add siblings to ToolMessage additional_kwargs */
2342
2368
  const update = cmd.update;
2343
- if (update && update.messages) {
2344
- for (const msg of update.messages) if (msg.getType() === "tool") msg.additional_kwargs.handoff_parallel_siblings = siblings;
2369
+ const handoffMessage = update?.messages ? findHandoffMessage(update.messages, destination) : void 0;
2370
+ if (handoffMessage) {
2371
+ handoffMessage.additional_kwargs.handoff_parallel_siblings = siblings;
2372
+ handoffMessage.additional_kwargs["__handoff_parallel_batch"] = parallelBatch;
2373
+ handoffMessage.additional_kwargs["__handoff_group_id"] = parallelGroupId;
2345
2374
  }
2346
2375
  return new _langchain_langgraph.Send(destination, cmd.update);
2347
2376
  });