@illuma-ai/agents 1.4.0-alpha.6 → 1.5.0

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 (800) hide show
  1. package/README.md +62 -0
  2. package/dist/cjs/agents/AgentContext.cjs +274 -67
  3. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  4. package/dist/cjs/common/enum.cjs +44 -13
  5. package/dist/cjs/common/enum.cjs.map +1 -1
  6. package/dist/cjs/graphs/Graph.cjs +182 -5
  7. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  8. package/dist/cjs/graphs/MultiAgentGraph.cjs +152 -1167
  9. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  10. package/dist/cjs/hooks/HookRegistry.cjs +162 -0
  11. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -0
  12. package/dist/cjs/hooks/executeHooks.cjs +276 -0
  13. package/dist/cjs/hooks/executeHooks.cjs.map +1 -0
  14. package/dist/cjs/hooks/matchers.cjs +256 -0
  15. package/dist/cjs/hooks/matchers.cjs.map +1 -0
  16. package/dist/cjs/hooks/types.cjs +27 -0
  17. package/dist/cjs/hooks/types.cjs.map +1 -0
  18. package/dist/cjs/langchain/google-common.cjs +3 -0
  19. package/dist/cjs/langchain/google-common.cjs.map +1 -0
  20. package/dist/cjs/langchain/index.cjs +86 -0
  21. package/dist/cjs/langchain/index.cjs.map +1 -0
  22. package/dist/cjs/langchain/language_models/chat_models.cjs +3 -0
  23. package/dist/cjs/langchain/language_models/chat_models.cjs.map +1 -0
  24. package/dist/cjs/langchain/messages/tool.cjs +3 -0
  25. package/dist/cjs/langchain/messages/tool.cjs.map +1 -0
  26. package/dist/cjs/langchain/messages.cjs +51 -0
  27. package/dist/cjs/langchain/messages.cjs.map +1 -0
  28. package/dist/cjs/langchain/openai.cjs +3 -0
  29. package/dist/cjs/langchain/openai.cjs.map +1 -0
  30. package/dist/cjs/langchain/prompts.cjs +11 -0
  31. package/dist/cjs/langchain/prompts.cjs.map +1 -0
  32. package/dist/cjs/langchain/runnables.cjs +19 -0
  33. package/dist/cjs/langchain/runnables.cjs.map +1 -0
  34. package/dist/cjs/langchain/tools.cjs +23 -0
  35. package/dist/cjs/langchain/tools.cjs.map +1 -0
  36. package/dist/cjs/langchain/utils/env.cjs +11 -0
  37. package/dist/cjs/langchain/utils/env.cjs.map +1 -0
  38. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +5 -1
  39. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  40. package/dist/cjs/llm/bedrock/cacheSupport.cjs +55 -0
  41. package/dist/cjs/llm/bedrock/cacheSupport.cjs.map +1 -0
  42. package/dist/cjs/llm/bedrock/index.cjs +61 -33
  43. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  44. package/dist/cjs/llm/openai/index.cjs +0 -3
  45. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  46. package/dist/cjs/llm/openai/utils/index.cjs +27 -10
  47. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
  48. package/dist/cjs/main.cjs +178 -127
  49. package/dist/cjs/main.cjs.map +1 -1
  50. package/dist/cjs/messages/cache.cjs +89 -0
  51. package/dist/cjs/messages/cache.cjs.map +1 -1
  52. package/dist/cjs/messages/contextPruning.cjs +156 -0
  53. package/dist/cjs/messages/contextPruning.cjs.map +1 -0
  54. package/dist/cjs/messages/contextPruningSettings.cjs +53 -0
  55. package/dist/cjs/messages/contextPruningSettings.cjs.map +1 -0
  56. package/dist/cjs/messages/format.cjs +144 -20
  57. package/dist/cjs/messages/format.cjs.map +1 -1
  58. package/dist/cjs/messages/prune.cjs +505 -4
  59. package/dist/cjs/messages/prune.cjs.map +1 -1
  60. package/dist/cjs/run.cjs +141 -1
  61. package/dist/cjs/run.cjs.map +1 -1
  62. package/dist/cjs/tools/BashExecutor.cjs +235 -0
  63. package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
  64. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +297 -0
  65. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
  66. package/dist/cjs/tools/CodeExecutor.cjs +44 -47
  67. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  68. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +16 -11
  69. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  70. package/dist/cjs/tools/ReadFile.cjs +44 -0
  71. package/dist/cjs/tools/ReadFile.cjs.map +1 -0
  72. package/dist/cjs/tools/SkillTool.cjs +51 -0
  73. package/dist/cjs/tools/SkillTool.cjs.map +1 -0
  74. package/dist/cjs/tools/SubagentTool.cjs +93 -0
  75. package/dist/cjs/tools/SubagentTool.cjs.map +1 -0
  76. package/dist/cjs/tools/ToolNode.cjs +450 -24
  77. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  78. package/dist/cjs/tools/search/search.cjs +11 -3
  79. package/dist/cjs/tools/search/search.cjs.map +1 -1
  80. package/dist/cjs/tools/search/tavily-scraper.cjs +189 -0
  81. package/dist/cjs/tools/search/tavily-scraper.cjs.map +1 -0
  82. package/dist/cjs/tools/search/tavily-search.cjs +372 -0
  83. package/dist/cjs/tools/search/tavily-search.cjs.map +1 -0
  84. package/dist/cjs/tools/search/tool.cjs +28 -4
  85. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  86. package/dist/cjs/tools/search/utils.cjs +10 -3
  87. package/dist/cjs/tools/search/utils.cjs.map +1 -1
  88. package/dist/cjs/tools/skillCatalog.cjs +84 -0
  89. package/dist/cjs/tools/skillCatalog.cjs.map +1 -0
  90. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +512 -0
  91. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -0
  92. package/dist/cjs/tools/toolOutputReferences.cjs +670 -0
  93. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -0
  94. package/dist/cjs/types/agent-cache.cjs +53 -0
  95. package/dist/cjs/types/agent-cache.cjs.map +1 -0
  96. package/dist/cjs/types/graph.cjs.map +1 -1
  97. package/dist/cjs/utils/truncation.cjs +135 -0
  98. package/dist/cjs/utils/truncation.cjs.map +1 -0
  99. package/dist/esm/agents/AgentContext.mjs +274 -67
  100. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  101. package/dist/esm/common/enum.mjs +44 -12
  102. package/dist/esm/common/enum.mjs.map +1 -1
  103. package/dist/esm/graphs/Graph.mjs +182 -5
  104. package/dist/esm/graphs/Graph.mjs.map +1 -1
  105. package/dist/esm/graphs/MultiAgentGraph.mjs +155 -1170
  106. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  107. package/dist/esm/hooks/HookRegistry.mjs +160 -0
  108. package/dist/esm/hooks/HookRegistry.mjs.map +1 -0
  109. package/dist/esm/hooks/executeHooks.mjs +273 -0
  110. package/dist/esm/hooks/executeHooks.mjs.map +1 -0
  111. package/dist/esm/hooks/matchers.mjs +251 -0
  112. package/dist/esm/hooks/matchers.mjs.map +1 -0
  113. package/dist/esm/hooks/types.mjs +25 -0
  114. package/dist/esm/hooks/types.mjs.map +1 -0
  115. package/dist/esm/langchain/google-common.mjs +2 -0
  116. package/dist/esm/langchain/google-common.mjs.map +1 -0
  117. package/dist/esm/langchain/index.mjs +5 -0
  118. package/dist/esm/langchain/language_models/chat_models.mjs +2 -0
  119. package/dist/esm/langchain/language_models/chat_models.mjs.map +1 -0
  120. package/dist/esm/langchain/messages/tool.mjs +2 -0
  121. package/dist/esm/langchain/messages/tool.mjs.map +1 -0
  122. package/dist/esm/langchain/messages.mjs +2 -0
  123. package/dist/esm/langchain/messages.mjs.map +1 -0
  124. package/dist/esm/langchain/openai.mjs +2 -0
  125. package/dist/esm/langchain/openai.mjs.map +1 -0
  126. package/dist/esm/langchain/prompts.mjs +2 -0
  127. package/dist/esm/langchain/prompts.mjs.map +1 -0
  128. package/dist/esm/langchain/runnables.mjs +2 -0
  129. package/dist/esm/langchain/runnables.mjs.map +1 -0
  130. package/dist/esm/langchain/tools.mjs +2 -0
  131. package/dist/esm/langchain/tools.mjs.map +1 -0
  132. package/dist/esm/langchain/utils/env.mjs +2 -0
  133. package/dist/esm/langchain/utils/env.mjs.map +1 -0
  134. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +5 -1
  135. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  136. package/dist/esm/llm/bedrock/cacheSupport.mjs +52 -0
  137. package/dist/esm/llm/bedrock/cacheSupport.mjs.map +1 -0
  138. package/dist/esm/llm/bedrock/index.mjs +61 -34
  139. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  140. package/dist/esm/llm/openai/index.mjs +0 -3
  141. package/dist/esm/llm/openai/index.mjs.map +1 -1
  142. package/dist/esm/llm/openai/utils/index.mjs +27 -10
  143. package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
  144. package/dist/esm/main.mjs +21 -27
  145. package/dist/esm/main.mjs.map +1 -1
  146. package/dist/esm/messages/cache.mjs +89 -0
  147. package/dist/esm/messages/cache.mjs.map +1 -1
  148. package/dist/esm/messages/contextPruning.mjs +154 -0
  149. package/dist/esm/messages/contextPruning.mjs.map +1 -0
  150. package/dist/esm/messages/contextPruningSettings.mjs +50 -0
  151. package/dist/esm/messages/contextPruningSettings.mjs.map +1 -0
  152. package/dist/esm/messages/format.mjs +136 -12
  153. package/dist/esm/messages/format.mjs.map +1 -1
  154. package/dist/esm/messages/prune.mjs +504 -7
  155. package/dist/esm/messages/prune.mjs.map +1 -1
  156. package/dist/esm/run.mjs +141 -1
  157. package/dist/esm/run.mjs.map +1 -1
  158. package/dist/esm/tools/BashExecutor.mjs +227 -0
  159. package/dist/esm/tools/BashExecutor.mjs.map +1 -0
  160. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +288 -0
  161. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
  162. package/dist/esm/tools/CodeExecutor.mjs +44 -48
  163. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  164. package/dist/esm/tools/ProgrammaticToolCalling.mjs +17 -12
  165. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  166. package/dist/esm/tools/ReadFile.mjs +39 -0
  167. package/dist/esm/tools/ReadFile.mjs.map +1 -0
  168. package/dist/esm/tools/SkillTool.mjs +46 -0
  169. package/dist/esm/tools/SkillTool.mjs.map +1 -0
  170. package/dist/esm/tools/SubagentTool.mjs +86 -0
  171. package/dist/esm/tools/SubagentTool.mjs.map +1 -0
  172. package/dist/esm/tools/ToolNode.mjs +452 -26
  173. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  174. package/dist/esm/tools/search/search.mjs +11 -3
  175. package/dist/esm/tools/search/search.mjs.map +1 -1
  176. package/dist/esm/tools/search/tavily-scraper.mjs +186 -0
  177. package/dist/esm/tools/search/tavily-scraper.mjs.map +1 -0
  178. package/dist/esm/tools/search/tavily-search.mjs +370 -0
  179. package/dist/esm/tools/search/tavily-search.mjs.map +1 -0
  180. package/dist/esm/tools/search/tool.mjs +28 -4
  181. package/dist/esm/tools/search/tool.mjs.map +1 -1
  182. package/dist/esm/tools/search/utils.mjs +10 -3
  183. package/dist/esm/tools/search/utils.mjs.map +1 -1
  184. package/dist/esm/tools/skillCatalog.mjs +82 -0
  185. package/dist/esm/tools/skillCatalog.mjs.map +1 -0
  186. package/dist/esm/tools/subagent/SubagentExecutor.mjs +506 -0
  187. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -0
  188. package/dist/esm/tools/toolOutputReferences.mjs +662 -0
  189. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -0
  190. package/dist/esm/types/agent-cache.mjs +51 -0
  191. package/dist/esm/types/agent-cache.mjs.map +1 -0
  192. package/dist/esm/types/graph.mjs.map +1 -1
  193. package/dist/esm/utils/truncation.mjs +128 -0
  194. package/dist/esm/utils/truncation.mjs.map +1 -0
  195. package/dist/types/agents/AgentContext.d.ts +101 -8
  196. package/dist/types/common/enum.d.ts +39 -12
  197. package/dist/types/common/index.d.ts +0 -1
  198. package/dist/types/graphs/Graph.d.ts +43 -0
  199. package/dist/types/graphs/MultiAgentGraph.d.ts +26 -150
  200. package/dist/types/graphs/index.d.ts +0 -1
  201. package/dist/types/hooks/HookRegistry.d.ts +56 -0
  202. package/dist/types/hooks/executeHooks.d.ts +79 -0
  203. package/dist/types/hooks/index.d.ts +6 -0
  204. package/dist/types/hooks/matchers.d.ts +95 -0
  205. package/dist/types/hooks/types.d.ts +320 -0
  206. package/dist/types/index.d.ts +9 -9
  207. package/dist/types/langchain/google-common.d.ts +1 -0
  208. package/dist/types/langchain/index.d.ts +8 -0
  209. package/dist/types/langchain/language_models/chat_models.d.ts +1 -0
  210. package/dist/types/langchain/messages/tool.d.ts +1 -0
  211. package/dist/types/langchain/messages.d.ts +2 -0
  212. package/dist/types/langchain/openai.d.ts +1 -0
  213. package/dist/types/langchain/prompts.d.ts +1 -0
  214. package/dist/types/langchain/runnables.d.ts +2 -0
  215. package/dist/types/langchain/tools.d.ts +2 -0
  216. package/dist/types/langchain/utils/env.d.ts +1 -0
  217. package/dist/types/llm/bedrock/cacheSupport.d.ts +35 -0
  218. package/dist/types/llm/bedrock/index.d.ts +54 -1
  219. package/dist/types/messages/contextPruning.d.ts +42 -0
  220. package/dist/types/messages/contextPruningSettings.d.ts +44 -0
  221. package/dist/types/messages/format.d.ts +9 -1
  222. package/dist/types/messages/index.d.ts +2 -0
  223. package/dist/types/messages/prune.d.ts +91 -1
  224. package/dist/types/run.d.ts +2 -0
  225. package/dist/types/tools/BashExecutor.d.ts +76 -0
  226. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +72 -0
  227. package/dist/types/tools/CodeExecutor.d.ts +8 -26
  228. package/dist/types/tools/ReadFile.d.ts +28 -0
  229. package/dist/types/tools/SkillTool.d.ts +40 -0
  230. package/dist/types/tools/SubagentTool.d.ts +36 -0
  231. package/dist/types/tools/ToolNode.d.ts +77 -5
  232. package/dist/types/tools/search/tavily-scraper.d.ts +19 -0
  233. package/dist/types/tools/search/tavily-search.d.ts +4 -0
  234. package/dist/types/tools/search/types.d.ts +99 -5
  235. package/dist/types/tools/search/utils.d.ts +2 -2
  236. package/dist/types/tools/skillCatalog.d.ts +19 -0
  237. package/dist/types/tools/subagent/SubagentExecutor.d.ts +137 -0
  238. package/dist/types/tools/subagent/index.d.ts +2 -0
  239. package/dist/types/tools/subagent/types.d.ts +84 -0
  240. package/dist/types/tools/toolOutputReferences.d.ts +236 -0
  241. package/dist/types/types/agent-cache.d.ts +70 -0
  242. package/dist/types/types/graph.d.ts +162 -22
  243. package/dist/types/types/index.d.ts +3 -0
  244. package/dist/types/types/messages.d.ts +26 -0
  245. package/dist/types/types/run.d.ts +22 -0
  246. package/dist/types/types/skill.d.ts +9 -0
  247. package/dist/types/types/tools.d.ts +111 -0
  248. package/dist/types/utils/index.d.ts +1 -3
  249. package/dist/types/utils/truncation.d.ts +70 -0
  250. package/package.json +57 -17
  251. package/src/agents/AgentContext.js.map +1 -0
  252. package/src/agents/AgentContext.test.js.map +1 -0
  253. package/src/agents/AgentContext.ts +321 -78
  254. package/src/agents/__tests__/AgentContext.cacheTtl.live.test.ts +259 -0
  255. package/src/agents/__tests__/AgentContext.crossAgentTier1.live.test.ts +264 -0
  256. package/src/agents/__tests__/AgentContext.crossUserCache.live.test.ts +342 -0
  257. package/src/agents/__tests__/AgentContext.test.js.map +1 -0
  258. package/src/agents/__tests__/AgentContext.test.ts +632 -0
  259. package/src/agents/__tests__/resolveStructuredOutputMode.test.js.map +1 -0
  260. package/src/common/__tests__/enum.test.ts +7 -17
  261. package/src/common/enum.js.map +1 -0
  262. package/src/common/enum.ts +43 -12
  263. package/src/common/index.js.map +1 -0
  264. package/src/common/index.ts +0 -1
  265. package/src/events.js.map +1 -0
  266. package/src/graphs/Graph.js.map +1 -0
  267. package/src/graphs/Graph.ts +222 -2
  268. package/src/graphs/MultiAgentGraph.js.map +1 -0
  269. package/src/graphs/MultiAgentGraph.ts +154 -1466
  270. package/src/graphs/__tests__/MultiAgentGraph.test.ts +91 -0
  271. package/src/graphs/__tests__/structured-output.integration.test.js.map +1 -0
  272. package/src/graphs/__tests__/structured-output.test.js.map +1 -0
  273. package/src/graphs/contextManagement.e2e.test.js.map +1 -0
  274. package/src/graphs/contextManagement.test.js.map +1 -0
  275. package/src/graphs/handoffValidation.test.js.map +1 -0
  276. package/src/graphs/index.js.map +1 -0
  277. package/src/graphs/index.ts +0 -1
  278. package/src/hooks/HookRegistry.ts +208 -0
  279. package/src/hooks/__tests__/HookRegistry.test.ts +190 -0
  280. package/src/hooks/__tests__/compactHooks.test.ts +214 -0
  281. package/src/hooks/__tests__/executeHooks.test.ts +1013 -0
  282. package/src/hooks/__tests__/integration.test.ts +337 -0
  283. package/src/hooks/__tests__/matchers.test.ts +238 -0
  284. package/src/hooks/__tests__/toolHooks.test.ts +665 -0
  285. package/src/hooks/executeHooks.ts +375 -0
  286. package/src/hooks/index.ts +57 -0
  287. package/src/hooks/matchers.ts +280 -0
  288. package/src/hooks/types.ts +404 -0
  289. package/src/index.js.map +1 -0
  290. package/src/index.ts +15 -24
  291. package/src/instrumentation.js.map +1 -0
  292. package/src/langchain/google-common.ts +1 -0
  293. package/src/langchain/index.ts +8 -0
  294. package/src/langchain/language_models/chat_models.ts +1 -0
  295. package/src/langchain/messages/tool.ts +5 -0
  296. package/src/langchain/messages.ts +21 -0
  297. package/src/langchain/openai.ts +1 -0
  298. package/src/langchain/prompts.ts +1 -0
  299. package/src/langchain/runnables.ts +7 -0
  300. package/src/langchain/tools.ts +8 -0
  301. package/src/langchain/utils/env.ts +1 -0
  302. package/src/llm/anthropic/index.js.map +1 -0
  303. package/src/llm/anthropic/types.js.map +1 -0
  304. package/src/llm/anthropic/utils/message_inputs.js.map +1 -0
  305. package/src/llm/anthropic/utils/message_inputs.ts +10 -1
  306. package/src/llm/anthropic/utils/message_outputs.js.map +1 -0
  307. package/src/llm/anthropic/utils/output_parsers.js.map +1 -0
  308. package/src/llm/anthropic/utils/server-tool-inputs.test.ts +436 -0
  309. package/src/llm/anthropic/utils/tools.js.map +1 -0
  310. package/src/llm/bedrock/__tests__/bedrock-caching.test.js.map +1 -0
  311. package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +166 -18
  312. package/src/llm/bedrock/cacheSupport.test.ts +99 -0
  313. package/src/llm/bedrock/cacheSupport.ts +53 -0
  314. package/src/llm/bedrock/index.js.map +1 -0
  315. package/src/llm/bedrock/index.ts +116 -41
  316. package/src/llm/bedrock/types.js.map +1 -0
  317. package/src/llm/bedrock/utils/index.js.map +1 -0
  318. package/src/llm/bedrock/utils/message_inputs.js.map +1 -0
  319. package/src/llm/bedrock/utils/message_outputs.js.map +1 -0
  320. package/src/llm/fake.js.map +1 -0
  321. package/src/llm/google/index.js.map +1 -0
  322. package/src/llm/google/types.js.map +1 -0
  323. package/src/llm/google/utils/common.js.map +1 -0
  324. package/src/llm/google/utils/tools.js.map +1 -0
  325. package/src/llm/google/utils/zod_to_genai_parameters.js.map +1 -0
  326. package/src/llm/openai/index.js.map +1 -0
  327. package/src/llm/openai/types.js.map +1 -0
  328. package/src/llm/openai/utils/index.js.map +1 -0
  329. package/src/llm/openai/utils/index.ts +31 -14
  330. package/src/llm/openai/utils/isReasoningModel.test.js.map +1 -0
  331. package/src/llm/openrouter/index.js.map +1 -0
  332. package/src/llm/openrouter/reasoning.test.js.map +1 -0
  333. package/src/llm/providers.js.map +1 -0
  334. package/src/llm/text.js.map +1 -0
  335. package/src/llm/vertexai/index.js.map +1 -0
  336. package/src/messages/__tests__/contextPruning.test.ts +228 -0
  337. package/src/messages/__tests__/tools.test.js.map +1 -0
  338. package/src/messages/cache.js.map +1 -0
  339. package/src/messages/cache.test.js.map +1 -0
  340. package/src/messages/cache.test.ts +62 -24
  341. package/src/messages/cache.ts +112 -0
  342. package/src/messages/content.js.map +1 -0
  343. package/src/messages/content.test.js.map +1 -0
  344. package/src/messages/contextPruning.ts +191 -0
  345. package/src/messages/contextPruningSettings.ts +90 -0
  346. package/src/messages/core.js.map +1 -0
  347. package/src/messages/ensureThinkingBlock.test.js.map +1 -0
  348. package/src/messages/format.js.map +1 -0
  349. package/src/messages/format.ts +164 -12
  350. package/src/messages/formatAgentMessages.skills.test.ts +413 -0
  351. package/src/messages/formatAgentMessages.test.js.map +1 -0
  352. package/src/messages/formatAgentMessages.tools.test.js.map +1 -0
  353. package/src/messages/formatMessage.test.js.map +1 -0
  354. package/src/messages/ids.js.map +1 -0
  355. package/src/messages/index.js.map +1 -0
  356. package/src/messages/index.ts +2 -0
  357. package/src/messages/labelContentByAgent.test.js.map +1 -0
  358. package/src/messages/prune.js.map +1 -0
  359. package/src/messages/prune.ts +661 -4
  360. package/src/messages/reducer.js.map +1 -0
  361. package/src/messages/shiftIndexTokenCountMap.test.js.map +1 -0
  362. package/src/messages/summarize.js.map +1 -0
  363. package/src/messages/summarize.test.js.map +1 -0
  364. package/src/messages/tools.js.map +1 -0
  365. package/src/mockStream.js.map +1 -0
  366. package/src/prompts/collab.js.map +1 -0
  367. package/src/prompts/index.js.map +1 -0
  368. package/src/prompts/taskmanager.js.map +1 -0
  369. package/src/run.js.map +1 -0
  370. package/src/run.ts +155 -1
  371. package/src/schemas/index.js.map +1 -0
  372. package/src/schemas/schema-preparation.test.js.map +1 -0
  373. package/src/schemas/validate.js.map +1 -0
  374. package/src/schemas/validate.test.js.map +1 -0
  375. package/src/scripts/abort.js.map +1 -0
  376. package/src/scripts/ant_web_search.js.map +1 -0
  377. package/src/scripts/ant_web_search_edge_case.js.map +1 -0
  378. package/src/scripts/ant_web_search_error_edge_case.js.map +1 -0
  379. package/src/scripts/args.js.map +1 -0
  380. package/src/scripts/bedrock-cache-debug.js.map +1 -0
  381. package/src/scripts/bedrock-content-aggregation-test.js.map +1 -0
  382. package/src/scripts/bedrock-merge-test.js.map +1 -0
  383. package/src/scripts/bedrock-parallel-tools-test.js.map +1 -0
  384. package/src/scripts/caching.js.map +1 -0
  385. package/src/scripts/cli.js.map +1 -0
  386. package/src/scripts/cli2.js.map +1 -0
  387. package/src/scripts/cli3.js.map +1 -0
  388. package/src/scripts/cli4.js.map +1 -0
  389. package/src/scripts/cli5.js.map +1 -0
  390. package/src/scripts/code_exec.js.map +1 -0
  391. package/src/scripts/code_exec_files.js.map +1 -0
  392. package/src/scripts/code_exec_multi_session.js.map +1 -0
  393. package/src/scripts/code_exec_ptc.js.map +1 -0
  394. package/src/scripts/code_exec_session.js.map +1 -0
  395. package/src/scripts/code_exec_simple.js.map +1 -0
  396. package/src/scripts/content.js.map +1 -0
  397. package/src/scripts/empty_input.js.map +1 -0
  398. package/src/scripts/handoff-test.js.map +1 -0
  399. package/src/scripts/image.js.map +1 -0
  400. package/src/scripts/memory.js.map +1 -0
  401. package/src/scripts/multi-agent-chain.js.map +1 -0
  402. package/src/scripts/multi-agent-chain.ts +2 -2
  403. package/src/scripts/multi-agent-conditional.js.map +1 -0
  404. package/src/scripts/multi-agent-document-review-chain.js.map +1 -0
  405. package/src/scripts/multi-agent-document-review-chain.ts +2 -2
  406. package/src/scripts/multi-agent-hybrid-flow.js.map +1 -0
  407. package/src/scripts/multi-agent-hybrid-flow.ts +4 -4
  408. package/src/scripts/multi-agent-parallel-start.js.map +1 -0
  409. package/src/scripts/multi-agent-parallel.js.map +1 -0
  410. package/src/scripts/multi-agent-parallel.ts +3 -3
  411. package/src/scripts/multi-agent-sequence.js.map +1 -0
  412. package/src/scripts/multi-agent-sequence.ts +3 -3
  413. package/src/scripts/multi-agent-subagent.ts +246 -0
  414. package/src/scripts/multi-agent-supervisor.js.map +1 -0
  415. package/src/scripts/multi-agent-supervisor.ts +5 -5
  416. package/src/scripts/multi-agent-test.js.map +1 -0
  417. package/src/scripts/parallel-asymmetric-tools-test.js.map +1 -0
  418. package/src/scripts/parallel-full-metadata-test.js.map +1 -0
  419. package/src/scripts/parallel-tools-test.js.map +1 -0
  420. package/src/scripts/poc-multi-agent-comprehensive.ts +8 -8
  421. package/src/scripts/programmatic_exec.js.map +1 -0
  422. package/src/scripts/programmatic_exec_agent.js.map +1 -0
  423. package/src/scripts/search.js.map +1 -0
  424. package/src/scripts/sequential-full-metadata-test.js.map +1 -0
  425. package/src/scripts/sequential-full-metadata-test.ts +2 -2
  426. package/src/scripts/simple.js.map +1 -0
  427. package/src/scripts/single-agent-metadata-test.js.map +1 -0
  428. package/src/scripts/stream.js.map +1 -0
  429. package/src/scripts/subagent-event-driven-debug.ts +190 -0
  430. package/src/scripts/subagent-tools-debug.ts +160 -0
  431. package/src/scripts/test-custom-prompt-key.js.map +1 -0
  432. package/src/scripts/test-custom-prompt-key.ts +3 -3
  433. package/src/scripts/test-handoff-input.js.map +1 -0
  434. package/src/scripts/test-handoff-input.ts +1 -1
  435. package/src/scripts/test-handoff-preamble.js.map +1 -0
  436. package/src/scripts/test-handoff-steering.js.map +1 -0
  437. package/src/scripts/test-handoff-steering.ts +3 -3
  438. package/src/scripts/test-multi-agent-list-handoff.js.map +1 -0
  439. package/src/scripts/test-multi-agent-list-handoff.ts +1 -1
  440. package/src/scripts/test-parallel-agent-labeling.js.map +1 -0
  441. package/src/scripts/test-parallel-agent-labeling.ts +3 -3
  442. package/src/scripts/test-parallel-handoffs.js.map +1 -0
  443. package/src/scripts/test-parallel-handoffs.ts +2 -2
  444. package/src/scripts/test-thinking-handoff-bedrock.js.map +1 -0
  445. package/src/scripts/test-thinking-handoff-bedrock.ts +1 -1
  446. package/src/scripts/test-thinking-handoff.js.map +1 -0
  447. package/src/scripts/test-thinking-handoff.ts +1 -1
  448. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js.map +1 -0
  449. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.ts +1 -1
  450. package/src/scripts/test-tool-before-handoff-role-order.js.map +1 -0
  451. package/src/scripts/test-tool-before-handoff-role-order.ts +1 -1
  452. package/src/scripts/test-tools-before-handoff.js.map +1 -0
  453. package/src/scripts/test-tools-before-handoff.ts +1 -1
  454. package/src/scripts/test_code_api.js.map +1 -0
  455. package/src/scripts/thinking-bedrock.js.map +1 -0
  456. package/src/scripts/thinking-vertexai.js.map +1 -0
  457. package/src/scripts/thinking.js.map +1 -0
  458. package/src/scripts/tool_search.js.map +1 -0
  459. package/src/scripts/tools.js.map +1 -0
  460. package/src/specs/agent-handoffs-bedrock.integration.test.js.map +1 -0
  461. package/src/specs/agent-handoffs.test.js.map +1 -0
  462. package/src/specs/agent-handoffs.test.ts +26 -483
  463. package/src/specs/anthropic.simple.test.js.map +1 -0
  464. package/src/specs/anthropic.simple.test.ts +61 -0
  465. package/src/specs/azure.simple.test.js.map +1 -0
  466. package/src/specs/cache.simple.test.js.map +1 -0
  467. package/src/specs/custom-event-await.test.js.map +1 -0
  468. package/src/specs/deepseek.simple.test.js.map +1 -0
  469. package/src/specs/emergency-prune.test.js.map +1 -0
  470. package/src/specs/moonshot.simple.test.js.map +1 -0
  471. package/src/specs/multi-agent-summarization.test.ts +396 -0
  472. package/src/specs/observability.integration.test.js.map +1 -0
  473. package/src/specs/openai.simple.test.js.map +1 -0
  474. package/src/specs/openrouter.simple.test.js.map +1 -0
  475. package/src/specs/prune.orphans.test.ts +248 -0
  476. package/src/specs/prune.test.js.map +1 -0
  477. package/src/specs/prune.test.ts +104 -16
  478. package/src/specs/reasoning.test.js.map +1 -0
  479. package/src/specs/spec.utils.js.map +1 -0
  480. package/src/specs/thinking-handoff.test.js.map +1 -0
  481. package/src/specs/thinking-handoff.test.ts +19 -19
  482. package/src/specs/thinking-prune.test.js.map +1 -0
  483. package/src/specs/token-distribution-edge-case.test.js.map +1 -0
  484. package/src/specs/token-memoization.test.js.map +1 -0
  485. package/src/specs/tokens.test.js.map +1 -0
  486. package/src/specs/tool-error.test.js.map +1 -0
  487. package/src/splitStream.js.map +1 -0
  488. package/src/splitStream.test.js.map +1 -0
  489. package/src/stream.js.map +1 -0
  490. package/src/stream.test.js.map +1 -0
  491. package/src/test/mockTools.js.map +1 -0
  492. package/src/tools/BashExecutor.ts +281 -0
  493. package/src/tools/BashProgrammaticToolCalling.ts +397 -0
  494. package/src/tools/BrowserTools.js.map +1 -0
  495. package/src/tools/Calculator.js.map +1 -0
  496. package/src/tools/Calculator.test.js.map +1 -0
  497. package/src/tools/CodeExecutor.js.map +1 -0
  498. package/src/tools/CodeExecutor.ts +62 -54
  499. package/src/tools/ProgrammaticToolCalling.js.map +1 -0
  500. package/src/tools/ProgrammaticToolCalling.ts +29 -14
  501. package/src/tools/ReadFile.ts +39 -0
  502. package/src/tools/SkillTool.ts +46 -0
  503. package/src/tools/StreamingToolCallBuffer.js.map +1 -0
  504. package/src/tools/SubagentTool.ts +100 -0
  505. package/src/tools/ToolNode.js.map +1 -0
  506. package/src/tools/ToolNode.ts +548 -26
  507. package/src/tools/ToolSearch.js.map +1 -0
  508. package/src/tools/__tests__/BashExecutor.test.ts +49 -0
  509. package/src/tools/__tests__/BrowserTools.test.js.map +1 -0
  510. package/src/tools/__tests__/CodeExecutor.test.ts +37 -36
  511. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js.map +1 -0
  512. package/src/tools/__tests__/ProgrammaticToolCalling.test.js.map +1 -0
  513. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +60 -0
  514. package/src/tools/__tests__/ReadFile.test.ts +44 -0
  515. package/src/tools/__tests__/SkillTool.test.ts +442 -0
  516. package/src/tools/__tests__/StreamingToolCallBuffer.test.js.map +1 -0
  517. package/src/tools/__tests__/SubagentExecutor.test.ts +1148 -0
  518. package/src/tools/__tests__/SubagentTool.test.ts +149 -0
  519. package/src/tools/__tests__/ToolApproval.test.js.map +1 -0
  520. package/src/tools/__tests__/ToolNode.outputReferences.test.ts +1438 -0
  521. package/src/tools/__tests__/ToolNode.recovery.test.js.map +1 -0
  522. package/src/tools/__tests__/ToolNode.session.test.js.map +1 -0
  523. package/src/tools/__tests__/ToolSearch.integration.test.js.map +1 -0
  524. package/src/tools/__tests__/ToolSearch.test.js.map +1 -0
  525. package/src/tools/__tests__/annotateMessagesForLLM.test.ts +479 -0
  526. package/src/tools/__tests__/handlers.test.js.map +1 -0
  527. package/src/tools/__tests__/skillCatalog.test.ts +161 -0
  528. package/src/tools/__tests__/subagentHooks.test.ts +210 -0
  529. package/src/tools/__tests__/toolOutputReferences.test.ts +415 -0
  530. package/src/tools/__tests__/truncation-recovery.integration.test.js.map +1 -0
  531. package/src/tools/handlers.js.map +1 -0
  532. package/src/tools/schema.js.map +1 -0
  533. package/src/tools/search/anthropic.js.map +1 -0
  534. package/src/tools/search/content.js.map +1 -0
  535. package/src/tools/search/content.test.js.map +1 -0
  536. package/src/tools/search/firecrawl.js.map +1 -0
  537. package/src/tools/search/format.js.map +1 -0
  538. package/src/tools/search/highlights.js.map +1 -0
  539. package/src/tools/search/index.js.map +1 -0
  540. package/src/tools/search/jina-reranker.test.js.map +1 -0
  541. package/src/tools/search/rerankers.js.map +1 -0
  542. package/src/tools/search/schema.js.map +1 -0
  543. package/src/tools/search/search.js.map +1 -0
  544. package/src/tools/search/search.ts +12 -2
  545. package/src/tools/search/serper-scraper.js.map +1 -0
  546. package/src/tools/search/tavily-scraper.ts +235 -0
  547. package/src/tools/search/tavily-search.ts +424 -0
  548. package/src/tools/search/tavily.test.ts +965 -0
  549. package/src/tools/search/test.js.map +1 -0
  550. package/src/tools/search/tool.js.map +1 -0
  551. package/src/tools/search/tool.ts +36 -2
  552. package/src/tools/search/types.js.map +1 -0
  553. package/src/tools/search/types.ts +133 -8
  554. package/src/tools/search/utils.js.map +1 -0
  555. package/src/tools/search/utils.ts +13 -5
  556. package/src/tools/skillCatalog.ts +126 -0
  557. package/src/tools/subagent/SubagentExecutor.ts +676 -0
  558. package/src/tools/subagent/index.ts +13 -0
  559. package/src/tools/subagent/types.test.ts +70 -0
  560. package/src/tools/subagent/types.ts +115 -0
  561. package/src/tools/toolOutputReferences.ts +825 -0
  562. package/src/types/agent-cache.ts +73 -0
  563. package/src/types/graph.js.map +1 -0
  564. package/src/types/graph.test.js.map +1 -0
  565. package/src/types/graph.ts +171 -20
  566. package/src/types/index.js.map +1 -0
  567. package/src/types/index.ts +3 -0
  568. package/src/types/llm.js.map +1 -0
  569. package/src/types/messages.js.map +1 -0
  570. package/src/types/messages.ts +27 -0
  571. package/src/types/run.js.map +1 -0
  572. package/src/types/run.ts +22 -0
  573. package/src/types/skill.ts +11 -0
  574. package/src/types/stream.js.map +1 -0
  575. package/src/types/tools.js.map +1 -0
  576. package/src/types/tools.ts +118 -0
  577. package/src/utils/__tests__/truncation.test.ts +66 -0
  578. package/src/utils/contextAnalytics.js.map +1 -0
  579. package/src/utils/contextAnalytics.test.js.map +1 -0
  580. package/src/utils/events.js.map +1 -0
  581. package/src/utils/graph.js.map +1 -0
  582. package/src/utils/handlers.js.map +1 -0
  583. package/src/utils/index.js.map +1 -0
  584. package/src/utils/index.ts +1 -3
  585. package/src/utils/llm.js.map +1 -0
  586. package/src/utils/llmConfig.js.map +1 -0
  587. package/src/utils/logging.js.map +1 -0
  588. package/src/utils/misc.js.map +1 -0
  589. package/src/utils/run.js.map +1 -0
  590. package/src/utils/schema.js.map +1 -0
  591. package/src/utils/title.js.map +1 -0
  592. package/src/utils/tokens.js.map +1 -0
  593. package/src/utils/toonFormat.js.map +1 -0
  594. package/src/utils/truncation.ts +154 -0
  595. package/dist/cjs/common/spawnPath.cjs +0 -104
  596. package/dist/cjs/common/spawnPath.cjs.map +0 -1
  597. package/dist/cjs/content/ArtifactStore.cjs +0 -579
  598. package/dist/cjs/content/ArtifactStore.cjs.map +0 -1
  599. package/dist/cjs/content/ContentStore.cjs +0 -638
  600. package/dist/cjs/content/ContentStore.cjs.map +0 -1
  601. package/dist/cjs/content/contentAnalyzer.cjs +0 -91
  602. package/dist/cjs/content/contentAnalyzer.cjs.map +0 -1
  603. package/dist/cjs/content/index.cjs +0 -20
  604. package/dist/cjs/content/index.cjs.map +0 -1
  605. package/dist/cjs/content/mcpAutoCache.cjs +0 -115
  606. package/dist/cjs/content/mcpAutoCache.cjs.map +0 -1
  607. package/dist/cjs/graphs/HandoffRegistry.cjs +0 -143
  608. package/dist/cjs/graphs/HandoffRegistry.cjs.map +0 -1
  609. package/dist/cjs/providers/a2a/A2ACapabilityProvider.cjs +0 -288
  610. package/dist/cjs/providers/a2a/A2ACapabilityProvider.cjs.map +0 -1
  611. package/dist/cjs/providers/a2a/client.cjs +0 -92
  612. package/dist/cjs/providers/a2a/client.cjs.map +0 -1
  613. package/dist/cjs/providers/a2a/config.cjs +0 -38
  614. package/dist/cjs/providers/a2a/config.cjs.map +0 -1
  615. package/dist/cjs/providers/capabilityNaming.cjs +0 -43
  616. package/dist/cjs/providers/capabilityNaming.cjs.map +0 -1
  617. package/dist/cjs/providers/mcp/MCPCapabilityProvider.cjs +0 -244
  618. package/dist/cjs/providers/mcp/MCPCapabilityProvider.cjs.map +0 -1
  619. package/dist/cjs/providers/mcp/config.cjs +0 -42
  620. package/dist/cjs/providers/mcp/config.cjs.map +0 -1
  621. package/dist/cjs/providers/mcp/transport.cjs +0 -65
  622. package/dist/cjs/providers/mcp/transport.cjs.map +0 -1
  623. package/dist/cjs/providers/tools-server/ToolsServerCapabilityProvider.cjs +0 -128
  624. package/dist/cjs/providers/tools-server/ToolsServerCapabilityProvider.cjs.map +0 -1
  625. package/dist/cjs/providers/types.cjs +0 -51
  626. package/dist/cjs/providers/types.cjs.map +0 -1
  627. package/dist/cjs/tools/artifacts/schema.cjs +0 -86
  628. package/dist/cjs/tools/artifacts/schema.cjs.map +0 -1
  629. package/dist/cjs/tools/artifacts/tool.cjs +0 -219
  630. package/dist/cjs/tools/artifacts/tool.cjs.map +0 -1
  631. package/dist/cjs/tools/fileSearch/formatter.cjs +0 -93
  632. package/dist/cjs/tools/fileSearch/formatter.cjs.map +0 -1
  633. package/dist/cjs/tools/fileSearch/ragClient.cjs +0 -102
  634. package/dist/cjs/tools/fileSearch/ragClient.cjs.map +0 -1
  635. package/dist/cjs/tools/fileSearch/schema.cjs +0 -18
  636. package/dist/cjs/tools/fileSearch/schema.cjs.map +0 -1
  637. package/dist/cjs/tools/fileSearch/tool.cjs +0 -155
  638. package/dist/cjs/tools/fileSearch/tool.cjs.map +0 -1
  639. package/dist/cjs/tools/proxyTool.cjs +0 -102
  640. package/dist/cjs/tools/proxyTool.cjs.map +0 -1
  641. package/dist/cjs/utils/childAgentContext.cjs +0 -242
  642. package/dist/cjs/utils/childAgentContext.cjs.map +0 -1
  643. package/dist/cjs/utils/credentials.cjs +0 -142
  644. package/dist/cjs/utils/credentials.cjs.map +0 -1
  645. package/dist/cjs/utils/httpClient.cjs +0 -74
  646. package/dist/cjs/utils/httpClient.cjs.map +0 -1
  647. package/dist/cjs/utils/toolManifest.cjs +0 -100
  648. package/dist/cjs/utils/toolManifest.cjs.map +0 -1
  649. package/dist/esm/common/spawnPath.mjs +0 -95
  650. package/dist/esm/common/spawnPath.mjs.map +0 -1
  651. package/dist/esm/content/ArtifactStore.mjs +0 -576
  652. package/dist/esm/content/ArtifactStore.mjs.map +0 -1
  653. package/dist/esm/content/ContentStore.mjs +0 -635
  654. package/dist/esm/content/ContentStore.mjs.map +0 -1
  655. package/dist/esm/content/contentAnalyzer.mjs +0 -87
  656. package/dist/esm/content/contentAnalyzer.mjs.map +0 -1
  657. package/dist/esm/content/index.mjs +0 -5
  658. package/dist/esm/content/mcpAutoCache.mjs +0 -111
  659. package/dist/esm/content/mcpAutoCache.mjs.map +0 -1
  660. package/dist/esm/graphs/HandoffRegistry.mjs +0 -141
  661. package/dist/esm/graphs/HandoffRegistry.mjs.map +0 -1
  662. package/dist/esm/providers/a2a/A2ACapabilityProvider.mjs +0 -281
  663. package/dist/esm/providers/a2a/A2ACapabilityProvider.mjs.map +0 -1
  664. package/dist/esm/providers/a2a/client.mjs +0 -88
  665. package/dist/esm/providers/a2a/client.mjs.map +0 -1
  666. package/dist/esm/providers/a2a/config.mjs +0 -35
  667. package/dist/esm/providers/a2a/config.mjs.map +0 -1
  668. package/dist/esm/providers/capabilityNaming.mjs +0 -39
  669. package/dist/esm/providers/capabilityNaming.mjs.map +0 -1
  670. package/dist/esm/providers/mcp/MCPCapabilityProvider.mjs +0 -240
  671. package/dist/esm/providers/mcp/MCPCapabilityProvider.mjs.map +0 -1
  672. package/dist/esm/providers/mcp/config.mjs +0 -39
  673. package/dist/esm/providers/mcp/config.mjs.map +0 -1
  674. package/dist/esm/providers/mcp/transport.mjs +0 -63
  675. package/dist/esm/providers/mcp/transport.mjs.map +0 -1
  676. package/dist/esm/providers/tools-server/ToolsServerCapabilityProvider.mjs +0 -126
  677. package/dist/esm/providers/tools-server/ToolsServerCapabilityProvider.mjs.map +0 -1
  678. package/dist/esm/providers/types.mjs +0 -51
  679. package/dist/esm/providers/types.mjs.map +0 -1
  680. package/dist/esm/tools/artifacts/schema.mjs +0 -79
  681. package/dist/esm/tools/artifacts/schema.mjs.map +0 -1
  682. package/dist/esm/tools/artifacts/tool.mjs +0 -213
  683. package/dist/esm/tools/artifacts/tool.mjs.map +0 -1
  684. package/dist/esm/tools/fileSearch/formatter.mjs +0 -90
  685. package/dist/esm/tools/fileSearch/formatter.mjs.map +0 -1
  686. package/dist/esm/tools/fileSearch/ragClient.mjs +0 -98
  687. package/dist/esm/tools/fileSearch/ragClient.mjs.map +0 -1
  688. package/dist/esm/tools/fileSearch/schema.mjs +0 -15
  689. package/dist/esm/tools/fileSearch/schema.mjs.map +0 -1
  690. package/dist/esm/tools/fileSearch/tool.mjs +0 -152
  691. package/dist/esm/tools/fileSearch/tool.mjs.map +0 -1
  692. package/dist/esm/tools/proxyTool.mjs +0 -100
  693. package/dist/esm/tools/proxyTool.mjs.map +0 -1
  694. package/dist/esm/utils/childAgentContext.mjs +0 -237
  695. package/dist/esm/utils/childAgentContext.mjs.map +0 -1
  696. package/dist/esm/utils/credentials.mjs +0 -135
  697. package/dist/esm/utils/credentials.mjs.map +0 -1
  698. package/dist/esm/utils/httpClient.mjs +0 -70
  699. package/dist/esm/utils/httpClient.mjs.map +0 -1
  700. package/dist/esm/utils/toolManifest.mjs +0 -96
  701. package/dist/esm/utils/toolManifest.mjs.map +0 -1
  702. package/dist/types/common/spawnPath.d.ts +0 -59
  703. package/dist/types/content/ArtifactStore.d.ts +0 -223
  704. package/dist/types/content/ContentStore.d.ts +0 -140
  705. package/dist/types/content/contentAnalyzer.d.ts +0 -38
  706. package/dist/types/content/index.d.ts +0 -24
  707. package/dist/types/content/mcpAutoCache.d.ts +0 -89
  708. package/dist/types/content/types.d.ts +0 -75
  709. package/dist/types/graphs/HandoffRegistry.d.ts +0 -97
  710. package/dist/types/providers/a2a/A2ACapabilityProvider.d.ts +0 -89
  711. package/dist/types/providers/a2a/client.d.ts +0 -47
  712. package/dist/types/providers/a2a/config.d.ts +0 -18
  713. package/dist/types/providers/a2a/index.d.ts +0 -6
  714. package/dist/types/providers/a2a/types.d.ts +0 -173
  715. package/dist/types/providers/capabilityNaming.d.ts +0 -25
  716. package/dist/types/providers/index.d.ts +0 -12
  717. package/dist/types/providers/mcp/MCPCapabilityProvider.d.ts +0 -54
  718. package/dist/types/providers/mcp/config.d.ts +0 -20
  719. package/dist/types/providers/mcp/index.d.ts +0 -5
  720. package/dist/types/providers/mcp/transport.d.ts +0 -18
  721. package/dist/types/providers/mcp/types.d.ts +0 -112
  722. package/dist/types/providers/tools-server/ToolsServerCapabilityProvider.d.ts +0 -59
  723. package/dist/types/providers/tools-server/index.d.ts +0 -1
  724. package/dist/types/providers/types.d.ts +0 -184
  725. package/dist/types/tools/artifacts/index.d.ts +0 -3
  726. package/dist/types/tools/artifacts/schema.d.ts +0 -63
  727. package/dist/types/tools/artifacts/tool.d.ts +0 -16
  728. package/dist/types/tools/artifacts/types.d.ts +0 -127
  729. package/dist/types/tools/fileSearch/formatter.d.ts +0 -25
  730. package/dist/types/tools/fileSearch/index.d.ts +0 -5
  731. package/dist/types/tools/fileSearch/ragClient.d.ts +0 -32
  732. package/dist/types/tools/fileSearch/schema.d.ts +0 -13
  733. package/dist/types/tools/fileSearch/tool.d.ts +0 -18
  734. package/dist/types/tools/fileSearch/types.d.ts +0 -139
  735. package/dist/types/tools/proxyTool.d.ts +0 -62
  736. package/dist/types/utils/childAgentContext.d.ts +0 -99
  737. package/dist/types/utils/credentials.d.ts +0 -77
  738. package/dist/types/utils/httpClient.d.ts +0 -46
  739. package/dist/types/utils/toolManifest.d.ts +0 -49
  740. package/src/common/__tests__/spawnPath.test.ts +0 -110
  741. package/src/common/spawnPath.ts +0 -101
  742. package/src/content/ArtifactStore.ts +0 -782
  743. package/src/content/ContentStore.ts +0 -753
  744. package/src/content/contentAnalyzer.ts +0 -105
  745. package/src/content/index.ts +0 -51
  746. package/src/content/mcpAutoCache.ts +0 -185
  747. package/src/content/types.ts +0 -82
  748. package/src/graphs/HandoffRegistry.ts +0 -199
  749. package/src/graphs/__tests__/HandoffRegistry.test.ts +0 -410
  750. package/src/graphs/__tests__/multi-agent-delegate.test.ts +0 -458
  751. package/src/graphs/__tests__/multi-agent-edges.test.ts +0 -276
  752. package/src/graphs/__tests__/multi-agent-nested-subgraph.test.ts +0 -221
  753. package/src/graphs/handoffValidation.test.ts +0 -353
  754. package/src/providers/__tests__/ToolsServerCapabilityProvider.integration.spec.ts +0 -79
  755. package/src/providers/__tests__/ToolsServerCapabilityProvider.test.ts +0 -271
  756. package/src/providers/__tests__/types.test.ts +0 -64
  757. package/src/providers/a2a/A2ACapabilityProvider.ts +0 -384
  758. package/src/providers/a2a/__tests__/A2ACapabilityProvider.integration.spec.ts +0 -345
  759. package/src/providers/a2a/__tests__/A2ACapabilityProvider.test.ts +0 -460
  760. package/src/providers/a2a/client.ts +0 -115
  761. package/src/providers/a2a/config.ts +0 -40
  762. package/src/providers/a2a/index.ts +0 -29
  763. package/src/providers/a2a/types.ts +0 -191
  764. package/src/providers/capabilityNaming.ts +0 -42
  765. package/src/providers/index.ts +0 -68
  766. package/src/providers/mcp/MCPCapabilityProvider.ts +0 -345
  767. package/src/providers/mcp/__tests__/MCPCapabilityProvider.integration.spec.ts +0 -386
  768. package/src/providers/mcp/__tests__/MCPCapabilityProvider.test.ts +0 -371
  769. package/src/providers/mcp/config.ts +0 -45
  770. package/src/providers/mcp/index.ts +0 -21
  771. package/src/providers/mcp/transport.ts +0 -76
  772. package/src/providers/mcp/types.ts +0 -139
  773. package/src/providers/tools-server/ToolsServerCapabilityProvider.ts +0 -249
  774. package/src/providers/tools-server/index.ts +0 -1
  775. package/src/providers/types.ts +0 -204
  776. package/src/scripts/test-bedrock-handoff-autonomous.ts +0 -267
  777. package/src/scripts/test-handoff-preamble.ts +0 -278
  778. package/src/specs/agent-handoffs-bedrock.integration.test.ts +0 -415
  779. package/src/tools/artifacts/__tests__/tool.test.ts +0 -259
  780. package/src/tools/artifacts/index.ts +0 -33
  781. package/src/tools/artifacts/schema.ts +0 -99
  782. package/src/tools/artifacts/tool.ts +0 -289
  783. package/src/tools/artifacts/types.ts +0 -162
  784. package/src/tools/fileSearch/__tests__/tool.test.ts +0 -261
  785. package/src/tools/fileSearch/formatter.ts +0 -129
  786. package/src/tools/fileSearch/index.ts +0 -23
  787. package/src/tools/fileSearch/ragClient.ts +0 -137
  788. package/src/tools/fileSearch/schema.ts +0 -19
  789. package/src/tools/fileSearch/tool.ts +0 -207
  790. package/src/tools/fileSearch/types.ts +0 -149
  791. package/src/tools/proxyTool.ts +0 -166
  792. package/src/utils/__tests__/childAgentContext.test.ts +0 -217
  793. package/src/utils/__tests__/credentials.test.ts +0 -130
  794. package/src/utils/__tests__/httpClient.test.ts +0 -75
  795. package/src/utils/__tests__/toolManifest.test.ts +0 -116
  796. package/src/utils/childAgentContext.ts +0 -259
  797. package/src/utils/credentials.ts +0 -157
  798. package/src/utils/httpClient.ts +0 -92
  799. package/src/utils/toolManifest.ts +0 -109
  800. /package/dist/esm/{content → langchain}/index.mjs.map +0 -0
@@ -0,0 +1,288 @@
1
+ import { config } from 'dotenv';
2
+ import { getEnvironmentVariable } from '@langchain/core/utils/env';
3
+ import { tool } from '@langchain/core/tools';
4
+ import { fetchSessionFiles, makeRequest, executeTools, formatCompletedResponse } from './ProgrammaticToolCalling.mjs';
5
+ import { getCodeBaseURL } from './CodeExecutor.mjs';
6
+ import { Constants, EnvVar } from '../common/enum.mjs';
7
+ import './approval/constants.mjs';
8
+
9
+ config();
10
+ // ============================================================================
11
+ // Constants
12
+ // ============================================================================
13
+ const DEFAULT_MAX_ROUND_TRIPS = 20;
14
+ const DEFAULT_TIMEOUT = 60000;
15
+ /** Bash reserved words that get `_tool` suffix when used as function names */
16
+ const BASH_RESERVED = new Set([
17
+ 'if',
18
+ 'then',
19
+ 'else',
20
+ 'elif',
21
+ 'fi',
22
+ 'case',
23
+ 'esac',
24
+ 'for',
25
+ 'while',
26
+ 'until',
27
+ 'do',
28
+ 'done',
29
+ 'in',
30
+ 'function',
31
+ 'select',
32
+ 'time',
33
+ 'coproc',
34
+ 'declare',
35
+ 'typeset',
36
+ 'local',
37
+ 'readonly',
38
+ 'export',
39
+ 'unset',
40
+ ]);
41
+ // ============================================================================
42
+ // Description Components
43
+ // ============================================================================
44
+ const STATELESS_WARNING = `CRITICAL - STATELESS EXECUTION:
45
+ Each call is a fresh bash shell. Variables and state do NOT persist between calls.
46
+ You MUST complete your entire workflow in ONE code block.
47
+ DO NOT split work across multiple calls expecting to reuse variables.`;
48
+ const CORE_RULES = `Rules:
49
+ - EVERYTHING in one call—no state persists between executions
50
+ - Tools are pre-defined as bash functions—DO NOT redefine them
51
+ - Each tool function accepts a JSON string argument
52
+ - Only echo/printf output returns to the model
53
+ - Generated files are automatically available in /mnt/data/ for subsequent executions`;
54
+ const ADDITIONAL_RULES = '- Tool names normalized: hyphens→underscores, reserved words get `_tool` suffix';
55
+ const EXAMPLES = `Example (Complete workflow in one call):
56
+ # Query data and process
57
+ data=$(query_database '{"sql": "SELECT * FROM users"}')
58
+ echo "$data" | jq '.[] | .name'
59
+
60
+ Example (Parallel calls):
61
+ web_search '{"query": "SF weather"}' > /tmp/sf.txt &
62
+ web_search '{"query": "NY weather"}' > /tmp/ny.txt &
63
+ wait
64
+ echo "SF: $(cat /tmp/sf.txt)"
65
+ echo "NY: $(cat /tmp/ny.txt)"`;
66
+ const CODE_PARAM_DESCRIPTION = `Bash code that calls tools programmatically. Tools are available as bash functions.
67
+
68
+ ${STATELESS_WARNING}
69
+
70
+ Each tool function accepts a JSON string as its argument.
71
+ Example: tool_name '{"key": "value"}'
72
+
73
+ ${EXAMPLES}
74
+
75
+ ${CORE_RULES}`;
76
+ // ============================================================================
77
+ // Schema
78
+ // ============================================================================
79
+ const BashProgrammaticToolCallingSchema = {
80
+ type: 'object',
81
+ properties: {
82
+ code: {
83
+ type: 'string',
84
+ minLength: 1,
85
+ description: CODE_PARAM_DESCRIPTION,
86
+ },
87
+ timeout: {
88
+ type: 'integer',
89
+ minimum: 1000,
90
+ maximum: 300000,
91
+ default: DEFAULT_TIMEOUT,
92
+ description: 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.',
93
+ },
94
+ },
95
+ required: ['code'],
96
+ };
97
+ const BashProgrammaticToolCallingName = Constants.BASH_PROGRAMMATIC_TOOL_CALLING;
98
+ const BashProgrammaticToolCallingDescription = `
99
+ Run tools via bash code. Tools are available as bash functions that accept JSON string arguments.
100
+
101
+ ${STATELESS_WARNING}
102
+
103
+ ${CORE_RULES}
104
+ ${ADDITIONAL_RULES}
105
+
106
+ When to use: shell pipelines, parallel execution (& and wait), file processing, text manipulation.
107
+
108
+ ${EXAMPLES}
109
+ `.trim();
110
+ const BashProgrammaticToolCallingDefinition = {
111
+ name: BashProgrammaticToolCallingName,
112
+ description: BashProgrammaticToolCallingDescription,
113
+ schema: BashProgrammaticToolCallingSchema,
114
+ };
115
+ // ============================================================================
116
+ // Helper Functions
117
+ // ============================================================================
118
+ /**
119
+ * Normalizes a tool name to a valid bash function identifier.
120
+ * 1. Replace hyphens, spaces, dots with underscores
121
+ * 2. Remove any other invalid characters
122
+ * 3. Prefix with underscore if starts with number
123
+ * 4. Append `_tool` if it's a bash reserved word
124
+ */
125
+ function normalizeToBashIdentifier(name) {
126
+ let normalized = name.replace(/[-\s.]/g, '_');
127
+ normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');
128
+ if (/^[0-9]/.test(normalized)) {
129
+ normalized = '_' + normalized;
130
+ }
131
+ if (BASH_RESERVED.has(normalized)) {
132
+ normalized = normalized + '_tool';
133
+ }
134
+ return normalized;
135
+ }
136
+ /**
137
+ * Extracts tool names that are actually called in the bash code.
138
+ * Bash functions are invoked as commands (no parentheses), so we match
139
+ * the normalized name as a word boundary.
140
+ */
141
+ function extractUsedBashToolNames(code, toolNameMap) {
142
+ const usedTools = new Set();
143
+ for (const [bashName, originalName] of toolNameMap) {
144
+ const escapedName = bashName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
145
+ const pattern = new RegExp(`\\b${escapedName}\\b`, 'g');
146
+ if (pattern.test(code)) {
147
+ usedTools.add(originalName);
148
+ }
149
+ }
150
+ return usedTools;
151
+ }
152
+ /**
153
+ * Filters tool definitions to only include tools actually used in the bash code.
154
+ */
155
+ function filterBashToolsByUsage(toolDefs, code, debug = false) {
156
+ const toolNameMap = new Map();
157
+ for (const def of toolDefs) {
158
+ const bashName = normalizeToBashIdentifier(def.name);
159
+ toolNameMap.set(bashName, def.name);
160
+ }
161
+ const usedToolNames = extractUsedBashToolNames(code, toolNameMap);
162
+ if (debug) {
163
+ // eslint-disable-next-line no-console
164
+ console.log(`[BashPTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`);
165
+ if (usedToolNames.size > 0) {
166
+ // eslint-disable-next-line no-console
167
+ console.log(`[BashPTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`);
168
+ }
169
+ }
170
+ if (usedToolNames.size === 0) {
171
+ if (debug) {
172
+ // eslint-disable-next-line no-console
173
+ console.log('[BashPTC Debug] No tools detected in code - sending all tools as fallback');
174
+ }
175
+ return toolDefs;
176
+ }
177
+ return toolDefs.filter((def) => usedToolNames.has(def.name));
178
+ }
179
+ // ============================================================================
180
+ // Tool Factory
181
+ // ============================================================================
182
+ /**
183
+ * Creates a Bash Programmatic Tool Calling tool for multi-tool orchestration.
184
+ *
185
+ * This tool enables AI agents to write bash scripts that orchestrate multiple
186
+ * tool calls programmatically via the remote Code API, reducing LLM round-trips.
187
+ *
188
+ * The tool map must be provided at runtime via config.toolCall (injected by ToolNode).
189
+ */
190
+ function createBashProgrammaticToolCallingTool(initParams = {}) {
191
+ const apiKey = initParams[EnvVar.CODE_API_KEY] ??
192
+ initParams.apiKey ??
193
+ getEnvironmentVariable(EnvVar.CODE_API_KEY) ??
194
+ '';
195
+ if (!apiKey) {
196
+ throw new Error('No API key provided for bash programmatic tool calling. ' +
197
+ 'Set CODE_API_KEY environment variable or pass apiKey in initParams.');
198
+ }
199
+ const baseUrl = initParams.baseUrl ?? getCodeBaseURL();
200
+ const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;
201
+ const proxy = initParams.proxy ?? process.env.PROXY;
202
+ const debug = initParams.debug ?? process.env.BASH_PTC_DEBUG === 'true';
203
+ const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;
204
+ return tool(async (rawParams, config) => {
205
+ const params = rawParams;
206
+ const { code, timeout = DEFAULT_TIMEOUT } = params;
207
+ const { toolMap, toolDefs, session_id, _injected_files } = (config.toolCall ?? {});
208
+ if (toolMap == null || toolMap.size === 0) {
209
+ throw new Error('No toolMap provided. ' +
210
+ 'ToolNode should inject this from AgentContext when invoked through the graph.');
211
+ }
212
+ if (toolDefs == null || toolDefs.length === 0) {
213
+ throw new Error('No tool definitions provided. ' +
214
+ 'Either pass tools in the input or ensure ToolNode injects toolDefs.');
215
+ }
216
+ let roundTrip = 0;
217
+ try {
218
+ // ====================================================================
219
+ // Phase 1: Filter tools and make initial request
220
+ // ====================================================================
221
+ const effectiveTools = filterBashToolsByUsage(toolDefs, code, debug);
222
+ if (debug) {
223
+ // eslint-disable-next-line no-console
224
+ console.log(`[BashPTC Debug] Sending ${effectiveTools.length} tools to API ` +
225
+ `(filtered from ${toolDefs.length})`);
226
+ }
227
+ let files;
228
+ if (_injected_files && _injected_files.length > 0) {
229
+ files = _injected_files;
230
+ }
231
+ else if (session_id != null && session_id.length > 0) {
232
+ files = await fetchSessionFiles(baseUrl, apiKey, session_id, proxy);
233
+ }
234
+ let response = await makeRequest(EXEC_ENDPOINT, apiKey, {
235
+ lang: 'bash',
236
+ code,
237
+ tools: effectiveTools,
238
+ session_id,
239
+ timeout,
240
+ ...(files && files.length > 0 ? { files } : {}),
241
+ }, proxy);
242
+ // ====================================================================
243
+ // Phase 2: Handle response loop
244
+ // ====================================================================
245
+ while (response.status === 'tool_call_required') {
246
+ roundTrip++;
247
+ if (roundTrip > maxRoundTrips) {
248
+ throw new Error(`Exceeded maximum round trips (${maxRoundTrips}). ` +
249
+ 'This may indicate an infinite loop, excessive tool calls, ' +
250
+ 'or a logic error in your code.');
251
+ }
252
+ if (debug) {
253
+ // eslint-disable-next-line no-console
254
+ console.log(`[BashPTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`);
255
+ }
256
+ const toolResults = await executeTools(response.tool_calls ?? [], toolMap);
257
+ response = await makeRequest(EXEC_ENDPOINT, apiKey, {
258
+ continuation_token: response.continuation_token,
259
+ tool_results: toolResults,
260
+ }, proxy);
261
+ }
262
+ // ====================================================================
263
+ // Phase 3: Handle final state
264
+ // ====================================================================
265
+ if (response.status === 'completed') {
266
+ return formatCompletedResponse(response);
267
+ }
268
+ if (response.status === 'error') {
269
+ throw new Error(`Execution error: ${response.error}` +
270
+ (response.stderr != null && response.stderr !== ''
271
+ ? `\n\nStderr:\n${response.stderr}`
272
+ : ''));
273
+ }
274
+ throw new Error(`Unexpected response status: ${response.status}`);
275
+ }
276
+ catch (error) {
277
+ throw new Error(`Bash programmatic execution failed: ${error.message}`);
278
+ }
279
+ }, {
280
+ name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,
281
+ description: BashProgrammaticToolCallingDescription,
282
+ schema: BashProgrammaticToolCallingSchema,
283
+ responseFormat: Constants.CONTENT_AND_ARTIFACT,
284
+ });
285
+ }
286
+
287
+ export { BashProgrammaticToolCallingDefinition, BashProgrammaticToolCallingDescription, BashProgrammaticToolCallingName, BashProgrammaticToolCallingSchema, createBashProgrammaticToolCallingTool, extractUsedBashToolNames, filterBashToolsByUsage, normalizeToBashIdentifier };
288
+ //# sourceMappingURL=BashProgrammaticToolCalling.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BashProgrammaticToolCalling.mjs","sources":["../../../src/tools/BashProgrammaticToolCalling.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport {\n makeRequest,\n executeTools,\n fetchSessionFiles,\n formatCompletedResponse,\n} from './ProgrammaticToolCalling';\nimport { getCodeBaseURL } from './CodeExecutor';\nimport { Constants, EnvVar } from '@/common';\n\nconfig();\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\nconst DEFAULT_TIMEOUT = 60000;\n\n/** Bash reserved words that get `_tool` suffix when used as function names */\nconst BASH_RESERVED = new Set([\n 'if',\n 'then',\n 'else',\n 'elif',\n 'fi',\n 'case',\n 'esac',\n 'for',\n 'while',\n 'until',\n 'do',\n 'done',\n 'in',\n 'function',\n 'select',\n 'time',\n 'coproc',\n 'declare',\n 'typeset',\n 'local',\n 'readonly',\n 'export',\n 'unset',\n]);\n\n// ============================================================================\n// Description Components\n// ============================================================================\n\nconst STATELESS_WARNING = `CRITICAL - STATELESS EXECUTION:\nEach call is a fresh bash shell. Variables and state do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block.\nDO NOT split work across multiple calls expecting to reuse variables.`;\n\nconst CORE_RULES = `Rules:\n- EVERYTHING in one call—no state persists between executions\n- Tools are pre-defined as bash functions—DO NOT redefine them\n- Each tool function accepts a JSON string argument\n- Only echo/printf output returns to the model\n- Generated files are automatically available in /mnt/data/ for subsequent executions`;\n\nconst ADDITIONAL_RULES =\n '- Tool names normalized: hyphens→underscores, reserved words get `_tool` suffix';\n\nconst EXAMPLES = `Example (Complete workflow in one call):\n # Query data and process\n data=$(query_database '{\"sql\": \"SELECT * FROM users\"}')\n echo \"$data\" | jq '.[] | .name'\n\nExample (Parallel calls):\n web_search '{\"query\": \"SF weather\"}' > /tmp/sf.txt &\n web_search '{\"query\": \"NY weather\"}' > /tmp/ny.txt &\n wait\n echo \"SF: $(cat /tmp/sf.txt)\"\n echo \"NY: $(cat /tmp/ny.txt)\"`;\n\nconst CODE_PARAM_DESCRIPTION = `Bash code that calls tools programmatically. Tools are available as bash functions.\n\n${STATELESS_WARNING}\n\nEach tool function accepts a JSON string as its argument.\nExample: tool_name '{\"key\": \"value\"}'\n\n${EXAMPLES}\n\n${CORE_RULES}`;\n\n// ============================================================================\n// Schema\n// ============================================================================\n\nexport const BashProgrammaticToolCallingSchema = {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n minLength: 1,\n description: CODE_PARAM_DESCRIPTION,\n },\n timeout: {\n type: 'integer',\n minimum: 1000,\n maximum: 300000,\n default: DEFAULT_TIMEOUT,\n description:\n 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.',\n },\n },\n required: ['code'],\n} as const;\n\nexport const BashProgrammaticToolCallingName =\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING;\n\nexport const BashProgrammaticToolCallingDescription = `\nRun tools via bash code. Tools are available as bash functions that accept JSON string arguments.\n\n${STATELESS_WARNING}\n\n${CORE_RULES}\n${ADDITIONAL_RULES}\n\nWhen to use: shell pipelines, parallel execution (& and wait), file processing, text manipulation.\n\n${EXAMPLES}\n`.trim();\n\nexport const BashProgrammaticToolCallingDefinition = {\n name: BashProgrammaticToolCallingName,\n description: BashProgrammaticToolCallingDescription,\n schema: BashProgrammaticToolCallingSchema,\n} as const;\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Normalizes a tool name to a valid bash function identifier.\n * 1. Replace hyphens, spaces, dots with underscores\n * 2. Remove any other invalid characters\n * 3. Prefix with underscore if starts with number\n * 4. Append `_tool` if it's a bash reserved word\n */\nexport function normalizeToBashIdentifier(name: string): string {\n let normalized = name.replace(/[-\\s.]/g, '_');\n normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');\n\n if (/^[0-9]/.test(normalized)) {\n normalized = '_' + normalized;\n }\n\n if (BASH_RESERVED.has(normalized)) {\n normalized = normalized + '_tool';\n }\n\n return normalized;\n}\n\n/**\n * Extracts tool names that are actually called in the bash code.\n * Bash functions are invoked as commands (no parentheses), so we match\n * the normalized name as a word boundary.\n */\nexport function extractUsedBashToolNames(\n code: string,\n toolNameMap: Map<string, string>\n): Set<string> {\n const usedTools = new Set<string>();\n\n for (const [bashName, originalName] of toolNameMap) {\n const escapedName = bashName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const pattern = new RegExp(`\\\\b${escapedName}\\\\b`, 'g');\n\n if (pattern.test(code)) {\n usedTools.add(originalName);\n }\n }\n\n return usedTools;\n}\n\n/**\n * Filters tool definitions to only include tools actually used in the bash code.\n */\nexport function filterBashToolsByUsage(\n toolDefs: t.LCTool[],\n code: string,\n debug = false\n): t.LCTool[] {\n const toolNameMap = new Map<string, string>();\n for (const def of toolDefs) {\n const bashName = normalizeToBashIdentifier(def.name);\n toolNameMap.set(bashName, def.name);\n }\n\n const usedToolNames = extractUsedBashToolNames(code, toolNameMap);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`\n );\n if (usedToolNames.size > 0) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`\n );\n }\n }\n\n if (usedToolNames.size === 0) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[BashPTC Debug] No tools detected in code - sending all tools as fallback'\n );\n }\n return toolDefs;\n }\n\n return toolDefs.filter((def) => usedToolNames.has(def.name));\n}\n\n// ============================================================================\n// Tool Factory\n// ============================================================================\n\n/**\n * Creates a Bash Programmatic Tool Calling tool for multi-tool orchestration.\n *\n * This tool enables AI agents to write bash scripts that orchestrate multiple\n * tool calls programmatically via the remote Code API, reducing LLM round-trips.\n *\n * The tool map must be provided at runtime via config.toolCall (injected by ToolNode).\n */\nexport function createBashProgrammaticToolCallingTool(\n initParams: t.BashProgrammaticToolCallingParams = {}\n): DynamicStructuredTool {\n const apiKey =\n (initParams[EnvVar.CODE_API_KEY] as string | undefined) ??\n initParams.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n\n if (!apiKey) {\n throw new Error(\n 'No API key provided for bash programmatic tool calling. ' +\n 'Set CODE_API_KEY environment variable or pass apiKey in initParams.'\n );\n }\n\n const baseUrl = initParams.baseUrl ?? getCodeBaseURL();\n const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;\n const proxy = initParams.proxy ?? process.env.PROXY;\n const debug = initParams.debug ?? process.env.BASH_PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n return tool(\n async (rawParams, config) => {\n const params = rawParams as { code: string; timeout?: number };\n const { code, timeout = DEFAULT_TIMEOUT } = params;\n\n const { toolMap, toolDefs, session_id, _injected_files } =\n (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache> & {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error(\n 'No toolMap provided. ' +\n 'ToolNode should inject this from AgentContext when invoked through the graph.'\n );\n }\n\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided. ' +\n 'Either pass tools in the input or ensure ToolNode injects toolDefs.'\n );\n }\n\n let roundTrip = 0;\n\n try {\n // ====================================================================\n // Phase 1: Filter tools and make initial request\n // ====================================================================\n\n const effectiveTools = filterBashToolsByUsage(toolDefs, code, debug);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Sending ${effectiveTools.length} tools to API ` +\n `(filtered from ${toolDefs.length})`\n );\n }\n\n let files: t.CodeEnvFile[] | undefined;\n if (_injected_files && _injected_files.length > 0) {\n files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n files = await fetchSessionFiles(baseUrl, apiKey, session_id, proxy);\n }\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n apiKey,\n {\n lang: 'bash',\n code,\n tools: effectiveTools,\n session_id,\n timeout,\n ...(files && files.length > 0 ? { files } : {}),\n },\n proxy\n );\n\n // ====================================================================\n // Phase 2: Handle response loop\n // ====================================================================\n\n while (response.status === 'tool_call_required') {\n roundTrip++;\n\n if (roundTrip > maxRoundTrips) {\n throw new Error(\n `Exceeded maximum round trips (${maxRoundTrips}). ` +\n 'This may indicate an infinite loop, excessive tool calls, ' +\n 'or a logic error in your code.'\n );\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`\n );\n }\n\n const toolResults = await executeTools(\n response.tool_calls ?? [],\n toolMap\n );\n\n response = await makeRequest(\n EXEC_ENDPOINT,\n apiKey,\n {\n continuation_token: response.continuation_token,\n tool_results: toolResults,\n },\n proxy\n );\n }\n\n // ====================================================================\n // Phase 3: Handle final state\n // ====================================================================\n\n if (response.status === 'completed') {\n return formatCompletedResponse(response);\n }\n\n if (response.status === 'error') {\n throw new Error(\n `Execution error: ${response.error}` +\n (response.stderr != null && response.stderr !== ''\n ? `\\n\\nStderr:\\n${response.stderr}`\n : '')\n );\n }\n\n throw new Error(`Unexpected response status: ${response.status}`);\n } catch (error) {\n throw new Error(\n `Bash programmatic execution failed: ${(error as Error).message}`\n );\n }\n },\n {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n description: BashProgrammaticToolCallingDescription,\n schema: BashProgrammaticToolCallingSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"names":[],"mappings":";;;;;;;;AAcA,MAAM,EAAE;AAER;AACA;AACA;AAEA,MAAM,uBAAuB,GAAG,EAAE;AAClC,MAAM,eAAe,GAAG,KAAK;AAE7B;AACA,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC;IAC5B,IAAI;IACJ,MAAM;IACN,MAAM;IACN,MAAM;IACN,IAAI;IACJ,MAAM;IACN,MAAM;IACN,KAAK;IACL,OAAO;IACP,OAAO;IACP,IAAI;IACJ,MAAM;IACN,IAAI;IACJ,UAAU;IACV,QAAQ;IACR,MAAM;IACN,QAAQ;IACR,SAAS;IACT,SAAS;IACT,OAAO;IACP,UAAU;IACV,QAAQ;IACR,OAAO;AACR,CAAA,CAAC;AAEF;AACA;AACA;AAEA,MAAM,iBAAiB,GAAG,CAAA;;;sEAG4C;AAEtE,MAAM,UAAU,GAAG,CAAA;;;;;sFAKmE;AAEtF,MAAM,gBAAgB,GACpB,iFAAiF;AAEnF,MAAM,QAAQ,GAAG,CAAA;;;;;;;;;;gCAUe;AAEhC,MAAM,sBAAsB,GAAG,CAAA;;EAE7B,iBAAiB;;;;;EAKjB,QAAQ;;AAER,EAAA,UAAU,EAAE;AAEd;AACA;AACA;AAEO,MAAM,iCAAiC,GAAG;AAC/C,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,SAAS,EAAE,CAAC;AACZ,YAAA,WAAW,EAAE,sBAAsB;AACpC,SAAA;AACD,QAAA,OAAO,EAAE;AACP,YAAA,IAAI,EAAE,SAAS;AACf,YAAA,OAAO,EAAE,IAAI;AACb,YAAA,OAAO,EAAE,MAAM;AACf,YAAA,OAAO,EAAE,eAAe;AACxB,YAAA,WAAW,EACT,8EAA8E;AACjF,S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BAAA,CAAqB,CAClG;gBACH;AAEA,gBAAA,MAAM,WAAW,GAAG,MAAM,YAAY,CACpC,QAAQ,CAAC,UAAU,IAAI,EAAE,EACzB,OAAO,CACR;AAED,gBAAA,QAAQ,GAAG,MAAM,WAAW,CAC1B,aAAa,EACb,MAAM,EACN;oBACE,kBAAkB,EAAE,QAAQ,CAAC,kBAAkB;AAC/C,oBAAA,YAAY,EAAE,WAAW;iBAC1B,EACD,KAAK,CACN;YACH;;;;AAMA,YAAA,IAAI,QAAQ,CAAC,MAAM,KAAK,WAAW,EAAE;AACnC,gBAAA,OAAO,uBAAuB,CAAC,QAAQ,CAAC;YAC1C;AAEA,YAAA,IAAI,QAAQ,CAAC,MAAM,KAAK,OAAO,EAAE;AAC/B,gBAAA,MAAM,IAAI,KAAK,CACb,oBAAoB,QAAQ,CAAC,KAAK,CAAA,CAAE;qBACjC,QAAQ,CAAC,MAAM,IAAI,IAAI,IAAI,QAAQ,CAAC,MAAM,KAAK;AAC9C,0BAAE,CAAA,aAAA,EAAgB,QAAQ,CAAC,MAAM,CAAA;AACjC,0BAAE,EAAE,CAAC,CACV;YACH;YAEA,MAAM,IAAI,KAAK,CAAC,CAAA,4BAAA,EAA+B,QAAQ,CAAC,MAAM,CAAA,CAAE,CAAC;QACnE;QAAE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,oCAAA,EAAwC,KAAe,CAAC,OAAO,CAAA,CAAE,CAClE;QACH;AACF,IAAA,CAAC,EACD;QACE,IAAI,EAAE,SAAS,CAAC,8BAA8B;AAC9C,QAAA,WAAW,EAAE,sCAAsC;AACnD,QAAA,MAAM,EAAE,iCAAiC;QACzC,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
@@ -12,8 +12,32 @@ const getCodeBaseURL = () => getEnvironmentVariable(EnvVar.CODE_BASEURL) ??
12
12
  Constants.OFFICIAL_CODE_BASEURL;
13
13
  const imageMessage = 'Image is already displayed to the user';
14
14
  const otherMessage = 'File is already downloaded by the user';
15
+ const inheritedFileMessage = 'Available as an input — already known to the user';
15
16
  const accessMessage = 'Note: Files from previous executions are automatically available and can be modified.';
16
17
  const emptyOutputMessage = "stdout: Empty. Ensure you're writing output explicitly.\n";
18
+ const inheritedFilesHeader = 'Available files (inputs, not generated by this execution):';
19
+ const generatedFilesHeader = 'Generated files:';
20
+ const inheritedNote = 'Note: Files in "Available files" are inputs the user (or a skill) already provided to the sandbox. They were not produced by this execution and you should not present them as new outputs in your response.';
21
+ /**
22
+ * Renders one section of the post-execution file listing. Used by the
23
+ * code/bash tool formatters to keep generated outputs and inherited
24
+ * inputs visually separated. See BashExecutor for full docs.
25
+ */
26
+ function renderFileSection(header, files, defaultMessage) {
27
+ if (files.length === 0)
28
+ return '';
29
+ let out = `${header}\n`;
30
+ for (let i = 0; i < files.length; i++) {
31
+ const file = files[i];
32
+ const isImage = imageExtRegex.test(file.name);
33
+ out += `- /mnt/data/${file.name} | ${isImage ? imageMessage : defaultMessage}`;
34
+ if (i < files.length - 1) {
35
+ out += files.length <= 3 ? ', ' : ',\n';
36
+ }
37
+ }
38
+ out += '\n';
39
+ return out;
40
+ }
17
41
  const SUPPORTED_LANGUAGES = [
18
42
  'py',
19
43
  'js',
@@ -29,6 +53,11 @@ const SUPPORTED_LANGUAGES = [
29
53
  'r',
30
54
  'bash',
31
55
  ];
56
+ // Minimal schema for raw code execution. Only what the /exec endpoint needs.
57
+ // Higher-level workflows (versioning, edit, store, replay) are consumer
58
+ // concerns — e.g. ranger layers its own write/edit/execute schema on top via
59
+ // codeEditWrapper and a separate ContentStore-backed Zod schema. Keeping this
60
+ // tool narrow means every consumer gets a clean, schema-stable primitive.
32
61
  const CodeExecutionToolSchema = {
33
62
  type: 'object',
34
63
  properties: {
@@ -57,20 +86,8 @@ const CodeExecutionToolSchema = {
57
86
  items: { type: 'string' },
58
87
  description: 'Additional arguments to execute the code with. This should only be used if the input code requires additional arguments to run.',
59
88
  },
60
- code_id: {
61
- type: 'string',
62
- description: 'ID of previously stored code (returned by a prior execute_code call). Use with old_str/new_str to edit stored code instead of rewriting it.',
63
- },
64
- old_str: {
65
- type: 'string',
66
- description: 'Exact string to find in stored code (requires code_id). Copy verbatim from the code you wrote.',
67
- },
68
- new_str: {
69
- type: 'string',
70
- description: 'Replacement string (requires code_id and old_str). The matched old_str will be replaced with this value.',
71
- },
72
89
  },
73
- required: ['lang'],
90
+ required: [],
74
91
  };
75
92
  const CodeExecutionToolDescription = `
76
93
  Runs code and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.
@@ -79,7 +96,6 @@ Usage:
79
96
  - No network access available. Do NOT use pip install, npm install, or any package manager.
80
97
  - Generated files are automatically delivered; **DO NOT** provide download links.
81
98
  - NEVER use this tool to execute malicious code.
82
- - When a code_id is returned in output, you can edit that code using code_id + old_str + new_str instead of rewriting the entire code block.
83
99
 
84
100
  Pre-installed Python packages (use directly, no installation needed):
85
101
  - Data Science: numpy, pandas
@@ -112,29 +128,7 @@ function createCodeExecutionTool(params = {}) {
112
128
  if (!apiKey) {
113
129
  throw new Error('No API key provided for code execution tool.');
114
130
  }
115
- const description = `
116
- ⛔ STOP! Before using this tool, ask: "Does user need a DOWNLOADABLE FILE?"
117
- - If NO (dashboard, chart, visualization, UI) → DO NOT USE THIS TOOL. Use content_tool write instead.
118
- - If YES (.pptx, .docx, .pdf, .xlsx) → Use this tool.
119
-
120
- Runs code in a stateless execution environment. Each execution is isolated.
121
-
122
- 🚫 NEVER USE FOR:
123
- - Dashboards, charts, visualizations → Use content_tool write with React/Chart.js
124
- - "Mock data" or "sample data" for display → Hardcode data in content_tool write
125
- - UI components, HTML pages, React apps → Use content_tool write
126
-
127
- ✅ ONLY USE FOR:
128
- - File generation: PowerPoint (.pptx), Word (.docx), PDF (.pdf), Excel (.xlsx)
129
- - Processing uploaded files (CSV, Excel analysis)
130
- - Heavy computation requiring Python (numpy, pandas for data analytics)
131
-
132
- Rules:
133
- - No network access — do NOT use pip install, npm install, or any package manager
134
- - All packages are pre-installed: numpy, pandas, matplotlib, seaborn, plotly, python-docx, python-pptx, reportlab, openpyxl, xlsxwriter, pillow, faker, orjson, lxml, beautifulsoup4
135
- - Generated files auto-delivered (no download links needed)
136
- - **Error recovery**: When execution fails, use \`code_id\` + \`old_str\` + \`new_str\` to fix only the broken part — do NOT rewrite the entire code block. This is faster and saves tokens.
137
- `.trim();
131
+ const description = CodeExecutionToolDescription;
138
132
  return tool(async (rawInput, config) => {
139
133
  // Resolve URL at call time (not module load time) to pick up env var changes
140
134
  const baseEndpoint = getCodeBaseURL();
@@ -277,17 +271,19 @@ Rules:
277
271
  '\n[OUTPUT_TOO_LARGE] stdout was capped. Use targeted print() for specific values.';
278
272
  }
279
273
  if (result.files && result.files.length > 0) {
280
- formattedOutput += 'Generated files:\n';
281
- const fileCount = result.files.length;
282
- for (let i = 0; i < fileCount; i++) {
283
- const file = result.files[i];
284
- const isImage = imageExtRegex.test(file.name);
285
- formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;
286
- if (i < fileCount - 1) {
287
- formattedOutput += fileCount <= 3 ? ', ' : ',\n';
288
- }
274
+ /* Split inherited (read-only passthrough) inputs from real
275
+ * generated outputs so the LLM doesn't conflate skill files
276
+ * with newly-produced artifacts. */
277
+ const inheritedFiles = result.files.filter((f) => f.inherited === true);
278
+ const generatedFiles = result.files.filter((f) => f.inherited !== true);
279
+ formattedOutput += renderFileSection(generatedFilesHeader, generatedFiles, otherMessage);
280
+ formattedOutput += renderFileSection(inheritedFilesHeader, inheritedFiles, inheritedFileMessage);
281
+ if (generatedFiles.length > 0) {
282
+ formattedOutput += `\n\n${accessMessage}`;
283
+ }
284
+ if (inheritedFiles.length > 0) {
285
+ formattedOutput += `\n\n${inheritedNote}`;
289
286
  }
290
- formattedOutput += `\n\n${accessMessage}`;
291
287
  return [
292
288
  formattedOutput.trim(),
293
289
  {
@@ -309,5 +305,5 @@ Rules:
309
305
  });
310
306
  }
311
307
 
312
- export { CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, createCodeExecutionTool, getCodeBaseURL, imageExtRegex };
308
+ export { CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, createCodeExecutionTool, getCodeBaseURL, imageExtRegex, renderFileSection };
313
309
  //# sourceMappingURL=CodeExecutor.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"CodeExecutor.mjs","sources":["../../../src/tools/CodeExecutor.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport type * as t from '@/types';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\nexport const imageExtRegex = /\\.(jpg|jpeg|png|gif|webp)$/i;\nexport const getCodeBaseURL = (): string =>\n getEnvironmentVariable(EnvVar.CODE_BASEURL) ??\n Constants.OFFICIAL_CODE_BASEURL;\n\nconst imageMessage = 'Image is already displayed to the user';\nconst otherMessage = 'File is already downloaded by the user';\nconst accessMessage =\n 'Note: Files from previous executions are automatically available and can be modified.';\nconst emptyOutputMessage =\n \"stdout: Empty. Ensure you're writing output explicitly.\\n\";\n\nconst SUPPORTED_LANGUAGES = [\n 'py',\n 'js',\n 'ts',\n 'c',\n 'cpp',\n 'java',\n 'php',\n 'rs',\n 'go',\n 'd',\n 'f90',\n 'r',\n 'bash',\n] as const;\n\nexport const CodeExecutionToolSchema = {\n type: 'object',\n properties: {\n lang: {\n type: 'string',\n enum: SUPPORTED_LANGUAGES,\n description:\n 'The programming language or runtime to execute the code in.',\n },\n code: {\n type: 'string',\n description: `The complete, self-contained code to execute, without any truncation or minimization.\n- The environment is stateless; variables and imports don't persist between executions.\n- Generated files from previous executions are automatically available in \"/mnt/data/\".\n- Files from previous executions are automatically available and can be modified in place.\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- py: This is not a Jupyter notebook environment. Use \\`print()\\` for all outputs.\n- py: Matplotlib: Use \\`plt.savefig()\\` to save plots as files.\n- js: use the \\`console\\` or \\`process\\` methods for all outputs.\n- r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).\n- Other languages: use appropriate output functions.`,\n },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Additional arguments to execute the code with. This should only be used if the input code requires additional arguments to run.',\n },\n code_id: {\n type: 'string',\n description:\n 'ID of previously stored code (returned by a prior execute_code call). Use with old_str/new_str to edit stored code instead of rewriting it.',\n },\n old_str: {\n type: 'string',\n description:\n 'Exact string to find in stored code (requires code_id). Copy verbatim from the code you wrote.',\n },\n new_str: {\n type: 'string',\n description:\n 'Replacement string (requires code_id and old_str). The matched old_str will be replaced with this value.',\n },\n },\n required: ['lang'],\n} as const;\n\n// NOTE: Resolved at call time inside the tool function, not at module load time.\n// Module-level caching caused stale URLs when env vars changed between restarts.\n\ntype SupportedLanguage = (typeof SUPPORTED_LANGUAGES)[number];\n\nexport const CodeExecutionToolDescription = `\nRuns code and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available. Do NOT use pip install, npm install, or any package manager.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- NEVER use this tool to execute malicious code.\n- When a code_id is returned in output, you can edit that code using code_id + old_str + new_str instead of rewriting the entire code block.\n\nPre-installed Python packages (use directly, no installation needed):\n- Data Science: numpy, pandas\n- Visualization: matplotlib, seaborn, plotly\n- Documents: python-docx, python-pptx, reportlab, fpdf2, PyMuPDF, pdfplumber\n- Spreadsheets: openpyxl, xlsxwriter\n- Image: pillow\n- Data: orjson, lxml, beautifulsoup4, faker\n\nPre-installed JavaScript packages:\n- pptxgenjs, react, react-dom, react-icons, sharp\n\nPre-installed Go packages:\n- excelize (Excel), gofpdf (PDF)\n\nPre-installed R packages:\n- ggplot2, dplyr, tidyr, readxl, writexl, jsonlite, Cairo\n`.trim();\n\nexport const CodeExecutionToolName = Constants.EXECUTE_CODE;\n\nexport const CodeExecutionToolDefinition = {\n name: CodeExecutionToolName,\n description: CodeExecutionToolDescription,\n schema: CodeExecutionToolSchema,\n} as const;\n\nfunction createCodeExecutionTool(\n params: t.CodeExecutionToolParams = {}\n): DynamicStructuredTool {\n const apiKey =\n params[EnvVar.CODE_API_KEY] ??\n params.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n if (!apiKey) {\n throw new Error('No API key provided for code execution tool.');\n }\n\n const description = `\n⛔ STOP! Before using this tool, ask: \"Does user need a DOWNLOADABLE FILE?\"\n- If NO (dashboard, chart, visualization, UI) → DO NOT USE THIS TOOL. Use content_tool write instead.\n- If YES (.pptx, .docx, .pdf, .xlsx) → Use this tool.\n\nRuns code in a stateless execution environment. Each execution is isolated.\n\n🚫 NEVER USE FOR:\n- Dashboards, charts, visualizations → Use content_tool write with React/Chart.js\n- \"Mock data\" or \"sample data\" for display → Hardcode data in content_tool write\n- UI components, HTML pages, React apps → Use content_tool write\n\n✅ ONLY USE FOR:\n- File generation: PowerPoint (.pptx), Word (.docx), PDF (.pdf), Excel (.xlsx)\n- Processing uploaded files (CSV, Excel analysis)\n- Heavy computation requiring Python (numpy, pandas for data analytics)\n\nRules:\n- No network access — do NOT use pip install, npm install, or any package manager\n- All packages are pre-installed: numpy, pandas, matplotlib, seaborn, plotly, python-docx, python-pptx, reportlab, openpyxl, xlsxwriter, pillow, faker, orjson, lxml, beautifulsoup4\n- Generated files auto-delivered (no download links needed)\n- **Error recovery**: When execution fails, use \\`code_id\\` + \\`old_str\\` + \\`new_str\\` to fix only the broken part — do NOT rewrite the entire code block. This is faster and saves tokens.\n`.trim();\n\n return tool(\n async (rawInput, config) => {\n // Resolve URL at call time (not module load time) to pick up env var changes\n const baseEndpoint = getCodeBaseURL();\n const EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\n const { lang, code, ...rest } = rawInput as {\n lang: SupportedLanguage;\n code: string;\n code_id?: string;\n old_str?: string;\n new_str?: string;\n args?: string[];\n };\n /**\n * Extract session context from config.toolCall (injected by ToolNode).\n * - session_id: For API to associate with previous session\n * - _injected_files: File refs to pass directly (avoids /files endpoint race condition)\n */\n const { session_id, _injected_files } = (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n const postData: Record<string, unknown> = {\n lang,\n code,\n ...rest,\n ...params,\n };\n\n /**\n * Pass session_id to /exec so code-executor reuses the existing session workspace.\n * This allows retries and follow-up executions to access previously generated files.\n */\n if (session_id != null && session_id.length > 0) {\n postData.session_id = session_id;\n }\n\n /**\n * File injection priority:\n * 1. Use _injected_files from ToolNode (avoids /files endpoint race condition)\n * 2. Fall back to fetching from /files endpoint if session_id provided but no injected files\n */\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n /** Fallback: fetch from /files endpoint (may have race condition issues) */\n try {\n const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;\n const userIdForFiles = params.user_id ?? '';\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'Illuma/1.0',\n 'X-API-Key': apiKey,\n ...(userIdForFiles ? { 'User-Id': userIdForFiles } : {}),\n },\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n\n const response = await fetch(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch files for session: ${response.status}`\n );\n }\n\n const files = await response.json();\n if (Array.isArray(files) && files.length > 0) {\n const fileReferences: t.CodeEnvFile[] = files.map((file) => {\n const nameParts = file.name.split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id,\n id,\n name: file.metadata['original-filename'],\n };\n });\n\n postData.files = fileReferences;\n }\n } catch {\n // eslint-disable-next-line no-console\n console.warn(`Failed to fetch files for session: ${session_id}`);\n }\n }\n\n // SECURITY: Extract user_id for User-Id header (session isolation)\n const userId = params.user_id ?? '';\n\n try {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'Illuma/1.0',\n 'X-API-Key': apiKey,\n ...(userId ? { 'User-Id': userId } : {}),\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const result: t.ExecuteResult = await response.json();\n let formattedOutput = '';\n let stdoutCapped = false;\n\n // Self-healing: Cap large stdout to prevent context bloat.\n // Preserves head (8KB) + tail (4KB) so the agent sees beginning and end.\n const STDOUT_MAX_CHARS = 16384;\n const STDOUT_HEAD_CHARS = 8192;\n const STDOUT_TAIL_CHARS = 4096;\n if (result.stdout && result.stdout.length > STDOUT_MAX_CHARS) {\n const originalLen = result.stdout.length;\n const head = result.stdout.substring(0, STDOUT_HEAD_CHARS);\n const tail = result.stdout.substring(\n result.stdout.length - STDOUT_TAIL_CHARS\n );\n const omitted = originalLen - STDOUT_HEAD_CHARS - STDOUT_TAIL_CHARS;\n result.stdout = `${head}\\n\\n[...${omitted} chars omitted...]\\n\\n${tail}`;\n stdoutCapped = true;\n // eslint-disable-next-line no-console\n console.debug(\n `[CodeExecutor] stdout capped: ${originalLen} → ${result.stdout.length} chars`\n );\n }\n\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 // Self-healing: Detect code truncation (syntax error on long code).\n // When the agent's generated code is >1500 chars and produces a SyntaxError,\n // it's likely truncated mid-generation rather than a real bug.\n const CODE_TRUNCATION_MIN_CHARS = 1500;\n if (result.stderr && code.length > CODE_TRUNCATION_MIN_CHARS) {\n const stderrLower = result.stderr.toLowerCase();\n if (\n stderrLower.includes('syntaxerror') ||\n stderrLower.includes('unexpected end') ||\n stderrLower.includes('unexpected eof') ||\n stderrLower.includes('unterminated')\n ) {\n // eslint-disable-next-line no-console\n console.debug(\n `[CodeExecutor] Code truncation detected: code=${code.length} chars, stderr contains syntax error`\n );\n formattedOutput +=\n '\\n[CODE_TRUNCATION_LIKELY] Your code appears truncated mid-generation.' +\n ' Split into multiple smaller execute_code calls (max 60 lines each).' +\n ' For documents: create+save first, then open+append+save in follow-up calls.' +\n ' Do NOT retry the same long code block.';\n }\n }\n\n // Self-healing: Advisory when stdout was capped\n if (stdoutCapped) {\n formattedOutput +=\n '\\n[OUTPUT_TOO_LARGE] stdout was capped. Use targeted print() for specific values.';\n }\n\n if (result.files && result.files.length > 0) {\n formattedOutput += 'Generated files:\\n';\n\n const fileCount = result.files.length;\n for (let i = 0; i < fileCount; i++) {\n const file = result.files[i];\n const isImage = imageExtRegex.test(file.name);\n formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\n\n if (i < fileCount - 1) {\n formattedOutput += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n formattedOutput += `\\n\\n${accessMessage}`;\n return [\n formattedOutput.trim(),\n {\n session_id: result.session_id,\n files: result.files,\n },\n ];\n }\n\n return [formattedOutput.trim(), { session_id: result.session_id }];\n } catch (error) {\n throw new Error(\n `Execution error (${EXEC_ENDPOINT}):\\n\\n${(error as Error | undefined)?.message}`\n );\n }\n },\n {\n name: CodeExecutionToolName,\n description,\n schema: CodeExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport {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IAAI,CAAA,YAAA,EAAe,IAAI,CAAC,IAAI,MAAM,OAAO,GAAG,YAAY,GAAG,YAAY,EAAE;AAExF,oBAAA,IAAI,CAAC,GAAG,SAAS,GAAG,CAAC,EAAE;AACrB,wBAAA,eAAe,IAAI,SAAS,IAAI,CAAC,GAAG,IAAI,GAAG,KAAK;oBAClD;gBACF;AAEA,gBAAA,eAAe,IAAI,CAAA,IAAA,EAAO,aAAa,CAAA,CAAE;gBACzC,OAAO;oBACL,eAAe,CAAC,IAAI,EAAE;AACtB,oBAAA;wBACE,UAAU,EAAE,MAAM,CAAC,UAAU;wBAC7B,KAAK,EAAE,MAAM,CAAC,KAAK;AACpB,qBAAA;iBACF;YACH;AAEA,YAAA,OAAO,CAAC,eAAe,CAAC,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC;QACpE;QAAE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,iBAAA,EAAoB,aAAa,CAAA,MAAA,EAAU,KAA2B,EAAE,OAAO,CAAA,CAAE,CAClF;QACH;AACF,IAAA,CAAC,EACD;AACE,QAAA,IAAI,EAAE,qBAAqB;QAC3B,WAAW;AACX,QAAA,MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
1
+ {"version":3,"file":"CodeExecutor.mjs","sources":["../../../src/tools/CodeExecutor.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport type * as t from '@/types';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\nexport const imageExtRegex = /\\.(jpg|jpeg|png|gif|webp)$/i;\nexport const getCodeBaseURL = (): string =>\n getEnvironmentVariable(EnvVar.CODE_BASEURL) ??\n Constants.OFFICIAL_CODE_BASEURL;\n\nconst imageMessage = 'Image is already displayed to the user';\nconst otherMessage = 'File is already downloaded by the user';\nconst inheritedFileMessage =\n 'Available as an input — already known to the user';\nconst accessMessage =\n 'Note: Files from previous executions are automatically available and can be modified.';\nconst emptyOutputMessage =\n \"stdout: Empty. Ensure you're writing output explicitly.\\n\";\nconst inheritedFilesHeader =\n 'Available files (inputs, not generated by this execution):';\nconst generatedFilesHeader = 'Generated files:';\nconst inheritedNote =\n 'Note: Files in \"Available files\" are inputs the user (or a skill) already provided to the sandbox. They were not produced by this execution and you should not present them as new outputs in your response.';\n\n/**\n * Renders one section of the post-execution file listing. Used by the\n * code/bash tool formatters to keep generated outputs and inherited\n * inputs visually separated. See BashExecutor for full docs.\n */\nexport function renderFileSection(\n header: string,\n files: t.FileRefs,\n defaultMessage: string\n): string {\n if (files.length === 0) return '';\n let out = `${header}\\n`;\n for (let i = 0; i < files.length; i++) {\n const file = files[i];\n const isImage = imageExtRegex.test(file.name);\n out += `- /mnt/data/${file.name} | ${isImage ? imageMessage : defaultMessage}`;\n if (i < files.length - 1) {\n out += files.length <= 3 ? ', ' : ',\\n';\n }\n }\n out += '\\n';\n return out;\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\n// Minimal schema for raw code execution. Only what the /exec endpoint needs.\n// Higher-level workflows (versioning, edit, store, replay) are consumer\n// concerns — e.g. ranger layers its own write/edit/execute schema on top via\n// codeEditWrapper and a separate ContentStore-backed Zod schema. Keeping this\n// tool narrow means every consumer gets a clean, schema-stable primitive.\nexport const CodeExecutionToolSchema = {\n type: 'object',\n properties: {\n lang: {\n type: 'string',\n enum: SUPPORTED_LANGUAGES,\n description:\n 'The programming language or runtime to execute the code in.',\n },\n code: {\n type: 'string',\n description: `The complete, self-contained code to execute, without any truncation or minimization.\n- The environment is stateless; variables and imports don't persist between executions.\n- Generated files from previous executions are automatically available in \"/mnt/data/\".\n- Files from previous executions are automatically available and can be modified in place.\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- py: This is not a Jupyter notebook environment. Use \\`print()\\` for all outputs.\n- py: Matplotlib: Use \\`plt.savefig()\\` to save plots as files.\n- js: use the \\`console\\` or \\`process\\` methods for all outputs.\n- r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).\n- Other languages: use appropriate output functions.`,\n },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Additional arguments to execute the code with. This should only be used if the input code requires additional arguments to run.',\n },\n },\n required: [],\n} as const;\n\n// NOTE: Resolved at call time inside the tool function, not at module load time.\n// Module-level caching caused stale URLs when env vars changed between restarts.\n\ntype SupportedLanguage = (typeof SUPPORTED_LANGUAGES)[number];\n\nexport const CodeExecutionToolDescription = `\nRuns code and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available. Do NOT use pip install, npm install, or any package manager.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- NEVER use this tool to execute malicious code.\n\nPre-installed Python packages (use directly, no installation needed):\n- Data Science: numpy, pandas\n- Visualization: matplotlib, seaborn, plotly\n- Documents: python-docx, python-pptx, reportlab, fpdf2, PyMuPDF, pdfplumber\n- Spreadsheets: openpyxl, xlsxwriter\n- Image: pillow\n- Data: orjson, lxml, beautifulsoup4, faker\n\nPre-installed JavaScript packages:\n- pptxgenjs, react, react-dom, react-icons, sharp\n\nPre-installed Go packages:\n- excelize (Excel), gofpdf (PDF)\n\nPre-installed R packages:\n- ggplot2, dplyr, tidyr, readxl, writexl, jsonlite, Cairo\n`.trim();\n\nexport const CodeExecutionToolName = Constants.EXECUTE_CODE;\n\nexport const CodeExecutionToolDefinition = {\n name: CodeExecutionToolName,\n description: CodeExecutionToolDescription,\n schema: CodeExecutionToolSchema,\n} as const;\n\nfunction createCodeExecutionTool(\n params: t.CodeExecutionToolParams = {}\n): DynamicStructuredTool {\n const apiKey =\n params[EnvVar.CODE_API_KEY] ??\n params.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n if (!apiKey) {\n throw new Error('No API key provided for code execution tool.');\n }\n\n const description = CodeExecutionToolDescription;\n\n return tool(\n async (rawInput, config) => {\n // Resolve URL at call time (not module load time) to pick up env var changes\n const baseEndpoint = getCodeBaseURL();\n const EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\n const { lang, code, ...rest } = rawInput as {\n lang: SupportedLanguage;\n code: string;\n args?: string[];\n };\n /**\n * Extract session context from config.toolCall (injected by ToolNode).\n * - session_id: For API to associate with previous session\n * - _injected_files: File refs to pass directly (avoids /files endpoint race condition)\n */\n const { session_id, _injected_files } = (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n const postData: Record<string, unknown> = {\n lang,\n code,\n ...rest,\n ...params,\n };\n\n /**\n * Pass session_id to /exec so code-executor reuses the existing session workspace.\n * This allows retries and follow-up executions to access previously generated files.\n */\n if (session_id != null && session_id.length > 0) {\n postData.session_id = session_id;\n }\n\n /**\n * File injection priority:\n * 1. Use _injected_files from ToolNode (avoids /files endpoint race condition)\n * 2. Fall back to fetching from /files endpoint if session_id provided but no injected files\n */\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n /** Fallback: fetch from /files endpoint (may have race condition issues) */\n try {\n const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;\n const userIdForFiles = params.user_id ?? '';\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'Illuma/1.0',\n 'X-API-Key': apiKey,\n ...(userIdForFiles ? { 'User-Id': userIdForFiles } : {}),\n },\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n\n const response = await fetch(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch files for session: ${response.status}`\n );\n }\n\n const files = await response.json();\n if (Array.isArray(files) && files.length > 0) {\n const fileReferences: t.CodeEnvFile[] = files.map((file) => {\n const nameParts = file.name.split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id,\n id,\n name: file.metadata['original-filename'],\n };\n });\n\n postData.files = fileReferences;\n }\n } catch {\n // eslint-disable-next-line no-console\n console.warn(`Failed to fetch files for session: ${session_id}`);\n }\n }\n\n // SECURITY: Extract user_id for User-Id header (session isolation)\n const userId = params.user_id ?? '';\n\n try {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'Illuma/1.0',\n 'X-API-Key': apiKey,\n ...(userId ? { 'User-Id': userId } : {}),\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const result: t.ExecuteResult = await response.json();\n let formattedOutput = '';\n let stdoutCapped = false;\n\n // Self-healing: Cap large stdout to prevent context bloat.\n // Preserves head (8KB) + tail (4KB) so the agent sees beginning and end.\n const STDOUT_MAX_CHARS = 16384;\n const STDOUT_HEAD_CHARS = 8192;\n const STDOUT_TAIL_CHARS = 4096;\n if (result.stdout && result.stdout.length > STDOUT_MAX_CHARS) {\n const originalLen = result.stdout.length;\n const head = result.stdout.substring(0, STDOUT_HEAD_CHARS);\n const tail = result.stdout.substring(\n result.stdout.length - STDOUT_TAIL_CHARS\n );\n const omitted = originalLen - STDOUT_HEAD_CHARS - STDOUT_TAIL_CHARS;\n result.stdout = `${head}\\n\\n[...${omitted} chars omitted...]\\n\\n${tail}`;\n stdoutCapped = true;\n // eslint-disable-next-line no-console\n console.debug(\n `[CodeExecutor] stdout capped: ${originalLen} → ${result.stdout.length} chars`\n );\n }\n\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 // Self-healing: Detect code truncation (syntax error on long code).\n // When the agent's generated code is >1500 chars and produces a SyntaxError,\n // it's likely truncated mid-generation rather than a real bug.\n const CODE_TRUNCATION_MIN_CHARS = 1500;\n if (result.stderr && code.length > CODE_TRUNCATION_MIN_CHARS) {\n const stderrLower = result.stderr.toLowerCase();\n if (\n stderrLower.includes('syntaxerror') ||\n stderrLower.includes('unexpected end') ||\n stderrLower.includes('unexpected eof') ||\n stderrLower.includes('unterminated')\n ) {\n // eslint-disable-next-line no-console\n console.debug(\n `[CodeExecutor] Code truncation detected: code=${code.length} chars, stderr contains syntax error`\n );\n formattedOutput +=\n '\\n[CODE_TRUNCATION_LIKELY] Your code appears truncated mid-generation.' +\n ' Split into multiple smaller execute_code calls (max 60 lines each).' +\n ' For documents: create+save first, then open+append+save in follow-up calls.' +\n ' Do NOT retry the same long code block.';\n }\n }\n\n // Self-healing: Advisory when stdout was capped\n if (stdoutCapped) {\n formattedOutput +=\n '\\n[OUTPUT_TOO_LARGE] stdout was capped. Use targeted print() for specific values.';\n }\n\n if (result.files && result.files.length > 0) {\n /* Split inherited (read-only passthrough) inputs from real\n * generated outputs so the LLM doesn't conflate skill files\n * with newly-produced artifacts. */\n const inheritedFiles = result.files.filter(\n (f) => f.inherited === true\n );\n const generatedFiles = result.files.filter(\n (f) => f.inherited !== true\n );\n\n formattedOutput += renderFileSection(\n generatedFilesHeader,\n generatedFiles,\n otherMessage\n );\n formattedOutput += renderFileSection(\n inheritedFilesHeader,\n inheritedFiles,\n inheritedFileMessage\n );\n\n if (generatedFiles.length > 0) {\n formattedOutput += `\\n\\n${accessMessage}`;\n }\n if (inheritedFiles.length > 0) {\n formattedOutput += `\\n\\n${inheritedNote}`;\n }\n return [\n formattedOutput.trim(),\n {\n session_id: result.session_id,\n files: result.files,\n },\n ];\n }\n\n return [formattedOutput.trim(), { session_id: result.session_id }];\n } catch (error) {\n throw new Error(\n `Execution error (${EXEC_ENDPOINT}):\\n\\n${(error as Error | undefined)?.message}`\n );\n }\n },\n {\n name: CodeExecutionToolName,\n description,\n schema: CodeExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createCodeExecutionTool };\n"],"names":[],"mappings":";;;;;;;;AAQA,MAAM,EAAE;AAED,MAAM,aAAa,GAAG;AACtB,MAAM,cAAc,GAAG,MAC5B,sBAAsB,CAAC,MAAM,CAAC,YAAY,CAAC;IAC3C,SAAS,CAAC;AAEZ,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,oBAAoB,GACxB,mDAAmD;AACrD,MAAM,aAAa,GACjB,uFAAuF;AACzF,MAAM,kBAAkB,GACtB,2DAA2D;AAC7D,MAAM,oBAAoB,GACxB,4DAA4D;AAC9D,MAAM,oBAAoB,GAAG,kBAAkB;AAC/C,MAAM,aAAa,GACjB,8MAA8M;AAEhN;;;;AAIG;SACa,iBAAiB,CAC/B,MAAc,EACd,KAAiB,EACjB,cAAsB,EAAA;AAEtB,IAAA,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;AAAE,QAAA,OAAO,EAAE;AACjC,IAAA,IAAI,GAAG,GAAG,CAAA,EAAG,MAAM,IAAI;AACvB,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACrC,QAAA,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC;QACrB,MAAM,OAAO,GAAG,aAA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AA,EAAO,aAAa,CAAA,CAAE;gBAC3C;gBACA,OAAO;oBACL,eAAe,CAAC,IAAI,EAAE;AACtB,oBAAA;wBACE,UAAU,EAAE,MAAM,CAAC,UAAU;wBAC7B,KAAK,EAAE,MAAM,CAAC,KAAK;AACpB,qBAAA;iBACF;YACH;AAEA,YAAA,OAAO,CAAC,eAAe,CAAC,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC;QACpE;QAAE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,iBAAA,EAAoB,aAAa,CAAA,MAAA,EAAU,KAA2B,EAAE,OAAO,CAAA,CAAE,CAClF;QACH;AACF,IAAA,CAAC,EACD;AACE,QAAA,IAAI,EAAE,qBAAqB;QAC3B,WAAW;AACX,QAAA,MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
@@ -3,7 +3,7 @@ import fetch from 'node-fetch';
3
3
  import { HttpsProxyAgent } from 'https-proxy-agent';
4
4
  import { getEnvironmentVariable } from '@langchain/core/utils/env';
5
5
  import { tool } from '@langchain/core/tools';
6
- import { getCodeBaseURL, imageExtRegex } from './CodeExecutor.mjs';
6
+ import { getCodeBaseURL, renderFileSection } from './CodeExecutor.mjs';
7
7
  import { Constants, EnvVar } from '../common/enum.mjs';
8
8
  import './approval/constants.mjs';
9
9
 
@@ -12,8 +12,11 @@ config();
12
12
  // ============================================================================
13
13
  // Constants
14
14
  // ============================================================================
15
- const imageMessage = 'Image is already displayed to the user';
16
15
  const otherMessage = 'File is already downloaded by the user';
16
+ const inheritedFileMessage = 'Available as an input — already known to the user';
17
+ const inheritedFilesHeader = 'Available files (inputs, not generated by this execution):';
18
+ const generatedFilesHeader = 'Generated files:';
19
+ const inheritedNote = 'Note: Files in "Available files" are inputs the user (or a skill) already provided to the sandbox. They were not produced by this execution and you should not present them as new outputs in your response.';
17
20
  const accessMessage = 'Note: Files from previous executions are automatically available and can be modified.';
18
21
  const emptyOutputMessage = "stdout: Empty. Ensure you're writing output explicitly.\n";
19
22
  /** Default max round-trips to prevent infinite loops */
@@ -457,17 +460,19 @@ function formatCompletedResponse(response) {
457
460
  formatted += `stderr:\n${response.stderr}\n`;
458
461
  }
459
462
  if (response.files && response.files.length > 0) {
460
- formatted += 'Generated files:\n';
461
- const fileCount = response.files.length;
462
- for (let i = 0; i < fileCount; i++) {
463
- const file = response.files[i];
464
- const isImage = imageExtRegex.test(file.name);
465
- formatted += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;
466
- if (i < fileCount - 1) {
467
- formatted += fileCount <= 3 ? ', ' : ',\n';
468
- }
463
+ /* See BashExecutor for the rationale: split inherited (read-only
464
+ * passthrough) inputs from real generated outputs so the LLM doesn't
465
+ * conflate skill files with newly-produced artifacts. */
466
+ const inheritedFiles = response.files.filter((f) => f.inherited === true);
467
+ const generatedFiles = response.files.filter((f) => f.inherited !== true);
468
+ formatted += renderFileSection(generatedFilesHeader, generatedFiles, otherMessage);
469
+ formatted += renderFileSection(inheritedFilesHeader, inheritedFiles, inheritedFileMessage);
470
+ if (generatedFiles.length > 0) {
471
+ formatted += `\n\n${accessMessage}`;
472
+ }
473
+ if (inheritedFiles.length > 0) {
474
+ formatted += `\n\n${inheritedNote}`;
469
475
  }
470
- formatted += `\n\n${accessMessage}`;
471
476
  }
472
477
  return [
473
478
  formatted.trim(),