@librechat/agents 3.3.5 → 3.3.6

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 (127) hide show
  1. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs +1 -1
  2. package/dist/cjs/llm/openai/index.cjs +51 -6
  3. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  4. package/dist/cjs/main.cjs +14 -0
  5. package/dist/cjs/session/JsonlSessionStore.cjs +1 -1
  6. package/dist/cjs/stream.cjs +6 -1
  7. package/dist/cjs/stream.cjs.map +1 -1
  8. package/dist/cjs/tools/BashExecutor.cjs +3 -1
  9. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  10. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +2 -0
  11. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  12. package/dist/cjs/tools/CodeExecutor.cjs +19 -16
  13. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  14. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +2 -0
  15. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  16. package/dist/cjs/tools/ReadFile.cjs +8 -4
  17. package/dist/cjs/tools/ReadFile.cjs.map +1 -1
  18. package/dist/cjs/tools/SkillTool.cjs +2 -0
  19. package/dist/cjs/tools/SkillTool.cjs.map +1 -1
  20. package/dist/cjs/tools/SubagentTool.cjs +3 -0
  21. package/dist/cjs/tools/SubagentTool.cjs.map +1 -1
  22. package/dist/cjs/tools/ToolNode.cjs +88 -27
  23. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  24. package/dist/cjs/tools/ToolSearch.cjs +5 -1
  25. package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
  26. package/dist/cjs/tools/intentArg.cjs +230 -0
  27. package/dist/cjs/tools/intentArg.cjs.map +1 -0
  28. package/dist/cjs/tools/local/CompileCheckTool.cjs +3 -2
  29. package/dist/cjs/tools/local/CompileCheckTool.cjs.map +1 -1
  30. package/dist/cjs/tools/local/LocalCodingTools.cjs +13 -12
  31. package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -1
  32. package/dist/cjs/tools/local/LocalExecutionEngine.cjs +2 -2
  33. package/dist/cjs/tools/ptcTimeout.cjs.map +1 -1
  34. package/dist/cjs/tools/search/schema.cjs +2 -0
  35. package/dist/cjs/tools/search/schema.cjs.map +1 -1
  36. package/dist/cjs/tools/search/tool.cjs +31 -1
  37. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  38. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +1 -0
  39. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  40. package/dist/cjs/tools/toolOutputReferences.cjs +41 -7
  41. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
  42. package/dist/esm/hooks/createWorkspacePolicyHook.mjs +1 -1
  43. package/dist/esm/llm/openai/index.mjs +51 -6
  44. package/dist/esm/llm/openai/index.mjs.map +1 -1
  45. package/dist/esm/main.mjs +4 -3
  46. package/dist/esm/session/JsonlSessionStore.mjs +1 -1
  47. package/dist/esm/stream.mjs +6 -1
  48. package/dist/esm/stream.mjs.map +1 -1
  49. package/dist/esm/tools/BashExecutor.mjs +3 -1
  50. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  51. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +2 -0
  52. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  53. package/dist/esm/tools/CodeExecutor.mjs +19 -16
  54. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  55. package/dist/esm/tools/ProgrammaticToolCalling.mjs +2 -0
  56. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  57. package/dist/esm/tools/ReadFile.mjs +8 -4
  58. package/dist/esm/tools/ReadFile.mjs.map +1 -1
  59. package/dist/esm/tools/SkillTool.mjs +2 -0
  60. package/dist/esm/tools/SkillTool.mjs.map +1 -1
  61. package/dist/esm/tools/SubagentTool.mjs +3 -0
  62. package/dist/esm/tools/SubagentTool.mjs.map +1 -1
  63. package/dist/esm/tools/ToolNode.mjs +88 -28
  64. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  65. package/dist/esm/tools/ToolSearch.mjs +5 -1
  66. package/dist/esm/tools/ToolSearch.mjs.map +1 -1
  67. package/dist/esm/tools/intentArg.mjs +220 -0
  68. package/dist/esm/tools/intentArg.mjs.map +1 -0
  69. package/dist/esm/tools/local/CompileCheckTool.mjs +3 -2
  70. package/dist/esm/tools/local/CompileCheckTool.mjs.map +1 -1
  71. package/dist/esm/tools/local/LocalCodingTools.mjs +13 -12
  72. package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -1
  73. package/dist/esm/tools/local/LocalExecutionEngine.mjs +2 -2
  74. package/dist/esm/tools/ptcTimeout.mjs.map +1 -1
  75. package/dist/esm/tools/search/schema.mjs +2 -0
  76. package/dist/esm/tools/search/schema.mjs.map +1 -1
  77. package/dist/esm/tools/search/tool.mjs +31 -2
  78. package/dist/esm/tools/search/tool.mjs.map +1 -1
  79. package/dist/esm/tools/subagent/SubagentExecutor.mjs +1 -0
  80. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  81. package/dist/esm/tools/toolOutputReferences.mjs +41 -7
  82. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
  83. package/dist/types/index.d.ts +1 -0
  84. package/dist/types/llm/openai/index.d.ts +0 -11
  85. package/dist/types/tools/BashExecutor.d.ts +18 -0
  86. package/dist/types/tools/CodeExecutor.d.ts +18 -0
  87. package/dist/types/tools/ReadFile.d.ts +18 -0
  88. package/dist/types/tools/SkillTool.d.ts +18 -0
  89. package/dist/types/tools/SubagentTool.d.ts +9 -0
  90. package/dist/types/tools/ToolNode.d.ts +37 -5
  91. package/dist/types/tools/ToolSearch.d.ts +18 -0
  92. package/dist/types/tools/intentArg.d.ts +119 -0
  93. package/dist/types/tools/ptcTimeout.d.ts +2 -0
  94. package/dist/types/tools/search/schema.d.ts +18 -0
  95. package/dist/types/tools/search/tool.d.ts +18 -0
  96. package/dist/types/tools/toolOutputReferences.d.ts +12 -2
  97. package/dist/types/types/stream.d.ts +12 -0
  98. package/dist/types/types/tools.d.ts +27 -2
  99. package/package.json +1 -1
  100. package/src/index.ts +1 -0
  101. package/src/llm/openai/index.ts +74 -10
  102. package/src/llm/openai/llm.spec.ts +105 -0
  103. package/src/stream.ts +12 -1
  104. package/src/tools/BashExecutor.ts +6 -0
  105. package/src/tools/BashProgrammaticToolCalling.ts +2 -0
  106. package/src/tools/CodeExecutor.ts +6 -0
  107. package/src/tools/ProgrammaticToolCalling.ts +2 -0
  108. package/src/tools/ReadFile.ts +2 -0
  109. package/src/tools/SkillTool.ts +2 -0
  110. package/src/tools/SubagentTool.ts +3 -0
  111. package/src/tools/ToolNode.ts +190 -43
  112. package/src/tools/ToolSearch.ts +3 -0
  113. package/src/tools/__tests__/ToolNode.onResultCompletion.test.ts +174 -0
  114. package/src/tools/__tests__/intentArg.test.ts +281 -0
  115. package/src/tools/__tests__/intentCoverage.test.ts +139 -0
  116. package/src/tools/__tests__/toolOutputReferences.test.ts +83 -0
  117. package/src/tools/intentArg.ts +323 -0
  118. package/src/tools/local/CompileCheckTool.ts +4 -3
  119. package/src/tools/local/LocalCodingTools.ts +14 -13
  120. package/src/tools/ptcTimeout.ts +2 -0
  121. package/src/tools/search/outcome.test.ts +90 -0
  122. package/src/tools/search/schema.ts +3 -0
  123. package/src/tools/search/tool.ts +47 -1
  124. package/src/tools/subagent/SubagentExecutor.ts +2 -1
  125. package/src/tools/toolOutputReferences.ts +77 -9
  126. package/src/types/stream.ts +12 -0
  127. package/src/types/tools.ts +24 -2
@@ -1 +1 @@
1
- {"version":3,"file":"BashExecutor.cjs","names":["getCodeBaseURL","CODE_ARTIFACT_PATH_GUIDANCE","BASH_SHELL_GUIDANCE","resolveCodeApiAuthHeaders","HttpsProxyAgent","CodeApiRequestError","buildCodeApiHttpErrorMessage","emptyOutputMessage","appendTmpScratchReminder","appendCodeSessionFileSummary","appendFailedExecutionFileReminder","normalizeCodeApiRequestError"],"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 CodeApiRequestError,\n getCodeBaseURL,\n normalizeCodeApiRequestError,\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 and scoped to `/mnt/data`. The machine\n * is warm across calls, but each call runs in a fresh sandbox (new process\n * tree + private /tmp), so background processes are reaped when the call ends\n * and anything written outside /mnt/data is discarded. The note must not\n * promise otherwise: a model told background processes survive will start a\n * server in one call and assume it is listening in the next.\n */\nexport const STATEFUL_BASH_NOTE =\n 'Session state: commands in this conversation run on the same warm machine, so files written to /mnt/data persist between calls. Each call runs in a fresh, isolated sandbox: shell variables, the working directory, /tmp, and background processes do NOT survive after the call returns — a process started in one call is terminated when that call ends. Only /mnt/data is durable (the machine itself may also be reset at any time).';\n\nexport const StatefulBashExecutionToolDescription = `\nRuns bash commands and returns stdout/stderr output. Commands in this conversation share one warm machine with a persistent /mnt/data, but each command runs in its own isolated sandbox (not a persistent shell session).\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 written to /mnt/data persist between calls on the same warm machine. Each call runs in a fresh sandbox: shell variables, cwd, /tmp, and background processes do NOT survive the call. 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 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 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 normalizeCodeApiRequestError(error).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":";;;;;;;;;;;mBAoBO;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;;;;;;;;;AAUP,MAAa,qBACX;AAEF,MAAa,uCAAuC;;;EAGlD,mBAAmB;;;;;IAKjBD,qBAAAA,4BAA4B;IAC5BC,qBAAAA,oBAAoB;;EAEtB,KAAK;;;;;;;;;;;AAYP,MAAa,gCAAgC;;;;;;;;;EAS3C,KAAK;;;;;;;;AASP,SAAgB,kCAAkC,SAGvC;CACT,MAAM,OACJ,SAAS,qBAAqB,OAC1B,uCACA;CACN,IAAI,SAAS,+BAA+B,MAC1C,OAAO,GAAG,KAAK,MAAM;CAEvB,OAAO;AACT;AAEA,MAAM,4BACJ;AACF,MAAM,2BACJ;AAEF,SAAgB,6BAA6B,MAEV;CACjC,MAAM,OACJ,MAAM,qBAAqB,OACvB,2BACA;CACN,MAAM,qBACJ,wBAAwB,WAAW,QAAQ,YAAY,QACrD,2BACA,IACF;CACF,OAAO;EACL,GAAG;EACH,YAAY;GACV,GAAG,wBAAwB;GAC3B,SAAS;IACP,GAAG,wBAAwB,WAAW;IACtC,aAAa;GACf;EACF;CACF;AACF;AAEA,MAAa,wBAAA;;;;;;;;;;;AAYb,MAAa,8BAA8B;CACzC,MAAM;CACN,aAAa;CACb,QAAQ;AACV;AAE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ACzB,iBACA,OACF;GACA,MAAM,WAAW,OAAO,SAAS,QAAQ,OAAO,MAAM,SAAS;GAC/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,sBAAsBC,qBAAAA,kCAC1BC,qBAAAA,6BAA6B,KAAK,CAAC,CAAC,SACpC,OACF;GACA,MAAM,IAAI,MAAM,uBAAuB,qBAAqB;EAC9D;CACF,GACA;EACE,MAAM;EACN,aAAa,kCAAkC,EAC7C,kBAAkB,QAAQ,iBAC5B,CAAC;EACD,QAAQ,6BAA6B,UAAU,KAAA,CAAS;EACxD,gBAAA;CACF,CACF;AACF"}
1
+ {"version":3,"file":"BashExecutor.cjs","names":["getCodeBaseURL","INTENT_PROPERTY","CODE_ARTIFACT_PATH_GUIDANCE","BASH_SHELL_GUIDANCE","resolveCodeApiAuthHeaders","HttpsProxyAgent","CodeApiRequestError","buildCodeApiHttpErrorMessage","emptyOutputMessage","appendTmpScratchReminder","appendCodeSessionFileSummary","appendFailedExecutionFileReminder","normalizeCodeApiRequestError"],"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 CodeApiRequestError,\n getCodeBaseURL,\n normalizeCodeApiRequestError,\n resolveCodeApiAuthHeaders,\n} from './CodeExecutor';\nimport { INTENT_PROPERTY } from '@/tools/intentArg';\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 intent: { ...INTENT_PROPERTY },\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 and scoped to `/mnt/data`. The machine\n * is warm across calls, but each call runs in a fresh sandbox (new process\n * tree + private /tmp), so background processes are reaped when the call ends\n * and anything written outside /mnt/data is discarded. The note must not\n * promise otherwise: a model told background processes survive will start a\n * server in one call and assume it is listening in the next.\n */\nexport const STATEFUL_BASH_NOTE =\n 'Session state: commands in this conversation run on the same warm machine, so files written to /mnt/data persist between calls. Each call runs in a fresh, isolated sandbox: shell variables, the working directory, /tmp, and background processes do NOT survive after the call returns — a process started in one call is terminated when that call ends. Only /mnt/data is durable (the machine itself may also be reset at any time).';\n\nexport const StatefulBashExecutionToolDescription = `\nRuns bash commands and returns stdout/stderr output. Commands in this conversation share one warm machine with a persistent /mnt/data, but each command runs in its own isolated sandbox (not a persistent shell session).\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 written to /mnt/data persist between calls on the same warm machine. Each call runs in a fresh sandbox: shell variables, cwd, /tmp, and background processes do NOT survive the call. 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 /* `intent` is a UI display label — never part of the wire body. */\n const {\n command,\n intent: _ignoredIntent,\n runtime_session_hint: _ignoredModelHint,\n ...rest\n } = rawInput as {\n command: string;\n intent?: unknown;\n runtime_session_hint?: unknown;\n args?: string[];\n };\n void _ignoredModelHint;\n void _ignoredIntent;\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 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 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 normalizeCodeApiRequestError(error).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":";;;;;;;;;;;;mBAqBO;AAGP,MAAM,gBAAgB,GADDA,qBAAAA,eACe,EAAE;AAEtC,MAAa,0BAA0B;CACrC,MAAM;CACN,YAAY;EACV,QAAQ,EAAE,GAAGC,kBAAAA,gBAAgB;EAC7B,SAAS;GACP,MAAM;GACN,aAAa;;;IAGfC,q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,YAAY,OAAO;IACnB,OAAO,OAAO;IACd,GAAG;GACL,IACE;IACA,YAAY,OAAO;IACnB,GAAG;GACL,CACJ;EACF,SAAS,OAAO;GACd,MAAM,sBAAsBC,qBAAAA,kCAC1BC,qBAAAA,6BAA6B,KAAK,CAAC,CAAC,SACpC,OACF;GACA,MAAM,IAAI,MAAM,uBAAuB,qBAAqB;EAC9D;CACF,GACA;EACE,MAAM;EACN,aAAa,kCAAkC,EAC7C,kBAAkB,QAAQ,iBAC5B,CAAC;EACD,QAAQ,6BAA6B,UAAU,KAAA,CAAS;EACxD,gBAAA;CACF,CACF;AACF"}
@@ -1,5 +1,6 @@
1
1
  require("../common/enum.cjs");
2
2
  require("../common/index.cjs");
3
+ const require_intentArg = require("./intentArg.cjs");
3
4
  const require_CodeExecutor = require("./CodeExecutor.cjs");
4
5
  const require_ptcTimeout = require("./ptcTimeout.cjs");
5
6
  const require_ProgrammaticToolCalling = require("./ProgrammaticToolCalling.cjs");
@@ -74,6 +75,7 @@ function createBashProgrammaticToolCallingSchema(maxRunTimeoutMs = DEFAULT_RUN_T
74
75
  return {
75
76
  type: "object",
76
77
  properties: {
78
+ intent: { ...require_intentArg.INTENT_PROPERTY },
77
79
  code: {
78
80
  type: "string",
79
81
  minLength: 1,
@@ -1 +1 @@
1
- {"version":3,"file":"BashProgrammaticToolCalling.cjs","names":["resolveCodeApiRunTimeoutMs","CODE_ARTIFACT_PATH_GUIDANCE","BASH_SHELL_GUIDANCE","createCodeApiRunTimeoutSchema","getCodeBaseURL","clampCodeApiRunTimeoutMs","makeRequest","executeTools","formatCompletedResponse","buildCodeApiExecutionErrorMessage","CodeApiRequestError","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 buildCodeApiExecutionErrorMessage,\n CodeApiRequestError,\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(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 `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":";;;;;;;8BAyBO;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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AU,IAAI;GAG/C,IAAI,SAAS,WAAW,SACtB,MAAM,IAAI,MAAMC,qBAAAA,kCAAkC,QAAQ,CAAC;GAG7D,MAAM,IAAIC,qBAAAA,oBAAoB;EAChC,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"}
1
+ {"version":3,"file":"BashProgrammaticToolCalling.cjs","names":["resolveCodeApiRunTimeoutMs","CODE_ARTIFACT_PATH_GUIDANCE","BASH_SHELL_GUIDANCE","INTENT_PROPERTY","createCodeApiRunTimeoutSchema","getCodeBaseURL","clampCodeApiRunTimeoutMs","makeRequest","executeTools","formatCompletedResponse","buildCodeApiExecutionErrorMessage","CodeApiRequestError","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 buildCodeApiExecutionErrorMessage,\n CodeApiRequestError,\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 { INTENT_PROPERTY } from '@/tools/intentArg';\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 intent: { ...INTENT_PROPERTY },\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(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 `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":";;;;;;;;8BA0BO;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,QAAQ,EAAE,GAAGC,kBAAAA,gBAAgB;GAC7B,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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
1
  const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
2
2
  require("../common/enum.cjs");
3
3
  require("../common/index.cjs");
4
+ const require_intentArg = require("./intentArg.cjs");
4
5
  const require_CodeSessionFileSummary = require("./CodeSessionFileSummary.cjs");
5
6
  let _langchain_core_tools = require("@langchain/core/tools");
6
7
  let _langchain_core_utils_env = require("@langchain/core/utils/env");
@@ -26,26 +27,28 @@ function appendFailedExecutionFileReminder(output, code) {
26
27
  if (!MNT_DATA_PATH_PATTERN.test(code) || output.includes("Note: any files written during this failed call were not registered for later calls; fix the error and rerun before relying on them.")) return output;
27
28
  return `${output.trimEnd()}\n${FAILED_EXECUTION_FILE_REMINDER}\n`;
28
29
  }
30
+ const SUPPORTED_LANGUAGES = [
31
+ "py",
32
+ "js",
33
+ "ts",
34
+ "c",
35
+ "cpp",
36
+ "java",
37
+ "php",
38
+ "rs",
39
+ "go",
40
+ "d",
41
+ "f90",
42
+ "r",
43
+ "bash"
44
+ ];
29
45
  const CodeExecutionToolSchema = {
30
46
  type: "object",
31
47
  properties: {
48
+ intent: { ...require_intentArg.INTENT_PROPERTY },
32
49
  lang: {
33
50
  type: "string",
34
- enum: [
35
- "py",
36
- "js",
37
- "ts",
38
- "c",
39
- "cpp",
40
- "java",
41
- "php",
42
- "rs",
43
- "go",
44
- "d",
45
- "f90",
46
- "r",
47
- "bash"
48
- ],
51
+ enum: SUPPORTED_LANGUAGES,
49
52
  description: "The programming language or runtime to execute the code in."
50
53
  },
51
54
  code: {
@@ -198,7 +201,7 @@ const CodeExecutionToolDefinition = {
198
201
  function createCodeExecutionTool(params = {}) {
199
202
  return (0, _langchain_core_tools.tool)(async (rawInput, config) => {
200
203
  const { authHeaders, statefulSessions: _statefulSessions, ...executionParams } = params ?? {};
201
- const { lang, code, runtime_session_hint: _ignoredModelHint, ...rest } = rawInput;
204
+ const { lang, code, intent: _ignoredIntent, runtime_session_hint: _ignoredModelHint, ...rest } = rawInput;
202
205
  /**
203
206
  * Extract session context from config.toolCall (injected by ToolNode).
204
207
  * - session_id: associates with the previous run.
@@ -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\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;I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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,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"}
1
+ {"version":3,"file":"CodeExecutor.cjs","names":["INTENT_PROPERTY","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 { INTENT_PROPERTY } from '@/tools/intentArg';\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 intent: { ...INTENT_PROPERTY },\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 /* `intent` is a UI display label — never part of the wire body. */\n const {\n lang,\n code,\n intent: _ignoredIntent,\n runtime_session_hint: _ignoredModelHint,\n ...rest\n } = rawInput as {\n lang: SupportedLanguage;\n code: string;\n intent?: unknown;\n runtime_session_hint?: unknown;\n args?: string[];\n };\n void _ignoredModelHint;\n void _ignoredIntent;\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":";;;;;;;;;;;;mBAeO;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;AAEA,MAAM,sBAAsB;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,0BAA0B;CACrC,MAAM;CACN,YAAY;EACV,QAAQ,EAAE,GAAGA,kBAAAA,gBAAgB;EAC7B,MAAM;GACJ,MAAM;GACN,MAAM;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;CACF,iCAAiC;CACjC,iBAA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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"}
@@ -1,6 +1,7 @@
1
1
  const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
2
2
  require("../common/enum.cjs");
3
3
  require("../common/index.cjs");
4
+ const require_intentArg = require("./intentArg.cjs");
4
5
  const require_CodeSessionFileSummary = require("./CodeSessionFileSummary.cjs");
5
6
  const require_CodeExecutor = require("./CodeExecutor.cjs");
6
7
  const require_ptcTimeout = require("./ptcTimeout.cjs");
@@ -54,6 +55,7 @@ function createProgrammaticToolCallingSchema(maxRunTimeoutMs = DEFAULT_RUN_TIMEO
54
55
  return {
55
56
  type: "object",
56
57
  properties: {
58
+ intent: { ...require_intentArg.INTENT_PROPERTY },
57
59
  code: {
58
60
  type: "string",
59
61
  minLength: 1,
@@ -1 +1 @@
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,MAAM,yBAAyB;;EAE7B,kBAAkB;;;;EAIlB,SAAS;;EAET;AAEF,SAAgB,oCACd,kBAAkB,wBACiB;CACnC,OAAO;EACL,MAAM;EACN,YAAY;GACV,MAAM;IACJ,MAAM;IACN,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eApiRunTimeoutMs","CODE_ARTIFACT_PATH_GUIDANCE","INTENT_PROPERTY","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 { INTENT_PROPERTY } from '@/tools/intentArg';\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 intent: { ...INTENT_PROPERTY },\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":";;;;;;;;;;;;;mBA6BO;;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,QAAQ,EAAE,GAAGC,kBAAAA,gBAAgB;GAC7B,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,kBAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAkBD,SAAS,yBACP,OACiC;CACjC,IAAI,SAAS,QAAQ,OAAO,UAAU,UACpC,OAAO;CAET,MAAM,QAAQ;CACd,KACG,MAAM,SAAS,WAAW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