@librechat/agents 3.4.7 → 3.5.1

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 (924) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +0 -356
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/agents/projection.cjs +0 -9
  4. package/dist/cjs/agents/projection.cjs.map +1 -1
  5. package/dist/cjs/common/constants.cjs +0 -26
  6. package/dist/cjs/common/constants.cjs.map +1 -1
  7. package/dist/cjs/common/enum.cjs +0 -85
  8. package/dist/cjs/common/enum.cjs.map +1 -1
  9. package/dist/cjs/events.cjs +0 -14
  10. package/dist/cjs/events.cjs.map +1 -1
  11. package/dist/cjs/graphs/Graph.cjs +1 -909
  12. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  13. package/dist/cjs/graphs/MultiAgentGraph.cjs +7 -272
  14. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  15. package/dist/cjs/graphs/applyGraphRuntimeConfig.cjs.map +1 -1
  16. package/dist/cjs/graphs/createGraph.cjs.map +1 -1
  17. package/dist/cjs/hitl/askUserQuestion.cjs +0 -53
  18. package/dist/cjs/hitl/askUserQuestion.cjs.map +1 -1
  19. package/dist/cjs/hitl/askUserQuestions.cjs +0 -20
  20. package/dist/cjs/hitl/askUserQuestions.cjs.map +1 -1
  21. package/dist/cjs/hitl/askUserQuestionsInterrupt.cjs +0 -6
  22. package/dist/cjs/hitl/askUserQuestionsInterrupt.cjs.map +1 -1
  23. package/dist/cjs/hooks/HookRegistry.cjs +0 -127
  24. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -1
  25. package/dist/cjs/hooks/createToolPolicyHook.cjs +0 -38
  26. package/dist/cjs/hooks/createToolPolicyHook.cjs.map +1 -1
  27. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs +0 -77
  28. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs.map +1 -1
  29. package/dist/cjs/hooks/executeHooks.cjs +0 -79
  30. package/dist/cjs/hooks/executeHooks.cjs.map +1 -1
  31. package/dist/cjs/hooks/index.cjs +0 -16
  32. package/dist/cjs/hooks/index.cjs.map +1 -1
  33. package/dist/cjs/hooks/matchers.cjs +0 -104
  34. package/dist/cjs/hooks/matchers.cjs.map +1 -1
  35. package/dist/cjs/hooks/types.cjs +0 -8
  36. package/dist/cjs/hooks/types.cjs.map +1 -1
  37. package/dist/cjs/instrumentation.cjs +0 -14
  38. package/dist/cjs/instrumentation.cjs.map +1 -1
  39. package/dist/cjs/langfuse.cjs +0 -75
  40. package/dist/cjs/langfuse.cjs.map +1 -1
  41. package/dist/cjs/langfuseConfig.cjs.map +1 -1
  42. package/dist/cjs/langfuseRuntimeContext.cjs +0 -13
  43. package/dist/cjs/langfuseRuntimeContext.cjs.map +1 -1
  44. package/dist/cjs/langfuseRuntimeScope.cjs +0 -4
  45. package/dist/cjs/langfuseRuntimeScope.cjs.map +1 -1
  46. package/dist/cjs/langfuseSpanRegistry.cjs +0 -28
  47. package/dist/cjs/langfuseSpanRegistry.cjs.map +1 -1
  48. package/dist/cjs/langfuseToolOutputTracing.cjs +0 -3
  49. package/dist/cjs/langfuseToolOutputTracing.cjs.map +1 -1
  50. package/dist/cjs/langfuseTraceShaping.cjs +0 -74
  51. package/dist/cjs/langfuseTraceShaping.cjs.map +1 -1
  52. package/dist/cjs/llm/anthropic/index.cjs +0 -3
  53. package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
  54. package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
  55. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +1 -111
  56. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  57. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +0 -1
  58. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
  59. package/dist/cjs/llm/anthropic/utils/stream_events.cjs +0 -8
  60. package/dist/cjs/llm/anthropic/utils/stream_events.cjs.map +1 -1
  61. package/dist/cjs/llm/anthropic/utils/tools.cjs.map +1 -1
  62. package/dist/cjs/llm/bedrock/cachePoints.cjs.map +1 -1
  63. package/dist/cjs/llm/bedrock/index.cjs +1 -95
  64. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  65. package/dist/cjs/llm/bedrock/toolCache.cjs.map +1 -1
  66. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +0 -78
  67. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
  68. package/dist/cjs/llm/bedrock/utils/message_outputs.cjs +0 -24
  69. package/dist/cjs/llm/bedrock/utils/message_outputs.cjs.map +1 -1
  70. package/dist/cjs/llm/contextOverflowRecovery.cjs +0 -62
  71. package/dist/cjs/llm/contextOverflowRecovery.cjs.map +1 -1
  72. package/dist/cjs/llm/fake.cjs.map +1 -1
  73. package/dist/cjs/llm/google/index.cjs +2 -21
  74. package/dist/cjs/llm/google/index.cjs.map +1 -1
  75. package/dist/cjs/llm/google/utils/common.cjs +0 -35
  76. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  77. package/dist/cjs/llm/init.cjs +0 -9
  78. package/dist/cjs/llm/init.cjs.map +1 -1
  79. package/dist/cjs/llm/invoke.cjs +1 -270
  80. package/dist/cjs/llm/invoke.cjs.map +1 -1
  81. package/dist/cjs/llm/mistral/index.cjs.map +1 -1
  82. package/dist/cjs/llm/openai/index.cjs +0 -99
  83. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  84. package/dist/cjs/llm/openai/streamMetadata.cjs +0 -21
  85. package/dist/cjs/llm/openai/streamMetadata.cjs.map +1 -1
  86. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
  87. package/dist/cjs/llm/openrouter/index.cjs +0 -1
  88. package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
  89. package/dist/cjs/llm/openrouter/toolCache.cjs +0 -6
  90. package/dist/cjs/llm/openrouter/toolCache.cjs.map +1 -1
  91. package/dist/cjs/llm/preempt.cjs +0 -75
  92. package/dist/cjs/llm/preempt.cjs.map +1 -1
  93. package/dist/cjs/llm/providers.cjs.map +1 -1
  94. package/dist/cjs/llm/request.cjs +0 -10
  95. package/dist/cjs/llm/request.cjs.map +1 -1
  96. package/dist/cjs/llm/stream/chunkAdapters.cjs +0 -62
  97. package/dist/cjs/llm/stream/chunkAdapters.cjs.map +1 -1
  98. package/dist/cjs/llm/stream/smoother.cjs +0 -58
  99. package/dist/cjs/llm/stream/smoother.cjs.map +1 -1
  100. package/dist/cjs/llm/streamLimits.cjs +4 -293
  101. package/dist/cjs/llm/streamLimits.cjs.map +1 -1
  102. package/dist/cjs/llm/truncation.cjs +0 -36
  103. package/dist/cjs/llm/truncation.cjs.map +1 -1
  104. package/dist/cjs/llm/vertexai/index.cjs +0 -330
  105. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  106. package/dist/cjs/messages/alternation.cjs +0 -43
  107. package/dist/cjs/messages/alternation.cjs.map +1 -1
  108. package/dist/cjs/messages/anthropicToolCache.cjs +0 -45
  109. package/dist/cjs/messages/anthropicToolCache.cjs.map +1 -1
  110. package/dist/cjs/messages/assistantPhase.cjs +0 -12
  111. package/dist/cjs/messages/assistantPhase.cjs.map +1 -1
  112. package/dist/cjs/messages/budget.cjs +0 -9
  113. package/dist/cjs/messages/budget.cjs.map +1 -1
  114. package/dist/cjs/messages/cache.cjs +0 -172
  115. package/dist/cjs/messages/cache.cjs.map +1 -1
  116. package/dist/cjs/messages/content.cjs +0 -9
  117. package/dist/cjs/messages/content.cjs.map +1 -1
  118. package/dist/cjs/messages/contextPruning.cjs +0 -15
  119. package/dist/cjs/messages/contextPruning.cjs.map +1 -1
  120. package/dist/cjs/messages/contextPruningSettings.cjs +0 -3
  121. package/dist/cjs/messages/contextPruningSettings.cjs.map +1 -1
  122. package/dist/cjs/messages/core.cjs +0 -48
  123. package/dist/cjs/messages/core.cjs.map +1 -1
  124. package/dist/cjs/messages/format.cjs +1 -345
  125. package/dist/cjs/messages/format.cjs.map +1 -1
  126. package/dist/cjs/messages/handoffCue.cjs +0 -36
  127. package/dist/cjs/messages/handoffCue.cjs.map +1 -1
  128. package/dist/cjs/messages/ids.cjs.map +1 -1
  129. package/dist/cjs/messages/injected.cjs +0 -33
  130. package/dist/cjs/messages/injected.cjs.map +1 -1
  131. package/dist/cjs/messages/langchain.cjs +0 -14
  132. package/dist/cjs/messages/langchain.cjs.map +1 -1
  133. package/dist/cjs/messages/prune.cjs +1 -184
  134. package/dist/cjs/messages/prune.cjs.map +1 -1
  135. package/dist/cjs/messages/recency.cjs +0 -32
  136. package/dist/cjs/messages/recency.cjs.map +1 -1
  137. package/dist/cjs/messages/reducer.cjs +0 -30
  138. package/dist/cjs/messages/reducer.cjs.map +1 -1
  139. package/dist/cjs/messages/tools.cjs +0 -14
  140. package/dist/cjs/messages/tools.cjs.map +1 -1
  141. package/dist/cjs/openai/index.cjs.map +1 -1
  142. package/dist/cjs/prompts/activityLabel.cjs +9 -79
  143. package/dist/cjs/prompts/activityLabel.cjs.map +1 -1
  144. package/dist/cjs/responses/index.cjs.map +1 -1
  145. package/dist/cjs/run.cjs +2 -538
  146. package/dist/cjs/run.cjs.map +1 -1
  147. package/dist/cjs/session/AgentSession.cjs +1 -17
  148. package/dist/cjs/session/AgentSession.cjs.map +1 -1
  149. package/dist/cjs/session/JsonlSessionStore.cjs.map +1 -1
  150. package/dist/cjs/session/handlers.cjs +0 -7
  151. package/dist/cjs/session/handlers.cjs.map +1 -1
  152. package/dist/cjs/session/ids.cjs.map +1 -1
  153. package/dist/cjs/session/messageSerialization.cjs +0 -4
  154. package/dist/cjs/session/messageSerialization.cjs.map +1 -1
  155. package/dist/cjs/stream.cjs +1 -93
  156. package/dist/cjs/stream.cjs.map +1 -1
  157. package/dist/cjs/summarization/index.cjs +0 -27
  158. package/dist/cjs/summarization/index.cjs.map +1 -1
  159. package/dist/cjs/summarization/node.cjs +0 -273
  160. package/dist/cjs/summarization/node.cjs.map +1 -1
  161. package/dist/cjs/tools/BashExecutor.cjs +0 -35
  162. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  163. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +0 -24
  164. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  165. package/dist/cjs/tools/Calculator.cjs.map +1 -1
  166. package/dist/cjs/tools/CodeExecutor.cjs +0 -13
  167. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  168. package/dist/cjs/tools/CodeSessionFileSummary.cjs.map +1 -1
  169. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +0 -101
  170. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  171. package/dist/cjs/tools/ReadFile.cjs.map +1 -1
  172. package/dist/cjs/tools/SkillTool.cjs +0 -5
  173. package/dist/cjs/tools/SkillTool.cjs.map +1 -1
  174. package/dist/cjs/tools/SubagentTool.cjs +0 -10
  175. package/dist/cjs/tools/SubagentTool.cjs.map +1 -1
  176. package/dist/cjs/tools/ToolNode.cjs +6 -1038
  177. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  178. package/dist/cjs/tools/ToolSearch.cjs +0 -179
  179. package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
  180. package/dist/cjs/tools/cloudflare/CloudflareBridgeRuntime.cjs.map +1 -1
  181. package/dist/cjs/tools/cloudflare/CloudflareProgrammaticToolCalling.cjs.map +1 -1
  182. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs +0 -39
  183. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs.map +1 -1
  184. package/dist/cjs/tools/cloudflare/CloudflareSandboxTools.cjs.map +1 -1
  185. package/dist/cjs/tools/eagerEventExecution.cjs +0 -6
  186. package/dist/cjs/tools/eagerEventExecution.cjs.map +1 -1
  187. package/dist/cjs/tools/handlers.cjs +1 -41
  188. package/dist/cjs/tools/handlers.cjs.map +1 -1
  189. package/dist/cjs/tools/intentArg.cjs +1 -132
  190. package/dist/cjs/tools/intentArg.cjs.map +1 -1
  191. package/dist/cjs/tools/local/CompileCheckTool.cjs +0 -25
  192. package/dist/cjs/tools/local/CompileCheckTool.cjs.map +1 -1
  193. package/dist/cjs/tools/local/FileCheckpointer.cjs +0 -23
  194. package/dist/cjs/tools/local/FileCheckpointer.cjs.map +1 -1
  195. package/dist/cjs/tools/local/LocalCodingTools.cjs +0 -80
  196. package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -1
  197. package/dist/cjs/tools/local/LocalExecutionEngine.cjs +0 -126
  198. package/dist/cjs/tools/local/LocalExecutionEngine.cjs.map +1 -1
  199. package/dist/cjs/tools/local/LocalExecutionTools.cjs.map +1 -1
  200. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs +0 -12
  201. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs.map +1 -1
  202. package/dist/cjs/tools/local/attachments.cjs +0 -44
  203. package/dist/cjs/tools/local/attachments.cjs.map +1 -1
  204. package/dist/cjs/tools/local/bashAst.cjs +0 -16
  205. package/dist/cjs/tools/local/bashAst.cjs.map +1 -1
  206. package/dist/cjs/tools/local/editStrategies.cjs +0 -14
  207. package/dist/cjs/tools/local/editStrategies.cjs.map +1 -1
  208. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs.map +1 -1
  209. package/dist/cjs/tools/local/syntaxCheck.cjs +0 -31
  210. package/dist/cjs/tools/local/syntaxCheck.cjs.map +1 -1
  211. package/dist/cjs/tools/local/textEncoding.cjs +0 -11
  212. package/dist/cjs/tools/local/textEncoding.cjs.map +1 -1
  213. package/dist/cjs/tools/local/workspaceFS.cjs +0 -33
  214. package/dist/cjs/tools/local/workspaceFS.cjs.map +1 -1
  215. package/dist/cjs/tools/ptcTimeout.cjs.map +1 -1
  216. package/dist/cjs/tools/schema.cjs +0 -8
  217. package/dist/cjs/tools/schema.cjs.map +1 -1
  218. package/dist/cjs/tools/search/anthropic.cjs +0 -9
  219. package/dist/cjs/tools/search/anthropic.cjs.map +1 -1
  220. package/dist/cjs/tools/search/content.cjs.map +1 -1
  221. package/dist/cjs/tools/search/crw-scraper.cjs +0 -33
  222. package/dist/cjs/tools/search/crw-scraper.cjs.map +1 -1
  223. package/dist/cjs/tools/search/crw-search.cjs +0 -2
  224. package/dist/cjs/tools/search/crw-search.cjs.map +1 -1
  225. package/dist/cjs/tools/search/firecrawl.cjs +0 -25
  226. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  227. package/dist/cjs/tools/search/format.cjs +0 -30
  228. package/dist/cjs/tools/search/format.cjs.map +1 -1
  229. package/dist/cjs/tools/search/highlights.cjs +0 -16
  230. package/dist/cjs/tools/search/highlights.cjs.map +1 -1
  231. package/dist/cjs/tools/search/keenable-scraper.cjs +0 -8
  232. package/dist/cjs/tools/search/keenable-scraper.cjs.map +1 -1
  233. package/dist/cjs/tools/search/keenable-search.cjs +0 -7
  234. package/dist/cjs/tools/search/keenable-search.cjs.map +1 -1
  235. package/dist/cjs/tools/search/rerankers.cjs +0 -35
  236. package/dist/cjs/tools/search/rerankers.cjs.map +1 -1
  237. package/dist/cjs/tools/search/schema.cjs +0 -1
  238. package/dist/cjs/tools/search/schema.cjs.map +1 -1
  239. package/dist/cjs/tools/search/search.cjs +1 -14
  240. package/dist/cjs/tools/search/search.cjs.map +1 -1
  241. package/dist/cjs/tools/search/serper-scraper.cjs +0 -46
  242. package/dist/cjs/tools/search/serper-scraper.cjs.map +1 -1
  243. package/dist/cjs/tools/search/tavily-scraper.cjs.map +1 -1
  244. package/dist/cjs/tools/search/tavily-search.cjs.map +1 -1
  245. package/dist/cjs/tools/search/tool.cjs +0 -25
  246. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  247. package/dist/cjs/tools/search/utils.cjs +0 -8
  248. package/dist/cjs/tools/search/utils.cjs.map +1 -1
  249. package/dist/cjs/tools/skillCatalog.cjs +0 -6
  250. package/dist/cjs/tools/skillCatalog.cjs.map +1 -1
  251. package/dist/cjs/tools/streamedToolCallSeals.cjs +0 -6
  252. package/dist/cjs/tools/streamedToolCallSeals.cjs.map +1 -1
  253. package/dist/cjs/tools/subagent/SubagentExecutionRegistry.cjs +0 -2
  254. package/dist/cjs/tools/subagent/SubagentExecutionRegistry.cjs.map +1 -1
  255. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +3 -213
  256. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  257. package/dist/cjs/tools/subagent/SubagentReplay.cjs.map +1 -1
  258. package/dist/cjs/tools/subagent/childGraphConfig.cjs +0 -4
  259. package/dist/cjs/tools/subagent/childGraphConfig.cjs.map +1 -1
  260. package/dist/cjs/tools/subagent/runtimeLimits.cjs.map +1 -1
  261. package/dist/cjs/tools/toolOutputReferences.cjs +1 -322
  262. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
  263. package/dist/cjs/types/hitl.cjs +0 -5
  264. package/dist/cjs/types/hitl.cjs.map +1 -1
  265. package/dist/cjs/utils/callbacks.cjs.map +1 -1
  266. package/dist/cjs/utils/errors.cjs +14 -165
  267. package/dist/cjs/utils/errors.cjs.map +1 -1
  268. package/dist/cjs/utils/events.cjs +0 -10
  269. package/dist/cjs/utils/events.cjs.map +1 -1
  270. package/dist/cjs/utils/graph.cjs.map +1 -1
  271. package/dist/cjs/utils/handlers.cjs +0 -3
  272. package/dist/cjs/utils/handlers.cjs.map +1 -1
  273. package/dist/cjs/utils/llm.cjs +0 -1
  274. package/dist/cjs/utils/llm.cjs.map +1 -1
  275. package/dist/cjs/utils/misc.cjs +0 -16
  276. package/dist/cjs/utils/misc.cjs.map +1 -1
  277. package/dist/cjs/utils/proxy.cjs +0 -26
  278. package/dist/cjs/utils/proxy.cjs.map +1 -1
  279. package/dist/cjs/utils/run.cjs +0 -6
  280. package/dist/cjs/utils/run.cjs.map +1 -1
  281. package/dist/cjs/utils/schema.cjs +0 -5
  282. package/dist/cjs/utils/schema.cjs.map +1 -1
  283. package/dist/cjs/utils/title.cjs +0 -6
  284. package/dist/cjs/utils/title.cjs.map +1 -1
  285. package/dist/cjs/utils/tokens.cjs +0 -113
  286. package/dist/cjs/utils/tokens.cjs.map +1 -1
  287. package/dist/cjs/utils/toolContent.cjs +0 -41
  288. package/dist/cjs/utils/toolContent.cjs.map +1 -1
  289. package/dist/cjs/utils/truncation.cjs +0 -61
  290. package/dist/cjs/utils/truncation.cjs.map +1 -1
  291. package/dist/esm/agents/AgentContext.mjs +0 -356
  292. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  293. package/dist/esm/agents/projection.mjs +0 -9
  294. package/dist/esm/agents/projection.mjs.map +1 -1
  295. package/dist/esm/common/constants.mjs +0 -26
  296. package/dist/esm/common/constants.mjs.map +1 -1
  297. package/dist/esm/common/enum.mjs +0 -85
  298. package/dist/esm/common/enum.mjs.map +1 -1
  299. package/dist/esm/events.mjs +0 -14
  300. package/dist/esm/events.mjs.map +1 -1
  301. package/dist/esm/graphs/Graph.mjs +1 -909
  302. package/dist/esm/graphs/Graph.mjs.map +1 -1
  303. package/dist/esm/graphs/MultiAgentGraph.mjs +7 -272
  304. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  305. package/dist/esm/graphs/applyGraphRuntimeConfig.mjs.map +1 -1
  306. package/dist/esm/graphs/createGraph.mjs.map +1 -1
  307. package/dist/esm/hitl/askUserQuestion.mjs +0 -53
  308. package/dist/esm/hitl/askUserQuestion.mjs.map +1 -1
  309. package/dist/esm/hitl/askUserQuestions.mjs +0 -20
  310. package/dist/esm/hitl/askUserQuestions.mjs.map +1 -1
  311. package/dist/esm/hitl/askUserQuestionsInterrupt.mjs +0 -6
  312. package/dist/esm/hitl/askUserQuestionsInterrupt.mjs.map +1 -1
  313. package/dist/esm/hooks/HookRegistry.mjs +0 -127
  314. package/dist/esm/hooks/HookRegistry.mjs.map +1 -1
  315. package/dist/esm/hooks/createToolPolicyHook.mjs +0 -38
  316. package/dist/esm/hooks/createToolPolicyHook.mjs.map +1 -1
  317. package/dist/esm/hooks/createWorkspacePolicyHook.mjs +0 -77
  318. package/dist/esm/hooks/createWorkspacePolicyHook.mjs.map +1 -1
  319. package/dist/esm/hooks/executeHooks.mjs +0 -79
  320. package/dist/esm/hooks/executeHooks.mjs.map +1 -1
  321. package/dist/esm/hooks/index.mjs +0 -16
  322. package/dist/esm/hooks/index.mjs.map +1 -1
  323. package/dist/esm/hooks/matchers.mjs +0 -104
  324. package/dist/esm/hooks/matchers.mjs.map +1 -1
  325. package/dist/esm/hooks/types.mjs +0 -8
  326. package/dist/esm/hooks/types.mjs.map +1 -1
  327. package/dist/esm/instrumentation.mjs +0 -14
  328. package/dist/esm/instrumentation.mjs.map +1 -1
  329. package/dist/esm/langfuse.mjs +0 -75
  330. package/dist/esm/langfuse.mjs.map +1 -1
  331. package/dist/esm/langfuseConfig.mjs.map +1 -1
  332. package/dist/esm/langfuseRuntimeContext.mjs +0 -13
  333. package/dist/esm/langfuseRuntimeContext.mjs.map +1 -1
  334. package/dist/esm/langfuseRuntimeScope.mjs +0 -4
  335. package/dist/esm/langfuseRuntimeScope.mjs.map +1 -1
  336. package/dist/esm/langfuseSpanRegistry.mjs +0 -28
  337. package/dist/esm/langfuseSpanRegistry.mjs.map +1 -1
  338. package/dist/esm/langfuseToolOutputTracing.mjs +0 -3
  339. package/dist/esm/langfuseToolOutputTracing.mjs.map +1 -1
  340. package/dist/esm/langfuseTraceShaping.mjs +0 -74
  341. package/dist/esm/langfuseTraceShaping.mjs.map +1 -1
  342. package/dist/esm/llm/anthropic/index.mjs +0 -3
  343. package/dist/esm/llm/anthropic/index.mjs.map +1 -1
  344. package/dist/esm/llm/anthropic/types.mjs.map +1 -1
  345. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +1 -111
  346. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  347. package/dist/esm/llm/anthropic/utils/message_outputs.mjs +0 -1
  348. package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
  349. package/dist/esm/llm/anthropic/utils/stream_events.mjs +0 -8
  350. package/dist/esm/llm/anthropic/utils/stream_events.mjs.map +1 -1
  351. package/dist/esm/llm/anthropic/utils/tools.mjs.map +1 -1
  352. package/dist/esm/llm/bedrock/cachePoints.mjs.map +1 -1
  353. package/dist/esm/llm/bedrock/index.mjs +1 -95
  354. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  355. package/dist/esm/llm/bedrock/toolCache.mjs.map +1 -1
  356. package/dist/esm/llm/bedrock/utils/message_inputs.mjs +0 -78
  357. package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
  358. package/dist/esm/llm/bedrock/utils/message_outputs.mjs +0 -24
  359. package/dist/esm/llm/bedrock/utils/message_outputs.mjs.map +1 -1
  360. package/dist/esm/llm/contextOverflowRecovery.mjs +0 -62
  361. package/dist/esm/llm/contextOverflowRecovery.mjs.map +1 -1
  362. package/dist/esm/llm/fake.mjs.map +1 -1
  363. package/dist/esm/llm/google/index.mjs +2 -21
  364. package/dist/esm/llm/google/index.mjs.map +1 -1
  365. package/dist/esm/llm/google/utils/common.mjs +0 -35
  366. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  367. package/dist/esm/llm/init.mjs +0 -9
  368. package/dist/esm/llm/init.mjs.map +1 -1
  369. package/dist/esm/llm/invoke.mjs +1 -270
  370. package/dist/esm/llm/invoke.mjs.map +1 -1
  371. package/dist/esm/llm/mistral/index.mjs.map +1 -1
  372. package/dist/esm/llm/openai/index.mjs +0 -99
  373. package/dist/esm/llm/openai/index.mjs.map +1 -1
  374. package/dist/esm/llm/openai/streamMetadata.mjs +0 -21
  375. package/dist/esm/llm/openai/streamMetadata.mjs.map +1 -1
  376. package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
  377. package/dist/esm/llm/openrouter/index.mjs +0 -1
  378. package/dist/esm/llm/openrouter/index.mjs.map +1 -1
  379. package/dist/esm/llm/openrouter/toolCache.mjs +0 -6
  380. package/dist/esm/llm/openrouter/toolCache.mjs.map +1 -1
  381. package/dist/esm/llm/preempt.mjs +0 -75
  382. package/dist/esm/llm/preempt.mjs.map +1 -1
  383. package/dist/esm/llm/providers.mjs.map +1 -1
  384. package/dist/esm/llm/request.mjs +0 -10
  385. package/dist/esm/llm/request.mjs.map +1 -1
  386. package/dist/esm/llm/stream/chunkAdapters.mjs +0 -62
  387. package/dist/esm/llm/stream/chunkAdapters.mjs.map +1 -1
  388. package/dist/esm/llm/stream/smoother.mjs +0 -58
  389. package/dist/esm/llm/stream/smoother.mjs.map +1 -1
  390. package/dist/esm/llm/streamLimits.mjs +4 -293
  391. package/dist/esm/llm/streamLimits.mjs.map +1 -1
  392. package/dist/esm/llm/truncation.mjs +0 -36
  393. package/dist/esm/llm/truncation.mjs.map +1 -1
  394. package/dist/esm/llm/vertexai/index.mjs +0 -330
  395. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  396. package/dist/esm/messages/alternation.mjs +0 -43
  397. package/dist/esm/messages/alternation.mjs.map +1 -1
  398. package/dist/esm/messages/anthropicToolCache.mjs +0 -45
  399. package/dist/esm/messages/anthropicToolCache.mjs.map +1 -1
  400. package/dist/esm/messages/assistantPhase.mjs +0 -12
  401. package/dist/esm/messages/assistantPhase.mjs.map +1 -1
  402. package/dist/esm/messages/budget.mjs +0 -9
  403. package/dist/esm/messages/budget.mjs.map +1 -1
  404. package/dist/esm/messages/cache.mjs +0 -172
  405. package/dist/esm/messages/cache.mjs.map +1 -1
  406. package/dist/esm/messages/content.mjs +0 -9
  407. package/dist/esm/messages/content.mjs.map +1 -1
  408. package/dist/esm/messages/contextPruning.mjs +0 -15
  409. package/dist/esm/messages/contextPruning.mjs.map +1 -1
  410. package/dist/esm/messages/contextPruningSettings.mjs +0 -3
  411. package/dist/esm/messages/contextPruningSettings.mjs.map +1 -1
  412. package/dist/esm/messages/core.mjs +0 -48
  413. package/dist/esm/messages/core.mjs.map +1 -1
  414. package/dist/esm/messages/format.mjs +1 -345
  415. package/dist/esm/messages/format.mjs.map +1 -1
  416. package/dist/esm/messages/handoffCue.mjs +0 -36
  417. package/dist/esm/messages/handoffCue.mjs.map +1 -1
  418. package/dist/esm/messages/ids.mjs.map +1 -1
  419. package/dist/esm/messages/injected.mjs +0 -33
  420. package/dist/esm/messages/injected.mjs.map +1 -1
  421. package/dist/esm/messages/langchain.mjs +0 -14
  422. package/dist/esm/messages/langchain.mjs.map +1 -1
  423. package/dist/esm/messages/prune.mjs +1 -184
  424. package/dist/esm/messages/prune.mjs.map +1 -1
  425. package/dist/esm/messages/recency.mjs +0 -32
  426. package/dist/esm/messages/recency.mjs.map +1 -1
  427. package/dist/esm/messages/reducer.mjs +0 -30
  428. package/dist/esm/messages/reducer.mjs.map +1 -1
  429. package/dist/esm/messages/tools.mjs +0 -14
  430. package/dist/esm/messages/tools.mjs.map +1 -1
  431. package/dist/esm/openai/index.mjs.map +1 -1
  432. package/dist/esm/prompts/activityLabel.mjs +9 -79
  433. package/dist/esm/prompts/activityLabel.mjs.map +1 -1
  434. package/dist/esm/responses/index.mjs.map +1 -1
  435. package/dist/esm/run.mjs +2 -538
  436. package/dist/esm/run.mjs.map +1 -1
  437. package/dist/esm/session/AgentSession.mjs +1 -17
  438. package/dist/esm/session/AgentSession.mjs.map +1 -1
  439. package/dist/esm/session/JsonlSessionStore.mjs.map +1 -1
  440. package/dist/esm/session/handlers.mjs +0 -7
  441. package/dist/esm/session/handlers.mjs.map +1 -1
  442. package/dist/esm/session/ids.mjs.map +1 -1
  443. package/dist/esm/session/messageSerialization.mjs +0 -4
  444. package/dist/esm/session/messageSerialization.mjs.map +1 -1
  445. package/dist/esm/stream.mjs +1 -93
  446. package/dist/esm/stream.mjs.map +1 -1
  447. package/dist/esm/summarization/index.mjs +0 -27
  448. package/dist/esm/summarization/index.mjs.map +1 -1
  449. package/dist/esm/summarization/node.mjs +0 -273
  450. package/dist/esm/summarization/node.mjs.map +1 -1
  451. package/dist/esm/tools/BashExecutor.mjs +0 -35
  452. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  453. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +0 -24
  454. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  455. package/dist/esm/tools/Calculator.mjs.map +1 -1
  456. package/dist/esm/tools/CodeExecutor.mjs +0 -13
  457. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  458. package/dist/esm/tools/CodeSessionFileSummary.mjs.map +1 -1
  459. package/dist/esm/tools/ProgrammaticToolCalling.mjs +0 -101
  460. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  461. package/dist/esm/tools/ReadFile.mjs.map +1 -1
  462. package/dist/esm/tools/SkillTool.mjs +0 -5
  463. package/dist/esm/tools/SkillTool.mjs.map +1 -1
  464. package/dist/esm/tools/SubagentTool.mjs +0 -10
  465. package/dist/esm/tools/SubagentTool.mjs.map +1 -1
  466. package/dist/esm/tools/ToolNode.mjs +6 -1038
  467. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  468. package/dist/esm/tools/ToolSearch.mjs +0 -179
  469. package/dist/esm/tools/ToolSearch.mjs.map +1 -1
  470. package/dist/esm/tools/cloudflare/CloudflareBridgeRuntime.mjs.map +1 -1
  471. package/dist/esm/tools/cloudflare/CloudflareProgrammaticToolCalling.mjs.map +1 -1
  472. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs +0 -39
  473. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs.map +1 -1
  474. package/dist/esm/tools/cloudflare/CloudflareSandboxTools.mjs.map +1 -1
  475. package/dist/esm/tools/eagerEventExecution.mjs +0 -6
  476. package/dist/esm/tools/eagerEventExecution.mjs.map +1 -1
  477. package/dist/esm/tools/handlers.mjs +1 -41
  478. package/dist/esm/tools/handlers.mjs.map +1 -1
  479. package/dist/esm/tools/intentArg.mjs +1 -132
  480. package/dist/esm/tools/intentArg.mjs.map +1 -1
  481. package/dist/esm/tools/local/CompileCheckTool.mjs +0 -25
  482. package/dist/esm/tools/local/CompileCheckTool.mjs.map +1 -1
  483. package/dist/esm/tools/local/FileCheckpointer.mjs +0 -23
  484. package/dist/esm/tools/local/FileCheckpointer.mjs.map +1 -1
  485. package/dist/esm/tools/local/LocalCodingTools.mjs +0 -80
  486. package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -1
  487. package/dist/esm/tools/local/LocalExecutionEngine.mjs +0 -126
  488. package/dist/esm/tools/local/LocalExecutionEngine.mjs.map +1 -1
  489. package/dist/esm/tools/local/LocalExecutionTools.mjs.map +1 -1
  490. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs +0 -12
  491. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs.map +1 -1
  492. package/dist/esm/tools/local/attachments.mjs +0 -44
  493. package/dist/esm/tools/local/attachments.mjs.map +1 -1
  494. package/dist/esm/tools/local/bashAst.mjs +0 -16
  495. package/dist/esm/tools/local/bashAst.mjs.map +1 -1
  496. package/dist/esm/tools/local/editStrategies.mjs +0 -14
  497. package/dist/esm/tools/local/editStrategies.mjs.map +1 -1
  498. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs.map +1 -1
  499. package/dist/esm/tools/local/syntaxCheck.mjs +0 -31
  500. package/dist/esm/tools/local/syntaxCheck.mjs.map +1 -1
  501. package/dist/esm/tools/local/textEncoding.mjs +0 -11
  502. package/dist/esm/tools/local/textEncoding.mjs.map +1 -1
  503. package/dist/esm/tools/local/workspaceFS.mjs +0 -33
  504. package/dist/esm/tools/local/workspaceFS.mjs.map +1 -1
  505. package/dist/esm/tools/ptcTimeout.mjs.map +1 -1
  506. package/dist/esm/tools/schema.mjs +0 -8
  507. package/dist/esm/tools/schema.mjs.map +1 -1
  508. package/dist/esm/tools/search/anthropic.mjs +0 -9
  509. package/dist/esm/tools/search/anthropic.mjs.map +1 -1
  510. package/dist/esm/tools/search/content.mjs.map +1 -1
  511. package/dist/esm/tools/search/crw-scraper.mjs +0 -33
  512. package/dist/esm/tools/search/crw-scraper.mjs.map +1 -1
  513. package/dist/esm/tools/search/crw-search.mjs +0 -2
  514. package/dist/esm/tools/search/crw-search.mjs.map +1 -1
  515. package/dist/esm/tools/search/firecrawl.mjs +0 -25
  516. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  517. package/dist/esm/tools/search/format.mjs +0 -30
  518. package/dist/esm/tools/search/format.mjs.map +1 -1
  519. package/dist/esm/tools/search/highlights.mjs +0 -16
  520. package/dist/esm/tools/search/highlights.mjs.map +1 -1
  521. package/dist/esm/tools/search/keenable-scraper.mjs +0 -8
  522. package/dist/esm/tools/search/keenable-scraper.mjs.map +1 -1
  523. package/dist/esm/tools/search/keenable-search.mjs +0 -7
  524. package/dist/esm/tools/search/keenable-search.mjs.map +1 -1
  525. package/dist/esm/tools/search/rerankers.mjs +0 -35
  526. package/dist/esm/tools/search/rerankers.mjs.map +1 -1
  527. package/dist/esm/tools/search/schema.mjs +0 -1
  528. package/dist/esm/tools/search/schema.mjs.map +1 -1
  529. package/dist/esm/tools/search/search.mjs +1 -14
  530. package/dist/esm/tools/search/search.mjs.map +1 -1
  531. package/dist/esm/tools/search/serper-scraper.mjs +0 -46
  532. package/dist/esm/tools/search/serper-scraper.mjs.map +1 -1
  533. package/dist/esm/tools/search/tavily-scraper.mjs.map +1 -1
  534. package/dist/esm/tools/search/tavily-search.mjs.map +1 -1
  535. package/dist/esm/tools/search/tool.mjs +0 -25
  536. package/dist/esm/tools/search/tool.mjs.map +1 -1
  537. package/dist/esm/tools/search/utils.mjs +0 -8
  538. package/dist/esm/tools/search/utils.mjs.map +1 -1
  539. package/dist/esm/tools/skillCatalog.mjs +0 -6
  540. package/dist/esm/tools/skillCatalog.mjs.map +1 -1
  541. package/dist/esm/tools/streamedToolCallSeals.mjs +0 -6
  542. package/dist/esm/tools/streamedToolCallSeals.mjs.map +1 -1
  543. package/dist/esm/tools/subagent/SubagentExecutionRegistry.mjs +0 -2
  544. package/dist/esm/tools/subagent/SubagentExecutionRegistry.mjs.map +1 -1
  545. package/dist/esm/tools/subagent/SubagentExecutor.mjs +3 -213
  546. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  547. package/dist/esm/tools/subagent/SubagentReplay.mjs.map +1 -1
  548. package/dist/esm/tools/subagent/childGraphConfig.mjs +0 -4
  549. package/dist/esm/tools/subagent/childGraphConfig.mjs.map +1 -1
  550. package/dist/esm/tools/subagent/runtimeLimits.mjs.map +1 -1
  551. package/dist/esm/tools/toolOutputReferences.mjs +1 -322
  552. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
  553. package/dist/esm/types/hitl.mjs +0 -5
  554. package/dist/esm/types/hitl.mjs.map +1 -1
  555. package/dist/esm/utils/callbacks.mjs.map +1 -1
  556. package/dist/esm/utils/errors.mjs +14 -165
  557. package/dist/esm/utils/errors.mjs.map +1 -1
  558. package/dist/esm/utils/events.mjs +0 -10
  559. package/dist/esm/utils/events.mjs.map +1 -1
  560. package/dist/esm/utils/graph.mjs.map +1 -1
  561. package/dist/esm/utils/handlers.mjs +0 -3
  562. package/dist/esm/utils/handlers.mjs.map +1 -1
  563. package/dist/esm/utils/llm.mjs +0 -1
  564. package/dist/esm/utils/llm.mjs.map +1 -1
  565. package/dist/esm/utils/misc.mjs +0 -16
  566. package/dist/esm/utils/misc.mjs.map +1 -1
  567. package/dist/esm/utils/proxy.mjs +0 -26
  568. package/dist/esm/utils/proxy.mjs.map +1 -1
  569. package/dist/esm/utils/run.mjs +0 -6
  570. package/dist/esm/utils/run.mjs.map +1 -1
  571. package/dist/esm/utils/schema.mjs +0 -5
  572. package/dist/esm/utils/schema.mjs.map +1 -1
  573. package/dist/esm/utils/title.mjs +0 -6
  574. package/dist/esm/utils/title.mjs.map +1 -1
  575. package/dist/esm/utils/tokens.mjs +0 -113
  576. package/dist/esm/utils/tokens.mjs.map +1 -1
  577. package/dist/esm/utils/toolContent.mjs +0 -41
  578. package/dist/esm/utils/toolContent.mjs.map +1 -1
  579. package/dist/esm/utils/truncation.mjs +0 -61
  580. package/dist/esm/utils/truncation.mjs.map +1 -1
  581. package/package.json +35 -32
  582. package/dist/types/agents/__tests__/promptCacheLiveHelpers.d.ts +0 -52
  583. package/dist/types/test/mockTools.d.ts +0 -28
  584. package/dist/types/utils/__tests__/fixtures/contextOverflowSignatures.d.ts +0 -40
  585. package/src/__tests__/stream.eagerArgsDivergence.test.ts +0 -911
  586. package/src/__tests__/stream.eagerEventExecution.test.ts +0 -5046
  587. package/src/__tests__/stream.streamLimits.test.ts +0 -1982
  588. package/src/agents/__tests__/AgentContext.anthropic.live.test.ts +0 -448
  589. package/src/agents/__tests__/AgentContext.bedrock.live.test.ts +0 -655
  590. package/src/agents/__tests__/AgentContext.openrouter.live.test.ts +0 -128
  591. package/src/agents/__tests__/AgentContext.overflow.test.ts +0 -205
  592. package/src/agents/__tests__/AgentContext.test.ts +0 -2425
  593. package/src/agents/__tests__/projection.test.ts +0 -73
  594. package/src/agents/__tests__/promptCacheLiveHelpers.ts +0 -175
  595. package/src/aggregator.test.ts +0 -1214
  596. package/src/graphs/__tests__/Graph.breakerLifecycle.test.ts +0 -273
  597. package/src/graphs/__tests__/Graph.closeRunStep.test.ts +0 -385
  598. package/src/graphs/__tests__/Graph.contextOverflow.test.ts +0 -1766
  599. package/src/graphs/__tests__/Graph.preemptSignal.test.ts +0 -126
  600. package/src/graphs/__tests__/Graph.reasoning.test.ts +0 -1717
  601. package/src/graphs/__tests__/Graph.subagentResumeState.test.ts +0 -80
  602. package/src/graphs/__tests__/MultiAgentGraph.test.ts +0 -177
  603. package/src/graphs/__tests__/composition.smoke.test.ts +0 -509
  604. package/src/graphs/__tests__/createGraph.test.ts +0 -206
  605. package/src/hooks/__tests__/HookRegistry.test.ts +0 -334
  606. package/src/hooks/__tests__/compactHooks.test.ts +0 -250
  607. package/src/hooks/__tests__/createToolPolicyHook.test.ts +0 -268
  608. package/src/hooks/__tests__/createWorkspacePolicyHook.test.ts +0 -405
  609. package/src/hooks/__tests__/executeHooks.test.ts +0 -1294
  610. package/src/hooks/__tests__/integration.test.ts +0 -337
  611. package/src/hooks/__tests__/matchers.test.ts +0 -238
  612. package/src/hooks/__tests__/preemptBoundary.test.ts +0 -152
  613. package/src/hooks/__tests__/toolHooks.test.ts +0 -669
  614. package/src/llm/__tests__/contextOverflowRecovery.test.ts +0 -401
  615. package/src/llm/__tests__/fallbackOverflow.test.ts +0 -287
  616. package/src/llm/anthropic/Jacob_Lee_Resume_2023.pdf +0 -0
  617. package/src/llm/anthropic/inherited-content-utils.spec.ts +0 -249
  618. package/src/llm/anthropic/inherited-stream-events.spec.ts +0 -1259
  619. package/src/llm/anthropic/inherited-strict.spec.ts +0 -302
  620. package/src/llm/anthropic/llm.spec.ts +0 -3394
  621. package/src/llm/anthropic/utils/cross-provider-reasoning.test.ts +0 -383
  622. package/src/llm/anthropic/utils/cross-provider-server-tools.test.ts +0 -110
  623. package/src/llm/anthropic/utils/server-tool-inputs.test.ts +0 -508
  624. package/src/llm/anthropic/utils/streaming-tool-input.test.ts +0 -361
  625. package/src/llm/anthropic/utils/stripPrefillCache.test.ts +0 -111
  626. package/src/llm/anthropic/utils/tool-id-normalization.test.ts +0 -287
  627. package/src/llm/bedrock/inherited-cache.spec.ts +0 -144
  628. package/src/llm/bedrock/inherited.spec.ts +0 -724
  629. package/src/llm/bedrock/llm.spec.ts +0 -1533
  630. package/src/llm/bedrock/streamSealDispatch.test.ts +0 -331
  631. package/src/llm/bedrock/toolCache.test.ts +0 -194
  632. package/src/llm/bedrock/utils/cross-provider-reasoning.test.ts +0 -131
  633. package/src/llm/bedrock/utils/cross-provider-server-tools.test.ts +0 -122
  634. package/src/llm/bedrock/utils/message_inputs.test.ts +0 -650
  635. package/src/llm/bedrock/utils/message_outputs.test.ts +0 -85
  636. package/src/llm/bedrock/utils/toolResultCachePoint.test.ts +0 -118
  637. package/src/llm/custom-chat-models.smoke.test.ts +0 -1966
  638. package/src/llm/google/data/gettysburg10.wav +0 -0
  639. package/src/llm/google/data/hotdog.jpg +0 -0
  640. package/src/llm/google/inherited-stream-events.spec.ts +0 -350
  641. package/src/llm/google/llm.spec.ts +0 -1388
  642. package/src/llm/google/streamSmoothing.test.ts +0 -121
  643. package/src/llm/google/utils/common.test.ts +0 -196
  644. package/src/llm/invoke.alternation.test.ts +0 -87
  645. package/src/llm/invoke.handoffCue.test.ts +0 -112
  646. package/src/llm/invoke.streamLimits.test.ts +0 -142
  647. package/src/llm/invoke.test.ts +0 -1198
  648. package/src/llm/mistral/streamSmoothing.test.ts +0 -97
  649. package/src/llm/openai/cacheWriteTokens.test.ts +0 -112
  650. package/src/llm/openai/contentBlocks.test.ts +0 -381
  651. package/src/llm/openai/deepseek.test.ts +0 -747
  652. package/src/llm/openai/inherited-deepseek.spec.ts +0 -347
  653. package/src/llm/openai/inherited-xai.spec.ts +0 -416
  654. package/src/llm/openai/llm.spec.ts +0 -1774
  655. package/src/llm/openai/managedRequests.test.ts +0 -182
  656. package/src/llm/openai/sequentialToolCallSeals.test.ts +0 -199
  657. package/src/llm/openai/streamMetadata.spec.ts +0 -86
  658. package/src/llm/openai/streamMetadataDedup.spec.ts +0 -166
  659. package/src/llm/openai/utils/isReasoningModel.test.ts +0 -90
  660. package/src/llm/openai/utils/messages.test.ts +0 -488
  661. package/src/llm/openrouter/reasoning.test.ts +0 -561
  662. package/src/llm/openrouter/toolCache.test.ts +0 -134
  663. package/src/llm/preempt.test.ts +0 -323
  664. package/src/llm/stream/chunkAdapters.test.ts +0 -202
  665. package/src/llm/stream/reassembly.test.ts +0 -241
  666. package/src/llm/stream/smoother.bench.test.ts +0 -155
  667. package/src/llm/stream/smoother.test.ts +0 -519
  668. package/src/llm/streamLimits.test.ts +0 -450
  669. package/src/llm/truncation.test.ts +0 -242
  670. package/src/llm/vertexai/fixThoughtSignatures.test.ts +0 -154
  671. package/src/llm/vertexai/inherited-stream-events.spec.ts +0 -271
  672. package/src/llm/vertexai/llm.spec.ts +0 -159
  673. package/src/llm/vertexai/repairUsageMetadata.test.ts +0 -54
  674. package/src/llm/vertexai/sealStreamedToolCalls.test.ts +0 -88
  675. package/src/llm/vertexai/streamSealDispatch.test.ts +0 -148
  676. package/src/llm/vertexai/streamSmoothing.test.ts +0 -109
  677. package/src/messages/__tests__/anthropicToolCache.test.ts +0 -339
  678. package/src/messages/__tests__/observationMasking.test.ts +0 -312
  679. package/src/messages/__tests__/recency.test.ts +0 -267
  680. package/src/messages/__tests__/tools.test.ts +0 -473
  681. package/src/messages/alternation.test.ts +0 -212
  682. package/src/messages/assistantPhase.test.ts +0 -75
  683. package/src/messages/cache.tail.test.ts +0 -533
  684. package/src/messages/cache.test.ts +0 -2166
  685. package/src/messages/content.test.ts +0 -362
  686. package/src/messages/contextPruning.test.ts +0 -184
  687. package/src/messages/ensureThinkingBlock.test.ts +0 -1427
  688. package/src/messages/foldToollessToolBlocks.test.ts +0 -596
  689. package/src/messages/formatAgentMessages.reducer.test.ts +0 -162
  690. package/src/messages/formatAgentMessages.skills.test.ts +0 -513
  691. package/src/messages/formatAgentMessages.steer.test.ts +0 -598
  692. package/src/messages/formatAgentMessages.test.ts +0 -8111
  693. package/src/messages/formatAgentMessages.tools.test.ts +0 -522
  694. package/src/messages/formatMessage.test.ts +0 -693
  695. package/src/messages/handoffCue.test.ts +0 -96
  696. package/src/messages/injected.test.ts +0 -107
  697. package/src/messages/labelContentByAgent.test.ts +0 -962
  698. package/src/messages/reducer.spec.ts +0 -32
  699. package/src/messages/shiftIndexTokenCountMap.test.ts +0 -81
  700. package/src/messages/tailCacheConversion.test.ts +0 -161
  701. package/src/openai/__tests__/openai.test.ts +0 -337
  702. package/src/responses/__tests__/responses.test.ts +0 -652
  703. package/src/scripts/abort.ts +0 -157
  704. package/src/scripts/activity-labels/captured.json +0 -56
  705. package/src/scripts/activity-labels/checks.cjs +0 -205
  706. package/src/scripts/activity-labels/corpus.cjs +0 -473
  707. package/src/scripts/activity-labels/report.cjs +0 -203
  708. package/src/scripts/activity-labels/rescore.cjs +0 -102
  709. package/src/scripts/activity-labels/run.ts +0 -705
  710. package/src/scripts/activity-labels/variants.ts +0 -71
  711. package/src/scripts/ant_web_search.ts +0 -159
  712. package/src/scripts/ant_web_search_edge_case.ts +0 -163
  713. package/src/scripts/ant_web_search_error_edge_case.ts +0 -149
  714. package/src/scripts/args.ts +0 -48
  715. package/src/scripts/bedrock-cache-debug.ts +0 -250
  716. package/src/scripts/bedrock-content-aggregation-test.ts +0 -266
  717. package/src/scripts/bedrock-merge-test.ts +0 -107
  718. package/src/scripts/bedrock-parallel-tools-test.ts +0 -204
  719. package/src/scripts/bench-prompt-cache.ts +0 -479
  720. package/src/scripts/caching.ts +0 -132
  721. package/src/scripts/cli.ts +0 -172
  722. package/src/scripts/cli2.ts +0 -133
  723. package/src/scripts/cli3.ts +0 -184
  724. package/src/scripts/cli4.ts +0 -191
  725. package/src/scripts/cli5.ts +0 -191
  726. package/src/scripts/code_exec.ts +0 -214
  727. package/src/scripts/code_exec_files.ts +0 -237
  728. package/src/scripts/code_exec_multi_session.ts +0 -237
  729. package/src/scripts/code_exec_ptc.ts +0 -335
  730. package/src/scripts/code_exec_session.ts +0 -283
  731. package/src/scripts/code_exec_simple.ts +0 -148
  732. package/src/scripts/compare_pi_vs_ours.ts +0 -1259
  733. package/src/scripts/content.ts +0 -139
  734. package/src/scripts/context-overflow-probe.ts +0 -997
  735. package/src/scripts/empty_input.ts +0 -137
  736. package/src/scripts/handoff-test.ts +0 -134
  737. package/src/scripts/local_engine.ts +0 -166
  738. package/src/scripts/local_engine_checkpointer.ts +0 -205
  739. package/src/scripts/local_engine_compile.ts +0 -263
  740. package/src/scripts/local_engine_hooks.ts +0 -226
  741. package/src/scripts/local_engine_image.ts +0 -201
  742. package/src/scripts/local_engine_ptc.ts +0 -151
  743. package/src/scripts/local_engine_workspace.ts +0 -258
  744. package/src/scripts/memory.ts +0 -107
  745. package/src/scripts/multi-agent-chain.ts +0 -332
  746. package/src/scripts/multi-agent-conditional.ts +0 -222
  747. package/src/scripts/multi-agent-document-review-chain.ts +0 -198
  748. package/src/scripts/multi-agent-hybrid-flow.ts +0 -311
  749. package/src/scripts/multi-agent-parallel-start.ts +0 -265
  750. package/src/scripts/multi-agent-parallel.ts +0 -395
  751. package/src/scripts/multi-agent-sequence.ts +0 -217
  752. package/src/scripts/multi-agent-subagent.ts +0 -246
  753. package/src/scripts/multi-agent-supervisor.ts +0 -366
  754. package/src/scripts/multi-agent-test.ts +0 -187
  755. package/src/scripts/openrouter_prompt_cache_live.ts +0 -310
  756. package/src/scripts/parallel-asymmetric-tools-test.ts +0 -275
  757. package/src/scripts/parallel-full-metadata-test.ts +0 -241
  758. package/src/scripts/parallel-tools-test.ts +0 -341
  759. package/src/scripts/preempt-probe.ts +0 -330
  760. package/src/scripts/preempt-scenarios.ts +0 -388
  761. package/src/scripts/programmatic_exec.ts +0 -387
  762. package/src/scripts/programmatic_exec_agent.ts +0 -232
  763. package/src/scripts/search.ts +0 -147
  764. package/src/scripts/sequential-full-metadata-test.ts +0 -198
  765. package/src/scripts/session_live.ts +0 -548
  766. package/src/scripts/simple.ts +0 -226
  767. package/src/scripts/single-agent-metadata-test.ts +0 -196
  768. package/src/scripts/stream.ts +0 -141
  769. package/src/scripts/subagent-configurable-inheritance.ts +0 -252
  770. package/src/scripts/subagent-event-driven-debug.ts +0 -190
  771. package/src/scripts/subagent-tools-debug.ts +0 -160
  772. package/src/scripts/subagent-usage-sink.ts +0 -176
  773. package/src/scripts/summarization-recency.ts +0 -462
  774. package/src/scripts/test-custom-prompt-key.ts +0 -145
  775. package/src/scripts/test-handoff-input.ts +0 -170
  776. package/src/scripts/test-handoff-preamble.ts +0 -278
  777. package/src/scripts/test-handoff-steering.ts +0 -430
  778. package/src/scripts/test-multi-agent-list-handoff.ts +0 -418
  779. package/src/scripts/test-parallel-agent-labeling.ts +0 -327
  780. package/src/scripts/test-parallel-handoffs.ts +0 -292
  781. package/src/scripts/test-thinking-handoff-bedrock.ts +0 -154
  782. package/src/scripts/test-thinking-handoff.ts +0 -156
  783. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.ts +0 -166
  784. package/src/scripts/test-tool-before-handoff-role-order.ts +0 -276
  785. package/src/scripts/test-tools-before-handoff.ts +0 -222
  786. package/src/scripts/test_code_api.ts +0 -354
  787. package/src/scripts/thinking-bedrock.ts +0 -160
  788. package/src/scripts/thinking-vertexai.ts +0 -168
  789. package/src/scripts/thinking.ts +0 -172
  790. package/src/scripts/tool_search.ts +0 -153
  791. package/src/scripts/tools.ts +0 -163
  792. package/src/session/__tests__/JsonlSessionStore.test.ts +0 -1463
  793. package/src/session/__tests__/handlers.test.ts +0 -161
  794. package/src/specs/activity-label-observability.live.test.ts +0 -262
  795. package/src/specs/activity-label-observability.test.ts +0 -167
  796. package/src/specs/activity-label-prompt.test.ts +0 -359
  797. package/src/specs/activity-label-trace-seed.test.ts +0 -47
  798. package/src/specs/activity-phase-label.test.ts +0 -306
  799. package/src/specs/agent-handoffs.live.test.ts +0 -140
  800. package/src/specs/agent-handoffs.test.ts +0 -2465
  801. package/src/specs/anthropic.simple.test.ts +0 -453
  802. package/src/specs/ask-user-question-batch.test.ts +0 -289
  803. package/src/specs/ask-user-questions.live.test.ts +0 -185
  804. package/src/specs/ask-user-questions.test.ts +0 -293
  805. package/src/specs/azure.simple.test.ts +0 -502
  806. package/src/specs/bedrock-toolless.live.test.ts +0 -123
  807. package/src/specs/bedrock-truncation.live.test.ts +0 -191
  808. package/src/specs/cache.simple.test.ts +0 -416
  809. package/src/specs/context-accuracy.live.test.ts +0 -409
  810. package/src/specs/context-overflow-recovery.live.test.ts +0 -213
  811. package/src/specs/context-usage-event.test.ts +0 -117
  812. package/src/specs/context-usage.live.test.ts +0 -297
  813. package/src/specs/custom-event-await.test.ts +0 -304
  814. package/src/specs/deepseek.simple.test.ts +0 -290
  815. package/src/specs/deterministic-trace-id.test.ts +0 -43
  816. package/src/specs/discovered-tools.test.ts +0 -217
  817. package/src/specs/durability-checkpoint.integration.test.ts +0 -243
  818. package/src/specs/graph-subagent.live.test.ts +0 -242
  819. package/src/specs/graph-subagent.test.ts +0 -322
  820. package/src/specs/handoffCue.test.ts +0 -165
  821. package/src/specs/langfuse-callbacks.test.ts +0 -1578
  822. package/src/specs/langfuse-config.test.ts +0 -247
  823. package/src/specs/langfuse-instrumentation.test.ts +0 -393
  824. package/src/specs/langfuse-metadata.test.ts +0 -245
  825. package/src/specs/langfuse-routing.integration.test.ts +0 -844
  826. package/src/specs/langfuse-runtime-context.test.ts +0 -92
  827. package/src/specs/langfuse-span-registry.test.ts +0 -87
  828. package/src/specs/langfuse-tool-output-tracing.test.ts +0 -1858
  829. package/src/specs/langfuse-trace-shaping.test.ts +0 -591
  830. package/src/specs/moonshot.simple.test.ts +0 -367
  831. package/src/specs/multi-agent-summarization.test.ts +0 -396
  832. package/src/specs/openai.simple.test.ts +0 -315
  833. package/src/specs/openrouter.simple.test.ts +0 -275
  834. package/src/specs/preemptSeal.test.ts +0 -678
  835. package/src/specs/prune.test.ts +0 -3741
  836. package/src/specs/reasoning.test.ts +0 -201
  837. package/src/specs/run-step-timestamps.test.ts +0 -414
  838. package/src/specs/spec.utils.ts +0 -15
  839. package/src/specs/subagent.test.ts +0 -864
  840. package/src/specs/summarization-unit.test.ts +0 -973
  841. package/src/specs/summarization.test.ts +0 -3823
  842. package/src/specs/summarize-prune.test.ts +0 -376
  843. package/src/specs/thinking-handoff.test.ts +0 -621
  844. package/src/specs/thinking-prune.test.ts +0 -827
  845. package/src/specs/token-accounting-e2e.test.ts +0 -1034
  846. package/src/specs/token-accounting-pipeline.test.ts +0 -1008
  847. package/src/specs/token-distribution-edge-case.test.ts +0 -315
  848. package/src/specs/token-memoization.test.ts +0 -40
  849. package/src/specs/tokens.test.ts +0 -1000
  850. package/src/specs/tool-error-resume.test.ts +0 -194
  851. package/src/specs/tool-error.test.ts +0 -198
  852. package/src/specs/vllm-reasoning-toolcalls.test.ts +0 -340
  853. package/src/stream.dispatch.test.ts +0 -63
  854. package/src/stream.test.ts +0 -144
  855. package/src/summarization/__tests__/aggregator.test.ts +0 -236
  856. package/src/summarization/__tests__/node.test.ts +0 -1996
  857. package/src/summarization/__tests__/trigger.test.ts +0 -149
  858. package/src/summarization/chunkHandler.test.ts +0 -196
  859. package/src/test/mockTools.ts +0 -386
  860. package/src/tools/Calculator.test.ts +0 -278
  861. package/src/tools/__tests__/BashExecutor.test.ts +0 -108
  862. package/src/tools/__tests__/CloudflareSandboxExecution.test.ts +0 -939
  863. package/src/tools/__tests__/CodeApiAuthHeaders.test.ts +0 -858
  864. package/src/tools/__tests__/CodeExecutor.stateful.test.ts +0 -124
  865. package/src/tools/__tests__/LocalExecutionRoots.test.ts +0 -8
  866. package/src/tools/__tests__/LocalExecutionTools.test.ts +0 -2733
  867. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +0 -318
  868. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -1557
  869. package/src/tools/__tests__/ReadFile.test.ts +0 -44
  870. package/src/tools/__tests__/SkillTool.test.ts +0 -442
  871. package/src/tools/__tests__/SubagentExecutor.test.ts +0 -3728
  872. package/src/tools/__tests__/SubagentReplay.test.ts +0 -329
  873. package/src/tools/__tests__/SubagentTool.test.ts +0 -149
  874. package/src/tools/__tests__/ToolNode.breakerSignal.test.ts +0 -595
  875. package/src/tools/__tests__/ToolNode.eagerEventExecution.test.ts +0 -1191
  876. package/src/tools/__tests__/ToolNode.invalidToolCalls.test.ts +0 -757
  877. package/src/tools/__tests__/ToolNode.langfuse.test.ts +0 -57
  878. package/src/tools/__tests__/ToolNode.onResultCompletion.test.ts +0 -736
  879. package/src/tools/__tests__/ToolNode.outputReferences.test.ts +0 -1710
  880. package/src/tools/__tests__/ToolNode.runtimeState.test.ts +0 -120
  881. package/src/tools/__tests__/ToolNode.session.test.ts +0 -1352
  882. package/src/tools/__tests__/ToolNode.streamLimits.test.ts +0 -69
  883. package/src/tools/__tests__/ToolSearch.integration.test.ts +0 -161
  884. package/src/tools/__tests__/ToolSearch.test.ts +0 -1227
  885. package/src/tools/__tests__/annotateMessagesForLLM.test.ts +0 -561
  886. package/src/tools/__tests__/directToolHITLResumeScope.test.ts +0 -980
  887. package/src/tools/__tests__/directToolHooks.test.ts +0 -700
  888. package/src/tools/__tests__/eagerEventExecution.session.test.ts +0 -92
  889. package/src/tools/__tests__/handlers.test.ts +0 -997
  890. package/src/tools/__tests__/hitl.test.ts +0 -4663
  891. package/src/tools/__tests__/intentArg.test.ts +0 -357
  892. package/src/tools/__tests__/intentCoverage.test.ts +0 -139
  893. package/src/tools/__tests__/localToolNames.test.ts +0 -75
  894. package/src/tools/__tests__/skillCatalog.test.ts +0 -161
  895. package/src/tools/__tests__/subagentHooks.test.ts +0 -1651
  896. package/src/tools/__tests__/toolOutputReferences.test.ts +0 -515
  897. package/src/tools/__tests__/workspaceSeam.test.ts +0 -147
  898. package/src/tools/local/__tests__/FileCheckpointer.test.ts +0 -162
  899. package/src/tools/local/__tests__/editStrategies.test.ts +0 -134
  900. package/src/tools/search/content.test.ts +0 -173
  901. package/src/tools/search/crw.test.ts +0 -836
  902. package/src/tools/search/format.test.ts +0 -242
  903. package/src/tools/search/http-agent.test.ts +0 -133
  904. package/src/tools/search/jina-reranker.test.ts +0 -306
  905. package/src/tools/search/keenable-scraper.test.ts +0 -153
  906. package/src/tools/search/keenable.test.ts +0 -183
  907. package/src/tools/search/outcome.test.ts +0 -90
  908. package/src/tools/search/output.md +0 -2775
  909. package/src/tools/search/rag-api-reranker.test.ts +0 -891
  910. package/src/tools/search/source-processing.test.ts +0 -516
  911. package/src/tools/search/tavily.test.ts +0 -965
  912. package/src/tools/search/test.html +0 -884
  913. package/src/tools/search/test.md +0 -643
  914. package/src/tools/subagent/__tests__/SubagentExecutionRegistry.test.ts +0 -637
  915. package/src/tools/subagent/__tests__/SubagentExecutor.lazy.test.ts +0 -3054
  916. package/src/tools/subagent/__tests__/childGraphConfig.test.ts +0 -521
  917. package/src/utils/__tests__/apportion.test.ts +0 -32
  918. package/src/utils/__tests__/errors.test.ts +0 -270
  919. package/src/utils/__tests__/fixtures/contextOverflowSignatures.ts +0 -336
  920. package/src/utils/__tests__/redactSecrets.test.ts +0 -56
  921. package/src/utils/__tests__/truncation.test.ts +0 -66
  922. package/src/utils/llm.test.ts +0 -18
  923. package/src/utils/proxy.test.ts +0 -176
  924. package/src/utils/toolContent.test.ts +0 -1432
@@ -1 +1 @@
1
- {"version":3,"file":"CloudflareProgrammaticToolCalling.cjs","names":["resolveCloudflareSandbox","getCloudflareWorkspaceRoot","execWithClientTimeout","clientExecTimeoutMs","ProgrammaticToolCallingSchema","BashProgrammaticToolCallingSchema","filterBashToolsByUsage","filterToolsByUsage","normalizeToPythonIdentifier","normalizeToBashIdentifier","validateCloudflareBashCommand","executeCloudflareCode","formatCompletedResponse","ProgrammaticToolCallingName","ProgrammaticToolCallingDescription","BashProgrammaticToolCallingDescription"],"sources":["../../../../src/tools/cloudflare/CloudflareProgrammaticToolCalling.ts"],"sourcesContent":["import { tool } from '@langchain/core/tools';\nimport type { DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\n\n/* eslint-disable no-useless-escape -- generated sandbox helper source needs escapes for emitted JS/Python string literals. */\nimport {\n formatCompletedResponse,\n normalizeToPythonIdentifier,\n ProgrammaticToolCallingDescription,\n ProgrammaticToolCallingName,\n ProgrammaticToolCallingSchema,\n filterToolsByUsage,\n} from '@/tools/ProgrammaticToolCalling';\nimport {\n BashProgrammaticToolCallingDescription,\n BashProgrammaticToolCallingSchema,\n filterBashToolsByUsage,\n normalizeToBashIdentifier,\n} from '@/tools/BashProgrammaticToolCalling';\nimport { Constants } from '@/common';\nimport {\n clientExecTimeoutMs,\n execWithClientTimeout,\n executeCloudflareCode,\n getCloudflareWorkspaceRoot,\n resolveCloudflareSandbox,\n validateCloudflareBashCommand,\n} from './CloudflareSandboxExecutionEngine';\n\ntype ProgrammaticParams = {\n code: string;\n timeout?: number;\n lang?: string;\n runtime?: string;\n language?: string;\n};\n\nconst DEFAULT_TIMEOUT = 60000;\nconst MIN_TIMEOUT = 1000;\nconst MAX_TIMEOUT = 300000;\nconst DEFAULT_MAX_OUTPUT_CHARS = 200000;\n\ntype TimeoutSchema = {\n type: 'integer';\n minimum: number;\n maximum: number;\n default: number;\n description: string;\n};\n\ntype CloudflareProgrammaticToolCallingJsonSchema = {\n type: 'object';\n properties: typeof ProgrammaticToolCallingSchema.properties & {\n timeout: TimeoutSchema;\n lang: {\n type: 'string';\n enum: readonly ['py', 'python', 'bash', 'sh'];\n default: 'bash';\n description: string;\n };\n };\n required: readonly ['code'];\n};\n\ntype CloudflareBashProgrammaticToolCallingJsonSchema = {\n type: 'object';\n properties: typeof BashProgrammaticToolCallingSchema.properties & {\n timeout: TimeoutSchema;\n };\n required: readonly ['code'];\n};\n\nconst NATIVE_TOOL_NAMES = new Set<string>([\n Constants.READ_FILE,\n Constants.WRITE_FILE,\n Constants.EDIT_FILE,\n Constants.GREP_SEARCH,\n Constants.GLOB_SEARCH,\n Constants.LIST_DIRECTORY,\n Constants.COMPILE_CHECK,\n Constants.BASH_TOOL,\n Constants.EXECUTE_CODE,\n]);\n\nfunction normalizeTimeout(timeoutMs: number | undefined): number {\n if (timeoutMs == null || !Number.isFinite(timeoutMs)) {\n return DEFAULT_TIMEOUT;\n }\n return Math.max(MIN_TIMEOUT, Math.floor(timeoutMs));\n}\n\nfunction formatTimeout(timeoutMs: number): string {\n return timeoutMs % 1000 === 0\n ? `${timeoutMs / 1000} seconds`\n : `${timeoutMs} milliseconds`;\n}\n\nfunction createTimeoutSchema(timeoutMs?: number): TimeoutSchema {\n const defaultTimeout = normalizeTimeout(timeoutMs);\n const maxTimeout = Math.max(MAX_TIMEOUT, defaultTimeout);\n return {\n type: 'integer',\n minimum: MIN_TIMEOUT,\n maximum: maxTimeout,\n default: defaultTimeout,\n description:\n 'Maximum Cloudflare Sandbox execution time in milliseconds. ' +\n `Default: ${formatTimeout(defaultTimeout)}. Max: ${formatTimeout(maxTimeout)}.`,\n };\n}\n\nfunction clampExecutionTimeout(\n requestedTimeoutMs: number | undefined,\n configuredTimeoutMs: number | undefined\n): number {\n const defaultTimeout = normalizeTimeout(configuredTimeoutMs);\n const maxTimeout = Math.max(MAX_TIMEOUT, defaultTimeout);\n if (requestedTimeoutMs == null || !Number.isFinite(requestedTimeoutMs)) {\n return defaultTimeout;\n }\n return Math.min(\n Math.max(MIN_TIMEOUT, Math.floor(requestedTimeoutMs)),\n maxTimeout\n );\n}\n\nfunction quoteShell(value: string): string {\n if (/^[A-Za-z0-9_/:=.,@%+-]+$/.test(value)) {\n return value;\n }\n const escapedQuote = String.raw`'\\''`;\n return `'${value.replace(/'/g, escapedQuote)}'`;\n}\n\nfunction truncateOutput(\n value: string,\n maxChars = DEFAULT_MAX_OUTPUT_CHARS\n): string {\n if (value.length <= maxChars) {\n return value;\n }\n const head = Math.floor(maxChars * 0.6);\n const tail = maxChars - head;\n const omitted = value.length - maxChars;\n return `${value.slice(0, head)}\\n\\n[... ${omitted} characters truncated ...]\\n\\n${value.slice(\n value.length - tail\n )}`;\n}\n\nfunction withInSandboxTimeout(command: string, timeoutMs: number): string {\n const timeoutSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));\n return `timeout -k 2s ${timeoutSeconds}s ${command}`;\n}\n\nfunction outerTimeoutMs(timeoutMs: number): number {\n return timeoutMs + 5000;\n}\n\nfunction isInSandboxTimeoutExit(exitCode: number | null): boolean {\n return exitCode === 124 || exitCode === 137;\n}\n\nasync function executeGeneratedCloudflareBash(\n command: string,\n config: t.CloudflareSandboxExecutionConfig\n): ReturnType<typeof executeCloudflareCode> {\n const sandbox = await resolveCloudflareSandbox(config);\n const workspaceRoot = getCloudflareWorkspaceRoot(config);\n const shell = config.shell ?? 'bash';\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT;\n const result = await execWithClientTimeout(\n sandbox,\n withInSandboxTimeout(`${shell} -lc ${quoteShell(command)}`, timeoutMs),\n {\n cwd: workspaceRoot,\n env: config.env,\n timeout: outerTimeoutMs(timeoutMs),\n },\n clientExecTimeoutMs(timeoutMs),\n 'cloudflare bash programmatic exec'\n );\n const maxOutputChars = config.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;\n return {\n stdout: truncateOutput(result.stdout, maxOutputChars),\n stderr: truncateOutput(result.stderr, maxOutputChars),\n exitCode: result.exitCode,\n timedOut: isInSandboxTimeoutExit(result.exitCode),\n };\n}\n\nfunction createCloudflareProgrammaticToolCallingSchema(\n config: t.CloudflareSandboxExecutionConfig\n): CloudflareProgrammaticToolCallingJsonSchema {\n return {\n ...ProgrammaticToolCallingSchema,\n properties: {\n ...ProgrammaticToolCallingSchema.properties,\n timeout: createTimeoutSchema(config.timeoutMs),\n lang: {\n type: 'string',\n enum: ['py', 'python', 'bash', 'sh'],\n default: 'bash',\n description:\n 'Cloudflare Sandbox runtime for orchestration code. Defaults to bash; use py/python for Python orchestration.',\n },\n },\n } as const;\n}\n\nfunction createCloudflareBashProgrammaticToolCallingSchema(\n config: t.CloudflareSandboxExecutionConfig\n): CloudflareBashProgrammaticToolCallingJsonSchema {\n return {\n ...BashProgrammaticToolCallingSchema,\n properties: {\n ...BashProgrammaticToolCallingSchema.properties,\n timeout: createTimeoutSchema(config.timeoutMs),\n },\n } as const;\n}\n\nfunction resolveRuntime(params: ProgrammaticParams): 'python' | 'bash' {\n const raw = params.lang ?? params.runtime ?? params.language ?? 'bash';\n return raw === 'py' || raw === 'python' ? 'python' : 'bash';\n}\n\nfunction filterNativeTools(\n toolDefs: t.LCTool[],\n code: string,\n runtime: 'python' | 'bash'\n): t.LCTool[] {\n const nativeDefs = toolDefs.filter((def) => NATIVE_TOOL_NAMES.has(def.name));\n const filter =\n runtime === 'bash' ? filterBashToolsByUsage : filterToolsByUsage;\n return filter(nativeDefs, code);\n}\n\nfunction indent(code: string, spaces = 4): string {\n const prefix = ' '.repeat(spaces);\n return code\n .split('\\n')\n .map((line) => (line === '' ? line : prefix + line))\n .join('\\n');\n}\n\nfunction pythonBoolean(value: boolean | undefined): 'True' | 'False' {\n return value === true ? 'True' : 'False';\n}\n\nfunction createPythonNativeToolSource(\n config: t.CloudflareSandboxExecutionConfig,\n workspaceRoot: string\n): string {\n return `\nimport asyncio, fnmatch, glob, json, os, pathlib, re, shlex, shutil, subprocess, sys, tempfile\n\nWORKSPACE = ${JSON.stringify(workspaceRoot)}\nSHELL = ${JSON.stringify(config.shell ?? 'bash')}\nREAD_ONLY = ${pythonBoolean(config.readOnly)}\nALLOW_DANGEROUS_COMMANDS = ${pythonBoolean(config.allowDangerousCommands)}\nDESTRUCTIVE_TARGET = r\"(?:/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)(?:/?\\\\.?\\\\*|/)?\"\nDANGEROUS_COMMAND_PATTERNS = [\n re.compile(r\"\\\\brm\\\\s+(?:-[^\\\\s]*[rf][^\\\\s]*\\\\s+|-[^\\\\s]*[r][^\\\\s]*\\\\s+-[^\\\\s]*[f][^\\\\s]*\\\\s+)(?:--\\\\s+)?\" + DESTRUCTIVE_TARGET + r\"\\\\s*(?:$|[;&|])\"),\n re.compile(r\"\\\\b(?:mkfs|mkswap|fdisk|parted|diskutil)\\\\b\"),\n re.compile(r\"\\\\bdd\\\\s+[^;&|]*\\\\bof=/dev/\"),\n re.compile(r\"\\\\bchmod\\\\s+-R\\\\s+(?:777|a\\\\+w)\\\\s+(?:--\\\\s+)?\" + DESTRUCTIVE_TARGET + r\"(?:$|\\\\s|[;&|])\"),\n re.compile(r\"\\\\bchown\\\\s+-R\\\\s+[^;&|]+\\\\s+(?:--\\\\s+)?\" + DESTRUCTIVE_TARGET + r\"(?:$|\\\\s|[;&|])\"),\n re.compile(r\":\\\\s*\\\\(\\\\s*\\\\)\\\\s*\\\\{\\\\s*:\\\\s*\\\\|\\\\s*:\\\\s*&\\\\s*\\\\}\\\\s*;\\\\s*:\"),\n]\nQUOTED_DESTRUCTIVE_PATTERNS = [\n re.compile(r\"\\\\brm\\\\s+(?:-[^\\\\s]*[rf][^\\\\s]*\\\\s+){1,3}(?:--\\\\s+)?[\\\\\"']\" + DESTRUCTIVE_TARGET + r\"[\\\\\"']\"),\n re.compile(r\"\\\\bchmod\\\\s+-R\\\\s+(?:777|a\\\\+w)\\\\s+(?:--\\\\s+)?[\\\\\"']\" + DESTRUCTIVE_TARGET + r\"[\\\\\"']\"),\n re.compile(r\"\\\\bchown\\\\s+-R\\\\s+[^;&|]+\\\\s+(?:--\\\\s+)?[\\\\\"']\" + DESTRUCTIVE_TARGET + r\"[\\\\\"']\"),\n]\nNESTED_SHELL_PREFIX = r\"(?:(?:ba|z|da|k)?sh|eval)\\\\s+(?:-l?c\\\\s+)?\"\nNESTED_SHELL_DESTRUCTIVE_PATTERNS = [\n re.compile(NESTED_SHELL_PREFIX + r\"[\\\\\"'][^\\\\\"']*\\\\brm\\\\s+-[^\\\\s\\\\\"']*[rf][^\\\\s\\\\\"']*\\\\s+(?:--\\\\s+)?(?:/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)\"),\n re.compile(NESTED_SHELL_PREFIX + r\"[\\\\\"'][^\\\\\"']*\\\\bchmod\\\\s+-R\\\\s+(?:777|a\\\\+w)\\\\s+(?:--\\\\s+)?(?:/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)\"),\n re.compile(NESTED_SHELL_PREFIX + r\"[\\\\\"'][^\\\\\"']*\\\\bchown\\\\s+-R\\\\s+[^;&|]+\\\\s+(?:--\\\\s+)?(?:/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)\"),\n]\nMUTATING_COMMAND_PATTERN = re.compile(r\"\\\\b(?:rm|mv|cp|touch|mkdir|rmdir|ln|truncate|tee|sed\\\\s+-i|perl\\\\s+-pi|python(?:3)?\\\\s+-c|node\\\\s+-e|npm\\\\s+(?:install|ci|update|publish)|pnpm\\\\s+(?:install|update|publish)|yarn\\\\s+(?:install|add|publish)|git\\\\s+(?:add|commit|checkout|switch|reset|clean|rebase|merge|push|pull|stash|tag|branch)|chmod|chown)\\\\b|(?:^|[^<])>\\\\s*[^&]|\\\\bcat\\\\s+[^|;&]*>\\\\s*\")\nPROTECTED_TARGET_ARG_RE = re.compile(r\"^(?:/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)(?:/?\\\\.?\\\\*|/)?$\")\nDESTRUCTIVE_OP_IN_COMMAND_RE = re.compile(r\"\\\\b(?:rm\\\\s+-[^\\\\s]*[rf]|chmod\\\\s+-R|chown\\\\s+-R)\\\\b\")\n\ndef _is_within_workspace(file_path):\n resolved = os.path.abspath(file_path)\n root = os.path.abspath(WORKSPACE)\n return os.path.commonpath([root, resolved]) == root\n\ndef _resolve(file_path=\".\"):\n raw = file_path or \".\"\n candidate = raw if os.path.isabs(raw) else os.path.join(WORKSPACE, raw)\n resolved = os.path.abspath(candidate)\n if not _is_within_workspace(resolved):\n raise ValueError(f\"Path is outside the Cloudflare sandbox workspace: {file_path}\")\n return resolved\n\ndef _assert_writable(tool_name):\n if READ_ONLY:\n raise PermissionError(f\"{tool_name} is blocked in read-only Cloudflare sandbox mode.\")\n\ndef _strip_quoted_content(command):\n output = []\n quote = None\n escaped = False\n index = 0\n while index < len(command):\n char = command[index]\n if escaped:\n escaped = False\n output.append(\" \")\n index += 1\n continue\n if char == \"\\\\\\\\\":\n escaped = True\n output.append(\" \")\n index += 1\n continue\n if quote is not None:\n if char == quote:\n quote = None\n output.append(\" \")\n index += 1\n continue\n if char in (\"'\", '\"', \"\\`\"):\n quote = char\n output.append(\" \")\n index += 1\n continue\n if char == \"#\":\n while index < len(command) and command[index] != \"\\\\n\":\n output.append(\" \")\n index += 1\n output.append(\"\\\\n\")\n index += 1\n continue\n output.append(char)\n index += 1\n return \"\".join(output)\n\ndef _validate_bash_command(command, args=None):\n errors = []\n normalized = _strip_quoted_content(command)\n if command.strip() == \"\":\n errors.append(\"Command is empty.\")\n if \"\\\\0\" in command:\n errors.append(\"Command contains a NUL byte.\")\n if not ALLOW_DANGEROUS_COMMANDS:\n if any(pattern.search(normalized) for pattern in DANGEROUS_COMMAND_PATTERNS):\n errors.append(\"Command matches a destructive command pattern.\")\n elif any(pattern.search(command) for pattern in QUOTED_DESTRUCTIVE_PATTERNS):\n errors.append(\"Command matches a destructive command pattern (quoted target).\")\n elif any(pattern.search(command) for pattern in NESTED_SHELL_DESTRUCTIVE_PATTERNS):\n errors.append(\"Command matches a destructive command pattern (nested shell payload).\")\n elif args and DESTRUCTIVE_OP_IN_COMMAND_RE.search(command):\n offending = next((str(arg) for arg in args if PROTECTED_TARGET_ARG_RE.search(str(arg))), None)\n if offending is not None:\n errors.append(f\"Command matches a destructive command pattern (protected target \\\\\"{offending}\\\\\" passed via positional arg).\")\n if READ_ONLY and MUTATING_COMMAND_PATTERN.search(normalized):\n errors.append(\"Command appears to mutate files or repository state in read-only Cloudflare sandbox mode.\")\n if errors:\n raise ValueError(\"\\\\n\".join(errors))\n\ndef _line_window(content, offset=None, limit=None):\n start = max((offset or 1) - 1, 0)\n lines = content.split(\"\\\\n\")\n selected = lines[start:] if not limit or limit <= 0 else lines[start:start + limit]\n return \"\\\\n\".join(f\"{start + idx + 1:6d}\\\\t{line}\" for idx, line in enumerate(selected))\n\ndef _run(command, timeout=None, args=None):\n _validate_bash_command(command, args=args)\n completed = subprocess.run(\n [SHELL, \"-lc\", command, \"--\"] + [str(arg) for arg in (args or [])],\n cwd=WORKSPACE,\n capture_output=True,\n text=True,\n timeout=(timeout / 1000 if timeout else None),\n )\n return {\n \"stdout\": completed.stdout,\n \"stderr\": completed.stderr,\n \"exit_code\": completed.returncode,\n }\n\ndef _format_run(result):\n text = \"\"\n if result.get(\"stdout\"):\n text += f\"stdout:\\\\n{result['stdout']}\\\\n\"\n else:\n text += \"stdout: Empty. Ensure you're writing output explicitly.\\\\n\"\n if result.get(\"stderr\"):\n text += f\"stderr:\\\\n{result['stderr']}\\\\n\"\n if result.get(\"exit_code\") not in (None, 0):\n text += f\"exit_code: {result['exit_code']}\\\\n\"\n text += f\"working_directory: {WORKSPACE}\"\n return text.strip()\n\ndef _detect_compile_command():\n if os.path.exists(os.path.join(WORKSPACE, \"tsconfig.json\")):\n return \"typescript\", \"npx --no-install tsc --noEmit\", \"tsconfig.json present\"\n package_json = os.path.join(WORKSPACE, \"package.json\")\n if os.path.exists(package_json):\n try:\n if '\"typescript\"' in open(package_json, encoding=\"utf-8\").read():\n return \"typescript\", \"npx --no-install tsc --noEmit\", \"package.json declares typescript\"\n except Exception:\n pass\n if os.path.exists(os.path.join(WORKSPACE, \"Cargo.toml\")):\n return \"rust\", \"cargo check --message-format=short\", \"Cargo.toml present\"\n if os.path.exists(os.path.join(WORKSPACE, \"go.mod\")):\n return \"go\", \"go vet ./...\", \"go.mod present\"\n if any(os.path.exists(os.path.join(WORKSPACE, name)) for name in [\"pyproject.toml\", \"setup.py\", \"setup.cfg\"]):\n return \"python-compile\", \"python3 -m py_compile $(find . -name '*.py' -not -path './.venv/*' -not -path './node_modules/*')\", \"Python project\"\n return \"unknown\", \"\", \"no recognised project marker\"\n\nasync def bash_tool(command, args=None):\n return _format_run(_run(command, args=args))\n\nasync def execute_code(lang, code, args=None):\n args = args or []\n temp_dir = tempfile.mkdtemp(prefix=\"lc-ptc-\", dir=WORKSPACE)\n try:\n def q(value):\n import shlex\n return shlex.quote(str(value))\n arg_text = \" \".join(q(arg) for arg in args)\n if lang in (\"py\", \"python\"):\n file_path = os.path.join(temp_dir, \"main.py\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"python3 {q(file_path)} {arg_text}\"))\n if lang in (\"js\", \"javascript\"):\n file_path = os.path.join(temp_dir, \"main.js\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"node {q(file_path)} {arg_text}\"))\n if lang in (\"ts\", \"typescript\"):\n file_path = os.path.join(temp_dir, \"main.ts\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"npx --no-install tsx {q(file_path)} {arg_text}\"))\n if lang == \"php\":\n file_path = os.path.join(temp_dir, \"main.php\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"php {q(file_path)} {arg_text}\"))\n if lang == \"go\":\n file_path = os.path.join(temp_dir, \"main.go\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"go run {q(file_path)} {arg_text}\"))\n if lang == \"rs\":\n file_path = os.path.join(temp_dir, \"main.rs\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n binary = os.path.join(temp_dir, \"main-rs\")\n return _format_run(_run(f\"rustc {q(file_path)} -o {q(binary)} && {q(binary)} {arg_text}\"))\n if lang == \"c\":\n file_path = os.path.join(temp_dir, \"main.c\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n binary = os.path.join(temp_dir, \"main-c\")\n return _format_run(_run(f\"cc {q(file_path)} -o {q(binary)} && {q(binary)} {arg_text}\"))\n if lang == \"cpp\":\n file_path = os.path.join(temp_dir, \"main.cpp\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n binary = os.path.join(temp_dir, \"main-cpp\")\n return _format_run(_run(f\"c++ {q(file_path)} -o {q(binary)} && {q(binary)} {arg_text}\"))\n if lang == \"java\":\n file_path = os.path.join(temp_dir, \"Main.java\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"javac {q(file_path)} && java -cp {q(temp_dir)} Main {arg_text}\"))\n if lang == \"r\":\n file_path = os.path.join(temp_dir, \"main.R\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"Rscript {q(file_path)} {arg_text}\"))\n if lang == \"d\":\n file_path = os.path.join(temp_dir, \"main.d\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n binary = os.path.join(temp_dir, \"main-d\")\n return _format_run(_run(f\"dmd {q(file_path)} -of={q(binary)} && {q(binary)} {arg_text}\"))\n if lang == \"f90\":\n file_path = os.path.join(temp_dir, \"main.f90\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n binary = os.path.join(temp_dir, \"main-f90\")\n return _format_run(_run(f\"gfortran {q(file_path)} -o {q(binary)} && {q(binary)} {arg_text}\"))\n if lang in (\"bash\", \"sh\"):\n return _format_run(_run(code, args=args))\n raise ValueError(f\"Unsupported Cloudflare sandbox runtime: {lang}\")\n finally:\n shutil.rmtree(temp_dir, ignore_errors=True)\n\nasync def read_file(path, offset=None, limit=None):\n resolved = _resolve(path)\n with open(resolved, encoding=\"utf-8\") as handle:\n return _line_window(handle.read(), offset, limit)\n\nasync def write_file(path, content):\n _assert_writable(\"write_file\")\n resolved = _resolve(path)\n os.makedirs(os.path.dirname(resolved), exist_ok=True)\n existed = os.path.exists(resolved)\n with open(resolved, \"w\", encoding=\"utf-8\") as handle:\n handle.write(content)\n return f\"{'Overwrote' if existed else 'Created'} {resolved} ({len(content)} chars).\"\n\nasync def edit_file(path, old_text=None, new_text=None, edits=None):\n _assert_writable(\"edit_file\")\n resolved = _resolve(path)\n edits = edits or [{\"old_text\": old_text, \"new_text\": new_text}]\n content = open(resolved, encoding=\"utf-8\").read()\n for edit in edits:\n old = edit.get(\"old_text\") or \"\"\n new = edit.get(\"new_text\") or \"\"\n if content.count(old) != 1:\n raise ValueError(f\"Could not locate old_text exactly once in {path}\")\n content = content.replace(old, new, 1)\n open(resolved, \"w\", encoding=\"utf-8\").write(content)\n return f\"Applied {len(edits)} edit(s) to {resolved}.\"\n\nasync def list_directory(path=\".\"):\n resolved = _resolve(path)\n entries = []\n for name in sorted(os.listdir(resolved)):\n full = os.path.join(resolved, name)\n entries.append((\"dir \" if os.path.isdir(full) else \"file\") + \"\\\\t\" + name)\n return \"\\\\n\".join(entries) or \"Directory is empty.\"\n\nasync def grep_search(pattern, path=\".\", glob=None, max_results=200):\n root = _resolve(path)\n regex = re.compile(pattern)\n out = []\n for current, dirs, files in os.walk(root):\n dirs[:] = [d for d in dirs if d not in {\".git\", \"node_modules\", \".venv\", \"dist\", \"build\"}]\n for name in files:\n rel = os.path.relpath(os.path.join(current, name), root)\n if glob and not fnmatch.fnmatch(rel, glob):\n continue\n try:\n for line_no, line in enumerate(open(os.path.join(current, name), encoding=\"utf-8\", errors=\"ignore\"), 1):\n if regex.search(line):\n out.append(f\"{os.path.join(current, name)}:{line_no}:{line.rstrip()}\")\n if len(out) >= max_results:\n return \"\\\\n\".join(out)\n except Exception:\n pass\n return \"\\\\n\".join(out) if out else \"No matches found.\"\n\nasync def glob_search(pattern, path=\".\", max_results=200):\n root = _resolve(path)\n target = pattern if os.path.isabs(pattern) else os.path.join(root, pattern)\n matches = []\n for match in glob_module.glob(target, recursive=True):\n resolved = os.path.abspath(match)\n if _is_within_workspace(resolved):\n matches.append(resolved)\n if len(matches) >= max_results:\n break\n return \"\\\\n\".join(matches) if matches else \"No files found.\"\n\nasync def compile_check(command=None, timeout_ms=None):\n kind, detected, reason = _detect_compile_command()\n command = command or detected\n if not command:\n return f\"compile_check: {reason}. Pass an explicit command to override.\"\n result = _run(command, timeout_ms)\n status = \"PASSED\" if result[\"exit_code\"] == 0 else \"FAILED\"\n return f\"compile_check ({kind}) {status} via {command}\\\\n\\\\nstdout:\\\\n{result['stdout']}\\\\nstderr:\\\\n{result['stderr']}\\\\nworking_directory: {WORKSPACE}\\\\nreason: {reason}\"\n\n# Avoid shadowing the glob_search function argument named \"glob\".\nglob_module = glob\n`.trim();\n}\n\nfunction createNodeNativeToolSource(\n config: t.CloudflareSandboxExecutionConfig,\n workspaceRoot: string\n): string {\n return `\nconst fs = require(\"fs\");\nconst fsp = fs.promises;\nconst path = require(\"path\");\nconst cp = require(\"child_process\");\n\nconst WORKSPACE = ${JSON.stringify(workspaceRoot)};\nconst SHELL = ${JSON.stringify(config.shell ?? 'bash')};\nconst READ_ONLY = ${JSON.stringify(config.readOnly === true)};\nconst ALLOW_DANGEROUS_COMMANDS = ${JSON.stringify(config.allowDangerousCommands === true)};\nconst DESTRUCTIVE_TARGET = \"(?:\\\\\\\\/|~|\\\\\\\\$\\\\\\\\{?HOME\\\\\\\\}?|\\\\\\\\.)(?:\\\\\\\\/?\\\\\\\\.?\\\\\\\\*|\\\\\\\\/)?\";\nconst DANGEROUS_COMMAND_PATTERNS = [\n new RegExp(\"\\\\\\\\brm\\\\\\\\s+(?:-[^\\\\\\\\s]*[rf][^\\\\\\\\s]*\\\\\\\\s+|-[^\\\\\\\\s]*[r][^\\\\\\\\s]*\\\\\\\\s+-[^\\\\\\\\s]*[f][^\\\\\\\\s]*\\\\\\\\s+)(?:--\\\\\\\\s+)?\" + DESTRUCTIVE_TARGET + \"\\\\\\\\s*(?:$|[;&|])\"),\n /\\\\b(?:mkfs|mkswap|fdisk|parted|diskutil)\\\\b/,\n /\\\\bdd\\\\s+[^;&|]*\\\\bof=\\\\/dev\\\\//,\n new RegExp(\"\\\\\\\\bchmod\\\\\\\\s+-R\\\\\\\\s+(?:777|a\\\\\\\\+w)\\\\\\\\s+(?:--\\\\\\\\s+)?\" + DESTRUCTIVE_TARGET + \"(?:$|\\\\\\\\s|[;&|])\"),\n new RegExp(\"\\\\\\\\bchown\\\\\\\\s+-R\\\\\\\\s+[^;&|]+\\\\\\\\s+(?:--\\\\\\\\s+)?\" + DESTRUCTIVE_TARGET + \"(?:$|\\\\\\\\s|[;&|])\"),\n /:\\\\s*\\\\(\\\\s*\\\\)\\\\s*\\\\{\\\\s*:\\\\s*\\\\|\\\\s*:\\\\s*&\\\\s*\\\\}\\\\s*;\\\\s*:/,\n];\nconst QUOTED_DESTRUCTIVE_PATTERNS = [\n new RegExp(\"\\\\\\\\brm\\\\\\\\s+(?:-[^\\\\\\\\s]*[rf][^\\\\\\\\s]*\\\\\\\\s+){1,3}(?:--\\\\\\\\s+)?[\\\\\\\"']\" + DESTRUCTIVE_TARGET + \"[\\\\\\\"']\"),\n new RegExp(\"\\\\\\\\bchmod\\\\\\\\s+-R\\\\\\\\s+(?:777|a\\\\\\\\+w)\\\\\\\\s+(?:--\\\\\\\\s+)?[\\\\\\\"']\" + DESTRUCTIVE_TARGET + \"[\\\\\\\"']\"),\n new RegExp(\"\\\\\\\\bchown\\\\\\\\s+-R\\\\\\\\s+[^;&|]+\\\\\\\\s+(?:--\\\\\\\\s+)?[\\\\\\\"']\" + DESTRUCTIVE_TARGET + \"[\\\\\\\"']\"),\n];\nconst NESTED_SHELL_PREFIX = \"(?:(?:ba|z|da|k)?sh|eval)\\\\\\\\s+(?:-l?c\\\\\\\\s+)?\";\nconst NESTED_SHELL_DESTRUCTIVE_PATTERNS = [\n new RegExp(NESTED_SHELL_PREFIX + \"[\\\\\\\"'][^\\\\\\\"']*\\\\\\\\brm\\\\\\\\s+-[^\\\\\\\\s\\\\\\\"']*[rf][^\\\\\\\\s\\\\\\\"']*\\\\\\\\s+(?:--\\\\\\\\s+)?(?:\\\\\\\\/|~|\\\\\\\\$\\\\\\\\{?HOME\\\\\\\\}?|\\\\\\\\.)\"),\n new RegExp(NESTED_SHELL_PREFIX + \"[\\\\\\\"'][^\\\\\\\"']*\\\\\\\\bchmod\\\\\\\\s+-R\\\\\\\\s+(?:777|a\\\\\\\\+w)\\\\\\\\s+(?:--\\\\\\\\s+)?(?:\\\\\\\\/|~|\\\\\\\\$\\\\\\\\{?HOME\\\\\\\\}?|\\\\\\\\.)\"),\n new RegExp(NESTED_SHELL_PREFIX + \"[\\\\\\\"'][^\\\\\\\"']*\\\\\\\\bchown\\\\\\\\s+-R\\\\\\\\s+[^;&|]+\\\\\\\\s+(?:--\\\\\\\\s+)?(?:\\\\\\\\/|~|\\\\\\\\$\\\\\\\\{?HOME\\\\\\\\}?|\\\\\\\\.)\"),\n];\nconst MUTATING_COMMAND_PATTERN = /\\\\b(?:rm|mv|cp|touch|mkdir|rmdir|ln|truncate|tee|sed\\\\s+-i|perl\\\\s+-pi|python(?:3)?\\\\s+-c|node\\\\s+-e|npm\\\\s+(?:install|ci|update|publish)|pnpm\\\\s+(?:install|update|publish)|yarn\\\\s+(?:install|add|publish)|git\\\\s+(?:add|commit|checkout|switch|reset|clean|rebase|merge|push|pull|stash|tag|branch)|chmod|chown)\\\\b|(?:^|[^<])>\\\\s*[^&]|\\\\bcat\\\\s+[^|;&]*>\\\\s*/;\nconst PROTECTED_TARGET_ARG_RE = /^(?:\\\\/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)(?:\\\\/?\\\\.?\\\\*|\\\\/)?$/;\nconst DESTRUCTIVE_OP_IN_COMMAND_RE = /\\\\b(?:rm\\\\s+-[^\\\\s]*[rf]|chmod\\\\s+-R|chown\\\\s+-R)\\\\b/;\n\nfunction resolvePath(filePath) {\n const raw = filePath || \".\";\n const candidate = path.isAbsolute(raw) ? raw : path.join(WORKSPACE, raw);\n const resolved = path.resolve(candidate);\n const root = path.resolve(WORKSPACE);\n const relative = path.relative(root, resolved);\n if (relative && (relative.startsWith(\"..\") || path.isAbsolute(relative))) {\n throw new Error(\"Path is outside the Cloudflare sandbox workspace: \" + filePath);\n }\n return resolved;\n}\n\nfunction assertWritable(toolName) {\n if (READ_ONLY) {\n throw new Error(toolName + \" is blocked in read-only Cloudflare sandbox mode.\");\n }\n}\n\nfunction stripQuotedContent(command) {\n let output = \"\";\n let quote;\n let escaped = false;\n for (let index = 0; index < command.length; index++) {\n const char = command[index];\n if (escaped) {\n escaped = false;\n output += \" \";\n continue;\n }\n if (char === \"\\\\\\\\\") {\n escaped = true;\n output += \" \";\n continue;\n }\n if (quote != null) {\n if (char === quote) quote = undefined;\n output += \" \";\n continue;\n }\n if (char === \"\\\\\\\"\" || char === \"'\" || char === \"\\`\") {\n quote = char;\n output += \" \";\n continue;\n }\n if (char === \"#\") {\n while (index < command.length && command[index] !== \"\\\\n\") {\n output += \" \";\n index += 1;\n }\n output += \"\\\\n\";\n continue;\n }\n output += char;\n }\n return output;\n}\n\nfunction validateBashCommand(command, args) {\n const errors = [];\n const normalized = stripQuotedContent(command);\n if (command.trim() === \"\") {\n errors.push(\"Command is empty.\");\n }\n if (command.includes(\"\\\\0\")) {\n errors.push(\"Command contains a NUL byte.\");\n }\n if (!ALLOW_DANGEROUS_COMMANDS) {\n if (DANGEROUS_COMMAND_PATTERNS.some((pattern) => pattern.test(normalized))) {\n errors.push(\"Command matches a destructive command pattern.\");\n } else if (QUOTED_DESTRUCTIVE_PATTERNS.some((pattern) => pattern.test(command))) {\n errors.push(\"Command matches a destructive command pattern (quoted target).\");\n } else if (NESTED_SHELL_DESTRUCTIVE_PATTERNS.some((pattern) => pattern.test(command))) {\n errors.push(\"Command matches a destructive command pattern (nested shell payload).\");\n } else if ((args || []).length > 0 && DESTRUCTIVE_OP_IN_COMMAND_RE.test(command)) {\n const offending = (args || []).map(String).find((arg) => PROTECTED_TARGET_ARG_RE.test(arg));\n if (offending !== undefined) {\n errors.push(\"Command matches a destructive command pattern (protected target \\\\\"\" + offending + \"\\\\\" passed via positional arg).\");\n }\n }\n }\n if (READ_ONLY && MUTATING_COMMAND_PATTERN.test(normalized)) {\n errors.push(\"Command appears to mutate files or repository state in read-only Cloudflare sandbox mode.\");\n }\n if (errors.length > 0) {\n throw new Error(errors.join(\"\\\\n\"));\n }\n}\n\nfunction lineWindow(content, offset, limit) {\n const start = Math.max((offset || 1) - 1, 0);\n const lines = content.split(\"\\\\n\");\n const selected = !limit || limit <= 0 ? lines.slice(start) : lines.slice(start, start + limit);\n return selected.map((line, index) => String(start + index + 1).padStart(6, \" \") + \"\\\\t\" + line).join(\"\\\\n\");\n}\n\nfunction quote(value) {\n const text = String(value);\n if (text === \"\") return \"''\";\n if (/^[A-Za-z0-9_/:=.,@%+-]+$/.test(text)) return text;\n return \"'\" + text.replace(/'/g, \"'\\\\\\\\''\") + \"'\";\n}\n\nfunction run(command, timeoutMs, args) {\n validateBashCommand(command, args);\n return new Promise((resolve) => {\n const child = cp.spawn(SHELL, [\"-lc\", command, \"--\", ...((args || []).map(String))], {\n cwd: WORKSPACE,\n env: process.env,\n });\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = timeoutMs\n ? setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGTERM\");\n }, timeoutMs)\n : null;\n\n child.stdout.on(\"data\", (chunk) => {\n stdout += chunk.toString();\n });\n child.stderr.on(\"data\", (chunk) => {\n stderr += chunk.toString();\n });\n child.on(\"error\", (error) => {\n if (timer) clearTimeout(timer);\n resolve({ stdout, stderr: stderr + error.message, exit_code: 1, timed_out: timedOut });\n });\n child.on(\"close\", (code) => {\n if (timer) clearTimeout(timer);\n resolve({ stdout, stderr, exit_code: timedOut ? null : code, timed_out: timedOut });\n });\n });\n}\n\nfunction formatRun(result) {\n let text = \"\";\n if (result.stdout) {\n text += \"stdout:\\\\n\" + result.stdout + \"\\\\n\";\n } else {\n text += \"stdout: Empty. Ensure you're writing output explicitly.\\\\n\";\n }\n if (result.stderr) {\n text += \"stderr:\\\\n\" + result.stderr + \"\\\\n\";\n }\n if (result.timed_out) {\n text += \"timed_out: true\\\\n\";\n }\n if (result.exit_code !== null && result.exit_code !== undefined && result.exit_code !== 0) {\n text += \"exit_code: \" + result.exit_code + \"\\\\n\";\n }\n text += \"working_directory: \" + WORKSPACE;\n return text.trim();\n}\n\nasync function detectCompileCommand() {\n async function exists(name) {\n try {\n await fsp.access(path.join(WORKSPACE, name));\n return true;\n } catch {\n return false;\n }\n }\n if (await exists(\"tsconfig.json\")) {\n return [\"typescript\", \"npx --no-install tsc --noEmit\", \"tsconfig.json present\"];\n }\n if (await exists(\"package.json\")) {\n try {\n if ((await fsp.readFile(path.join(WORKSPACE, \"package.json\"), \"utf8\")).includes('\"typescript\"')) {\n return [\"typescript\", \"npx --no-install tsc --noEmit\", \"package.json declares typescript\"];\n }\n } catch {}\n }\n if (await exists(\"Cargo.toml\")) return [\"rust\", \"cargo check --message-format=short\", \"Cargo.toml present\"];\n if (await exists(\"go.mod\")) return [\"go\", \"go vet ./...\", \"go.mod present\"];\n if (await exists(\"pyproject.toml\") || await exists(\"setup.py\") || await exists(\"setup.cfg\")) {\n return [\"python-compile\", \"python3 -m py_compile $(find . -name '*.py' -not -path './.venv/*' -not -path './node_modules/*')\", \"Python project\"];\n }\n return [\"unknown\", \"\", \"no recognised project marker\"];\n}\n\nfunction globToRegExp(pattern) {\n const escaped = pattern.replace(/[|\\\\\\\\{}()[\\\\]^$+*?.]/g, \"\\\\\\\\$&\");\n return new RegExp(\"^\" + escaped.replace(/\\\\\\\\\\\\*\\\\\\\\\\\\*/g, \".*\").replace(/\\\\\\\\\\\\*/g, \"[^/]*\") + \"$\");\n}\n\nfunction globMatch(relativePath, pattern) {\n const matcher = globToRegExp(pattern);\n return matcher.test(relativePath) || matcher.test(path.basename(relativePath));\n}\n\nasync function walkFiles(root, visit) {\n const entries = await fsp.readdir(root, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(root, entry.name);\n if (entry.isDirectory()) {\n if ([\".git\", \"node_modules\", \".venv\", \"dist\", \"build\"].includes(entry.name)) continue;\n await walkFiles(full, visit);\n } else if (entry.isFile()) {\n await visit(full);\n }\n }\n}\n\nasync function bash_tool(payload) {\n return formatRun(await run(payload.command, undefined, payload.args));\n}\n\nasync function execute_code(payload) {\n const lang = payload.lang;\n const code = payload.code;\n const args = payload.args || [];\n const tempDir = await fsp.mkdtemp(path.join(WORKSPACE, \"lc-ptc-\"));\n try {\n const argText = args.map(quote).join(\" \");\n async function writeAndRun(fileName, command) {\n const filePath = path.join(tempDir, fileName);\n await fsp.writeFile(filePath, code, \"utf8\");\n return formatRun(await run(command(filePath, argText), undefined, []));\n }\n if (lang === \"py\" || lang === \"python\") {\n return writeAndRun(\"main.py\", (filePath, argText) => \"python3 \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"js\" || lang === \"javascript\") {\n return writeAndRun(\"main.js\", (filePath, argText) => \"node \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"ts\" || lang === \"typescript\") {\n return writeAndRun(\"main.ts\", (filePath, argText) => \"npx --no-install tsx \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"php\") {\n return writeAndRun(\"main.php\", (filePath, argText) => \"php \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"go\") {\n return writeAndRun(\"main.go\", (filePath, argText) => \"go run \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"rs\") {\n return writeAndRun(\"main.rs\", (filePath, argText) => {\n const binary = path.join(tempDir, \"main-rs\");\n return \"rustc \" + quote(filePath) + \" -o \" + quote(binary) + \" && \" + quote(binary) + \" \" + argText;\n });\n }\n if (lang === \"c\") {\n return writeAndRun(\"main.c\", (filePath, argText) => {\n const binary = path.join(tempDir, \"main-c\");\n return \"cc \" + quote(filePath) + \" -o \" + quote(binary) + \" && \" + quote(binary) + \" \" + argText;\n });\n }\n if (lang === \"cpp\") {\n return writeAndRun(\"main.cpp\", (filePath, argText) => {\n const binary = path.join(tempDir, \"main-cpp\");\n return \"c++ \" + quote(filePath) + \" -o \" + quote(binary) + \" && \" + quote(binary) + \" \" + argText;\n });\n }\n if (lang === \"java\") {\n return writeAndRun(\"Main.java\", (filePath, argText) => \"javac \" + quote(filePath) + \" && java -cp \" + quote(tempDir) + \" Main \" + argText);\n }\n if (lang === \"r\") {\n return writeAndRun(\"main.R\", (filePath, argText) => \"Rscript \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"d\") {\n return writeAndRun(\"main.d\", (filePath, argText) => {\n const binary = path.join(tempDir, \"main-d\");\n return \"dmd \" + quote(filePath) + \" -of=\" + quote(binary) + \" && \" + quote(binary) + \" \" + argText;\n });\n }\n if (lang === \"f90\") {\n return writeAndRun(\"main.f90\", (filePath, argText) => {\n const binary = path.join(tempDir, \"main-f90\");\n return \"gfortran \" + quote(filePath) + \" -o \" + quote(binary) + \" && \" + quote(binary) + \" \" + argText;\n });\n }\n if (lang === \"bash\" || lang === \"sh\") {\n return formatRun(await run(code, undefined, args));\n }\n throw new Error(\"Unsupported Cloudflare sandbox runtime: \" + lang);\n } finally {\n await fsp.rm(tempDir, { recursive: true, force: true });\n }\n}\n\nasync function read_file(payload) {\n const resolved = resolvePath(payload.path);\n return lineWindow(await fsp.readFile(resolved, \"utf8\"), payload.offset, payload.limit);\n}\n\nasync function write_file(payload) {\n assertWritable(\"write_file\");\n const resolved = resolvePath(payload.path);\n await fsp.mkdir(path.dirname(resolved), { recursive: true });\n const existed = fs.existsSync(resolved);\n await fsp.writeFile(resolved, payload.content, \"utf8\");\n return (existed ? \"Overwrote \" : \"Created \") + resolved + \" (\" + payload.content.length + \" chars).\";\n}\n\nasync function edit_file(payload) {\n assertWritable(\"edit_file\");\n const resolved = resolvePath(payload.path);\n const edits = payload.edits || [{ old_text: payload.old_text, new_text: payload.new_text }];\n let content = await fsp.readFile(resolved, \"utf8\");\n for (const edit of edits) {\n const oldText = edit.old_text || \"\";\n const newText = edit.new_text || \"\";\n if (oldText === \"\" || content.split(oldText).length - 1 !== 1) {\n throw new Error(\"Could not locate old_text exactly once in \" + payload.path);\n }\n content = content.replace(oldText, newText);\n }\n await fsp.writeFile(resolved, content, \"utf8\");\n return \"Applied \" + edits.length + \" edit(s) to \" + resolved + \".\";\n}\n\nasync function list_directory(payload) {\n const resolved = resolvePath(payload.path || \".\");\n const entries = await fsp.readdir(resolved, { withFileTypes: true });\n const lines = entries\n .sort((a, b) => a.name.localeCompare(b.name))\n .map((entry) => (entry.isDirectory() ? \"dir\" : \"file\") + \"\\\\t\" + entry.name);\n return lines.join(\"\\\\n\") || \"Directory is empty.\";\n}\n\nasync function grep_search(payload) {\n const root = resolvePath(payload.path || \".\");\n const regex = new RegExp(payload.pattern);\n const maxResults = payload.max_results || 200;\n const out = [];\n await walkFiles(root, async (filePath) => {\n if (out.length >= maxResults) return;\n const relative = path.relative(root, filePath);\n if (payload.glob && !globMatch(relative, payload.glob)) return;\n let text = \"\";\n try {\n text = await fsp.readFile(filePath, \"utf8\");\n } catch {\n return;\n }\n text.split(\"\\\\n\").forEach((line, index) => {\n if (out.length < maxResults && regex.test(line)) {\n out.push(filePath + \":\" + (index + 1) + \":\" + line);\n }\n });\n });\n return out.join(\"\\\\n\") || \"No matches found.\";\n}\n\nasync function glob_search(payload) {\n const root = resolvePath(payload.path || \".\");\n const maxResults = payload.max_results || 200;\n const out = [];\n await walkFiles(root, async (filePath) => {\n if (out.length >= maxResults) return;\n const relative = path.relative(root, filePath);\n if (globMatch(relative, payload.pattern)) out.push(filePath);\n });\n return out.join(\"\\\\n\") || \"No files found.\";\n}\n\nasync function compile_check(payload) {\n const [kind, detected, reason] = await detectCompileCommand();\n const command = payload.command || detected;\n if (!command) {\n return \"compile_check: \" + reason + \". Pass an explicit command to override.\";\n }\n const result = await run(command, payload.timeout_ms);\n const status = result.exit_code === 0 ? \"PASSED\" : \"FAILED\";\n return \"compile_check (\" + kind + \") \" + status + \" via \" + command + \"\\\\n\\\\nstdout:\\\\n\" + result.stdout + \"\\\\nstderr:\\\\n\" + result.stderr + \"\\\\nworking_directory: \" + WORKSPACE + \"\\\\nreason: \" + reason;\n}\n\nconst TOOLS = {\n bash_tool,\n execute_code,\n read_file,\n write_file,\n edit_file,\n list_directory,\n grep_search,\n glob_search,\n compile_check,\n};\n\nasync function main() {\n const name = process.argv[2];\n const payload = JSON.parse(process.argv[3] || \"{}\");\n if (!TOOLS[name]) throw new Error(\"Unknown tool: \" + name);\n const result = await TOOLS[name](payload);\n process.stdout.write(typeof result === \"string\" ? result : JSON.stringify(result));\n}\n\nmain().catch((error) => {\n console.error(error && error.stack ? error.stack : String(error));\n process.exit(1);\n});\n`.trim();\n}\n\nfunction createPythonProgram(\n userCode: string,\n toolDefs: t.LCTool[],\n config: t.CloudflareSandboxExecutionConfig,\n workspaceRoot: string\n): string {\n const aliases = toolDefs\n .map((def) => {\n const pythonName = normalizeToPythonIdentifier(def.name);\n return NATIVE_TOOL_NAMES.has(def.name) && pythonName !== def.name\n ? `${pythonName} = globals()[${JSON.stringify(def.name)}]`\n : '';\n })\n .filter(Boolean)\n .join('\\n');\n return `${createPythonNativeToolSource(config, workspaceRoot)}\n${aliases}\n\nasync def __lc_user_main__():\n${indent(userCode)}\n\nasyncio.run(__lc_user_main__())\n`;\n}\n\nfunction createBashProgram(\n userCode: string,\n toolDefs: t.LCTool[],\n config: t.CloudflareSandboxExecutionConfig,\n workspaceRoot: string\n): string {\n const helper = createNodeNativeToolSource(config, workspaceRoot);\n const functions = toolDefs\n .map((def) => {\n const bashName = normalizeToBashIdentifier(def.name);\n if (!NATIVE_TOOL_NAMES.has(def.name)) {\n return '';\n }\n return `${bashName}() { node \"$__LC_TOOL_HELPER\" ${JSON.stringify(def.name)} \"$1\"; }`;\n })\n .filter(Boolean)\n .join('\\n');\n return `\nset -euo pipefail\ncommand -v node >/dev/null 2>&1 || { echo \"Cloudflare programmatic tool calling requires node in the sandbox image.\" >&2; exit 127; }\n__LC_TOOL_HELPER=\"$(mktemp /tmp/lc-tools.XXXXXX.js)\"\ncat > \"$__LC_TOOL_HELPER\" <<'JS'\n${helper}\nJS\ntrap 'rm -f \"$__LC_TOOL_HELPER\"' EXIT\n${functions}\n${userCode}\n`.trim();\n}\n\nasync function runProgrammatic(args: {\n params: ProgrammaticParams;\n config?: { toolCall?: unknown };\n cloudflareConfig: t.CloudflareSandboxExecutionConfig;\n runtime: 'python' | 'bash';\n}): Promise<[string, t.ProgrammaticExecutionArtifact]> {\n const toolCall = (args.config?.toolCall ??\n {}) as Partial<t.ProgrammaticCache>;\n const toolDefs = toolCall.toolDefs ?? [];\n const effectiveTools = filterNativeTools(\n toolDefs,\n args.params.code,\n args.runtime\n );\n const timeoutMs = clampExecutionTimeout(\n args.params.timeout,\n args.cloudflareConfig.timeoutMs\n );\n const workspaceRoot = getCloudflareWorkspaceRoot(args.cloudflareConfig);\n let result: Awaited<ReturnType<typeof executeCloudflareCode>>;\n\n if (args.runtime === 'bash') {\n await validateCloudflareBashCommand(args.params.code, [], {\n ...args.cloudflareConfig,\n timeoutMs,\n });\n result = await executeGeneratedCloudflareBash(\n createBashProgram(\n args.params.code,\n effectiveTools,\n args.cloudflareConfig,\n workspaceRoot\n ),\n { ...args.cloudflareConfig, timeoutMs }\n );\n } else {\n result = await executeCloudflareCode(\n {\n lang: 'py',\n code: createPythonProgram(\n args.params.code,\n effectiveTools,\n args.cloudflareConfig,\n workspaceRoot\n ),\n },\n { ...args.cloudflareConfig, timeoutMs }\n );\n }\n\n if (result.exitCode !== 0 || result.timedOut) {\n throw new Error(\n result.stderr !== ''\n ? result.stderr\n : `Cloudflare ${args.runtime} programmatic execution exited with code ${result.exitCode ?? 'unknown'}`\n );\n }\n\n return formatCompletedResponse({\n status: 'completed',\n session_id: 'cloudflare-sandbox',\n stdout: result.stdout,\n stderr: result.stderr,\n files: [],\n });\n}\n\nexport function createCloudflareProgrammaticToolCallingTool(\n cloudflareConfig: t.CloudflareSandboxExecutionConfig\n): DynamicStructuredTool {\n return tool(\n async (rawParams, config) => {\n const params = rawParams as ProgrammaticParams;\n return runProgrammatic({\n params,\n config,\n cloudflareConfig,\n runtime: resolveRuntime(params),\n });\n },\n {\n name: ProgrammaticToolCallingName,\n description: `${ProgrammaticToolCallingDescription}\\n\\nCloudflare Sandbox engine: exposes the built-in coding tools inside the sandbox process. Non-coding host tools are not callable from this in-sandbox programmatic runner.`,\n schema: createCloudflareProgrammaticToolCallingSchema(cloudflareConfig),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createCloudflareBashProgrammaticToolCallingTool(\n cloudflareConfig: t.CloudflareSandboxExecutionConfig\n): DynamicStructuredTool {\n return tool(\n async (rawParams, config) => {\n const params = rawParams as ProgrammaticParams;\n return runProgrammatic({\n params,\n config,\n cloudflareConfig,\n runtime: 'bash',\n });\n },\n {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n description: `${BashProgrammaticToolCallingDescription}\\n\\nCloudflare Sandbox engine: exposes the built-in coding tools as bash functions inside the sandbox process. Non-coding host tools are not callable from this in-sandbox programmatic runner.`,\n schema:\n createCloudflareBashProgrammaticToolCallingSchema(cloudflareConfig),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"mappings":";;;;;;;AAqCA,MAAM,kBAAkB;AACxB,MAAM,cAAc;AACpB,MAAM,cAAc;AACpB,MAAM,2BAA2B;AAg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ACN,aAAa,GAAGC,gCAAAA,mCAAmC;EACnD,QAAQ,8CAA8C,gBAAgB;EACtE,gBAAA;CACF,CACF;AACF;AAEA,SAAgB,gDACd,kBACuB;CACvB,QAAA,GAAA,sBAAA,KAAA,CACE,OAAO,WAAW,WAAW;EAE3B,OAAO,gBAAgB;GACrB,QAAA;GACA;GACA;GACA,SAAS;EACX,CAAC;CACH,GACA;EACE,MAAA;EACA,aAAa,GAAGC,oCAAAA,uCAAuC;EACvD,QACE,kDAAkD,gBAAgB;EACpE,gBAAA;CACF,CACF;AACF"}
1
+ {"version":3,"file":"CloudflareProgrammaticToolCalling.cjs","names":["resolveCloudflareSandbox","getCloudflareWorkspaceRoot","execWithClientTimeout","clientExecTimeoutMs","ProgrammaticToolCallingSchema","BashProgrammaticToolCallingSchema","filterBashToolsByUsage","filterToolsByUsage","normalizeToPythonIdentifier","normalizeToBashIdentifier","validateCloudflareBashCommand","executeCloudflareCode","formatCompletedResponse","ProgrammaticToolCallingName","ProgrammaticToolCallingDescription","BashProgrammaticToolCallingDescription"],"sources":["../../../../src/tools/cloudflare/CloudflareProgrammaticToolCalling.ts"],"mappings":";;;;;;;AAqCA,MAAM,kBAAkB;AACxB,MAAM,cAAc;AACpB,MAAM,cAAc;AACpB,MAAM,2BAA2B;AAgCjC,MAAM,oBAAoB,IAAI,IAAY;;;;;;;;;;AAU1C,CAAC;AAED,SAAS,iBAAiB,WAAuC;CAC/D,IAAI,aAAa,QAAQ,CAAC,OAAO,SAAS,SAAS,GACjD,OAAO;CAET,OAAO,KAAK,IAAI,aAAa,KAAK,MAAM,SAAS,CAAC;AACpD;AAEA,SAAS,cAAc,WAA2B;CAChD,OAAO,YAAY,QAAS,IACxB,GAAG,YAAY,IAAK,YACpB,GAAG,UAAU;AACnB;AAEA,SAAS,oBAAoB,WAAmC;CAC9D,MAAM,iBAAiB,iBAAiB,SAAS;CACjD,MAAM,aAAa,KAAK,IAAI,aAAa,cAAc;CACvD,OAAO;EACL,MAAM;EACN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,8BAA8B,KAAK,OAAO,MAAM,CAAC,GAAG;GACxD,GAAG,KAAK;GACR;EACF,CAAC;EACD,SAAS,MAAM,+BACb,kBACE,KAAK,OAAO,MACZ,gBACA,KAAK,kBACL,aACF,GACA;GAAE,GAAG,KAAK;GAAkB;EAAU,CACxC;CACF,OACE,SAAS,MAAMC,yCAAAA,sBACb;EACE,MAAM;EACN,MAAM,oBACJ,KAAK,OAAO,MACZ,gBACA,KAAK,kBACL,aACF;CACF,GACA;EAAE,GAAG,KAAK;EAAkB;CAAU,CACxC;CAGF,IAAI,OAAO,aAAa,KAAK,OAAO,UAClC,MAAM,IAAI,MACR,OAAO,WAAW,KACd,OAAO,SACP,cAAc,KAAK,QAAQ,2CAA2C,OAAO,YAAY,WAC/F;CAGF,OAAOC,gCAAAA,wBAAwB;EAC7B,QAAQ;EACR,YAAY;EACZ,QAAQ,OAAO;EACf,QAAQ,OAAO;EACf,OAAO,CAAC;CACV,CAAC;AACH;AAEA,SAAgB,4CACd,kBACuB;CACvB,QAAA,GAAA,sBAAA,KAAA,CACE,OAAO,WAAW,WAAW;EAC3B,MAAM,SAAS;EACf,OAAO,gBAAgB;GACrB;GACA;GACA;GACA,SAAS,eAAe,MAAM;EAChC,CAAC;CACH,GACA;EACE,MAAMC,gCAAAA;EACN,aAAa,GAAGC,gCAAAA,mCAAmC;EACnD,QAAQ,8CAA8C,gBAAgB;EACtE,gBAAA;CACF,CACF;AACF;AAEA,SAAgB,gDACd,kBACuB;CACvB,QAAA,GAAA,sBAAA,KAAA,CACE,OAAO,WAAW,WAAW;EAE3B,OAAO,gBAAgB;GACrB,QAAA;GACA;GACA;GACA,SAAS;EACX,CAAC;CACH,GACA;EACE,MAAA;EACA,aAAa,GAAGC,oCAAAA,uCAAuC;EACvD,QACE,kDAAkD,gBAAgB;EACpE,gBAAA;CACF,CACF;AACF"}
@@ -62,42 +62,12 @@ function outerTimeoutMs(timeoutMs) {
62
62
  function isInSandboxTimeoutExit(exitCode) {
63
63
  return exitCode === 124 || exitCode === 137;
64
64
  }
65
- /**
66
- * Client-side backstop timeout for a `sandbox.exec()` await: a few seconds beyond
67
- * the exec's own `timeout` option, so a stalled exec that never honors `timeout`
68
- * still can't outlast this.
69
- */
70
65
  function clientExecTimeoutMs(timeoutMs) {
71
66
  return outerTimeoutMs(timeoutMs) + 5e3;
72
67
  }
73
- /**
74
- * Client-side backstop timeout for a native-DO sandbox FILE-IO RPC
75
- * (`readFile`/`writeFile`/`listFiles`/`mkdir`/`deleteFile`). Unlike `exec()`
76
- * there is no in-sandbox `timeout(1)` layer for these to honor, so this is just a
77
- * few seconds of headroom over the configured tool timeout — enough that a normal
78
- * (even large, byte-capped) read completes, while a stalled/cold container can't
79
- * outlast it. See `withClientTimeout` for why the native DO RPC needs this.
80
- */
81
68
  function clientFsTimeoutMs(timeoutMs) {
82
69
  return timeoutMs + 5e3;
83
70
  }
84
- /**
85
- * Bound a `sandbox.exec()` await with a CLIENT-SIDE timeout.
86
- *
87
- * The native Cloudflare Sandbox Durable Object `exec()` is effectively
88
- * uncancellable from the host: `ExecOptions` has no `signal` (so
89
- * `supportsExecSignal` is false for the native transport), and its `timeout`
90
- * option is not reliably enforced when the container/RPC itself stalls — while
91
- * the in-sandbox `timeout(1)` wrapper only bounds a command that is actually
92
- * running. So a stalled exec (an unresponsive/cold container) otherwise hangs
93
- * until the host's run-level abort, burning the whole run budget on one tool
94
- * call. This race guarantees the host await settles within `timeoutMs`
95
- * regardless of the transport.
96
- *
97
- * On timeout the underlying `exec` promise may keep running in the DO (a
98
- * native-DO exec cannot be truly cancelled), so its late settlement is swallowed
99
- * to avoid an unhandled rejection.
100
- */
101
71
  async function withClientTimeout(exec, timeoutMs, label, options = {}) {
102
72
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return exec;
103
73
  exec.catch(() => void 0);
@@ -114,13 +84,6 @@ async function withClientTimeout(exec, timeoutMs, label, options = {}) {
114
84
  if (timer !== void 0) clearTimeout(timer);
115
85
  }
116
86
  }
117
- /**
118
- * Run `sandbox.exec()` bounded by a client-side timeout, and — for signal-aware
119
- * transports (e.g. the HTTP bridge, `supportsExecSignal === true`) — abort the
120
- * underlying exec when the timeout fires instead of merely abandoning it. The
121
- * native DO transport ignores `signal`, so it only gets the timeout. Leaves the
122
- * backstop timer ref'd (this is an awaited direct-exec path).
123
- */
124
87
  async function execWithClientTimeout(sandbox, command, options, timeoutMs, label, runOptions = {}) {
125
88
  const controller = new AbortController();
126
89
  const execOptions = { ...options };
@@ -331,8 +294,6 @@ function createCloudflareSpawn(config) {
331
294
  const child = new events.EventEmitter();
332
295
  const abortController = new AbortController();
333
296
  const state = { closed: false };
334
- /** Read through a function so concurrent `closeOnce` mutation (via
335
- * `kill()`/abort during an `await`) isn't statically narrowed away. */
336
297
  const isClosed = () => state.closed;
337
298
  const closeOnce = (exitCode, signal) => {
338
299
  if (state.closed) return;
@@ -1 +1 @@
1
- {"version":3,"file":"CloudflareSandboxExecutionEngine.cjs","names":["WorkspaceClientTimeoutError","stream","isWorkspaceClientTimeoutError","PassThrough","EventEmitter","LOCAL_SPAWN_TIMEOUT_MS","validateBashCommand"],"sources":["../../../../src/tools/cloudflare/CloudflareSandboxExecutionEngine.ts"],"sourcesContent":["import { PassThrough } from 'stream';\nimport { posix as path } from 'path';\nimport { EventEmitter } from 'events';\nimport type { WriteFileOptions, MakeDirectoryOptions, Stats } from 'fs';\nimport type { ChildProcessWithoutNullStreams } from 'child_process';\nimport type { FileHandle } from 'fs/promises';\nimport type { WorkspaceFS, ReaddirEntry } from '@/tools/local/workspaceFS';\nimport {\n WorkspaceClientTimeoutError,\n isWorkspaceClientTimeoutError,\n} from '@/tools/local/workspaceFS';\nimport type * as t from '@/types';\nimport {\n LOCAL_SPAWN_TIMEOUT_MS,\n validateBashCommand,\n} from '@/tools/local/LocalExecutionEngine';\n\nconst DEFAULT_WORKSPACE_ROOT = '/workspace';\nconst DEFAULT_TIMEOUT_MS = 60000;\nconst DEFAULT_MAX_OUTPUT_CHARS = 200000;\nconst PROTECTED_TARGET_ARG_RE = /^(?:\\/|~|\\$\\{?HOME\\}?|\\.)(?:\\/?\\.?\\*|\\/)?$/;\nconst DESTRUCTIVE_OP_IN_COMMAND_RE =\n /\\b(?:rm\\s+-[^\\s]*[rf]|chmod\\s+-R|chown\\s+-R)\\b/;\n\ntype SpawnResult = {\n stdout: string;\n stderr: string;\n exitCode: number | null;\n timedOut: boolean;\n};\n\ntype RuntimeCommand = {\n fileName: string;\n source?: string;\n command: string;\n};\n\ntype SandboxRuntimeContext = {\n sandbox: t.CloudflareSandboxRuntime;\n workspaceRoot: string;\n env?: Record<string, string | undefined>;\n timeoutMs: number;\n maxOutputChars: number;\n shell: string;\n};\n\nconst sandboxFactoryCache = new WeakMap<\n t.CloudflareSandboxExecutionConfig,\n Promise<t.CloudflareSandboxRuntime>\n>();\n\nfunction normalizeWorkspaceRoot(workspaceRoot: string): string {\n const normalized = path.normalize(workspaceRoot);\n return normalized === '/' ? normalized : normalized.replace(/\\/+$/, '');\n}\n\nexport function getCloudflareWorkspaceRoot(\n config?: t.CloudflareSandboxExecutionConfig\n): string {\n return normalizeWorkspaceRoot(\n config?.workspaceRoot ?? DEFAULT_WORKSPACE_ROOT\n );\n}\n\nexport async function resolveCloudflareSandbox(\n config: t.CloudflareSandboxExecutionConfig\n): Promise<t.CloudflareSandboxRuntime> {\n const sandbox = config.sandbox;\n if (typeof sandbox !== 'function') {\n return sandbox;\n }\n let cached = sandboxFactoryCache.get(config);\n if (cached == null) {\n cached = Promise.resolve()\n .then(() => sandbox())\n .catch((error: unknown) => {\n sandboxFactoryCache.delete(config);\n throw error;\n });\n sandboxFactoryCache.set(config, cached);\n }\n return cached;\n}\n\nasync function getRuntimeContext(\n config: t.CloudflareSandboxExecutionConfig\n): Promise<SandboxRuntimeContext> {\n return {\n sandbox: await resolveCloudflareSandbox(config),\n workspaceRoot: getCloudflareWorkspaceRoot(config),\n env: config.env,\n timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n maxOutputChars: config.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS,\n shell: config.shell ?? 'bash',\n };\n}\n\nfunction toSandboxPath(filePath: string, workspaceRoot: string): string {\n const raw = filePath === '' ? '.' : filePath;\n const root = normalizeWorkspaceRoot(workspaceRoot);\n const resolved = raw.startsWith('/')\n ? path.normalize(raw)\n : path.resolve(root, raw);\n if (root === '/') {\n return resolved;\n }\n if (resolved === root || resolved.startsWith(`${root}/`)) {\n return resolved;\n }\n throw new Error(\n `Path is outside the Cloudflare sandbox workspace: ${filePath}`\n );\n}\n\nfunction quote(value: string): string {\n if (value === '') {\n return '\\'\\'';\n }\n if (/^[A-Za-z0-9_/:=.,@%+-]+$/.test(value)) {\n return value;\n }\n return `'${value.replace(/'/g, '\\'\\\\\\'\\'')}'`;\n}\n\nfunction withInSandboxTimeout(command: string, timeoutMs: number): string {\n const timeoutSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));\n return `timeout -k 2s ${timeoutSeconds}s ${command}`;\n}\n\nfunction outerTimeoutMs(timeoutMs: number): number {\n return timeoutMs + 5000;\n}\n\nfunction isInSandboxTimeoutExit(exitCode: number | null): boolean {\n return exitCode === 124 || exitCode === 137;\n}\n\n/**\n * Client-side backstop timeout for a `sandbox.exec()` await: a few seconds beyond\n * the exec's own `timeout` option, so a stalled exec that never honors `timeout`\n * still can't outlast this.\n */\nexport function clientExecTimeoutMs(timeoutMs: number): number {\n return outerTimeoutMs(timeoutMs) + 5000;\n}\n\n/**\n * Client-side backstop timeout for a native-DO sandbox FILE-IO RPC\n * (`readFile`/`writeFile`/`listFiles`/`mkdir`/`deleteFile`). Unlike `exec()`\n * there is no in-sandbox `timeout(1)` layer for these to honor, so this is just a\n * few seconds of headroom over the configured tool timeout — enough that a normal\n * (even large, byte-capped) read completes, while a stalled/cold container can't\n * outlast it. See `withClientTimeout` for why the native DO RPC needs this.\n */\nexport function clientFsTimeoutMs(timeoutMs: number): number {\n return timeoutMs + 5000;\n}\n\n/**\n * Bound a `sandbox.exec()` await with a CLIENT-SIDE timeout.\n *\n * The native Cloudflare Sandbox Durable Object `exec()` is effectively\n * uncancellable from the host: `ExecOptions` has no `signal` (so\n * `supportsExecSignal` is false for the native transport), and its `timeout`\n * option is not reliably enforced when the container/RPC itself stalls — while\n * the in-sandbox `timeout(1)` wrapper only bounds a command that is actually\n * running. So a stalled exec (an unresponsive/cold container) otherwise hangs\n * until the host's run-level abort, burning the whole run budget on one tool\n * call. This race guarantees the host await settles within `timeoutMs`\n * regardless of the transport.\n *\n * On timeout the underlying `exec` promise may keep running in the DO (a\n * native-DO exec cannot be truly cancelled), so its late settlement is swallowed\n * to avoid an unhandled rejection.\n */\nexport async function withClientTimeout<T>(\n exec: Promise<T>,\n timeoutMs: number,\n label: string,\n options: {\n /**\n * Detach the backstop timer from the event loop. Use ONLY when something else\n * already settles the caller (e.g. the spawn path, where spawnLocalProcess's\n * own timer resolves the child). The awaited direct-exec paths must leave it\n * REF'd so the timeout is guaranteed to fire even if nothing else is pending.\n */\n unref?: boolean;\n /** Invoked when the client timeout fires — e.g. abort a signal-aware exec. */\n onTimeout?: () => void;\n } = {}\n): Promise<T> {\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n return exec;\n }\n // Swallow a late rejection from the losing promise after the race settles.\n exec.catch(() => undefined);\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n exec,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n // Reject FIRST so this client-timeout message reliably wins the race;\n // only then abort a signal-aware exec, whose resulting AbortError must\n // not surface to the caller instead of the timeout.\n reject(\n new WorkspaceClientTimeoutError(\n `${label} exceeded ${timeoutMs}ms client-side timeout (sandbox RPC did not return)`\n )\n );\n options.onTimeout?.();\n }, timeoutMs);\n if (options.unref === true) {\n (timer as { unref?: () => void } | undefined)?.unref?.();\n }\n }),\n ]);\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }\n}\n\n/**\n * Run `sandbox.exec()` bounded by a client-side timeout, and — for signal-aware\n * transports (e.g. the HTTP bridge, `supportsExecSignal === true`) — abort the\n * underlying exec when the timeout fires instead of merely abandoning it. The\n * native DO transport ignores `signal`, so it only gets the timeout. Leaves the\n * backstop timer ref'd (this is an awaited direct-exec path).\n */\nexport async function execWithClientTimeout(\n sandbox: t.CloudflareSandboxRuntime,\n command: string,\n options: t.CloudflareSandboxExecOptions,\n timeoutMs: number,\n label: string,\n runOptions: { unref?: boolean } = {}\n): Promise<t.CloudflareSandboxExecResult> {\n const controller = new AbortController();\n const execOptions: t.CloudflareSandboxExecOptions = { ...options };\n const callerSignal = options.signal;\n let onCallerAbort: (() => void) | undefined;\n if (sandbox.supportsExecSignal === true) {\n // Compose the caller's signal (e.g. run/user cancellation) with our timeout\n // controller so EITHER source cancels the exec — don't clobber the caller's.\n if (callerSignal != null) {\n if (callerSignal.aborted) {\n controller.abort();\n } else {\n onCallerAbort = (): void => controller.abort();\n callerSignal.addEventListener('abort', onCallerAbort, { once: true });\n }\n }\n execOptions.signal = controller.signal;\n } else if ('signal' in execOptions) {\n // Native DO RPC cannot consume an AbortSignal (and would fail to clone it).\n // Strip any caller-provided one so the spread above can't reintroduce it.\n delete execOptions.signal;\n }\n try {\n return await withClientTimeout(\n sandbox.exec(command, execOptions),\n timeoutMs,\n label,\n {\n unref: runOptions.unref,\n onTimeout: () => controller.abort(),\n }\n );\n } finally {\n // Don't leave a listener attached to a long-lived/shared caller signal.\n if (onCallerAbort != null && callerSignal != null) {\n callerSignal.removeEventListener('abort', onCallerAbort);\n }\n }\n}\n\nfunction truncateOutput(value: string, maxChars: number): string {\n if (maxChars <= 0 || value.length <= maxChars) {\n return value;\n }\n const head = Math.max(Math.floor(maxChars / 2), 0);\n const tail = Math.max(maxChars - head, 0);\n return `${value.slice(0, head)}\\n...[truncated ${value.length - maxChars} chars]...\\n${value.slice(value.length - tail)}`;\n}\n\nasync function readStream(stream: ReadableStream<Uint8Array>): Promise<Buffer> {\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));\n}\n\nasync function normalizeReadFileContent(\n result: t.CloudflareSandboxReadFileResult\n): Promise<Buffer> {\n if (typeof result === 'string') {\n return Buffer.from(result, 'utf8');\n }\n if (Buffer.isBuffer(result)) {\n return result;\n }\n if (result instanceof Uint8Array) {\n return Buffer.from(result);\n }\n const content = result.content;\n if (typeof content === 'string') {\n if (result.encoding === 'base64') {\n return Buffer.from(content, 'base64');\n }\n return Buffer.from(content, 'utf8');\n }\n if (Buffer.isBuffer(content)) {\n return content;\n }\n if (content instanceof Uint8Array) {\n return Buffer.from(content);\n }\n return readStream(content);\n}\n\nfunction bytesToStream(bytes: Uint8Array): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n start(controller): void {\n controller.enqueue(bytes);\n controller.close();\n },\n });\n}\n\nfunction normalizeWriteFileContent(content: string | Buffer | Uint8Array): {\n content: string | ReadableStream<Uint8Array>;\n options?: { encoding?: string };\n} {\n if (typeof content === 'string') {\n return { content, options: { encoding: 'utf8' } };\n }\n return { content: bytesToStream(content) };\n}\n\nfunction createStats(info: {\n size?: number;\n type?: t.CloudflareSandboxFileInfo['type'];\n}): Stats {\n const type = info.type ?? 'file';\n const now = new Date();\n return {\n size: info.size ?? 0,\n isFile: () => type === 'file',\n isDirectory: () => type === 'directory',\n isSymbolicLink: () => type === 'symlink',\n isBlockDevice: () => false,\n isCharacterDevice: () => false,\n isFIFO: () => false,\n isSocket: () => false,\n dev: 0,\n ino: 0,\n mode: 0,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n blksize: 0,\n blocks: 0,\n atimeMs: now.getTime(),\n mtimeMs: now.getTime(),\n ctimeMs: now.getTime(),\n birthtimeMs: now.getTime(),\n atime: now,\n mtime: now,\n ctime: now,\n birthtime: now,\n } as Stats;\n}\n\nfunction normalizeFileList(\n result: t.CloudflareSandboxListFilesResult\n): t.CloudflareSandboxFileInfo[] {\n return Array.isArray(result) ? result : result.files;\n}\n\nfunction entryNameFor(\n info: t.CloudflareSandboxFileInfo,\n parentPath: string\n): string {\n if (info.name !== '') {\n return info.name.includes('/') ? path.basename(info.name) : info.name;\n }\n if (info.absolutePath != null && info.absolutePath !== '') {\n return path.basename(info.absolutePath);\n }\n if (info.relativePath != null && info.relativePath !== '') {\n return path.basename(info.relativePath);\n }\n return path.basename(parentPath);\n}\n\nfunction entryAbsolutePath(\n info: t.CloudflareSandboxFileInfo,\n parentPath: string\n): string {\n if (info.absolutePath != null && info.absolutePath !== '') {\n return path.normalize(info.absolutePath);\n }\n if (info.relativePath != null && info.relativePath !== '') {\n return path.resolve(parentPath, info.relativePath);\n }\n return path.resolve(parentPath, info.name);\n}\n\nfunction createDirent(info: t.CloudflareSandboxFileInfo): ReaddirEntry {\n return {\n name: entryNameFor(info, ''),\n isFile: () => (info.type ?? 'file') === 'file',\n isDirectory: () => info.type === 'directory',\n isSymbolicLink: () => info.type === 'symlink',\n };\n}\n\nasync function findChildInfo(\n sandbox: t.CloudflareSandboxRuntime,\n filePath: string,\n timeoutMs: number\n): Promise<t.CloudflareSandboxFileInfo | undefined> {\n const parent = path.dirname(filePath);\n const basename = path.basename(filePath);\n const entries = normalizeFileList(\n await withClientTimeout(\n sandbox.listFiles(parent, { includeHidden: true }),\n timeoutMs,\n 'cloudflare sandbox listFiles'\n )\n );\n return entries.find((entry) => {\n const absolute = entryAbsolutePath(entry, parent);\n return absolute === filePath || entryNameFor(entry, parent) === basename;\n });\n}\n\nexport function createCloudflareWorkspaceFS(\n config: t.CloudflareSandboxExecutionConfig\n): WorkspaceFS {\n const workspaceRoot = getCloudflareWorkspaceRoot(config);\n // Native-DO file-IO RPCs have the SAME stall hazard as exec() (PR #252): no\n // `signal`, no reliably-enforced timeout, so a cold/unresponsive container\n // hangs the host await until the run-level abort — burning the whole budget on\n // one read (observed: a `read_file` that stalled ~552s before the wall-clock\n // budget killed it). Bound every native FS RPC with the same client-side\n // backstop the exec sites use.\n const fsTimeoutMs = clientFsTimeoutMs(config.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n const bound = <T>(op: Promise<T>, label: string): Promise<T> =>\n withClientTimeout(op, fsTimeoutMs, `cloudflare sandbox ${label}`);\n\n const fs: WorkspaceFS = {\n readFile: (async (filePath: string, encoding?: 'utf8') => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n // Wrap the stream drain (normalizeReadFileContent) inside the backstop too:\n // a sandbox.readFile that resolves to a { content: ReadableStream } can\n // still stall mid-drain after the RPC promise settled.\n const buffer = await bound(\n (async (): Promise<Buffer> =>\n normalizeReadFileContent(\n await sandbox.readFile(resolved, encoding ? { encoding } : undefined)\n ))(),\n 'readFile'\n );\n return encoding != null ? buffer.toString(encoding) : buffer;\n }) as WorkspaceFS['readFile'],\n writeFile: async (\n filePath: string,\n content: string | Buffer,\n _options?: WriteFileOptions\n ) => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const normalized = normalizeWriteFileContent(content);\n await bound(\n sandbox.writeFile(resolved, normalized.content, normalized.options),\n 'writeFile'\n );\n },\n stat: async (filePath: string) => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n if (resolved === workspaceRoot) {\n const entries = normalizeFileList(\n await bound(\n sandbox.listFiles(resolved, { includeHidden: true }),\n 'listFiles'\n )\n );\n return createStats({ size: entries.length, type: 'directory' });\n }\n const info = await findChildInfo(sandbox, resolved, fsTimeoutMs);\n if (info != null) {\n return createStats({ size: info.size, type: info.type });\n }\n try {\n const entries = normalizeFileList(\n await bound(\n sandbox.listFiles(resolved, { includeHidden: true }),\n 'listFiles'\n )\n );\n return createStats({ size: entries.length, type: 'directory' });\n } catch (error) {\n // A directory-probe timeout is a stalled container, not \"not a directory\".\n // Don't fall through to the readFile branch — that would wait through a\n // SECOND full backstop (~2x the timeout) before surfacing.\n if (isWorkspaceClientTimeoutError(error)) {\n throw error;\n }\n const buffer = await bound(\n (async (): Promise<Buffer> =>\n normalizeReadFileContent(await sandbox.readFile(resolved)))(),\n 'readFile'\n );\n return createStats({ size: buffer.length, type: 'file' });\n }\n },\n readdir: (async (filePath: string, options?: { withFileTypes: true }) => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const entries = normalizeFileList(\n await bound(\n sandbox.listFiles(resolved, { includeHidden: true }),\n 'listFiles'\n )\n );\n if (options?.withFileTypes === true) {\n return entries.map(createDirent);\n }\n return entries.map((entry) => entryNameFor(entry, resolved));\n }) as WorkspaceFS['readdir'],\n mkdir: async (filePath: string, options?: MakeDirectoryOptions) => {\n const sandbox = await resolveCloudflareSandbox(config);\n await bound(\n sandbox.mkdir(toSandboxPath(filePath, workspaceRoot), {\n recursive: options?.recursive,\n }),\n 'mkdir'\n );\n },\n realpath: async (filePath: string) =>\n toSandboxPath(filePath, workspaceRoot),\n unlink: async (filePath: string) => {\n const sandbox = await resolveCloudflareSandbox(config);\n await bound(\n sandbox.deleteFile(toSandboxPath(filePath, workspaceRoot)),\n 'deleteFile'\n );\n },\n open: async (filePath: string, _flags: 'r') => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const buffer = await bound(\n (async (): Promise<Buffer> =>\n normalizeReadFileContent(await sandbox.readFile(resolved)))(),\n 'readFile'\n );\n return {\n read: async (\n target: Buffer,\n offset: number,\n length: number,\n position: number\n ) => {\n const start = Math.max(position, 0);\n const slice = buffer.subarray(start, start + length);\n slice.copy(target, offset);\n return { bytesRead: slice.length, buffer: target };\n },\n close: async () => undefined,\n } as unknown as FileHandle;\n },\n };\n\n return fs;\n}\n\nfunction createCloudflareSpawn(\n config: t.CloudflareSandboxExecutionConfig\n): t.LocalSpawn {\n return (command, args, options) => {\n const stdout = new PassThrough();\n const stderr = new PassThrough();\n const child = new EventEmitter() as ChildProcessWithoutNullStreams;\n const abortController = new AbortController();\n const state = { closed: false };\n /** Read through a function so concurrent `closeOnce` mutation (via\n * `kill()`/abort during an `await`) isn't statically narrowed away. */\n const isClosed = (): boolean => state.closed;\n const closeOnce = (\n exitCode: number | null,\n signal: NodeJS.Signals | null\n ): void => {\n if (state.closed) {\n return;\n }\n state.closed = true;\n stdout.end();\n stderr.end();\n Object.assign(child, {\n exitCode,\n signalCode: signal,\n });\n child.emit('close', exitCode, signal);\n };\n Object.assign(child, {\n stdout,\n stderr,\n stdin: new PassThrough(),\n stdio: [null, stdout, stderr],\n killed: false,\n exitCode: null,\n signalCode: null,\n pid: undefined,\n kill: (signal: NodeJS.Signals = 'SIGTERM') => {\n Object.assign(child, { killed: true, signalCode: signal });\n abortController.abort();\n closeOnce(null, signal);\n return true;\n },\n });\n\n void (async (): Promise<void> => {\n const ctx = await getRuntimeContext(config);\n const rendered = [command, ...args].map(quote).join(' ');\n const spawnTimeoutMs = (\n options as {\n [LOCAL_SPAWN_TIMEOUT_MS]?: number;\n }\n )[LOCAL_SPAWN_TIMEOUT_MS];\n const timeoutMs =\n typeof spawnTimeoutMs === 'number' && Number.isFinite(spawnTimeoutMs)\n ? spawnTimeoutMs\n : ctx.timeoutMs;\n const timedCommand = withInSandboxTimeout(rendered, timeoutMs);\n const cwd =\n options.cwd == null ? ctx.workspaceRoot : options.cwd.toString();\n if (isClosed()) {\n return;\n }\n const execOptions: t.CloudflareSandboxExecOptions = {\n cwd,\n env: ctx.env,\n timeout: outerTimeoutMs(timeoutMs),\n };\n if (ctx.sandbox.supportsExecSignal === true) {\n execOptions.signal = abortController.signal;\n }\n try {\n const result = await withClientTimeout(\n ctx.sandbox.exec(timedCommand, execOptions),\n clientExecTimeoutMs(timeoutMs),\n 'cloudflare sandbox exec',\n // spawnLocalProcess's own timer already resolves the child, so this\n // backstop may safely detach; abort the (signal-aware) exec on timeout.\n { unref: true, onTimeout: () => abortController.abort() }\n );\n if (isClosed()) {\n return;\n }\n if (result.stdout) stdout.write(result.stdout);\n if (result.stderr) stderr.write(result.stderr);\n closeOnce(result.exitCode, null);\n } catch (error) {\n if (isClosed()) {\n return;\n }\n stderr.write((error as Error).message);\n closeOnce(1, null);\n }\n })();\n\n return child;\n };\n}\n\nexport function createCloudflareLocalExecutionConfig(\n config: t.CloudflareSandboxExecutionConfig\n): t.LocalExecutionConfig {\n const workspaceRoot = getCloudflareWorkspaceRoot(config);\n return {\n cwd: workspaceRoot,\n workspace: { root: workspaceRoot },\n exec: {\n spawn: createCloudflareSpawn(config),\n fs: createCloudflareWorkspaceFS(config),\n sandboxed: true,\n },\n shell: config.shell ?? 'bash',\n timeoutMs: config.timeoutMs,\n maxOutputChars: config.maxOutputChars,\n env: config.env,\n includeCodingTools: config.includeCodingTools,\n compileCheck: config.compileCheck,\n readOnly: config.readOnly,\n allowDangerousCommands: config.allowDangerousCommands,\n bashAst: config.bashAst,\n fileCheckpointing: config.fileCheckpointing,\n maxReadBytes: config.maxReadBytes,\n attachReadAttachments: config.attachReadAttachments,\n maxAttachmentBytes: config.maxAttachmentBytes,\n postEditSyntaxCheck: config.postEditSyntaxCheck,\n };\n}\n\nexport async function validateCloudflareBashCommand(\n command: string,\n args: readonly string[],\n config: t.CloudflareSandboxExecutionConfig\n): Promise<void> {\n const localConfig = createCloudflareLocalExecutionConfig(config);\n const validation = await validateBashCommand(command, localConfig);\n if (!validation.valid) {\n throw new Error(validation.errors.join('\\n'));\n }\n\n if (\n args.length > 0 &&\n config.allowDangerousCommands !== true &&\n DESTRUCTIVE_OP_IN_COMMAND_RE.test(command)\n ) {\n const offending = args.find((arg) => PROTECTED_TARGET_ARG_RE.test(arg));\n if (offending !== undefined) {\n throw new Error(\n `Command matches a destructive command pattern (protected target \"${offending}\" passed via positional arg).`\n );\n }\n }\n}\n\nexport async function executeCloudflareBash(\n command: string,\n config: t.CloudflareSandboxExecutionConfig,\n args: readonly string[] = []\n): Promise<SpawnResult> {\n await validateCloudflareBashCommand(command, args, config);\n const ctx = await getRuntimeContext(config);\n const shellCommand =\n args.length > 0\n ? `${ctx.shell} -lc ${quote(command)} -- ${args.map(quote).join(' ')}`\n : `${ctx.shell} -lc ${quote(command)}`;\n const result = await execWithClientTimeout(\n ctx.sandbox,\n withInSandboxTimeout(shellCommand, ctx.timeoutMs),\n {\n cwd: ctx.workspaceRoot,\n env: ctx.env,\n timeout: outerTimeoutMs(ctx.timeoutMs),\n },\n clientExecTimeoutMs(ctx.timeoutMs),\n 'cloudflare sandbox bash exec'\n );\n return {\n stdout: truncateOutput(result.stdout, ctx.maxOutputChars),\n stderr: truncateOutput(result.stderr, ctx.maxOutputChars),\n exitCode: result.exitCode,\n timedOut: isInSandboxTimeoutExit(result.exitCode),\n };\n}\n\nfunction runtimeForCode(\n lang: string,\n tempDir: string,\n code: string,\n args: string[] = [],\n shell = 'bash'\n): RuntimeCommand {\n const fileFor = (name: string): string => path.join(tempDir, name);\n const argText = args.map(quote).join(' ');\n switch (lang) {\n case 'py':\n case 'python':\n return {\n fileName: 'main.py',\n source: code,\n command: `python3 ${quote(fileFor('main.py'))} ${argText}`,\n };\n case 'js':\n case 'javascript':\n return {\n fileName: 'main.js',\n source: code,\n command: `node ${quote(fileFor('main.js'))} ${argText}`,\n };\n case 'ts':\n case 'typescript':\n return {\n fileName: 'main.ts',\n source: code,\n command: `npx --no-install tsx ${quote(fileFor('main.ts'))} ${argText}`,\n };\n case 'php':\n return {\n fileName: 'main.php',\n source: code,\n command: `php ${quote(fileFor('main.php'))} ${argText}`,\n };\n case 'go':\n return {\n fileName: 'main.go',\n source: code,\n command: `go run ${quote(fileFor('main.go'))} ${argText}`,\n };\n case 'rs':\n return {\n fileName: 'main.rs',\n source: code,\n command: `${shell} -lc ${quote(\n `rustc ${quote(fileFor('main.rs'))} -o ${quote(fileFor('main-rs'))} && ${quote(fileFor('main-rs'))} ${argText}`\n )}`,\n };\n case 'c':\n return {\n fileName: 'main.c',\n source: code,\n command: `${shell} -lc ${quote(\n `cc ${quote(fileFor('main.c'))} -o ${quote(fileFor('main-c'))} && ${quote(fileFor('main-c'))} ${argText}`\n )}`,\n };\n case 'cpp':\n return {\n fileName: 'main.cpp',\n source: code,\n command: `${shell} -lc ${quote(\n `c++ ${quote(fileFor('main.cpp'))} -o ${quote(fileFor('main-cpp'))} && ${quote(fileFor('main-cpp'))} ${argText}`\n )}`,\n };\n case 'java':\n return {\n fileName: 'Main.java',\n source: code,\n command: `${shell} -lc ${quote(\n `javac ${quote(fileFor('Main.java'))} && java -cp ${quote(tempDir)} Main ${argText}`\n )}`,\n };\n case 'r':\n return {\n fileName: 'main.R',\n source: code,\n command: `Rscript ${quote(fileFor('main.R'))} ${argText}`,\n };\n case 'd':\n return {\n fileName: 'main.d',\n source: code,\n command: `${shell} -lc ${quote(\n `dmd ${quote(fileFor('main.d'))} -of=${quote(fileFor('main-d'))} && ${quote(fileFor('main-d'))} ${argText}`\n )}`,\n };\n case 'f90':\n return {\n fileName: 'main.f90',\n source: code,\n command: `${shell} -lc ${quote(\n `gfortran ${quote(fileFor('main.f90'))} -o ${quote(fileFor('main-f90'))} && ${quote(fileFor('main-f90'))} ${argText}`\n )}`,\n };\n case 'bash':\n case 'sh':\n return {\n fileName: 'main.sh',\n source: code,\n command: `${shell} -lc ${quote(code)} -- ${argText}`,\n };\n default:\n throw new Error(`Unsupported Cloudflare sandbox runtime: ${lang}`);\n }\n}\n\nexport async function executeCloudflareCode(\n input: { lang: string; code: string; args?: string[] },\n config: t.CloudflareSandboxExecutionConfig\n): Promise<SpawnResult> {\n if (input.lang === 'bash' || input.lang === 'sh') {\n return executeCloudflareBash(input.code, config, input.args ?? []);\n }\n const ctx = await getRuntimeContext(config);\n const id = globalThis.crypto.randomUUID();\n const tempDir = path.join(ctx.workspaceRoot, '.lc-exec', id);\n const runtime = runtimeForCode(\n input.lang,\n tempDir,\n input.code,\n input.args,\n ctx.shell\n );\n let execSucceeded = false;\n try {\n // Bound the temp-dir setup RPCs (they run BEFORE the bounded exec): a\n // native-DO stall here would hang the host on a single mkdir/writeFile and\n // burn the run budget. Keep them INSIDE the try so the finally cleanup still\n // removes .lc-exec/<uuid> if setup throws — the uncancellable write can land\n // late on a cold container, so an orphaned dir would otherwise accumulate.\n await withClientTimeout(\n ctx.sandbox.mkdir(tempDir, { recursive: true }),\n clientFsTimeoutMs(ctx.timeoutMs),\n 'cloudflare sandbox mkdir'\n );\n if (runtime.source != null) {\n await withClientTimeout(\n ctx.sandbox.writeFile(\n path.join(tempDir, runtime.fileName),\n runtime.source,\n { encoding: 'utf8' }\n ),\n clientFsTimeoutMs(ctx.timeoutMs),\n 'cloudflare sandbox writeFile'\n );\n }\n const result = await execWithClientTimeout(\n ctx.sandbox,\n withInSandboxTimeout(runtime.command, ctx.timeoutMs),\n {\n cwd: ctx.workspaceRoot,\n env: ctx.env,\n timeout: outerTimeoutMs(ctx.timeoutMs),\n },\n clientExecTimeoutMs(ctx.timeoutMs),\n 'cloudflare sandbox code-exec'\n );\n execSucceeded = true;\n return {\n stdout: truncateOutput(result.stdout, ctx.maxOutputChars),\n stderr: truncateOutput(result.stderr, ctx.maxOutputChars),\n exitCode: result.exitCode,\n timedOut: isInSandboxTimeoutExit(result.exitCode),\n };\n } finally {\n // After a normal run, AWAIT cleanup so the temp dir is gone before returning.\n // After a stalled/failed run, detach it (unref'd) so we don't pile a second\n // client timeout onto the caller's latency; cleanup still runs best-effort.\n const detach = !execSucceeded;\n const cleanup = execWithClientTimeout(\n ctx.sandbox,\n `rm -rf ${quote(tempDir)}`,\n {\n cwd: ctx.workspaceRoot,\n env: ctx.env,\n timeout: 10000,\n },\n clientExecTimeoutMs(10000),\n 'cloudflare sandbox cleanup',\n { unref: detach }\n ).catch(() => undefined);\n if (!detach) {\n await cleanup;\n }\n }\n}\n\nexport function formatCloudflareOutput(\n result: SpawnResult,\n cwd: string\n): string {\n let formatted = '';\n if (result.stdout !== '') {\n formatted += `stdout:\\n${result.stdout}\\n`;\n } else {\n formatted += 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n }\n if (result.stderr !== '') {\n formatted += `stderr:\\n${result.stderr}\\n`;\n }\n if (result.exitCode != null && result.exitCode !== 0) {\n formatted += `exit_code: ${result.exitCode}\\n`;\n }\n if (result.timedOut) {\n formatted += 'timed_out: true\\n';\n }\n formatted += `working_directory: ${cwd}`;\n return formatted.trim();\n}\n"],"mappings":";;;;;;AAiBA,MAAM,yBAAyB;AAC/B,MAAM,qBAAqB;AAC3B,MAAM,2BAA2B;AACjC,MAAM,0BAA0B;AAChC,MAAM,+BACJ;AAwBF,MAAM,sCAAsB,IAAI,QAG9B;AAEF,SAAS,uBAAuB,eAA+B;CAC7D,MAAM,aAAa,KAAA,MAAK,UAAU,aAAa;CAC/C,OAAO,eAAe,MAAM,aAAa,WAAW,QAAQ,QAAQ,EAAE;AACxE;AAEA,SAAgB,2BACd,QACQ;CACR,OAAO,uBACL,QAAQ,iBAAiB,sBAC3B;AACF;AAEA,eAAsB,yBACpB,QACqC;CACrC,MAAM,UAAU,OAAO;CACvB,IAAI,OAAO,YAAY,YACrB,OAAO;CAET,IAAI,SAAS,oBAAoB,IAAI,MAAM;CAC3C,IAAI,UAAU,MAAM;EAClB,SAAS,QAAQ,QAAQ,CAAC,CACvB,WAAW,QAAQ,CAAC,CAAC,CACrB,OAAO,UAAmB;GACzB,oBAAoB,OAAO,MAAM;GACjC,MAAM;EACR,CAAC;EACH,oBAAoB,IAAI,QAAQ,MAAM;CACxC;CACA,OAAO;AACT;AAEA,eAAe,kBACb,QACgC;CAChC,OAAO;EACL,SAAS,MAAM,yBAAyB,MAAM;EAC9C,eAAe,2BAA2B,MAAM;EAChD,KAAK,OAAO;EACZ,WAAW,OAAO,aAAa;EAC/B,gBAAgB,OAAO,kBAAkB;EACzC,OAAO,OAAO,SAAS;CACzB;AACF;AAEA,SAAS,cAAc,UAAkB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Aa;CAEf,aAAa,sBAAsB;CACnC,OAAO,UAAU,KAAK;AACxB"}
1
+ {"version":3,"file":"CloudflareSandboxExecutionEngine.cjs","names":["WorkspaceClientTimeoutError","stream","isWorkspaceClientTimeoutError","PassThrough","EventEmitter","LOCAL_SPAWN_TIMEOUT_MS","validateBashCommand"],"sources":["../../../../src/tools/cloudflare/CloudflareSandboxExecutionEngine.ts"],"mappings":";;;;;;AAiBA,MAAM,yBAAyB;AAC/B,MAAM,qBAAqB;AAC3B,MAAM,2BAA2B;AACjC,MAAM,0BAA0B;AAChC,MAAM,+BACJ;AAwBF,MAAM,sCAAsB,IAAI,QAG9B;AAEF,SAAS,uBAAuB,eAA+B;CAC7D,MAAM,aAAa,KAAA,MAAK,UAAU,aAAa;CAC/C,OAAO,eAAe,MAAM,aAAa,WAAW,QAAQ,QAAQ,EAAE;AACxE;AAEA,SAAgB,2BACd,QACQ;CACR,OAAO,uBACL,QAAQ,iBAAiB,sBAC3B;AACF;AAEA,eAAsB,yBACpB,QACqC;CACrC,MAAM,UAAU,OAAO;CACvB,IAAI,OAAO,YAAY,YACrB,OAAO;CAET,IAAI,SAAS,oBAAoB,IAAI,MAAM;CAC3C,IAAI,UAAU,MAAM;EAClB,SAAS,QAAQ,QAAQ,CAAC,CACvB,WAAW,QAAQ,CAAC,CAAC,CACrB,OAAO,UAAmB;GACzB,oBAAoB,OAAO,MAAM;GACjC,MAAM;EACR,CAAC;EACH,oBAAoB,IAAI,QAAQ,MAAM;CACxC;CACA,OAAO;AACT;AAEA,eAAe,kBACb,QACgC;CAChC,OAAO;EACL,SAAS,MAAM,yBAAyB,MAAM;EAC9C,eAAe,2BAA2B,MAAM;EAChD,KAAK,OAAO;EACZ,WAAW,OAAO,aAAa;EAC/B,gBAAgB,OAAO,kBAAkB;EACzC,OAAO,OAAO,SAAS;CACzB;AACF;AAEA,SAAS,cAAc,UAAkB,eAA+B;CACtE,MAAM,MAAM,aAAa,KAAK,MAAM;CACpC,MAAM,OAAO,uB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loudflareWorkspaceRoot","formatCloudflareOutput","executeCloudflareCode","CodeExecutionToolName","CodeExecutionToolSchema","executeCloudflareBash","BashExecutionToolName","BashToolOutputReferencesGuide","BashExecutionToolSchema","createCloudflareLocalExecutionConfig","createLocalFileCheckpointer","createCloudflareWorkspaceFS","createLocalReadFileTool","createLocalWriteFileTool","createLocalEditFileTool","createLocalGrepSearchTool","createLocalGlobSearchTool","createLocalListDirectoryTool","createCompileCheckTool","createCloudflareProgrammaticToolCallingTool","createCloudflareBashProgrammaticToolCallingTool"],"sources":["../../../../src/tools/cloudflare/CloudflareSandboxTools.ts"],"sourcesContent":["import { tool } from '@langchain/core/tools';\nimport type { DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport {\n createCloudflareLocalExecutionConfig,\n createCloudflareWorkspaceFS,\n executeCloudflareBash,\n executeCloudflareCode,\n formatCloudflareOutput,\n getCloudflareWorkspaceRoot,\n} from './CloudflareSandboxExecutionEngine';\nimport {\n createLocalReadFileTool,\n createLocalWriteFileTool,\n createLocalEditFileTool,\n createLocalGrepSearchTool,\n createLocalGlobSearchTool,\n createLocalListDirectoryTool,\n} from '@/tools/local/LocalCodingTools';\nimport {\n createCloudflareBashProgrammaticToolCallingTool,\n createCloudflareProgrammaticToolCallingTool,\n} from './CloudflareProgrammaticToolCalling';\nimport {\n BashExecutionToolName,\n BashExecutionToolSchema,\n BashToolOutputReferencesGuide,\n} from '@/tools/BashExecutor';\nimport {\n CodeExecutionToolName,\n CodeExecutionToolSchema,\n} from '@/tools/CodeExecutor';\nimport { createLocalFileCheckpointer } from '@/tools/local/FileCheckpointer';\nimport { createCompileCheckTool } from '@/tools/local/CompileCheckTool';\nimport { Constants } from '@/common';\n\nexport const CLOUDFLARE_CODING_TOOL_NAMES: readonly string[] = [\n Constants.READ_FILE,\n Constants.WRITE_FILE,\n Constants.EDIT_FILE,\n Constants.GREP_SEARCH,\n Constants.GLOB_SEARCH,\n Constants.LIST_DIRECTORY,\n Constants.COMPILE_CHECK,\n Constants.BASH_TOOL,\n Constants.EXECUTE_CODE,\n Constants.PROGRAMMATIC_TOOL_CALLING,\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n];\n\nexport const CLOUDFLARE_BASH_CODING_TOOL_NAMES: readonly string[] = [\n Constants.READ_FILE,\n Constants.WRITE_FILE,\n Constants.EDIT_FILE,\n Constants.GREP_SEARCH,\n Constants.GLOB_SEARCH,\n Constants.LIST_DIRECTORY,\n Constants.COMPILE_CHECK,\n Constants.BASH_TOOL,\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n];\n\nexport const CloudflareCodeExecutionToolDescription = `\nRuns code inside the configured Cloudflare Sandbox workspace. The sandbox can see files and installed runtimes available inside the Cloudflare Sandbox container.\n\nUsage:\n- Commands execute in the Cloudflare Sandbox workspace and may modify sandbox files.\n- Input code is already displayed to the user, so do not repeat it unless asked.\n- Output is not displayed unless you print it explicitly.\n`.trim();\n\nexport const CloudflareBashExecutionToolDescription = `\nRuns bash commands inside the configured Cloudflare Sandbox workspace.\n\nUsage:\n- Commands execute in the Cloudflare Sandbox workspace and may modify sandbox files.\n- Output is not displayed unless you print it explicitly.\n- Prefer project-native commands and inspect files before changing them.\n`.trim();\n\nexport function createCloudflareCodeExecutionTool(\n config: t.CloudflareSandboxExecutionConfig\n): DynamicStructuredTool {\n return tool(\n async (rawInput) => {\n const input = rawInput as {\n lang: string;\n code: string;\n args?: string[];\n };\n const cwd = getCloudflareWorkspaceRoot(config);\n const result = await executeCloudflareCode(input, config);\n return [\n formatCloudflareOutput(result, cwd),\n {\n session_id: 'cloudflare-sandbox',\n files: [],\n } satisfies t.CodeExecutionArtifact,\n ];\n },\n {\n name: CodeExecutionToolName,\n description: CloudflareCodeExecutionToolDescription,\n schema: CodeExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createCloudflareBashExecutionTool(options: {\n config: t.CloudflareSandboxExecutionConfig;\n enableToolOutputReferences?: boolean;\n}): DynamicStructuredTool {\n const { config } = options;\n return tool(\n async (rawInput) => {\n const input = rawInput as { command: string; args?: string[] };\n const cwd = getCloudflareWorkspaceRoot(config);\n const result = await executeCloudflareBash(\n input.command,\n config,\n input.args ?? []\n );\n return [\n formatCloudflareOutput(result, cwd),\n {\n session_id: 'cloudflare-sandbox',\n files: [],\n } satisfies t.CodeExecutionArtifact,\n ];\n },\n {\n name: BashExecutionToolName,\n description:\n options.enableToolOutputReferences === true\n ? `${CloudflareBashExecutionToolDescription}\\n\\n${BashToolOutputReferencesGuide}`\n : CloudflareBashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport type CloudflareCodingToolBundle = {\n tools: DynamicStructuredTool[];\n checkpointer?: t.LocalFileCheckpointer;\n};\n\nfunction getSelectedCodingToolNames(\n config: t.CloudflareSandboxExecutionConfig\n): Set<string> {\n return new Set(config.codingToolNames ?? CLOUDFLARE_CODING_TOOL_NAMES);\n}\n\nexport function createCloudflareCodingTools(\n config: t.CloudflareSandboxExecutionConfig,\n options: { checkpointer?: t.LocalFileCheckpointer } = {}\n): DynamicStructuredTool[] {\n const localConfig = createCloudflareLocalExecutionConfig(config);\n const checkpointer =\n options.checkpointer ??\n (config.fileCheckpointing === true\n ? createLocalFileCheckpointer({\n fs: createCloudflareWorkspaceFS(config),\n })\n : undefined);\n const tools = [\n [Constants.READ_FILE, createLocalReadFileTool(localConfig)],\n [Constants.WRITE_FILE, createLocalWriteFileTool(localConfig, checkpointer)],\n [Constants.EDIT_FILE, createLocalEditFileTool(localConfig, checkpointer)],\n [Constants.GREP_SEARCH, createLocalGrepSearchTool(localConfig)],\n [Constants.GLOB_SEARCH, createLocalGlobSearchTool(localConfig)],\n [Constants.LIST_DIRECTORY, createLocalListDirectoryTool(localConfig)],\n [Constants.COMPILE_CHECK, createCompileCheckTool(localConfig)],\n [Constants.BASH_TOOL, createCloudflareBashExecutionTool({ config })],\n [Constants.EXECUTE_CODE, createCloudflareCodeExecutionTool(config)],\n [\n Constants.PROGRAMMATIC_TOOL_CALLING,\n createCloudflareProgrammaticToolCallingTool(config),\n ],\n [\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n createCloudflareBashProgrammaticToolCallingTool(config),\n ],\n ] satisfies Array<[string, DynamicStructuredTool]>;\n const selectedNames = getSelectedCodingToolNames(config);\n return tools\n .filter(([name]) => selectedNames.has(name))\n .map(([, selectedTool]) => selectedTool);\n}\n\nexport function createCloudflareCodingToolBundle(\n config: t.CloudflareSandboxExecutionConfig,\n options: { checkpointer?: t.LocalFileCheckpointer } = {}\n): CloudflareCodingToolBundle {\n const checkpointer =\n options.checkpointer ??\n (config.fileCheckpointing === true\n ? createLocalFileCheckpointer({\n fs: createCloudflareWorkspaceFS(config),\n })\n : undefined);\n return {\n tools: createCloudflareCodingTools(config, { checkpointer }),\n checkpointer,\n };\n}\n\nexport function createCloudflareExecutionTool(\n name: string,\n config: t.CloudflareSandboxExecutionConfig\n): t.GenericTool | undefined {\n switch (name) {\n case Constants.EXECUTE_CODE:\n return createCloudflareCodeExecutionTool(config);\n case Constants.BASH_TOOL:\n return createCloudflareBashExecutionTool({ config });\n case Constants.PROGRAMMATIC_TOOL_CALLING:\n return createCloudflareProgrammaticToolCallingTool(config);\n case Constants.BASH_PROGRAMMATIC_TOOL_CALLING:\n return createCloudflareBashProgrammaticToolCallingTool(config);\n default:\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;AAoCA,MAAa,+BAAkD;;;;;;;;;;;;AAY/D;AAEA,MAAa,oCAAuD;;;;;;;;;;AAUpE;AAEA,MAAa,yCAAyC;;;;;;;EAOpD,KAAK;AAEP,MAAa,yCAAyC;;;;;;;EAOpD,KAAK;AAEP,SAAgB,kCACd,QACuB;CACvB,QAAA,GAAA,sBAAA,KAAA,CACE,OAAO,aAAa;EAClB,MAAM,QAAQ;EAKd,MAAM,MAAMA,yCAAAA,2BAA2B,MAAM;EA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,0BAA0B,WAAW,CAAC;EAC9D,CAAA,kBAA2BC,yBAAAA,6BAA6B,WAAW,CAAC;EACpE,CAAA,iBAA0BC,yBAAAA,uBAAuB,WAAW,CAAC;EAC7D,CAAA,aAAsB,kCAAkC,EAAE,OAAO,CAAC,CAAC;EACnE,CAAA,gBAAyB,kCAAkC,MAAM,CAAC;EAClE,CAAA,uBAEEC,0CAAAA,4CAA4C,MAAM,CACpD;EACA,CAAA,uBAEEC,0CAAAA,gDAAgD,MAAM,CACxD;CACF;CACA,MAAM,gBAAgB,2BAA2B,MAAM;CACvD,OAAO,MACJ,QAAQ,CAAC,UAAU,cAAc,IAAI,IAAI,CAAC,CAAC,CAC3C,KAAK,GAAG,kBAAkB,YAAY;AAC3C;AAEA,SAAgB,iCACd,QACA,UAAsD,CAAC,GAC3B;CAC5B,MAAM,eACJ,QAAQ,iBACP,OAAO,sBAAsB,OAC1BV,yBAAAA,4BAA4B,EAC5B,IAAIC,yCAAAA,4BAA4B,MAAM,EACxC,CAAC,IACC,KAAA;CACN,OAAO;EACL,OAAO,4BAA4B,QAAQ,EAAE,aAAa,CAAC;EAC3D;CACF;AACF;AAEA,SAAgB,8BACd,MACA,QAC2B;CAC3B,QAAQ,MAAR;EACA,KAAA,gBACE,OAAO,kCAAkC,MAAM;EACjD,KAAA,aACE,OAAO,kCAAkC,EAAE,OAAO,CAAC;EACrD,KAAA,uBACE,OAAOQ,0CAAAA,4CAA4C,MAAM;EAC3D,KAAA,uBACE,OAAOC,0CAAAA,gDAAgD,MAAM;EAC/D,SACE;CACF;AACF"}
1
+ {"version":3,"file":"CloudflareSandboxTools.cjs","names":["getCloudflareWorkspaceRoot","formatCloudflareOutput","executeCloudflareCode","CodeExecutionToolName","CodeExecutionToolSchema","executeCloudflareBash","BashExecutionToolName","BashToolOutputReferencesGuide","BashExecutionToolSchema","createCloudflareLocalExecutionConfig","createLocalFileCheckpointer","createCloudflareWorkspaceFS","createLocalReadFileTool","createLocalWriteFileTool","createLocalEditFileTool","createLocalGrepSearchTool","createLocalGlobSearchTool","createLocalListDirectoryTool","createCompileCheckTool","createCloudflareProgrammaticToolCallingTool","createCloudflareBashProgrammaticToolCallingTool"],"sources":["../../../../src/tools/cloudflare/CloudflareSandboxTools.ts"],"mappings":";;;;;;;;;;;AAoCA,MAAa,+BAAkD;;;;;;;;;;;;AAY/D;AAEA,MAAa,oCAAuD;;;;;;;;;;AAUpE;AAEA,MAAa,yCAAyC;;;;;;;EAOpD,KAAK;AAEP,MAAa,yCAAyC;;;;;;;EAOpD,KAAK;AAEP,SAAgB,kCACd,QACuB;CACvB,QAAA,GAAA,sBAAA,KAAA,CACE,OAAO,aAAa;EAClB,MAAM,QAAQ;EAKd,MAAM,MAAMA,yCAAAA,2BAA2B,MAAM;EAE7C,OAAO,CACLC,yCAAAA,uBAAuB,MAFJC,yCAAAA,sBAAsB,OAAO,MAAM,GAEvB,GAAG,GAClC;GACE,YAAY;GACZ,OAAO,CAAC;EACV,CACF;CACF,GACA;EACE,MAAMC,qBAAAA;EACN,aAAa;EACb,QAAQC,qBAAAA;EACR,gBAAA;CACF,CACF;AACF;AAEA,SAAgB,kCAAkC,SAGxB;CACxB,MAAM,EAAE,WAAW;CACnB,QAAA,GAAA,sBAAA,KAAA,CACE,OAAO,aAAa;EAClB,MAAM,QAAQ;EACd,MAAM,MAAMJ,yCAAAA,2BAA2B,MAAM;EAM7C,OAAO,CACLC,yCAAAA,uBAAuB,MANJI,yCAAAA,sBACnB,MAAM,SACN,QACA,MAAM,QAAQ,CAAC,CACjB,GAEiC,GAAG,GAClC;GACE,YAAY;GACZ,OAAO,CAAC;EACV,CACF;CACF,GACA;EACE,MAAMC,qBAAAA;EACN,aACE,QAAQ,+BAA+B,OACnC,GAAG,uCAAuC,MAAMC,qBAAAA,kCAChD;EACN,QAAQC,qBAAAA;EACR,gBAAA;CACF,CACF;AACF;AAOA,SAAS,2BACP,QACa;CACb,OAAO,IAAI,IAAI,OAAO,mBAAmB,4BAA4B;AACvE;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,MAAR;EACA,KAAA,gBACE,OAAO,kCAAkC,MAAM;EACjD,KAAA,aACE,OAAO,kCAAkC,EAAE,OAAO,CAAC;EACrD,KAAA,uBACE,OAAOQ,0CAAAA,4CAA4C,MAAM;EAC3D,KAAA,uBACE,OAAOC,0CAAAA,gDAAgD,MAAM;EAC/D,SACE;CACF;AACF"}
@@ -22,12 +22,6 @@ function recordArgsEqual(left, right) {
22
22
  function normalizeError(error) {
23
23
  return error instanceof Error ? error : new Error(String(error));
24
24
  }
25
- /**
26
- * Stateful runtime session hint for the remote sandbox: only when
27
- * `toolExecution.sandbox.statefulSessions` is on; explicit host hint else the
28
- * conversation `thread_id`. Undefined disables the wire field. Shared by the
29
- * direct ToolNode path and both event-driven planners so they stay in lockstep.
30
- */
31
25
  function resolveRuntimeSessionHint(toolExecution, threadId) {
32
26
  const sandbox = toolExecution?.sandbox;
33
27
  if (sandbox?.statefulSessions !== true) return;
@@ -1 +1 @@
1
- {"version":3,"file":"eagerEventExecution.cjs","names":[],"sources":["../../../src/tools/eagerEventExecution.ts"],"sourcesContent":["import type * as t from '@/types';\n\nexport function coerceRecordArgs(\n args: unknown\n): Record<string, unknown> | undefined {\n if (typeof args === 'string') {\n try {\n const parsed = JSON.parse(args) as unknown;\n return coerceRecordArgs(parsed);\n } catch {\n return undefined;\n }\n }\n\n if (args === null || typeof args !== 'object' || Array.isArray(args)) {\n return undefined;\n }\n\n return args as Record<string, unknown>;\n}\n\nexport function stableStringify(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(',')}]`;\n }\n\n if (value !== null && typeof value === 'object') {\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n return `{${keys\n .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)\n .join(',')}}`;\n }\n\n return JSON.stringify(value);\n}\n\nexport function recordArgsEqual(\n left: Record<string, unknown>,\n right: Record<string, unknown>\n): boolean {\n return stableStringify(left) === stableStringify(right);\n}\n\nexport function normalizeError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nexport type ToolExecutionPlanCall = {\n id?: string;\n name: string;\n args: unknown;\n stepId?: string;\n codeSessionContext?: t.ToolCallRequest['codeSessionContext'];\n runtimeSessionHint?: string;\n};\n\n/**\n * Stateful runtime session hint for the remote sandbox: only when\n * `toolExecution.sandbox.statefulSessions` is on; explicit host hint else the\n * conversation `thread_id`. Undefined disables the wire field. Shared by the\n * direct ToolNode path and both event-driven planners so they stay in lockstep.\n */\nexport function resolveRuntimeSessionHint(\n toolExecution: t.ToolExecutionConfig | undefined,\n threadId: string | undefined\n): string | undefined {\n const sandbox = toolExecution?.sandbox;\n if (sandbox?.statefulSessions !== true) {\n return undefined;\n }\n const explicit = sandbox.runtimeSessionHint;\n if (explicit != null && explicit !== '') {\n return explicit;\n }\n return threadId != null && threadId !== '' ? threadId : undefined;\n}\n\nexport type ToolExecutionRequestPlan = {\n allRequests: t.ToolCallRequest[];\n requests: t.ToolCallRequest[];\n rejectedResults: t.ToolExecuteResult[];\n};\n\nexport function buildToolExecutionRequestPlan(args: {\n toolCalls: ToolExecutionPlanCall[];\n usageCount: Map<string, number>;\n invalidArgsBehavior?: 'abort' | 'error-result';\n recordTurn?: (toolName: string, turn: number, callId: string) => void;\n}): ToolExecutionRequestPlan | undefined {\n const invalidArgsBehavior = args.invalidArgsBehavior ?? 'abort';\n const prepared: Array<{\n id: string;\n name: string;\n args: Record<string, unknown>;\n stepId?: string;\n codeSessionContext?: t.ToolCallRequest['codeSessionContext'];\n runtimeSessionHint?: string;\n rejectedErrorMessage?: string;\n }> = [];\n\n for (const toolCall of args.toolCalls) {\n if (toolCall.id == null || toolCall.id === '' || toolCall.name === '') {\n return undefined;\n }\n const coercedArgs = coerceRecordArgs(toolCall.args);\n if (coercedArgs == null) {\n if (invalidArgsBehavior === 'abort') {\n return undefined;\n }\n prepared.push({\n id: toolCall.id,\n name: toolCall.name,\n args: {},\n stepId: toolCall.stepId,\n codeSessionContext: toolCall.codeSessionContext,\n runtimeSessionHint: toolCall.runtimeSessionHint,\n rejectedErrorMessage:\n 'Invalid tool call arguments: expected a JSON object.',\n });\n continue;\n }\n prepared.push({\n id: toolCall.id,\n name: toolCall.name,\n args: coercedArgs,\n stepId: toolCall.stepId,\n codeSessionContext: toolCall.codeSessionContext,\n runtimeSessionHint: toolCall.runtimeSessionHint,\n });\n }\n\n const nextUsageCount = new Map(args.usageCount);\n const allRequests = prepared.map((toolCall): t.ToolCallRequest => {\n const turn = nextUsageCount.get(toolCall.name) ?? 0;\n nextUsageCount.set(toolCall.name, turn + 1);\n const request: t.ToolCallRequest = {\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n stepId: toolCall.stepId,\n turn,\n };\n if (toolCall.codeSessionContext != null) {\n request.codeSessionContext = toolCall.codeSessionContext;\n }\n if (\n toolCall.runtimeSessionHint != null &&\n toolCall.runtimeSessionHint !== ''\n ) {\n request.runtimeSessionHint = toolCall.runtimeSessionHint;\n }\n return request;\n });\n const requests = allRequests.filter(\n (_, index) => prepared[index].rejectedErrorMessage == null\n );\n const rejectedResults = prepared.flatMap((toolCall) => {\n if (toolCall.rejectedErrorMessage == null) {\n return [];\n }\n return [\n {\n toolCallId: toolCall.id,\n status: 'error' as const,\n content: '',\n errorMessage: toolCall.rejectedErrorMessage,\n },\n ];\n });\n\n for (const [toolName, count] of nextUsageCount) {\n args.usageCount.set(toolName, count);\n }\n for (const request of allRequests) {\n args.recordTurn?.(request.name, request.turn ?? 0, request.id);\n }\n\n return { allRequests, requests, rejectedResults };\n}\n"],"mappings":";AAEA,SAAgB,iBACd,MACqC;CACrC,IAAI,OAAO,SAAS,UAClB,IAAI;EAEF,OAAO,iBADQ,KAAK,MAAM,IACG,CAAC;CAChC,QAAQ;EACN;CACF;CAGF,IAAI,SAAS,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GACjE;CAGF,OAAO;AACT;AAEA,SAAgB,gBAAgB,OAAwB;CACtD,I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ACf,MAAM,CAAC;IACP,QAAQ,SAAS;IACjB,oBAAoB,SAAS;IAC7B,oBAAoB,SAAS;IAC7B,sBACE;GACJ,CAAC;GACD;EACF;EACA,SAAS,KAAK;GACZ,IAAI,SAAS;GACb,MAAM,SAAS;GACf,MAAM;GACN,QAAQ,SAAS;GACjB,oBAAoB,SAAS;GAC7B,oBAAoB,SAAS;EAC/B,CAAC;CACH;CAEA,MAAM,iBAAiB,IAAI,IAAI,KAAK,UAAU;CAC9C,MAAM,cAAc,SAAS,KAAK,aAAgC;EAChE,MAAM,OAAO,eAAe,IAAI,SAAS,IAAI,KAAK;EAClD,eAAe,IAAI,SAAS,MAAM,OAAO,CAAC;EAC1C,MAAM,UAA6B;GACjC,IAAI,SAAS;GACb,MAAM,SAAS;GACf,MAAM,SAAS;GACf,QAAQ,SAAS;GACjB;EACF;EACA,IAAI,SAAS,sBAAsB,MACjC,QAAQ,qBAAqB,SAAS;EAExC,IACE,SAAS,sBAAsB,QAC/B,SAAS,uBAAuB,IAEhC,QAAQ,qBAAqB,SAAS;EAExC,OAAO;CACT,CAAC;CACD,MAAM,WAAW,YAAY,QAC1B,GAAG,UAAU,SAAS,MAAM,CAAC,wBAAwB,IACxD;CACA,MAAM,kBAAkB,SAAS,SAAS,aAAa;EACrD,IAAI,SAAS,wBAAwB,MACnC,OAAO,CAAC;EAEV,OAAO,CACL;GACE,YAAY,SAAS;GACrB,QAAQ;GACR,SAAS;GACT,cAAc,SAAS;EACzB,CACF;CACF,CAAC;CAED,KAAK,MAAM,CAAC,UAAU,UAAU,gBAC9B,KAAK,WAAW,IAAI,UAAU,KAAK;CAErC,KAAK,MAAM,WAAW,aACpB,KAAK,aAAa,QAAQ,MAAM,QAAQ,QAAQ,GAAG,QAAQ,EAAE;CAG/D,OAAO;EAAE;EAAa;EAAU;CAAgB;AAClD"}
@@ -14,7 +14,6 @@ async function handleToolCallChunks({ graph, stepKey, toolCallChunks, metadata }
14
14
  prevStepId = graph.getStepIdByKey(stepKey);
15
15
  prevRunStep = graph.getRunStep(prevStepId);
16
16
  } catch {
17
- /** Edge Case: If no previous step exists, create a new message creation step */
18
17
  const message_id = require_ids.getMessageId(stepKey, graph, true) ?? "";
19
18
  prevStepId = await graph.dispatchRunStep(stepKey, {
20
19
  type: "message_creation",
@@ -23,9 +22,7 @@ async function handleToolCallChunks({ graph, stepKey, toolCallChunks, metadata }
23
22
  prevRunStep = graph.getRunStep(prevStepId);
24
23
  }
25
24
  const _stepId = graph.getStepIdByKey(stepKey);
26
- /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */
27
25
  const tool_calls = prevStepId && prevRunStep && prevRunStep.type === "message_creation" ? [] : void 0;
28
- /** Edge Case: `id` and `name` fields cannot be empty strings */
29
26
  for (const toolCallChunk of toolCallChunks) {
30
27
  if (toolCallChunk.name === "") toolCallChunk.name = void 0;
31
28
  if (toolCallChunk.id === "") toolCallChunk.id = void 0;
@@ -38,23 +35,8 @@ async function handleToolCallChunks({ graph, stepKey, toolCallChunks, metadata }
38
35
  }
39
36
  let stepId = _stepId;
40
37
  const alreadyDispatched = prevRunStep?.type === "message_creation" && graph.messageStepHasToolCalls.has(prevStepId);
41
- if (prevRunStep?.type === "tool_calls")
42
- /**
43
- * If previous step is already a tool_calls step, use that step ID
44
- * This ensures tool call deltas are dispatched to the correct step
45
- */
46
- stepId = prevStepId;
38
+ if (prevRunStep?.type === "tool_calls") stepId = prevStepId;
47
39
  else if (!alreadyDispatched && prevRunStep?.type === "message_creation") {
48
- /**
49
- * Create tool_calls step as soon as we receive the first tool call chunk
50
- * This ensures deltas are always associated with the correct step
51
- *
52
- * NOTE: We do NOT dispatch an empty text block here because:
53
- * - Empty text blocks cause providers (Anthropic, Bedrock) to reject messages
54
- * - The tool_calls themselves are sufficient for the step
55
- * - Empty content with tool_call_ids gets stored in conversation history
56
- * and causes "messages must have non-empty content" errors on replay
57
- */
58
40
  graph.messageStepHasToolCalls.set(prevStepId, true);
59
41
  stepId = await graph.dispatchRunStep(stepKey, {
60
42
  type: "tool_calls",
@@ -74,11 +56,6 @@ const handleToolCalls = async (toolCalls, metadata, graph) => {
74
56
  if (!toolCalls) return;
75
57
  if (toolCalls.length === 0) return;
76
58
  const stepKey = graph.getStepKey(metadata);
77
- /**
78
- * Track whether we've already reused an empty TOOL_CALLS step created by
79
- * handleToolCallChunks during streaming. Only reuse it once (for the first
80
- * tool call); subsequent parallel tool calls must create their own steps.
81
- */
82
59
  let reusedChunkStepId;
83
60
  for (const tool_call of toolCalls) {
84
61
  const toolCallId = tool_call.id ?? `toolu_${(0, nanoid.nanoid)()}`;
@@ -90,11 +67,6 @@ const handleToolCalls = async (toolCalls, metadata, graph) => {
90
67
  prevStepId = graph.getStepIdByKey(stepKey);
91
68
  prevRunStep = graph.getRunStep(prevStepId);
92
69
  } catch {}
93
- /**
94
- * If the previous step is TOOL_CALLS (from handleToolCallChunks or a prior
95
- * iteration), either reuse it (if empty) or dispatch a new TOOL_CALLS step
96
- * directly — skip the intermediate MESSAGE_CREATION to avoid orphaned gaps.
97
- */
98
70
  if (prevRunStep?.type === "tool_calls") {
99
71
  const details = prevRunStep.stepDetails;
100
72
  if ((!details.tool_calls || details.tool_calls.length === 0) && prevStepId !== reusedChunkStepId) {
@@ -109,14 +81,6 @@ const handleToolCalls = async (toolCalls, metadata, graph) => {
109
81
  }, metadata);
110
82
  continue;
111
83
  }
112
- /**
113
- * NOTE: We do NOT dispatch empty text blocks with tool_call_ids because:
114
- * - Empty text blocks cause providers (Anthropic, Bedrock) to reject messages
115
- * - They get stored in conversation history and cause errors on replay:
116
- * "messages must have non-empty content" (Anthropic)
117
- * "The content field in the Message object is empty" (Bedrock)
118
- * - The tool_calls themselves are sufficient
119
- */
120
84
  if (prevStepId && prevRunStep) graph.messageStepHasToolCalls.set(prevStepId, true);
121
85
  else if (!prevRunStep) {
122
86
  const messageId = require_ids.getMessageId(stepKey, graph, true) ?? "";
@@ -137,10 +101,6 @@ const toolResultTypes = new Set([
137
101
  "web_search_result",
138
102
  "web_search_tool_result"
139
103
  ]);
140
- /**
141
- * Handles the result of a server tool call; in other words, a provider's built-in tool.
142
- * As of 2025-07-06, only Anthropic handles server tool calls with this pattern.
143
- */
144
104
  async function handleServerToolResult({ graph, content, metadata, agentContext }) {
145
105
  let skipHandling = false;
146
106
  if (agentContext?.provider !== "anthropic") return skipHandling;
@@ -1 +1 @@
1
- {"version":3,"file":"handlers.cjs","names":["getMessageId","isAnthropicWebSearchResult","coerceAnthropicSearchResults","formatResultsForLLM","ToolMessage"],"sources":["../../../src/tools/handlers.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/tools/handlers.ts\nimport { nanoid } from 'nanoid';\nimport { ToolMessage } from '@langchain/core/messages';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { AnthropicWebSearchResultBlockParam } from '@/llm/anthropic/types';\nimport type { Graph, MultiAgentGraph, StandardGraph } from '@/graphs';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type * as t from '@/types';\nimport {\n coerceAnthropicSearchResults,\n isAnthropicWebSearchResult,\n} from '@/tools/search/anthropic';\nimport {\n ToolCallTypes,\n GraphEvents,\n StepTypes,\n Providers,\n Constants,\n} from '@/common';\nimport { formatResultsForLLM } from '@/tools/search/format';\nimport { getMessageId } from '@/messages';\n\nexport async function handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks,\n metadata,\n}: {\n graph: StandardGraph | MultiAgentGraph;\n stepKey: string;\n toolCallChunks: ToolCallChunk[];\n metadata?: Record<string, unknown>;\n}): Promise<void> {\n let prevStepId: string;\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n /** Edge Case: If no previous step exists, create a new message creation step */\n const message_id = getMessageId(stepKey, graph, true) ?? '';\n prevStepId = await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n prevRunStep = graph.getRunStep(prevStepId);\n }\n\n const _stepId = graph.getStepIdByKey(stepKey);\n\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\n\n /** Edge Case: `id` and `name` fields cannot be empty strings */\n for (const toolCallChunk of toolCallChunks) {\n if (toolCallChunk.name === '') {\n toolCallChunk.name = undefined;\n }\n if (toolCallChunk.id === '') {\n toolCallChunk.id = undefined;\n } else if (\n tool_calls != null &&\n toolCallChunk.id != null &&\n toolCallChunk.name != null\n ) {\n tool_calls.push({\n args: {},\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n type: ToolCallTypes.TOOL_CALL,\n });\n }\n }\n\n let stepId: string = _stepId;\n const alreadyDispatched =\n prevRunStep?.type === StepTypes.MESSAGE_CREATION &&\n graph.messageStepHasToolCalls.has(prevStepId);\n\n if (prevRunStep?.type === StepTypes.TOOL_CALLS) {\n /**\n * If previous step is already a tool_calls step, use that step ID\n * This ensures tool call deltas are dispatched to the correct step\n */\n stepId = prevStepId;\n } else if (\n !alreadyDispatched &&\n prevRunStep?.type === StepTypes.MESSAGE_CREATION\n ) {\n /**\n * Create tool_calls step as soon as we receive the first tool call chunk\n * This ensures deltas are always associated with the correct step\n *\n * NOTE: We do NOT dispatch an empty text block here because:\n * - Empty text blocks cause providers (Anthropic, Bedrock) to reject messages\n * - The tool_calls themselves are sufficient for the step\n * - Empty content with tool_call_ids gets stored in conversation history\n * and causes \"messages must have non-empty content\" errors on replay\n */\n graph.messageStepHasToolCalls.set(prevStepId, true);\n stepId = await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.TOOL_CALLS,\n tool_calls: tool_calls ?? [],\n },\n metadata\n );\n }\n\n await graph.dispatchRunStepDelta(\n stepId,\n {\n type: StepTypes.TOOL_CALLS,\n tool_calls: toolCallChunks,\n },\n metadata\n );\n}\n\nexport const handleToolCalls = async (\n toolCalls?: ToolCall[],\n metadata?: Record<string, unknown>,\n graph?: Graph | StandardGraph | MultiAgentGraph\n): Promise<void> => {\n if (!graph || !metadata) {\n console.warn('Graph or metadata not found in `handleToolCalls`');\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n /**\n * Track whether we've already reused an empty TOOL_CALLS step created by\n * handleToolCallChunks during streaming. Only reuse it once (for the first\n * tool call); subsequent parallel tool calls must create their own steps.\n */\n let reusedChunkStepId: string | undefined;\n\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n // no previous step\n }\n\n /**\n * If the previous step is TOOL_CALLS (from handleToolCallChunks or a prior\n * iteration), either reuse it (if empty) or dispatch a new TOOL_CALLS step\n * directly — skip the intermediate MESSAGE_CREATION to avoid orphaned gaps.\n */\n if (prevRunStep?.type === StepTypes.TOOL_CALLS) {\n const details = prevRunStep.stepDetails as t.ToolCallsDetails;\n const isEmpty = !details.tool_calls || details.tool_calls.length === 0;\n if (isEmpty && prevStepId !== reusedChunkStepId) {\n graph.toolCallStepIds.set(toolCallId, prevStepId);\n graph.registerPendingToolCall(toolCallId, prevStepId);\n reusedChunkStepId = prevStepId;\n continue;\n }\n await graph.dispatchRunStep(\n stepKey,\n { type: StepTypes.TOOL_CALLS, tool_calls: [tool_call] },\n metadata\n );\n continue;\n }\n\n /**\n * NOTE: We do NOT dispatch empty text blocks with tool_call_ids because:\n * - Empty text blocks cause providers (Anthropic, Bedrock) to reject messages\n * - They get stored in conversation history and cause errors on replay:\n * \"messages must have non-empty content\" (Anthropic)\n * \"The content field in the Message object is empty\" (Bedrock)\n * - The tool_calls themselves are sufficient\n */\n if (prevStepId && prevRunStep) {\n graph.messageStepHasToolCalls.set(prevStepId, true);\n } else if (!prevRunStep) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n },\n metadata\n );\n graph.messageStepHasToolCalls.set(stepId, true);\n }\n\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.TOOL_CALLS,\n tool_calls: [tool_call],\n },\n metadata\n );\n }\n};\n\nexport const toolResultTypes = new Set([\n // 'tool_use',\n // 'server_tool_use',\n // 'input_json_delta',\n 'tool_result',\n 'web_search_result',\n 'web_search_tool_result',\n]);\n\n/**\n * Handles the result of a server tool call; in other words, a provider's built-in tool.\n * As of 2025-07-06, only Anthropic handles server tool calls with this pattern.\n */\nexport async function handleServerToolResult({\n graph,\n content,\n metadata,\n agentContext,\n}: {\n graph: StandardGraph | MultiAgentGraph;\n content?: string | t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n}): Promise<boolean> {\n let skipHandling = false;\n if (agentContext?.provider !== Providers.ANTHROPIC) {\n return skipHandling;\n }\n if (\n typeof content === 'string' ||\n content == null ||\n content.length === 0 ||\n (content.length === 1 &&\n (content[0] as t.ToolResultContent).tool_use_id == null)\n ) {\n return skipHandling;\n }\n\n for (const contentPart of content) {\n const toolUseId = (contentPart as t.ToolResultContent).tool_use_id;\n if (toolUseId == null || toolUseId === '') {\n continue;\n }\n const stepId = graph.toolCallStepIds.get(toolUseId);\n if (stepId == null || stepId === '') {\n console.warn(\n `Tool use ID ${toolUseId} not found in graph, cannot dispatch tool result.`\n );\n continue;\n }\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(\n `Run step for ${stepId} does not exist, cannot dispatch tool result.`\n );\n continue;\n } else if (runStep.type !== StepTypes.TOOL_CALLS) {\n console.warn(\n `Run step for ${stepId} is not a tool call step, cannot dispatch tool result.`\n );\n continue;\n }\n\n const toolCall =\n runStep.stepDetails.type === StepTypes.TOOL_CALLS\n ? (runStep.stepDetails.tool_calls?.find(\n (toolCall) => toolCall.id === toolUseId\n ) as ToolCall)\n : undefined;\n\n if (!toolCall) {\n continue;\n }\n\n if (\n contentPart.type === 'web_search_result' ||\n contentPart.type === 'web_search_tool_result'\n ) {\n await handleAnthropicSearchResults({\n contentPart: contentPart as t.ToolResultContent,\n toolCall,\n metadata,\n graph,\n });\n }\n\n if (!skipHandling) {\n skipHandling = true;\n }\n }\n\n return skipHandling;\n}\n\nasync function handleAnthropicSearchResults({\n contentPart,\n toolCall,\n metadata,\n graph,\n}: {\n contentPart: t.ToolResultContent;\n toolCall: Partial<ToolCall>;\n metadata?: Record<string, unknown>;\n graph: StandardGraph | MultiAgentGraph;\n}): Promise<void> {\n if (!Array.isArray(contentPart.content)) {\n console.warn(\n `Expected content to be an array, got ${typeof contentPart.content}`\n );\n return;\n }\n\n if (!isAnthropicWebSearchResult(contentPart.content[0])) {\n console.warn(\n `Expected content to be an Anthropic web search result, got ${JSON.stringify(\n contentPart.content\n )}`\n );\n return;\n }\n\n const turn = graph.invokedToolIds?.size ?? 0;\n const searchResultData = coerceAnthropicSearchResults({\n turn,\n results: contentPart.content as AnthropicWebSearchResultBlockParam[],\n });\n\n const name = toolCall.name;\n const input = toolCall.args ?? {};\n const artifact = {\n [Constants.WEB_SEARCH]: searchResultData,\n };\n const { output: formattedOutput } = formatResultsForLLM(\n turn,\n searchResultData\n );\n const output = new ToolMessage({\n name,\n artifact,\n content: formattedOutput,\n tool_call_id: toolCall.id!,\n });\n const toolEndData: t.ToolEndData = {\n input,\n output,\n };\n await graph.handlerRegistry\n ?.getHandler(GraphEvents.TOOL_END)\n ?.handle(GraphEvents.TOOL_END, toolEndData, metadata, graph);\n\n if (graph.invokedToolIds == null) {\n graph.invokedToolIds = new Set<string>();\n }\n\n graph.invokedToolIds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pD;EACA,SAAS,YAAY;CACvB,CAAC;CAED,MAAM,OAAO,SAAS;CACtB,MAAM,QAAQ,SAAS,QAAQ,CAAC;CAChC,MAAM,WAAW,GAAA,eACS,iBAC1B;CACA,MAAM,EAAE,QAAQ,oBAAoBC,eAAAA,oBAClC,MACA,gBACF;CAOA,MAAM,cAA6B;EACjC;EACA,QAAA,IARiBC,yBAAAA,YAAY;GAC7B;GACA;GACA,SAAS;GACT,cAAc,SAAS;EACzB,CAGO;CACP;CACA,MAAM,MAAM,iBACR,WAAA,aAA+B,CAAC,EAChC,OAAA,eAA6B,aAAa,UAAU,KAAK;CAE7D,IAAI,MAAM,kBAAkB,MAC1B,MAAM,iCAAiB,IAAI,IAAY;CAGzC,MAAM,eAAe,IAAI,SAAS,EAAG;AACvC"}
1
+ {"version":3,"file":"handlers.cjs","names":["getMessageId","isAnthropicWebSearchResult","coerceAnthropicSearchResults","formatResultsForLLM","ToolMessage"],"sources":["../../../src/tools/handlers.ts"],"mappings":";;;;;;;;;AAuBA,eAAsB,qBAAqB,EACzC,OACA,SACA,gBACA,YAMgB;CAChB,IAAI;CACJ,IAAI;CACJ,IAAI;EACF,aAAa,MAAM,eAAe,OAAO;EACzC,cAAc,MAAM,WAAW,UAAU;CAC3C,QAAQ;EAEN,MAAM,aAAaA,YAAAA,aAAa,SAAS,OAAO,IAAI,KAAK;EACzD,aAAa,MAAM,MAAM,gBACvB,SACA;GACE,MAAA;GACA,kBAAkB,EAChB,WACF;EACF,GACA,QACF;EACA,cAAc,MAAM,WAAW,UAAU;CAC3C;CAEA,MAAM,UAAU,MAAM,eAAe,OAAO;CAG5C,MAAM,aACJ,cAAc,eAAe,YAAY,SAAA,qBACrC,CAAC,IACD,KAAA;CAGN,KAAK,MAAM,iBAAiB,gBAAgB;EAC1C,IAAI,cAAc,SAAS,IACzB,cAAc,OAAO,KAAA;EAEvB,IAAI,cAAc,OAAO,IACvB,cAAc,KAAK,KAAA;OACd,IACL,cAAc,QACd,cAAc,MAA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