@librechat/agents 3.2.32 → 3.2.33

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 (573) hide show
  1. package/dist/cjs/_virtual/_rolldown/runtime.cjs +23 -0
  2. package/dist/cjs/agents/AgentContext.cjs +844 -1046
  3. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  4. package/dist/cjs/common/constants.cjs +13 -13
  5. package/dist/cjs/common/constants.cjs.map +1 -1
  6. package/dist/cjs/common/enum.cjs +233 -240
  7. package/dist/cjs/common/enum.cjs.map +1 -1
  8. package/dist/cjs/common/index.cjs +2 -0
  9. package/dist/cjs/events.cjs +121 -169
  10. package/dist/cjs/events.cjs.map +1 -1
  11. package/dist/cjs/graphs/Graph.cjs +1389 -1807
  12. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  13. package/dist/cjs/graphs/MultiAgentGraph.cjs +713 -945
  14. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  15. package/dist/cjs/graphs/index.cjs +2 -0
  16. package/dist/cjs/hitl/askUserQuestion.cjs +60 -62
  17. package/dist/cjs/hitl/askUserQuestion.cjs.map +1 -1
  18. package/dist/cjs/hitl/index.cjs +1 -0
  19. package/dist/cjs/hooks/HookRegistry.cjs +176 -202
  20. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -1
  21. package/dist/cjs/hooks/createToolPolicyHook.cjs +71 -101
  22. package/dist/cjs/hooks/createToolPolicyHook.cjs.map +1 -1
  23. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs +170 -273
  24. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs.map +1 -1
  25. package/dist/cjs/hooks/executeHooks.cjs +227 -282
  26. package/dist/cjs/hooks/executeHooks.cjs.map +1 -1
  27. package/dist/cjs/hooks/index.cjs +6 -0
  28. package/dist/cjs/hooks/matchers.cjs +196 -230
  29. package/dist/cjs/hooks/matchers.cjs.map +1 -1
  30. package/dist/cjs/hooks/types.cjs +24 -24
  31. package/dist/cjs/hooks/types.cjs.map +1 -1
  32. package/dist/cjs/instrumentation.cjs +110 -137
  33. package/dist/cjs/instrumentation.cjs.map +1 -1
  34. package/dist/cjs/langchain/google-common.cjs +0 -3
  35. package/dist/cjs/langchain/index.cjs +80 -43
  36. package/dist/cjs/langchain/language_models/chat_models.cjs +0 -3
  37. package/dist/cjs/langchain/messages/tool.cjs +0 -3
  38. package/dist/cjs/langchain/messages.cjs +35 -18
  39. package/dist/cjs/langchain/openai.cjs +0 -3
  40. package/dist/cjs/langchain/prompts.cjs +5 -8
  41. package/dist/cjs/langchain/runnables.cjs +11 -10
  42. package/dist/cjs/langchain/tools.cjs +14 -11
  43. package/dist/cjs/langchain/utils/env.cjs +5 -8
  44. package/dist/cjs/langfuse.cjs +60 -79
  45. package/dist/cjs/langfuse.cjs.map +1 -1
  46. package/dist/cjs/langfuseToolOutputTracing.cjs +267 -399
  47. package/dist/cjs/langfuseToolOutputTracing.cjs.map +1 -1
  48. package/dist/cjs/llm/anthropic/index.cjs +432 -562
  49. package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
  50. package/dist/cjs/llm/anthropic/types.cjs +23 -47
  51. package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
  52. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +441 -731
  53. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  54. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +171 -256
  55. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
  56. package/dist/cjs/llm/anthropic/utils/output_parsers.cjs +2 -0
  57. package/dist/cjs/llm/anthropic/utils/tools.cjs +12 -26
  58. package/dist/cjs/llm/anthropic/utils/tools.cjs.map +1 -1
  59. package/dist/cjs/llm/bedrock/index.cjs +195 -240
  60. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  61. package/dist/cjs/llm/bedrock/toolCache.cjs +84 -106
  62. package/dist/cjs/llm/bedrock/toolCache.cjs.map +1 -1
  63. package/dist/cjs/llm/bedrock/utils/index.cjs +2 -0
  64. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +357 -620
  65. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
  66. package/dist/cjs/llm/bedrock/utils/message_outputs.cjs +105 -149
  67. package/dist/cjs/llm/bedrock/utils/message_outputs.cjs.map +1 -1
  68. package/dist/cjs/llm/fake.cjs +86 -96
  69. package/dist/cjs/llm/fake.cjs.map +1 -1
  70. package/dist/cjs/llm/google/index.cjs +183 -237
  71. package/dist/cjs/llm/google/index.cjs.map +1 -1
  72. package/dist/cjs/llm/google/utils/common.cjs +398 -674
  73. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  74. package/dist/cjs/llm/google/utils/zod_to_genai_parameters.cjs +2 -0
  75. package/dist/cjs/llm/init.cjs +44 -53
  76. package/dist/cjs/llm/init.cjs.map +1 -1
  77. package/dist/cjs/llm/invoke.cjs +142 -182
  78. package/dist/cjs/llm/invoke.cjs.map +1 -1
  79. package/dist/cjs/llm/openai/index.cjs +991 -1276
  80. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  81. package/dist/cjs/llm/openai/utils/index.cjs +189 -316
  82. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
  83. package/dist/cjs/llm/openrouter/index.cjs +102 -153
  84. package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
  85. package/dist/cjs/llm/openrouter/toolCache.cjs +35 -44
  86. package/dist/cjs/llm/openrouter/toolCache.cjs.map +1 -1
  87. package/dist/cjs/llm/providers.cjs +29 -37
  88. package/dist/cjs/llm/providers.cjs.map +1 -1
  89. package/dist/cjs/llm/request.cjs +20 -33
  90. package/dist/cjs/llm/request.cjs.map +1 -1
  91. package/dist/cjs/llm/vertexai/index.cjs +427 -453
  92. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  93. package/dist/cjs/main.cjs +547 -528
  94. package/dist/cjs/messages/anthropicToolCache.cjs +68 -119
  95. package/dist/cjs/messages/anthropicToolCache.cjs.map +1 -1
  96. package/dist/cjs/messages/cache.cjs +305 -418
  97. package/dist/cjs/messages/cache.cjs.map +1 -1
  98. package/dist/cjs/messages/content.cjs +36 -49
  99. package/dist/cjs/messages/content.cjs.map +1 -1
  100. package/dist/cjs/messages/contextPruning.cjs +112 -145
  101. package/dist/cjs/messages/contextPruning.cjs.map +1 -1
  102. package/dist/cjs/messages/contextPruningSettings.cjs +36 -46
  103. package/dist/cjs/messages/contextPruningSettings.cjs.map +1 -1
  104. package/dist/cjs/messages/core.cjs +256 -397
  105. package/dist/cjs/messages/core.cjs.map +1 -1
  106. package/dist/cjs/messages/format.cjs +904 -1387
  107. package/dist/cjs/messages/format.cjs.map +1 -1
  108. package/dist/cjs/messages/ids.cjs +16 -20
  109. package/dist/cjs/messages/ids.cjs.map +1 -1
  110. package/dist/cjs/messages/index.cjs +12 -0
  111. package/dist/cjs/messages/langchain.cjs +18 -18
  112. package/dist/cjs/messages/langchain.cjs.map +1 -1
  113. package/dist/cjs/messages/prune.cjs +1054 -1517
  114. package/dist/cjs/messages/prune.cjs.map +1 -1
  115. package/dist/cjs/messages/recency.cjs +77 -95
  116. package/dist/cjs/messages/recency.cjs.map +1 -1
  117. package/dist/cjs/messages/reducer.cjs +63 -78
  118. package/dist/cjs/messages/reducer.cjs.map +1 -1
  119. package/dist/cjs/messages/tools.cjs +51 -79
  120. package/dist/cjs/messages/tools.cjs.map +1 -1
  121. package/dist/cjs/openai/index.cjs +171 -217
  122. package/dist/cjs/openai/index.cjs.map +1 -1
  123. package/dist/cjs/responses/index.cjs +302 -391
  124. package/dist/cjs/responses/index.cjs.map +1 -1
  125. package/dist/cjs/run.cjs +903 -1113
  126. package/dist/cjs/run.cjs.map +1 -1
  127. package/dist/cjs/session/AgentSession.cjs +805 -986
  128. package/dist/cjs/session/AgentSession.cjs.map +1 -1
  129. package/dist/cjs/session/JsonlSessionStore.cjs +327 -410
  130. package/dist/cjs/session/JsonlSessionStore.cjs.map +1 -1
  131. package/dist/cjs/session/handlers.cjs +192 -208
  132. package/dist/cjs/session/handlers.cjs.map +1 -1
  133. package/dist/cjs/session/ids.cjs +9 -10
  134. package/dist/cjs/session/ids.cjs.map +1 -1
  135. package/dist/cjs/session/index.cjs +4 -0
  136. package/dist/cjs/session/messageSerialization.cjs +94 -156
  137. package/dist/cjs/session/messageSerialization.cjs.map +1 -1
  138. package/dist/cjs/splitStream.cjs +147 -206
  139. package/dist/cjs/splitStream.cjs.map +1 -1
  140. package/dist/cjs/stream.cjs +856 -1344
  141. package/dist/cjs/stream.cjs.map +1 -1
  142. package/dist/cjs/summarization/index.cjs +57 -101
  143. package/dist/cjs/summarization/index.cjs.map +1 -1
  144. package/dist/cjs/summarization/node.cjs +643 -796
  145. package/dist/cjs/summarization/node.cjs.map +1 -1
  146. package/dist/cjs/tools/BashExecutor.cjs +110 -136
  147. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  148. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +165 -245
  149. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  150. package/dist/cjs/tools/Calculator.cjs +36 -57
  151. package/dist/cjs/tools/Calculator.cjs.map +1 -1
  152. package/dist/cjs/tools/CodeExecutor.cjs +126 -168
  153. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  154. package/dist/cjs/tools/CodeSessionFileSummary.cjs +36 -46
  155. package/dist/cjs/tools/CodeSessionFileSummary.cjs.map +1 -1
  156. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +459 -649
  157. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  158. package/dist/cjs/tools/ReadFile.cjs +17 -20
  159. package/dist/cjs/tools/ReadFile.cjs.map +1 -1
  160. package/dist/cjs/tools/SkillTool.cjs +26 -27
  161. package/dist/cjs/tools/SkillTool.cjs.map +1 -1
  162. package/dist/cjs/tools/SubagentTool.cjs +59 -61
  163. package/dist/cjs/tools/SubagentTool.cjs.map +1 -1
  164. package/dist/cjs/tools/ToolNode.cjs +2109 -2686
  165. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  166. package/dist/cjs/tools/ToolSearch.cjs +663 -825
  167. package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
  168. package/dist/cjs/tools/cloudflare/CloudflareBridgeRuntime.cjs +248 -340
  169. package/dist/cjs/tools/cloudflare/CloudflareBridgeRuntime.cjs.map +1 -1
  170. package/dist/cjs/tools/cloudflare/CloudflareProgrammaticToolCalling.cjs +170 -197
  171. package/dist/cjs/tools/cloudflare/CloudflareProgrammaticToolCalling.cjs.map +1 -1
  172. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs +425 -520
  173. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs.map +1 -1
  174. package/dist/cjs/tools/cloudflare/CloudflareSandboxTools.cjs +91 -124
  175. package/dist/cjs/tools/cloudflare/CloudflareSandboxTools.cjs.map +1 -1
  176. package/dist/cjs/tools/cloudflare/index.cjs +4 -0
  177. package/dist/cjs/tools/eagerEventExecution.cjs +75 -99
  178. package/dist/cjs/tools/eagerEventExecution.cjs.map +1 -1
  179. package/dist/cjs/tools/handlers.cjs +200 -262
  180. package/dist/cjs/tools/handlers.cjs.map +1 -1
  181. package/dist/cjs/tools/local/CompileCheckTool.cjs +150 -212
  182. package/dist/cjs/tools/local/CompileCheckTool.cjs.map +1 -1
  183. package/dist/cjs/tools/local/FileCheckpointer.cjs +77 -85
  184. package/dist/cjs/tools/local/FileCheckpointer.cjs.map +1 -1
  185. package/dist/cjs/tools/local/LocalCodingTools.cjs +763 -1022
  186. package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -1
  187. package/dist/cjs/tools/local/LocalExecutionEngine.cjs +666 -941
  188. package/dist/cjs/tools/local/LocalExecutionEngine.cjs.map +1 -1
  189. package/dist/cjs/tools/local/LocalExecutionTools.cjs +49 -92
  190. package/dist/cjs/tools/local/LocalExecutionTools.cjs.map +1 -1
  191. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs +286 -354
  192. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs.map +1 -1
  193. package/dist/cjs/tools/local/attachments.cjs +108 -165
  194. package/dist/cjs/tools/local/attachments.cjs.map +1 -1
  195. package/dist/cjs/tools/local/bashAst.cjs +99 -113
  196. package/dist/cjs/tools/local/bashAst.cjs.map +1 -1
  197. package/dist/cjs/tools/local/editStrategies.cjs +126 -169
  198. package/dist/cjs/tools/local/editStrategies.cjs.map +1 -1
  199. package/dist/cjs/tools/local/index.cjs +12 -0
  200. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs +136 -218
  201. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs.map +1 -1
  202. package/dist/cjs/tools/local/syntaxCheck.cjs +142 -161
  203. package/dist/cjs/tools/local/syntaxCheck.cjs.map +1 -1
  204. package/dist/cjs/tools/local/textEncoding.cjs +25 -23
  205. package/dist/cjs/tools/local/textEncoding.cjs.map +1 -1
  206. package/dist/cjs/tools/local/workspaceFS.cjs +38 -46
  207. package/dist/cjs/tools/local/workspaceFS.cjs.map +1 -1
  208. package/dist/cjs/tools/ptcTimeout.cjs +27 -47
  209. package/dist/cjs/tools/ptcTimeout.cjs.map +1 -1
  210. package/dist/cjs/tools/schema.cjs +24 -23
  211. package/dist/cjs/tools/schema.cjs.map +1 -1
  212. package/dist/cjs/tools/search/anthropic.cjs +24 -33
  213. package/dist/cjs/tools/search/anthropic.cjs.map +1 -1
  214. package/dist/cjs/tools/search/content.cjs +95 -137
  215. package/dist/cjs/tools/search/content.cjs.map +1 -1
  216. package/dist/cjs/tools/search/firecrawl.cjs +141 -172
  217. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  218. package/dist/cjs/tools/search/format.cjs +128 -196
  219. package/dist/cjs/tools/search/format.cjs.map +1 -1
  220. package/dist/cjs/tools/search/highlights.cjs +165 -232
  221. package/dist/cjs/tools/search/highlights.cjs.map +1 -1
  222. package/dist/cjs/tools/search/index.cjs +2 -0
  223. package/dist/cjs/tools/search/rerankers.cjs +151 -174
  224. package/dist/cjs/tools/search/rerankers.cjs.map +1 -1
  225. package/dist/cjs/tools/search/schema.cjs +40 -39
  226. package/dist/cjs/tools/search/schema.cjs.map +1 -1
  227. package/dist/cjs/tools/search/search.cjs +428 -530
  228. package/dist/cjs/tools/search/search.cjs.map +1 -1
  229. package/dist/cjs/tools/search/serper-scraper.cjs +106 -127
  230. package/dist/cjs/tools/search/serper-scraper.cjs.map +1 -1
  231. package/dist/cjs/tools/search/tavily-scraper.cjs +129 -181
  232. package/dist/cjs/tools/search/tavily-scraper.cjs.map +1 -1
  233. package/dist/cjs/tools/search/tavily-search.cjs +295 -359
  234. package/dist/cjs/tools/search/tavily-search.cjs.map +1 -1
  235. package/dist/cjs/tools/search/tool.cjs +260 -299
  236. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  237. package/dist/cjs/tools/search/utils.cjs +74 -117
  238. package/dist/cjs/tools/search/utils.cjs.map +1 -1
  239. package/dist/cjs/tools/skillCatalog.cjs +54 -72
  240. package/dist/cjs/tools/skillCatalog.cjs.map +1 -1
  241. package/dist/cjs/tools/streamedToolCallSeals.cjs +19 -36
  242. package/dist/cjs/tools/streamedToolCallSeals.cjs.map +1 -1
  243. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +612 -771
  244. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  245. package/dist/cjs/tools/subagent/index.cjs +1 -0
  246. package/dist/cjs/tools/toolOutputReferences.cjs +523 -630
  247. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
  248. package/dist/cjs/utils/callbacks.cjs +11 -21
  249. package/dist/cjs/utils/callbacks.cjs.map +1 -1
  250. package/dist/cjs/utils/errors.cjs +70 -95
  251. package/dist/cjs/utils/errors.cjs.map +1 -1
  252. package/dist/cjs/utils/events.cjs +32 -42
  253. package/dist/cjs/utils/events.cjs.map +1 -1
  254. package/dist/cjs/utils/graph.cjs +8 -12
  255. package/dist/cjs/utils/graph.cjs.map +1 -1
  256. package/dist/cjs/utils/handlers.cjs +60 -82
  257. package/dist/cjs/utils/handlers.cjs.map +1 -1
  258. package/dist/cjs/utils/index.cjs +9 -0
  259. package/dist/cjs/utils/llm.cjs +19 -27
  260. package/dist/cjs/utils/llm.cjs.map +1 -1
  261. package/dist/cjs/utils/misc.cjs +30 -46
  262. package/dist/cjs/utils/misc.cjs.map +1 -1
  263. package/dist/cjs/utils/run.cjs +50 -66
  264. package/dist/cjs/utils/run.cjs.map +1 -1
  265. package/dist/cjs/utils/schema.cjs +11 -19
  266. package/dist/cjs/utils/schema.cjs.map +1 -1
  267. package/dist/cjs/utils/title.cjs +71 -106
  268. package/dist/cjs/utils/title.cjs.map +1 -1
  269. package/dist/cjs/utils/tokens.cjs +186 -283
  270. package/dist/cjs/utils/tokens.cjs.map +1 -1
  271. package/dist/cjs/utils/truncation.cjs +95 -114
  272. package/dist/cjs/utils/truncation.cjs.map +1 -1
  273. package/dist/esm/agents/AgentContext.mjs +844 -1044
  274. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  275. package/dist/esm/common/constants.mjs +13 -11
  276. package/dist/esm/common/constants.mjs.map +1 -1
  277. package/dist/esm/common/enum.mjs +221 -238
  278. package/dist/esm/common/enum.mjs.map +1 -1
  279. package/dist/esm/common/index.mjs +3 -0
  280. package/dist/esm/events.mjs +121 -167
  281. package/dist/esm/events.mjs.map +1 -1
  282. package/dist/esm/graphs/Graph.mjs +1388 -1804
  283. package/dist/esm/graphs/Graph.mjs.map +1 -1
  284. package/dist/esm/graphs/MultiAgentGraph.mjs +713 -943
  285. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  286. package/dist/esm/graphs/index.mjs +3 -0
  287. package/dist/esm/hitl/askUserQuestion.mjs +60 -60
  288. package/dist/esm/hitl/askUserQuestion.mjs.map +1 -1
  289. package/dist/esm/hitl/index.mjs +2 -0
  290. package/dist/esm/hooks/HookRegistry.mjs +176 -200
  291. package/dist/esm/hooks/HookRegistry.mjs.map +1 -1
  292. package/dist/esm/hooks/createToolPolicyHook.mjs +71 -99
  293. package/dist/esm/hooks/createToolPolicyHook.mjs.map +1 -1
  294. package/dist/esm/hooks/createWorkspacePolicyHook.mjs +170 -271
  295. package/dist/esm/hooks/createWorkspacePolicyHook.mjs.map +1 -1
  296. package/dist/esm/hooks/executeHooks.mjs +227 -280
  297. package/dist/esm/hooks/executeHooks.mjs.map +1 -1
  298. package/dist/esm/hooks/index.mjs +7 -0
  299. package/dist/esm/hooks/matchers.mjs +196 -228
  300. package/dist/esm/hooks/matchers.mjs.map +1 -1
  301. package/dist/esm/hooks/types.mjs +24 -22
  302. package/dist/esm/hooks/types.mjs.map +1 -1
  303. package/dist/esm/instrumentation.mjs +109 -132
  304. package/dist/esm/instrumentation.mjs.map +1 -1
  305. package/dist/esm/langchain/google-common.mjs +1 -2
  306. package/dist/esm/langchain/index.mjs +5 -5
  307. package/dist/esm/langchain/language_models/chat_models.mjs +1 -2
  308. package/dist/esm/langchain/messages/tool.mjs +1 -2
  309. package/dist/esm/langchain/messages.mjs +2 -2
  310. package/dist/esm/langchain/openai.mjs +1 -2
  311. package/dist/esm/langchain/prompts.mjs +2 -2
  312. package/dist/esm/langchain/runnables.mjs +2 -2
  313. package/dist/esm/langchain/tools.mjs +2 -2
  314. package/dist/esm/langchain/utils/env.mjs +2 -2
  315. package/dist/esm/langfuse.mjs +60 -76
  316. package/dist/esm/langfuse.mjs.map +1 -1
  317. package/dist/esm/langfuseToolOutputTracing.mjs +267 -395
  318. package/dist/esm/langfuseToolOutputTracing.mjs.map +1 -1
  319. package/dist/esm/llm/anthropic/index.mjs +432 -559
  320. package/dist/esm/llm/anthropic/index.mjs.map +1 -1
  321. package/dist/esm/llm/anthropic/types.mjs +23 -45
  322. package/dist/esm/llm/anthropic/types.mjs.map +1 -1
  323. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +439 -725
  324. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  325. package/dist/esm/llm/anthropic/utils/message_outputs.mjs +171 -253
  326. package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
  327. package/dist/esm/llm/anthropic/utils/output_parsers.mjs +3 -0
  328. package/dist/esm/llm/anthropic/utils/tools.mjs +12 -24
  329. package/dist/esm/llm/anthropic/utils/tools.mjs.map +1 -1
  330. package/dist/esm/llm/bedrock/index.mjs +195 -238
  331. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  332. package/dist/esm/llm/bedrock/toolCache.mjs +84 -104
  333. package/dist/esm/llm/bedrock/toolCache.mjs.map +1 -1
  334. package/dist/esm/llm/bedrock/utils/index.mjs +3 -0
  335. package/dist/esm/llm/bedrock/utils/message_inputs.mjs +357 -618
  336. package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
  337. package/dist/esm/llm/bedrock/utils/message_outputs.mjs +105 -147
  338. package/dist/esm/llm/bedrock/utils/message_outputs.mjs.map +1 -1
  339. package/dist/esm/llm/fake.mjs +86 -94
  340. package/dist/esm/llm/fake.mjs.map +1 -1
  341. package/dist/esm/llm/google/index.mjs +183 -235
  342. package/dist/esm/llm/google/index.mjs.map +1 -1
  343. package/dist/esm/llm/google/utils/common.mjs +397 -666
  344. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  345. package/dist/esm/llm/google/utils/zod_to_genai_parameters.mjs +3 -0
  346. package/dist/esm/llm/init.mjs +44 -51
  347. package/dist/esm/llm/init.mjs.map +1 -1
  348. package/dist/esm/llm/invoke.mjs +142 -180
  349. package/dist/esm/llm/invoke.mjs.map +1 -1
  350. package/dist/esm/llm/openai/index.mjs +991 -1271
  351. package/dist/esm/llm/openai/index.mjs.map +1 -1
  352. package/dist/esm/llm/openai/utils/index.mjs +188 -312
  353. package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
  354. package/dist/esm/llm/openrouter/index.mjs +102 -151
  355. package/dist/esm/llm/openrouter/index.mjs.map +1 -1
  356. package/dist/esm/llm/openrouter/toolCache.mjs +35 -42
  357. package/dist/esm/llm/openrouter/toolCache.mjs.map +1 -1
  358. package/dist/esm/llm/providers.mjs +29 -34
  359. package/dist/esm/llm/providers.mjs.map +1 -1
  360. package/dist/esm/llm/request.mjs +20 -31
  361. package/dist/esm/llm/request.mjs.map +1 -1
  362. package/dist/esm/llm/vertexai/index.mjs +427 -449
  363. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  364. package/dist/esm/main.mjs +99 -87
  365. package/dist/esm/messages/anthropicToolCache.mjs +68 -117
  366. package/dist/esm/messages/anthropicToolCache.mjs.map +1 -1
  367. package/dist/esm/messages/cache.mjs +305 -416
  368. package/dist/esm/messages/cache.mjs.map +1 -1
  369. package/dist/esm/messages/content.mjs +36 -47
  370. package/dist/esm/messages/content.mjs.map +1 -1
  371. package/dist/esm/messages/contextPruning.mjs +112 -143
  372. package/dist/esm/messages/contextPruning.mjs.map +1 -1
  373. package/dist/esm/messages/contextPruningSettings.mjs +36 -44
  374. package/dist/esm/messages/contextPruningSettings.mjs.map +1 -1
  375. package/dist/esm/messages/core.mjs +254 -393
  376. package/dist/esm/messages/core.mjs.map +1 -1
  377. package/dist/esm/messages/format.mjs +902 -1383
  378. package/dist/esm/messages/format.mjs.map +1 -1
  379. package/dist/esm/messages/ids.mjs +16 -18
  380. package/dist/esm/messages/ids.mjs.map +1 -1
  381. package/dist/esm/messages/index.mjs +13 -0
  382. package/dist/esm/messages/langchain.mjs +18 -16
  383. package/dist/esm/messages/langchain.mjs.map +1 -1
  384. package/dist/esm/messages/prune.mjs +1053 -1514
  385. package/dist/esm/messages/prune.mjs.map +1 -1
  386. package/dist/esm/messages/recency.mjs +77 -93
  387. package/dist/esm/messages/recency.mjs.map +1 -1
  388. package/dist/esm/messages/reducer.mjs +63 -76
  389. package/dist/esm/messages/reducer.mjs.map +1 -1
  390. package/dist/esm/messages/tools.mjs +49 -75
  391. package/dist/esm/messages/tools.mjs.map +1 -1
  392. package/dist/esm/openai/index.mjs +170 -215
  393. package/dist/esm/openai/index.mjs.map +1 -1
  394. package/dist/esm/responses/index.mjs +301 -389
  395. package/dist/esm/responses/index.mjs.map +1 -1
  396. package/dist/esm/run.mjs +903 -1111
  397. package/dist/esm/run.mjs.map +1 -1
  398. package/dist/esm/session/AgentSession.mjs +806 -985
  399. package/dist/esm/session/AgentSession.mjs.map +1 -1
  400. package/dist/esm/session/JsonlSessionStore.mjs +326 -407
  401. package/dist/esm/session/JsonlSessionStore.mjs.map +1 -1
  402. package/dist/esm/session/handlers.mjs +192 -206
  403. package/dist/esm/session/handlers.mjs.map +1 -1
  404. package/dist/esm/session/ids.mjs +9 -8
  405. package/dist/esm/session/ids.mjs.map +1 -1
  406. package/dist/esm/session/index.mjs +5 -0
  407. package/dist/esm/session/messageSerialization.mjs +94 -154
  408. package/dist/esm/session/messageSerialization.mjs.map +1 -1
  409. package/dist/esm/splitStream.mjs +147 -204
  410. package/dist/esm/splitStream.mjs.map +1 -1
  411. package/dist/esm/stream.mjs +854 -1341
  412. package/dist/esm/stream.mjs.map +1 -1
  413. package/dist/esm/summarization/index.mjs +57 -99
  414. package/dist/esm/summarization/index.mjs.map +1 -1
  415. package/dist/esm/summarization/node.mjs +640 -790
  416. package/dist/esm/summarization/node.mjs.map +1 -1
  417. package/dist/esm/tools/BashExecutor.mjs +103 -129
  418. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  419. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +162 -239
  420. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  421. package/dist/esm/tools/Calculator.mjs +34 -36
  422. package/dist/esm/tools/Calculator.mjs.map +1 -1
  423. package/dist/esm/tools/CodeExecutor.mjs +123 -164
  424. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  425. package/dist/esm/tools/CodeSessionFileSummary.mjs +36 -44
  426. package/dist/esm/tools/CodeSessionFileSummary.mjs.map +1 -1
  427. package/dist/esm/tools/ProgrammaticToolCalling.mjs +454 -644
  428. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  429. package/dist/esm/tools/ReadFile.mjs +17 -18
  430. package/dist/esm/tools/ReadFile.mjs.map +1 -1
  431. package/dist/esm/tools/SkillTool.mjs +26 -25
  432. package/dist/esm/tools/SkillTool.mjs.map +1 -1
  433. package/dist/esm/tools/SubagentTool.mjs +59 -59
  434. package/dist/esm/tools/SubagentTool.mjs.map +1 -1
  435. package/dist/esm/tools/ToolNode.mjs +2107 -2684
  436. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  437. package/dist/esm/tools/ToolSearch.mjs +659 -804
  438. package/dist/esm/tools/ToolSearch.mjs.map +1 -1
  439. package/dist/esm/tools/cloudflare/CloudflareBridgeRuntime.mjs +248 -338
  440. package/dist/esm/tools/cloudflare/CloudflareBridgeRuntime.mjs.map +1 -1
  441. package/dist/esm/tools/cloudflare/CloudflareProgrammaticToolCalling.mjs +170 -195
  442. package/dist/esm/tools/cloudflare/CloudflareProgrammaticToolCalling.mjs.map +1 -1
  443. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs +424 -517
  444. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs.map +1 -1
  445. package/dist/esm/tools/cloudflare/CloudflareSandboxTools.mjs +91 -122
  446. package/dist/esm/tools/cloudflare/CloudflareSandboxTools.mjs.map +1 -1
  447. package/dist/esm/tools/cloudflare/index.mjs +5 -0
  448. package/dist/esm/tools/eagerEventExecution.mjs +75 -96
  449. package/dist/esm/tools/eagerEventExecution.mjs.map +1 -1
  450. package/dist/esm/tools/handlers.mjs +200 -260
  451. package/dist/esm/tools/handlers.mjs.map +1 -1
  452. package/dist/esm/tools/local/CompileCheckTool.mjs +150 -210
  453. package/dist/esm/tools/local/CompileCheckTool.mjs.map +1 -1
  454. package/dist/esm/tools/local/FileCheckpointer.mjs +77 -83
  455. package/dist/esm/tools/local/FileCheckpointer.mjs.map +1 -1
  456. package/dist/esm/tools/local/LocalCodingTools.mjs +760 -1017
  457. package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -1
  458. package/dist/esm/tools/local/LocalExecutionEngine.mjs +663 -936
  459. package/dist/esm/tools/local/LocalExecutionEngine.mjs.map +1 -1
  460. package/dist/esm/tools/local/LocalExecutionTools.mjs +49 -90
  461. package/dist/esm/tools/local/LocalExecutionTools.mjs.map +1 -1
  462. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs +283 -349
  463. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs.map +1 -1
  464. package/dist/esm/tools/local/attachments.mjs +108 -163
  465. package/dist/esm/tools/local/attachments.mjs.map +1 -1
  466. package/dist/esm/tools/local/bashAst.mjs +99 -111
  467. package/dist/esm/tools/local/bashAst.mjs.map +1 -1
  468. package/dist/esm/tools/local/editStrategies.mjs +126 -167
  469. package/dist/esm/tools/local/editStrategies.mjs.map +1 -1
  470. package/dist/esm/tools/local/index.mjs +13 -0
  471. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs +136 -216
  472. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs.map +1 -1
  473. package/dist/esm/tools/local/syntaxCheck.mjs +138 -155
  474. package/dist/esm/tools/local/syntaxCheck.mjs.map +1 -1
  475. package/dist/esm/tools/local/textEncoding.mjs +25 -21
  476. package/dist/esm/tools/local/textEncoding.mjs.map +1 -1
  477. package/dist/esm/tools/local/workspaceFS.mjs +38 -44
  478. package/dist/esm/tools/local/workspaceFS.mjs.map +1 -1
  479. package/dist/esm/tools/ptcTimeout.mjs +27 -42
  480. package/dist/esm/tools/ptcTimeout.mjs.map +1 -1
  481. package/dist/esm/tools/schema.mjs +24 -21
  482. package/dist/esm/tools/schema.mjs.map +1 -1
  483. package/dist/esm/tools/search/anthropic.mjs +24 -31
  484. package/dist/esm/tools/search/anthropic.mjs.map +1 -1
  485. package/dist/esm/tools/search/content.mjs +93 -116
  486. package/dist/esm/tools/search/content.mjs.map +1 -1
  487. package/dist/esm/tools/search/firecrawl.mjs +139 -169
  488. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  489. package/dist/esm/tools/search/format.mjs +128 -194
  490. package/dist/esm/tools/search/format.mjs.map +1 -1
  491. package/dist/esm/tools/search/highlights.mjs +165 -230
  492. package/dist/esm/tools/search/highlights.mjs.map +1 -1
  493. package/dist/esm/tools/search/index.mjs +3 -0
  494. package/dist/esm/tools/search/rerankers.mjs +149 -168
  495. package/dist/esm/tools/search/rerankers.mjs.map +1 -1
  496. package/dist/esm/tools/search/schema.mjs +39 -37
  497. package/dist/esm/tools/search/schema.mjs.map +1 -1
  498. package/dist/esm/tools/search/search.mjs +426 -528
  499. package/dist/esm/tools/search/search.mjs.map +1 -1
  500. package/dist/esm/tools/search/serper-scraper.mjs +104 -124
  501. package/dist/esm/tools/search/serper-scraper.mjs.map +1 -1
  502. package/dist/esm/tools/search/tavily-scraper.mjs +127 -178
  503. package/dist/esm/tools/search/tavily-scraper.mjs.map +1 -1
  504. package/dist/esm/tools/search/tavily-search.mjs +293 -357
  505. package/dist/esm/tools/search/tavily-search.mjs.map +1 -1
  506. package/dist/esm/tools/search/tool.mjs +259 -297
  507. package/dist/esm/tools/search/tool.mjs.map +1 -1
  508. package/dist/esm/tools/search/utils.mjs +74 -115
  509. package/dist/esm/tools/search/utils.mjs.map +1 -1
  510. package/dist/esm/tools/skillCatalog.mjs +54 -70
  511. package/dist/esm/tools/skillCatalog.mjs.map +1 -1
  512. package/dist/esm/tools/streamedToolCallSeals.mjs +19 -31
  513. package/dist/esm/tools/streamedToolCallSeals.mjs.map +1 -1
  514. package/dist/esm/tools/subagent/SubagentExecutor.mjs +612 -768
  515. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  516. package/dist/esm/tools/subagent/index.mjs +2 -0
  517. package/dist/esm/tools/toolOutputReferences.mjs +523 -624
  518. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
  519. package/dist/esm/utils/callbacks.mjs +11 -19
  520. package/dist/esm/utils/callbacks.mjs.map +1 -1
  521. package/dist/esm/utils/errors.mjs +70 -93
  522. package/dist/esm/utils/errors.mjs.map +1 -1
  523. package/dist/esm/utils/events.mjs +32 -40
  524. package/dist/esm/utils/events.mjs.map +1 -1
  525. package/dist/esm/utils/graph.mjs +8 -10
  526. package/dist/esm/utils/graph.mjs.map +1 -1
  527. package/dist/esm/utils/handlers.mjs +60 -80
  528. package/dist/esm/utils/handlers.mjs.map +1 -1
  529. package/dist/esm/utils/index.mjs +10 -0
  530. package/dist/esm/utils/llm.mjs +19 -25
  531. package/dist/esm/utils/llm.mjs.map +1 -1
  532. package/dist/esm/utils/misc.mjs +30 -44
  533. package/dist/esm/utils/misc.mjs.map +1 -1
  534. package/dist/esm/utils/run.mjs +50 -64
  535. package/dist/esm/utils/run.mjs.map +1 -1
  536. package/dist/esm/utils/schema.mjs +11 -17
  537. package/dist/esm/utils/schema.mjs.map +1 -1
  538. package/dist/esm/utils/title.mjs +71 -104
  539. package/dist/esm/utils/title.mjs.map +1 -1
  540. package/dist/esm/utils/tokens.mjs +186 -281
  541. package/dist/esm/utils/tokens.mjs.map +1 -1
  542. package/dist/esm/utils/truncation.mjs +95 -112
  543. package/dist/esm/utils/truncation.mjs.map +1 -1
  544. package/dist/types/tools/search/tool.d.ts +17 -0
  545. package/dist/types/tools/search/types.d.ts +4 -0
  546. package/package.json +4 -10
  547. package/src/tools/search/highlights.ts +9 -1
  548. package/src/tools/search/search.ts +41 -3
  549. package/src/tools/search/source-processing.test.ts +373 -0
  550. package/src/tools/search/tool.ts +22 -2
  551. package/src/tools/search/types.ts +4 -0
  552. package/dist/cjs/langchain/google-common.cjs.map +0 -1
  553. package/dist/cjs/langchain/index.cjs.map +0 -1
  554. package/dist/cjs/langchain/language_models/chat_models.cjs.map +0 -1
  555. package/dist/cjs/langchain/messages/tool.cjs.map +0 -1
  556. package/dist/cjs/langchain/messages.cjs.map +0 -1
  557. package/dist/cjs/langchain/openai.cjs.map +0 -1
  558. package/dist/cjs/langchain/prompts.cjs.map +0 -1
  559. package/dist/cjs/langchain/runnables.cjs.map +0 -1
  560. package/dist/cjs/langchain/tools.cjs.map +0 -1
  561. package/dist/cjs/langchain/utils/env.cjs.map +0 -1
  562. package/dist/cjs/main.cjs.map +0 -1
  563. package/dist/esm/langchain/google-common.mjs.map +0 -1
  564. package/dist/esm/langchain/index.mjs.map +0 -1
  565. package/dist/esm/langchain/language_models/chat_models.mjs.map +0 -1
  566. package/dist/esm/langchain/messages/tool.mjs.map +0 -1
  567. package/dist/esm/langchain/messages.mjs.map +0 -1
  568. package/dist/esm/langchain/openai.mjs.map +0 -1
  569. package/dist/esm/langchain/prompts.mjs.map +0 -1
  570. package/dist/esm/langchain/runnables.mjs.map +0 -1
  571. package/dist/esm/langchain/tools.mjs.map +0 -1
  572. package/dist/esm/langchain/utils/env.mjs.map +0 -1
  573. package/dist/esm/main.mjs.map +0 -1
@@ -1,1031 +1,758 @@
1
- import { tmpdir } from 'os';
2
- import { spawn } from 'child_process';
3
- import { createWriteStream } from 'fs';
4
- import { randomUUID, createHash } from 'crypto';
5
- import { resolve, isAbsolute, relative } from 'path';
6
- import { mkdir, writeFile, rm, realpath } from 'fs/promises';
7
- import { runBashAstChecks, bashAstFindingsToErrors } from './bashAst.mjs';
8
- import { nodeWorkspaceFS } from './workspaceFS.mjs';
9
-
10
- const DEFAULT_TIMEOUT_MS = 60000;
11
- const DEFAULT_MAX_OUTPUT_CHARS = 200000;
1
+ import { bashAstFindingsToErrors, runBashAstChecks } from "./bashAst.mjs";
2
+ import { nodeWorkspaceFS } from "./workspaceFS.mjs";
3
+ import { isAbsolute, relative, resolve } from "path";
4
+ import { tmpdir } from "os";
5
+ import { spawn } from "child_process";
6
+ import { createWriteStream } from "fs";
7
+ import { createHash, randomUUID } from "crypto";
8
+ import { mkdir, realpath, rm, writeFile } from "fs/promises";
9
+ //#region src/tools/local/LocalExecutionEngine.ts
10
+ const DEFAULT_TIMEOUT_MS = 6e4;
11
+ const DEFAULT_MAX_OUTPUT_CHARS = 2e5;
12
12
  /**
13
- * Hard cap on total stdout+stderr bytes a child process can stream
14
- * before we kill its process tree. Independent from `maxOutputChars`
15
- * (which only affects what the *model* sees) — this is the OOM
16
- * backstop. Configurable via `local.maxSpawnedBytes`.
17
- */
13
+ * Hard cap on total stdout+stderr bytes a child process can stream
14
+ * before we kill its process tree. Independent from `maxOutputChars`
15
+ * (which only affects what the *model* sees) — this is the OOM
16
+ * backstop. Configurable via `local.maxSpawnedBytes`.
17
+ */
18
18
  const DEFAULT_MAX_SPAWNED_BYTES = 50 * 1024 * 1024;
19
- const DEFAULT_LOCAL_SESSION_ID = 'local';
20
- const DEFAULT_SHELL = process.platform === 'win32' ? 'bash.exe' : 'bash';
21
- // `(?:--\s+)?` before each destructive-target alternation: GNU/BSD
22
- // utilities accept `--` as an end-of-options marker, so `rm -rf -- /`
23
- // is identical in effect to `rm -rf /` but pre-fix it slipped past
24
- // the guard because the regex required the path to follow option
25
- // flags directly. Codex P1 #20.
26
- // `DESTRUCTIVE_TARGET` is the canonical "protected location" pattern:
27
- // matches `/`, `~`, `$HOME`, `${HOME}`, `.`, each optionally followed
28
- // by a trailing-slash and/or wildcard glob suffix. The suffix matrix:
29
- // '' — `$HOME` (round 14)
30
- // '/' — `$HOME/` (round 14, Codex P1 [37])
31
- // '*' — `$HOME*` (round 15, Codex P1 [42])
32
- // '/*' — `$HOME/*` (round 15, Codex P1 [42])
33
- // '.*' — `$HOME.*` (round 17, Codex P1 [47])
34
- // '/.*' — `$HOME/.*` (round 17, Codex P1 [47]) — the
35
- // dot-glob form deletes all dotfiles under the protected
36
- // root, just as destructive as `/*` but the prior matrix
37
- // missed it.
38
- // Suffix expression: `(?:\/?\.?\*|\/)?` — one of:
39
- // `\/?\.?\*` → `*`, `.*`, `/*`, `/.*`
40
- // `\/` → `/`
41
- // (empty) → bare base
42
- const DESTRUCTIVE_TARGET = '(?:\\/|~|\\$\\{?HOME\\}?|\\.)(?:\\/?\\.?\\*|\\/)?';
19
+ const DEFAULT_LOCAL_SESSION_ID = "local";
20
+ const DEFAULT_SHELL = process.platform === "win32" ? "bash.exe" : "bash";
21
+ const DESTRUCTIVE_TARGET = "(?:\\/|~|\\$\\{?HOME\\}?|\\.)(?:\\/?\\.?\\*|\\/)?";
43
22
  const dangerousCommandPatterns = [
44
- new RegExp(`\\brm\\s+(?:-[^\\s]*[rf][^\\s]*\\s+|-[^\\s]*[r][^\\s]*\\s+-[^\\s]*[f][^\\s]*\\s+)(?:--\\s+)?${DESTRUCTIVE_TARGET}\\s*(?:$|[;&|])`),
45
- /\b(?:mkfs|mkswap|fdisk|parted|diskutil)\b/,
46
- /\bdd\s+[^;&|]*\bof=\/dev\//,
47
- new RegExp(`\\bchmod\\s+-R\\s+(?:777|a\\+w)\\s+(?:--\\s+)?${DESTRUCTIVE_TARGET}(?:$|\\s|[;&|])`),
48
- new RegExp(`\\bchown\\s+-R\\s+[^;&|]+\\s+(?:--\\s+)?${DESTRUCTIVE_TARGET}(?:$|\\s|[;&|])`),
49
- /:\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:/,
23
+ new RegExp(`\\brm\\s+(?:-[^\\s]*[rf][^\\s]*\\s+|-[^\\s]*[r][^\\s]*\\s+-[^\\s]*[f][^\\s]*\\s+)(?:--\\s+)?${DESTRUCTIVE_TARGET}\\s*(?:$|[;&|])`),
24
+ /\b(?:mkfs|mkswap|fdisk|parted|diskutil)\b/,
25
+ /\bdd\s+[^;&|]*\bof=\/dev\//,
26
+ new RegExp(`\\bchmod\\s+-R\\s+(?:777|a\\+w)\\s+(?:--\\s+)?${DESTRUCTIVE_TARGET}(?:$|\\s|[;&|])`),
27
+ new RegExp(`\\bchown\\s+-R\\s+[^;&|]+\\s+(?:--\\s+)?${DESTRUCTIVE_TARGET}(?:$|\\s|[;&|])`),
28
+ /:\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:/
50
29
  ];
51
30
  /**
52
- * Companion patterns that look for destructive targets *inside*
53
- * matching quote pairs. These are checked against the ORIGINAL
54
- * command (not the post-quote-strip `normalized` form), because
55
- * `stripQuotedContent` blanks the contents of quoted spans —
56
- * which would otherwise let `rm -rf "/"` and friends slip past
57
- * `dangerousCommandPatterns`.
58
- *
59
- * Kept as a separate list so we don't pay false-positive cost on
60
- * benign uses like `echo "rm -rf /"` (the print case): each pattern
61
- * here REQUIRES a quote *around the destructive path argument*, not
62
- * just a quote *somewhere* in the command. `echo "rm -rf /"` has
63
- * `/` outside of any quote-pair-around-the-path (the quotes wrap
64
- * the whole `rm -rf /` text), so it doesn't match here either.
65
- */
66
- // Quoted variant uses the same DESTRUCTIVE_TARGET (which accepts an
67
- // optional trailing slash) so `rm -rf "$HOME/"` and `rm -rf "~/"`
68
- // don't slip past. Codex P1 #37.
31
+ * Companion patterns that look for destructive targets *inside*
32
+ * matching quote pairs. These are checked against the ORIGINAL
33
+ * command (not the post-quote-strip `normalized` form), because
34
+ * `stripQuotedContent` blanks the contents of quoted spans —
35
+ * which would otherwise let `rm -rf "/"` and friends slip past
36
+ * `dangerousCommandPatterns`.
37
+ *
38
+ * Kept as a separate list so we don't pay false-positive cost on
39
+ * benign uses like `echo "rm -rf /"` (the print case): each pattern
40
+ * here REQUIRES a quote *around the destructive path argument*, not
41
+ * just a quote *somewhere* in the command. `echo "rm -rf /"` has
42
+ * `/` outside of any quote-pair-around-the-path (the quotes wrap
43
+ * the whole `rm -rf /` text), so it doesn't match here either.
44
+ */
69
45
  const quotedDestructivePatterns = [
70
- new RegExp(`\\brm\\s+(?:-[^\\s]*[rf][^\\s]*\\s+){1,3}(?:--\\s+)?["']${DESTRUCTIVE_TARGET}["']`),
71
- new RegExp(`\\bchmod\\s+-R\\s+(?:777|a\\+w)\\s+(?:--\\s+)?["']${DESTRUCTIVE_TARGET}["']`),
72
- new RegExp(`\\bchown\\s+-R\\s+[^;&|]+\\s+(?:--\\s+)?["']${DESTRUCTIVE_TARGET}["']`),
46
+ new RegExp(`\\brm\\s+(?:-[^\\s]*[rf][^\\s]*\\s+){1,3}(?:--\\s+)?["']${DESTRUCTIVE_TARGET}["']`),
47
+ new RegExp(`\\bchmod\\s+-R\\s+(?:777|a\\+w)\\s+(?:--\\s+)?["']${DESTRUCTIVE_TARGET}["']`),
48
+ new RegExp(`\\bchown\\s+-R\\s+[^;&|]+\\s+(?:--\\s+)?["']${DESTRUCTIVE_TARGET}["']`)
73
49
  ];
74
- /**
75
- * Catches destructive operations smuggled inside a nested shell or
76
- * `eval` call, e.g. `bash -lc "rm -rf $HOME"` — the outer command
77
- * looks benign (`bash -lc "..."`) and the destructive `rm` lives
78
- * inside the quoted payload that `stripQuotedContent` blanks out.
79
- * Comprehensive review (manual finding C) flagged this as a real
80
- * bypass of the otherwise-correct quote-strip-then-match approach.
81
- *
82
- * Run against the ORIGINAL command (quotes intact) so the inside of
83
- * the nested-shell payload is visible. Conservative: matches only
84
- * the same operation set as `dangerousCommandPatterns` (rm -rf,
85
- * chmod -R 777, chown -R) when they appear inside a `<shell> -[l]?c
86
- * "..."` or `eval "..."` payload.
87
- */
88
- const NESTED_SHELL_PREFIX = '(?:(?:ba|z|da|k)?sh|eval)\\s+(?:-l?c\\s+)?';
89
50
  const nestedShellDestructivePatterns = [
90
- new RegExp(NESTED_SHELL_PREFIX +
91
- '["\'][^"\']*\\brm\\s+-[^\\s"\']*[rf][^\\s"\']*\\s+(?:--\\s+)?(?:\\/|~|\\$\\{?HOME\\}?|\\.)'),
92
- new RegExp(NESTED_SHELL_PREFIX +
93
- '["\'][^"\']*\\bchmod\\s+-R\\s+(?:777|a\\+w)\\s+(?:--\\s+)?(?:\\/|~|\\$\\{?HOME\\}?|\\.)'),
94
- new RegExp(NESTED_SHELL_PREFIX +
95
- '["\'][^"\']*\\bchown\\s+-R\\s+[^;&|]+\\s+(?:--\\s+)?(?:\\/|~|\\$\\{?HOME\\}?|\\.)'),
51
+ /* @__PURE__ */ new RegExp("(?:(?:ba|z|da|k)?sh|eval)\\s+(?:-l?c\\s+)?[\"'][^\"']*\\brm\\s+-[^\\s\"']*[rf][^\\s\"']*\\s+(?:--\\s+)?(?:\\/|~|\\$\\{?HOME\\}?|\\.)"),
52
+ /* @__PURE__ */ new RegExp("(?:(?:ba|z|da|k)?sh|eval)\\s+(?:-l?c\\s+)?[\"'][^\"']*\\bchmod\\s+-R\\s+(?:777|a\\+w)\\s+(?:--\\s+)?(?:\\/|~|\\$\\{?HOME\\}?|\\.)"),
53
+ /* @__PURE__ */ new RegExp("(?:(?:ba|z|da|k)?sh|eval)\\s+(?:-l?c\\s+)?[\"'][^\"']*\\bchown\\s+-R\\s+[^;&|]+\\s+(?:--\\s+)?(?:\\/|~|\\$\\{?HOME\\}?|\\.)")
96
54
  ];
97
55
  const mutatingCommandPattern = /\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*/;
98
56
  /**
99
- * POSIX convention: `128 + signum` when a process is killed by a
100
- * signal. Maps the common signals; unknown ones default to 1 so the
101
- * caller still sees a non-zero (failed) exit. Only used when Node's
102
- * `close` event reports `exitCode === null` (true signal kill).
103
- */
57
+ * POSIX convention: `128 + signum` when a process is killed by a
58
+ * signal. Maps the common signals; unknown ones default to 1 so the
59
+ * caller still sees a non-zero (failed) exit. Only used when Node's
60
+ * `close` event reports `exitCode === null` (true signal kill).
61
+ */
104
62
  const SIGNAL_TO_EXIT_CODE = {
105
- SIGHUP: 129,
106
- SIGINT: 130,
107
- SIGQUIT: 131,
108
- SIGILL: 132,
109
- SIGTRAP: 133,
110
- SIGABRT: 134,
111
- SIGBUS: 135,
112
- SIGFPE: 136,
113
- SIGKILL: 137,
114
- SIGUSR1: 138,
115
- SIGSEGV: 139,
116
- SIGUSR2: 140,
117
- SIGPIPE: 141,
118
- SIGALRM: 142,
119
- SIGTERM: 143,
63
+ SIGHUP: 129,
64
+ SIGINT: 130,
65
+ SIGQUIT: 131,
66
+ SIGILL: 132,
67
+ SIGTRAP: 133,
68
+ SIGABRT: 134,
69
+ SIGBUS: 135,
70
+ SIGFPE: 136,
71
+ SIGKILL: 137,
72
+ SIGUSR1: 138,
73
+ SIGSEGV: 139,
74
+ SIGUSR2: 140,
75
+ SIGPIPE: 141,
76
+ SIGALRM: 142,
77
+ SIGTERM: 143
120
78
  };
121
79
  function exitCodeForSignal(signal) {
122
- if (signal == null)
123
- return 1;
124
- return SIGNAL_TO_EXIT_CODE[signal] ?? 1;
80
+ if (signal == null) return 1;
81
+ return SIGNAL_TO_EXIT_CODE[signal] ?? 1;
125
82
  }
126
83
  let sandboxConfigKey;
127
84
  let sandboxInitialized = false;
128
85
  let sandboxRuntimePromise;
129
86
  function isToolExecutionConfig(config) {
130
- return 'engine' in config || 'local' in config;
87
+ return "engine" in config || "local" in config;
131
88
  }
132
89
  function resolveLocalExecutionConfig(config) {
133
- if (config != null && isToolExecutionConfig(config)) {
134
- return config.local ?? {};
135
- }
136
- return config ?? {};
90
+ if (config != null && isToolExecutionConfig(config)) return config.local ?? {};
91
+ return config ?? {};
137
92
  }
138
93
  function getLocalCwd(config) {
139
- return resolve(config?.workspace?.root ?? config?.cwd ?? process.cwd());
94
+ return resolve(config?.workspace?.root ?? config?.cwd ?? process.cwd());
140
95
  }
141
96
  /**
142
- * Resolves the effective workspace boundary: a list of absolute roots
143
- * that file operations are allowed to touch. The first entry is always
144
- * the canonical root (`getLocalCwd`); subsequent entries come from
145
- * `workspace.additionalRoots` when provided.
146
- *
147
- * Returns plain absolute paths — callers symlink-resolve when they
148
- * need realpath equality (see `resolveWorkspacePathSafe`).
149
- */
97
+ * Resolves the effective workspace boundary: a list of absolute roots
98
+ * that file operations are allowed to touch. The first entry is always
99
+ * the canonical root (`getLocalCwd`); subsequent entries come from
100
+ * `workspace.additionalRoots` when provided.
101
+ *
102
+ * Returns plain absolute paths — callers symlink-resolve when they
103
+ * need realpath equality (see `resolveWorkspacePathSafe`).
104
+ */
150
105
  function getWorkspaceRoots(config) {
151
- const root = getLocalCwd(config);
152
- const extras = config?.workspace?.additionalRoots ?? [];
153
- if (extras.length === 0)
154
- return [root];
155
- const seen = new Set([root]);
156
- const out = [root];
157
- for (const extra of extras) {
158
- // Relative `additionalRoots` entries are anchored to the
159
- // workspace root (so monorepo configs like
160
- // `additionalRoots: ['../shared']` resolve to a sibling of
161
- // `root` rather than to `process.cwd()/../shared`, which would
162
- // mean something completely different on a server with a
163
- // different cwd).
164
- const abs = isAbsolute(extra) ? resolve(extra) : resolve(root, extra);
165
- if (!seen.has(abs)) {
166
- seen.add(abs);
167
- out.push(abs);
168
- }
169
- }
170
- return out;
106
+ const root = getLocalCwd(config);
107
+ const extras = config?.workspace?.additionalRoots ?? [];
108
+ if (extras.length === 0) return [root];
109
+ const seen = new Set([root]);
110
+ const out = [root];
111
+ for (const extra of extras) {
112
+ const abs = isAbsolute(extra) ? resolve(extra) : resolve(root, extra);
113
+ if (!seen.has(abs)) {
114
+ seen.add(abs);
115
+ out.push(abs);
116
+ }
117
+ }
118
+ return out;
171
119
  }
172
120
  /**
173
- * Pluggable spawn resolver. Honours `local.exec.spawn` first, falls
174
- * back to the legacy top-level `local.spawn`, then to Node's
175
- * `child_process.spawn`. Centralised so engine swapping is one knob.
176
- */
121
+ * Pluggable spawn resolver. Honours `local.exec.spawn` first, falls
122
+ * back to the legacy top-level `local.spawn`, then to Node's
123
+ * `child_process.spawn`. Centralised so engine swapping is one knob.
124
+ */
177
125
  function getSpawn(config) {
178
- return (config?.exec?.spawn ?? config?.spawn ?? spawn);
126
+ return config?.exec?.spawn ?? config?.spawn ?? spawn;
179
127
  }
180
128
  /**
181
- * Pluggable filesystem resolver. Honours `local.exec.fs`, falls back
182
- * to the Node-host implementation. A future remote engine supplies
183
- * its own implementation here and inherits every file-touching tool.
184
- */
129
+ * Pluggable filesystem resolver. Honours `local.exec.fs`, falls back
130
+ * to the Node-host implementation. A future remote engine supplies
131
+ * its own implementation here and inherits every file-touching tool.
132
+ */
185
133
  function getWorkspaceFS(config) {
186
- return config?.exec?.fs ?? nodeWorkspaceFS;
134
+ return config?.exec?.fs ?? nodeWorkspaceFS;
187
135
  }
188
136
  /**
189
- * Resolves the workspace boundary for *write* operations. Honours
190
- * `workspace.allowWriteOutside` (and the deprecated
191
- * `allowOutsideWorkspace`) by returning `null`, which the path-safety
192
- * helpers interpret as "skip the write clamp".
193
- */
137
+ * Resolves the workspace boundary for *write* operations. Honours
138
+ * `workspace.allowWriteOutside` (and the deprecated
139
+ * `allowOutsideWorkspace`) by returning `null`, which the path-safety
140
+ * helpers interpret as "skip the write clamp".
141
+ */
194
142
  function getWriteRoots(config = {}) {
195
- // Granular flag wins over the legacy one when explicitly set
196
- // (true OR false) otherwise a host tightening access during
197
- // migration (`allowOutsideWorkspace: true, workspace.
198
- // allowWriteOutside: false`) would still get the loose behavior
199
- // because the legacy flag short-circuited the OR. Codex P1 #36.
200
- const granular = config.workspace?.allowWriteOutside;
201
- if (granular === true)
202
- return null;
203
- if (granular === false)
204
- return getWorkspaceRoots(config);
205
- if (config.allowOutsideWorkspace === true)
206
- return null;
207
- return getWorkspaceRoots(config);
143
+ const granular = config.workspace?.allowWriteOutside;
144
+ if (granular === true) return null;
145
+ if (granular === false) return getWorkspaceRoots(config);
146
+ if (config.allowOutsideWorkspace === true) return null;
147
+ return getWorkspaceRoots(config);
208
148
  }
209
149
  /**
210
- * Resolves the workspace boundary for *read* operations. Honours
211
- * `workspace.allowReadOutside` (and the deprecated
212
- * `allowOutsideWorkspace`) by returning `null`.
213
- */
150
+ * Resolves the workspace boundary for *read* operations. Honours
151
+ * `workspace.allowReadOutside` (and the deprecated
152
+ * `allowOutsideWorkspace`) by returning `null`.
153
+ */
214
154
  function getReadRoots(config = {}) {
215
- // Same precedence as getWriteRoots: granular flag is authoritative
216
- // when set, legacy flag is the fallback. Codex P1 #36.
217
- const granular = config.workspace?.allowReadOutside;
218
- if (granular === true)
219
- return null;
220
- if (granular === false)
221
- return getWorkspaceRoots(config);
222
- if (config.allowOutsideWorkspace === true)
223
- return null;
224
- return getWorkspaceRoots(config);
155
+ const granular = config.workspace?.allowReadOutside;
156
+ if (granular === true) return null;
157
+ if (granular === false) return getWorkspaceRoots(config);
158
+ if (config.allowOutsideWorkspace === true) return null;
159
+ return getWorkspaceRoots(config);
225
160
  }
226
161
  function getLocalSessionId(config) {
227
- const cwd = getLocalCwd(config);
228
- const digest = createHash('sha1').update(cwd).digest('hex').slice(0, 12);
229
- return `${DEFAULT_LOCAL_SESSION_ID}:${digest}`;
162
+ const cwd = getLocalCwd(config);
163
+ return `${DEFAULT_LOCAL_SESSION_ID}:${createHash("sha1").update(cwd).digest("hex").slice(0, 12)}`;
230
164
  }
231
- const missingSandboxRuntimeMessage = [
232
- 'Local sandbox is enabled, but @anthropic-ai/sandbox-runtime is not installed.',
233
- 'Install it with `npm install @anthropic-ai/sandbox-runtime`, or disable local sandboxing with `local.sandbox.enabled: false`.',
234
- ].join(' ');
235
- const sandboxRuntimePackage = '@anthropic-ai/sandbox-runtime';
165
+ const missingSandboxRuntimeMessage = ["Local sandbox is enabled, but @anthropic-ai/sandbox-runtime is not installed.", "Install it with `npm install @anthropic-ai/sandbox-runtime`, or disable local sandboxing with `local.sandbox.enabled: false`."].join(" ");
166
+ const sandboxRuntimePackage = "@anthropic-ai/sandbox-runtime";
236
167
  /** Lazy-loads the ESM-only sandbox runtime only when sandboxing is enabled. */
237
168
  function loadSandboxRuntime() {
238
- sandboxRuntimePromise ??= import(sandboxRuntimePackage);
239
- return sandboxRuntimePromise;
169
+ sandboxRuntimePromise ??= import(sandboxRuntimePackage);
170
+ return sandboxRuntimePromise;
240
171
  }
241
172
  function shouldUseLocalSandbox(config) {
242
- return config.sandbox?.enabled === true;
173
+ return config.sandbox?.enabled === true;
243
174
  }
244
175
  let sandboxOffWarned = false;
245
176
  function maybeWarnSandboxOff(config) {
246
- if (sandboxOffWarned ||
247
- shouldUseLocalSandbox(config) ||
248
- config.exec?.sandboxed === true) {
249
- return;
250
- }
251
- sandboxOffWarned = true;
252
- // eslint-disable-next-line no-console
253
- console.warn('[@librechat/agents] Local execution engine is running without ' +
254
- '@anthropic-ai/sandbox-runtime wrapping. The agent has full access to ' +
255
- 'the host filesystem and network. Set toolExecution.local.sandbox.enabled ' +
256
- '= true to opt into process sandboxing.');
177
+ if (sandboxOffWarned || shouldUseLocalSandbox(config) || config.exec?.sandboxed === true) return;
178
+ sandboxOffWarned = true;
179
+ console.warn("[@librechat/agents] Local execution engine is running without @anthropic-ai/sandbox-runtime wrapping. The agent has full access to the host filesystem and network. Set toolExecution.local.sandbox.enabled = true to opt into process sandboxing.");
257
180
  }
258
181
  /**
259
- * Test-only reset hook for the sandbox-off warning latch.
260
- *
261
- * @internal Not part of the public SDK surface.
262
- */
182
+ * Test-only reset hook for the sandbox-off warning latch.
183
+ *
184
+ * @internal Not part of the public SDK surface.
185
+ */
263
186
  function _resetLocalEngineWarningsForTests() {
264
- sandboxOffWarned = false;
187
+ sandboxOffWarned = false;
265
188
  }
266
189
  function truncateLocalOutput(value, maxChars = DEFAULT_MAX_OUTPUT_CHARS) {
267
- if (value.length <= maxChars) {
268
- return value;
269
- }
270
- const head = Math.floor(maxChars * 0.6);
271
- const tail = maxChars - head;
272
- const omitted = value.length - maxChars;
273
- return `${value.slice(0, head)}\n\n[... ${omitted} characters truncated ...]\n\n${value.slice(value.length - tail)}`;
190
+ if (value.length <= maxChars) return value;
191
+ const head = Math.floor(maxChars * .6);
192
+ const tail = maxChars - head;
193
+ const omitted = value.length - maxChars;
194
+ return `${value.slice(0, head)}\n\n[... ${omitted} characters truncated ...]\n\n${value.slice(value.length - tail)}`;
274
195
  }
275
196
  function stripQuotedContent(command) {
276
- let output = '';
277
- let quote;
278
- let escaped = false;
279
- for (let i = 0; i < command.length; i++) {
280
- const char = command[i];
281
- if (escaped) {
282
- escaped = false;
283
- output += ' ';
284
- continue;
285
- }
286
- if (char === '\\') {
287
- escaped = true;
288
- output += ' ';
289
- continue;
290
- }
291
- if (quote != null) {
292
- if (char === quote) {
293
- quote = undefined;
294
- }
295
- output += ' ';
296
- continue;
297
- }
298
- if (char === '"' || char === '\'' || char === '`') {
299
- quote = char;
300
- output += ' ';
301
- continue;
302
- }
303
- if (char === '#') {
304
- while (i < command.length && command[i] !== '\n') {
305
- output += ' ';
306
- i++;
307
- }
308
- output += '\n';
309
- continue;
310
- }
311
- output += char;
312
- }
313
- return output;
197
+ let output = "";
198
+ let quote;
199
+ let escaped = false;
200
+ for (let i = 0; i < command.length; i++) {
201
+ const char = command[i];
202
+ if (escaped) {
203
+ escaped = false;
204
+ output += " ";
205
+ continue;
206
+ }
207
+ if (char === "\\") {
208
+ escaped = true;
209
+ output += " ";
210
+ continue;
211
+ }
212
+ if (quote != null) {
213
+ if (char === quote) quote = void 0;
214
+ output += " ";
215
+ continue;
216
+ }
217
+ if (char === "\"" || char === "'" || char === "`") {
218
+ quote = char;
219
+ output += " ";
220
+ continue;
221
+ }
222
+ if (char === "#") {
223
+ while (i < command.length && command[i] !== "\n") {
224
+ output += " ";
225
+ i++;
226
+ }
227
+ output += "\n";
228
+ continue;
229
+ }
230
+ output += char;
231
+ }
232
+ return output;
314
233
  }
315
234
  async function validateBashCommand(command, config = {}) {
316
- const errors = [];
317
- const warnings = [];
318
- const normalized = stripQuotedContent(command);
319
- if (command.trim() === '') {
320
- errors.push('Command is empty.');
321
- }
322
- if (command.includes('\0')) {
323
- errors.push('Command contains a NUL byte.');
324
- }
325
- if (config.allowDangerousCommands !== true) {
326
- let blocked = false;
327
- // Strip-then-match for the bare-form patterns (avoids false
328
- // positives where the destructive text is buried inside a
329
- // string the user is just printing).
330
- for (const pattern of dangerousCommandPatterns) {
331
- if (pattern.test(normalized)) {
332
- errors.push('Command matches a destructive command pattern.');
333
- blocked = true;
334
- break;
335
- }
336
- }
337
- // Original-form pass for patterns that REQUIRE matching quote
338
- // pairs around a destructive path. Without this, `rm -rf "/"`
339
- // and `chmod -R 777 "/"` slip past the strip-then-match pass
340
- // because their destructive target is inside quotes.
341
- if (!blocked) {
342
- for (const pattern of quotedDestructivePatterns) {
343
- if (pattern.test(command)) {
344
- errors.push('Command matches a destructive command pattern (quoted target).');
345
- blocked = true;
346
- break;
347
- }
348
- }
349
- }
350
- if (!blocked) {
351
- for (const pattern of nestedShellDestructivePatterns) {
352
- if (pattern.test(command)) {
353
- errors.push('Command matches a destructive command pattern (nested shell payload).');
354
- break;
355
- }
356
- }
357
- }
358
- }
359
- const bashAstMode = config.bashAst ?? 'off';
360
- if (bashAstMode !== 'off' && config.allowDangerousCommands !== true) {
361
- const findings = runBashAstChecks(normalized, bashAstMode);
362
- const split = bashAstFindingsToErrors(findings);
363
- errors.push(...split.errors);
364
- warnings.push(...split.warnings);
365
- }
366
- if (config.readOnly === true && mutatingCommandPattern.test(normalized)) {
367
- errors.push('Command appears to mutate files or repository state in read-only local mode.');
368
- }
369
- // Use the same shell the actual execution path will use. Hard-coding
370
- // DEFAULT_SHELL here would reject perfectly valid commands when the
371
- // host configures `local.shell` to a non-bash binary (or when the
372
- // runtime doesn't have bash installed at all but does have e.g. zsh).
373
- const syntaxShell = config.shell ?? DEFAULT_SHELL;
374
- const syntax = await spawnLocalProcess(syntaxShell, ['-n', '-c', command], {
375
- ...config,
376
- timeoutMs: Math.min(config.timeoutMs ?? DEFAULT_TIMEOUT_MS, 5000),
377
- sandbox: { enabled: false },
378
- }, { internal: true }).catch((error) => ({
379
- stdout: '',
380
- stderr: error.message,
381
- exitCode: 1,
382
- timedOut: false,
383
- }));
384
- if (syntax.exitCode !== 0) {
385
- errors.push(syntax.stderr.trim() === ''
386
- ? 'Command failed shell syntax validation.'
387
- : `Command failed shell syntax validation: ${syntax.stderr.trim()}`);
388
- }
389
- if (/\bsudo\b/.test(normalized)) {
390
- warnings.push('Command requests elevated privileges with sudo.');
391
- }
392
- return {
393
- valid: errors.length === 0,
394
- errors,
395
- warnings,
396
- };
235
+ const errors = [];
236
+ const warnings = [];
237
+ const normalized = stripQuotedContent(command);
238
+ if (command.trim() === "") errors.push("Command is empty.");
239
+ if (command.includes("\0")) errors.push("Command contains a NUL byte.");
240
+ if (config.allowDangerousCommands !== true) {
241
+ let blocked = false;
242
+ for (const pattern of dangerousCommandPatterns) if (pattern.test(normalized)) {
243
+ errors.push("Command matches a destructive command pattern.");
244
+ blocked = true;
245
+ break;
246
+ }
247
+ if (!blocked) {
248
+ for (const pattern of quotedDestructivePatterns) if (pattern.test(command)) {
249
+ errors.push("Command matches a destructive command pattern (quoted target).");
250
+ blocked = true;
251
+ break;
252
+ }
253
+ }
254
+ if (!blocked) {
255
+ for (const pattern of nestedShellDestructivePatterns) if (pattern.test(command)) {
256
+ errors.push("Command matches a destructive command pattern (nested shell payload).");
257
+ break;
258
+ }
259
+ }
260
+ }
261
+ const bashAstMode = config.bashAst ?? "off";
262
+ if (bashAstMode !== "off" && config.allowDangerousCommands !== true) {
263
+ const split = bashAstFindingsToErrors(runBashAstChecks(normalized, bashAstMode));
264
+ errors.push(...split.errors);
265
+ warnings.push(...split.warnings);
266
+ }
267
+ if (config.readOnly === true && mutatingCommandPattern.test(normalized)) errors.push("Command appears to mutate files or repository state in read-only local mode.");
268
+ const syntax = await spawnLocalProcess(config.shell ?? DEFAULT_SHELL, [
269
+ "-n",
270
+ "-c",
271
+ command
272
+ ], {
273
+ ...config,
274
+ timeoutMs: Math.min(config.timeoutMs ?? DEFAULT_TIMEOUT_MS, 5e3),
275
+ sandbox: { enabled: false }
276
+ }, { internal: true }).catch((error) => ({
277
+ stdout: "",
278
+ stderr: error.message,
279
+ exitCode: 1,
280
+ timedOut: false
281
+ }));
282
+ if (syntax.exitCode !== 0) errors.push(syntax.stderr.trim() === "" ? "Command failed shell syntax validation." : `Command failed shell syntax validation: ${syntax.stderr.trim()}`);
283
+ if (/\bsudo\b/.test(normalized)) warnings.push("Command requests elevated privileges with sudo.");
284
+ return {
285
+ valid: errors.length === 0,
286
+ errors,
287
+ warnings
288
+ };
397
289
  }
398
290
  async function ensureSandbox(config, cwd) {
399
- if (!shouldUseLocalSandbox(config)) {
400
- return undefined;
401
- }
402
- const runtime = await loadSandboxRuntime().catch((error) => {
403
- throw new Error(`${missingSandboxRuntimeMessage} Cause: ${error.message}`);
404
- });
405
- const runtimeConfig = buildSandboxRuntimeConfig(config, cwd, runtime.getDefaultWritePaths);
406
- const nextKey = JSON.stringify(runtimeConfig);
407
- if (sandboxInitialized && sandboxConfigKey === nextKey) {
408
- return runtime.SandboxManager;
409
- }
410
- const dependencyCheck = runtime.SandboxManager.checkDependencies();
411
- if (dependencyCheck.errors.length > 0) {
412
- if (config.sandbox?.failIfUnavailable === true) {
413
- throw new Error(`Local sandbox requested but unavailable: ${dependencyCheck.errors.join('; ')}`);
414
- }
415
- return undefined;
416
- }
417
- if (sandboxInitialized) {
418
- await runtime.SandboxManager.reset();
419
- }
420
- await runtime.SandboxManager.initialize(runtimeConfig);
421
- sandboxInitialized = true;
422
- sandboxConfigKey = nextKey;
423
- return runtime.SandboxManager;
291
+ if (!shouldUseLocalSandbox(config)) return;
292
+ const runtime = await loadSandboxRuntime().catch((error) => {
293
+ throw new Error(`${missingSandboxRuntimeMessage} Cause: ${error.message}`);
294
+ });
295
+ const runtimeConfig = buildSandboxRuntimeConfig(config, cwd, runtime.getDefaultWritePaths);
296
+ const nextKey = JSON.stringify(runtimeConfig);
297
+ if (sandboxInitialized && sandboxConfigKey === nextKey) return runtime.SandboxManager;
298
+ const dependencyCheck = runtime.SandboxManager.checkDependencies();
299
+ if (dependencyCheck.errors.length > 0) {
300
+ if (config.sandbox?.failIfUnavailable === true) throw new Error(`Local sandbox requested but unavailable: ${dependencyCheck.errors.join("; ")}`);
301
+ return;
302
+ }
303
+ if (sandboxInitialized) await runtime.SandboxManager.reset();
304
+ await runtime.SandboxManager.initialize(runtimeConfig);
305
+ sandboxInitialized = true;
306
+ sandboxConfigKey = nextKey;
307
+ return runtime.SandboxManager;
424
308
  }
425
309
  /**
426
- * Loopback addresses the in-process programmatic-tool bridge listens
427
- * on (`LocalProgrammaticToolCalling.ts` binds 127.0.0.1). Sandboxed
428
- * code launched by `run_tools_with_code` / `run_tools_with_bash` HTTPs
429
- * back to that address — without the entries below, the bridge is
430
- * silently blocked under sandbox.
431
- */
432
- const BRIDGE_LOOPBACK_HOSTS = ['127.0.0.1', 'localhost', '::1'];
310
+ * Loopback addresses the in-process programmatic-tool bridge listens
311
+ * on (`LocalProgrammaticToolCalling.ts` binds 127.0.0.1). Sandboxed
312
+ * code launched by `run_tools_with_code` / `run_tools_with_bash` HTTPs
313
+ * back to that address — without the entries below, the bridge is
314
+ * silently blocked under sandbox.
315
+ */
316
+ const BRIDGE_LOOPBACK_HOSTS = [
317
+ "127.0.0.1",
318
+ "localhost",
319
+ "::1"
320
+ ];
433
321
  function buildSandboxRuntimeConfig(config, cwd, getDefaultWritePaths) {
434
- const sandbox = config.sandbox;
435
- // Seed allowedDomains with loopback so the programmatic-tool bridge
436
- // works under sandbox. If the host explicitly denied a loopback
437
- // entry via `deniedDomains`, respect that and skip seeding it.
438
- const userAllowed = sandbox?.network?.allowedDomains ?? [];
439
- const denied = new Set(sandbox?.network?.deniedDomains ?? []);
440
- const seededLoopback = BRIDGE_LOOPBACK_HOSTS.filter((host) => !denied.has(host) && !userAllowed.includes(host));
441
- const allowedDomains = [...seededLoopback, ...userAllowed];
442
- // Mirror the file-tools workspace boundary: anything in
443
- // `additionalRoots` counts as in-workspace, so sandboxed shell/code
444
- // can write there too. Without this, file_tools can resolve a
445
- // sibling-root path but `bash`/`execute_code` is denied write
446
- // access confusing divergence flagged in Codex P2 #15.
447
- const workspaceWriteRoots = config.workspace?.additionalRoots != null
448
- ? getWorkspaceRoots(config)
449
- : [cwd];
450
- return {
451
- network: {
452
- allowedDomains,
453
- deniedDomains: sandbox?.network?.deniedDomains ?? [],
454
- ...(sandbox?.network?.allowUnixSockets != null && {
455
- allowUnixSockets: sandbox.network.allowUnixSockets,
456
- }),
457
- ...(sandbox?.network?.allowAllUnixSockets != null && {
458
- allowAllUnixSockets: sandbox.network.allowAllUnixSockets,
459
- }),
460
- ...(sandbox?.network?.allowLocalBinding != null && {
461
- allowLocalBinding: sandbox.network.allowLocalBinding,
462
- }),
463
- ...(sandbox?.network?.allowMachLookup != null && {
464
- allowMachLookup: sandbox.network.allowMachLookup,
465
- }),
466
- },
467
- filesystem: {
468
- denyRead: sandbox?.filesystem?.denyRead ?? [],
469
- allowRead: sandbox?.filesystem?.allowRead,
470
- allowWrite: sandbox?.filesystem?.allowWrite ?? [
471
- ...workspaceWriteRoots,
472
- ...getDefaultWritePaths(),
473
- ],
474
- denyWrite: sandbox?.filesystem?.denyWrite ?? [
475
- '.env',
476
- '.env.*',
477
- '.git/config',
478
- '.git/hooks/**',
479
- ],
480
- allowGitConfig: sandbox?.filesystem?.allowGitConfig,
481
- },
482
- };
483
- }
484
- const LOCAL_SPAWN_TIMEOUT_MS = Symbol('librechat.localSpawn.timeoutMs');
322
+ const sandbox = config.sandbox;
323
+ const userAllowed = sandbox?.network?.allowedDomains ?? [];
324
+ const denied = new Set(sandbox?.network?.deniedDomains ?? []);
325
+ const allowedDomains = [...BRIDGE_LOOPBACK_HOSTS.filter((host) => !denied.has(host) && !userAllowed.includes(host)), ...userAllowed];
326
+ const workspaceWriteRoots = config.workspace?.additionalRoots != null ? getWorkspaceRoots(config) : [cwd];
327
+ return {
328
+ network: {
329
+ allowedDomains,
330
+ deniedDomains: sandbox?.network?.deniedDomains ?? [],
331
+ ...sandbox?.network?.allowUnixSockets != null && { allowUnixSockets: sandbox.network.allowUnixSockets },
332
+ ...sandbox?.network?.allowAllUnixSockets != null && { allowAllUnixSockets: sandbox.network.allowAllUnixSockets },
333
+ ...sandbox?.network?.allowLocalBinding != null && { allowLocalBinding: sandbox.network.allowLocalBinding },
334
+ ...sandbox?.network?.allowMachLookup != null && { allowMachLookup: sandbox.network.allowMachLookup }
335
+ },
336
+ filesystem: {
337
+ denyRead: sandbox?.filesystem?.denyRead ?? [],
338
+ allowRead: sandbox?.filesystem?.allowRead,
339
+ allowWrite: sandbox?.filesystem?.allowWrite ?? [...workspaceWriteRoots, ...getDefaultWritePaths()],
340
+ denyWrite: sandbox?.filesystem?.denyWrite ?? [
341
+ ".env",
342
+ ".env.*",
343
+ ".git/config",
344
+ ".git/hooks/**"
345
+ ],
346
+ allowGitConfig: sandbox?.filesystem?.allowGitConfig
347
+ }
348
+ };
349
+ }
350
+ const LOCAL_SPAWN_TIMEOUT_MS = Symbol("librechat.localSpawn.timeoutMs");
485
351
  async function spawnLocalProcess(command, args, config = {}, options) {
486
- const cwd = getLocalCwd(config);
487
- const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
488
- const maxOutputChars = config.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
489
- // Streaming caps. Local tools execute arbitrary shell/code, so a noisy
490
- // command (`yes`, `cat /dev/urandom | base64`, a verbose build) could
491
- // accumulate gigabytes in memory before hitting the post-close cap.
492
- // We bound in-memory per-stream and spill the rest to disk; we also
493
- // hard-kill the child once total streamed bytes pass `maxSpawnedBytes`
494
- // so a process producing unbounded output gets stopped instead of
495
- // letting the host OOM.
496
- const inMemoryCapBytes = maxOutputChars * 2;
497
- const hardKillBytes = config.maxSpawnedBytes ?? DEFAULT_MAX_SPAWNED_BYTES;
498
- const sandboxManager = await ensureSandbox(config, cwd);
499
- // Internal probes (validateBashCommand syntax preflight,
500
- // isRipgrepAvailable, syntax-check probe cache priming) pass
501
- // `internal: true` so they don't emit a misleading "sandbox is
502
- // off" warning AND don't flip `sandboxOffWarned = true`. Without
503
- // this Codex P2 path: a run with `sandbox.enabled: true` would
504
- // see a false warning from the syntax preflight, and the latch
505
- // flip would suppress the warning in a *later* truly-unsandboxed
506
- // run — exactly the scenario operators need to see.
507
- if (sandboxManager == null && options?.internal !== true) {
508
- maybeWarnSandboxOff(config);
509
- }
510
- let spawnCommand = command;
511
- let spawnArgs = args;
512
- if (sandboxManager != null) {
513
- const rendered = [command, ...args.map(shellQuote)].join(' ');
514
- const sandboxed = await sandboxManager.wrapWithSandbox(rendered);
515
- spawnCommand = config.shell ?? DEFAULT_SHELL;
516
- spawnArgs = ['-lc', sandboxed];
517
- }
518
- const launcher = getSpawn(config);
519
- return new Promise((resolveResult, reject) => {
520
- const spawnOptions = {
521
- cwd,
522
- detached: process.platform !== 'win32',
523
- env: { ...process.env, ...(config.env ?? {}) },
524
- stdio: ['ignore', 'pipe', 'pipe'],
525
- };
526
- Object.defineProperty(spawnOptions, LOCAL_SPAWN_TIMEOUT_MS, {
527
- value: timeoutMs,
528
- });
529
- const child = launcher(spawnCommand, spawnArgs, spawnOptions);
530
- let stdout = '';
531
- let stderr = '';
532
- let totalSpawnedBytes = 0;
533
- let overflowKilled = false;
534
- let spillStream;
535
- let spillPath;
536
- let settled = false;
537
- let timedOut = false;
538
- let timeout;
539
- const ensureSpill = () => {
540
- if (spillStream != null)
541
- return;
542
- // Lazy-open the temp file the first time a stream's in-memory
543
- // buffer overflows. Seed it with everything we've buffered so
544
- // the file holds the FULL output (not just the post-cap tail).
545
- // Uses the static `createWriteStream` import — `require('fs')`
546
- // would throw `ReferenceError: require is not defined` in ESM
547
- // consumers (this package ships both `dist/cjs` and `dist/esm`).
548
- spillPath = resolve(tmpdir(), `lc-local-output-${randomUUID()}.txt`);
549
- spillStream = createWriteStream(spillPath);
550
- spillStream.write('===== stdout =====\n');
551
- spillStream.write(stdout);
552
- spillStream.write('\n===== stderr =====\n');
553
- spillStream.write(stderr);
554
- spillStream.write('\n===== overflow stream begins here =====\n');
555
- };
556
- const handleChunk = (buf, kind) => {
557
- totalSpawnedBytes += buf.length;
558
- // hardKillBytes <= 0 means "no cap" per the public config contract
559
- // (see LocalExecutionConfig.maxSpawnedBytes). Skip the kill check
560
- // entirely in that case so a single byte doesn't terminate the run.
561
- if (hardKillBytes > 0 &&
562
- totalSpawnedBytes > hardKillBytes &&
563
- !overflowKilled) {
564
- overflowKilled = true;
565
- killProcessTree(child);
566
- return;
567
- }
568
- const current = kind === 'stdout' ? stdout : stderr;
569
- if (current.length < inMemoryCapBytes) {
570
- const text = buf.toString('utf8');
571
- if (kind === 'stdout')
572
- stdout += text;
573
- else
574
- stderr += text;
575
- if (current.length + text.length >= inMemoryCapBytes) {
576
- ensureSpill();
577
- }
578
- }
579
- else {
580
- ensureSpill();
581
- spillStream.write(`[${kind}] `);
582
- spillStream.write(buf);
583
- }
584
- };
585
- const finish = (result) => {
586
- if (settled) {
587
- return;
588
- }
589
- settled = true;
590
- if (timeout != null) {
591
- clearTimeout(timeout);
592
- }
593
- const finalize = () => {
594
- const truncated = {
595
- stdout: truncateLocalOutput(result.stdout, maxOutputChars),
596
- stderr: truncateLocalOutput(result.stderr, maxOutputChars),
597
- };
598
- resolveResult({
599
- ...result,
600
- ...truncated,
601
- ...(spillPath != null ? { fullOutputPath: spillPath } : {}),
602
- });
603
- };
604
- if (spillStream == null) {
605
- finalize();
606
- return;
607
- }
608
- // Wait for the temp file to flush before reporting the path.
609
- // Otherwise the model sees `full_output_path: …` for a file
610
- // that's still being written.
611
- spillStream.end(() => finalize());
612
- };
613
- const fail = (error) => {
614
- if (settled) {
615
- return;
616
- }
617
- settled = true;
618
- if (timeout != null) {
619
- clearTimeout(timeout);
620
- }
621
- if (spillStream != null) {
622
- spillStream.end();
623
- }
624
- reject(error);
625
- };
626
- if (timeoutMs > 0) {
627
- timeout = setTimeout(() => {
628
- timedOut = true;
629
- killProcessTree(child);
630
- }, timeoutMs);
631
- }
632
- child.stdout.on('data', (chunk) => {
633
- handleChunk(chunk, 'stdout');
634
- });
635
- child.stderr.on('data', (chunk) => {
636
- handleChunk(chunk, 'stderr');
637
- });
638
- child.on('error', fail);
639
- child.on('close', (exitCode, signal) => {
640
- // Synthesize a non-zero exit code whenever the process exited
641
- // by signal — Node reports `exitCode: null` in that case and
642
- // the formatter only prints non-null exit codes, so signal
643
- // kills (overflow guard, `kill -9 $$` from inside the script,
644
- // native crashes, OS OOM killer, …) would otherwise look like
645
- // successful runs (Codex P1 + Codex P2). Overflow path keeps
646
- // its 137 (SIGKILL) for compatibility; other signals map per
647
- // POSIX `128 + signum`.
648
- let finalExit = exitCode;
649
- if (finalExit == null) {
650
- if (overflowKilled) {
651
- finalExit = 137;
652
- }
653
- else if (signal != null) {
654
- finalExit = exitCodeForSignal(signal);
655
- }
656
- }
657
- finish({
658
- stdout,
659
- stderr,
660
- exitCode: finalExit,
661
- timedOut,
662
- ...(overflowKilled ? { overflowKilled: true } : {}),
663
- ...(signal != null ? { signal } : {}),
664
- });
665
- });
666
- });
352
+ const cwd = getLocalCwd(config);
353
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
354
+ const maxOutputChars = config.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
355
+ const inMemoryCapBytes = maxOutputChars * 2;
356
+ const hardKillBytes = config.maxSpawnedBytes ?? DEFAULT_MAX_SPAWNED_BYTES;
357
+ const sandboxManager = await ensureSandbox(config, cwd);
358
+ if (sandboxManager == null && options?.internal !== true) maybeWarnSandboxOff(config);
359
+ let spawnCommand = command;
360
+ let spawnArgs = args;
361
+ if (sandboxManager != null) {
362
+ const rendered = [command, ...args.map(shellQuote)].join(" ");
363
+ const sandboxed = await sandboxManager.wrapWithSandbox(rendered);
364
+ spawnCommand = config.shell ?? DEFAULT_SHELL;
365
+ spawnArgs = ["-lc", sandboxed];
366
+ }
367
+ const launcher = getSpawn(config);
368
+ return new Promise((resolveResult, reject) => {
369
+ const spawnOptions = {
370
+ cwd,
371
+ detached: process.platform !== "win32",
372
+ env: {
373
+ ...process.env,
374
+ ...config.env ?? {}
375
+ },
376
+ stdio: [
377
+ "ignore",
378
+ "pipe",
379
+ "pipe"
380
+ ]
381
+ };
382
+ Object.defineProperty(spawnOptions, LOCAL_SPAWN_TIMEOUT_MS, { value: timeoutMs });
383
+ const child = launcher(spawnCommand, spawnArgs, spawnOptions);
384
+ let stdout = "";
385
+ let stderr = "";
386
+ let totalSpawnedBytes = 0;
387
+ let overflowKilled = false;
388
+ let spillStream;
389
+ let spillPath;
390
+ let settled = false;
391
+ let timedOut = false;
392
+ let timeout;
393
+ const ensureSpill = () => {
394
+ if (spillStream != null) return;
395
+ spillPath = resolve(tmpdir(), `lc-local-output-${randomUUID()}.txt`);
396
+ spillStream = createWriteStream(spillPath);
397
+ spillStream.write("===== stdout =====\n");
398
+ spillStream.write(stdout);
399
+ spillStream.write("\n===== stderr =====\n");
400
+ spillStream.write(stderr);
401
+ spillStream.write("\n===== overflow stream begins here =====\n");
402
+ };
403
+ const handleChunk = (buf, kind) => {
404
+ totalSpawnedBytes += buf.length;
405
+ if (hardKillBytes > 0 && totalSpawnedBytes > hardKillBytes && !overflowKilled) {
406
+ overflowKilled = true;
407
+ killProcessTree(child);
408
+ return;
409
+ }
410
+ const current = kind === "stdout" ? stdout : stderr;
411
+ if (current.length < inMemoryCapBytes) {
412
+ const text = buf.toString("utf8");
413
+ if (kind === "stdout") stdout += text;
414
+ else stderr += text;
415
+ if (current.length + text.length >= inMemoryCapBytes) ensureSpill();
416
+ } else {
417
+ ensureSpill();
418
+ spillStream.write(`[${kind}] `);
419
+ spillStream.write(buf);
420
+ }
421
+ };
422
+ const finish = (result) => {
423
+ if (settled) return;
424
+ settled = true;
425
+ if (timeout != null) clearTimeout(timeout);
426
+ const finalize = () => {
427
+ const truncated = {
428
+ stdout: truncateLocalOutput(result.stdout, maxOutputChars),
429
+ stderr: truncateLocalOutput(result.stderr, maxOutputChars)
430
+ };
431
+ resolveResult({
432
+ ...result,
433
+ ...truncated,
434
+ ...spillPath != null ? { fullOutputPath: spillPath } : {}
435
+ });
436
+ };
437
+ if (spillStream == null) {
438
+ finalize();
439
+ return;
440
+ }
441
+ spillStream.end(() => finalize());
442
+ };
443
+ const fail = (error) => {
444
+ if (settled) return;
445
+ settled = true;
446
+ if (timeout != null) clearTimeout(timeout);
447
+ if (spillStream != null) spillStream.end();
448
+ reject(error);
449
+ };
450
+ if (timeoutMs > 0) timeout = setTimeout(() => {
451
+ timedOut = true;
452
+ killProcessTree(child);
453
+ }, timeoutMs);
454
+ child.stdout.on("data", (chunk) => {
455
+ handleChunk(chunk, "stdout");
456
+ });
457
+ child.stderr.on("data", (chunk) => {
458
+ handleChunk(chunk, "stderr");
459
+ });
460
+ child.on("error", fail);
461
+ child.on("close", (exitCode, signal) => {
462
+ let finalExit = exitCode;
463
+ if (finalExit == null) {
464
+ if (overflowKilled) finalExit = 137;
465
+ else if (signal != null) finalExit = exitCodeForSignal(signal);
466
+ }
467
+ finish({
468
+ stdout,
469
+ stderr,
470
+ exitCode: finalExit,
471
+ timedOut,
472
+ ...overflowKilled ? { overflowKilled: true } : {},
473
+ ...signal != null ? { signal } : {}
474
+ });
475
+ });
476
+ });
667
477
  }
668
478
  async function executeLocalBash(command, config = {}) {
669
- const validation = await validateBashCommand(command, config);
670
- if (!validation.valid) {
671
- throw new Error(validation.errors.join('\n'));
672
- }
673
- const shell = config.shell ?? DEFAULT_SHELL;
674
- return spawnLocalProcess(shell, ['-lc', command], config);
479
+ const validation = await validateBashCommand(command, config);
480
+ if (!validation.valid) throw new Error(validation.errors.join("\n"));
481
+ return spawnLocalProcess(config.shell ?? DEFAULT_SHELL, ["-lc", command], config);
675
482
  }
676
483
  /**
677
- * Variant of `executeLocalBash` that exposes `args` as positional
678
- * shell parameters (`$1`, `$2`, …). Mirrors what the other runtimes
679
- * do in `getRuntimeCommand`. Uses the standard `bash -c <code> --
680
- * arg0 arg1 …` form: the `--` becomes `$0`, then `args[0]` is `$1`
681
- * and so on. Same AST validation as the no-args path.
682
- *
683
- * Used by both the `execute_code`/`lang:'bash'` path AND the
684
- * `bash_tool` factory so the schema's `args` contract works
685
- * identically in both surfaces.
686
- */
484
+ * Variant of `executeLocalBash` that exposes `args` as positional
485
+ * shell parameters (`$1`, `$2`, …). Mirrors what the other runtimes
486
+ * do in `getRuntimeCommand`. Uses the standard `bash -c <code> --
487
+ * arg0 arg1 …` form: the `--` becomes `$0`, then `args[0]` is `$1`
488
+ * and so on. Same AST validation as the no-args path.
489
+ *
490
+ * Used by both the `execute_code`/`lang:'bash'` path AND the
491
+ * `bash_tool` factory so the schema's `args` contract works
492
+ * identically in both surfaces.
493
+ */
687
494
  /**
688
- * Matches a single arg that, on its own, references a protected
689
- * location (`/`, `~`, `$HOME`, `${HOME}`, `.`, with optional trailing
690
- * slash, wildcard, or dot-glob suffix). Used to spot the
691
- * `command: 'rm -rf "$1"', args: ['/']` shape where the destructive
692
- * target is moved into a positional arg to evade the command regex.
693
- * Codex P1 [45], extended for dot-glob in Codex P1 [47] (mirrors the
694
- * `DESTRUCTIVE_TARGET` suffix matrix exactly).
695
- */
495
+ * Matches a single arg that, on its own, references a protected
496
+ * location (`/`, `~`, `$HOME`, `${HOME}`, `.`, with optional trailing
497
+ * slash, wildcard, or dot-glob suffix). Used to spot the
498
+ * `command: 'rm -rf "$1"', args: ['/']` shape where the destructive
499
+ * target is moved into a positional arg to evade the command regex.
500
+ * Codex P1 [45], extended for dot-glob in Codex P1 [47] (mirrors the
501
+ * `DESTRUCTIVE_TARGET` suffix matrix exactly).
502
+ */
696
503
  const PROTECTED_TARGET_ARG_RE = /^(?:\/|~|\$\{?HOME\}?|\.)(?:\/?\.?\*|\/)?$/;
697
504
  /**
698
- * Mutating-op recognizer for the args check. Conservative: only the
699
- * three operations the destructive-command guard already covers
700
- * directly (`rm -rf …`, `chmod -R …`, `chown -R …`). Other shell
701
- * builtins might mutate state (`mv`, `cp` over an existing file,
702
- * etc.) but the destructive guard doesn't try to catch those today,
703
- * so we don't widen here either.
704
- */
505
+ * Mutating-op recognizer for the args check. Conservative: only the
506
+ * three operations the destructive-command guard already covers
507
+ * directly (`rm -rf …`, `chmod -R …`, `chown -R …`). Other shell
508
+ * builtins might mutate state (`mv`, `cp` over an existing file,
509
+ * etc.) but the destructive guard doesn't try to catch those today,
510
+ * so we don't widen here either.
511
+ */
705
512
  const DESTRUCTIVE_OP_IN_COMMAND_RE = /\b(?:rm\s+-[^\s]*[rf]|chmod\s+-R|chown\s+-R)\b/;
706
513
  async function executeLocalBashWithArgs(command, args, config = {}) {
707
- const validation = await validateBashCommand(command, config);
708
- if (!validation.valid) {
709
- throw new Error(validation.errors.join('\n'));
710
- }
711
- // Per-arg protected-target check (Codex P1 [45]). The command
712
- // regex can't see `$1`/`$@` substitutions at runtime — `command:
713
- // 'rm -rf "$1"', args: ['/']` would expand to `rm -rf '/'` inside
714
- // bash but the validator only saw `rm -rf "$1"` (no destructive
715
- // target). Block when (a) the command contains a destructive op
716
- // AND (b) at least one arg matches the protected-target shape.
717
- // Skipped when allowDangerousCommands is true (host-opted-in).
718
- if (args.length > 0 &&
719
- config.allowDangerousCommands !== true &&
720
- DESTRUCTIVE_OP_IN_COMMAND_RE.test(command)) {
721
- const offending = args.find((a) => PROTECTED_TARGET_ARG_RE.test(a));
722
- if (offending !== undefined) {
723
- throw new Error(`Command matches a destructive command pattern (protected target "${offending}" passed via positional arg).`);
724
- }
725
- }
726
- const shell = config.shell ?? DEFAULT_SHELL;
727
- return spawnLocalProcess(shell, ['-lc', command, '--', ...args], config);
514
+ const validation = await validateBashCommand(command, config);
515
+ if (!validation.valid) throw new Error(validation.errors.join("\n"));
516
+ if (args.length > 0 && config.allowDangerousCommands !== true && DESTRUCTIVE_OP_IN_COMMAND_RE.test(command)) {
517
+ const offending = args.find((a) => PROTECTED_TARGET_ARG_RE.test(a));
518
+ if (offending !== void 0) throw new Error(`Command matches a destructive command pattern (protected target "${offending}" passed via positional arg).`);
519
+ }
520
+ return spawnLocalProcess(config.shell ?? DEFAULT_SHELL, [
521
+ "-lc",
522
+ command,
523
+ "--",
524
+ ...args
525
+ ], config);
728
526
  }
729
527
  async function executeLocalCode(input, config = {}) {
730
- if (input.lang === 'bash') {
731
- // Append `args` as positional parameters via the standard
732
- // `bash -c <code> -- <args...>` form so `$1`, `$2`, … inside
733
- // `code` resolve correctly. Honours the same args contract the
734
- // other runtimes (py, js, …) already support.
735
- if (input.args != null && input.args.length > 0) {
736
- return executeLocalBashWithArgs(input.code, input.args, config);
737
- }
738
- return executeLocalBash(input.code, config);
739
- }
740
- const tempDir = resolve(tmpdir(), `lc-local-${randomUUID()}`);
741
- await mkdir(tempDir, { recursive: true });
742
- try {
743
- const runtime = getRuntimeCommand(input.lang, tempDir, input.code, input.args, config.shell);
744
- if (runtime.source != null) {
745
- await writeFile(resolve(tempDir, runtime.fileName), runtime.source, 'utf8');
746
- }
747
- return await spawnLocalProcess(runtime.command, runtime.args, config);
748
- }
749
- finally {
750
- await rm(tempDir, { recursive: true, force: true });
751
- }
752
- }
753
- function getRuntimeCommand(lang, tempDir, code, args = [],
754
- // Override for the shell used by compile-style runtimes (`rs`,
755
- // `c`, `cpp`, `java`, `d`, `f90`). Threads `local.shell` so a host
756
- // that doesn't have bash (or wants `/bin/sh` / zsh) can still
757
- // execute these languages — Codex P2 #29: the bare-bash hardcode
758
- // mirrored the same gap that Codex P1 #6 fixed for the syntax
759
- // preflight, but had been missed for these runtime invocations.
760
- shellOverride) {
761
- const fileFor = (name) => resolve(tempDir, name);
762
- const shell = shellOverride ?? configShell();
763
- switch (lang) {
764
- case 'py':
765
- return {
766
- command: 'python3',
767
- args: [fileFor('main.py'), ...args],
768
- fileName: 'main.py',
769
- source: code,
770
- };
771
- case 'js':
772
- return {
773
- command: 'node',
774
- args: [fileFor('main.js'), ...args],
775
- fileName: 'main.js',
776
- source: code,
777
- };
778
- case 'ts':
779
- return {
780
- command: 'npx',
781
- args: ['--no-install', 'tsx', fileFor('main.ts'), ...args],
782
- fileName: 'main.ts',
783
- source: code,
784
- };
785
- case 'php':
786
- return {
787
- command: 'php',
788
- args: [fileFor('main.php'), ...args],
789
- fileName: 'main.php',
790
- source: code,
791
- };
792
- case 'go':
793
- return {
794
- command: 'go',
795
- args: ['run', fileFor('main.go'), ...args],
796
- fileName: 'main.go',
797
- source: code,
798
- };
799
- case 'rs':
800
- return {
801
- command: shell,
802
- args: [
803
- '-lc',
804
- `rustc ${shellQuote(fileFor('main.rs'))} -o ${shellQuote(fileFor('main-rs'))} && ${shellQuote(fileFor('main-rs'))} ${args.map(shellQuote).join(' ')}`,
805
- ],
806
- fileName: 'main.rs',
807
- source: code,
808
- };
809
- case 'c':
810
- return {
811
- command: shell,
812
- args: [
813
- '-lc',
814
- `cc ${shellQuote(fileFor('main.c'))} -o ${shellQuote(fileFor('main-c'))} && ${shellQuote(fileFor('main-c'))} ${args.map(shellQuote).join(' ')}`,
815
- ],
816
- fileName: 'main.c',
817
- source: code,
818
- };
819
- case 'cpp':
820
- return {
821
- command: shell,
822
- args: [
823
- '-lc',
824
- `c++ ${shellQuote(fileFor('main.cpp'))} -o ${shellQuote(fileFor('main-cpp'))} && ${shellQuote(fileFor('main-cpp'))} ${args.map(shellQuote).join(' ')}`,
825
- ],
826
- fileName: 'main.cpp',
827
- source: code,
828
- };
829
- case 'java':
830
- return {
831
- command: shell,
832
- args: [
833
- '-lc',
834
- `javac ${shellQuote(fileFor('Main.java'))} && java -cp ${shellQuote(tempDir)} Main ${args.map(shellQuote).join(' ')}`,
835
- ],
836
- fileName: 'Main.java',
837
- source: code,
838
- };
839
- case 'r':
840
- return {
841
- command: 'Rscript',
842
- args: [fileFor('main.R'), ...args],
843
- fileName: 'main.R',
844
- source: code,
845
- };
846
- case 'd':
847
- return {
848
- command: shell,
849
- args: [
850
- '-lc',
851
- `dmd ${shellQuote(fileFor('main.d'))} -of=${shellQuote(fileFor('main-d'))} && ${shellQuote(fileFor('main-d'))} ${args.map(shellQuote).join(' ')}`,
852
- ],
853
- fileName: 'main.d',
854
- source: code,
855
- };
856
- case 'f90':
857
- return {
858
- command: shell,
859
- args: [
860
- '-lc',
861
- `gfortran ${shellQuote(fileFor('main.f90'))} -o ${shellQuote(fileFor('main-f90'))} && ${shellQuote(fileFor('main-f90'))} ${args.map(shellQuote).join(' ')}`,
862
- ],
863
- fileName: 'main.f90',
864
- source: code,
865
- };
866
- default:
867
- throw new Error(`Unsupported local runtime: ${lang}`);
868
- }
528
+ if (input.lang === "bash") {
529
+ if (input.args != null && input.args.length > 0) return executeLocalBashWithArgs(input.code, input.args, config);
530
+ return executeLocalBash(input.code, config);
531
+ }
532
+ const tempDir = resolve(tmpdir(), `lc-local-${randomUUID()}`);
533
+ await mkdir(tempDir, { recursive: true });
534
+ try {
535
+ const runtime = getRuntimeCommand(input.lang, tempDir, input.code, input.args, config.shell);
536
+ if (runtime.source != null) await writeFile(resolve(tempDir, runtime.fileName), runtime.source, "utf8");
537
+ return await spawnLocalProcess(runtime.command, runtime.args, config);
538
+ } finally {
539
+ await rm(tempDir, {
540
+ recursive: true,
541
+ force: true
542
+ });
543
+ }
544
+ }
545
+ function getRuntimeCommand(lang, tempDir, code, args = [], shellOverride) {
546
+ const fileFor = (name) => resolve(tempDir, name);
547
+ const shell = shellOverride ?? configShell();
548
+ switch (lang) {
549
+ case "py": return {
550
+ command: "python3",
551
+ args: [fileFor("main.py"), ...args],
552
+ fileName: "main.py",
553
+ source: code
554
+ };
555
+ case "js": return {
556
+ command: "node",
557
+ args: [fileFor("main.js"), ...args],
558
+ fileName: "main.js",
559
+ source: code
560
+ };
561
+ case "ts": return {
562
+ command: "npx",
563
+ args: [
564
+ "--no-install",
565
+ "tsx",
566
+ fileFor("main.ts"),
567
+ ...args
568
+ ],
569
+ fileName: "main.ts",
570
+ source: code
571
+ };
572
+ case "php": return {
573
+ command: "php",
574
+ args: [fileFor("main.php"), ...args],
575
+ fileName: "main.php",
576
+ source: code
577
+ };
578
+ case "go": return {
579
+ command: "go",
580
+ args: [
581
+ "run",
582
+ fileFor("main.go"),
583
+ ...args
584
+ ],
585
+ fileName: "main.go",
586
+ source: code
587
+ };
588
+ case "rs": return {
589
+ command: shell,
590
+ args: ["-lc", `rustc ${shellQuote(fileFor("main.rs"))} -o ${shellQuote(fileFor("main-rs"))} && ${shellQuote(fileFor("main-rs"))} ${args.map(shellQuote).join(" ")}`],
591
+ fileName: "main.rs",
592
+ source: code
593
+ };
594
+ case "c": return {
595
+ command: shell,
596
+ args: ["-lc", `cc ${shellQuote(fileFor("main.c"))} -o ${shellQuote(fileFor("main-c"))} && ${shellQuote(fileFor("main-c"))} ${args.map(shellQuote).join(" ")}`],
597
+ fileName: "main.c",
598
+ source: code
599
+ };
600
+ case "cpp": return {
601
+ command: shell,
602
+ args: ["-lc", `c++ ${shellQuote(fileFor("main.cpp"))} -o ${shellQuote(fileFor("main-cpp"))} && ${shellQuote(fileFor("main-cpp"))} ${args.map(shellQuote).join(" ")}`],
603
+ fileName: "main.cpp",
604
+ source: code
605
+ };
606
+ case "java": return {
607
+ command: shell,
608
+ args: ["-lc", `javac ${shellQuote(fileFor("Main.java"))} && java -cp ${shellQuote(tempDir)} Main ${args.map(shellQuote).join(" ")}`],
609
+ fileName: "Main.java",
610
+ source: code
611
+ };
612
+ case "r": return {
613
+ command: "Rscript",
614
+ args: [fileFor("main.R"), ...args],
615
+ fileName: "main.R",
616
+ source: code
617
+ };
618
+ case "d": return {
619
+ command: shell,
620
+ args: ["-lc", `dmd ${shellQuote(fileFor("main.d"))} -of=${shellQuote(fileFor("main-d"))} && ${shellQuote(fileFor("main-d"))} ${args.map(shellQuote).join(" ")}`],
621
+ fileName: "main.d",
622
+ source: code
623
+ };
624
+ case "f90": return {
625
+ command: shell,
626
+ args: ["-lc", `gfortran ${shellQuote(fileFor("main.f90"))} -o ${shellQuote(fileFor("main-f90"))} && ${shellQuote(fileFor("main-f90"))} ${args.map(shellQuote).join(" ")}`],
627
+ fileName: "main.f90",
628
+ source: code
629
+ };
630
+ default: throw new Error(`Unsupported local runtime: ${lang}`);
631
+ }
869
632
  }
870
633
  function configShell() {
871
- return process.platform === 'win32' ? 'bash.exe' : 'bash';
634
+ return process.platform === "win32" ? "bash.exe" : "bash";
872
635
  }
873
636
  /**
874
- * How long after SIGTERM we wait before escalating to SIGKILL. A
875
- * cooperative process gets a graceful chance to flush + clean up;
876
- * a process that ignores or traps SIGTERM (`trap '' TERM`) gets
877
- * killed unconditionally so timeoutMs / maxSpawnedBytes can't be
878
- * defeated by a hostile script. Codex P1 #28 — pre-fix the spawn
879
- * promise would never resolve in that case and the entire tool run
880
- * would hang past the advertised timeout.
881
- */
882
- const SIGKILL_ESCALATION_MS = 2000;
637
+ * How long after SIGTERM we wait before escalating to SIGKILL. A
638
+ * cooperative process gets a graceful chance to flush + clean up;
639
+ * a process that ignores or traps SIGTERM (`trap '' TERM`) gets
640
+ * killed unconditionally so timeoutMs / maxSpawnedBytes can't be
641
+ * defeated by a hostile script. Codex P1 #28 — pre-fix the spawn
642
+ * promise would never resolve in that case and the entire tool run
643
+ * would hang past the advertised timeout.
644
+ */
645
+ const SIGKILL_ESCALATION_MS = 2e3;
883
646
  function sigterm(child) {
884
- if (child.pid == null) {
885
- child.kill('SIGTERM');
886
- return;
887
- }
888
- try {
889
- if (process.platform === 'win32') {
890
- child.kill('SIGTERM');
891
- return;
892
- }
893
- process.kill(-child.pid, 'SIGTERM');
894
- }
895
- catch {
896
- child.kill('SIGTERM');
897
- }
647
+ if (child.pid == null) {
648
+ child.kill("SIGTERM");
649
+ return;
650
+ }
651
+ try {
652
+ if (process.platform === "win32") {
653
+ child.kill("SIGTERM");
654
+ return;
655
+ }
656
+ process.kill(-child.pid, "SIGTERM");
657
+ } catch {
658
+ child.kill("SIGTERM");
659
+ }
898
660
  }
899
661
  function sigkill(child) {
900
- if (child.exitCode != null || child.signalCode != null)
901
- return;
902
- if (child.pid == null) {
903
- child.kill('SIGKILL');
904
- return;
905
- }
906
- try {
907
- if (process.platform === 'win32') {
908
- child.kill('SIGKILL');
909
- return;
910
- }
911
- process.kill(-child.pid, 'SIGKILL');
912
- }
913
- catch {
914
- try {
915
- child.kill('SIGKILL');
916
- }
917
- catch {
918
- /* already dead */
919
- }
920
- }
662
+ if (child.exitCode != null || child.signalCode != null) return;
663
+ if (child.pid == null) {
664
+ child.kill("SIGKILL");
665
+ return;
666
+ }
667
+ try {
668
+ if (process.platform === "win32") {
669
+ child.kill("SIGKILL");
670
+ return;
671
+ }
672
+ process.kill(-child.pid, "SIGKILL");
673
+ } catch {
674
+ try {
675
+ child.kill("SIGKILL");
676
+ } catch {}
677
+ }
921
678
  }
922
679
  function killProcessTree(child) {
923
- sigterm(child);
924
- // Escalate to SIGKILL if the child is still alive after the grace
925
- // window. Use unref() so the timer doesn't keep the Node process
926
- // alive past the parent's natural exit.
927
- const escalation = setTimeout(() => sigkill(child), SIGKILL_ESCALATION_MS);
928
- escalation.unref();
929
- child.once('close', () => clearTimeout(escalation));
680
+ sigterm(child);
681
+ const escalation = setTimeout(() => sigkill(child), SIGKILL_ESCALATION_MS);
682
+ escalation.unref();
683
+ child.once("close", () => clearTimeout(escalation));
930
684
  }
931
685
  function shellQuote(value) {
932
- if (value === '') {
933
- return '\'\'';
934
- }
935
- if (/^[A-Za-z0-9_/:=.,@%+-]+$/.test(value)) {
936
- return value;
937
- }
938
- return `'${value.replace(/'/g, '\'\\\'\'')}'`;
939
- }
940
- function resolveWorkspacePath(filePath, config = {}, intent = 'write') {
941
- const cwd = getLocalCwd(config);
942
- const absolutePath = isAbsolute(filePath)
943
- ? resolve(filePath)
944
- : resolve(cwd, filePath);
945
- const roots = intent === 'write' ? getWriteRoots(config) : getReadRoots(config);
946
- if (roots == null)
947
- return absolutePath; // explicit allow-outside
948
- if (absolutePath === cwd || isInsideAnyRoot(absolutePath, roots)) {
949
- return absolutePath;
950
- }
951
- throw new Error(`Path is outside the local workspace: ${filePath}`);
686
+ if (value === "") return "''";
687
+ if (/^[A-Za-z0-9_/:=.,@%+-]+$/.test(value)) return value;
688
+ return `'${value.replace(/'/g, "'\\''")}'`;
689
+ }
690
+ function resolveWorkspacePath(filePath, config = {}, intent = "write") {
691
+ const cwd = getLocalCwd(config);
692
+ const absolutePath = isAbsolute(filePath) ? resolve(filePath) : resolve(cwd, filePath);
693
+ const roots = intent === "write" ? getWriteRoots(config) : getReadRoots(config);
694
+ if (roots == null) return absolutePath;
695
+ if (absolutePath === cwd || isInsideAnyRoot(absolutePath, roots)) return absolutePath;
696
+ throw new Error(`Path is outside the local workspace: ${filePath}`);
952
697
  }
953
698
  function isInsideAnyRoot(absolutePath, roots) {
954
- for (const root of roots) {
955
- if (absolutePath === root)
956
- return true;
957
- const rel = relative(root, absolutePath);
958
- if (!rel.startsWith('..') && !isAbsolute(rel))
959
- return true;
960
- }
961
- return false;
699
+ for (const root of roots) {
700
+ if (absolutePath === root) return true;
701
+ const rel = relative(root, absolutePath);
702
+ if (!rel.startsWith("..") && !isAbsolute(rel)) return true;
703
+ }
704
+ return false;
962
705
  }
963
706
  async function realpathOrSelf(absolutePath, realpathImpl = realpath) {
964
- try {
965
- return await realpathImpl(absolutePath);
966
- }
967
- catch {
968
- return absolutePath;
969
- }
707
+ try {
708
+ return await realpathImpl(absolutePath);
709
+ } catch {
710
+ return absolutePath;
711
+ }
970
712
  }
971
713
  /**
972
- * Resolves the realpath of `absolutePath`, falling back to the nearest
973
- * existing ancestor when the target itself does not yet exist (so the
974
- * containment check still works for `write_file` to a brand-new path).
975
- *
976
- * Codex P2 #38: takes the realpath impl as a parameter so callers
977
- * can route through `WorkspaceFS.realpath` when a custom engine is
978
- * configured. Pre-fix, host `fs/promises.realpath` would fail on a
979
- * remote/in-memory FS path and silently fall back to lexical
980
- * containment, leaving the symlink-escape clamp ineffective on
981
- * non-default engines.
982
- */
714
+ * Resolves the realpath of `absolutePath`, falling back to the nearest
715
+ * existing ancestor when the target itself does not yet exist (so the
716
+ * containment check still works for `write_file` to a brand-new path).
717
+ *
718
+ * Codex P2 #38: takes the realpath impl as a parameter so callers
719
+ * can route through `WorkspaceFS.realpath` when a custom engine is
720
+ * configured. Pre-fix, host `fs/promises.realpath` would fail on a
721
+ * remote/in-memory FS path and silently fall back to lexical
722
+ * containment, leaving the symlink-escape clamp ineffective on
723
+ * non-default engines.
724
+ */
983
725
  async function realpathOfPathOrAncestor(absolutePath, realpathImpl = realpath) {
984
- let current = absolutePath;
985
- let suffix = '';
986
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
987
- while (true) {
988
- try {
989
- const real = await realpathImpl(current);
990
- return suffix === '' ? real : resolve(real, suffix);
991
- }
992
- catch {
993
- const parent = resolve(current, '..');
994
- if (parent === current) {
995
- return absolutePath;
996
- }
997
- const base = current.slice(parent.length + 1);
998
- suffix = suffix === '' ? base : `${base}/${suffix}`;
999
- current = parent;
1000
- }
1001
- }
726
+ let current = absolutePath;
727
+ let suffix = "";
728
+ while (true) try {
729
+ const real = await realpathImpl(current);
730
+ return suffix === "" ? real : resolve(real, suffix);
731
+ } catch {
732
+ const parent = resolve(current, "..");
733
+ if (parent === current) return absolutePath;
734
+ const base = current.slice(parent.length + 1);
735
+ suffix = suffix === "" ? base : `${base}/${suffix}`;
736
+ current = parent;
737
+ }
1002
738
  }
1003
739
  /**
1004
- * Resolves a workspace path AND follows any symlinks before checking
1005
- * containment, so a symlink inside the workspace pointing outside is
1006
- * rejected even though the lexical path looks safe. Handles paths that
1007
- * don't yet exist (e.g. write_file targets) by realpath-resolving the
1008
- * nearest existing ancestor and re-attaching the unresolved suffix.
1009
- */
1010
- async function resolveWorkspacePathSafe(filePath, config = {}, intent = 'write') {
1011
- const lexical = resolveWorkspacePath(filePath, config, intent);
1012
- const roots = intent === 'write' ? getWriteRoots(config) : getReadRoots(config);
1013
- if (roots == null) {
1014
- return lexical;
1015
- }
1016
- // Route realpath through the configured WorkspaceFS so a custom
1017
- // engine (in-memory, remote) gets the same symlink-escape clamp
1018
- // the host-fs path gets. Codex P2 #38: pre-fix the host realpath
1019
- // would fail on a non-default FS path and silently fall back to
1020
- // lexical containment, leaving the clamp ineffective.
1021
- const fsRealpath = (p) => getWorkspaceFS(config).realpath(p);
1022
- const realRoots = await Promise.all(roots.map((r) => realpathOrSelf(r, fsRealpath)));
1023
- const realPath = await realpathOfPathOrAncestor(lexical, fsRealpath);
1024
- if (isInsideAnyRoot(realPath, realRoots)) {
1025
- return lexical;
1026
- }
1027
- throw new Error(`Path is outside the local workspace (symlink escape): ${filePath}`);
1028
- }
1029
-
740
+ * Resolves a workspace path AND follows any symlinks before checking
741
+ * containment, so a symlink inside the workspace pointing outside is
742
+ * rejected even though the lexical path looks safe. Handles paths that
743
+ * don't yet exist (e.g. write_file targets) by realpath-resolving the
744
+ * nearest existing ancestor and re-attaching the unresolved suffix.
745
+ */
746
+ async function resolveWorkspacePathSafe(filePath, config = {}, intent = "write") {
747
+ const lexical = resolveWorkspacePath(filePath, config, intent);
748
+ const roots = intent === "write" ? getWriteRoots(config) : getReadRoots(config);
749
+ if (roots == null) return lexical;
750
+ const fsRealpath = (p) => getWorkspaceFS(config).realpath(p);
751
+ const realRoots = await Promise.all(roots.map((r) => realpathOrSelf(r, fsRealpath)));
752
+ if (isInsideAnyRoot(await realpathOfPathOrAncestor(lexical, fsRealpath), realRoots)) return lexical;
753
+ throw new Error(`Path is outside the local workspace (symlink escape): ${filePath}`);
754
+ }
755
+ //#endregion
1030
756
  export { LOCAL_SPAWN_TIMEOUT_MS, _resetLocalEngineWarningsForTests, buildSandboxRuntimeConfig, executeLocalBash, executeLocalBashWithArgs, executeLocalCode, getLocalCwd, getLocalSessionId, getReadRoots, getSpawn, getWorkspaceFS, getWorkspaceRoots, getWriteRoots, resolveLocalExecutionConfig, resolveWorkspacePath, resolveWorkspacePathSafe, shellQuote, spawnLocalProcess, truncateLocalOutput, validateBashCommand };
1031
- //# sourceMappingURL=LocalExecutionEngine.mjs.map
757
+
758
+ //# sourceMappingURL=LocalExecutionEngine.mjs.map