@nhtio/adk 0.1.0-master-e5947c71 → 0.1.0-master-74266e68

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 (355) hide show
  1. package/CHANGELOG.md +124 -1
  2. package/artifact_methods-BvoDGBnH.cjs +1 -0
  3. package/artifact_methods-q52ETLwI.mjs +1 -0
  4. package/batteries/artifacts/ecmascript.cjs +1 -1
  5. package/batteries/artifacts/ecmascript.mjs +1 -1
  6. package/batteries/artifacts/toon.cjs +1 -1
  7. package/batteries/artifacts/toon.mjs +1 -1
  8. package/batteries/artifacts/xml.cjs +1 -1
  9. package/batteries/artifacts/xml.mjs +1 -1
  10. package/batteries/artifacts/yaml.cjs +1 -1
  11. package/batteries/artifacts/yaml.mjs +1 -1
  12. package/batteries/artifacts.cjs +4 -4
  13. package/batteries/artifacts.mjs +4 -4
  14. package/batteries/dev-tools/forge.cjs +3 -3
  15. package/batteries/dev-tools/forge.mjs +3 -3
  16. package/batteries/dev-tools.cjs +2 -2
  17. package/batteries/dev-tools.mjs +2 -2
  18. package/batteries/encoding.cjs +7 -7
  19. package/batteries/encoding.mjs +7 -7
  20. package/batteries/generation/gemini/adapter.cjs +1 -1
  21. package/batteries/generation/gemini/adapter.mjs +1 -1
  22. package/batteries/generation/local_diffusion/adapter.cjs +1 -1
  23. package/batteries/generation/local_diffusion/adapter.mjs +1 -1
  24. package/batteries/generation/openai/adapter.cjs +1 -1
  25. package/batteries/generation/openai/adapter.mjs +1 -1
  26. package/batteries/llm/anthropic_messages/adapter.cjs +6 -6
  27. package/batteries/llm/anthropic_messages/adapter.mjs +6 -6
  28. package/batteries/llm/anthropic_messages/count_tokens.cjs +2 -2
  29. package/batteries/llm/anthropic_messages/count_tokens.mjs +1 -1
  30. package/batteries/llm/anthropic_messages/helpers.cjs +3 -3
  31. package/batteries/llm/anthropic_messages/helpers.mjs +3 -3
  32. package/batteries/llm/anthropic_messages/validation.cjs +2 -2
  33. package/batteries/llm/anthropic_messages/validation.mjs +2 -2
  34. package/batteries/llm/anthropic_messages.cjs +2 -2
  35. package/batteries/llm/anthropic_messages.mjs +2 -2
  36. package/batteries/llm/bedrock_converse/adapter.cjs +6 -6
  37. package/batteries/llm/bedrock_converse/adapter.mjs +6 -6
  38. package/batteries/llm/bedrock_converse/helpers.cjs +1 -1
  39. package/batteries/llm/bedrock_converse/helpers.mjs +1 -1
  40. package/batteries/llm/bedrock_converse/validation.cjs +2 -2
  41. package/batteries/llm/bedrock_converse/validation.mjs +2 -2
  42. package/batteries/llm/bedrock_converse.cjs +2 -2
  43. package/batteries/llm/bedrock_converse.mjs +2 -2
  44. package/batteries/llm/claude_code_cli/adapter.cjs +7 -7
  45. package/batteries/llm/claude_code_cli/adapter.mjs +7 -7
  46. package/batteries/llm/claude_code_cli/helpers.cjs +3 -3
  47. package/batteries/llm/claude_code_cli/helpers.mjs +3 -3
  48. package/batteries/llm/claude_code_cli/validation.cjs +2 -2
  49. package/batteries/llm/claude_code_cli/validation.mjs +2 -2
  50. package/batteries/llm/claude_code_cli.cjs +2 -2
  51. package/batteries/llm/claude_code_cli.mjs +2 -2
  52. package/batteries/llm/gemini_generate_content/adapter.cjs +7 -7
  53. package/batteries/llm/gemini_generate_content/adapter.mjs +7 -7
  54. package/batteries/llm/gemini_generate_content/helpers.cjs +1 -1
  55. package/batteries/llm/gemini_generate_content/helpers.mjs +1 -1
  56. package/batteries/llm/gemini_generate_content/validation.cjs +2 -2
  57. package/batteries/llm/gemini_generate_content/validation.mjs +2 -2
  58. package/batteries/llm/gemini_generate_content.cjs +2 -2
  59. package/batteries/llm/gemini_generate_content.mjs +2 -2
  60. package/batteries/llm/litert_lm/adapter.cjs +6 -6
  61. package/batteries/llm/litert_lm/adapter.mjs +6 -6
  62. package/batteries/llm/litert_lm/helpers.cjs +3 -3
  63. package/batteries/llm/litert_lm/helpers.mjs +3 -3
  64. package/batteries/llm/litert_lm/validation.cjs +2 -2
  65. package/batteries/llm/litert_lm/validation.mjs +2 -2
  66. package/batteries/llm/litert_lm.cjs +1 -1
  67. package/batteries/llm/litert_lm.mjs +1 -1
  68. package/batteries/llm/ollama/adapter.cjs +6 -6
  69. package/batteries/llm/ollama/adapter.mjs +6 -6
  70. package/batteries/llm/ollama/helpers.cjs +4 -4
  71. package/batteries/llm/ollama/helpers.mjs +4 -4
  72. package/batteries/llm/ollama/validation.cjs +2 -2
  73. package/batteries/llm/ollama/validation.mjs +2 -2
  74. package/batteries/llm/ollama.cjs +2 -2
  75. package/batteries/llm/ollama.mjs +2 -2
  76. package/batteries/llm/openai_chat_completions/adapter.cjs +6 -6
  77. package/batteries/llm/openai_chat_completions/adapter.mjs +6 -6
  78. package/batteries/llm/openai_chat_completions/helpers.cjs +4 -4
  79. package/batteries/llm/openai_chat_completions/helpers.mjs +4 -4
  80. package/batteries/llm/openai_chat_completions/validation.cjs +2 -2
  81. package/batteries/llm/openai_chat_completions/validation.mjs +2 -2
  82. package/batteries/llm/openai_chat_completions.cjs +2 -2
  83. package/batteries/llm/openai_chat_completions.mjs +2 -2
  84. package/batteries/llm/openai_responses/adapter.cjs +6 -6
  85. package/batteries/llm/openai_responses/adapter.mjs +6 -6
  86. package/batteries/llm/openai_responses/helpers.cjs +3 -3
  87. package/batteries/llm/openai_responses/helpers.mjs +3 -3
  88. package/batteries/llm/openai_responses/validation.cjs +2 -2
  89. package/batteries/llm/openai_responses/validation.mjs +2 -2
  90. package/batteries/llm/openai_responses.cjs +2 -2
  91. package/batteries/llm/openai_responses.mjs +2 -2
  92. package/batteries/llm/transformers_js/adapter.cjs +6 -6
  93. package/batteries/llm/transformers_js/adapter.mjs +6 -6
  94. package/batteries/llm/transformers_js/helpers.cjs +3 -3
  95. package/batteries/llm/transformers_js/helpers.mjs +3 -3
  96. package/batteries/llm/transformers_js/validation.cjs +2 -2
  97. package/batteries/llm/transformers_js/validation.mjs +2 -2
  98. package/batteries/llm/transformers_js.cjs +1 -1
  99. package/batteries/llm/transformers_js.mjs +1 -1
  100. package/batteries/llm/webllm_chat_completions/adapter.cjs +6 -6
  101. package/batteries/llm/webllm_chat_completions/adapter.mjs +6 -6
  102. package/batteries/llm/webllm_chat_completions/helpers.cjs +1 -1
  103. package/batteries/llm/webllm_chat_completions/helpers.mjs +1 -1
  104. package/batteries/llm/webllm_chat_completions/validation.cjs +2 -2
  105. package/batteries/llm/webllm_chat_completions/validation.mjs +2 -2
  106. package/batteries/llm/webllm_chat_completions.cjs +2 -2
  107. package/batteries/llm/webllm_chat_completions.mjs +2 -2
  108. package/batteries/llm.cjs +2 -2
  109. package/batteries/llm.mjs +2 -2
  110. package/batteries/media/contracts.cjs.map +1 -1
  111. package/batteries/media/contracts.d.ts +93 -2
  112. package/batteries/media/contracts.mjs.map +1 -1
  113. package/batteries/media/engines/execa_executor.cjs +285 -13
  114. package/batteries/media/engines/execa_executor.cjs.map +1 -1
  115. package/batteries/media/engines/execa_executor.d.ts +113 -8
  116. package/batteries/media/engines/execa_executor.mjs +285 -13
  117. package/batteries/media/engines/execa_executor.mjs.map +1 -1
  118. package/batteries/media/forge.cjs +4 -4
  119. package/batteries/media/forge.mjs +4 -4
  120. package/batteries/media/lint.cjs +1 -1
  121. package/batteries/media/lint.mjs +1 -1
  122. package/batteries/media.cjs +1 -1
  123. package/batteries/orchestration/dispatch_reasoner.cjs +4 -4
  124. package/batteries/orchestration/dispatch_reasoner.mjs +4 -4
  125. package/batteries/orchestration/executor.cjs +2 -2
  126. package/batteries/orchestration/executor.mjs +2 -2
  127. package/batteries/orchestration/forge.cjs +3 -3
  128. package/batteries/orchestration/forge.mjs +3 -3
  129. package/batteries/orchestration/validation.cjs +2 -2
  130. package/batteries/orchestration/validation.mjs +2 -2
  131. package/batteries/orchestration.cjs +3 -3
  132. package/batteries/orchestration.mjs +3 -3
  133. package/batteries/sandbox/contracts/policy_enforcer.d.ts +12 -6
  134. package/batteries/sandbox/executor.d.ts +28 -10
  135. package/batteries/sandbox/js.cjs +1 -1
  136. package/batteries/sandbox/js.mjs +1 -1
  137. package/batteries/sandbox/node/index.d.ts +1 -1
  138. package/batteries/sandbox/node/srt_enforcer.d.ts +74 -0
  139. package/batteries/sandbox/node.cjs +98 -5
  140. package/batteries/sandbox/node.cjs.map +1 -1
  141. package/batteries/sandbox/node.mjs +98 -6
  142. package/batteries/sandbox/node.mjs.map +1 -1
  143. package/batteries/sandbox/tools.cjs +1 -1
  144. package/batteries/sandbox/tools.mjs +1 -1
  145. package/batteries/sandbox.cjs +13 -13
  146. package/batteries/sandbox.cjs.map +1 -1
  147. package/batteries/sandbox.mjs +13 -13
  148. package/batteries/sandbox.mjs.map +1 -1
  149. package/batteries/skills/in_memory.cjs +1 -1
  150. package/batteries/skills.cjs +10 -10
  151. package/batteries/skills.mjs +9 -9
  152. package/batteries/tools/_shared.cjs +1 -1
  153. package/batteries/tools/_shared.mjs +1 -1
  154. package/batteries/tools/color.cjs +2 -2
  155. package/batteries/tools/color.mjs +2 -2
  156. package/batteries/tools/comparison.cjs +2 -2
  157. package/batteries/tools/comparison.mjs +2 -2
  158. package/batteries/tools/data_structure.cjs +2 -2
  159. package/batteries/tools/data_structure.mjs +2 -2
  160. package/batteries/tools/datetime_extended.cjs +3 -3
  161. package/batteries/tools/datetime_extended.mjs +3 -3
  162. package/batteries/tools/datetime_math.cjs +3 -3
  163. package/batteries/tools/datetime_math.mjs +3 -3
  164. package/batteries/tools/encoding.cjs +2 -2
  165. package/batteries/tools/encoding.mjs +2 -2
  166. package/batteries/tools/formatting.cjs +2 -2
  167. package/batteries/tools/formatting.mjs +2 -2
  168. package/batteries/tools/geo_basics.cjs +2 -2
  169. package/batteries/tools/geo_basics.mjs +2 -2
  170. package/batteries/tools/math.cjs +2 -2
  171. package/batteries/tools/math.mjs +2 -2
  172. package/batteries/tools/memory.cjs +5 -5
  173. package/batteries/tools/memory.mjs +5 -5
  174. package/batteries/tools/parsing.cjs +3 -3
  175. package/batteries/tools/parsing.mjs +3 -3
  176. package/batteries/tools/retrievables.cjs +5 -5
  177. package/batteries/tools/retrievables.mjs +5 -5
  178. package/batteries/tools/scrapper.cjs +1 -1
  179. package/batteries/tools/scrapper.mjs +1 -1
  180. package/batteries/tools/searxng.cjs +1 -1
  181. package/batteries/tools/searxng.mjs +1 -1
  182. package/batteries/tools/standing_instructions.cjs +3 -3
  183. package/batteries/tools/standing_instructions.mjs +3 -3
  184. package/batteries/tools/statistics.cjs +3 -3
  185. package/batteries/tools/statistics.mjs +3 -3
  186. package/batteries/tools/string_processing.cjs +2 -2
  187. package/batteries/tools/string_processing.mjs +2 -2
  188. package/batteries/tools/structured_data.cjs +2 -2
  189. package/batteries/tools/structured_data.mjs +2 -2
  190. package/batteries/tools/text_analysis.cjs +3 -3
  191. package/batteries/tools/text_analysis.mjs +3 -3
  192. package/batteries/tools/text_comparison.cjs +2 -2
  193. package/batteries/tools/text_comparison.mjs +2 -2
  194. package/batteries/tools/time.cjs +3 -3
  195. package/batteries/tools/time.mjs +3 -3
  196. package/batteries/tools/unit_conversion.cjs +2 -2
  197. package/batteries/tools/unit_conversion.mjs +2 -2
  198. package/batteries/tools.cjs +2 -2
  199. package/batteries/tools.mjs +2 -2
  200. package/batteries/validation.cjs +4 -4
  201. package/batteries/validation.mjs +4 -4
  202. package/batteries/vector/chroma.cjs +1 -1
  203. package/batteries/vector/chroma.mjs +1 -1
  204. package/batteries/vector/clickhouse.cjs +1 -1
  205. package/batteries/vector/clickhouse.mjs +1 -1
  206. package/batteries/vector/cloudflare.cjs +1 -1
  207. package/batteries/vector/cloudflare.mjs +1 -1
  208. package/batteries/vector/couchbase.cjs +1 -1
  209. package/batteries/vector/couchbase.mjs +1 -1
  210. package/batteries/vector/duckdb.cjs +1 -1
  211. package/batteries/vector/duckdb.mjs +1 -1
  212. package/batteries/vector/elasticsearch.cjs +1 -1
  213. package/batteries/vector/elasticsearch.mjs +1 -1
  214. package/batteries/vector/hnswlib.cjs +1 -1
  215. package/batteries/vector/hnswlib.mjs +1 -1
  216. package/batteries/vector/in_memory.cjs +1 -1
  217. package/batteries/vector/in_memory.mjs +1 -1
  218. package/batteries/vector/lancedb.cjs +1 -1
  219. package/batteries/vector/lancedb.mjs +1 -1
  220. package/batteries/vector/mariadb.cjs +1 -1
  221. package/batteries/vector/mariadb.mjs +1 -1
  222. package/batteries/vector/milvus.cjs +1 -1
  223. package/batteries/vector/milvus.mjs +1 -1
  224. package/batteries/vector/opensearch.cjs +1 -1
  225. package/batteries/vector/opensearch.mjs +1 -1
  226. package/batteries/vector/oracle23ai.cjs +1 -1
  227. package/batteries/vector/oracle23ai.mjs +1 -1
  228. package/batteries/vector/orama.cjs +1 -1
  229. package/batteries/vector/orama.mjs +1 -1
  230. package/batteries/vector/pgvector.cjs +1 -1
  231. package/batteries/vector/pgvector.mjs +1 -1
  232. package/batteries/vector/pinecone.cjs +1 -1
  233. package/batteries/vector/pinecone.mjs +1 -1
  234. package/batteries/vector/qdrant.cjs +1 -1
  235. package/batteries/vector/qdrant.mjs +1 -1
  236. package/batteries/vector/redis.cjs +1 -1
  237. package/batteries/vector/redis.mjs +1 -1
  238. package/batteries/vector/retrievable.cjs +1 -1
  239. package/batteries/vector/retrievable.mjs +1 -1
  240. package/batteries/vector/s3vectors.cjs +1 -1
  241. package/batteries/vector/s3vectors.mjs +1 -1
  242. package/batteries/vector/sqlite_vec.cjs +1 -1
  243. package/batteries/vector/sqlite_vec.mjs +1 -1
  244. package/batteries/vector/typesense.cjs +1 -1
  245. package/batteries/vector/typesense.mjs +1 -1
  246. package/batteries/vector/vespa.cjs +1 -1
  247. package/batteries/vector/vespa.mjs +1 -1
  248. package/batteries/vector/weaviate.cjs +1 -1
  249. package/batteries/vector/weaviate.mjs +1 -1
  250. package/batteries/vector.cjs +2 -2
  251. package/batteries/vector.mjs +2 -2
  252. package/batteries.cjs +9 -9
  253. package/batteries.mjs +9 -9
  254. package/{chat_common-DKw8FDol.mjs → chat_common-CeoHwSsz.mjs} +2 -2
  255. package/{chat_common-DKw8FDol.mjs.map → chat_common-CeoHwSsz.mjs.map} +1 -1
  256. package/{chat_common-vSxDBGgr.cjs → chat_common-DlIK1IAn.cjs} +2 -2
  257. package/{chat_common-vSxDBGgr.cjs.map → chat_common-DlIK1IAn.cjs.map} +1 -1
  258. package/{common-oI1niK9Z.mjs → common-B5maOoF_.mjs} +7 -7
  259. package/{common-oI1niK9Z.mjs.map → common-B5maOoF_.mjs.map} +1 -1
  260. package/{common-BcB05Isq.cjs → common-joo6vLu-.cjs} +7 -7
  261. package/{common-BcB05Isq.cjs.map → common-joo6vLu-.cjs.map} +1 -1
  262. package/common.cjs +7 -7
  263. package/common.mjs +7 -7
  264. package/{dispatch_runner-CTAI0RSs.cjs → dispatch_runner-BTaUtdtO.cjs} +5 -5
  265. package/{dispatch_runner-CTAI0RSs.cjs.map → dispatch_runner-BTaUtdtO.cjs.map} +1 -1
  266. package/{dispatch_runner-BZDXUe0G.mjs → dispatch_runner-DO7jo_gl.mjs} +5 -5
  267. package/{dispatch_runner-BZDXUe0G.mjs.map → dispatch_runner-DO7jo_gl.mjs.map} +1 -1
  268. package/dispatch_runner.cjs +1 -1
  269. package/dispatch_runner.mjs +1 -1
  270. package/{ecmascript-DOv8gVQ5.cjs → ecmascript-ChvxTCXz.cjs} +3 -3
  271. package/{ecmascript-DOv8gVQ5.cjs.map → ecmascript-ChvxTCXz.cjs.map} +1 -1
  272. package/{ecmascript-B9Z2C24U.mjs → ecmascript-bgwVyZG1.mjs} +3 -3
  273. package/{ecmascript-B9Z2C24U.mjs.map → ecmascript-bgwVyZG1.mjs.map} +1 -1
  274. package/eslint/rules.cjs +1 -1
  275. package/eslint/rules.mjs +1 -1
  276. package/eslint.cjs +2 -2
  277. package/eslint.mjs +2 -2
  278. package/exceptions.cjs +1 -1
  279. package/exceptions.mjs +1 -1
  280. package/forge.cjs +2 -2
  281. package/forge.mjs +2 -2
  282. package/guards.cjs +7 -7
  283. package/guards.mjs +7 -7
  284. package/{helpers-mbn_EsDV.mjs → helpers-C1T0DV8Q.mjs} +3 -3
  285. package/{helpers-mbn_EsDV.mjs.map → helpers-C1T0DV8Q.mjs.map} +1 -1
  286. package/{helpers-CiZnHmxC.cjs → helpers-D6ebO8Vc.cjs} +3 -3
  287. package/{helpers-CiZnHmxC.cjs.map → helpers-D6ebO8Vc.cjs.map} +1 -1
  288. package/index.cjs +10 -10
  289. package/index.mjs +10 -10
  290. package/{manifest-BPcrFRN4.cjs → manifest-DPYWN15l.cjs} +2 -2
  291. package/{manifest-BPcrFRN4.cjs.map → manifest-DPYWN15l.cjs.map} +1 -1
  292. package/mcp/adk-docs-corpus.json +2 -2
  293. package/package.json +407 -407
  294. package/{retrievable-CXTAUuuv.mjs → retrievable-CrGKx4sc.mjs} +3 -3
  295. package/{retrievable-CXTAUuuv.mjs.map → retrievable-CrGKx4sc.mjs.map} +1 -1
  296. package/{retrievable-BOuQSDHF.cjs → retrievable-DVkAglIv.cjs} +3 -3
  297. package/{retrievable-BOuQSDHF.cjs.map → retrievable-DVkAglIv.cjs.map} +1 -1
  298. package/{scrapper-lXnFGDi0.cjs → scrapper-Boc6kq2v.cjs} +4 -4
  299. package/{scrapper-lXnFGDi0.cjs.map → scrapper-Boc6kq2v.cjs.map} +1 -1
  300. package/{scrapper-BCdUm8c8.mjs → scrapper-D2Gy9Jhv.mjs} +4 -4
  301. package/{scrapper-BCdUm8c8.mjs.map → scrapper-D2Gy9Jhv.mjs.map} +1 -1
  302. package/{searxng-N7qu6dA-.cjs → searxng-DOy3eBDH.cjs} +4 -4
  303. package/{searxng-N7qu6dA-.cjs.map → searxng-DOy3eBDH.cjs.map} +1 -1
  304. package/{searxng-B-LdaVUP.mjs → searxng-cCb0lAcN.mjs} +4 -4
  305. package/{searxng-B-LdaVUP.mjs.map → searxng-cCb0lAcN.mjs.map} +1 -1
  306. package/server.json +2 -2
  307. package/skills/adk-assembly/SKILL.md +2 -2
  308. package/{spooled_artifact-Bw_7swIp.mjs → spooled_artifact-BkOe4-j-.mjs} +731 -731
  309. package/spooled_artifact-BkOe4-j-.mjs.map +1 -0
  310. package/{spooled_artifact-DZXsP4s1.cjs → spooled_artifact-BoYsldvO.cjs} +730 -730
  311. package/spooled_artifact-BoYsldvO.cjs.map +1 -0
  312. package/spooled_artifact.cjs +2 -2
  313. package/spooled_artifact.mjs +2 -2
  314. package/{spooled_markdown_artifact-vd6eNtIP.mjs → spooled_markdown_artifact-Dnl-lCGv.mjs} +3 -3
  315. package/{spooled_markdown_artifact-vd6eNtIP.mjs.map → spooled_markdown_artifact-Dnl-lCGv.mjs.map} +1 -1
  316. package/{spooled_markdown_artifact-Bo0u8cRS.cjs → spooled_markdown_artifact-DzbydBel.cjs} +3 -3
  317. package/{spooled_markdown_artifact-Bo0u8cRS.cjs.map → spooled_markdown_artifact-DzbydBel.cjs.map} +1 -1
  318. package/{thought-CxSaF6Xf.mjs → thought-BrQt6HAb.mjs} +3 -3
  319. package/{thought-CxSaF6Xf.mjs.map → thought-BrQt6HAb.mjs.map} +1 -1
  320. package/{thought-C12mqaKQ.cjs → thought-CXsVh5hS.cjs} +3 -3
  321. package/{thought-C12mqaKQ.cjs.map → thought-CXsVh5hS.cjs.map} +1 -1
  322. package/{tokenizable-BcodRtoW.cjs → tokenizable-DDIdXbJN.cjs} +29 -29
  323. package/{tokenizable-BcodRtoW.cjs.map → tokenizable-DDIdXbJN.cjs.map} +1 -1
  324. package/{tokenizable-VB4Av8GF.mjs → tokenizable-xPXj1AQX.mjs} +30 -30
  325. package/{tokenizable-VB4Av8GF.mjs.map → tokenizable-xPXj1AQX.mjs.map} +1 -1
  326. package/{tool_call-Cfaj-6zK.mjs → tool_call-8crmZsO8.mjs} +4 -4
  327. package/{tool_call-Cfaj-6zK.mjs.map → tool_call-8crmZsO8.mjs.map} +1 -1
  328. package/{tool_call-CsBOpKsg.cjs → tool_call-NvQcPf5d.cjs} +4 -4
  329. package/{tool_call-CsBOpKsg.cjs.map → tool_call-NvQcPf5d.cjs.map} +1 -1
  330. package/{tools-BjHXlDlV.cjs → tools-BHc8qB5I.cjs} +6 -6
  331. package/{tools-BjHXlDlV.cjs.map → tools-BHc8qB5I.cjs.map} +1 -1
  332. package/{tools-Vkfht7mU.mjs → tools-geIlta3C.mjs} +6 -6
  333. package/{tools-Vkfht7mU.mjs.map → tools-geIlta3C.mjs.map} +1 -1
  334. package/{toon-BSTQnHed.mjs → toon-BA9Q7NHG.mjs} +5 -5
  335. package/{toon-BSTQnHed.mjs.map → toon-BA9Q7NHG.mjs.map} +1 -1
  336. package/{toon-5c9ceKiU.cjs → toon-C8IFssRi.cjs} +5 -5
  337. package/{toon-5c9ceKiU.cjs.map → toon-C8IFssRi.cjs.map} +1 -1
  338. package/{turn_runner--tsMLLx4.cjs → turn_runner-A-vpLUvj.cjs} +5 -5
  339. package/{turn_runner--tsMLLx4.cjs.map → turn_runner-A-vpLUvj.cjs.map} +1 -1
  340. package/{turn_runner-BHHD6h77.mjs → turn_runner-BmVXcBZ2.mjs} +5 -5
  341. package/{turn_runner-BHHD6h77.mjs.map → turn_runner-BmVXcBZ2.mjs.map} +1 -1
  342. package/turn_runner.cjs +1 -1
  343. package/turn_runner.mjs +1 -1
  344. package/{xml-CYseDztH.mjs → xml-B1JIGLpU.mjs} +5 -5
  345. package/{xml-CYseDztH.mjs.map → xml-B1JIGLpU.mjs.map} +1 -1
  346. package/{xml-DTOnPN52.cjs → xml-Cu7ZvgBQ.cjs} +5 -5
  347. package/{xml-DTOnPN52.cjs.map → xml-Cu7ZvgBQ.cjs.map} +1 -1
  348. package/{yaml-BPBoiOjx.mjs → yaml-1mP4uxdf.mjs} +5 -5
  349. package/{yaml-BPBoiOjx.mjs.map → yaml-1mP4uxdf.mjs.map} +1 -1
  350. package/{yaml-CMrbNWLc.cjs → yaml-BlB29N68.cjs} +5 -5
  351. package/{yaml-CMrbNWLc.cjs.map → yaml-BlB29N68.cjs.map} +1 -1
  352. package/artifact_methods-Cg0go7Q4.mjs +0 -1
  353. package/artifact_methods-Dtf4-3C-.cjs +0 -1
  354. package/spooled_artifact-Bw_7swIp.mjs.map +0 -1
  355. package/spooled_artifact-DZXsP4s1.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"sandbox.cjs","names":[],"sources":["../../src/batteries/sandbox/preflight.ts","../../src/batteries/sandbox/observability.ts","../../src/batteries/sandbox/manager.ts","../../src/batteries/sandbox/executor.ts","../../src/batteries/sandbox/tool.ts","../../src/batteries/sandbox/contracts/policy_enforcer.ts","../../src/batteries/sandbox/contracts/file_system.ts","../../src/batteries/sandbox/contracts/search.ts","../../src/batteries/sandbox/contracts/path_translator.ts","../../src/batteries/sandbox/contracts/guest_runtime.ts","../../src/batteries/sandbox/contracts/mime_resolver.ts","../../src/batteries/sandbox/contracts/artifact_minter.ts"],"sourcesContent":["/**\n * Construction-time admission for the sandbox.\n *\n * This is the seam consumed by WP-A1: `createSandbox()` must call this function once and\n * retain the returned, frozen decision. In particular, WP-A1 must not reproduce the three\n * fallback predicates here; doing so would make the handle's security posture depend on two\n * subtly different implementations.\n */\nimport { isException } from '../../lib/utils/exceptions'\nimport {\n E_SANDBOX_DEPENDENCY_MISSING,\n E_SANDBOX_FAILED,\n E_SANDBOX_UNSUPPORTED_ENV,\n} from './exceptions'\nimport type { SandboxPolicy } from './types'\nimport type { SandboxEventSink } from './observability'\nimport type { SandboxPolicyEnforcer } from './contracts/policy_enforcer'\n\n/** Platform identity supplied by the construction site. */\nexport type SandboxPlatform = 'darwin' | 'linux' | 'win32' | string\n\n/** Inputs to the construction-time environment admission check. */\nexport interface PreflightOptions {\n /** Policy backend to admit. */\n readonly enforcer: SandboxPolicyEnforcer\n /** Platform override, primarily for hermetic tests. */\n readonly platform?: SandboxPlatform\n /** Explicit opt-in to run without OS containment when a pre-execution condition applies. */\n readonly allowUnsandboxedFallback?: boolean\n /** Claude Code's strict mode: per-call escape/bypass is ignored by the consumer. */\n readonly strictMode?: boolean\n /** Whether the optional SRT peer was resolved. Defaults to true for injected test enforcers. */\n readonly optionalPeerPresent?: boolean\n /** Receives dependency warnings; warnings never make admission fail. */\n readonly onSandbox?: SandboxEventSink\n /** Path redaction is performed by the observability sink, not by this admission check. */\n readonly fsNodeVersion?: string\n}\n\n/** Immutable decision retained by a sandbox handle for its entire lifetime. */\nexport interface SandboxPreflight {\n /** Whether the construction opted into fallback. */\n readonly allowUnsandboxedFallback: boolean\n /** Whether one of the permitted pre-execution conditions fired. */\n readonly fallbackFired: boolean\n /** Whether per-call bypasses must be ignored. */\n readonly strictMode: boolean\n /** Non-fatal dependency diagnostics. */\n readonly dependencyWarnings: readonly string[]\n /** Version provenance for fs_node, when supplied by the backend. */\n readonly fsNodeVersion?: string\n}\n\nconst currentPlatform = (): SandboxPlatform =>\n typeof process !== 'undefined' && typeof process.platform === 'string'\n ? process.platform\n : 'browser'\n\n/** Run the once-only, fail-closed environment gauntlet used by `createSandbox()`. */\nexport const preflightSandbox = async (options: PreflightOptions): Promise<SandboxPreflight> => {\n const platform = options.platform ?? currentPlatform()\n if (platform === 'win32') {\n throw new E_SANDBOX_UNSUPPORTED_ENV([\n 'Native Windows is not supported; run the sandbox inside a WSL2 distribution.',\n ])\n }\n\n if (!options.enforcer.isSupported()) {\n throw new E_SANDBOX_UNSUPPORTED_ENV([\n 'The browser environment has no SRT boundary; use Part B (SES) as the cross-environment layer.',\n ])\n }\n\n const dependencies = await options.enforcer.checkDependencies()\n const warnings = Object.freeze([...dependencies.warnings])\n if (dependencies.warnings.length > 0) {\n options.onSandbox?.({ kind: 'dependency-warnings', warnings })\n }\n const optionalPeerPresent = options.optionalPeerPresent ?? true\n const platformCannotSandbox = options.enforcer.effectivePolicy() === undefined\n const fallbackCondition =\n platformCannotSandbox || dependencies.errors.length > 0 || !optionalPeerPresent\n if (dependencies.errors.length > 0 && !options.allowUnsandboxedFallback) {\n throw new E_SANDBOX_DEPENDENCY_MISSING([\n `Sandbox dependencies are unavailable: ${dependencies.errors.join('; ')}`,\n ])\n }\n const fallbackFired = Boolean(options.allowUnsandboxedFallback && fallbackCondition)\n const result: SandboxPreflight = {\n allowUnsandboxedFallback: fallbackFired,\n fallbackFired,\n strictMode: Boolean(options.strictMode),\n dependencyWarnings: warnings,\n ...(options.fsNodeVersion === undefined ? {} : { fsNodeVersion: options.fsNodeVersion }),\n }\n return Object.freeze(result)\n}\n\n/** Compatibility alias for the construction-site call in WP-A1. */\nexport const runSandboxPreflight = preflightSandbox\n\n/** Probe spawning after policy admission, rather than as part of preflight. */\nexport const probeSandboxSpawn = async (\n enforcer: SandboxPolicyEnforcer,\n policy: SandboxPolicy\n): Promise<void> => {\n let result: Awaited<ReturnType<SandboxPolicyEnforcer['run']>>\n try {\n result = await enforcer.run({\n argv: ['true'],\n policy,\n correlationId: crypto.randomUUID(),\n cwd: process.cwd(),\n })\n } catch (error) {\n // Preserve policy and lifecycle classifications; only an untyped spawn failure is treated as\n // the dependency/liveness failure this opt-in probe is designed to detect.\n if (isException(error) && error.name.startsWith('E_SANDBOX_')) throw error\n throw new E_SANDBOX_DEPENDENCY_MISSING([`Sandbox spawn probe failed: ${String(error)}`])\n }\n const drain = async (stream: ReadableStream<Uint8Array>): Promise<string> => {\n const reader = stream.getReader()\n const chunks: Uint8Array[] = []\n try {\n for (;;) {\n const next = await reader.read()\n if (next.done) break\n chunks.push(next.value)\n }\n } finally {\n reader.releaseLock()\n }\n const bytes = new Uint8Array(chunks.reduce((size, chunk) => size + chunk.length, 0))\n let offset = 0\n for (const chunk of chunks) {\n bytes.set(chunk, offset)\n offset += chunk.length\n }\n return new TextDecoder().decode(bytes)\n }\n let stderr: string\n let completed: Awaited<ReturnType<SandboxPolicyEnforcer['run']>>['completed'] extends Promise<\n infer T\n >\n ? T\n : never\n try {\n ;[, stderr, completed] = await Promise.all([\n drain(result.stdout),\n drain(result.stderr),\n result.completed,\n ])\n } catch (error) {\n if (isException(error) && error.name.startsWith('E_SANDBOX_')) throw error\n throw new E_SANDBOX_DEPENDENCY_MISSING([\n `Sandbox spawn probe failed while draining output: ${String(error)}`,\n ])\n }\n if (completed.failed)\n throw new E_SANDBOX_FAILED([\n `Sandbox spawn probe failed (exit code ${completed.exitCode}): ${stderr || 'no stderr'}`,\n ])\n}\n","/**\n * The single sandbox observability firehose.\n *\n * WP-A1 wires the callbacks from `createSandbox()` to `createSandboxObservability()`;\n * it must not emit parallel ad-hoc events. Every path-bearing field is redacted here,\n * before it reaches an operator, logger, or audit sink.\n */\nimport type { PathTranslator } from './contracts/path_translator'\n\n/** Typed records emitted by the sandbox's single audit firehose. */\nexport type SandboxEvent =\n | {\n readonly kind: 'bypass'\n readonly command: string\n readonly path?: string\n readonly loud: true\n }\n | {\n readonly kind: 'unsandboxed-fallback'\n readonly handleId: string\n readonly reason: string\n readonly path?: string\n readonly loud: true\n }\n | {\n readonly kind: 'drift-check'\n readonly outcome: 'passed' | 'failed' | 'skipped'\n readonly reason?: string\n readonly path?: string\n /** `skipped` is specifically the network-domain comparison, not adoption. */\n readonly comparison?: 'network-domains'\n }\n | {\n readonly kind: 'fs-node-version'\n readonly version: string\n }\n | { readonly kind: 'dependency-warnings'; readonly warnings: readonly string[] }\n\n/** Consumer callback for sandbox audit events. */\nexport type SandboxEventSink = (event: SandboxEvent) => void\n\n/** Dependencies used to create the redacting firehose. */\nexport interface SandboxObservabilityOptions {\n /** Translator used for every path-bearing event field. */\n readonly pathTranslator: PathTranslator\n /** Destination for already-redacted events. */\n readonly sink: SandboxEventSink\n}\n\nconst redactEvent = (event: SandboxEvent, translator: PathTranslator): SandboxEvent => {\n if (event.kind === 'bypass') {\n return Object.freeze({\n ...event,\n command: translator.redact(event.command),\n ...(event.path === undefined ? {} : { path: translator.redact(event.path) }),\n })\n }\n if (event.kind === 'unsandboxed-fallback') {\n return Object.freeze({\n ...event,\n handleId: translator.redact(event.handleId),\n reason: translator.redact(event.reason),\n ...(event.path === undefined ? {} : { path: translator.redact(event.path) }),\n })\n }\n if (event.kind === 'drift-check') {\n return Object.freeze({\n ...event,\n ...(event.reason === undefined ? {} : { reason: translator.redact(event.reason) }),\n ...(event.path === undefined ? {} : { path: translator.redact(event.path) }),\n })\n }\n if (event.kind === 'dependency-warnings') {\n return Object.freeze({\n ...event,\n warnings: Object.freeze(event.warnings.map((warning) => translator.redact(warning))),\n })\n }\n return Object.freeze(event)\n}\n\n/** Build the one event surface consumed by WP-A1's sandbox handle. */\nexport const createSandboxObservability = (\n options: SandboxObservabilityOptions\n): SandboxEventSink => {\n return (event) => options.sink(redactEvent(event, options.pathTranslator))\n}\n\n/** Emit a loud audit-only bypass report. */\nexport const emitBypass = (sink: SandboxEventSink, command: string, path?: string): void => {\n sink({ kind: 'bypass', command, ...(path === undefined ? {} : { path }), loud: true })\n}\n\n/** Emit the permanent loud report for an unsandboxed invocation. */\nexport const emitFallback = (\n sink: SandboxEventSink,\n handleId: string,\n reason: string,\n path?: string\n): void => {\n sink({\n kind: 'unsandboxed-fallback',\n handleId,\n reason,\n ...(path === undefined ? {} : { path }),\n loud: true,\n })\n}\n\n/** Emit a drift result, including an explicit network-domain skip when requested. */\nexport const emitDriftCheck = (\n sink: SandboxEventSink,\n outcome: 'passed' | 'failed' | 'skipped',\n details?: {\n readonly reason?: string\n readonly path?: string\n readonly networkDomainsSkipped?: boolean\n }\n): void => {\n sink({\n kind: 'drift-check',\n outcome,\n ...(details?.reason === undefined ? {} : { reason: details.reason }),\n ...(details?.path === undefined ? {} : { path: details.path }),\n ...(details?.networkDomainsSkipped ? { comparison: 'network-domains' as const } : {}),\n })\n}\n\n/** Emit the SRT version used by the in-process evaluator. */\nexport const emitFsNodeVersion = (sink: SandboxEventSink, version: string): void => {\n sink({ kind: 'fs-node-version', version })\n}\n","import { createSandboxEpoch } from './types'\nimport { probeSandboxSpawn, runSandboxPreflight } from './preflight'\nimport { createSandboxObservability, emitDriftCheck, emitFallback } from './observability'\nimport {\n E_SANDBOX_NOT_INITIALIZED,\n E_SANDBOX_POLICY_CONFLICT,\n E_SANDBOX_NARROWING_UNSUPPORTED,\n} from './exceptions'\nimport type { PathTranslator } from './contracts/path_translator'\nimport type { SandboxPolicy, DerivedRules, SandboxEpoch } from './types'\nimport type { SandboxPolicyEnforcer } from './contracts/policy_enforcer'\n\ntype RunOptions = Parameters<SandboxPolicyEnforcer['run']>[0]\n/**\n * A live sandbox session: the object every sandbox tool is built against.\n *\n * @remarks\n * THIS IS A PROCESS-GLOBAL CAPABILITY WEARING A PER-HANDLE API, and the shape is a promise narrowed\n * rather than a promise kept. `SandboxManager` is a singleton, so the first `createSandbox()` in a\n * process establishes the policy and a later one may only NARROW it — a request that is not a subset\n * throws `E_SANDBOX_POLICY_CONFLICT` naming both. One policy per process is the safe deployment;\n * multi-tenant agents with different policies want separate processes.\n *\n * Every `run()` re-validates against the admission baseline before spawning, so a widening of the live\n * policy is DETECTED. Detection is not prevention: SRT's proxies consult policy per request, so a\n * widening already affects an in-flight child for its whole lifetime.\n */\nexport interface SandboxHandle {\n /**\n * Opaque token issued at construction and invalidated by {@link SandboxHandle.dispose}.\n *\n * @remarks\n * File-backed readers hold this rather than a filesystem reference, which is what makes disposal\n * deterministic: a staged reader outliving its TURN is legitimate, outliving its HANDLE is not.\n */\n readonly epoch: SandboxEpoch\n /**\n * The live DERIVED rules — not the `SandboxPolicy` that was requested.\n *\n * @remarks\n * A policy cannot express what the drift check has to compare (`denyOnly`/`allowWithinDeny`, the\n * unioned default write paths, Linux-expanded read globs, the profile-only mandatory denies), so\n * returning one here would compare the wrong thing and pass while the live sandbox had widened.\n * Under ADOPTION this re-derives from the live manager on every call; an owned session is cached.\n */\n readonly effectivePolicy: () => DerivedRules | undefined\n /**\n * Spawn under this session's policy, optionally narrowed for the single invocation.\n *\n * @remarks\n * Resolves as soon as the child is SPAWNED, handing back live `stdout`/`stderr` streams plus a\n * separate `completed` promise. Drain BOTH concurrently: pipe buffers are per-fd, so draining one to\n * completion first can block the other and hang the child. A non-zero exit is data on `completed`,\n * never a rejection.\n *\n * `options.policy` is a PER-INVOCATION policy. Its effect is backend-specific and, under the SRT\n * enforcer, axis-specific (measured on macOS/seatbelt AND Linux/bwrap, issue #50, both identical): a\n * per-call FILESYSTEM grant is honoured for that ONE child, REPLACING the session baseline rather\n * than unioning with it — the per-call policy is that child's complete filesystem policy, so it must\n * repeat any baseline writes it still wants. A per-call NETWORK section that DIFFERS from the\n * session's — a new domain, a narrowing, an added deny, a different `disabled` — is REFUSED with\n * `E_SANDBOX_NETWORK_GRANT_UNSUPPORTED` (SRT's proxy filters every request against the\n * process-global session config, so neither a per-call grant NOR a per-call narrowing is\n * representable), so network policy is established for the session; a per-call policy must repeat\n * the session's network section exactly (order-insensitive set equality). See\n * [per-call policy semantics](/batteries/sandbox/index#per-call-policy-semantics-under-srt).\n */\n run(options: RunOptions): ReturnType<SandboxPolicyEnforcer['run']>\n /**\n * Narrow the session policy for subsequent operations.\n *\n * @param policy - Must be a subset per the per-axis rules; reads are deny-then-allow while writes\n * are allow-only, so \"narrower\" is not symmetric. Throws\n * `E_SANDBOX_NARROWING_UNSUPPORTED` naming the axis where the platform cannot narrow it.\n */\n narrow(policy: SandboxPolicy): Promise<void>\n /** Predicate consumed by file-backed readers; disposal makes the epoch unusable. */\n isEpochLive(epoch: SandboxEpoch): boolean\n /**\n * Quiesce the session: it does not abandon in-flight work.\n *\n * @remarks\n * Rejects new work with `E_SANDBOX_NOT_INITIALIZED`, aborts in-flight invocations through their\n * signals, kills spawned children, then releases the enforcer. On an ADOPTED session this is a\n * reported NO-OP — resetting a manager we did not create would strip ACEs a host application\n * depends on.\n */\n dispose(): Promise<void>\n}\n\n/** Options for {@link createSandbox}. */\nexport interface CreateSandboxOptions {\n /**\n * ADK-owned policy vocabulary, mapped to the backend's config inside the enforcer.\n *\n * @remarks\n * The per-axis defaults DIFFER and are not a symmetry worth \"fixing\": reads default to ALLOW\n * (absent `denyRead` means everything is readable, and `allowRead` re-permits WITHIN a deny), while\n * writes default to DENY and network is an allow-list. A checker that unified them would disagree\n * with the OS by construction.\n */\n readonly policy: SandboxPolicy\n /** The boundary itself. Node's SRT-backed enforcer lives on the `sandbox/node` subpath. */\n readonly enforcer: SandboxPolicyEnforcer\n /**\n * Model-path translation, and the redaction used on every observability event.\n *\n * @remarks\n * Supply it if you want host identifiers scrubbed from the event stream — no battery-generated\n * surface should carry the sandbox root, home directory, or user name.\n */\n readonly translator?: PathTranslator\n /** Observability firehose: bypasses, fallbacks, drift outcomes, and the SRT version rules came from. */\n readonly onSandbox?: (event: Parameters<ReturnType<typeof createSandboxObservability>>[0]) => void\n /**\n * Permit degraded operation when the environment cannot provide OS containment.\n *\n * @remarks\n * Fires only for pre-execution conditions resolved once at construction — a platform the backend\n * cannot sandbox that we still run on, dependency errors, or an absent optional peer. It NEVER fires\n * for a violation (a violation means the sandbox worked), and native Windows is refused outright\n * rather than degraded. When it fires the handle is permanently marked and every invocation emits\n * a loud observability event. Execution STILL goes through `enforcer.run`; this option never runs\n * a command unsandboxed, and the tool descriptions tell the model it has no OS containment.\n */\n readonly allowUnsandboxedFallback?: boolean\n /** Ignore the per-call escape entirely, matching the reference consumer's strict mode. */\n readonly strictMode?: boolean\n /** Whether the optional peer resolved; feeds the preflight decision above. */\n readonly optionalPeerPresent?: boolean\n /** Recorded on observability events so a rules-versus-backend mismatch is diagnosable without a bisect. */\n readonly fsNodeVersion?: string\n /** Opt in to a real child-spawn liveness check during construction. */\n readonly probeSpawn?: boolean\n}\n\nlet owner: { baseline: DerivedRules; enforcer: SandboxPolicyEnforcer; owned: boolean } | undefined\nlet establishment: Promise<void> = Promise.resolve()\nlet disposalRequested = 0\nconst acquireEstablishment = async (): Promise<() => void> => {\n const previous = establishment\n let release!: () => void\n establishment = new Promise<void>((resolve) => {\n release = resolve\n })\n await previous\n return release\n}\n\nconst list = (value: readonly string[] | undefined): readonly string[] => value ?? []\nconst json = (value: unknown): string => JSON.stringify(value)\n\n/**\n * Conservative list inclusion. Globs which are not lexically identical are deliberately\n * undecidable and therefore fail closed. This is a sufficient test, not a complete relation.\n */\nconst subset = (small: readonly string[], large: readonly string[]): boolean =>\n small.every((item) => large.includes(item))\nconst same = (a: unknown, b: unknown): boolean => json(a) === json(b)\n\n/** Compare a requested (admission) derived policy with the live one: requested ⊆ live. */\nconst admission = (ours: DerivedRules, live: DerivedRules): boolean => {\n if (!same(ours.matcher, live.matcher) || !same(ours.mandatoryDeny, live.mandatoryDeny))\n return false\n if (ours.filesystemDisabled && !live.filesystemDisabled) return false\n if (!ours.filesystemDisabled && live.filesystemDisabled) {\n // A kill switch is widening, and is consequently safe for admission.\n }\n return (\n subset(live.read.denyOnly, ours.read.denyOnly) &&\n subset(ours.read.allowWithinDeny, live.read.allowWithinDeny) &&\n subset(ours.write.allowOnly, live.write.allowOnly) &&\n subset(live.write.denyWithinAllow, ours.write.denyWithinAllow) &&\n subset(ours.network.allowedDomains, live.network.allowedDomains) &&\n subset(live.network.deniedDomains, ours.network.deniedDomains)\n )\n}\n\n/** Compare a live snapshot with the admission baseline: widening is drift. */\nconst drift = (baseline: DerivedRules, live: DerivedRules): string | undefined => {\n if (!same(baseline.matcher, live.matcher)) return 'matcher changed'\n if (!same(baseline.mandatoryDeny, live.mandatoryDeny)) return 'mandatory deny inputs changed'\n if (!baseline.filesystemDisabled && live.filesystemDisabled) return 'filesystem.disabled widened'\n if (baseline.filesystemDisabled && !live.filesystemDisabled) {\n // Narrowing is explicitly allowed.\n }\n if (live.unknownKeys.length > 0) return `unknown live config keys: ${live.unknownKeys.join(', ')}`\n if (live.undecidableGlobs.length > 0)\n return `uncompilable live globs: ${live.undecidableGlobs.join(', ')}`\n if (!subset(live.read.denyOnly, baseline.read.denyOnly)) return 'read deny rules widened'\n if (!subset(live.read.allowWithinDeny, baseline.read.allowWithinDeny))\n return 'read allow rules widened'\n if (!subset(live.write.allowOnly, baseline.write.allowOnly)) return 'write allow rules widened'\n if (!subset(live.write.denyWithinAllow, baseline.write.denyWithinAllow))\n return 'write deny rules widened'\n if (baseline.network.disabled) {\n // Disabled means unrestricted, which cannot be represented by a domain list.\n } else {\n if (live.network.disabled) return 'network.disabled widened'\n if (!subset(live.network.allowedDomains, baseline.network.allowedDomains))\n return 'allowed domains widened'\n if (!subset(baseline.network.deniedDomains, live.network.deniedDomains))\n return 'denied domains widened'\n }\n if (baseline.network.strictAllowlist !== live.network.strictAllowlist)\n return 'strictAllowlist changed'\n return undefined\n}\n\nconst policyEffect = (policy: SandboxPolicy, template: DerivedRules): DerivedRules => ({\n ...template,\n filesystemDisabled: Boolean(policy.filesystem.disabled),\n read: {\n denyOnly: [...list(policy.filesystem.denyRead)],\n allowWithinDeny: [...list(policy.filesystem.allowRead)],\n },\n write: {\n allowOnly: [...list(policy.filesystem.allowWrite)],\n denyWithinAllow: [...list(policy.filesystem.denyWrite)],\n },\n network: {\n ...template.network,\n disabled: Boolean(policy.network.disabled),\n allowedDomains: policy.network.disabled ? ['*'] : [...list(policy.network.allowedDomains)],\n deniedDomains: policy.network.disabled ? [] : [...list(policy.network.deniedDomains)],\n },\n})\n\n/**\n * Admit one process-global sandbox. Drift is detection, not prevention: SRT consults its\n * proxies per request, so a widening can affect an already-spawned child for its lifetime.\n */\nexport const createSandbox = async (options: CreateSandboxOptions): Promise<SandboxHandle> => {\n const sink =\n options.onSandbox && options.translator\n ? createSandboxObservability({ pathTranslator: options.translator, sink: options.onSandbox })\n : (options.onSandbox ?? (() => undefined))\n const release = await acquireEstablishment()\n let assignedOwner: typeof owner\n try {\n const preflight = await runSandboxPreflight({\n enforcer: options.enforcer,\n allowUnsandboxedFallback: options.allowUnsandboxedFallback,\n strictMode: options.strictMode,\n optionalPeerPresent: options.optionalPeerPresent,\n fsNodeVersion: options.fsNodeVersion,\n onSandbox: sink,\n })\n const live = options.enforcer.effectivePolicy()\n if (!live) throw new E_SANDBOX_POLICY_CONFLICT(['Sandbox has no derived policy'])\n // An adopted enforcer has no ADK policy provenance, so admission must compare the requested\n // effect against its genuinely live foreign baseline. Owned sessions retain the established\n // first-writer baseline for subsequent handles.\n const adopted = options.enforcer.adopted === true\n const firstHandle = owner === undefined\n if (owner !== undefined) {\n const admissionBaseline = adopted ? live : owner.baseline\n const requested = policyEffect(options.policy, admissionBaseline)\n if (!admission(requested, admissionBaseline)) {\n throw new E_SANDBOX_POLICY_CONFLICT([\n `requested policy ${json(options.policy)} conflicts with ${json(admissionBaseline)}`,\n ])\n }\n } else {\n // Adoption has no caller policy to compare against until this point; rule 3b compares the\n // requested effect with the foreign live baseline before admitting the first handle.\n if (adopted && !admission(policyEffect(options.policy, live), live))\n throw new E_SANDBOX_POLICY_CONFLICT([\n `requested policy ${json(options.policy)} conflicts with ${json(live)}`,\n ])\n owner = { baseline: live, enforcer: options.enforcer, owned: !adopted }\n assignedOwner = owner\n }\n const admittedOwner = owner\n if (!admittedOwner) throw new E_SANDBOX_NOT_INITIALIZED(['Sandbox owner was not established'])\n if (options.probeSpawn) {\n // Probe only after admission: preflight runs before admission and could exercise a rejected policy.\n // Probe failures fail closed; manager.ts:272 calls enforcer.run() unconditionally, so\n // allowUnsandboxedFallback cannot provide an unsandboxed alternative here.\n await probeSandboxSpawn(admittedOwner.enforcer, options.policy)\n }\n if (owner !== admittedOwner)\n throw new E_SANDBOX_NOT_INITIALIZED(['Sandbox owner changed during construction'])\n // A disposal requested while this construction was probing must invalidate construction rather\n // than return a handle that the queued disposal would immediately reset.\n if (disposalRequested > 0)\n throw new E_SANDBOX_NOT_INITIALIZED(['Sandbox disposal was requested during construction'])\n const baseline = admittedOwner.baseline\n const epoch = createSandboxEpoch()\n let disposed = false\n const controllers = new Set<AbortController>()\n const check = (): void => {\n if (disposed) throw new E_SANDBOX_NOT_INITIALIZED(['Sandbox handle has been disposed'])\n const current = owner?.enforcer.effectivePolicy()\n if (!current) throw new E_SANDBOX_NOT_INITIALIZED(['Sandbox policy is unavailable'])\n const reason = drift(baseline, current)\n if (reason) {\n emitDriftCheck(sink, 'failed', { reason })\n throw new E_SANDBOX_POLICY_CONFLICT([`sandbox drift detected: ${reason}`])\n }\n if (baseline.network.disabled)\n emitDriftCheck(sink, 'skipped', { networkDomainsSkipped: true })\n else emitDriftCheck(sink, 'passed')\n }\n const handle: SandboxHandle = {\n epoch,\n effectivePolicy: () => owner?.enforcer.effectivePolicy(),\n run: async (runOptions) => {\n check()\n // The manager owns this controller so disposal cancels every in-flight invocation. The\n // enforcer contract requires that cancellation terminate the corresponding child and settle\n // its `completed` promise; the caller's signal is mirrored into this lifecycle signal.\n const controller = new AbortController()\n controllers.add(controller)\n const signal = runOptions.signal\n let callerAbortListener: (() => void) | undefined\n const cleanup = (): void => {\n if (signal && callerAbortListener) {\n signal.removeEventListener('abort', callerAbortListener)\n callerAbortListener = undefined\n }\n controllers.delete(controller)\n }\n if (signal) {\n if (signal.aborted) controller.abort(signal.reason)\n else {\n callerAbortListener = () => controller.abort(signal.reason)\n signal.addEventListener('abort', callerAbortListener, { once: true })\n }\n }\n let result: ReturnType<SandboxPolicyEnforcer['run']>\n try {\n result = owner!.enforcer.run({ ...runOptions, signal: controller.signal })\n } catch (error) {\n cleanup()\n throw error\n }\n // `run` resolves after spawn, while `completed` settles after exit. Keep this controller\n // registered until completion so disposal can still cancel a live child.\n void result.then(({ completed }) => completed.then(cleanup, cleanup), cleanup)\n if (preflight.fallbackFired) emitFallback(sink, 'sandbox', 'unsandboxed fallback')\n return result\n },\n narrow: async (policy) => {\n check()\n const candidate = options.enforcer as SandboxPolicyEnforcer & {\n narrow?: (requested: SandboxPolicy) => Promise<void>\n }\n if (typeof candidate.narrow !== 'function')\n throw new E_SANDBOX_NARROWING_UNSUPPORTED(['filesystem/network'])\n await candidate.narrow(policy)\n },\n isEpochLive: (candidate) => !disposed && candidate === epoch,\n dispose: async () => {\n if (disposed) return\n disposed = true\n // Mark synchronously, before waiting for the establishment queue, so a pending probe can\n // fail with a lifecycle error instead of returning a handle that this disposal resets.\n if (firstHandle) disposalRequested += 1\n const releaseDispose = await acquireEstablishment()\n try {\n for (const controller of controllers) controller.abort()\n controllers.clear()\n if (firstHandle) {\n if (!adopted) await options.enforcer.dispose()\n if (owner?.enforcer === options.enforcer) owner = undefined\n }\n } finally {\n if (firstHandle) disposalRequested -= 1\n releaseDispose()\n }\n },\n }\n release()\n return handle\n } catch (error) {\n try {\n if (assignedOwner && owner === assignedOwner) {\n owner = undefined\n // Roll back the backend session as well as the manager record. Calling the enforcer\n // directly avoids re-entering the establishment queue held by this construction.\n if (assignedOwner.owned) await options.enforcer.dispose()\n }\n } finally {\n release()\n }\n throw error\n }\n}\n","import { quoteShellArgs } from './escape'\nimport { emitBypass, type SandboxEventSink } from './observability'\nimport type { BinaryExecutor, BinaryInvocation } from '../media/contracts'\n\n/**\n * A small command-wrapper seam used by {@link sandboxedExecutor}. The wrapper returns the\n * invocation that the inner executor should receive; it must not execute the command itself.\n */\n/** Command wrapping contract used by the executor adapter. */\nexport interface BinarySandbox {\n /** Wrap an invocation without executing it. */\n wrap(\n invocation: BinaryInvocation & { command: string }\n ): Promise<BinaryInvocation & { command: string }>\n}\n\n/** Configuration for the sandboxed binary executor. */\nexport interface SandboxedExecutorOptions {\n /** Command wrapper used for non-bypassed invocations. */\n readonly sandbox: BinarySandbox\n /** Underlying executor receiving the wrapped invocation. */\n readonly inner: BinaryExecutor\n /** Command-only opt-out. This is deliberately never passed argv to the predicate. */\n readonly bypass?: (cmd: string) => boolean\n /** Loud audit sink; bypass is observability, not enforcement. */\n readonly onSandbox?: SandboxEventSink\n}\n\n/**\n * Adapt a {@link BinaryExecutor} to a command sandbox. This WRAPS `inner.exec()` and DOES NOT\n * STREAM: the shipped BinaryExecutor contract returns settled strings. Consequently an execa\n * inner executor retains its output and inherits execa's bounded `maxBuffer` behaviour; this\n * adapter does not raise that bound (and never sets `maxBuffer: Infinity`). The streaming path is\n * {@link createRunShellCommandTool}, which uses the policy-enforcer stream contract instead.\n *\n * Bypass is an audit-only opt-out. Its predicate receives `cmd` only, never argv: callers must\n * allow only binaries safe with hostile arguments and must never allow an interpreter. Non-zero\n * exits remain data and are never thrown. Removing this wrapper call restores the inner executor.\n */\n/** Create a BinaryExecutor that wraps invocations unless an explicitly audited bypass applies. */\nexport const sandboxedExecutor = (options: SandboxedExecutorOptions): BinaryExecutor => ({\n async exec(invocation) {\n if (options.bypass?.(invocation.cmd)) {\n options.onSandbox?.({ kind: 'bypass', command: invocation.cmd, loud: true })\n return options.inner.exec(invocation)\n }\n const command = await quoteShellArgs([invocation.cmd, ...invocation.args])\n const wrapped = await options.sandbox.wrap({ ...invocation, command })\n return options.inner.exec({ ...wrapped, cmd: wrapped.command })\n },\n})\n\n/** Emit a bypass through the canonical sink for consumers that do not retain the adapter. */\nexport const reportSandboxBypass = (sink: SandboxEventSink, command: string): void =>\n emitBypass(sink, command)\n","import { Tool } from '@nhtio/adk/forge'\nimport { validator } from '@nhtio/validation'\nimport { classifySandboxPathRejection } from './paths'\nimport { isError, isInstanceOf } from '@nhtio/adk/guards'\nimport { SpooledArtifact } from '@nhtio/adk/spooled_artifact'\nimport { runToolGate, type ToolGateFn } from '../tools/_shared'\nimport { E_TURN_GATE_ABORTED } from '../../lib/exceptions/runtime'\nimport { defaultSandboxNarrator, type SandboxNarrator, type SandboxOutcome } from './narrator'\nimport {\n E_SANDBOX_GATE_REQUIRED,\n E_SANDBOX_REFUSED,\n E_SANDBOX_FAILED,\n E_SANDBOX_NETWORK_GRANT_UNSUPPORTED,\n} from './exceptions'\nimport type { SandboxPolicy } from './types'\nimport type { PathTranslator } from './contracts/path_translator'\nimport type { SandboxPolicyEnforcer } from './contracts/policy_enforcer'\n\n/**\n * What one `run_shell_command` invocation actually did.\n *\n * @remarks\n * The structured completion for {@link createRunShellCommandTool}'s `onCompletion` callback.\n * Deliberately issued once per invocation, on EVERY terminal outcome — a clean exit, a non-zero\n * exit, a timeout, a kill, a gate/approval denial, and an enforcer throw all settle this — because\n * the audit seam exists precisely so a denied or killed command is not indistinguishable from a\n * successful one.\n *\n * Field rules:\n * - `exitCode` is the child's real exit status, or `null` when the command never ran (a gate\n * denial, a path refusal, a spawn failure) or its exit status is unknowable.\n * - `failed` is `true` for every outcome that is not a successful zero exit, INCLUDING denials,\n * timeouts, killed children, enforcer errors, and a per-call `policy` function that failed.\n * `exitCode !== 0` implies `failed`, and so do outcomes with `exitCode: null`.\n * - `timedOut` marks the `timeout_seconds` deadline firing (`exitCode` is then `null` or the killed\n * child's status, depending on whether `completed` settled).\n * - `killedBy` names the signal that ACTUALLY terminated the child instead of letting it exit,\n * read from the real child settlement (Node's `signalCode`), e.g. `'SIGKILL'` when the enforcer\n * kills the process group on a timeout. Absent when the child exited on its own (a clean exit, a\n * non-zero exit, or a timeout it won by exiting before the kill landed).\n * - `denied` marks a refusal BEFORE the command ran (a gate denial, a path/gate/allow-list\n * refusal) — no child was spawned.\n * - `diagnostics` carries everything the enforcer reported (`diagnosticsFor`, the `[sandbox]\n * denied: …` lines) plus, for a handler failure, the thrown value's message — including a per-call\n * `policy` function that threw or rejected, which fires this completion before the error surfaces.\n * Empty usually.\n * - `artifactRef` names the returned {@link SpooledArtifact}'s correlation id — the same id the\n * spool store keyed the stream under — so an audit sink can join the completion to the artifact.\n * It is present whenever the run reached the enforcer, including an enforcer throw (its id still\n * keys any diagnostics recorded for that run). It is absent for the very first refusals (those\n * throw before any stream exists) and a throwing per-call `policy` (it fails before a stream is\n * opened).\n *\n * The tool's own return type is UNCHANGED: it still resolves to the artifact. This type travels\n * only through the callback, so existing consumers keep compiling.\n */\nexport interface RunShellCommandCompletion {\n /** The child's real exit status; `null` when the command never ran or never reported one. */\n readonly exitCode: number | null\n /** `true` for every non-success outcome, including denials, timeouts, kills, and enforcer throws. */\n readonly failed: boolean\n /** Whether the `timeout_seconds` deadline fired and terminated the command. */\n readonly timedOut: boolean\n /** The signal that actually killed the child instead of letting it exit, when one did, e.g. `'SIGKILL'`. */\n readonly killedBy?: string\n /** Whether the command was refused before spawning (gate denial, path refusal, allow-list). */\n readonly denied?: boolean\n /** Enforcer diagnostics (`[sandbox] denied: …` lines) and, on a handler failure, its message. */\n readonly diagnostics: readonly string[]\n /** The spool store correlation id backing the invocation's returned artifact, when one exists. */\n readonly artifactRef?: string\n}\n\n/** Consumer-supplied completion observer; errors it throws are contained, never propagated. */\nexport type RunShellCommandCompletionFn = (completion: RunShellCommandCompletion) => void\n\n/** The per-call context handed to a {@link RunShellCommandPolicyFn}. */\nexport interface RunShellCommandPolicyContext {\n /** The validated tool arguments (`command`, `cwd`, `timeout_seconds`) for this call. */\n readonly args: { command: string; cwd: string; timeout_seconds: number }\n /** The resolved workspace-relative `cwd` this call will run under. */\n readonly relativeCwd: string\n}\n\n/**\n * A policy resolved PER CALL rather than captured at construction.\n *\n * @remarks\n * Evaluated once per invocation, AFTER the gate has approved and AFTER `cwd` has passed the path\n * gauntlet, and its return value is passed to `enforcer.run` for that one child only — a policy\n * object captured at construction would keep a revoked grant alive forever. A per-call policy must\n * hand the ENFORCER a fresh object per call (`{ ...basePolicy }` at minimum): the enforcer stores\n * what it is handed, so a shared mutable object collapses concurrent runs back into one shared\n * policy.\n *\n * There is NO gate decision in the context. `ToolGateFn` approves with `void` and denies by\n * THROWING, and a thrown denial returns before this callback runs — so at the moment a policy is\n * resolved there is no approval artefact to hand over, and a denied call never reaches here.\n */\nexport type RunShellCommandPolicyFn = (\n context: RunShellCommandPolicyContext\n) => SandboxPolicy | Promise<SandboxPolicy>\n\n/** Configuration for the streaming shell-command tool. */\nexport interface RunShellCommandOptions {\n /** Streaming policy enforcer; unlike BinaryExecutor this exposes live stdout/stderr. */\n readonly sandbox: SandboxPolicyEnforcer\n /**\n * Policy applied to the spawned command: a static object for every call, or a per-call function.\n *\n * @remarks\n * A function is evaluated once per invocation, AFTER the gate has approved and after `cwd` has\n * passed the path gauntlet, and receives the call context (the validated tool args and the\n * resolved workspace-relative `cwd`). Its return is the policy for that ONE child — see\n * {@link RunShellCommandPolicyFn} for the fresh-object rule under concurrency.\n */\n readonly policy: SandboxPolicy | RunShellCommandPolicyFn\n /** Model-path translator for the working directory. */\n readonly translator: PathTranslator\n /** Required human/policy approval gate. */\n readonly gate?: ToolGateFn\n /**\n * Optional command-name allow-list; restricts the line to a single plain command.\n * Operators, pipes, redirection, grouping, backticks, all `$` expansion, and backslashes\n * are refused even inside quotes. The first word must be unquoted; argument quotes are allowed.\n * This is a name check, not a security boundary: the sandbox policy remains the boundary.\n */\n readonly allowedCommands?: readonly string[]\n /**\n * Environment variables to add to every command this tool spawns.\n *\n * @remarks\n * ADDITIVE, and applied LAST — over both the host variables the enforcer allow-listed and SRT's own\n * proxy/CA plumbing. It is not the host-inheritance control: the enforcer decides what the child\n * inherits (`envAllowList` / `inheritHostEnv` on the Node adapter), and this cannot re-admit a\n * variable the enforcer withheld except by supplying the value literally here.\n *\n * Anything put here is readable by the model — `run_shell_command` runs commands the model chose,\n * and `env` is one of them — so pass configuration, not credentials.\n */\n readonly env?: Readonly<Record<string, string>>\n /** Optional tool description override. */\n readonly description?: string\n /**\n * Called exactly once per invocation with the structured completion, on EVERY terminal outcome.\n *\n * @remarks\n * Success, non-zero exit, timeout, kill/signal, gate/approval denial, and an enforcer throw all\n * settle this once — see {@link RunShellCommandCompletion} for the field rules. A callback that\n * throws is logged and swallowed: it must never break the tool call or surface as an unhandled\n * rejection (the issue-#39 bug class).\n */\n readonly onCompletion?: RunShellCommandCompletionFn\n /** Injectable model-facing outcome renderer. */\n readonly narrate?: SandboxNarrator\n}\n\nconst encoder = new TextEncoder()\nconst line = (value: string): Uint8Array => encoder.encode(`${value}\\n`)\n\n/**\n * Assemble the factory-style `run_shell_command` tool. It is intentionally not a bulk-registered\n * battery value. `cwd` is a model-supplied workspace-relative path and receives the complete\n * PathTranslator gauntlet, including symlink refusal; the default is the workspace root.\n *\n * The command spawns first, then stdout and stderr are drained concurrently and merged in arrival\n * order into one stream and one `storeRetrievableBytes` call. Diagnostics are polled while drains\n * run and written as `[sandbox] denied: …` at their observation point (\"observed after\", not\n * \"caused by\"). The command is never accumulated here. `timeout_seconds` defaults to 300 and is\n * a tool argument. Non-zero exits, violations, timeouts, and post-spawn I/O failures return the\n * singular artifact; failures meaning the command never ran throw instead.\n */\nexport const createRunShellCommandTool = (options: RunShellCommandOptions): Tool => {\n if (!options.gate) throw new E_SANDBOX_GATE_REQUIRED(['run_shell_command requires a gate'])\n const inputSchema = validator.object({\n command: validator.string().required().description('Shell command to execute.'),\n cwd: validator\n .string()\n .default('')\n .allow('')\n .description('Workspace-relative working directory; defaults to the workspace root.'),\n timeout_seconds: validator\n .number()\n .min(1)\n .default(300)\n .description('Command timeout in seconds; defaults to 300. Raise it for slow commands.'),\n })\n return new Tool({\n name: 'run_shell_command',\n description:\n options.description ??\n 'Run a shell command under the sandbox. Output is one interleaved artifact; sandbox denials appear inline. cwd is workspace-relative and timeout_seconds defaults to 300.',\n inputSchema,\n trusted: false,\n handler: async (raw, ctx) => {\n const args = raw as {\n command: string\n cwd: string\n timeout_seconds: number\n }\n const narrate = options.narrate ?? defaultSandboxNarrator\n // Emitted EXACTLY ONCE per invocation, on every terminal outcome. The denied/pre-spawn and\n // enforcer-throw paths deliberately fire it too: this seam exists so those outcomes are\n // structured data instead of \"no artifact arrived\". A throwing observer is contained — its\n // failure must not replace the refusal/exception the caller is already receiving, and a raw\n // rejection escaping into the dispatch core is the issue-#39 bug class.\n let completionDone = false\n const emitCompletion = async (completion: RunShellCommandCompletion): Promise<void> => {\n if (completionDone) return\n completionDone = true\n if (!options.onCompletion) return\n try {\n await options.onCompletion(completion)\n } catch (error) {\n // Swallowed by design (see the option's docblock). `String` can itself throw, so the\n // message is assembled defensively.\n let detail: string\n try {\n detail = isError(error) ? error.message : String(error)\n } catch {\n detail = '<uncoercible>'\n }\n console.error(`[run_shell_command] onCompletion threw and was ignored: ${detail}`)\n }\n }\n const currentDiagnostics = (correlationId?: string): readonly string[] =>\n correlationId === undefined ? [] : [...options.sandbox.diagnosticsFor(correlationId)]\n try {\n await runToolGate(options.gate, ctx, 'run_shell_command', args)\n } catch (error) {\n if (isInstanceOf(error, 'E_TURN_GATE_ABORTED', E_TURN_GATE_ABORTED)) {\n if (ctx.abortSignal.aborted) throw error\n throw new E_SANDBOX_FAILED([narrate({ kind: 'aborted' })])\n }\n const outcome =\n (error as { outcome?: SandboxOutcome; kind?: string }).outcome ??\n ((error as { kind?: string }).kind === 'gate-declined'\n ? ({ kind: 'gate-declined' } satisfies SandboxOutcome)\n : undefined)\n await emitCompletion({\n exitCode: null,\n failed: true,\n timedOut: false,\n denied: true,\n diagnostics: currentDiagnostics(),\n })\n if (outcome?.kind === 'gate-declined') throw new E_SANDBOX_REFUSED([narrate(outcome)])\n throw new E_SANDBOX_REFUSED([narrate({ kind: 'gate-unavailable', reason: 'error' })])\n }\n let relative: string\n try {\n // NO pre-emptive leading-`/` rejection. The model's world IS the sandbox, so `/src/index.ts`\n // means \"top of what I can see\" and must NORMALISE to the root — rejecting it punishes the\n // model for a distinction we deliberately hid, and produces the mangle-retry loop the\n // LLM-operator rules exist to prevent. `toRelative` owns the whole gauntlet, `~` included.\n relative = await options.translator.toRelative(args.cwd)\n await options.translator.assertNoSymlinkComponents(relative)\n } catch (error) {\n // An ALREADY-NARRATED refusal passes through: re-wrapping it would discard a more precise\n // outcome and relabel it `escape`.\n if (\n isInstanceOf(error, 'E_SANDBOX_REFUSED', E_SANDBOX_REFUSED) ||\n isInstanceOf(error, 'E_SANDBOX_FAILED', E_SANDBOX_FAILED)\n )\n throw error\n // And the REASON is classified, not assumed — `cwd` is the model-supplied path on the one\n // tool that runs arbitrary code, so \"use a workspace-relative path\" is the wrong advice for\n // a NUL byte or a UNC form.\n await emitCompletion({\n exitCode: null,\n failed: true,\n timedOut: false,\n denied: true,\n diagnostics: currentDiagnostics(),\n })\n throw new E_SANDBOX_FAILED([\n narrate({\n kind: 'path-rejected',\n input: args.cwd,\n reason: classifySandboxPathRejection(args.cwd) ?? 'escape',\n }),\n ])\n }\n // Only spaces and tabs separate shell words. JS `\\s` also splits Unicode whitespace\n // that sh treats as part of the executable name, so it is not safe for this name check.\n const commandName = args.command.replace(/^[ \\t]+/, '').split(/[ \\t]/, 1)[0]\n // Conservative by design: do not interpret quoting. Even quoted metacharacters are refused,\n // as are all `$` expansions and backslashes (including escaped/continued command names).\n // Argument quotes remain useful, but the executable word itself must be plain and literal.\n const refusedSyntax = options.allowedCommands\n ? (args.command.match(/[;&|`$<>(){}\\r\\n\\\\]/)?.[0] ?? commandName.match(/['\"]/)?.[0])\n : undefined\n if (\n options.allowedCommands &&\n (refusedSyntax !== undefined || !options.allowedCommands.includes(commandName))\n ) {\n await emitCompletion({\n exitCode: null,\n failed: true,\n timedOut: false,\n denied: true,\n diagnostics: currentDiagnostics(),\n })\n throw new E_SANDBOX_REFUSED([\n refusedSyntax !== undefined\n ? `Shell syntax ${JSON.stringify(refusedSyntax)} is refused: allowedCommands restricts the line to a single plain command (unquoted command name; no operators, pipes, substitution, expansion, redirection, grouping, or backslashes, even inside quotes).`\n : narrate({\n kind: 'denied-by-policy',\n path: commandName,\n axis: 'read',\n }),\n ])\n }\n // Resolve the policy for THIS call. A function is evaluated after the gate and the cwd\n // gauntlet (a revoked grant is then gone on the very next call, and the per-call context is\n // complete), and must be handed a fresh object per call, or concurrent runs would share one\n // mutable policy. Resolution sits INSIDE the completion seam: a throwing or rejecting policy\n // function is a terminal outcome like any other, so it fires `onCompletion` exactly once with\n // a failed completion and then rethrows the SAME error the caller saw before this seam existed.\n let resolvedPolicy: SandboxPolicy\n try {\n resolvedPolicy =\n typeof options.policy === 'function'\n ? await options.policy({ args, relativeCwd: relative })\n : options.policy\n } catch (error) {\n await emitCompletion({\n exitCode: null,\n failed: true,\n timedOut: false,\n diagnostics: [isError(error) ? error.message : String(error)],\n })\n throw error\n }\n const correlationId = crypto.randomUUID()\n const controller = new AbortController()\n const abort = (): void => controller.abort(ctx.abortSignal.reason)\n if (ctx.abortSignal.aborted) abort()\n else ctx.abortSignal.addEventListener('abort', abort, { once: true })\n let timerFired = false\n const timeout = setTimeout(() => {\n timerFired = true\n controller.abort()\n }, args.timeout_seconds * 1000)\n // A stream controller is captured without buffering any payload.\n let streamController: ReadableStreamDefaultController<Uint8Array> | undefined\n const merged = new ReadableStream<Uint8Array>({\n start(mergedController) {\n streamController = mergedController\n },\n })\n const write = (bytes: Uint8Array): void => streamController?.enqueue(bytes)\n const close = (): void => streamController?.close()\n let execution: Awaited<ReturnType<SandboxPolicyEnforcer['run']>>\n try {\n // `command` is a real shell command LINE — `printf hello`, a pipe, quoting, redirection —\n // so it must reach a shell's `-c` as ONE argument. The enforcer quotes whatever `argv` it\n // receives (`quoteShellArgs(op.argv)`), so handing it `argv: [args.command]` made it quote\n // the whole line as a single word: the shell then looked for an executable literally named\n // `printf hello`, and every command with arguments exited 127. Wrapping the line in an\n // explicit `sh -c` makes the enforcer's argv contract correct — it receives a real command\n // with a real argument, which it can quote safely — instead of teaching every enforcer a\n // second \"unquoted command\" mode. `/bin/sh` is the POSIX shell present on every platform\n // SRT supports (macOS and Linux); SRT owns the outer shell (`binShell`) that invokes it.\n execution = await options.sandbox.run({\n argv: ['/bin/sh', '-c', args.command],\n policy: resolvedPolicy,\n correlationId,\n cwd: options.translator.toBackendPath(relative),\n signal: controller.signal,\n ...(options.env === undefined ? {} : { env: { ...options.env } }),\n })\n } catch (error) {\n clearTimeout(timeout)\n const outcome = (error as { outcome?: SandboxOutcome }).outcome\n // SRT refuses a divergent per-call network section BEFORE spawning. Preserve this\n // actionable typed admission error, not arbitrary untyped backend failures.\n const networkRefused = isInstanceOf(\n error,\n 'E_SANDBOX_NETWORK_GRANT_UNSUPPORTED',\n E_SANDBOX_NETWORK_GRANT_UNSUPPORTED\n )\n await emitCompletion({\n exitCode: null,\n failed: true,\n timedOut: false,\n denied: networkRefused || outcome?.kind === 'denied-by-policy' ? true : undefined,\n diagnostics: [\n ...(isError(error) ? [error.message] : [String(error)]),\n ...currentDiagnostics(correlationId),\n ],\n artifactRef: correlationId,\n })\n if (networkRefused) throw error\n if (outcome?.kind === 'denied-by-policy') throw new E_SANDBOX_REFUSED([narrate(outcome)])\n throw new E_SANDBOX_FAILED([\n narrate({\n kind: 'io-failure',\n detail: isError(error) ? error.message : String(error),\n }),\n ])\n }\n const storeWrite = Promise.resolve(ctx.storeRetrievableBytes(correlationId, merged))\n // Observe immediately: the store can reject while drains/poller are still running.\n // Keep the original promise so the terminal path below rethrows the SAME error.\n void storeWrite.catch(() => {})\n const seen = new Set<string>()\n const poll = (): void => {\n for (const denial of options.sandbox.diagnosticsFor(correlationId)) {\n if (!seen.has(denial)) {\n seen.add(denial)\n // Redacted because a denial is upstream TEXT and routinely names an absolute host path —\n // the one line in this stream the battery authors from someone else's words. The exit-code\n // and timeout lines below are numbers this battery formats, so they carry nothing to scrub.\n // This does NOT extend to the child's own stdout, which no field translation can reach.\n write(line(`[sandbox] denied: ${options.translator.redact(denial)} (observed after)`))\n }\n }\n }\n const drain = async (source: ReadableStream<Uint8Array>): Promise<void> => {\n const reader = source.getReader()\n try {\n for (;;) {\n const item = await reader.read()\n if (item.done) return\n write(item.value)\n poll()\n }\n } finally {\n reader.releaseLock()\n }\n }\n let polling = true\n const poller = (async (): Promise<void> => {\n while (polling) {\n await new Promise<void>((resolve) => setTimeout(resolve, 10))\n if (polling) poll()\n }\n })()\n let completed: Awaited<typeof execution.completed> | undefined\n let drainError: unknown\n try {\n await Promise.all([drain(execution.stdout), drain(execution.stderr)])\n completed = await execution.completed\n } catch (error) {\n drainError = error\n } finally {\n clearTimeout(timeout)\n polling = false\n await poller\n poll()\n if (timerFired) write(line(`[timed out after ${args.timeout_seconds}s]`))\n else if (completed && completed.exitCode !== 0)\n write(line(`Exit code: ${completed.exitCode}`))\n close()\n }\n if (drainError !== undefined) {\n // A post-spawn I/O failure (a stream erroring mid-drain) also settles the completion: the\n // child may have run, so it is a failed, non-denied outcome rather than a silent rejection.\n await emitCompletion({\n exitCode: completed?.exitCode ?? null,\n failed: true,\n timedOut: timerFired,\n diagnostics: [\n ...(isError(drainError) ? [drainError.message] : [String(drainError)]),\n ...currentDiagnostics(correlationId),\n ],\n })\n throw drainError\n }\n let reader: Awaited<typeof storeWrite>\n try {\n reader = await storeWrite\n } catch (error) {\n await emitCompletion({\n exitCode: completed?.exitCode ?? null,\n failed: true,\n timedOut: timerFired,\n diagnostics: [\n ...(isError(error) ? [error.message] : [String(error)]),\n ...currentDiagnostics(correlationId),\n ],\n })\n throw error\n }\n // The tool's return type is unchanged (the artifact); the completion travels only through the\n // callback. `killedBy` is the signal that ACTUALLY terminated the child, taken from the real\n // settlement (`completed.signalCode`, Node's `ChildProcess.signalCode`), NOT from the abort\n // REASON we wrote onto the controller: on a timeout the reason is an `AbortError` while the\n // enforcer runs `process.kill(-pid, 'SIGKILL')`, so reading the reason reported `'AbortError'`\n // for a child killed with SIGKILL (issue #49 follow-up). It is reported only when the child was\n // actually signal-killed; a normal exit has no `killedBy`. `timerFired` alone is not enough —\n // the child can win the race and exit cleanly — so the signal is the sole source of truth.\n const killedBy = completed?.signalCode ?? undefined\n await emitCompletion({\n exitCode: completed?.exitCode ?? null,\n failed: completed ? completed.failed : timerFired,\n timedOut: timerFired,\n ...(killedBy === undefined ? {} : { killedBy }),\n diagnostics: currentDiagnostics(correlationId),\n artifactRef: correlationId,\n })\n return new SpooledArtifact(reader)\n },\n })\n}\n","import { passesSchema } from '../validation'\nimport { validator } from '@nhtio/validation'\nimport type { SandboxPolicy, DerivedRules } from '../types'\n\n/** Policy boundary. `run` resolves on spawn and exposes live streams plus a later completion promise. */\nexport interface SandboxPolicyEnforcer {\n /** Whether this enforcer can enforce on the current platform. `false` (a browser tab, where SRT does not exist) raises `E_SANDBOX_UNSUPPORTED_ENV` at construction rather than degrading — a shim that enforces nothing reads as sandboxed. */\n isSupported(): boolean\n /** Whether this adapter adopted an already-enabled process-global sandbox rather than initializing it. */\n readonly adopted?: boolean\n /** Probe external prerequisites. A non-empty `errors` throws `E_SANDBOX_DEPENDENCY_MISSING`; `warnings` are surfaced through observability and are NOT fatal. */\n checkDependencies(): Promise<{ errors: string[]; warnings: string[] }>\n /**\n * Spawn under a narrowing policy; a non-zero exit is data, not a rejected promise.\n *\n * @remarks\n * When `op.signal` aborts, an implementation MUST terminate the spawned child (including a\n * child hidden behind a sandbox wrapper) and settle `completed`; it MUST NOT leave the child\n * running after the lifecycle owner has cancelled the invocation. The returned streams may end\n * as a consequence of termination, but `completed` remains the authoritative settlement signal.\n */\n run(op: {\n argv: string[]\n policy: SandboxPolicy\n correlationId: string\n cwd: string\n /**\n * An ADDITIVE per-call overlay on the child's environment, applied LAST.\n *\n * @remarks\n * NOT the host-inheritance control. What a child inherits from the host is the ADAPTER's decision\n * (the Node/SRT one denies by default and takes an allow-list at construction); this field only\n * adds to whatever that produced, and an adapter MUST NOT let it silently widen what the deployment\n * allowed. Leaving these semantics unstated is how the Node adapter came to spread the entire\n * `process.env` into every child while this field sat unused.\n */\n env?: Record<string, string>\n /**\n * Lifecycle cancellation for this child. Implementations must kill the spawned child and\n * settle `completed` when this signal aborts.\n */\n signal?: AbortSignal\n }): Promise<{\n stdout: ReadableStream<Uint8Array>\n stderr: ReadableStream<Uint8Array>\n /**\n * The child's terminal settlement. `signalCode` is the REAL signal that killed the child\n * (Node's `ChildProcess.signalCode`: `'SIGKILL'`, `'SIGTERM'`, …), and is OMITTED when the\n * child exited on its own. Additive and optional so an adapter that cannot surface it simply\n * leaves it off; a consumer must treat absence as \"not signal-killed\", never as a specific\n * signal.\n */\n completed: Promise<{ exitCode: number; failed: boolean; signalCode?: string }>\n }>\n /** Return the opaque derived snapshot used for drift validation. */\n effectivePolicy(): DerivedRules | undefined\n /** Retrieve diagnostics by correlation id, never by command text. */\n diagnosticsFor(correlationId: string): string[]\n /** Release what this enforcer OWNS. A no-op when it adopted a foreign sandbox — tearing down a manager we did not initialize would strip ACEs a host app depends on. */\n dispose(): Promise<void>\n}\n\n/** Duck-type schema. */\nexport const sandboxPolicyEnforcerSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (\n value !== null &&\n value !== undefined &&\n typeof (value as any).isSupported === 'function' &&\n typeof (value as any).checkDependencies === 'function' &&\n typeof (value as any).run === 'function' &&\n typeof (value as any).effectivePolicy === 'function' &&\n typeof (value as any).diagnosticsFor === 'function' &&\n typeof (value as any).dispose === 'function'\n )\n return value\n return helpers.error('any.invalid')\n })\n\n/** Structural guard. */\nexport const implementsSandboxPolicyEnforcer = (value: unknown): value is SandboxPolicyEnforcer =>\n passesSchema(sandboxPolicyEnforcerSchema, value)\n","import { passesSchema } from '../validation'\nimport { validator } from '@nhtio/validation'\nimport type { ListFrame } from '../types'\n\n/** Filesystem capability with no copy primitive; traversal is complete and terminal-framed. */\nexport interface SandboxFileSystem {\n /** Return metadata. A changed version token is evidence of change; equality is not a no-change guarantee. */\n stat(path: string): Promise<{\n size: number\n version: string\n kind: 'file' | 'dir' | 'symlink' | 'other'\n mtimeMs?: number\n ino?: number\n dev?: number\n }>\n /** Lazily yield every item, followed by exactly one mandatory done frame. */\n list(path: string, o: { maxDepth: number; signal?: AbortSignal }): AsyncIterable<ListFrame>\n /** Open a fresh, replayable byte stream; non-regular kinds are refused by adapters. */\n read(path: string, o?: { signal?: AbortSignal }): Promise<ReadableStream<Uint8Array>>\n /** Write bytes without imposing a battery-level size cap. */\n write(\n path: string,\n bytes: ReadableStream<Uint8Array> | Uint8Array,\n o?: { signal?: AbortSignal }\n ): Promise<void>\n /** Delete a path. Deletion is idempotent: deleting an absent path resolves. */\n delete?(path: string, o?: { signal?: AbortSignal }): Promise<void>\n /**\n * Move a path. MUST overwrite an existing destination (POSIX move semantics).\n * Dev-tools relies on this behaviour when breaking rename cycles.\n */\n rename?(from: string, to: string, o?: { signal?: AbortSignal }): Promise<void>\n /** Create a directory. */\n mkdir?(path: string, o?: { signal?: AbortSignal }): Promise<void>\n}\n\n/** Duck-type schema. */\nexport const sandboxFileSystemSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (\n value !== null &&\n value !== undefined &&\n typeof (value as any).stat === 'function' &&\n typeof (value as any).list === 'function' &&\n typeof (value as any).read === 'function' &&\n typeof (value as any).write === 'function'\n )\n return value\n return helpers.error('any.invalid')\n })\n\n/** Structural guard. */\nexport const implementsSandboxFileSystem = (value: unknown): value is SandboxFileSystem =>\n passesSchema(sandboxFileSystemSchema, value)\n","import { passesSchema } from '../validation'\nimport { validator } from '@nhtio/validation'\nimport type { HitFrame, PathFrame } from '../types'\n\n/** Search capability; every result is lazy, complete, and terminal-framed. */\nexport interface SandboxSearch {\n /**\n * Whether this adapter can CONTAIN symlinked descendants when `follow` is enabled.\n *\n * `rg --follow` traverses links whose targets never pass through the path translator, so an\n * uncontained backend turns `follow: true` into an unbounded read of wherever they point.\n * The tools layer cannot inspect what is behind this interface, so an adapter declares it:\n * omitted or `false` means the forged `search_files`/`find_files` schemas REJECT `follow: true`\n * outright rather than accepting it and failing at execution. Set it only if you have verified\n * containment; the bundled ripgrep adapter has not, and does not set it.\n */\n readonly supportsFollow?: boolean\n /** Lazily yield every whole matching line, then one done frame. */\n searchContent(o: {\n root: string\n pattern: string\n /**\n * Traversal depth. Omit for an unbounded scan; an explicit value must be a non-negative integer.\n *\n * @remarks\n * An adapter MUST NOT name a depth on its own initiative when omitted — the unbounded request is\n * the caller's choice, and `Number.MAX_SAFE_INTEGER` is a disguised cap, not an implementation of\n * it (issue #48).\n */\n maxDepth?: number\n /**\n * Maximum results to yield. Omit for an unbounded search; an explicit value MUST be an integer\n * >= 1, and adapters reject anything else.\n *\n * @remarks\n * Omission is the documented unbounded mode, NOT a default cap: every match is returned and the\n * scan finishes `{ kind: 'done', complete: true }`. There is deliberately no sentinel —`undefined`\n * cannot be confused with an explicit number, so `Infinity`/`NaN`/`0`/negatives stay rejections\n * even though they conceptually mean the same thing (issue #48).\n *\n * MEMORY: an unbounded search is collected by the adapter before results are yielded (rg's\n * stdout is buffered whole), so peak memory grows in proportion to the OUTPUT on very large\n * trees — an explicit `limit` truncates only after collection. Pass a `limit` (or `maxDepth`)\n * wherever the tree size is untrusted or unknown.\n */\n limit?: number\n ignoreCase?: boolean\n literal?: boolean\n glob?: string\n iglob?: string\n follow?: boolean\n hidden?: boolean\n noIgnore?: boolean\n signal?: AbortSignal\n }): AsyncIterable<HitFrame>\n /** Lazily yield every matching path, then one done frame. */\n findPaths(o: {\n root: string\n glob: string\n /**\n * Traversal depth. Omit for an unbounded scan; an explicit value must be a non-negative integer.\n *\n * @remarks\n * An adapter MUST NOT name a depth on its own initiative when omitted — see `searchContent`.\n */\n maxDepth?: number\n /**\n * Maximum results to yield. Omit for an unbounded search; an explicit value MUST be an integer\n * >= 1, and adapters reject anything else — see `searchContent` (issue #48).\n */\n limit?: number\n iglob?: string\n follow?: boolean\n hidden?: boolean\n noIgnore?: boolean\n signal?: AbortSignal\n }): AsyncIterable<PathFrame>\n}\n\n/** Duck-type schema. */\nexport const sandboxSearchSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (\n value !== null &&\n value !== undefined &&\n typeof (value as any).searchContent === 'function' &&\n typeof (value as any).findPaths === 'function'\n )\n return value\n return helpers.error('any.invalid')\n })\n\n/** Structural guard. */\nexport const implementsSandboxSearch = (value: unknown): value is SandboxSearch =>\n passesSchema(sandboxSearchSchema, value)\n","import { passesSchema } from '../validation'\nimport { validator } from '@nhtio/validation'\n\n/** Model-path boundary: normalises ergonomic paths while refusing unambiguous host escapes. */\nexport interface PathTranslator {\n /** Validate and convert a model path; leading separators mean the sandbox root. */\n toRelative(modelPath: string): Promise<string>\n /** Convert a validated relative path to an opaque backend locator. */\n toBackendPath(relative: string): string\n /** Scrub root and common host identifiers from battery-generated text. */\n redact(text: string): string\n /** The translator always inspects the resolved path and every parent for symlink components. */\n assertNoSymlinkComponents(relative: string): Promise<void>\n}\n\n/** Duck-type schema. */\nexport const pathTranslatorSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (\n value !== null &&\n value !== undefined &&\n typeof (value as any).toRelative === 'function' &&\n typeof (value as any).toBackendPath === 'function' &&\n typeof (value as any).redact === 'function' &&\n typeof (value as any).assertNoSymlinkComponents === 'function'\n )\n return value\n return helpers.error('any.invalid')\n })\n\n/** Structural guard. */\nexport const implementsPathTranslator = (value: unknown): value is PathTranslator =>\n passesSchema(pathTranslatorSchema, value)\n","import { passesSchema } from '../validation'\nimport { validator } from '@nhtio/validation'\nimport type { GuestLimits, GuestHandle } from '../types'\n\n/** Runtime boundary for a hardened guest realm; limits and capability declarations cross the boundary. */\nexport interface GuestRuntime {\n /** Spawn a guest with fully resolved hostile-realm limits and async capability stubs. */\n spawn(o: {\n modules: string[]\n globals: ReadonlyArray<{ name: string; kind: 'async-fn' }>\n limits: GuestLimits\n signal?: AbortSignal\n }): Promise<GuestHandle>\n}\n\n/** Duck-type schema. */\nexport const guestRuntimeSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (value !== null && value !== undefined && typeof (value as any).spawn === 'function')\n return value\n return helpers.error('any.invalid')\n })\n\n/** Structural guard. */\nexport const implementsGuestRuntime = (value: unknown): value is GuestRuntime =>\n passesSchema(guestRuntimeSchema, value)\n","import { passesSchema } from '../validation'\nimport { validator } from '@nhtio/validation'\n/** MIME resolver; `undefined` means the resolver declines and a later resolver may decide. */\nexport type MimeResolver = (ctx: {\n path: string\n declared?: string\n /** Read a bounded prefix only; this callback cannot read the whole file. */\n peek: (bytes: number) => Promise<Uint8Array>\n}) => string | undefined | Promise<string | undefined>\n/** MIME resolver schema. */\nexport const mimeResolverSchema = validator\n .any()\n .required()\n .custom((v, h) => (typeof v === 'function' ? v : h.error('any.invalid')))\n/** MIME resolver guard. */\nexport const implementsMimeResolver = (v: unknown): v is MimeResolver =>\n passesSchema(mimeResolverSchema, v)\n","import { passesSchema } from '../validation'\nimport { validator } from '@nhtio/validation'\n\n/** Artifact-class registry. Format constructors are lazy so unused parsers are never loaded. */\nexport interface ArtifactMinter {\n /** Return available formats and async constructors. */\n formats(): Promise<\n Array<{ id: string; mime: string[]; extensions: string[]; ctor: () => Promise<unknown> }>\n >\n}\n\n/** Duck-type schema. */\nexport const artifactMinterSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (value !== null && value !== undefined && typeof (value as any).formats === 'function')\n return value\n return helpers.error('any.invalid')\n })\n\n/** Structural guard. */\nexport const implementsArtifactMinter = (value: unknown): value is ArtifactMinter =>\n passesSchema(artifactMinterSchema, value)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,IAAM,wBACJ,OAAO,YAAY,eAAe,OAAO,QAAQ,aAAa,WAC1D,QAAQ,WACR;;AAGN,IAAa,mBAAmB,OAAO,YAAyD;CAE9F,KADiB,QAAQ,YAAY,gBAAgB,OACpC,SACf,MAAM,IAAI,qBAAA,0BAA0B,CAClC,8EACF,CAAC;CAGH,IAAI,CAAC,QAAQ,SAAS,YAAY,GAChC,MAAM,IAAI,qBAAA,0BAA0B,CAClC,+FACF,CAAC;CAGH,MAAM,eAAe,MAAM,QAAQ,SAAS,kBAAkB;CAC9D,MAAM,WAAW,OAAO,OAAO,CAAC,GAAG,aAAa,QAAQ,CAAC;CACzD,IAAI,aAAa,SAAS,SAAS,GACjC,QAAQ,YAAY;EAAE,MAAM;EAAuB;CAAS,CAAC;CAE/D,MAAM,sBAAsB,QAAQ,uBAAuB;CAE3D,MAAM,oBADwB,QAAQ,SAAS,gBAAgB,MAAM,KAAA,KAE1C,aAAa,OAAO,SAAS,KAAK,CAAC;CAC9D,IAAI,aAAa,OAAO,SAAS,KAAK,CAAC,QAAQ,0BAC7C,MAAM,IAAI,qBAAA,6BAA6B,CACrC,yCAAyC,aAAa,OAAO,KAAK,IAAI,GACxE,CAAC;CAEH,MAAM,gBAAgB,QAAQ,QAAQ,4BAA4B,iBAAiB;CACnF,MAAM,SAA2B;EAC/B,0BAA0B;EAC1B;EACA,YAAY,QAAQ,QAAQ,UAAU;EACtC,oBAAoB;EACpB,GAAI,QAAQ,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe,QAAQ,cAAc;CACxF;CACA,OAAO,OAAO,OAAO,MAAM;AAC7B;;AAGA,IAAa,sBAAsB;;AAGnC,IAAa,oBAAoB,OAC/B,UACA,WACkB;CAClB,IAAI;CACJ,IAAI;EACF,SAAS,MAAM,SA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ACpC,CAAC;;AAGH,IAAa,4BAA4B,UACvC,mBAAA,aAAa,sBAAsB,KAAK;;;;AClB1C,IAAa,qBAAqB,kBAAA,UAC/B,IAAI,EACJ,SAAS,EACT,QAAQ,OAAO,YAAY;CAC1B,IAAI,UAAU,QAAQ,UAAU,KAAA,KAAa,OAAQ,MAAc,UAAU,YAC3E,OAAO;CACT,OAAO,QAAQ,MAAM,aAAa;AACpC,CAAC;;AAGH,IAAa,0BAA0B,UACrC,mBAAA,aAAa,oBAAoB,KAAK;;;;ACjBxC,IAAa,qBAAqB,kBAAA,UAC/B,IAAI,EACJ,SAAS,EACT,QAAQ,GAAG,MAAO,OAAO,MAAM,aAAa,IAAI,EAAE,MAAM,aAAa,CAAE;;AAE1E,IAAa,0BAA0B,MACrC,mBAAA,aAAa,oBAAoB,CAAC;;;;ACJpC,IAAa,uBAAuB,kBAAA,UACjC,IAAI,EACJ,SAAS,EACT,QAAQ,OAAO,YAAY;CAC1B,IAAI,UAAU,QAAQ,UAAU,KAAA,KAAa,OAAQ,MAAc,YAAY,YAC7E,OAAO;CACT,OAAO,QAAQ,MAAM,aAAa;AACpC,CAAC;;AAGH,IAAa,4BAA4B,UACvC,mBAAA,aAAa,sBAAsB,KAAK"}
1
+ {"version":3,"file":"sandbox.cjs","names":[],"sources":["../../src/batteries/sandbox/preflight.ts","../../src/batteries/sandbox/observability.ts","../../src/batteries/sandbox/manager.ts","../../src/batteries/sandbox/executor.ts","../../src/batteries/sandbox/tool.ts","../../src/batteries/sandbox/contracts/policy_enforcer.ts","../../src/batteries/sandbox/contracts/file_system.ts","../../src/batteries/sandbox/contracts/search.ts","../../src/batteries/sandbox/contracts/path_translator.ts","../../src/batteries/sandbox/contracts/guest_runtime.ts","../../src/batteries/sandbox/contracts/mime_resolver.ts","../../src/batteries/sandbox/contracts/artifact_minter.ts"],"sourcesContent":["/**\n * Construction-time admission for the sandbox.\n *\n * This is the seam consumed by WP-A1: `createSandbox()` must call this function once and\n * retain the returned, frozen decision. In particular, WP-A1 must not reproduce the three\n * fallback predicates here; doing so would make the handle's security posture depend on two\n * subtly different implementations.\n */\nimport { isException } from '../../lib/utils/exceptions'\nimport {\n E_SANDBOX_DEPENDENCY_MISSING,\n E_SANDBOX_FAILED,\n E_SANDBOX_UNSUPPORTED_ENV,\n} from './exceptions'\nimport type { SandboxPolicy } from './types'\nimport type { SandboxEventSink } from './observability'\nimport type { SandboxPolicyEnforcer } from './contracts/policy_enforcer'\n\n/** Platform identity supplied by the construction site. */\nexport type SandboxPlatform = 'darwin' | 'linux' | 'win32' | string\n\n/** Inputs to the construction-time environment admission check. */\nexport interface PreflightOptions {\n /** Policy backend to admit. */\n readonly enforcer: SandboxPolicyEnforcer\n /** Platform override, primarily for hermetic tests. */\n readonly platform?: SandboxPlatform\n /** Explicit opt-in to run without OS containment when a pre-execution condition applies. */\n readonly allowUnsandboxedFallback?: boolean\n /** Claude Code's strict mode: per-call escape/bypass is ignored by the consumer. */\n readonly strictMode?: boolean\n /** Whether the optional SRT peer was resolved. Defaults to true for injected test enforcers. */\n readonly optionalPeerPresent?: boolean\n /** Receives dependency warnings; warnings never make admission fail. */\n readonly onSandbox?: SandboxEventSink\n /** Path redaction is performed by the observability sink, not by this admission check. */\n readonly fsNodeVersion?: string\n}\n\n/** Immutable decision retained by a sandbox handle for its entire lifetime. */\nexport interface SandboxPreflight {\n /** Whether the construction opted into fallback. */\n readonly allowUnsandboxedFallback: boolean\n /** Whether one of the permitted pre-execution conditions fired. */\n readonly fallbackFired: boolean\n /** Whether per-call bypasses must be ignored. */\n readonly strictMode: boolean\n /** Non-fatal dependency diagnostics. */\n readonly dependencyWarnings: readonly string[]\n /** Version provenance for fs_node, when supplied by the backend. */\n readonly fsNodeVersion?: string\n}\n\nconst currentPlatform = (): SandboxPlatform =>\n typeof process !== 'undefined' && typeof process.platform === 'string'\n ? process.platform\n : 'browser'\n\n/** Run the once-only, fail-closed environment gauntlet used by `createSandbox()`. */\nexport const preflightSandbox = async (options: PreflightOptions): Promise<SandboxPreflight> => {\n const platform = options.platform ?? currentPlatform()\n if (platform === 'win32') {\n throw new E_SANDBOX_UNSUPPORTED_ENV([\n 'Native Windows is not supported; run the sandbox inside a WSL2 distribution.',\n ])\n }\n\n if (!options.enforcer.isSupported()) {\n throw new E_SANDBOX_UNSUPPORTED_ENV([\n 'The browser environment has no SRT boundary; use Part B (SES) as the cross-environment layer.',\n ])\n }\n\n const dependencies = await options.enforcer.checkDependencies()\n const warnings = Object.freeze([...dependencies.warnings])\n if (dependencies.warnings.length > 0) {\n options.onSandbox?.({ kind: 'dependency-warnings', warnings })\n }\n const optionalPeerPresent = options.optionalPeerPresent ?? true\n const platformCannotSandbox = options.enforcer.effectivePolicy() === undefined\n const fallbackCondition =\n platformCannotSandbox || dependencies.errors.length > 0 || !optionalPeerPresent\n if (dependencies.errors.length > 0 && !options.allowUnsandboxedFallback) {\n throw new E_SANDBOX_DEPENDENCY_MISSING([\n `Sandbox dependencies are unavailable: ${dependencies.errors.join('; ')}`,\n ])\n }\n const fallbackFired = Boolean(options.allowUnsandboxedFallback && fallbackCondition)\n const result: SandboxPreflight = {\n allowUnsandboxedFallback: fallbackFired,\n fallbackFired,\n strictMode: Boolean(options.strictMode),\n dependencyWarnings: warnings,\n ...(options.fsNodeVersion === undefined ? {} : { fsNodeVersion: options.fsNodeVersion }),\n }\n return Object.freeze(result)\n}\n\n/** Compatibility alias for the construction-site call in WP-A1. */\nexport const runSandboxPreflight = preflightSandbox\n\n/** Probe spawning after policy admission, rather than as part of preflight. */\nexport const probeSandboxSpawn = async (\n enforcer: SandboxPolicyEnforcer,\n policy: SandboxPolicy\n): Promise<void> => {\n let result: Awaited<ReturnType<SandboxPolicyEnforcer['run']>>\n try {\n result = await enforcer.run({\n argv: ['true'],\n policy,\n correlationId: crypto.randomUUID(),\n cwd: process.cwd(),\n })\n } catch (error) {\n // Preserve policy and lifecycle classifications; only an untyped spawn failure is treated as\n // the dependency/liveness failure this opt-in probe is designed to detect.\n if (isException(error) && error.name.startsWith('E_SANDBOX_')) throw error\n throw new E_SANDBOX_DEPENDENCY_MISSING([`Sandbox spawn probe failed: ${String(error)}`])\n }\n const drain = async (stream: ReadableStream<Uint8Array>): Promise<string> => {\n const reader = stream.getReader()\n const chunks: Uint8Array[] = []\n try {\n for (;;) {\n const next = await reader.read()\n if (next.done) break\n chunks.push(next.value)\n }\n } finally {\n reader.releaseLock()\n }\n const bytes = new Uint8Array(chunks.reduce((size, chunk) => size + chunk.length, 0))\n let offset = 0\n for (const chunk of chunks) {\n bytes.set(chunk, offset)\n offset += chunk.length\n }\n return new TextDecoder().decode(bytes)\n }\n let stderr: string\n let completed: Awaited<ReturnType<SandboxPolicyEnforcer['run']>>['completed'] extends Promise<\n infer T\n >\n ? T\n : never\n try {\n ;[, stderr, completed] = await Promise.all([\n drain(result.stdout),\n drain(result.stderr),\n result.completed,\n ])\n } catch (error) {\n if (isException(error) && error.name.startsWith('E_SANDBOX_')) throw error\n throw new E_SANDBOX_DEPENDENCY_MISSING([\n `Sandbox spawn probe failed while draining output: ${String(error)}`,\n ])\n }\n if (completed.failed)\n throw new E_SANDBOX_FAILED([\n `Sandbox spawn probe failed (exit code ${completed.exitCode}): ${stderr || 'no stderr'}`,\n ])\n}\n","/**\n * The single sandbox observability firehose.\n *\n * WP-A1 wires the callbacks from `createSandbox()` to `createSandboxObservability()`;\n * it must not emit parallel ad-hoc events. Every path-bearing field is redacted here,\n * before it reaches an operator, logger, or audit sink.\n */\nimport type { PathTranslator } from './contracts/path_translator'\n\n/** Typed records emitted by the sandbox's single audit firehose. */\nexport type SandboxEvent =\n | {\n readonly kind: 'bypass'\n readonly command: string\n readonly path?: string\n readonly loud: true\n }\n | {\n readonly kind: 'unsandboxed-fallback'\n readonly handleId: string\n readonly reason: string\n readonly path?: string\n readonly loud: true\n }\n | {\n readonly kind: 'drift-check'\n readonly outcome: 'passed' | 'failed' | 'skipped'\n readonly reason?: string\n readonly path?: string\n /** `skipped` is specifically the network-domain comparison, not adoption. */\n readonly comparison?: 'network-domains'\n }\n | {\n readonly kind: 'fs-node-version'\n readonly version: string\n }\n | { readonly kind: 'dependency-warnings'; readonly warnings: readonly string[] }\n\n/** Consumer callback for sandbox audit events. */\nexport type SandboxEventSink = (event: SandboxEvent) => void\n\n/** Dependencies used to create the redacting firehose. */\nexport interface SandboxObservabilityOptions {\n /** Translator used for every path-bearing event field. */\n readonly pathTranslator: PathTranslator\n /** Destination for already-redacted events. */\n readonly sink: SandboxEventSink\n}\n\nconst redactEvent = (event: SandboxEvent, translator: PathTranslator): SandboxEvent => {\n if (event.kind === 'bypass') {\n return Object.freeze({\n ...event,\n command: translator.redact(event.command),\n ...(event.path === undefined ? {} : { path: translator.redact(event.path) }),\n })\n }\n if (event.kind === 'unsandboxed-fallback') {\n return Object.freeze({\n ...event,\n handleId: translator.redact(event.handleId),\n reason: translator.redact(event.reason),\n ...(event.path === undefined ? {} : { path: translator.redact(event.path) }),\n })\n }\n if (event.kind === 'drift-check') {\n return Object.freeze({\n ...event,\n ...(event.reason === undefined ? {} : { reason: translator.redact(event.reason) }),\n ...(event.path === undefined ? {} : { path: translator.redact(event.path) }),\n })\n }\n if (event.kind === 'dependency-warnings') {\n return Object.freeze({\n ...event,\n warnings: Object.freeze(event.warnings.map((warning) => translator.redact(warning))),\n })\n }\n return Object.freeze(event)\n}\n\n/** Build the one event surface consumed by WP-A1's sandbox handle. */\nexport const createSandboxObservability = (\n options: SandboxObservabilityOptions\n): SandboxEventSink => {\n return (event) => options.sink(redactEvent(event, options.pathTranslator))\n}\n\n/** Emit a loud audit-only bypass report. */\nexport const emitBypass = (sink: SandboxEventSink, command: string, path?: string): void => {\n sink({ kind: 'bypass', command, ...(path === undefined ? {} : { path }), loud: true })\n}\n\n/** Emit the permanent loud report for an unsandboxed invocation. */\nexport const emitFallback = (\n sink: SandboxEventSink,\n handleId: string,\n reason: string,\n path?: string\n): void => {\n sink({\n kind: 'unsandboxed-fallback',\n handleId,\n reason,\n ...(path === undefined ? {} : { path }),\n loud: true,\n })\n}\n\n/** Emit a drift result, including an explicit network-domain skip when requested. */\nexport const emitDriftCheck = (\n sink: SandboxEventSink,\n outcome: 'passed' | 'failed' | 'skipped',\n details?: {\n readonly reason?: string\n readonly path?: string\n readonly networkDomainsSkipped?: boolean\n }\n): void => {\n sink({\n kind: 'drift-check',\n outcome,\n ...(details?.reason === undefined ? {} : { reason: details.reason }),\n ...(details?.path === undefined ? {} : { path: details.path }),\n ...(details?.networkDomainsSkipped ? { comparison: 'network-domains' as const } : {}),\n })\n}\n\n/** Emit the SRT version used by the in-process evaluator. */\nexport const emitFsNodeVersion = (sink: SandboxEventSink, version: string): void => {\n sink({ kind: 'fs-node-version', version })\n}\n","import { createSandboxEpoch } from './types'\nimport { probeSandboxSpawn, runSandboxPreflight } from './preflight'\nimport { createSandboxObservability, emitDriftCheck, emitFallback } from './observability'\nimport {\n E_SANDBOX_NOT_INITIALIZED,\n E_SANDBOX_POLICY_CONFLICT,\n E_SANDBOX_NARROWING_UNSUPPORTED,\n} from './exceptions'\nimport type { PathTranslator } from './contracts/path_translator'\nimport type { SandboxPolicy, DerivedRules, SandboxEpoch } from './types'\nimport type { SandboxPolicyEnforcer } from './contracts/policy_enforcer'\n\ntype RunOptions = Parameters<SandboxPolicyEnforcer['run']>[0]\n/**\n * A live sandbox session: the object every sandbox tool is built against.\n *\n * @remarks\n * THIS IS A PROCESS-GLOBAL CAPABILITY WEARING A PER-HANDLE API, and the shape is a promise narrowed\n * rather than a promise kept. `SandboxManager` is a singleton, so the first `createSandbox()` in a\n * process establishes the policy and a later one may only NARROW it — a request that is not a subset\n * throws `E_SANDBOX_POLICY_CONFLICT` naming both. One policy per process is the safe deployment;\n * multi-tenant agents with different policies want separate processes.\n *\n * Every `run()` re-validates against the admission baseline before spawning, so a widening of the live\n * policy is DETECTED. Detection is not prevention: SRT's proxies consult policy per request, so a\n * widening already affects an in-flight child for its whole lifetime.\n */\nexport interface SandboxHandle {\n /**\n * Opaque token issued at construction and invalidated by {@link SandboxHandle.dispose}.\n *\n * @remarks\n * File-backed readers hold this rather than a filesystem reference, which is what makes disposal\n * deterministic: a staged reader outliving its TURN is legitimate, outliving its HANDLE is not.\n */\n readonly epoch: SandboxEpoch\n /**\n * The live DERIVED rules — not the `SandboxPolicy` that was requested.\n *\n * @remarks\n * A policy cannot express what the drift check has to compare (`denyOnly`/`allowWithinDeny`, the\n * unioned default write paths, Linux-expanded read globs, the profile-only mandatory denies), so\n * returning one here would compare the wrong thing and pass while the live sandbox had widened.\n * Under ADOPTION this re-derives from the live manager on every call; an owned session is cached.\n */\n readonly effectivePolicy: () => DerivedRules | undefined\n /**\n * Spawn under this session's policy, optionally narrowed for the single invocation.\n *\n * @remarks\n * Resolves as soon as the child is SPAWNED, handing back live `stdout`/`stderr` streams plus a\n * separate `completed` promise. Drain BOTH concurrently: pipe buffers are per-fd, so draining one to\n * completion first can block the other and hang the child. A non-zero exit is data on `completed`,\n * never a rejection.\n *\n * `options.policy` is a PER-INVOCATION policy. Its effect is backend-specific and, under the SRT\n * enforcer, axis-specific (measured on macOS/seatbelt AND Linux/bwrap, issue #50, both identical): a\n * per-call FILESYSTEM grant is honoured for that ONE child, REPLACING the session baseline rather\n * than unioning with it — the per-call policy is that child's complete filesystem policy, so it must\n * repeat any baseline writes it still wants. A per-call NETWORK section that DIFFERS from the\n * session's — a new domain, a narrowing, an added deny, a different `disabled` — is REFUSED with\n * `E_SANDBOX_NETWORK_GRANT_UNSUPPORTED` (SRT's proxy filters every request against the\n * process-global session config, so neither a per-call grant NOR a per-call narrowing is\n * representable), so network policy is established for the session; a per-call policy must repeat\n * the session's network section exactly (order-insensitive set equality). See\n * [per-call policy semantics](/batteries/sandbox/index#per-call-policy-semantics-under-srt).\n */\n run(options: RunOptions): ReturnType<SandboxPolicyEnforcer['run']>\n /**\n * Narrow the session policy for subsequent operations.\n *\n * @param policy - Must be a subset per the per-axis rules; reads are deny-then-allow while writes\n * are allow-only, so \"narrower\" is not symmetric. Throws\n * `E_SANDBOX_NARROWING_UNSUPPORTED` naming the axis where the platform cannot narrow it.\n */\n narrow(policy: SandboxPolicy): Promise<void>\n /** Predicate consumed by file-backed readers; disposal makes the epoch unusable. */\n isEpochLive(epoch: SandboxEpoch): boolean\n /**\n * Quiesce the session: it does not abandon in-flight work.\n *\n * @remarks\n * Rejects new work with `E_SANDBOX_NOT_INITIALIZED`, aborts in-flight invocations through their\n * signals, kills spawned children, then releases the enforcer. On an ADOPTED session this is a\n * reported NO-OP — resetting a manager we did not create would strip ACEs a host application\n * depends on.\n */\n dispose(): Promise<void>\n}\n\n/** Options for {@link createSandbox}. */\nexport interface CreateSandboxOptions {\n /**\n * ADK-owned policy vocabulary, mapped to the backend's config inside the enforcer.\n *\n * @remarks\n * The per-axis defaults DIFFER and are not a symmetry worth \"fixing\": reads default to ALLOW\n * (absent `denyRead` means everything is readable, and `allowRead` re-permits WITHIN a deny), while\n * writes default to DENY and network is an allow-list. A checker that unified them would disagree\n * with the OS by construction.\n */\n readonly policy: SandboxPolicy\n /** The boundary itself. Node's SRT-backed enforcer lives on the `sandbox/node` subpath. */\n readonly enforcer: SandboxPolicyEnforcer\n /**\n * Model-path translation, and the redaction used on every observability event.\n *\n * @remarks\n * Supply it if you want host identifiers scrubbed from the event stream — no battery-generated\n * surface should carry the sandbox root, home directory, or user name.\n */\n readonly translator?: PathTranslator\n /** Observability firehose: bypasses, fallbacks, drift outcomes, and the SRT version rules came from. */\n readonly onSandbox?: (event: Parameters<ReturnType<typeof createSandboxObservability>>[0]) => void\n /**\n * Permit degraded operation when the environment cannot provide OS containment.\n *\n * @remarks\n * Fires only for pre-execution conditions resolved once at construction — a platform the backend\n * cannot sandbox that we still run on, dependency errors, or an absent optional peer. It NEVER fires\n * for a violation (a violation means the sandbox worked), and native Windows is refused outright\n * rather than degraded. When it fires the handle is permanently marked and every invocation emits\n * a loud observability event. Execution STILL goes through `enforcer.run`; this option never runs\n * a command unsandboxed, and the tool descriptions tell the model it has no OS containment.\n */\n readonly allowUnsandboxedFallback?: boolean\n /** Ignore the per-call escape entirely, matching the reference consumer's strict mode. */\n readonly strictMode?: boolean\n /** Whether the optional peer resolved; feeds the preflight decision above. */\n readonly optionalPeerPresent?: boolean\n /** Recorded on observability events so a rules-versus-backend mismatch is diagnosable without a bisect. */\n readonly fsNodeVersion?: string\n /** Opt in to a real child-spawn liveness check during construction. */\n readonly probeSpawn?: boolean\n}\n\nlet owner: { baseline: DerivedRules; enforcer: SandboxPolicyEnforcer; owned: boolean } | undefined\nlet establishment: Promise<void> = Promise.resolve()\nlet disposalRequested = 0\nconst acquireEstablishment = async (): Promise<() => void> => {\n const previous = establishment\n let release!: () => void\n establishment = new Promise<void>((resolve) => {\n release = resolve\n })\n await previous\n return release\n}\n\nconst list = (value: readonly string[] | undefined): readonly string[] => value ?? []\nconst json = (value: unknown): string => JSON.stringify(value)\n\n/**\n * Conservative list inclusion. Globs which are not lexically identical are deliberately\n * undecidable and therefore fail closed. This is a sufficient test, not a complete relation.\n */\nconst subset = (small: readonly string[], large: readonly string[]): boolean =>\n small.every((item) => large.includes(item))\nconst same = (a: unknown, b: unknown): boolean => json(a) === json(b)\n\n/** Compare a requested (admission) derived policy with the live one: requested ⊆ live. */\nconst admission = (ours: DerivedRules, live: DerivedRules): boolean => {\n if (!same(ours.matcher, live.matcher) || !same(ours.mandatoryDeny, live.mandatoryDeny))\n return false\n if (ours.filesystemDisabled && !live.filesystemDisabled) return false\n if (!ours.filesystemDisabled && live.filesystemDisabled) {\n // A kill switch is widening, and is consequently safe for admission.\n }\n return (\n subset(live.read.denyOnly, ours.read.denyOnly) &&\n subset(ours.read.allowWithinDeny, live.read.allowWithinDeny) &&\n subset(ours.write.allowOnly, live.write.allowOnly) &&\n subset(live.write.denyWithinAllow, ours.write.denyWithinAllow) &&\n subset(ours.network.allowedDomains, live.network.allowedDomains) &&\n subset(live.network.deniedDomains, ours.network.deniedDomains)\n )\n}\n\n/** Compare a live snapshot with the admission baseline: widening is drift. */\nconst drift = (baseline: DerivedRules, live: DerivedRules): string | undefined => {\n if (!same(baseline.matcher, live.matcher)) return 'matcher changed'\n if (!same(baseline.mandatoryDeny, live.mandatoryDeny)) return 'mandatory deny inputs changed'\n if (!baseline.filesystemDisabled && live.filesystemDisabled) return 'filesystem.disabled widened'\n if (baseline.filesystemDisabled && !live.filesystemDisabled) {\n // Narrowing is explicitly allowed.\n }\n if (live.unknownKeys.length > 0) return `unknown live config keys: ${live.unknownKeys.join(', ')}`\n if (live.undecidableGlobs.length > 0)\n return `uncompilable live globs: ${live.undecidableGlobs.join(', ')}`\n if (!subset(live.read.denyOnly, baseline.read.denyOnly)) return 'read deny rules widened'\n if (!subset(live.read.allowWithinDeny, baseline.read.allowWithinDeny))\n return 'read allow rules widened'\n if (!subset(live.write.allowOnly, baseline.write.allowOnly)) return 'write allow rules widened'\n if (!subset(live.write.denyWithinAllow, baseline.write.denyWithinAllow))\n return 'write deny rules widened'\n if (baseline.network.disabled) {\n // Disabled means unrestricted, which cannot be represented by a domain list.\n } else {\n if (live.network.disabled) return 'network.disabled widened'\n if (!subset(live.network.allowedDomains, baseline.network.allowedDomains))\n return 'allowed domains widened'\n if (!subset(baseline.network.deniedDomains, live.network.deniedDomains))\n return 'denied domains widened'\n }\n if (baseline.network.strictAllowlist !== live.network.strictAllowlist)\n return 'strictAllowlist changed'\n return undefined\n}\n\nconst policyEffect = (policy: SandboxPolicy, template: DerivedRules): DerivedRules => ({\n ...template,\n filesystemDisabled: Boolean(policy.filesystem.disabled),\n read: {\n denyOnly: [...list(policy.filesystem.denyRead)],\n allowWithinDeny: [...list(policy.filesystem.allowRead)],\n },\n write: {\n allowOnly: [...list(policy.filesystem.allowWrite)],\n denyWithinAllow: [...list(policy.filesystem.denyWrite)],\n },\n network: {\n ...template.network,\n disabled: Boolean(policy.network.disabled),\n allowedDomains: policy.network.disabled ? ['*'] : [...list(policy.network.allowedDomains)],\n deniedDomains: policy.network.disabled ? [] : [...list(policy.network.deniedDomains)],\n },\n})\n\n/**\n * Admit one process-global sandbox. Drift is detection, not prevention: SRT consults its\n * proxies per request, so a widening can affect an already-spawned child for its lifetime.\n */\nexport const createSandbox = async (options: CreateSandboxOptions): Promise<SandboxHandle> => {\n const sink =\n options.onSandbox && options.translator\n ? createSandboxObservability({ pathTranslator: options.translator, sink: options.onSandbox })\n : (options.onSandbox ?? (() => undefined))\n const release = await acquireEstablishment()\n let assignedOwner: typeof owner\n try {\n const preflight = await runSandboxPreflight({\n enforcer: options.enforcer,\n allowUnsandboxedFallback: options.allowUnsandboxedFallback,\n strictMode: options.strictMode,\n optionalPeerPresent: options.optionalPeerPresent,\n fsNodeVersion: options.fsNodeVersion,\n onSandbox: sink,\n })\n const live = options.enforcer.effectivePolicy()\n if (!live) throw new E_SANDBOX_POLICY_CONFLICT(['Sandbox has no derived policy'])\n // An adopted enforcer has no ADK policy provenance, so admission must compare the requested\n // effect against its genuinely live foreign baseline. Owned sessions retain the established\n // first-writer baseline for subsequent handles.\n const adopted = options.enforcer.adopted === true\n const firstHandle = owner === undefined\n if (owner !== undefined) {\n const admissionBaseline = adopted ? live : owner.baseline\n const requested = policyEffect(options.policy, admissionBaseline)\n if (!admission(requested, admissionBaseline)) {\n throw new E_SANDBOX_POLICY_CONFLICT([\n `requested policy ${json(options.policy)} conflicts with ${json(admissionBaseline)}`,\n ])\n }\n } else {\n // Adoption has no caller policy to compare against until this point; rule 3b compares the\n // requested effect with the foreign live baseline before admitting the first handle.\n if (adopted && !admission(policyEffect(options.policy, live), live))\n throw new E_SANDBOX_POLICY_CONFLICT([\n `requested policy ${json(options.policy)} conflicts with ${json(live)}`,\n ])\n owner = { baseline: live, enforcer: options.enforcer, owned: !adopted }\n assignedOwner = owner\n }\n const admittedOwner = owner\n if (!admittedOwner) throw new E_SANDBOX_NOT_INITIALIZED(['Sandbox owner was not established'])\n if (options.probeSpawn) {\n // Probe only after admission: preflight runs before admission and could exercise a rejected policy.\n // Probe failures fail closed; manager.ts:272 calls enforcer.run() unconditionally, so\n // allowUnsandboxedFallback cannot provide an unsandboxed alternative here.\n await probeSandboxSpawn(admittedOwner.enforcer, options.policy)\n }\n if (owner !== admittedOwner)\n throw new E_SANDBOX_NOT_INITIALIZED(['Sandbox owner changed during construction'])\n // A disposal requested while this construction was probing must invalidate construction rather\n // than return a handle that the queued disposal would immediately reset.\n if (disposalRequested > 0)\n throw new E_SANDBOX_NOT_INITIALIZED(['Sandbox disposal was requested during construction'])\n const baseline = admittedOwner.baseline\n const epoch = createSandboxEpoch()\n let disposed = false\n const controllers = new Set<AbortController>()\n const check = (): void => {\n if (disposed) throw new E_SANDBOX_NOT_INITIALIZED(['Sandbox handle has been disposed'])\n const current = owner?.enforcer.effectivePolicy()\n if (!current) throw new E_SANDBOX_NOT_INITIALIZED(['Sandbox policy is unavailable'])\n const reason = drift(baseline, current)\n if (reason) {\n emitDriftCheck(sink, 'failed', { reason })\n throw new E_SANDBOX_POLICY_CONFLICT([`sandbox drift detected: ${reason}`])\n }\n if (baseline.network.disabled)\n emitDriftCheck(sink, 'skipped', { networkDomainsSkipped: true })\n else emitDriftCheck(sink, 'passed')\n }\n const handle: SandboxHandle = {\n epoch,\n effectivePolicy: () => owner?.enforcer.effectivePolicy(),\n run: async (runOptions) => {\n check()\n // The manager owns this controller so disposal cancels every in-flight invocation. The\n // enforcer contract requires that cancellation terminate the corresponding child and settle\n // its `completed` promise; the caller's signal is mirrored into this lifecycle signal.\n const controller = new AbortController()\n controllers.add(controller)\n const signal = runOptions.signal\n let callerAbortListener: (() => void) | undefined\n const cleanup = (): void => {\n if (signal && callerAbortListener) {\n signal.removeEventListener('abort', callerAbortListener)\n callerAbortListener = undefined\n }\n controllers.delete(controller)\n }\n if (signal) {\n if (signal.aborted) controller.abort(signal.reason)\n else {\n callerAbortListener = () => controller.abort(signal.reason)\n signal.addEventListener('abort', callerAbortListener, { once: true })\n }\n }\n let result: ReturnType<SandboxPolicyEnforcer['run']>\n try {\n result = owner!.enforcer.run({ ...runOptions, signal: controller.signal })\n } catch (error) {\n cleanup()\n throw error\n }\n // `run` resolves after spawn, while `completed` settles after exit. Keep this controller\n // registered until completion so disposal can still cancel a live child.\n void result.then(({ completed }) => completed.then(cleanup, cleanup), cleanup)\n if (preflight.fallbackFired) emitFallback(sink, 'sandbox', 'unsandboxed fallback')\n return result\n },\n narrow: async (policy) => {\n check()\n const candidate = options.enforcer as SandboxPolicyEnforcer & {\n narrow?: (requested: SandboxPolicy) => Promise<void>\n }\n if (typeof candidate.narrow !== 'function')\n throw new E_SANDBOX_NARROWING_UNSUPPORTED(['filesystem/network'])\n await candidate.narrow(policy)\n },\n isEpochLive: (candidate) => !disposed && candidate === epoch,\n dispose: async () => {\n if (disposed) return\n disposed = true\n // Mark synchronously, before waiting for the establishment queue, so a pending probe can\n // fail with a lifecycle error instead of returning a handle that this disposal resets.\n if (firstHandle) disposalRequested += 1\n const releaseDispose = await acquireEstablishment()\n try {\n for (const controller of controllers) controller.abort()\n controllers.clear()\n if (firstHandle) {\n if (!adopted) await options.enforcer.dispose()\n if (owner?.enforcer === options.enforcer) owner = undefined\n }\n } finally {\n if (firstHandle) disposalRequested -= 1\n releaseDispose()\n }\n },\n }\n release()\n return handle\n } catch (error) {\n try {\n if (assignedOwner && owner === assignedOwner) {\n owner = undefined\n // Roll back the backend session as well as the manager record. Calling the enforcer\n // directly avoids re-entering the establishment queue held by this construction.\n if (assignedOwner.owned) await options.enforcer.dispose()\n }\n } finally {\n release()\n }\n throw error\n }\n}\n","import { emitBypass, type SandboxEventSink } from './observability'\nimport type { BinaryExecutor, BinaryInvocation } from '../media/contracts'\n\n/**\n * A command wrapper that REWRITES an invocation into the one the inner executor should run.\n *\n * @remarks\n * The wrapper's job is to own quoting: it returns the argv that actually gets spawned, which for a\n * sandbox is the wrapper binary (bwrap, sandbox-exec, …) followed by everything that binary needs.\n * That is why {@link sandboxedExecutor} does NOT quote for it — quoting is a property of the\n * wrapper being used (a shell `-c` string, an argv vector, a container `exec` line), so an adapter\n * that quoted first would hand every implementor the wrong representation.\n *\n * A `wrap` implementation must NOT execute anything: it only computes and returns the invocation.\n */\nexport interface BinarySandbox {\n /**\n * Return the invocation the inner executor should run instead. Its `cmd` and `args` ARE the\n * wrapped argv, so the caller's original `args` are never appended.\n *\n * @param invocation - The command, args, working directory, environment, and limits to wrap.\n * @returns The replacement invocation, carrying through whatever the caller asked for that the\n * wrapper does not itself decide (`cwd`, `timeoutMs`, `signal`, the kill controls).\n */\n wrap(invocation: BinaryInvocation): Promise<BinaryInvocation>\n}\n\n/** Configuration for the sandboxed binary executor. */\nexport interface SandboxedExecutorOptions {\n /** Command wrapper used for non-bypassed invocations. */\n readonly sandbox: BinarySandbox\n /** Underlying executor receiving the wrapped invocation. */\n readonly inner: BinaryExecutor\n /** Command-only opt-out. This is deliberately never passed argv to the predicate. */\n readonly bypass?: (cmd: string) => boolean\n /** Loud audit sink; bypass is observability, not enforcement. */\n readonly onSandbox?: SandboxEventSink\n}\n\n/**\n * Adapt a {@link BinaryExecutor} to a command sandbox. This WRAPS `inner.exec()` and DOES NOT\n * STREAM: the shipped BinaryExecutor contract returns settled strings. Consequently an execa\n * inner executor retains its output and inherits execa's bounded `maxBuffer` behaviour; this\n * adapter does not raise that bound (and never sets `maxBuffer: Infinity`). The streaming path is\n * {@link createRunShellCommandTool}, which uses the policy-enforcer stream contract instead.\n *\n * The adapter hands the invocation to {@link BinarySandbox.wrap} verbatim and runs what comes\n * back: `inner.exec(await sandbox.wrap(invocation))`. The returned `cmd`/`args` are the complete\n * wrapped argv, so the original `args` are not re-appended — a wrapper that wants them in the\n * wrapped command puts them there itself. Quoting is therefore the wrapper's job, not this\n * adapter's.\n *\n * Bypass is an audit-only opt-out. Its predicate receives `cmd` only, never argv: callers must\n * allow only binaries safe with hostile arguments and must never allow an interpreter. Non-zero\n * exits remain data and are never thrown. Removing this wrapper call restores the inner executor.\n *\n * @param options - The wrapper, the inner executor, and the optional audit hooks.\n * @returns A `BinaryExecutor` whose non-bypassed invocations go through `options.sandbox.wrap`.\n */\nexport const sandboxedExecutor = (options: SandboxedExecutorOptions): BinaryExecutor => ({\n async exec(invocation) {\n if (options.bypass?.(invocation.cmd)) {\n options.onSandbox?.({ kind: 'bypass', command: invocation.cmd, loud: true })\n return options.inner.exec(invocation)\n }\n return options.inner.exec(await options.sandbox.wrap(invocation))\n },\n})\n\n/** Emit a bypass through the canonical sink for consumers that do not retain the adapter. */\nexport const reportSandboxBypass = (sink: SandboxEventSink, command: string): void =>\n emitBypass(sink, command)\n","import { Tool } from '@nhtio/adk/forge'\nimport { validator } from '@nhtio/validation'\nimport { classifySandboxPathRejection } from './paths'\nimport { isError, isInstanceOf } from '@nhtio/adk/guards'\nimport { SpooledArtifact } from '@nhtio/adk/spooled_artifact'\nimport { runToolGate, type ToolGateFn } from '../tools/_shared'\nimport { E_TURN_GATE_ABORTED } from '../../lib/exceptions/runtime'\nimport { defaultSandboxNarrator, type SandboxNarrator, type SandboxOutcome } from './narrator'\nimport {\n E_SANDBOX_GATE_REQUIRED,\n E_SANDBOX_REFUSED,\n E_SANDBOX_FAILED,\n E_SANDBOX_NETWORK_GRANT_UNSUPPORTED,\n} from './exceptions'\nimport type { SandboxPolicy } from './types'\nimport type { PathTranslator } from './contracts/path_translator'\nimport type { SandboxPolicyEnforcer } from './contracts/policy_enforcer'\n\n/**\n * What one `run_shell_command` invocation actually did.\n *\n * @remarks\n * The structured completion for {@link createRunShellCommandTool}'s `onCompletion` callback.\n * Deliberately issued once per invocation, on EVERY terminal outcome — a clean exit, a non-zero\n * exit, a timeout, a kill, a gate/approval denial, and an enforcer throw all settle this — because\n * the audit seam exists precisely so a denied or killed command is not indistinguishable from a\n * successful one.\n *\n * Field rules:\n * - `exitCode` is the child's real exit status, or `null` when the command never ran (a gate\n * denial, a path refusal, a spawn failure) or its exit status is unknowable.\n * - `failed` is `true` for every outcome that is not a successful zero exit, INCLUDING denials,\n * timeouts, killed children, enforcer errors, and a per-call `policy` function that failed.\n * `exitCode !== 0` implies `failed`, and so do outcomes with `exitCode: null`.\n * - `timedOut` marks the `timeout_seconds` deadline firing (`exitCode` is then `null` or the killed\n * child's status, depending on whether `completed` settled).\n * - `killedBy` names the signal that ACTUALLY terminated the child instead of letting it exit,\n * read from the real child settlement (Node's `signalCode`), e.g. `'SIGKILL'` when the enforcer\n * kills the process group on a timeout. Absent when the child exited on its own (a clean exit, a\n * non-zero exit, or a timeout it won by exiting before the kill landed).\n * - `denied` marks a refusal BEFORE the command ran (a gate denial, a path/gate/allow-list\n * refusal) — no child was spawned.\n * - `diagnostics` carries everything the enforcer reported (`diagnosticsFor`, the `[sandbox]\n * denied: …` lines) plus, for a handler failure, the thrown value's message — including a per-call\n * `policy` function that threw or rejected, which fires this completion before the error surfaces.\n * Empty usually.\n * - `artifactRef` names the returned {@link SpooledArtifact}'s correlation id — the same id the\n * spool store keyed the stream under — so an audit sink can join the completion to the artifact.\n * It is present whenever the run reached the enforcer, including an enforcer throw (its id still\n * keys any diagnostics recorded for that run). It is absent for the very first refusals (those\n * throw before any stream exists) and a throwing per-call `policy` (it fails before a stream is\n * opened).\n *\n * The tool's own return type is UNCHANGED: it still resolves to the artifact. This type travels\n * only through the callback, so existing consumers keep compiling.\n */\nexport interface RunShellCommandCompletion {\n /** The child's real exit status; `null` when the command never ran or never reported one. */\n readonly exitCode: number | null\n /** `true` for every non-success outcome, including denials, timeouts, kills, and enforcer throws. */\n readonly failed: boolean\n /** Whether the `timeout_seconds` deadline fired and terminated the command. */\n readonly timedOut: boolean\n /** The signal that actually killed the child instead of letting it exit, when one did, e.g. `'SIGKILL'`. */\n readonly killedBy?: string\n /** Whether the command was refused before spawning (gate denial, path refusal, allow-list). */\n readonly denied?: boolean\n /** Enforcer diagnostics (`[sandbox] denied: …` lines) and, on a handler failure, its message. */\n readonly diagnostics: readonly string[]\n /** The spool store correlation id backing the invocation's returned artifact, when one exists. */\n readonly artifactRef?: string\n}\n\n/** Consumer-supplied completion observer; errors it throws are contained, never propagated. */\nexport type RunShellCommandCompletionFn = (completion: RunShellCommandCompletion) => void\n\n/** The per-call context handed to a {@link RunShellCommandPolicyFn}. */\nexport interface RunShellCommandPolicyContext {\n /** The validated tool arguments (`command`, `cwd`, `timeout_seconds`) for this call. */\n readonly args: { command: string; cwd: string; timeout_seconds: number }\n /** The resolved workspace-relative `cwd` this call will run under. */\n readonly relativeCwd: string\n}\n\n/**\n * A policy resolved PER CALL rather than captured at construction.\n *\n * @remarks\n * Evaluated once per invocation, AFTER the gate has approved and AFTER `cwd` has passed the path\n * gauntlet, and its return value is passed to `enforcer.run` for that one child only — a policy\n * object captured at construction would keep a revoked grant alive forever. A per-call policy must\n * hand the ENFORCER a fresh object per call (`{ ...basePolicy }` at minimum): the enforcer stores\n * what it is handed, so a shared mutable object collapses concurrent runs back into one shared\n * policy.\n *\n * There is NO gate decision in the context. `ToolGateFn` approves with `void` and denies by\n * THROWING, and a thrown denial returns before this callback runs — so at the moment a policy is\n * resolved there is no approval artefact to hand over, and a denied call never reaches here.\n */\nexport type RunShellCommandPolicyFn = (\n context: RunShellCommandPolicyContext\n) => SandboxPolicy | Promise<SandboxPolicy>\n\n/** Configuration for the streaming shell-command tool. */\nexport interface RunShellCommandOptions {\n /** Streaming policy enforcer; unlike BinaryExecutor this exposes live stdout/stderr. */\n readonly sandbox: SandboxPolicyEnforcer\n /**\n * Policy applied to the spawned command: a static object for every call, or a per-call function.\n *\n * @remarks\n * A function is evaluated once per invocation, AFTER the gate has approved and after `cwd` has\n * passed the path gauntlet, and receives the call context (the validated tool args and the\n * resolved workspace-relative `cwd`). Its return is the policy for that ONE child — see\n * {@link RunShellCommandPolicyFn} for the fresh-object rule under concurrency.\n */\n readonly policy: SandboxPolicy | RunShellCommandPolicyFn\n /** Model-path translator for the working directory. */\n readonly translator: PathTranslator\n /** Required human/policy approval gate. */\n readonly gate?: ToolGateFn\n /**\n * Optional command-name allow-list; restricts the line to a single plain command.\n * Operators, pipes, redirection, grouping, backticks, all `$` expansion, and backslashes\n * are refused even inside quotes. The first word must be unquoted; argument quotes are allowed.\n * This is a name check, not a security boundary: the sandbox policy remains the boundary.\n */\n readonly allowedCommands?: readonly string[]\n /**\n * Environment variables to add to every command this tool spawns.\n *\n * @remarks\n * ADDITIVE, and applied LAST — over both the host variables the enforcer allow-listed and SRT's own\n * proxy/CA plumbing. It is not the host-inheritance control: the enforcer decides what the child\n * inherits (`envAllowList` / `inheritHostEnv` on the Node adapter), and this cannot re-admit a\n * variable the enforcer withheld except by supplying the value literally here.\n *\n * Anything put here is readable by the model — `run_shell_command` runs commands the model chose,\n * and `env` is one of them — so pass configuration, not credentials.\n */\n readonly env?: Readonly<Record<string, string>>\n /** Optional tool description override. */\n readonly description?: string\n /**\n * Called exactly once per invocation with the structured completion, on EVERY terminal outcome.\n *\n * @remarks\n * Success, non-zero exit, timeout, kill/signal, gate/approval denial, and an enforcer throw all\n * settle this once — see {@link RunShellCommandCompletion} for the field rules. A callback that\n * throws is logged and swallowed: it must never break the tool call or surface as an unhandled\n * rejection (the issue-#39 bug class).\n */\n readonly onCompletion?: RunShellCommandCompletionFn\n /** Injectable model-facing outcome renderer. */\n readonly narrate?: SandboxNarrator\n}\n\nconst encoder = new TextEncoder()\nconst line = (value: string): Uint8Array => encoder.encode(`${value}\\n`)\n\n/**\n * Assemble the factory-style `run_shell_command` tool. It is intentionally not a bulk-registered\n * battery value. `cwd` is a model-supplied workspace-relative path and receives the complete\n * PathTranslator gauntlet, including symlink refusal; the default is the workspace root.\n *\n * The command spawns first, then stdout and stderr are drained concurrently and merged in arrival\n * order into one stream and one `storeRetrievableBytes` call. Diagnostics are polled while drains\n * run and written as `[sandbox] denied: …` at their observation point (\"observed after\", not\n * \"caused by\"). The command is never accumulated here. `timeout_seconds` defaults to 300 and is\n * a tool argument. Non-zero exits, violations, timeouts, and post-spawn I/O failures return the\n * singular artifact; failures meaning the command never ran throw instead.\n */\nexport const createRunShellCommandTool = (options: RunShellCommandOptions): Tool => {\n if (!options.gate) throw new E_SANDBOX_GATE_REQUIRED(['run_shell_command requires a gate'])\n const inputSchema = validator.object({\n command: validator.string().required().description('Shell command to execute.'),\n cwd: validator\n .string()\n .default('')\n .allow('')\n .description('Workspace-relative working directory; defaults to the workspace root.'),\n timeout_seconds: validator\n .number()\n .min(1)\n .default(300)\n .description('Command timeout in seconds; defaults to 300. Raise it for slow commands.'),\n })\n return new Tool({\n name: 'run_shell_command',\n description:\n options.description ??\n 'Run a shell command under the sandbox. Output is one interleaved artifact; sandbox denials appear inline. cwd is workspace-relative and timeout_seconds defaults to 300.',\n inputSchema,\n trusted: false,\n handler: async (raw, ctx) => {\n const args = raw as {\n command: string\n cwd: string\n timeout_seconds: number\n }\n const narrate = options.narrate ?? defaultSandboxNarrator\n // Emitted EXACTLY ONCE per invocation, on every terminal outcome. The denied/pre-spawn and\n // enforcer-throw paths deliberately fire it too: this seam exists so those outcomes are\n // structured data instead of \"no artifact arrived\". A throwing observer is contained — its\n // failure must not replace the refusal/exception the caller is already receiving, and a raw\n // rejection escaping into the dispatch core is the issue-#39 bug class.\n let completionDone = false\n const emitCompletion = async (completion: RunShellCommandCompletion): Promise<void> => {\n if (completionDone) return\n completionDone = true\n if (!options.onCompletion) return\n try {\n await options.onCompletion(completion)\n } catch (error) {\n // Swallowed by design (see the option's docblock). `String` can itself throw, so the\n // message is assembled defensively.\n let detail: string\n try {\n detail = isError(error) ? error.message : String(error)\n } catch {\n detail = '<uncoercible>'\n }\n console.error(`[run_shell_command] onCompletion threw and was ignored: ${detail}`)\n }\n }\n const currentDiagnostics = (correlationId?: string): readonly string[] =>\n correlationId === undefined ? [] : [...options.sandbox.diagnosticsFor(correlationId)]\n try {\n await runToolGate(options.gate, ctx, 'run_shell_command', args)\n } catch (error) {\n if (isInstanceOf(error, 'E_TURN_GATE_ABORTED', E_TURN_GATE_ABORTED)) {\n if (ctx.abortSignal.aborted) throw error\n throw new E_SANDBOX_FAILED([narrate({ kind: 'aborted' })])\n }\n const outcome =\n (error as { outcome?: SandboxOutcome; kind?: string }).outcome ??\n ((error as { kind?: string }).kind === 'gate-declined'\n ? ({ kind: 'gate-declined' } satisfies SandboxOutcome)\n : undefined)\n await emitCompletion({\n exitCode: null,\n failed: true,\n timedOut: false,\n denied: true,\n diagnostics: currentDiagnostics(),\n })\n if (outcome?.kind === 'gate-declined') throw new E_SANDBOX_REFUSED([narrate(outcome)])\n throw new E_SANDBOX_REFUSED([narrate({ kind: 'gate-unavailable', reason: 'error' })])\n }\n let relative: string\n try {\n // NO pre-emptive leading-`/` rejection. The model's world IS the sandbox, so `/src/index.ts`\n // means \"top of what I can see\" and must NORMALISE to the root — rejecting it punishes the\n // model for a distinction we deliberately hid, and produces the mangle-retry loop the\n // LLM-operator rules exist to prevent. `toRelative` owns the whole gauntlet, `~` included.\n relative = await options.translator.toRelative(args.cwd)\n await options.translator.assertNoSymlinkComponents(relative)\n } catch (error) {\n // An ALREADY-NARRATED refusal passes through: re-wrapping it would discard a more precise\n // outcome and relabel it `escape`.\n if (\n isInstanceOf(error, 'E_SANDBOX_REFUSED', E_SANDBOX_REFUSED) ||\n isInstanceOf(error, 'E_SANDBOX_FAILED', E_SANDBOX_FAILED)\n )\n throw error\n // And the REASON is classified, not assumed — `cwd` is the model-supplied path on the one\n // tool that runs arbitrary code, so \"use a workspace-relative path\" is the wrong advice for\n // a NUL byte or a UNC form.\n await emitCompletion({\n exitCode: null,\n failed: true,\n timedOut: false,\n denied: true,\n diagnostics: currentDiagnostics(),\n })\n throw new E_SANDBOX_FAILED([\n narrate({\n kind: 'path-rejected',\n input: args.cwd,\n reason: classifySandboxPathRejection(args.cwd) ?? 'escape',\n }),\n ])\n }\n // Only spaces and tabs separate shell words. JS `\\s` also splits Unicode whitespace\n // that sh treats as part of the executable name, so it is not safe for this name check.\n const commandName = args.command.replace(/^[ \\t]+/, '').split(/[ \\t]/, 1)[0]\n // Conservative by design: do not interpret quoting. Even quoted metacharacters are refused,\n // as are all `$` expansions and backslashes (including escaped/continued command names).\n // Argument quotes remain useful, but the executable word itself must be plain and literal.\n const refusedSyntax = options.allowedCommands\n ? (args.command.match(/[;&|`$<>(){}\\r\\n\\\\]/)?.[0] ?? commandName.match(/['\"]/)?.[0])\n : undefined\n if (\n options.allowedCommands &&\n (refusedSyntax !== undefined || !options.allowedCommands.includes(commandName))\n ) {\n await emitCompletion({\n exitCode: null,\n failed: true,\n timedOut: false,\n denied: true,\n diagnostics: currentDiagnostics(),\n })\n throw new E_SANDBOX_REFUSED([\n refusedSyntax !== undefined\n ? `Shell syntax ${JSON.stringify(refusedSyntax)} is refused: allowedCommands restricts the line to a single plain command (unquoted command name; no operators, pipes, substitution, expansion, redirection, grouping, or backslashes, even inside quotes).`\n : narrate({\n kind: 'denied-by-policy',\n path: commandName,\n axis: 'read',\n }),\n ])\n }\n // Resolve the policy for THIS call. A function is evaluated after the gate and the cwd\n // gauntlet (a revoked grant is then gone on the very next call, and the per-call context is\n // complete), and must be handed a fresh object per call, or concurrent runs would share one\n // mutable policy. Resolution sits INSIDE the completion seam: a throwing or rejecting policy\n // function is a terminal outcome like any other, so it fires `onCompletion` exactly once with\n // a failed completion and then rethrows the SAME error the caller saw before this seam existed.\n let resolvedPolicy: SandboxPolicy\n try {\n resolvedPolicy =\n typeof options.policy === 'function'\n ? await options.policy({ args, relativeCwd: relative })\n : options.policy\n } catch (error) {\n await emitCompletion({\n exitCode: null,\n failed: true,\n timedOut: false,\n diagnostics: [isError(error) ? error.message : String(error)],\n })\n throw error\n }\n const correlationId = crypto.randomUUID()\n const controller = new AbortController()\n const abort = (): void => controller.abort(ctx.abortSignal.reason)\n if (ctx.abortSignal.aborted) abort()\n else ctx.abortSignal.addEventListener('abort', abort, { once: true })\n let timerFired = false\n const timeout = setTimeout(() => {\n timerFired = true\n controller.abort()\n }, args.timeout_seconds * 1000)\n // A stream controller is captured without buffering any payload.\n let streamController: ReadableStreamDefaultController<Uint8Array> | undefined\n const merged = new ReadableStream<Uint8Array>({\n start(mergedController) {\n streamController = mergedController\n },\n })\n const write = (bytes: Uint8Array): void => streamController?.enqueue(bytes)\n const close = (): void => streamController?.close()\n let execution: Awaited<ReturnType<SandboxPolicyEnforcer['run']>>\n try {\n // `command` is a real shell command LINE — `printf hello`, a pipe, quoting, redirection —\n // so it must reach a shell's `-c` as ONE argument. The enforcer quotes whatever `argv` it\n // receives (`quoteShellArgs(op.argv)`), so handing it `argv: [args.command]` made it quote\n // the whole line as a single word: the shell then looked for an executable literally named\n // `printf hello`, and every command with arguments exited 127. Wrapping the line in an\n // explicit `sh -c` makes the enforcer's argv contract correct — it receives a real command\n // with a real argument, which it can quote safely — instead of teaching every enforcer a\n // second \"unquoted command\" mode. `/bin/sh` is the POSIX shell present on every platform\n // SRT supports (macOS and Linux); SRT owns the outer shell (`binShell`) that invokes it.\n execution = await options.sandbox.run({\n argv: ['/bin/sh', '-c', args.command],\n policy: resolvedPolicy,\n correlationId,\n cwd: options.translator.toBackendPath(relative),\n signal: controller.signal,\n ...(options.env === undefined ? {} : { env: { ...options.env } }),\n })\n } catch (error) {\n clearTimeout(timeout)\n const outcome = (error as { outcome?: SandboxOutcome }).outcome\n // SRT refuses a divergent per-call network section BEFORE spawning. Preserve this\n // actionable typed admission error, not arbitrary untyped backend failures.\n const networkRefused = isInstanceOf(\n error,\n 'E_SANDBOX_NETWORK_GRANT_UNSUPPORTED',\n E_SANDBOX_NETWORK_GRANT_UNSUPPORTED\n )\n await emitCompletion({\n exitCode: null,\n failed: true,\n timedOut: false,\n denied: networkRefused || outcome?.kind === 'denied-by-policy' ? true : undefined,\n diagnostics: [\n ...(isError(error) ? [error.message] : [String(error)]),\n ...currentDiagnostics(correlationId),\n ],\n artifactRef: correlationId,\n })\n if (networkRefused) throw error\n if (outcome?.kind === 'denied-by-policy') throw new E_SANDBOX_REFUSED([narrate(outcome)])\n throw new E_SANDBOX_FAILED([\n narrate({\n kind: 'io-failure',\n detail: isError(error) ? error.message : String(error),\n }),\n ])\n }\n const storeWrite = Promise.resolve(ctx.storeRetrievableBytes(correlationId, merged))\n // Observe immediately: the store can reject while drains/poller are still running.\n // Keep the original promise so the terminal path below rethrows the SAME error.\n void storeWrite.catch(() => {})\n const seen = new Set<string>()\n const poll = (): void => {\n for (const denial of options.sandbox.diagnosticsFor(correlationId)) {\n if (!seen.has(denial)) {\n seen.add(denial)\n // Redacted because a denial is upstream TEXT and routinely names an absolute host path —\n // the one line in this stream the battery authors from someone else's words. The exit-code\n // and timeout lines below are numbers this battery formats, so they carry nothing to scrub.\n // This does NOT extend to the child's own stdout, which no field translation can reach.\n write(line(`[sandbox] denied: ${options.translator.redact(denial)} (observed after)`))\n }\n }\n }\n const drain = async (source: ReadableStream<Uint8Array>): Promise<void> => {\n const reader = source.getReader()\n try {\n for (;;) {\n const item = await reader.read()\n if (item.done) return\n write(item.value)\n poll()\n }\n } finally {\n reader.releaseLock()\n }\n }\n let polling = true\n const poller = (async (): Promise<void> => {\n while (polling) {\n await new Promise<void>((resolve) => setTimeout(resolve, 10))\n if (polling) poll()\n }\n })()\n let completed: Awaited<typeof execution.completed> | undefined\n let drainError: unknown\n try {\n await Promise.all([drain(execution.stdout), drain(execution.stderr)])\n completed = await execution.completed\n } catch (error) {\n drainError = error\n } finally {\n clearTimeout(timeout)\n polling = false\n await poller\n poll()\n if (timerFired) write(line(`[timed out after ${args.timeout_seconds}s]`))\n else if (completed && completed.exitCode !== 0)\n write(line(`Exit code: ${completed.exitCode}`))\n close()\n }\n if (drainError !== undefined) {\n // A post-spawn I/O failure (a stream erroring mid-drain) also settles the completion: the\n // child may have run, so it is a failed, non-denied outcome rather than a silent rejection.\n await emitCompletion({\n exitCode: completed?.exitCode ?? null,\n failed: true,\n timedOut: timerFired,\n diagnostics: [\n ...(isError(drainError) ? [drainError.message] : [String(drainError)]),\n ...currentDiagnostics(correlationId),\n ],\n })\n throw drainError\n }\n let reader: Awaited<typeof storeWrite>\n try {\n reader = await storeWrite\n } catch (error) {\n await emitCompletion({\n exitCode: completed?.exitCode ?? null,\n failed: true,\n timedOut: timerFired,\n diagnostics: [\n ...(isError(error) ? [error.message] : [String(error)]),\n ...currentDiagnostics(correlationId),\n ],\n })\n throw error\n }\n // The tool's return type is unchanged (the artifact); the completion travels only through the\n // callback. `killedBy` is the signal that ACTUALLY terminated the child, taken from the real\n // settlement (`completed.signalCode`, Node's `ChildProcess.signalCode`), NOT from the abort\n // REASON we wrote onto the controller: on a timeout the reason is an `AbortError` while the\n // enforcer runs `process.kill(-pid, 'SIGKILL')`, so reading the reason reported `'AbortError'`\n // for a child killed with SIGKILL (issue #49 follow-up). It is reported only when the child was\n // actually signal-killed; a normal exit has no `killedBy`. `timerFired` alone is not enough —\n // the child can win the race and exit cleanly — so the signal is the sole source of truth.\n const killedBy = completed?.signalCode ?? undefined\n await emitCompletion({\n exitCode: completed?.exitCode ?? null,\n failed: completed ? completed.failed : timerFired,\n timedOut: timerFired,\n ...(killedBy === undefined ? {} : { killedBy }),\n diagnostics: currentDiagnostics(correlationId),\n artifactRef: correlationId,\n })\n return new SpooledArtifact(reader)\n },\n })\n}\n","import { passesSchema } from '../validation'\nimport { validator } from '@nhtio/validation'\nimport type { SandboxPolicy, DerivedRules } from '../types'\n\n/** Policy boundary. `run` resolves on spawn and exposes live streams plus a later completion promise. */\nexport interface SandboxPolicyEnforcer {\n /** Whether this enforcer can enforce on the current platform. `false` (a browser tab, where SRT does not exist) raises `E_SANDBOX_UNSUPPORTED_ENV` at construction rather than degrading — a shim that enforces nothing reads as sandboxed. */\n isSupported(): boolean\n /** Whether this adapter adopted an already-enabled process-global sandbox rather than initializing it. */\n readonly adopted?: boolean\n /** Probe external prerequisites. A non-empty `errors` throws `E_SANDBOX_DEPENDENCY_MISSING`; `warnings` are surfaced through observability and are NOT fatal. */\n checkDependencies(): Promise<{ errors: string[]; warnings: string[] }>\n /**\n * Spawn under a narrowing policy; a non-zero exit is data, not a rejected promise.\n *\n * @remarks\n * When `op.signal` aborts, an implementation MUST terminate the spawned child (including a\n * child hidden behind a sandbox wrapper) and settle `completed`; it MUST NOT leave the child\n * running after the lifecycle owner has cancelled the invocation. The returned streams may end\n * as a consequence of termination, but `completed` remains the authoritative settlement signal.\n */\n run(op: {\n argv: string[]\n policy: SandboxPolicy\n correlationId: string\n cwd: string\n /**\n * The caller's own EXPLICIT environment values, applied LAST.\n *\n * @remarks\n * NOT the host-inheritance control. What a child inherits from the host is the ADAPTER's\n * decision, expressed as an allow-list the adapter owns (the Node/SRT one denies by default and\n * takes that allow-list at construction). This field is the other half of the picture: the\n * values the caller names itself. They may add names, or override inherited ones, and because\n * they are applied last they also win a collision with an allow-listed name.\n *\n * An adapter MUST NOT let `env` — or anything else — cause host variables BEYOND its allow-list\n * to reach the child. Concretely, it must not merge the rest of `process.env` back in on top,\n * and it must not treat the presence of `env` as a trigger to inherit more widely. Leaving these\n * semantics unstated is how the Node adapter came to spread the entire `process.env` into every\n * child while this field sat unused.\n */\n env?: Record<string, string>\n /**\n * Lifecycle cancellation for this child. Implementations must kill the spawned child and\n * settle `completed` when this signal aborts.\n */\n signal?: AbortSignal\n }): Promise<{\n stdout: ReadableStream<Uint8Array>\n stderr: ReadableStream<Uint8Array>\n /**\n * The child's terminal settlement. `signalCode` is the REAL signal that killed the child\n * (Node's `ChildProcess.signalCode`: `'SIGKILL'`, `'SIGTERM'`, …), and is OMITTED when the\n * child exited on its own. Additive and optional so an adapter that cannot surface it simply\n * leaves it off; a consumer must treat absence as \"not signal-killed\", never as a specific\n * signal.\n */\n completed: Promise<{ exitCode: number; failed: boolean; signalCode?: string }>\n }>\n /** Return the opaque derived snapshot used for drift validation. */\n effectivePolicy(): DerivedRules | undefined\n /** Retrieve diagnostics by correlation id, never by command text. */\n diagnosticsFor(correlationId: string): string[]\n /** Release what this enforcer OWNS. A no-op when it adopted a foreign sandbox — tearing down a manager we did not initialize would strip ACEs a host app depends on. */\n dispose(): Promise<void>\n}\n\n/** Duck-type schema. */\nexport const sandboxPolicyEnforcerSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (\n value !== null &&\n value !== undefined &&\n typeof (value as any).isSupported === 'function' &&\n typeof (value as any).checkDependencies === 'function' &&\n typeof (value as any).run === 'function' &&\n typeof (value as any).effectivePolicy === 'function' &&\n typeof (value as any).diagnosticsFor === 'function' &&\n typeof (value as any).dispose === 'function'\n )\n return value\n return helpers.error('any.invalid')\n })\n\n/** Structural guard. */\nexport const implementsSandboxPolicyEnforcer = (value: unknown): value is SandboxPolicyEnforcer =>\n passesSchema(sandboxPolicyEnforcerSchema, value)\n","import { passesSchema } from '../validation'\nimport { validator } from '@nhtio/validation'\nimport type { ListFrame } from '../types'\n\n/** Filesystem capability with no copy primitive; traversal is complete and terminal-framed. */\nexport interface SandboxFileSystem {\n /** Return metadata. A changed version token is evidence of change; equality is not a no-change guarantee. */\n stat(path: string): Promise<{\n size: number\n version: string\n kind: 'file' | 'dir' | 'symlink' | 'other'\n mtimeMs?: number\n ino?: number\n dev?: number\n }>\n /** Lazily yield every item, followed by exactly one mandatory done frame. */\n list(path: string, o: { maxDepth: number; signal?: AbortSignal }): AsyncIterable<ListFrame>\n /** Open a fresh, replayable byte stream; non-regular kinds are refused by adapters. */\n read(path: string, o?: { signal?: AbortSignal }): Promise<ReadableStream<Uint8Array>>\n /** Write bytes without imposing a battery-level size cap. */\n write(\n path: string,\n bytes: ReadableStream<Uint8Array> | Uint8Array,\n o?: { signal?: AbortSignal }\n ): Promise<void>\n /** Delete a path. Deletion is idempotent: deleting an absent path resolves. */\n delete?(path: string, o?: { signal?: AbortSignal }): Promise<void>\n /**\n * Move a path. MUST overwrite an existing destination (POSIX move semantics).\n * Dev-tools relies on this behaviour when breaking rename cycles.\n */\n rename?(from: string, to: string, o?: { signal?: AbortSignal }): Promise<void>\n /** Create a directory. */\n mkdir?(path: string, o?: { signal?: AbortSignal }): Promise<void>\n}\n\n/** Duck-type schema. */\nexport const sandboxFileSystemSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (\n value !== null &&\n value !== undefined &&\n typeof (value as any).stat === 'function' &&\n typeof (value as any).list === 'function' &&\n typeof (value as any).read === 'function' &&\n typeof (value as any).write === 'function'\n )\n return value\n return helpers.error('any.invalid')\n })\n\n/** Structural guard. */\nexport const implementsSandboxFileSystem = (value: unknown): value is SandboxFileSystem =>\n passesSchema(sandboxFileSystemSchema, value)\n","import { passesSchema } from '../validation'\nimport { validator } from '@nhtio/validation'\nimport type { HitFrame, PathFrame } from '../types'\n\n/** Search capability; every result is lazy, complete, and terminal-framed. */\nexport interface SandboxSearch {\n /**\n * Whether this adapter can CONTAIN symlinked descendants when `follow` is enabled.\n *\n * `rg --follow` traverses links whose targets never pass through the path translator, so an\n * uncontained backend turns `follow: true` into an unbounded read of wherever they point.\n * The tools layer cannot inspect what is behind this interface, so an adapter declares it:\n * omitted or `false` means the forged `search_files`/`find_files` schemas REJECT `follow: true`\n * outright rather than accepting it and failing at execution. Set it only if you have verified\n * containment; the bundled ripgrep adapter has not, and does not set it.\n */\n readonly supportsFollow?: boolean\n /** Lazily yield every whole matching line, then one done frame. */\n searchContent(o: {\n root: string\n pattern: string\n /**\n * Traversal depth. Omit for an unbounded scan; an explicit value must be a non-negative integer.\n *\n * @remarks\n * An adapter MUST NOT name a depth on its own initiative when omitted — the unbounded request is\n * the caller's choice, and `Number.MAX_SAFE_INTEGER` is a disguised cap, not an implementation of\n * it (issue #48).\n */\n maxDepth?: number\n /**\n * Maximum results to yield. Omit for an unbounded search; an explicit value MUST be an integer\n * >= 1, and adapters reject anything else.\n *\n * @remarks\n * Omission is the documented unbounded mode, NOT a default cap: every match is returned and the\n * scan finishes `{ kind: 'done', complete: true }`. There is deliberately no sentinel —`undefined`\n * cannot be confused with an explicit number, so `Infinity`/`NaN`/`0`/negatives stay rejections\n * even though they conceptually mean the same thing (issue #48).\n *\n * MEMORY: an unbounded search is collected by the adapter before results are yielded (rg's\n * stdout is buffered whole), so peak memory grows in proportion to the OUTPUT on very large\n * trees — an explicit `limit` truncates only after collection. Pass a `limit` (or `maxDepth`)\n * wherever the tree size is untrusted or unknown.\n */\n limit?: number\n ignoreCase?: boolean\n literal?: boolean\n glob?: string\n iglob?: string\n follow?: boolean\n hidden?: boolean\n noIgnore?: boolean\n signal?: AbortSignal\n }): AsyncIterable<HitFrame>\n /** Lazily yield every matching path, then one done frame. */\n findPaths(o: {\n root: string\n glob: string\n /**\n * Traversal depth. Omit for an unbounded scan; an explicit value must be a non-negative integer.\n *\n * @remarks\n * An adapter MUST NOT name a depth on its own initiative when omitted — see `searchContent`.\n */\n maxDepth?: number\n /**\n * Maximum results to yield. Omit for an unbounded search; an explicit value MUST be an integer\n * >= 1, and adapters reject anything else — see `searchContent` (issue #48).\n */\n limit?: number\n iglob?: string\n follow?: boolean\n hidden?: boolean\n noIgnore?: boolean\n signal?: AbortSignal\n }): AsyncIterable<PathFrame>\n}\n\n/** Duck-type schema. */\nexport const sandboxSearchSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (\n value !== null &&\n value !== undefined &&\n typeof (value as any).searchContent === 'function' &&\n typeof (value as any).findPaths === 'function'\n )\n return value\n return helpers.error('any.invalid')\n })\n\n/** Structural guard. */\nexport const implementsSandboxSearch = (value: unknown): value is SandboxSearch =>\n passesSchema(sandboxSearchSchema, value)\n","import { passesSchema } from '../validation'\nimport { validator } from '@nhtio/validation'\n\n/** Model-path boundary: normalises ergonomic paths while refusing unambiguous host escapes. */\nexport interface PathTranslator {\n /** Validate and convert a model path; leading separators mean the sandbox root. */\n toRelative(modelPath: string): Promise<string>\n /** Convert a validated relative path to an opaque backend locator. */\n toBackendPath(relative: string): string\n /** Scrub root and common host identifiers from battery-generated text. */\n redact(text: string): string\n /** The translator always inspects the resolved path and every parent for symlink components. */\n assertNoSymlinkComponents(relative: string): Promise<void>\n}\n\n/** Duck-type schema. */\nexport const pathTranslatorSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (\n value !== null &&\n value !== undefined &&\n typeof (value as any).toRelative === 'function' &&\n typeof (value as any).toBackendPath === 'function' &&\n typeof (value as any).redact === 'function' &&\n typeof (value as any).assertNoSymlinkComponents === 'function'\n )\n return value\n return helpers.error('any.invalid')\n })\n\n/** Structural guard. */\nexport const implementsPathTranslator = (value: unknown): value is PathTranslator =>\n passesSchema(pathTranslatorSchema, value)\n","import { passesSchema } from '../validation'\nimport { validator } from '@nhtio/validation'\nimport type { GuestLimits, GuestHandle } from '../types'\n\n/** Runtime boundary for a hardened guest realm; limits and capability declarations cross the boundary. */\nexport interface GuestRuntime {\n /** Spawn a guest with fully resolved hostile-realm limits and async capability stubs. */\n spawn(o: {\n modules: string[]\n globals: ReadonlyArray<{ name: string; kind: 'async-fn' }>\n limits: GuestLimits\n signal?: AbortSignal\n }): Promise<GuestHandle>\n}\n\n/** Duck-type schema. */\nexport const guestRuntimeSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (value !== null && value !== undefined && typeof (value as any).spawn === 'function')\n return value\n return helpers.error('any.invalid')\n })\n\n/** Structural guard. */\nexport const implementsGuestRuntime = (value: unknown): value is GuestRuntime =>\n passesSchema(guestRuntimeSchema, value)\n","import { passesSchema } from '../validation'\nimport { validator } from '@nhtio/validation'\n/** MIME resolver; `undefined` means the resolver declines and a later resolver may decide. */\nexport type MimeResolver = (ctx: {\n path: string\n declared?: string\n /** Read a bounded prefix only; this callback cannot read the whole file. */\n peek: (bytes: number) => Promise<Uint8Array>\n}) => string | undefined | Promise<string | undefined>\n/** MIME resolver schema. */\nexport const mimeResolverSchema = validator\n .any()\n .required()\n .custom((v, h) => (typeof v === 'function' ? v : h.error('any.invalid')))\n/** MIME resolver guard. */\nexport const implementsMimeResolver = (v: unknown): v is MimeResolver =>\n passesSchema(mimeResolverSchema, v)\n","import { passesSchema } from '../validation'\nimport { validator } from '@nhtio/validation'\n\n/** Artifact-class registry. Format constructors are lazy so unused parsers are never loaded. */\nexport interface ArtifactMinter {\n /** Return available formats and async constructors. */\n formats(): Promise<\n Array<{ id: string; mime: string[]; extensions: string[]; ctor: () => Promise<unknown> }>\n >\n}\n\n/** Duck-type schema. */\nexport const artifactMinterSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (value !== null && value !== undefined && typeof (value as any).formats === 'function')\n return value\n return helpers.error('any.invalid')\n })\n\n/** Structural guard. */\nexport const implementsArtifactMinter = (value: unknown): value is ArtifactMinter =>\n passesSchema(artifactMinterSchema, value)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,IAAM,wBACJ,OAAO,YAAY,eAAe,OAAO,QAAQ,aAAa,WAC1D,QAAQ,WACR;;AAGN,IAAa,mBAAmB,OAAO,YAAyD;CAE9F,KADiB,QAAQ,YAAY,gBAAgB,OACpC,SACf,MAAM,IAAI,qBAAA,0BAA0B,CAClC,8EACF,CAAC;CAGH,IAAI,CAAC,QAAQ,SAAS,YAAY,GAChC,MAAM,IAAI,qBAAA,0BAA0B,CAClC,+FACF,CAAC;CAGH,MAAM,eAAe,MAAM,QAAQ,SAAS,kBAAkB;CAC9D,MAAM,WAAW,OAAO,OAAO,CAAC,GAAG,aAAa,QAAQ,CAAC;CACzD,IAAI,aAAa,SAAS,SAAS,GACjC,QAAQ,YAAY;EAAE,MAAM;EAAuB;CAAS,CAAC;CAE/D,MAAM,sBAAsB,QAAQ,uBAAuB;CAE3D,MAAM,oBADwB,QAAQ,SAAS,gBAAgB,MAAM,KAAA,KAE1C,aAAa,OAAO,SAAS,KAAK,CAAC;CAC9D,IAAI,aAAa,OAAO,SAAS,KAAK,CAAC,QAAQ,0BAC7C,MAAM,IAAI,qBAAA,6BAA6B,CACrC,yCAAyC,aAAa,OAAO,KAAK,IAAI,GACxE,CAAC;CAEH,MAAM,gBAAgB,QAAQ,QAAQ,4BAA4B,iBAAiB;CACnF,MAAM,SAA2B;EAC/B,0BAA0B;EAC1B;EACA,YAAY,QAAQ,QAAQ,UAAU;EACtC,oBAAoB;EACpB,GAAI,QAAQ,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe,QAAQ,cAAc;CACxF;CACA,OAAO,OAAO,OAAO,M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UACvC,mBAAA,aAAa,sBAAsB,KAAK;;;;AClB1C,IAAa,qBAAqB,kBAAA,UAC/B,IAAI,EACJ,SAAS,EACT,QAAQ,OAAO,YAAY;CAC1B,IAAI,UAAU,QAAQ,UAAU,KAAA,KAAa,OAAQ,MAAc,UAAU,YAC3E,OAAO;CACT,OAAO,QAAQ,MAAM,aAAa;AACpC,CAAC;;AAGH,IAAa,0BAA0B,UACrC,mBAAA,aAAa,oBAAoB,KAAK;;;;ACjBxC,IAAa,qBAAqB,kBAAA,UAC/B,IAAI,EACJ,SAAS,EACT,QAAQ,GAAG,MAAO,OAAO,MAAM,aAAa,IAAI,EAAE,MAAM,aAAa,CAAE;;AAE1E,IAAa,0BAA0B,MACrC,mBAAA,aAAa,oBAAoB,CAAC;;;;ACJpC,IAAa,uBAAuB,kBAAA,UACjC,IAAI,EACJ,SAAS,EACT,QAAQ,OAAO,YAAY;CAC1B,IAAI,UAAU,QAAQ,UAAU,KAAA,KAAa,OAAQ,MAAc,YAAY,YAC7E,OAAO;CACT,OAAO,QAAQ,MAAM,aAAa;AACpC,CAAC;;AAGH,IAAa,4BAA4B,UACvC,mBAAA,aAAa,sBAAsB,KAAK"}
@@ -1,14 +1,14 @@
1
1
  import { a as passesSchema, i as asyncValidateOrThrow, n as isException, o as validateOrThrow } from "../exceptions-DRYLe-J4.mjs";
2
2
  import { n as isInstanceOf, t as isError } from "../guards-BEpY7lBI.mjs";
3
- import { L as E_TURN_GATE_ABORTED } from "../tokenizable-VB4Av8GF.mjs";
4
- import { p as Tool, t as SpooledArtifact } from "../spooled_artifact-Bw_7swIp.mjs";
3
+ import { z as E_TURN_GATE_ABORTED } from "../tokenizable-xPXj1AQX.mjs";
4
+ import { f as Tool, t as SpooledArtifact } from "../spooled_artifact-BkOe4-j-.mjs";
5
5
  import "../forge.mjs";
6
6
  import "../guards.mjs";
7
7
  import "../spooled_artifact.mjs";
8
8
  import { runToolGate } from "./tools/_shared.mjs";
9
9
  import { _ as isRejectedSandboxPath, a as guestLimitFloors, c as hostcallQuotasDefaults, d as implementsHostcallQuotas, f as implementsSandboxPolicy, g as createPathTranslator, h as createExistingSymlinkGuard, i as createSandboxEpoch, l as hostcallQuotasSchema, m as classifySandboxPathRejection, n as createModelPath, o as guestLimitsDefaults, p as sandboxPolicySchema, r as createModelWriteRoot, s as guestLimitsSchema, t as SandboxEpoch, u as implementsGuestLimits, v as normalizeSandboxPath } from "../types-BRG2MDAN.mjs";
10
10
  import { a as E_SANDBOX_NARROWING_UNSUPPORTED, c as E_SANDBOX_PATH_ESCAPE, d as E_SANDBOX_UNSUPPORTED_ENV, i as E_SANDBOX_GATE_REQUIRED, l as E_SANDBOX_POLICY_CONFLICT, n as E_SANDBOX_DEPENDENCY_MISSING, o as E_SANDBOX_NETWORK_GRANT_UNSUPPORTED, r as E_SANDBOX_FAILED, s as E_SANDBOX_NOT_INITIALIZED, t as E_INVALID_SANDBOX_CONFIG, u as E_SANDBOX_REFUSED } from "../exceptions-Cf1zCfzZ.mjs";
11
- import { a as DefaultArtifactMinter, c as defaultArtifactMinter, d as defaultMimeResolver, f as extensionMimeResolver, g as defaultSandboxNarrator, h as createSandboxMediaReader, i as narratingPath, l as DEFAULT_MIME_PEEK_BYTES, m as createSandboxMedia, n as descriptions, o as artifactConstructorForPath, p as resolveMime, r as forgeSandboxTools, s as constructorFromMinter, t as createSandboxTools, u as SANDBOX_EXTENSION_MIME } from "../tools-Vkfht7mU.mjs";
11
+ import { a as DefaultArtifactMinter, c as defaultArtifactMinter, d as defaultMimeResolver, f as extensionMimeResolver, g as defaultSandboxNarrator, h as createSandboxMediaReader, i as narratingPath, l as DEFAULT_MIME_PEEK_BYTES, m as createSandboxMedia, n as descriptions, o as artifactConstructorForPath, p as resolveMime, r as forgeSandboxTools, s as constructorFromMinter, t as createSandboxTools, u as SANDBOX_EXTENSION_MIME } from "../tools-geIlta3C.mjs";
12
12
  import { a as assertArgvValue, c as escapeShellArgs, d as quoteShellValue, f as validateAbsoluteBinaryPath, i as assertAllowedRipgrepFlag, l as escapeShellValue, n as DOUBLE_DASH_BINARIES, o as assertPosixBinShell, p as validateBinShell, r as POSIX_SHELLS, s as binaryHonorsDoubleDash, t as ALLOWED_RIPGREP_FLAGS, u as quoteShellArgs } from "../escape-WjKeWGgG.mjs";
13
13
  import { t as runSandboxConformance } from "../conformance-FncyAbRs.mjs";
14
14
  import { E_SES_EVALUATION_TIMEOUT, E_SES_HOST_LOCKDOWN_REQUIRED, E_SES_LOCKDOWN_REQUIRED, createCompartmentRuntime, createEvaluateJavascriptTool, createGuestRunner, createGuestRuntime, isGuestOutcome, resolveGuestLimits, resolveHostcallQuotas } from "./sandbox/js.mjs";
@@ -367,11 +367,19 @@ var createSandbox = async (options) => {
367
367
  * adapter does not raise that bound (and never sets `maxBuffer: Infinity`). The streaming path is
368
368
  * {@link createRunShellCommandTool}, which uses the policy-enforcer stream contract instead.
369
369
  *
370
+ * The adapter hands the invocation to {@link BinarySandbox.wrap} verbatim and runs what comes
371
+ * back: `inner.exec(await sandbox.wrap(invocation))`. The returned `cmd`/`args` are the complete
372
+ * wrapped argv, so the original `args` are not re-appended — a wrapper that wants them in the
373
+ * wrapped command puts them there itself. Quoting is therefore the wrapper's job, not this
374
+ * adapter's.
375
+ *
370
376
  * Bypass is an audit-only opt-out. Its predicate receives `cmd` only, never argv: callers must
371
377
  * allow only binaries safe with hostile arguments and must never allow an interpreter. Non-zero
372
378
  * exits remain data and are never thrown. Removing this wrapper call restores the inner executor.
379
+ *
380
+ * @param options - The wrapper, the inner executor, and the optional audit hooks.
381
+ * @returns A `BinaryExecutor` whose non-bypassed invocations go through `options.sandbox.wrap`.
373
382
  */
374
- /** Create a BinaryExecutor that wraps invocations unless an explicitly audited bypass applies. */
375
383
  var sandboxedExecutor = (options) => ({ async exec(invocation) {
376
384
  if (options.bypass?.(invocation.cmd)) {
377
385
  options.onSandbox?.({
@@ -381,15 +389,7 @@ var sandboxedExecutor = (options) => ({ async exec(invocation) {
381
389
  });
382
390
  return options.inner.exec(invocation);
383
391
  }
384
- const command = await quoteShellArgs([invocation.cmd, ...invocation.args]);
385
- const wrapped = await options.sandbox.wrap({
386
- ...invocation,
387
- command
388
- });
389
- return options.inner.exec({
390
- ...wrapped,
391
- cmd: wrapped.command
392
- });
392
+ return options.inner.exec(await options.sandbox.wrap(invocation));
393
393
  } });
394
394
  /** Emit a bypass through the canonical sink for consumers that do not retain the adapter. */
395
395
  var reportSandboxBypass = (sink, command) => emitBypass(sink, command);