@librechat/agents 3.2.58 → 3.2.60

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 (67) hide show
  1. package/dist/cjs/graphs/Graph.cjs +31 -7
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/main.cjs +7 -0
  4. package/dist/cjs/run.cjs +4 -0
  5. package/dist/cjs/run.cjs.map +1 -1
  6. package/dist/cjs/stream.cjs +2 -1
  7. package/dist/cjs/stream.cjs.map +1 -1
  8. package/dist/cjs/tools/BashExecutor.cjs +58 -9
  9. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  10. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +4 -2
  11. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  12. package/dist/cjs/tools/CodeExecutor.cjs +57 -7
  13. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  14. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +9 -3
  15. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  16. package/dist/cjs/tools/ToolNode.cjs +114 -11
  17. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  18. package/dist/cjs/tools/eagerEventExecution.cjs +18 -1
  19. package/dist/cjs/tools/eagerEventExecution.cjs.map +1 -1
  20. package/dist/esm/graphs/Graph.mjs +31 -7
  21. package/dist/esm/graphs/Graph.mjs.map +1 -1
  22. package/dist/esm/main.mjs +3 -3
  23. package/dist/esm/run.mjs +4 -0
  24. package/dist/esm/run.mjs.map +1 -1
  25. package/dist/esm/stream.mjs +2 -1
  26. package/dist/esm/stream.mjs.map +1 -1
  27. package/dist/esm/tools/BashExecutor.mjs +56 -10
  28. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  29. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +4 -2
  30. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  31. package/dist/esm/tools/CodeExecutor.mjs +54 -8
  32. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  33. package/dist/esm/tools/ProgrammaticToolCalling.mjs +9 -3
  34. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  35. package/dist/esm/tools/ToolNode.mjs +115 -12
  36. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  37. package/dist/esm/tools/eagerEventExecution.mjs +18 -2
  38. package/dist/esm/tools/eagerEventExecution.mjs.map +1 -1
  39. package/dist/types/graphs/Graph.d.ts +21 -3
  40. package/dist/types/run.d.ts +1 -0
  41. package/dist/types/tools/BashExecutor.d.ts +13 -0
  42. package/dist/types/tools/CodeExecutor.d.ts +14 -0
  43. package/dist/types/tools/ToolNode.d.ts +60 -1
  44. package/dist/types/tools/eagerEventExecution.d.ts +8 -0
  45. package/dist/types/types/hitl.d.ts +49 -3
  46. package/dist/types/types/run.d.ts +21 -0
  47. package/dist/types/types/tools.d.ts +95 -1
  48. package/package.json +1 -1
  49. package/src/graphs/Graph.ts +74 -28
  50. package/src/run.ts +4 -0
  51. package/src/specs/ask-user-question-batch.test.ts +289 -0
  52. package/src/specs/tool-error-resume.test.ts +194 -0
  53. package/src/stream.ts +17 -1
  54. package/src/tools/BashExecutor.ts +107 -14
  55. package/src/tools/BashProgrammaticToolCalling.ts +20 -1
  56. package/src/tools/CodeExecutor.ts +113 -9
  57. package/src/tools/ProgrammaticToolCalling.ts +27 -1
  58. package/src/tools/ToolNode.ts +208 -31
  59. package/src/tools/__tests__/BashExecutor.test.ts +39 -0
  60. package/src/tools/__tests__/CodeExecutor.stateful.test.ts +113 -0
  61. package/src/tools/__tests__/ToolNode.session.test.ts +86 -0
  62. package/src/tools/__tests__/eagerEventExecution.session.test.ts +92 -0
  63. package/src/tools/__tests__/hitl.test.ts +48 -0
  64. package/src/tools/eagerEventExecution.ts +32 -5
  65. package/src/types/hitl.ts +49 -3
  66. package/src/types/run.ts +21 -0
  67. package/src/types/tools.ts +102 -1
@@ -1 +1 @@
1
- {"version":3,"file":"BashExecutor.cjs","names":["getCodeBaseURL","CODE_ARTIFACT_PATH_GUIDANCE","BASH_SHELL_GUIDANCE","resolveCodeApiAuthHeaders","HttpsProxyAgent","buildCodeApiHttpErrorMessage","emptyOutputMessage","appendTmpScratchReminder","appendCodeSessionFileSummary","appendFailedExecutionFileReminder"],"sources":["../../../src/tools/BashExecutor.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport {\n BASH_SHELL_GUIDANCE,\n CODE_ARTIFACT_PATH_GUIDANCE,\n appendFailedExecutionFileReminder,\n appendTmpScratchReminder,\n appendCodeSessionFileSummary,\n emptyOutputMessage,\n buildCodeApiHttpErrorMessage,\n getCodeBaseURL,\n resolveCodeApiAuthHeaders,\n} from './CodeExecutor';\nimport { Constants } from '@/common';\n\nconfig();\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\nexport const BashExecutionToolSchema = {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: `The bash command or script to execute.\n- The environment is stateless; variables and state don't persist between executions.\n- Prior /mnt/data files are available and can be modified in place.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_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- Use \\`echo\\`, \\`printf\\`, or \\`cat\\` for all outputs.`,\n },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Additional arguments to execute the command with. This should only be used if the input command requires additional arguments to run.',\n },\n },\n required: ['command'],\n} as const;\n\nexport const BashExecutionToolDescription = `\nRuns bash commands 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- ${BASH_SHELL_GUIDANCE}\n- NEVER use this tool to execute malicious commands.\n`.trim();\n\n/**\n * Supplemental prompt documenting the tool-output reference feature.\n *\n * Hosts should append this (separated by a blank line) to the base\n * {@link BashExecutionToolDescription} only when\n * `RunConfig.toolOutputReferences.enabled` is `true`. When the feature\n * is disabled, including this text would tell the LLM to emit\n * `{{tool0turn0}}` placeholders that pass through unsubstituted and\n * leak into the shell.\n */\nexport const BashToolOutputReferencesGuide = `\nReferencing previous tool outputs:\n- Every successful tool result is tagged with a reference key of the form \\`tool<idx>turn<turn>\\` (e.g., \\`tool0turn0\\`). The key appears either as a \\`[ref: tool0turn0]\\` prefix line or, when the output is a JSON object, as a \\`_ref\\` field on the object.\n- To pipe a previous tool output into this tool, embed the placeholder \\`{{tool<idx>turn<turn>}}\\` literally anywhere in the \\`command\\` string (or any string arg). It will be substituted with the stored output verbatim before the command runs.\n- The substituted value is the original output string (no \\`[ref: …]\\` prefix, no \\`_ref\\` key), so it is safe to pipe directly into \\`jq\\`, \\`grep\\`, \\`awk\\`, etc.\n- Example (simple ASCII output): \\`echo '{{tool0turn0}}' | jq '.foo'\\` takes the full output of the first tool from the first turn and pipes it into jq.\n- For payloads that may contain quotes, parentheses, backticks, or arbitrary bytes (random/binary data, JSON with embedded quotes, multi-line strings), prefer a quoted-delimiter heredoc over \\`echo '…'\\`. The heredoc body is not interpreted by the shell, so substituted payloads pass through unchanged.\n- Heredoc example: \\`wc -c << 'EOF'\\\\n{{tool0turn0}}\\\\nEOF\\` (the quotes around \\`'EOF'\\` disable interpolation inside the body).\n- Unknown reference keys are left in place and surfaced as \\`[unresolved refs: …]\\` after the output.\n`.trim();\n\n/**\n * Composes the bash tool description, optionally appending the\n * tool-output references guide. Hosts that enable\n * `RunConfig.toolOutputReferences` should pass `enableToolOutputReferences: true`\n * when registering the tool so the LLM learns the `{{…}}` syntax it\n * will actually be able to use.\n */\nexport function buildBashExecutionToolDescription(options?: {\n enableToolOutputReferences?: boolean;\n}): string {\n if (options?.enableToolOutputReferences === true) {\n return `${BashExecutionToolDescription}\\n\\n${BashToolOutputReferencesGuide}`;\n }\n return BashExecutionToolDescription;\n}\n\nexport const BashExecutionToolName = Constants.BASH_TOOL;\n\n/**\n * Default bash tool definition using the base description.\n *\n * When `RunConfig.toolOutputReferences.enabled` is `true`, build a\n * reference-aware description with\n * {@link buildBashExecutionToolDescription}\n * (`{ enableToolOutputReferences: true }`) and construct a custom\n * definition using it — using this constant as-is leaves the LLM\n * unaware of the `{{tool<i>turn<n>}}` syntax.\n */\nexport const BashExecutionToolDefinition = {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n} as const;\n\nfunction createBashExecutionTool(\n params: t.BashExecutionToolParams | null = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput, config) => {\n const { authHeaders, ...executionParams } = params ?? {};\n const { command, ...rest } = rawInput as {\n command: string;\n args?: string[];\n };\n const { session_id, _injected_files } = (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n const postData: Record<string, unknown> = {\n lang: 'bash',\n code: command,\n ...rest,\n ...executionParams,\n };\n\n /* See `CodeExecutor.ts` for the rationale — `/files/<session_id>`\n * HTTP fallback was removed because codeapi's sessionAuth requires\n * kind/id query params unavailable at this point. */\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 `[BashExecutor] 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 command\n );\n const hasFiles = result.files != null && result.files.length > 0;\n return [\n appendCodeSessionFileSummary(outputWithReminder, result.files),\n (hasFiles\n ? { session_id: result.session_id, files: result.files }\n : {\n session_id: result.session_id,\n }) satisfies t.CodeExecutionArtifact,\n ];\n } catch (error) {\n const messageWithReminder = appendFailedExecutionFileReminder(\n (error as Error | undefined)?.message ?? '',\n command\n );\n throw new Error(\n `Execution error:\\n\\n${messageWithReminder}`\n );\n }\n },\n {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createBashExecutionTool };\n"],"mappings":";;;;;;;;;;;mBAkBO;AAGP,MAAM,gBAAgB,GADDA,qBAAAA,eACe,EAAE;AAEtC,MAAa,0BAA0B;CACrC,MAAM;CACN,YAAY;EACV,SAAS;GACP,MAAM;GACN,aAAa;;;IAGfC,qBAAAA,4BAA4B;IAC5BC,qBAAAA,oBAAoB;;;;;EAKpB;EACA,MAAM;GACJ,MAAM;GACN,OAAO,EAAE,MAAM,SAAS;GACxB,aACE;EACJ;CACF;CACA,UAAU,CAAC,SAAS;AACtB;AAEA,MAAa,+BAA+B;;;;;;IAMxCD,qBAAAA,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SAA0B,MAAM,SAAS,KAAK;GACpD,IAAI,kBAAkB;GACtB,IAAI,OAAO,QACT,mBAAmB,YAAY,OAAO,OAAO;QAE7C,mBAAmBC,qBAAAA;GAErB,IAAI,OAAO,QAAQ,mBAAmB,YAAY,OAAO,OAAO;GAEhE,MAAM,qBAAqBC,qBAAAA,yBACzB,iBACA,OACF;GACA,MAAM,WAAW,OAAO,SAAS,QAAQ,OAAO,MAAM,SAAS;GAC/D,OAAO,CACLC,+BAAAA,6BAA6B,oBAAoB,OAAO,KAAK,GAC5D,WACG;IAAE,YAAY,OAAO;IAAY,OAAO,OAAO;GAAM,IACrD,EACA,YAAY,OAAO,WACrB,CACJ;EACF,SAAS,OAAO;GACd,MAAM,sBAAsBC,qBAAAA,kCACzB,OAA6B,WAAW,IACzC,OACF;GACA,MAAM,IAAI,MACR,uBAAuB,qBACzB;EACF;CACF,GACA;EACE,MAAM;EACN,aAAa;EACb,QAAQ;EACR,gBAAA;CACF,CACF;AACF"}
1
+ {"version":3,"file":"BashExecutor.cjs","names":["getCodeBaseURL","CODE_ARTIFACT_PATH_GUIDANCE","BASH_SHELL_GUIDANCE","resolveCodeApiAuthHeaders","HttpsProxyAgent","buildCodeApiHttpErrorMessage","emptyOutputMessage","appendTmpScratchReminder","appendCodeSessionFileSummary","appendFailedExecutionFileReminder"],"sources":["../../../src/tools/BashExecutor.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport {\n BASH_SHELL_GUIDANCE,\n CODE_ARTIFACT_PATH_GUIDANCE,\n appendFailedExecutionFileReminder,\n appendTmpScratchReminder,\n appendCodeSessionFileSummary,\n emptyOutputMessage,\n buildCodeApiHttpErrorMessage,\n getCodeBaseURL,\n resolveCodeApiAuthHeaders,\n} from './CodeExecutor';\nimport { Constants } from '@/common';\n\nconfig();\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\nexport const BashExecutionToolSchema = {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: `The bash command or script to execute.\n- The environment is stateless; variables and state don't persist between executions.\n- Prior /mnt/data files are available and can be modified in place.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_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- Use \\`echo\\`, \\`printf\\`, or \\`cat\\` for all outputs.`,\n },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Additional arguments to execute the command with. This should only be used if the input command requires additional arguments to run.',\n },\n },\n required: ['command'],\n} as const;\n\nexport const BashExecutionToolDescription = `\nRuns bash commands 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- ${BASH_SHELL_GUIDANCE}\n- NEVER use this tool to execute malicious commands.\n`.trim();\n\n/**\n * Bash statefulness is filesystem-tier: on a warm session the machine (files\n * including /tmp, installed packages, background processes) persists between\n * calls, but each call may start a fresh shell — so shell variables and cwd\n * are NOT reliable, and the machine can be reset at any time. Only /mnt/data\n * is durable.\n */\nexport const STATEFUL_BASH_NOTE =\n 'Session state (best-effort): commands in this conversation usually run on the same machine, so files (including /tmp), installed packages, and running background processes from earlier calls typically persist. Each call may still start a fresh shell — do not rely on shell variables or the working directory carrying over — and the machine may be reset at any time. Only /mnt/data is durable.';\n\nexport const StatefulBashExecutionToolDescription = `\nRuns bash commands and returns stdout/stderr output from a session-based execution environment, similar to a long-running machine.\n\n${STATEFUL_BASH_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- ${BASH_SHELL_GUIDANCE}\n- NEVER use this tool to execute malicious commands.\n`.trim();\n\n/**\n * Supplemental prompt documenting the tool-output reference feature.\n *\n * Hosts should append this (separated by a blank line) to the base\n * {@link BashExecutionToolDescription} only when\n * `RunConfig.toolOutputReferences.enabled` is `true`. When the feature\n * is disabled, including this text would tell the LLM to emit\n * `{{tool0turn0}}` placeholders that pass through unsubstituted and\n * leak into the shell.\n */\nexport const BashToolOutputReferencesGuide = `\nReferencing previous tool outputs:\n- Every successful tool result is tagged with a reference key of the form \\`tool<idx>turn<turn>\\` (e.g., \\`tool0turn0\\`). The key appears either as a \\`[ref: tool0turn0]\\` prefix line or, when the output is a JSON object, as a \\`_ref\\` field on the object.\n- To pipe a previous tool output into this tool, embed the placeholder \\`{{tool<idx>turn<turn>}}\\` literally anywhere in the \\`command\\` string (or any string arg). It will be substituted with the stored output verbatim before the command runs.\n- The substituted value is the original output string (no \\`[ref: …]\\` prefix, no \\`_ref\\` key), so it is safe to pipe directly into \\`jq\\`, \\`grep\\`, \\`awk\\`, etc.\n- Example (simple ASCII output): \\`echo '{{tool0turn0}}' | jq '.foo'\\` takes the full output of the first tool from the first turn and pipes it into jq.\n- For payloads that may contain quotes, parentheses, backticks, or arbitrary bytes (random/binary data, JSON with embedded quotes, multi-line strings), prefer a quoted-delimiter heredoc over \\`echo '…'\\`. The heredoc body is not interpreted by the shell, so substituted payloads pass through unchanged.\n- Heredoc example: \\`wc -c << 'EOF'\\\\n{{tool0turn0}}\\\\nEOF\\` (the quotes around \\`'EOF'\\` disable interpolation inside the body).\n- Unknown reference keys are left in place and surfaced as \\`[unresolved refs: …]\\` after the output.\n`.trim();\n\n/**\n * Composes the bash tool description, optionally appending the\n * tool-output references guide. Hosts that enable\n * `RunConfig.toolOutputReferences` should pass `enableToolOutputReferences: true`\n * when registering the tool so the LLM learns the `{{…}}` syntax it\n * will actually be able to use.\n */\nexport function buildBashExecutionToolDescription(options?: {\n enableToolOutputReferences?: boolean;\n statefulSessions?: boolean;\n}): string {\n const base =\n options?.statefulSessions === true\n ? StatefulBashExecutionToolDescription\n : BashExecutionToolDescription;\n if (options?.enableToolOutputReferences === true) {\n return `${base}\\n\\n${BashToolOutputReferencesGuide}`;\n }\n return base;\n}\n\nconst STATELESS_BASH_PARAM_NOTE =\n 'The environment is stateless; variables and state don\\'t persist between executions.';\nconst STATEFUL_BASH_PARAM_NOTE =\n 'Files, installed packages, and background processes usually persist between calls, but each call may start a fresh shell (do not rely on shell variables or cwd) and the machine may reset. Only /mnt/data is durable.';\n\nexport function buildBashExecutionToolSchema(opts?: {\n statefulSessions?: boolean;\n}): typeof BashExecutionToolSchema {\n const note =\n opts?.statefulSessions === true\n ? STATEFUL_BASH_PARAM_NOTE\n : STATELESS_BASH_PARAM_NOTE;\n const commandDescription =\n BashExecutionToolSchema.properties.command.description.replace(\n STATELESS_BASH_PARAM_NOTE,\n note\n );\n return {\n ...BashExecutionToolSchema,\n properties: {\n ...BashExecutionToolSchema.properties,\n command: {\n ...BashExecutionToolSchema.properties.command,\n description: commandDescription,\n },\n },\n } as typeof BashExecutionToolSchema;\n}\n\nexport const BashExecutionToolName = Constants.BASH_TOOL;\n\n/**\n * Default bash tool definition using the base description.\n *\n * When `RunConfig.toolOutputReferences.enabled` is `true`, build a\n * reference-aware description with\n * {@link buildBashExecutionToolDescription}\n * (`{ enableToolOutputReferences: true }`) and construct a custom\n * definition using it — using this constant as-is leaves the LLM\n * unaware of the `{{tool<i>turn<n>}}` syntax.\n */\nexport const BashExecutionToolDefinition = {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n} as const;\n\nfunction createBashExecutionTool(\n params: t.BashExecutionToolParams | null = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput, config) => {\n /* `statefulSessions` is prompt-only — 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 must only come from ToolNode's injected `_runtime_session_hint`\n * (below), never from the tool call itself. */\n const {\n command,\n runtime_session_hint: _ignoredModelHint,\n ...rest\n } = rawInput as {\n command: string;\n runtime_session_hint?: unknown;\n args?: string[];\n };\n void _ignoredModelHint;\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: 'bash',\n code: command,\n ...rest,\n ...executionParams,\n };\n\n if (\n typeof _runtime_session_hint === 'string' &&\n _runtime_session_hint !== ''\n ) {\n postData.runtime_session_hint = _runtime_session_hint;\n }\n\n /* See `CodeExecutor.ts` for the rationale — `/files/<session_id>`\n * HTTP fallback was removed because codeapi's sessionAuth requires\n * kind/id query params unavailable at this point. */\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 `[BashExecutor] 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 command\n );\n const hasFiles = result.files != null && result.files.length > 0;\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 command\n );\n throw new Error(`Execution error:\\n\\n${messageWithReminder}`);\n }\n },\n {\n name: BashExecutionToolName,\n description: buildBashExecutionToolDescription({\n statefulSessions: params?.statefulSessions,\n }),\n schema: buildBashExecutionToolSchema(params ?? undefined),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createBashExecutionTool };\n"],"mappings":";;;;;;;;;;;mBAkBO;AAGP,MAAM,gBAAgB,GADDA,qBAAAA,eACe,EAAE;AAEtC,MAAa,0BAA0B;CACrC,MAAM;CACN,YAAY;EACV,SAAS;GACP,MAAM;GACN,aAAa;;;IAGfC,qBAAAA,4BAA4B;IAC5BC,qBAAAA,oBAAoB;;;;;EAKpB;EACA,MAAM;GACJ,MAAM;GACN,OAAO,EAAE,MAAM,SAAS;GACxB,aACE;EACJ;CACF;CACA,UAAU,CAAC,SAAS;AACtB;AAEA,MAAa,+BAA+B;;;;;;IAMxCD,qBAAAA,4BAA4B;IAC5BC,qBAAAA,oBAAoB;;EAEtB,KAAK;;;;;;;;AASP,MAAa,qBACX;AAEF,MAAa,uCAAuC;;;EAGlD,mBAAmB;;;;;IAKjBD,qBAAAA,4BAA4B;IAC5BC,qBAAAA,oBAAoB;;EAEtB,KAAK;;;;;;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188
188
  const params = rawParams;
189
189
  const { code } = params;
190
190
  const timeout = require_ptcTimeout.clampCodeApiRunTimeoutMs(params.timeout, maxRunTimeoutMs);
191
- const { toolMap, toolDefs, session_id, _injected_files } = config.toolCall ?? {};
191
+ const { toolMap, toolDefs, session_id, _injected_files, _runtime_session_hint } = config.toolCall ?? {};
192
192
  if (toolMap == null || toolMap.size === 0) throw new Error("No toolMap provided. ToolNode should inject this from AgentContext when invoked through the graph.");
193
193
  if (toolDefs == null || toolDefs.length === 0) throw new Error("No tool definitions provided. Either pass tools in the input or ensure ToolNode injects toolDefs.");
194
194
  let roundTrip = 0;
@@ -198,13 +198,15 @@ function createBashProgrammaticToolCallingTool(initParams = {}) {
198
198
  let files;
199
199
  if (_injected_files && _injected_files.length > 0) files = _injected_files;
200
200
  else if (session_id != null && session_id.length > 0) console.debug(`[BashProgrammaticToolCalling] No injected files for session_id=${session_id} — exec will run without input files`);
201
+ const runtimeSessionHint = typeof _runtime_session_hint === "string" && _runtime_session_hint !== "" ? _runtime_session_hint : void 0;
201
202
  let response = await require_ProgrammaticToolCalling.makeRequest(EXEC_ENDPOINT, {
202
203
  lang: "bash",
203
204
  code,
204
205
  tools: effectiveTools,
205
206
  session_id,
206
207
  timeout,
207
- ...files && files.length > 0 ? { files } : {}
208
+ ...files && files.length > 0 ? { files } : {},
209
+ ...runtimeSessionHint != null ? { runtime_session_hint: runtimeSessionHint } : {}
208
210
  }, proxy, initParams.authHeaders);
209
211
  while (response.status === "tool_call_required") {
210
212
  roundTrip++;
@@ -1 +1 @@
1
- {"version":3,"file":"BashProgrammaticToolCalling.cjs","names":["resolveCodeApiRunTimeoutMs","CODE_ARTIFACT_PATH_GUIDANCE","BASH_SHELL_GUIDANCE","createCodeApiRunTimeoutSchema","getCodeBaseURL","clampCodeApiRunTimeoutMs","makeRequest","executeTools","formatCompletedResponse","appendFailedExecutionFileReminder"],"sources":["../../../src/tools/BashProgrammaticToolCalling.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { ProgrammaticToolCallingJsonSchema } from './ptcTimeout';\nimport type * as t from '@/types';\nimport {\n BASH_SHELL_GUIDANCE,\n CODE_ARTIFACT_PATH_GUIDANCE,\n appendFailedExecutionFileReminder,\n getCodeBaseURL,\n} from './CodeExecutor';\nimport {\n clampCodeApiRunTimeoutMs,\n createCodeApiRunTimeoutSchema,\n resolveCodeApiRunTimeoutMs,\n} from './ptcTimeout';\nimport {\n makeRequest,\n executeTools,\n formatCompletedResponse,\n} from './ProgrammaticToolCalling';\nimport { Constants } from '@/common';\n\nconfig();\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\nconst DEFAULT_RUN_TIMEOUT_MS = resolveCodeApiRunTimeoutMs();\n\n/** Bash reserved words that get `_tool` suffix when used as function names */\nconst BASH_RESERVED = new Set([\n 'if',\n 'then',\n 'else',\n 'elif',\n 'fi',\n 'case',\n 'esac',\n 'for',\n 'while',\n 'until',\n 'do',\n 'done',\n 'in',\n 'function',\n 'select',\n 'time',\n 'coproc',\n 'declare',\n 'typeset',\n 'local',\n 'readonly',\n 'export',\n 'unset',\n]);\n\n// ============================================================================\n// Description Components\n// ============================================================================\n\nconst STATELESS_WARNING = `CRITICAL - STATELESS EXECUTION:\nEach call is a fresh bash shell. Variables and state do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block.\nDO NOT split work across multiple calls expecting to reuse variables.`;\n\nconst CORE_RULES = `Rules:\n- One call: state does not persist\n- Tools are pre-defined as bash functions—DO NOT redefine them\n- Each tool function accepts a JSON string argument\n- Save tool output with raw=$(tool '{}'); printf '%s\\n' \"$raw\" > /mnt/data/file.json; direct tool > file may be empty\n- Tool stdout is normalized to one compact JSON value when possible; parse saved stdout once, then use fromjson? // . only for JSON-string fields\n- Only echo/printf output returns to the model\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_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, reserved words get `_tool` suffix';\n\nconst EXAMPLES = `Example (Complete workflow in one call):\n # Query data and process\n data=$(query_database '{\"sql\": \"SELECT * FROM users\"}')\n echo \"$data\" | jq '.[] | .name'\n\nExample (Parallel calls):\n { sf=$(web_search '{\"query\": \"SF weather\"}'); printf '%s\\n' \"$sf\" > /mnt/data/sf.json; } &\n { ny=$(web_search '{\"query\": \"NY weather\"}'); printf '%s\\n' \"$ny\" > /mnt/data/ny.json; } &\n wait\n echo \"SF: $(jq -r . /mnt/data/sf.json)\"\n echo \"NY: $(jq -r . /mnt/data/ny.json)\"`;\n\nconst CODE_PARAM_DESCRIPTION = `Bash code that calls tools programmatically. Tools are available as bash functions.\n\n${STATELESS_WARNING}\n\nEach tool function accepts a JSON string as its argument.\nExample: tool_name '{\"key\": \"value\"}'\n\n${EXAMPLES}\n\n${CORE_RULES}`;\n\n// ============================================================================\n// Schema\n// ============================================================================\n\nexport function createBashProgrammaticToolCallingSchema(\n maxRunTimeoutMs = DEFAULT_RUN_TIMEOUT_MS\n): ProgrammaticToolCallingJsonSchema {\n return {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n minLength: 1,\n description: CODE_PARAM_DESCRIPTION,\n },\n timeout: createCodeApiRunTimeoutSchema(maxRunTimeoutMs),\n },\n required: ['code'],\n } as const;\n}\n\nexport const BashProgrammaticToolCallingSchema =\n createBashProgrammaticToolCallingSchema();\n\nexport const BashProgrammaticToolCallingName =\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING;\n\nexport const BashProgrammaticToolCallingDescription = `\nRun tools via bash code. Tools are available as bash functions that accept JSON string arguments.\n\n${STATELESS_WARNING}\n\n${CORE_RULES}\n${ADDITIONAL_RULES}\n\nWhen to use: shell pipelines, parallel execution (& and wait), file processing, text manipulation.\n\n${EXAMPLES}\n`.trim();\n\nexport const BashProgrammaticToolCallingDefinition = {\n name: BashProgrammaticToolCallingName,\n description: BashProgrammaticToolCallingDescription,\n schema: BashProgrammaticToolCallingSchema,\n} as const;\n\nfunction maybeParseJsonResultString(result: unknown): unknown {\n if (typeof result !== 'string') {\n return result;\n }\n\n const trimmed = result.trim();\n if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {\n return result;\n }\n\n try {\n return JSON.parse(trimmed) as unknown;\n } catch {\n return result;\n }\n}\n\nexport function normalizeBashToolResultsForReplay(\n toolResults: t.PTCToolResult[]\n): t.PTCToolResult[] {\n return toolResults.map((toolResult) => {\n if (toolResult.is_error) {\n return toolResult;\n }\n\n return {\n ...toolResult,\n result: maybeParseJsonResultString(toolResult.result),\n };\n });\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Normalizes a tool name to a valid bash function identifier.\n * 1. Replace hyphens, spaces, dots with underscores\n * 2. Remove any other invalid characters\n * 3. Prefix with underscore if starts with number\n * 4. Append `_tool` if it's a bash reserved word\n */\nexport function normalizeToBashIdentifier(name: string): string {\n let normalized = name.replace(/[-\\s.]/g, '_');\n normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');\n\n if (/^[0-9]/.test(normalized)) {\n normalized = '_' + normalized;\n }\n\n if (BASH_RESERVED.has(normalized)) {\n normalized = normalized + '_tool';\n }\n\n return normalized;\n}\n\n/**\n * Extracts tool names that are actually called in the bash code.\n * Bash functions are invoked as commands (no parentheses), so we match\n * the normalized name as a word boundary.\n */\nexport function extractUsedBashToolNames(\n code: string,\n toolNameMap: Map<string, string>\n): Set<string> {\n const usedTools = new Set<string>();\n\n for (const [bashName, originalName] of toolNameMap) {\n const escapedName = bashName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const pattern = new RegExp(`\\\\b${escapedName}\\\\b`, 'g');\n\n if (pattern.test(code)) {\n usedTools.add(originalName);\n }\n }\n\n return usedTools;\n}\n\n/**\n * Filters tool definitions to only include tools actually used in the bash code.\n */\nexport function filterBashToolsByUsage(\n toolDefs: t.LCTool[],\n code: string,\n debug = false\n): t.LCTool[] {\n const toolNameMap = new Map<string, string>();\n for (const def of toolDefs) {\n const bashName = normalizeToBashIdentifier(def.name);\n toolNameMap.set(bashName, def.name);\n }\n\n const usedToolNames = extractUsedBashToolNames(code, toolNameMap);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`\n );\n if (usedToolNames.size > 0) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`\n );\n }\n }\n\n if (usedToolNames.size === 0) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[BashPTC Debug] No tools detected in code - sending all tools as fallback'\n );\n }\n return toolDefs;\n }\n\n return toolDefs.filter((def) => usedToolNames.has(def.name));\n}\n\n// ============================================================================\n// Tool Factory\n// ============================================================================\n\n/**\n * Creates a Bash Programmatic Tool Calling tool for multi-tool orchestration.\n *\n * This tool enables AI agents to write bash scripts that orchestrate multiple\n * tool calls programmatically via the remote Code API, reducing LLM round-trips.\n *\n * The tool map must be provided at runtime via config.toolCall (injected by ToolNode).\n */\nexport function createBashProgrammaticToolCallingTool(\n initParams: t.BashProgrammaticToolCallingParams = {}\n): DynamicStructuredTool {\n const baseUrl = initParams.baseUrl ?? getCodeBaseURL();\n const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;\n const maxRunTimeoutMs = resolveCodeApiRunTimeoutMs(initParams.runTimeoutMs);\n const proxy = initParams.proxy ?? process.env.PROXY;\n const debug = initParams.debug ?? process.env.BASH_PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n return tool(\n async (rawParams, config) => {\n const params = rawParams as { code: string; timeout?: number };\n const { code } = params;\n const timeout = clampCodeApiRunTimeoutMs(params.timeout, maxRunTimeoutMs);\n\n const toolCall = (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache> & {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n const { toolMap, toolDefs, session_id, _injected_files } = toolCall;\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error(\n 'No toolMap provided. ' +\n 'ToolNode should inject this from AgentContext when invoked through the graph.'\n );\n }\n\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided. ' +\n 'Either pass tools in the input or ensure ToolNode injects toolDefs.'\n );\n }\n\n let roundTrip = 0;\n\n try {\n // ====================================================================\n // Phase 1: Filter tools and make initial request\n // ====================================================================\n\n const effectiveTools = filterBashToolsByUsage(toolDefs, code, debug);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Sending ${effectiveTools.length} tools to API ` +\n `(filtered from ${toolDefs.length})`\n );\n }\n\n /* `/files/<session_id>` HTTP fallback removed — codeapi's\n * sessionAuth requires kind/id query params unavailable at\n * this point. See `CodeExecutor.ts` for full rationale. */\n let files: t.CodeEnvFile[] | undefined;\n if (_injected_files && _injected_files.length > 0) {\n files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n // eslint-disable-next-line no-console\n console.debug(\n `[BashProgrammaticToolCalling] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n {\n lang: 'bash',\n code,\n tools: effectiveTools,\n session_id,\n timeout,\n ...(files && files.length > 0 ? { files } : {}),\n },\n proxy,\n initParams.authHeaders\n );\n\n // ====================================================================\n // Phase 2: Handle response loop\n // ====================================================================\n\n while (response.status === 'tool_call_required') {\n roundTrip++;\n\n if (roundTrip > maxRoundTrips) {\n throw new Error(\n `Exceeded maximum round trips (${maxRoundTrips}). ` +\n 'This may indicate an infinite loop, excessive tool calls, ' +\n 'or a logic error in your code.'\n );\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`\n );\n }\n\n const toolResults = normalizeBashToolResultsForReplay(\n await executeTools(\n response.tool_calls ?? [],\n toolMap,\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING\n )\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 `Bash programmatic execution failed: ${messageWithReminder}`\n );\n }\n },\n {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n description: BashProgrammaticToolCallingDescription,\n schema: createBashProgrammaticToolCallingSchema(maxRunTimeoutMs),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"mappings":";;;;;;;8BAuBO;AAMP,MAAM,0BAA0B;AAChC,MAAM,yBAAyBA,mBAAAA,2BAA2B;;AAG1D,MAAM,gBAAgB,IAAI,IAAI;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAMD,MAAM,oBAAoB;;;;AAK1B,MAAM,aAAa;;;;;;;IAOfC,qBAAAA,4BAA4B;IAC5BC,qBAAAA,oBAAoB;;AAGxB,MAAM,mBACJ;AAEF,MAAM,WAAW;;;;;;;;;;;AAYjB,MAAM,yBAAyB;;EAE7B,kBAAkB;;;;;EAKlB,SAAS;;EAET;AAMF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B,MAAgB,SACjB,IACF;GACA,MAAM,IAAI,MACR,uCAAuC,qBACzC;EACF;CACF,GACA;EACE,MAAA;EACA,aAAa;EACb,QAAQ,wCAAwC,eAAe;EAC/D,gBAAA;CACF,CACF;AACF"}
1
+ {"version":3,"file":"BashProgrammaticToolCalling.cjs","names":["resolveCodeApiRunTimeoutMs","CODE_ARTIFACT_PATH_GUIDANCE","BASH_SHELL_GUIDANCE","createCodeApiRunTimeoutSchema","getCodeBaseURL","clampCodeApiRunTimeoutMs","makeRequest","executeTools","formatCompletedResponse","appendFailedExecutionFileReminder"],"sources":["../../../src/tools/BashProgrammaticToolCalling.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { ProgrammaticToolCallingJsonSchema } from './ptcTimeout';\nimport type * as t from '@/types';\nimport {\n BASH_SHELL_GUIDANCE,\n CODE_ARTIFACT_PATH_GUIDANCE,\n appendFailedExecutionFileReminder,\n getCodeBaseURL,\n} from './CodeExecutor';\nimport {\n clampCodeApiRunTimeoutMs,\n createCodeApiRunTimeoutSchema,\n resolveCodeApiRunTimeoutMs,\n} from './ptcTimeout';\nimport {\n makeRequest,\n executeTools,\n formatCompletedResponse,\n} from './ProgrammaticToolCalling';\nimport { Constants } from '@/common';\n\nconfig();\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\nconst DEFAULT_RUN_TIMEOUT_MS = resolveCodeApiRunTimeoutMs();\n\n/** Bash reserved words that get `_tool` suffix when used as function names */\nconst BASH_RESERVED = new Set([\n 'if',\n 'then',\n 'else',\n 'elif',\n 'fi',\n 'case',\n 'esac',\n 'for',\n 'while',\n 'until',\n 'do',\n 'done',\n 'in',\n 'function',\n 'select',\n 'time',\n 'coproc',\n 'declare',\n 'typeset',\n 'local',\n 'readonly',\n 'export',\n 'unset',\n]);\n\n// ============================================================================\n// Description Components\n// ============================================================================\n\nconst STATELESS_WARNING = `CRITICAL - STATELESS EXECUTION:\nEach call is a fresh bash shell. Variables and state do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block.\nDO NOT split work across multiple calls expecting to reuse variables.`;\n\nconst CORE_RULES = `Rules:\n- One call: state does not persist\n- Tools are pre-defined as bash functions—DO NOT redefine them\n- Each tool function accepts a JSON string argument\n- Save tool output with raw=$(tool '{}'); printf '%s\\n' \"$raw\" > /mnt/data/file.json; direct tool > file may be empty\n- Tool stdout is normalized to one compact JSON value when possible; parse saved stdout once, then use fromjson? // . only for JSON-string fields\n- Only echo/printf output returns to the model\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_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, reserved words get `_tool` suffix';\n\nconst EXAMPLES = `Example (Complete workflow in one call):\n # Query data and process\n data=$(query_database '{\"sql\": \"SELECT * FROM users\"}')\n echo \"$data\" | jq '.[] | .name'\n\nExample (Parallel calls):\n { sf=$(web_search '{\"query\": \"SF weather\"}'); printf '%s\\n' \"$sf\" > /mnt/data/sf.json; } &\n { ny=$(web_search '{\"query\": \"NY weather\"}'); printf '%s\\n' \"$ny\" > /mnt/data/ny.json; } &\n wait\n echo \"SF: $(jq -r . /mnt/data/sf.json)\"\n echo \"NY: $(jq -r . /mnt/data/ny.json)\"`;\n\nconst CODE_PARAM_DESCRIPTION = `Bash code that calls tools programmatically. Tools are available as bash functions.\n\n${STATELESS_WARNING}\n\nEach tool function accepts a JSON string as its argument.\nExample: tool_name '{\"key\": \"value\"}'\n\n${EXAMPLES}\n\n${CORE_RULES}`;\n\n// ============================================================================\n// Schema\n// ============================================================================\n\nexport function createBashProgrammaticToolCallingSchema(\n maxRunTimeoutMs = DEFAULT_RUN_TIMEOUT_MS\n): ProgrammaticToolCallingJsonSchema {\n return {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n minLength: 1,\n description: CODE_PARAM_DESCRIPTION,\n },\n timeout: createCodeApiRunTimeoutSchema(maxRunTimeoutMs),\n },\n required: ['code'],\n } as const;\n}\n\nexport const BashProgrammaticToolCallingSchema =\n createBashProgrammaticToolCallingSchema();\n\nexport const BashProgrammaticToolCallingName =\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING;\n\nexport const BashProgrammaticToolCallingDescription = `\nRun tools via bash code. Tools are available as bash functions that accept JSON string arguments.\n\n${STATELESS_WARNING}\n\n${CORE_RULES}\n${ADDITIONAL_RULES}\n\nWhen to use: shell pipelines, parallel execution (& and wait), file processing, text manipulation.\n\n${EXAMPLES}\n`.trim();\n\nexport const BashProgrammaticToolCallingDefinition = {\n name: BashProgrammaticToolCallingName,\n description: BashProgrammaticToolCallingDescription,\n schema: BashProgrammaticToolCallingSchema,\n} as const;\n\nfunction maybeParseJsonResultString(result: unknown): unknown {\n if (typeof result !== 'string') {\n return result;\n }\n\n const trimmed = result.trim();\n if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {\n return result;\n }\n\n try {\n return JSON.parse(trimmed) as unknown;\n } catch {\n return result;\n }\n}\n\nexport function normalizeBashToolResultsForReplay(\n toolResults: t.PTCToolResult[]\n): t.PTCToolResult[] {\n return toolResults.map((toolResult) => {\n if (toolResult.is_error) {\n return toolResult;\n }\n\n return {\n ...toolResult,\n result: maybeParseJsonResultString(toolResult.result),\n };\n });\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Normalizes a tool name to a valid bash function identifier.\n * 1. Replace hyphens, spaces, dots with underscores\n * 2. Remove any other invalid characters\n * 3. Prefix with underscore if starts with number\n * 4. Append `_tool` if it's a bash reserved word\n */\nexport function normalizeToBashIdentifier(name: string): string {\n let normalized = name.replace(/[-\\s.]/g, '_');\n normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');\n\n if (/^[0-9]/.test(normalized)) {\n normalized = '_' + normalized;\n }\n\n if (BASH_RESERVED.has(normalized)) {\n normalized = normalized + '_tool';\n }\n\n return normalized;\n}\n\n/**\n * Extracts tool names that are actually called in the bash code.\n * Bash functions are invoked as commands (no parentheses), so we match\n * the normalized name as a word boundary.\n */\nexport function extractUsedBashToolNames(\n code: string,\n toolNameMap: Map<string, string>\n): Set<string> {\n const usedTools = new Set<string>();\n\n for (const [bashName, originalName] of toolNameMap) {\n const escapedName = bashName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const pattern = new RegExp(`\\\\b${escapedName}\\\\b`, 'g');\n\n if (pattern.test(code)) {\n usedTools.add(originalName);\n }\n }\n\n return usedTools;\n}\n\n/**\n * Filters tool definitions to only include tools actually used in the bash code.\n */\nexport function filterBashToolsByUsage(\n toolDefs: t.LCTool[],\n code: string,\n debug = false\n): t.LCTool[] {\n const toolNameMap = new Map<string, string>();\n for (const def of toolDefs) {\n const bashName = normalizeToBashIdentifier(def.name);\n toolNameMap.set(bashName, def.name);\n }\n\n const usedToolNames = extractUsedBashToolNames(code, toolNameMap);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`\n );\n if (usedToolNames.size > 0) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`\n );\n }\n }\n\n if (usedToolNames.size === 0) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[BashPTC Debug] No tools detected in code - sending all tools as fallback'\n );\n }\n return toolDefs;\n }\n\n return toolDefs.filter((def) => usedToolNames.has(def.name));\n}\n\n// ============================================================================\n// Tool Factory\n// ============================================================================\n\n/**\n * Creates a Bash Programmatic Tool Calling tool for multi-tool orchestration.\n *\n * This tool enables AI agents to write bash scripts that orchestrate multiple\n * tool calls programmatically via the remote Code API, reducing LLM round-trips.\n *\n * The tool map must be provided at runtime via config.toolCall (injected by ToolNode).\n */\nexport function createBashProgrammaticToolCallingTool(\n initParams: t.BashProgrammaticToolCallingParams = {}\n): DynamicStructuredTool {\n const baseUrl = initParams.baseUrl ?? getCodeBaseURL();\n const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;\n const maxRunTimeoutMs = resolveCodeApiRunTimeoutMs(initParams.runTimeoutMs);\n const proxy = initParams.proxy ?? process.env.PROXY;\n const debug = initParams.debug ?? process.env.BASH_PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n return tool(\n async (rawParams, config) => {\n const params = rawParams as { code: string; timeout?: number };\n const { code } = params;\n const timeout = clampCodeApiRunTimeoutMs(params.timeout, maxRunTimeoutMs);\n\n const toolCall = (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache> & {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n _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 = filterBashToolsByUsage(toolDefs, code, debug);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Sending ${effectiveTools.length} tools to API ` +\n `(filtered from ${toolDefs.length})`\n );\n }\n\n /* `/files/<session_id>` HTTP fallback removed — codeapi's\n * sessionAuth requires kind/id query params unavailable at\n * this point. See `CodeExecutor.ts` for full rationale. */\n let files: t.CodeEnvFile[] | undefined;\n if (_injected_files && _injected_files.length > 0) {\n files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n // eslint-disable-next-line no-console\n console.debug(\n `[BashProgrammaticToolCalling] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n /* Stateful sessions: hint on the INITIAL request only (continuations\n * bind via continuation_token). Wire-only in v1 — BashPTC keeps its\n * stateless prompt. */\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 lang: 'bash',\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 `[BashPTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`\n );\n }\n\n const toolResults = normalizeBashToolResultsForReplay(\n await executeTools(\n response.tool_calls ?? [],\n toolMap,\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING\n )\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 `Bash programmatic execution failed: ${messageWithReminder}`\n );\n }\n },\n {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n description: BashProgrammaticToolCallingDescription,\n schema: createBashProgrammaticToolCallingSchema(maxRunTimeoutMs),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"mappings":";;;;;;;8BAuBO;AAMP,MAAM,0BAA0B;AAChC,MAAM,yBAAyBA,mBAAAA,2BAA2B;;AAG1D,MAAM,gBAAgB,IAAI,IAAI;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAMD,MAAM,oBAAoB;;;;AAK1B,MAAM,aAAa;;;;;;;IAOfC,qBAAAA,4BAA4B;IAC5BC,qBAAAA,oBAAoB;;AAGxB,MAAM,mBACJ;AAEF,MAAM,WAAW;;;;;;;;;;;AAYjB,MAAM,yBAAyB;;EAE7B,kBAAkB;;;;;EAKlB,SAAS;;EAET;AAMF,SAAgB,wCACd,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,oCACX,wCAAwC;AAE1C,MAAa,kCAAA;AAGb,MAAa,yCAAyC;;;EAGpD,kBAAkB;;EAElB,WAAW;EACX,iBAAiB;;;;EAIjB,SAAS;EACT,KAAK;AAEP,MAAa,wCAAwC;CACnD,MAAM;CACN,aAAa;CACb,QAAQ;AACV;AAEA,SAAS,2BAA2B,QAA0B;CAC5D,IAAI,OAAO,WAAW,UACpB,OAAO;CAGT,MAAM,UAAU,OAAO,KAAK;CAC5B,IAAI,CAAC,QAAQ,WAAW,GAAG,KAAK,CAAC,QAAQ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ACA;IACA,GAAI,SAAS,MAAM,SAAS,IAAI,EAAE,MAAM,IAAI,CAAC;IAC7C,GAAI,sBAAsB,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,8BAA8B,UAAU,IAAI,SAAS,YAAY,UAAU,EAAE,oBAC/E;IAGF,MAAM,cAAc,kCAClB,MAAMC,gCAAAA,aACJ,SAAS,cAAc,CAAC,GACxB,SAAA,qBAEF,CACF;IAEA,WAAW,MAAMD,gCAAAA,YACf,eACA;KACE,oBAAoB,SAAS;KAC7B,cAAc;IAChB,GACA,OACA,WAAW,WACb;GACF;GAMA,IAAI,SAAS,WAAW,aACtB,OAAOE,gCAAAA,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,uCAAuC,qBACzC;EACF;CACF,GACA;EACE,MAAA;EACA,aAAa;EACb,QAAQ,wCAAwC,eAAe;EAC/D,gBAAA;CACF,CACF;AACF"}
@@ -97,6 +97,43 @@ Usage:
97
97
  - ${CODE_ARTIFACT_PATH_GUIDANCE}
98
98
  - NEVER use this tool to execute malicious code.
99
99
  `.trim();
100
+ /**
101
+ * Best-effort statefulness note. Deliberately hedged: warm reuse is an
102
+ * optimization, not a guarantee (the runtime may be reset on idle timeout,
103
+ * eviction, or the 8h VM lifetime), so the model must never depend on carried
104
+ * state for correctness and must persist anything durable to /mnt/data.
105
+ */
106
+ const STATEFUL_ENV_NOTE = "Session state (best-effort): consecutive executions in this conversation usually share one runtime, so variables, imports, and in-memory data from earlier successful calls are typically still available. The runtime may be reset at any time, so treat carried-over state as an optimization, never a guarantee. Anything that must survive MUST be written to /mnt/data. If a NameError/ImportError signals lost state, re-run the needed setup and continue.";
107
+ const StatefulCodeExecutionToolDescription = `
108
+ Runs code and returns stdout/stderr output from a session-based execution environment, similar to a long-running command-line session.
109
+
110
+ ${STATEFUL_ENV_NOTE}
111
+
112
+ Usage:
113
+ - No network access available.
114
+ - Generated files are automatically delivered; **DO NOT** provide download links.
115
+ - ${CODE_ARTIFACT_PATH_GUIDANCE}
116
+ - NEVER use this tool to execute malicious code.
117
+ `.trim();
118
+ function buildCodeExecutionToolDescription(opts) {
119
+ return opts?.statefulSessions === true ? StatefulCodeExecutionToolDescription : CodeExecutionToolDescription;
120
+ }
121
+ const STATELESS_CODE_PARAM_NOTE = "The environment is stateless; variables and imports don't persist between executions.";
122
+ const STATEFUL_CODE_PARAM_NOTE = "Executions in this conversation usually share one runtime: variables and imports from prior successful calls are typically still defined, but the runtime may reset between calls. Rebuild state on NameError/ImportError; persist anything important to /mnt/data.";
123
+ function buildCodeExecutionToolSchema(opts) {
124
+ const note = opts?.statefulSessions === true ? STATEFUL_CODE_PARAM_NOTE : STATELESS_CODE_PARAM_NOTE;
125
+ const codeDescription = CodeExecutionToolSchema.properties.code.description.replace(STATELESS_CODE_PARAM_NOTE, note);
126
+ return {
127
+ ...CodeExecutionToolSchema,
128
+ properties: {
129
+ ...CodeExecutionToolSchema.properties,
130
+ code: {
131
+ ...CodeExecutionToolSchema.properties.code,
132
+ description: codeDescription
133
+ }
134
+ }
135
+ };
136
+ }
100
137
  const CodeExecutionToolName = "execute_code";
101
138
  const CodeExecutionToolDefinition = {
102
139
  name: CodeExecutionToolName,
@@ -105,20 +142,21 @@ const CodeExecutionToolDefinition = {
105
142
  };
106
143
  function createCodeExecutionTool(params = {}) {
107
144
  return (0, _langchain_core_tools.tool)(async (rawInput, config) => {
108
- const { authHeaders, ...executionParams } = params ?? {};
109
- const { lang, code, ...rest } = rawInput;
145
+ const { authHeaders, statefulSessions: _statefulSessions, ...executionParams } = params ?? {};
146
+ const { lang, code, runtime_session_hint: _ignoredModelHint, ...rest } = rawInput;
110
147
  /**
111
148
  * Extract session context from config.toolCall (injected by ToolNode).
112
149
  * - session_id: associates with the previous run.
113
150
  * - _injected_files: File refs to pass directly (avoids /files endpoint race condition).
114
151
  */
115
- const { session_id, _injected_files } = config.toolCall ?? {};
152
+ const { session_id, _injected_files, _runtime_session_hint } = config.toolCall ?? {};
116
153
  const postData = {
117
154
  lang,
118
155
  code,
119
156
  ...rest,
120
157
  ...executionParams
121
158
  };
159
+ if (typeof _runtime_session_hint === "string" && _runtime_session_hint !== "") postData.runtime_session_hint = _runtime_session_hint;
122
160
  if (_injected_files && _injected_files.length > 0) postData.files = _injected_files;
123
161
  else if (session_id != null && session_id.length > 0 && !Array.isArray(postData.files)) console.debug(`[CodeExecutor] No injected files for session_id=${session_id} — exec will run without input files`);
124
162
  try {
@@ -141,18 +179,26 @@ function createCodeExecutionTool(params = {}) {
141
179
  if (result.stderr) formattedOutput += `stderr:\n${result.stderr}\n`;
142
180
  const outputWithReminder = appendTmpScratchReminder(formattedOutput, code);
143
181
  const hasFiles = result.files != null && result.files.length > 0;
182
+ const runtimeEcho = result.runtime_session_id != null ? {
183
+ runtime_session_id: result.runtime_session_id,
184
+ runtime_status: result.runtime_status
185
+ } : {};
144
186
  return [require_CodeSessionFileSummary.appendCodeSessionFileSummary(outputWithReminder, result.files), hasFiles ? {
145
187
  session_id: result.session_id,
146
- files: result.files
147
- } : { session_id: result.session_id }];
188
+ files: result.files,
189
+ ...runtimeEcho
190
+ } : {
191
+ session_id: result.session_id,
192
+ ...runtimeEcho
193
+ }];
148
194
  } catch (error) {
149
195
  const messageWithReminder = appendFailedExecutionFileReminder(error?.message ?? "", code);
150
196
  throw new Error(`Execution error:\n\n${messageWithReminder}`);
151
197
  }
152
198
  }, {
153
199
  name: CodeExecutionToolName,
154
- description: CodeExecutionToolDescription,
155
- schema: CodeExecutionToolSchema,
200
+ description: buildCodeExecutionToolDescription(params ?? void 0),
201
+ schema: buildCodeExecutionToolSchema(params ?? void 0),
156
202
  responseFormat: "content_and_artifact"
157
203
  });
158
204
  }
@@ -164,10 +210,14 @@ exports.CodeExecutionToolDescription = CodeExecutionToolDescription;
164
210
  exports.CodeExecutionToolName = CodeExecutionToolName;
165
211
  exports.CodeExecutionToolSchema = CodeExecutionToolSchema;
166
212
  exports.FAILED_EXECUTION_FILE_REMINDER = FAILED_EXECUTION_FILE_REMINDER;
213
+ exports.STATEFUL_ENV_NOTE = STATEFUL_ENV_NOTE;
214
+ exports.StatefulCodeExecutionToolDescription = StatefulCodeExecutionToolDescription;
167
215
  exports.TMP_SCRATCH_OUTPUT_REMINDER = TMP_SCRATCH_OUTPUT_REMINDER;
168
216
  exports.appendFailedExecutionFileReminder = appendFailedExecutionFileReminder;
169
217
  exports.appendTmpScratchReminder = appendTmpScratchReminder;
170
218
  exports.buildCodeApiHttpErrorMessage = buildCodeApiHttpErrorMessage;
219
+ exports.buildCodeExecutionToolDescription = buildCodeExecutionToolDescription;
220
+ exports.buildCodeExecutionToolSchema = buildCodeExecutionToolSchema;
171
221
  exports.createCodeExecutionTool = createCodeExecutionTool;
172
222
  exports.emptyOutputMessage = emptyOutputMessage;
173
223
  exports.getCodeBaseURL = getCodeBaseURL;
@@ -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\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 const { authHeaders, ...executionParams } = params ?? {};\n const { lang, code, ...rest } = rawInput as {\n lang: SupportedLanguage;\n code: string;\n args?: string[];\n };\n /**\n * Extract session context from config.toolCall (injected by ToolNode).\n * - session_id: associates with the previous run.\n * - _injected_files: File refs to pass directly (avoids /files endpoint race condition).\n */\n const { session_id, _injected_files } = (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n const postData: Record<string, unknown> = {\n lang,\n code,\n ...rest,\n ...executionParams,\n };\n\n /* File injection: `_injected_files` from ToolNode (set when host\n * primes a CodeSessionContext) or `params.files` from tool\n * factory (set by hosts that pre-resolve at construction time).\n * The legacy `/files/<session_id>` HTTP fallback was removed —\n * codeapi's `sessionAuth` middleware now requires kind/id query\n * params the tool can't supply at this point, so the fetch 400'd\n * silently and the catch swallowed the failure. */\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (\n session_id != null &&\n session_id.length > 0 &&\n !Array.isArray(postData.files)\n ) {\n // eslint-disable-next-line no-console\n console.debug(\n `[CodeExecutor] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n try {\n const resolvedAuthHeaders =\n await resolveCodeApiAuthHeaders(authHeaders);\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n ...resolvedAuthHeaders,\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(\n await buildCodeApiHttpErrorMessage('POST', EXEC_ENDPOINT, response)\n );\n }\n\n const result: t.ExecuteResult = await response.json();\n 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 return [\n appendCodeSessionFileSummary(outputWithReminder, result.files),\n (hasFiles\n ? { session_id: result.session_id, files: result.files }\n : {\n session_id: result.session_id,\n }) satisfies t.CodeExecutionArtifact,\n ];\n } catch (error) {\n 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: CodeExecutionToolDescription,\n schema: CodeExecutionToolSchema,\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,MAAs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AM,IACrD,EACA,YAAY,OAAO,WACrB,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;EACb,QAAQ;EACR,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\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 * Best-effort statefulness note. Deliberately hedged: warm reuse is an\n * optimization, not a guarantee (the runtime may be reset on idle timeout,\n * eviction, or the 8h VM lifetime), so the model must never depend on carried\n * state for correctness and must persist anything durable to /mnt/data.\n */\nexport const STATEFUL_ENV_NOTE =\n 'Session state (best-effort): consecutive executions in this conversation usually share one runtime, so variables, imports, and in-memory data from earlier successful calls are typically still available. The runtime may be reset at any time, so treat carried-over state as an optimization, never a guarantee. Anything that must survive MUST be written to /mnt/data. If a NameError/ImportError signals lost state, re-run the needed setup and continue.';\n\nexport const StatefulCodeExecutionToolDescription = `\nRuns code and returns stdout/stderr output from a session-based execution environment, similar to a long-running command-line session.\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 usually share one runtime: variables and imports from prior successful calls are typically still defined, but the runtime may reset between calls. Rebuild state on NameError/ImportError; persist anything important to /mnt/data.';\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;AAE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U,IACrD,aAAa,QAAQ,IAAIA,kBAAAA,gBAAgB,QAAQ,IAAI,KAAK;GAE5D,MAAM,WAAW,OAAA,GAAA,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"}
@@ -470,7 +470,11 @@ function formatCompletedResponse(response, sourceCode = "") {
470
470
  if (response.stderr != null && response.stderr !== "") formatted += `stderr:\n${response.stderr}\n`;
471
471
  return [require_CodeSessionFileSummary.appendCodeSessionFileSummary(require_CodeExecutor.appendTmpScratchReminder(formatted, sourceCode), response.files), {
472
472
  session_id: response.session_id,
473
- files: response.files
473
+ files: response.files,
474
+ ...response.runtime_session_id != null ? {
475
+ runtime_session_id: response.runtime_session_id,
476
+ runtime_status: response.runtime_status
477
+ } : {}
474
478
  }];
475
479
  }
476
480
  /**
@@ -503,7 +507,7 @@ function createProgrammaticToolCallingTool(initParams = {}) {
503
507
  const params = rawParams;
504
508
  const { code } = params;
505
509
  const timeout = require_ptcTimeout.clampCodeApiRunTimeoutMs(params.timeout, maxRunTimeoutMs);
506
- const { toolMap, toolDefs, session_id, _injected_files } = config.toolCall ?? {};
510
+ const { toolMap, toolDefs, session_id, _injected_files, _runtime_session_hint } = config.toolCall ?? {};
507
511
  if (toolMap == null || toolMap.size === 0) throw new Error("No toolMap provided. ToolNode should inject this from AgentContext when invoked through the graph.");
508
512
  if (toolDefs == null || toolDefs.length === 0) throw new Error("No tool definitions provided. Either pass tools in the input or ensure ToolNode injects toolDefs.");
509
513
  let roundTrip = 0;
@@ -519,12 +523,14 @@ function createProgrammaticToolCallingTool(initParams = {}) {
519
523
  let files;
520
524
  if (_injected_files && _injected_files.length > 0) files = _injected_files;
521
525
  else if (session_id != null && session_id.length > 0) console.debug(`[ProgrammaticToolCalling] No injected files for session_id=${session_id} — exec will run without input files`);
526
+ const runtimeSessionHint = typeof _runtime_session_hint === "string" && _runtime_session_hint !== "" ? _runtime_session_hint : void 0;
522
527
  let response = await makeRequest(EXEC_ENDPOINT, {
523
528
  code,
524
529
  tools: effectiveTools,
525
530
  session_id,
526
531
  timeout,
527
- ...files && files.length > 0 ? { files } : {}
532
+ ...files && files.length > 0 ? { files } : {},
533
+ ...runtimeSessionHint != null ? { runtime_session_hint: runtimeSessionHint } : {}
528
534
  }, proxy, initParams.authHeaders);
529
535
  while (response.status === "tool_call_required") {
530
536
  roundTrip++;