@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.
- package/CHANGELOG.md +124 -1
- package/artifact_methods-BvoDGBnH.cjs +1 -0
- package/artifact_methods-q52ETLwI.mjs +1 -0
- package/batteries/artifacts/ecmascript.cjs +1 -1
- package/batteries/artifacts/ecmascript.mjs +1 -1
- package/batteries/artifacts/toon.cjs +1 -1
- package/batteries/artifacts/toon.mjs +1 -1
- package/batteries/artifacts/xml.cjs +1 -1
- package/batteries/artifacts/xml.mjs +1 -1
- package/batteries/artifacts/yaml.cjs +1 -1
- package/batteries/artifacts/yaml.mjs +1 -1
- package/batteries/artifacts.cjs +4 -4
- package/batteries/artifacts.mjs +4 -4
- package/batteries/dev-tools/forge.cjs +3 -3
- package/batteries/dev-tools/forge.mjs +3 -3
- package/batteries/dev-tools.cjs +2 -2
- package/batteries/dev-tools.mjs +2 -2
- package/batteries/encoding.cjs +7 -7
- package/batteries/encoding.mjs +7 -7
- package/batteries/generation/gemini/adapter.cjs +1 -1
- package/batteries/generation/gemini/adapter.mjs +1 -1
- package/batteries/generation/local_diffusion/adapter.cjs +1 -1
- package/batteries/generation/local_diffusion/adapter.mjs +1 -1
- package/batteries/generation/openai/adapter.cjs +1 -1
- package/batteries/generation/openai/adapter.mjs +1 -1
- package/batteries/llm/anthropic_messages/adapter.cjs +6 -6
- package/batteries/llm/anthropic_messages/adapter.mjs +6 -6
- package/batteries/llm/anthropic_messages/count_tokens.cjs +2 -2
- package/batteries/llm/anthropic_messages/count_tokens.mjs +1 -1
- package/batteries/llm/anthropic_messages/helpers.cjs +3 -3
- package/batteries/llm/anthropic_messages/helpers.mjs +3 -3
- package/batteries/llm/anthropic_messages/validation.cjs +2 -2
- package/batteries/llm/anthropic_messages/validation.mjs +2 -2
- package/batteries/llm/anthropic_messages.cjs +2 -2
- package/batteries/llm/anthropic_messages.mjs +2 -2
- package/batteries/llm/bedrock_converse/adapter.cjs +6 -6
- package/batteries/llm/bedrock_converse/adapter.mjs +6 -6
- package/batteries/llm/bedrock_converse/helpers.cjs +1 -1
- package/batteries/llm/bedrock_converse/helpers.mjs +1 -1
- package/batteries/llm/bedrock_converse/validation.cjs +2 -2
- package/batteries/llm/bedrock_converse/validation.mjs +2 -2
- package/batteries/llm/bedrock_converse.cjs +2 -2
- package/batteries/llm/bedrock_converse.mjs +2 -2
- package/batteries/llm/claude_code_cli/adapter.cjs +7 -7
- package/batteries/llm/claude_code_cli/adapter.mjs +7 -7
- package/batteries/llm/claude_code_cli/helpers.cjs +3 -3
- package/batteries/llm/claude_code_cli/helpers.mjs +3 -3
- package/batteries/llm/claude_code_cli/validation.cjs +2 -2
- package/batteries/llm/claude_code_cli/validation.mjs +2 -2
- package/batteries/llm/claude_code_cli.cjs +2 -2
- package/batteries/llm/claude_code_cli.mjs +2 -2
- package/batteries/llm/gemini_generate_content/adapter.cjs +7 -7
- package/batteries/llm/gemini_generate_content/adapter.mjs +7 -7
- package/batteries/llm/gemini_generate_content/helpers.cjs +1 -1
- package/batteries/llm/gemini_generate_content/helpers.mjs +1 -1
- package/batteries/llm/gemini_generate_content/validation.cjs +2 -2
- package/batteries/llm/gemini_generate_content/validation.mjs +2 -2
- package/batteries/llm/gemini_generate_content.cjs +2 -2
- package/batteries/llm/gemini_generate_content.mjs +2 -2
- package/batteries/llm/litert_lm/adapter.cjs +6 -6
- package/batteries/llm/litert_lm/adapter.mjs +6 -6
- package/batteries/llm/litert_lm/helpers.cjs +3 -3
- package/batteries/llm/litert_lm/helpers.mjs +3 -3
- package/batteries/llm/litert_lm/validation.cjs +2 -2
- package/batteries/llm/litert_lm/validation.mjs +2 -2
- package/batteries/llm/litert_lm.cjs +1 -1
- package/batteries/llm/litert_lm.mjs +1 -1
- package/batteries/llm/ollama/adapter.cjs +6 -6
- package/batteries/llm/ollama/adapter.mjs +6 -6
- package/batteries/llm/ollama/helpers.cjs +4 -4
- package/batteries/llm/ollama/helpers.mjs +4 -4
- package/batteries/llm/ollama/validation.cjs +2 -2
- package/batteries/llm/ollama/validation.mjs +2 -2
- package/batteries/llm/ollama.cjs +2 -2
- package/batteries/llm/ollama.mjs +2 -2
- package/batteries/llm/openai_chat_completions/adapter.cjs +6 -6
- package/batteries/llm/openai_chat_completions/adapter.mjs +6 -6
- package/batteries/llm/openai_chat_completions/helpers.cjs +4 -4
- package/batteries/llm/openai_chat_completions/helpers.mjs +4 -4
- package/batteries/llm/openai_chat_completions/validation.cjs +2 -2
- package/batteries/llm/openai_chat_completions/validation.mjs +2 -2
- package/batteries/llm/openai_chat_completions.cjs +2 -2
- package/batteries/llm/openai_chat_completions.mjs +2 -2
- package/batteries/llm/openai_responses/adapter.cjs +6 -6
- package/batteries/llm/openai_responses/adapter.mjs +6 -6
- package/batteries/llm/openai_responses/helpers.cjs +3 -3
- package/batteries/llm/openai_responses/helpers.mjs +3 -3
- package/batteries/llm/openai_responses/validation.cjs +2 -2
- package/batteries/llm/openai_responses/validation.mjs +2 -2
- package/batteries/llm/openai_responses.cjs +2 -2
- package/batteries/llm/openai_responses.mjs +2 -2
- package/batteries/llm/transformers_js/adapter.cjs +6 -6
- package/batteries/llm/transformers_js/adapter.mjs +6 -6
- package/batteries/llm/transformers_js/helpers.cjs +3 -3
- package/batteries/llm/transformers_js/helpers.mjs +3 -3
- package/batteries/llm/transformers_js/validation.cjs +2 -2
- package/batteries/llm/transformers_js/validation.mjs +2 -2
- package/batteries/llm/transformers_js.cjs +1 -1
- package/batteries/llm/transformers_js.mjs +1 -1
- package/batteries/llm/webllm_chat_completions/adapter.cjs +6 -6
- package/batteries/llm/webllm_chat_completions/adapter.mjs +6 -6
- package/batteries/llm/webllm_chat_completions/helpers.cjs +1 -1
- package/batteries/llm/webllm_chat_completions/helpers.mjs +1 -1
- package/batteries/llm/webllm_chat_completions/validation.cjs +2 -2
- package/batteries/llm/webllm_chat_completions/validation.mjs +2 -2
- package/batteries/llm/webllm_chat_completions.cjs +2 -2
- package/batteries/llm/webllm_chat_completions.mjs +2 -2
- package/batteries/llm.cjs +2 -2
- package/batteries/llm.mjs +2 -2
- package/batteries/media/contracts.cjs.map +1 -1
- package/batteries/media/contracts.d.ts +93 -2
- package/batteries/media/contracts.mjs.map +1 -1
- package/batteries/media/engines/execa_executor.cjs +285 -13
- package/batteries/media/engines/execa_executor.cjs.map +1 -1
- package/batteries/media/engines/execa_executor.d.ts +113 -8
- package/batteries/media/engines/execa_executor.mjs +285 -13
- package/batteries/media/engines/execa_executor.mjs.map +1 -1
- package/batteries/media/forge.cjs +4 -4
- package/batteries/media/forge.mjs +4 -4
- package/batteries/media/lint.cjs +1 -1
- package/batteries/media/lint.mjs +1 -1
- package/batteries/media.cjs +1 -1
- package/batteries/orchestration/dispatch_reasoner.cjs +4 -4
- package/batteries/orchestration/dispatch_reasoner.mjs +4 -4
- package/batteries/orchestration/executor.cjs +2 -2
- package/batteries/orchestration/executor.mjs +2 -2
- package/batteries/orchestration/forge.cjs +3 -3
- package/batteries/orchestration/forge.mjs +3 -3
- package/batteries/orchestration/validation.cjs +2 -2
- package/batteries/orchestration/validation.mjs +2 -2
- package/batteries/orchestration.cjs +3 -3
- package/batteries/orchestration.mjs +3 -3
- package/batteries/sandbox/contracts/policy_enforcer.d.ts +12 -6
- package/batteries/sandbox/executor.d.ts +28 -10
- package/batteries/sandbox/js.cjs +1 -1
- package/batteries/sandbox/js.mjs +1 -1
- package/batteries/sandbox/node/index.d.ts +1 -1
- package/batteries/sandbox/node/srt_enforcer.d.ts +74 -0
- package/batteries/sandbox/node.cjs +98 -5
- package/batteries/sandbox/node.cjs.map +1 -1
- package/batteries/sandbox/node.mjs +98 -6
- package/batteries/sandbox/node.mjs.map +1 -1
- package/batteries/sandbox/tools.cjs +1 -1
- package/batteries/sandbox/tools.mjs +1 -1
- package/batteries/sandbox.cjs +13 -13
- package/batteries/sandbox.cjs.map +1 -1
- package/batteries/sandbox.mjs +13 -13
- package/batteries/sandbox.mjs.map +1 -1
- package/batteries/skills/in_memory.cjs +1 -1
- package/batteries/skills.cjs +10 -10
- package/batteries/skills.mjs +9 -9
- package/batteries/tools/_shared.cjs +1 -1
- package/batteries/tools/_shared.mjs +1 -1
- package/batteries/tools/color.cjs +2 -2
- package/batteries/tools/color.mjs +2 -2
- package/batteries/tools/comparison.cjs +2 -2
- package/batteries/tools/comparison.mjs +2 -2
- package/batteries/tools/data_structure.cjs +2 -2
- package/batteries/tools/data_structure.mjs +2 -2
- package/batteries/tools/datetime_extended.cjs +3 -3
- package/batteries/tools/datetime_extended.mjs +3 -3
- package/batteries/tools/datetime_math.cjs +3 -3
- package/batteries/tools/datetime_math.mjs +3 -3
- package/batteries/tools/encoding.cjs +2 -2
- package/batteries/tools/encoding.mjs +2 -2
- package/batteries/tools/formatting.cjs +2 -2
- package/batteries/tools/formatting.mjs +2 -2
- package/batteries/tools/geo_basics.cjs +2 -2
- package/batteries/tools/geo_basics.mjs +2 -2
- package/batteries/tools/math.cjs +2 -2
- package/batteries/tools/math.mjs +2 -2
- package/batteries/tools/memory.cjs +5 -5
- package/batteries/tools/memory.mjs +5 -5
- package/batteries/tools/parsing.cjs +3 -3
- package/batteries/tools/parsing.mjs +3 -3
- package/batteries/tools/retrievables.cjs +5 -5
- package/batteries/tools/retrievables.mjs +5 -5
- package/batteries/tools/scrapper.cjs +1 -1
- package/batteries/tools/scrapper.mjs +1 -1
- package/batteries/tools/searxng.cjs +1 -1
- package/batteries/tools/searxng.mjs +1 -1
- package/batteries/tools/standing_instructions.cjs +3 -3
- package/batteries/tools/standing_instructions.mjs +3 -3
- package/batteries/tools/statistics.cjs +3 -3
- package/batteries/tools/statistics.mjs +3 -3
- package/batteries/tools/string_processing.cjs +2 -2
- package/batteries/tools/string_processing.mjs +2 -2
- package/batteries/tools/structured_data.cjs +2 -2
- package/batteries/tools/structured_data.mjs +2 -2
- package/batteries/tools/text_analysis.cjs +3 -3
- package/batteries/tools/text_analysis.mjs +3 -3
- package/batteries/tools/text_comparison.cjs +2 -2
- package/batteries/tools/text_comparison.mjs +2 -2
- package/batteries/tools/time.cjs +3 -3
- package/batteries/tools/time.mjs +3 -3
- package/batteries/tools/unit_conversion.cjs +2 -2
- package/batteries/tools/unit_conversion.mjs +2 -2
- package/batteries/tools.cjs +2 -2
- package/batteries/tools.mjs +2 -2
- package/batteries/validation.cjs +4 -4
- package/batteries/validation.mjs +4 -4
- package/batteries/vector/chroma.cjs +1 -1
- package/batteries/vector/chroma.mjs +1 -1
- package/batteries/vector/clickhouse.cjs +1 -1
- package/batteries/vector/clickhouse.mjs +1 -1
- package/batteries/vector/cloudflare.cjs +1 -1
- package/batteries/vector/cloudflare.mjs +1 -1
- package/batteries/vector/couchbase.cjs +1 -1
- package/batteries/vector/couchbase.mjs +1 -1
- package/batteries/vector/duckdb.cjs +1 -1
- package/batteries/vector/duckdb.mjs +1 -1
- package/batteries/vector/elasticsearch.cjs +1 -1
- package/batteries/vector/elasticsearch.mjs +1 -1
- package/batteries/vector/hnswlib.cjs +1 -1
- package/batteries/vector/hnswlib.mjs +1 -1
- package/batteries/vector/in_memory.cjs +1 -1
- package/batteries/vector/in_memory.mjs +1 -1
- package/batteries/vector/lancedb.cjs +1 -1
- package/batteries/vector/lancedb.mjs +1 -1
- package/batteries/vector/mariadb.cjs +1 -1
- package/batteries/vector/mariadb.mjs +1 -1
- package/batteries/vector/milvus.cjs +1 -1
- package/batteries/vector/milvus.mjs +1 -1
- package/batteries/vector/opensearch.cjs +1 -1
- package/batteries/vector/opensearch.mjs +1 -1
- package/batteries/vector/oracle23ai.cjs +1 -1
- package/batteries/vector/oracle23ai.mjs +1 -1
- package/batteries/vector/orama.cjs +1 -1
- package/batteries/vector/orama.mjs +1 -1
- package/batteries/vector/pgvector.cjs +1 -1
- package/batteries/vector/pgvector.mjs +1 -1
- package/batteries/vector/pinecone.cjs +1 -1
- package/batteries/vector/pinecone.mjs +1 -1
- package/batteries/vector/qdrant.cjs +1 -1
- package/batteries/vector/qdrant.mjs +1 -1
- package/batteries/vector/redis.cjs +1 -1
- package/batteries/vector/redis.mjs +1 -1
- package/batteries/vector/retrievable.cjs +1 -1
- package/batteries/vector/retrievable.mjs +1 -1
- package/batteries/vector/s3vectors.cjs +1 -1
- package/batteries/vector/s3vectors.mjs +1 -1
- package/batteries/vector/sqlite_vec.cjs +1 -1
- package/batteries/vector/sqlite_vec.mjs +1 -1
- package/batteries/vector/typesense.cjs +1 -1
- package/batteries/vector/typesense.mjs +1 -1
- package/batteries/vector/vespa.cjs +1 -1
- package/batteries/vector/vespa.mjs +1 -1
- package/batteries/vector/weaviate.cjs +1 -1
- package/batteries/vector/weaviate.mjs +1 -1
- package/batteries/vector.cjs +2 -2
- package/batteries/vector.mjs +2 -2
- package/batteries.cjs +9 -9
- package/batteries.mjs +9 -9
- package/{chat_common-DKw8FDol.mjs → chat_common-CeoHwSsz.mjs} +2 -2
- package/{chat_common-DKw8FDol.mjs.map → chat_common-CeoHwSsz.mjs.map} +1 -1
- package/{chat_common-vSxDBGgr.cjs → chat_common-DlIK1IAn.cjs} +2 -2
- package/{chat_common-vSxDBGgr.cjs.map → chat_common-DlIK1IAn.cjs.map} +1 -1
- package/{common-oI1niK9Z.mjs → common-B5maOoF_.mjs} +7 -7
- package/{common-oI1niK9Z.mjs.map → common-B5maOoF_.mjs.map} +1 -1
- package/{common-BcB05Isq.cjs → common-joo6vLu-.cjs} +7 -7
- package/{common-BcB05Isq.cjs.map → common-joo6vLu-.cjs.map} +1 -1
- package/common.cjs +7 -7
- package/common.mjs +7 -7
- package/{dispatch_runner-CTAI0RSs.cjs → dispatch_runner-BTaUtdtO.cjs} +5 -5
- package/{dispatch_runner-CTAI0RSs.cjs.map → dispatch_runner-BTaUtdtO.cjs.map} +1 -1
- package/{dispatch_runner-BZDXUe0G.mjs → dispatch_runner-DO7jo_gl.mjs} +5 -5
- package/{dispatch_runner-BZDXUe0G.mjs.map → dispatch_runner-DO7jo_gl.mjs.map} +1 -1
- package/dispatch_runner.cjs +1 -1
- package/dispatch_runner.mjs +1 -1
- package/{ecmascript-DOv8gVQ5.cjs → ecmascript-ChvxTCXz.cjs} +3 -3
- package/{ecmascript-DOv8gVQ5.cjs.map → ecmascript-ChvxTCXz.cjs.map} +1 -1
- package/{ecmascript-B9Z2C24U.mjs → ecmascript-bgwVyZG1.mjs} +3 -3
- package/{ecmascript-B9Z2C24U.mjs.map → ecmascript-bgwVyZG1.mjs.map} +1 -1
- package/eslint/rules.cjs +1 -1
- package/eslint/rules.mjs +1 -1
- package/eslint.cjs +2 -2
- package/eslint.mjs +2 -2
- package/exceptions.cjs +1 -1
- package/exceptions.mjs +1 -1
- package/forge.cjs +2 -2
- package/forge.mjs +2 -2
- package/guards.cjs +7 -7
- package/guards.mjs +7 -7
- package/{helpers-mbn_EsDV.mjs → helpers-C1T0DV8Q.mjs} +3 -3
- package/{helpers-mbn_EsDV.mjs.map → helpers-C1T0DV8Q.mjs.map} +1 -1
- package/{helpers-CiZnHmxC.cjs → helpers-D6ebO8Vc.cjs} +3 -3
- package/{helpers-CiZnHmxC.cjs.map → helpers-D6ebO8Vc.cjs.map} +1 -1
- package/index.cjs +10 -10
- package/index.mjs +10 -10
- package/{manifest-BPcrFRN4.cjs → manifest-DPYWN15l.cjs} +2 -2
- package/{manifest-BPcrFRN4.cjs.map → manifest-DPYWN15l.cjs.map} +1 -1
- package/mcp/adk-docs-corpus.json +2 -2
- package/package.json +407 -407
- package/{retrievable-CXTAUuuv.mjs → retrievable-CrGKx4sc.mjs} +3 -3
- package/{retrievable-CXTAUuuv.mjs.map → retrievable-CrGKx4sc.mjs.map} +1 -1
- package/{retrievable-BOuQSDHF.cjs → retrievable-DVkAglIv.cjs} +3 -3
- package/{retrievable-BOuQSDHF.cjs.map → retrievable-DVkAglIv.cjs.map} +1 -1
- package/{scrapper-lXnFGDi0.cjs → scrapper-Boc6kq2v.cjs} +4 -4
- package/{scrapper-lXnFGDi0.cjs.map → scrapper-Boc6kq2v.cjs.map} +1 -1
- package/{scrapper-BCdUm8c8.mjs → scrapper-D2Gy9Jhv.mjs} +4 -4
- package/{scrapper-BCdUm8c8.mjs.map → scrapper-D2Gy9Jhv.mjs.map} +1 -1
- package/{searxng-N7qu6dA-.cjs → searxng-DOy3eBDH.cjs} +4 -4
- package/{searxng-N7qu6dA-.cjs.map → searxng-DOy3eBDH.cjs.map} +1 -1
- package/{searxng-B-LdaVUP.mjs → searxng-cCb0lAcN.mjs} +4 -4
- package/{searxng-B-LdaVUP.mjs.map → searxng-cCb0lAcN.mjs.map} +1 -1
- package/server.json +2 -2
- package/skills/adk-assembly/SKILL.md +2 -2
- package/{spooled_artifact-Bw_7swIp.mjs → spooled_artifact-BkOe4-j-.mjs} +731 -731
- package/spooled_artifact-BkOe4-j-.mjs.map +1 -0
- package/{spooled_artifact-DZXsP4s1.cjs → spooled_artifact-BoYsldvO.cjs} +730 -730
- package/spooled_artifact-BoYsldvO.cjs.map +1 -0
- package/spooled_artifact.cjs +2 -2
- package/spooled_artifact.mjs +2 -2
- package/{spooled_markdown_artifact-vd6eNtIP.mjs → spooled_markdown_artifact-Dnl-lCGv.mjs} +3 -3
- package/{spooled_markdown_artifact-vd6eNtIP.mjs.map → spooled_markdown_artifact-Dnl-lCGv.mjs.map} +1 -1
- package/{spooled_markdown_artifact-Bo0u8cRS.cjs → spooled_markdown_artifact-DzbydBel.cjs} +3 -3
- package/{spooled_markdown_artifact-Bo0u8cRS.cjs.map → spooled_markdown_artifact-DzbydBel.cjs.map} +1 -1
- package/{thought-CxSaF6Xf.mjs → thought-BrQt6HAb.mjs} +3 -3
- package/{thought-CxSaF6Xf.mjs.map → thought-BrQt6HAb.mjs.map} +1 -1
- package/{thought-C12mqaKQ.cjs → thought-CXsVh5hS.cjs} +3 -3
- package/{thought-C12mqaKQ.cjs.map → thought-CXsVh5hS.cjs.map} +1 -1
- package/{tokenizable-BcodRtoW.cjs → tokenizable-DDIdXbJN.cjs} +29 -29
- package/{tokenizable-BcodRtoW.cjs.map → tokenizable-DDIdXbJN.cjs.map} +1 -1
- package/{tokenizable-VB4Av8GF.mjs → tokenizable-xPXj1AQX.mjs} +30 -30
- package/{tokenizable-VB4Av8GF.mjs.map → tokenizable-xPXj1AQX.mjs.map} +1 -1
- package/{tool_call-Cfaj-6zK.mjs → tool_call-8crmZsO8.mjs} +4 -4
- package/{tool_call-Cfaj-6zK.mjs.map → tool_call-8crmZsO8.mjs.map} +1 -1
- package/{tool_call-CsBOpKsg.cjs → tool_call-NvQcPf5d.cjs} +4 -4
- package/{tool_call-CsBOpKsg.cjs.map → tool_call-NvQcPf5d.cjs.map} +1 -1
- package/{tools-BjHXlDlV.cjs → tools-BHc8qB5I.cjs} +6 -6
- package/{tools-BjHXlDlV.cjs.map → tools-BHc8qB5I.cjs.map} +1 -1
- package/{tools-Vkfht7mU.mjs → tools-geIlta3C.mjs} +6 -6
- package/{tools-Vkfht7mU.mjs.map → tools-geIlta3C.mjs.map} +1 -1
- package/{toon-BSTQnHed.mjs → toon-BA9Q7NHG.mjs} +5 -5
- package/{toon-BSTQnHed.mjs.map → toon-BA9Q7NHG.mjs.map} +1 -1
- package/{toon-5c9ceKiU.cjs → toon-C8IFssRi.cjs} +5 -5
- package/{toon-5c9ceKiU.cjs.map → toon-C8IFssRi.cjs.map} +1 -1
- package/{turn_runner--tsMLLx4.cjs → turn_runner-A-vpLUvj.cjs} +5 -5
- package/{turn_runner--tsMLLx4.cjs.map → turn_runner-A-vpLUvj.cjs.map} +1 -1
- package/{turn_runner-BHHD6h77.mjs → turn_runner-BmVXcBZ2.mjs} +5 -5
- package/{turn_runner-BHHD6h77.mjs.map → turn_runner-BmVXcBZ2.mjs.map} +1 -1
- package/turn_runner.cjs +1 -1
- package/turn_runner.mjs +1 -1
- package/{xml-CYseDztH.mjs → xml-B1JIGLpU.mjs} +5 -5
- package/{xml-CYseDztH.mjs.map → xml-B1JIGLpU.mjs.map} +1 -1
- package/{xml-DTOnPN52.cjs → xml-Cu7ZvgBQ.cjs} +5 -5
- package/{xml-DTOnPN52.cjs.map → xml-Cu7ZvgBQ.cjs.map} +1 -1
- package/{yaml-BPBoiOjx.mjs → yaml-1mP4uxdf.mjs} +5 -5
- package/{yaml-BPBoiOjx.mjs.map → yaml-1mP4uxdf.mjs.map} +1 -1
- package/{yaml-CMrbNWLc.cjs → yaml-BlB29N68.cjs} +5 -5
- package/{yaml-CMrbNWLc.cjs.map → yaml-BlB29N68.cjs.map} +1 -1
- package/artifact_methods-Cg0go7Q4.mjs +0 -1
- package/artifact_methods-Dtf4-3C-.cjs +0 -1
- package/spooled_artifact-Bw_7swIp.mjs.map +0 -1
- package/spooled_artifact-DZXsP4s1.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.cjs","names":[],"sources":["../../../src/batteries/sandbox/node/srt_enforcer.ts","../../../src/batteries/sandbox/node/search_ripgrep.ts"],"sourcesContent":["import { statSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { spawn } from 'node:child_process'\nimport { isObject } from '@nhtio/adk/guards'\nimport { quoteShellArgs, validateAbsoluteBinaryPath, validateBinShell } from '../escape'\nimport { derivedRulesFromSrt, primeGlobMatcher, reproduceMandatoryDeny } from './fs_node'\nimport {\n E_INVALID_SANDBOX_CONFIG,\n E_SANDBOX_UNSUPPORTED_ENV,\n E_SANDBOX_POLICY_CONFLICT,\n E_SANDBOX_NETWORK_GRANT_UNSUPPORTED,\n} from '../exceptions'\nimport type { SandboxPolicy, DerivedRules } from '../types'\nimport type { SandboxPolicyEnforcer } from '../contracts/policy_enforcer'\n\ntype SrtManager = {\n initialize(config: SrtConfig): Promise<void>\n isSupportedPlatform(): boolean\n isSandboxingEnabled(): boolean\n checkDependenciesAsync(): Promise<{ errors: string[]; warnings: string[] }>\n wrapWithSandboxArgv(\n command: string,\n shell?: string,\n custom?: unknown,\n signal?: AbortSignal,\n cwd?: string,\n options?: { commandId?: string }\n ): Promise<{ argv: string[]; env: Record<string, string> }>\n getFsReadConfig(): { denyOnly: string[]; allowWithinDeny?: string[] }\n getFsWriteConfig(): { allowOnly: string[]; denyWithinAllow: string[] }\n getNetworkRestrictionConfig(): {\n allowedHosts?: string[]\n deniedHosts?: string[]\n }\n getConfig(): SrtConfig | undefined\n getSandboxViolationStore(): {\n getViolationsForCommand(command: string): unknown[]\n }\n reset(): Promise<void>\n}\ntype SrtConfig = {\n filesystem: Record<string, unknown>\n network?: Record<string, unknown>\n /** SRT's Linux mandatory-deny scan depth is session-level. */\n mandatoryDenySearchDepth?: number\n git?: { safeDirectories: string[] }\n /** Top-level and session-level: SRT reads this from the config `initialize()` stored, not per call. */\n enableWeakerNestedSandbox?: boolean\n bwrapPath?: string\n socatPath?: string\n}\n\nconst unsupported = (): never => {\n throw new E_SANDBOX_UNSUPPORTED_ENV([\n `SRT sandbox is unavailable on ${process.platform}; use WSL2 or the SES browser path`,\n ])\n}\n\nconst json = (value: unknown): string => JSON.stringify(value)\n\n/**\n * Why a per-call policy's network section is not the session baseline, or an empty list when it\n * EQUALS the baseline.\n *\n * @remarks\n * SRT enforces network allow/deny per REQUEST against the process-global SESSION config, never the\n * per-call `customConfig`: its mux proxy is started once at `initialize()` and `filterNetworkRequest`\n * reads `config.network.*` on every request (see the docs page for the source receipts). An\n * embedder hook exists — `network.filterRequest` and the `initialize()` ask callback — but neither\n * can scope enforcement to one child: the ask callback is handed only `{host, port}`, is suppressed\n * entirely while `strictAllowlist` is set (which this battery always sets), and its identity input\n * (the proxy username) is client-controlled and forgeable; `filterRequest` runs only AFTER the\n * session list has allowed a host, so it can deny within the list but never grant beyond it. A\n * per-call network section that differs from the session one — WIDER or NARROWER — would therefore be\n * silently ignored at enforcement time.\n *\n * Refusing every divergence turns that silent ignore into a typed, immediate error. Equality is\n * exact: the same `disabled` flag, and — compared as SETS, so order does not matter — the same\n * allowed and denied domain patterns and the same denial reasons. `deniedDomainReasons` is read from\n * the LIVE session config (`manager.getConfig()`), which is what SRT's filter actually consults.\n */\nconst networkDivergence = (\n baseline: DerivedRules,\n policy: SandboxPolicy,\n sessionReasons: Readonly<Record<string, string>>\n): readonly string[] => {\n // A disabled policy may not carry domains (`mapPolicy` throws for that combination), so its\n // canonical section is just the flag. A disabled BASELINE is unrestricted by definition, so it has\n // no domain lists or reasons to compare against.\n const policyDisabled = Boolean(policy.network.disabled)\n const policyAllowed = policyDisabled ? [] : nonEmpty(policy.network.allowedDomains)\n const policyDenied = policyDisabled ? [] : nonEmpty(policy.network.deniedDomains)\n const policyReasons = policyDisabled ? {} : { ...(policy.network.deniedDomainReasons ?? {}) }\n const baselineDisabled = baseline.network.disabled\n const baselineAllowed = baselineDisabled ? [] : baseline.network.allowedDomains\n const baselineDenied = baselineDisabled ? [] : baseline.network.deniedDomains\n const baselineReasons = baselineDisabled ? {} : sessionReasons\n\n const differences: string[] = []\n if (policyDisabled !== baselineDisabled)\n differences.push(`disabled ${baselineDisabled} → ${policyDisabled}`)\n if (!sameSet(asSet(policyAllowed), asSet(baselineAllowed)))\n differences.push(`allowedDomains ${json(baselineAllowed)} → ${json(policyAllowed)}`)\n if (!sameSet(asSet(policyDenied), asSet(baselineDenied)))\n differences.push(`deniedDomains ${json(baselineDenied)} → ${json(policyDenied)}`)\n if (!sameReasons(policyReasons, baselineReasons))\n differences.push(`deniedDomainReasons ${json(baselineReasons)} → ${json(policyReasons)}`)\n return differences\n}\nconst nonEmpty = (v: readonly string[] | undefined): string[] => [...(v ?? [])]\nconst asSet = (v: readonly string[]): ReadonlySet<string> => new Set(v)\nconst sameSet = (a: ReadonlySet<string>, b: ReadonlySet<string>): boolean =>\n a.size === b.size && [...a].every((item) => b.has(item))\nconst sameReasons = (\n a: Readonly<Record<string, string>>,\n b: Readonly<Record<string, string>>\n): boolean => {\n const aKeys = Object.keys(a)\n return aKeys.length === Object.keys(b).length && aKeys.every((key) => b[key] === a[key])\n}\n/** Coerce an arbitrary upstream value into the string→string denial-reason map SRT expects. */\nconst reasonMap = (value: unknown): Record<string, string> =>\n isObject(value)\n ? Object.fromEntries(\n Object.entries(value).filter(\n (entry): entry is [string, string] => typeof entry[1] === 'string'\n )\n )\n : {}\n\n/**\n * Host variables a sandboxed child inherits when the caller names no allow-list.\n *\n * @remarks\n * `PATH` ONLY, and it is the minimum rather than a convenience. The ripgrep searcher spawns `rg` by\n * BARE NAME, so with no `PATH` the child sees only the one a shell synthesises\n * (`/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.`) — which does not contain `/opt/homebrew/bin` or a Nix\n * profile, so `search_files` would fail as `io-failure` on any such host and present as *\"the search\n * tool is broken\"* rather than as a configuration error.\n *\n * `PATH` is not a credential: a model that runs `env` learns where binaries live, not a secret. Every\n * genuinely sensitive variable — and `HOME`, `USER`, `TMPDIR`, which leak host layout — stays out.\n */\nconst DEFAULT_ENV_ALLOW_LIST: readonly string[] = ['PATH']\n\n/** POSIX environment-variable names. Anything else could not be exported by a shell anyway. */\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/\n\n/**\n * Resolve the host half of a sandboxed child's environment ONCE, at construction.\n *\n * @remarks\n * DENY BY DEFAULT. Before this existed the enforcer spread the entire `process.env` into every child,\n * so a model directing the shell's argv could run `env` and read the host's credentials straight back\n * into its own context — which no filesystem or network policy prevents, because the secret arrives in\n * the tool result rather than over the wire.\n *\n * The allow-list REPLACES this default rather than extending it; that is stated on the option, because\n * the opposite assumption is the natural one and would silently drop `PATH`.\n *\n * @param options - The enforcer's construction options.\n * @returns The host variables to seed the child's environment with.\n */\nconst resolveHostEnv = (options: SrtEnforcerOptions): Record<string, string> => {\n if (options.inheritHostEnv === true) {\n const all: Record<string, string> = {}\n for (const [name, value] of Object.entries(process.env))\n if (value !== undefined) all[name] = value\n return all\n }\n const names = options.envAllowList ?? DEFAULT_ENV_ALLOW_LIST\n const picked: Record<string, string> = {}\n for (const name of names) {\n if (!ENV_NAME.test(name))\n throw new E_INVALID_SANDBOX_CONFIG([\n `envAllowList entry ${JSON.stringify(name)} is not a valid environment variable name`,\n ])\n const value = process.env[name]\n if (value !== undefined) picked[name] = value\n }\n return picked\n}\n\n/**\n * Whether `<cwd>/.git` is a real DIRECTORY.\n *\n * @remarks\n * Load-bearing on Linux only: upstream pushes the workspace-root `.git/hooks` and `.git/config` deny\n * entries just when `.git` is a directory, because in a worktree it is a FILE and denying it would\n * make bubblewrap fail. Treating a worktree as a directory would deny what the profile permits.\n */\nconst dotGitIsDirectory = (cwd: string): boolean => {\n try {\n return statSync(resolve(cwd, '.git')).isDirectory()\n } catch {\n return false\n }\n}\n\n/**\n * The sole ADK-to-SRT translation point. Keep the upstream type behind this local firewall.\n *\n * @remarks\n * `runtime` carries ADAPTER-level settings that are deliberately absent from `SandboxPolicy`. That\n * type is ADK-owned, SRT-neutral vocabulary — naming an SRT feature in it would make the firewall\n * nominal and leave a non-SRT enforcer unable to implement the contract — so an SRT-specific switch\n * belongs on the adapter's own options, exactly as `binShell` already does.\n */\nconst mapPolicy = (\n policy: SandboxPolicy,\n runtime: {\n enableWeakerNestedSandbox?: boolean\n bwrapPath?: string\n socatPath?: string\n } = {}\n): SrtConfig => {\n const fs = policy.filesystem\n const net = policy.network\n if (\n net.disabled &&\n (net.deniedDomains?.length ||\n Object.keys(net.deniedDomainReasons ?? {}).length ||\n (net.allowedDomains && !(net.allowedDomains.length === 1 && net.allowedDomains[0] === '*')))\n )\n throw new E_INVALID_SANDBOX_CONFIG(['network.disabled contradicts network domain restrictions'])\n const allowedDomains = net.disabled ? ['*'] : nonEmpty(net.allowedDomains)\n const deniedDomains = net.disabled ? [] : nonEmpty(net.deniedDomains)\n const deniedDomainReasons = net.disabled ? {} : { ...(net.deniedDomainReasons ?? {}) }\n return {\n ...(fs.mandatoryDenySearchDepth !== undefined\n ? { mandatoryDenySearchDepth: fs.mandatoryDenySearchDepth }\n : {}),\n // Emitted only when enabled, so an untouched configuration is byte-identical to before this\n // option existed — a drift snapshot taken either side of the upgrade compares equal.\n ...(runtime.enableWeakerNestedSandbox === true ? { enableWeakerNestedSandbox: true } : {}),\n ...(runtime.bwrapPath !== undefined ? { bwrapPath: runtime.bwrapPath } : {}),\n ...(runtime.socatPath !== undefined ? { socatPath: runtime.socatPath } : {}),\n filesystem: {\n ...(fs.disabled ? { disabled: true } : {}),\n denyRead: nonEmpty(fs.denyRead),\n allowRead: nonEmpty(fs.allowRead),\n allowWrite: nonEmpty(fs.allowWrite),\n denyWrite: nonEmpty(fs.denyWrite),\n allowGitConfig: fs.allowGitConfig ?? false,\n },\n // SRT keys network restriction by presence of this object. There is no schema-valid allow-all\n // domain pattern, so disabled deliberately omits the key instead of emitting the rejected '*'.\n ...(!net.disabled\n ? {\n network: {\n allowedDomains,\n deniedDomains,\n deniedDomainReasons,\n strictAllowlist: true,\n allowLocalBinding: false,\n allowUnixSockets: [],\n allowMachLookup: [],\n },\n }\n : {}),\n git: {\n safeDirectories: nonEmpty(fs.gitSafeDirectories ?? [process.cwd()]),\n },\n }\n}\n\nconst toWeb = (stream: NodeJS.ReadableStream): ReadableStream<Uint8Array> =>\n (\n ReadableStream as unknown as {\n from?: (x: unknown) => ReadableStream<Uint8Array>\n }\n ).from\n ? (\n ReadableStream as unknown as {\n from: (x: unknown) => ReadableStream<Uint8Array>\n }\n ).from(stream)\n : new ReadableStream({\n start(controller) {\n stream.on('data', (x: Buffer) => controller.enqueue(new Uint8Array(x)))\n stream.on('end', () => controller.close())\n stream.on('error', (e) => controller.error(e))\n },\n })\n\n/** Options for {@link srtEnforcer}. */\n/**\n * Whether an enforcer in THIS process performed the `initialize()` that is currently in force.\n *\n * @remarks\n * UPSTREAM'S OWN FLAG CANNOT ANSWER THIS. `isSandboxingEnabled()` is literally `config !== undefined`\n * (`sandbox-manager.js:672-675`) and `reset()` clears `managerContext`, the proxies, the registries —\n * **but never `config`**. So after any reset the flag stays `true` forever, and an enforcer that\n * trusted it would \"adopt\" a sandbox that is no longer in force, silently reporting a stale policy\n * and refusing to re-initialise. Verified: initialize, reset, and `isSandboxingEnabled()` is still\n * `true`.\n *\n * We therefore track what WE established. `true` here means this module owns the live session, so a\n * subsequent construction must re-initialise rather than adopt. `false` with upstream reporting\n * enabled means somebody else got there first — the genuine adoption case.\n */\nlet selfInitialized = false\n\n/**\n * Whether the session THIS module established is still claimed by a live enforcer.\n *\n * @remarks\n * FIRST-WRITER-WINS IS ENFORCED HERE, not only in the manager. `manager.ts` admits or refuses a\n * second handle by comparing policies — but that check runs AFTER `srtEnforcer()` has already\n * constructed, and construction is what touches the process-global. So a reset-and-reinitialise in the\n * constructor would tear down a live policy before anything could refuse it: caller 2 widens the real\n * sandbox, the manager then throws, and caller 1 carries on against a baseline that is no longer in\n * force. The refusal would arrive after the damage.\n *\n * `claimed` is therefore set when we initialise and cleared only by `dispose()`. While it is `true`,\n * re-initialising is refused outright; once cleared, the next construction may re-establish a session,\n * which is what makes sequential owned handles work.\n */\nlet selfSessionClaimed = false\n\n/**\n * Relinquish this module's ownership marker.\n *\n * @remarks\n * TEST SEAM, and a narrow one. The marker exists because upstream's `isSandboxingEnabled()` is\n * `config !== undefined` and `reset()` never clears `config` — so after the first `initialize()` the\n * flag is permanently `true` and cannot by itself distinguish *\"a session we established\"* from\n * *\"somebody else's\"*. Ownership therefore persists for the life of the module, which is correct in\n * production (a process that initialised once keeps re-initialising its own session) but makes the\n * ADOPTION branch unreachable in a test file that has already constructed an owned enforcer.\n *\n * Production code has no reason to call this: relinquishing ownership while a session we established\n * is still live would make the next construction adopt it and refuse to re-initialise.\n */\nexport const releaseSrtOwnershipForTests = (): void => {\n selfInitialized = false\n selfSessionClaimed = false\n}\n\n/** Construction options for {@link srtEnforcer}. */\nexport type SrtEnforcerOptions = {\n /**\n * Absolute path to the POSIX shell used to invoke wrapped commands. Defaults to `/bin/bash`.\n *\n * @remarks\n * Validated at construction in TWO checks, both required: it must be ABSOLUTE (a bare `bash` passes\n * any basename test while remaining `PATH`-dependent — the exact hazard the absolute default\n * avoids), and its basename must be on the allow-list (`sh`, `bash`, `dash`, `zsh`, `ksh`) — the\n * shells whose quoting the single escaper is correct for. An allow-list rather than a deny-list is\n * deliberate: `fish` and `nu` are POSIX-ish enough to look safe and different enough to break\n * single-quote escaping, so an unverified shell must fail closed.\n */\n binShell?: string\n /**\n * The ADK-owned policy to enforce.\n *\n * @remarks\n * Mapped to SRT's config inside this module and nowhere else. The derived baseline is captured\n * immediately after `initialize()`, because `SandboxManager` is a process-global singleton whose\n * SECOND `initialize()` is a no-op — a later call with a different policy silently keeps the first.\n */\n policy: SandboxPolicy\n /**\n * Host environment variable NAMES a sandboxed child may inherit. Defaults to `['PATH']`.\n *\n * @remarks\n * The child inherits NOTHING from the host beyond these names. That default is deliberate: a model\n * that can direct the shell's argv can run `env`, so anything inherited is readable back into its\n * context — and no filesystem or network policy stops it, because the value arrives in the tool\n * result rather than over the wire.\n *\n * **This REPLACES the default, it does not extend it.** A caller who needs `CARGO_HOME` and still\n * wants binaries to resolve must pass BOTH: `['PATH', 'CARGO_HOME']`. Passing `['CARGO_HOME']` alone\n * drops `PATH`, which breaks `search_files` on any host where `rg` lives outside `/usr/bin`.\n *\n * An entry that is not a valid POSIX environment-variable name throws `E_INVALID_SANDBOX_CONFIG` at\n * construction rather than being skipped, so a typo surfaces as a startup error instead of a\n * variable that silently never arrives.\n */\n envAllowList?: readonly string[]\n /**\n * Pass the ENTIRE host environment to sandboxed children. Defaults to `false`.\n *\n * @remarks\n * The escape hatch for a deployment that genuinely needs ambient configuration, and it is worth\n * being blunt about what it re-opens: **every secret in the host process becomes readable by the\n * model**, because `run_shell_command` exists precisely to run commands the model chose and `env` is\n * one of them. Prefer naming what you need in `envAllowList`.\n */\n inheritHostEnv?: boolean\n /**\n * Absolute path to a Linux bubblewrap wrapper or binary. SRT reads it from the config passed to\n * `initialize()`; on the Linux launch path it becomes argv[0] of the bwrap command\n * (`linux-sandbox-utils.js:1539`). A wrapper script placed at this path therefore receives every\n * bwrap argument and can strip or rewrite options such as `--unshare-net`. On Linux a nonexistent\n * path fails in SRT's `initialize()`; on macOS it is neither validated nor used.\n */\n bwrapPath?: string\n /**\n * Absolute path to a Linux socat binary or wrapper. SRT passes it to `initializeLinuxNetworkBridge`\n * on Linux. A nonexistent path fails in SRT's `initialize()`; on macOS it is neither validated nor\n * used.\n */\n socatPath?: string\n /**\n * Enable SRT's weaker nested-sandbox mode, for running inside an unprivileged container.\n *\n * @remarks\n * Bubblewrap cannot mount a fresh `/proc` inside an unprivileged container, so the sandbox fails to\n * start at all — the symptom is `apply-seccomp: write /proc/self/uid_map: Operation not permitted`\n * with exit 1, an empty stdout and NO diagnostics, which is indistinguishable from a policy denial.\n * This flag makes the inner sandbox bind-mount the container's EXISTING `/proc` instead.\n *\n * **It considerably weakens the boundary**, in upstream's own words: the bind-mounted `/proc`\n * exposes process information a fresh mount would hide. Only enable it when the OUTER container\n * already provides the isolation you need — it trades inner isolation for the sandbox running at all.\n *\n * Session-level: SRT reads it from the config given to `initialize()`, never per call.\n */\n enableWeakerNestedSandbox?: boolean\n}\n\n/**\n * Construct the SRT-backed policy enforcer — the OS boundary.\n *\n * @remarks\n * REFUSES rather than degrades on an unsupported platform: native `win32` throws\n * `E_SANDBOX_UNSUPPORTED_ENV` naming WSL2, because Windows folds all four filesystem-policy lists\n * case-insensitively and throws on per-exec allows. A half-built branch there would be a DIVERGENT\n * boundary rather than a limited one, so there is deliberately no native-Windows evaluator.\n *\n * `run()` resolves on SPAWN with live streams plus a separate `completed` promise, never a settled\n * exit code. That split is not stylistic: one promise cannot both hand over unread child streams AND\n * carry an exit code, because settling requires the streams to have ended and they cannot end before\n * someone drains them. A caller MUST drain both concurrently — pipe buffers are per-fd, so draining\n * one to completion first can block the other and hang the child.\n *\n * @param options - Shell and policy configuration.\n * @returns An enforcer whose derived baseline is already captured.\n */\nexport const srtEnforcer = async (options: SrtEnforcerOptions): Promise<SandboxPolicyEnforcer> => {\n if (process.platform !== 'darwin' && process.platform !== 'linux') return unsupported()\n const binShell = validateBinShell(options.binShell)\n const bwrapPath = validateAbsoluteBinaryPath(options.bwrapPath, 'bwrapPath')\n const socatPath = validateAbsoluteBinaryPath(options.socatPath, 'socatPath')\n // Resolved ONCE: the allow-list is fixed for the enforcer's life, so re-picking per spawn would only\n // add a chance for the two to disagree. Validation throws here, at construction, so a typo'd variable\n // name is a startup error rather than a variable that silently never arrives.\n const hostEnv = resolveHostEnv(options)\n const srt = (await import('@anthropic-ai/sandbox-runtime')) as unknown as {\n SandboxManager: SrtManager\n }\n const manager = srt.SandboxManager\n // SandboxManager is process-global and first-writer-wins. Detect before initialize: an already\n // enabled manager belongs to somebody else, and initializing it (even with a different policy)\n // would leave this handle describing a sandbox that is not in force.\n // ADOPT only when the live session is somebody ELSE'S. See `selfInitialized`: upstream's flag is\n // sticky across `reset()`, so it alone would make every enforcer after the first one adopt.\n // CLAIM FIRST, CLASSIFY SECOND — and both synchronously, because the boundary is a process-global\n // with no lock to take. An earlier revision computed `adopted` from `isSandboxingEnabled()` and only\n // claimed after `initialize()` resolved, which left TWO windows for concurrent constructions:\n // · both read `claimed === false`, both proceeded, and the second re-initialised over the first;\n // · worse, the second saw `enabled === true` (the first had just initialised) with our marker not\n // yet set, so it classified a session WE established as FOREIGN and adopted it — reporting the\n // other caller's policy as though it were an adopted third-party sandbox.\n // Verified both: `Promise.all` of two enforcers resolved BOTH, the second with `adopted: true` and\n // the first's derived lists. Claiming before any await closes them together.\n const claimedByUs = selfSessionClaimed\n const alreadyLive = manager.isSandboxingEnabled()\n const adopted = alreadyLive && !selfInitialized && !claimedByUs\n if (!adopted) {\n // RESET BEFORE RE-INITIALISING OUR OWN SESSION. Upstream's `initialize()` assigns `config`\n // unconditionally, but the DERIVED getters are computed from the managerContext built during\n // initialisation — so calling it twice without a reset leaves the FIRST policy's derived lists in\n // force. Verified: init A, then init B, and `getFsReadConfig()` still reports A; reset then init C\n // reports C. Without this, a second `srtEnforcer()` in one process silently enforces the previous\n // policy while reporting the new one.\n //\n // Only ever our OWN session: `adopted` is false here, and `selfInitialized` proves we established\n // what is currently live rather than inheriting somebody else's.\n //\n // AND ONLY A RELEASED ONE. Resetting a session a live handle still holds would silently replace\n // that handle's policy with this one — first-writer-wins broken in the constructor, before the\n // manager's admission check can refuse anything. Refuse here instead, where nothing has changed\n // yet: the caller must dispose the existing handle before establishing a different policy.\n if (selfSessionClaimed) {\n throw new E_SANDBOX_POLICY_CONFLICT([\n 'a sandbox session established by this process is still live; dispose that handle before ' +\n 'constructing another enforcer, or reuse it — replacing it here would widen the live ' +\n 'policy before admission could refuse it',\n ])\n }\n // CLAIM SYNCHRONOUSLY, BEFORE THE FIRST AWAIT. Setting this after `initialize()` leaves a window\n // in which two concurrent constructions both read `false`, both proceed, and the second silently\n // re-initialises over the first — verified: `Promise.all` of two enforcers with different policies\n // resolved BOTH, and the second reported the first's derived lists. The check and the claim must be\n // one synchronous step, because there is no lock to take: the boundary is a process-global.\n selfSessionClaimed = true\n try {\n if (selfInitialized && manager.isSandboxingEnabled()) await manager.reset()\n // THE nested-sandbox flag MUST ride this call and only this one. SRT resolves it from the\n // module-level config `initialize()` stored (`getEnableWeakerNestedSandbox()` reads\n // `config?.enableWeakerNestedSandbox`), NOT from the per-call config handed to\n // `wrapWithSandboxArgv` — so passing it only at the `run()` site below would compile, ship, and\n // silently do nothing.\n await manager.initialize(\n mapPolicy(options.policy, {\n enableWeakerNestedSandbox: options.enableWeakerNestedSandbox,\n bwrapPath,\n socatPath,\n })\n )\n selfInitialized = true\n } catch (error) {\n // A failed establishment must not leave the claim held, or the process is permanently wedged\n // with no live session to dispose.\n selfSessionClaimed = false\n throw error\n }\n }\n\n const platform = process.platform === 'linux' ? 'linux' : 'darwin'\n const cwd = process.cwd()\n const derive = (): DerivedRules => {\n const config = manager.getConfig()\n const filesystem = config?.filesystem ?? {}\n const network = config?.network ?? {}\n const allowGitConfig = adopted\n ? Boolean(filesystem.allowGitConfig)\n : (options.policy.filesystem.allowGitConfig ?? false)\n const searchDepth = adopted\n ? (config?.mandatoryDenySearchDepth ?? 3)\n : (options.policy.filesystem.mandatoryDenySearchDepth ?? 3)\n const dotGit = dotGitIsDirectory(cwd)\n return derivedRulesFromSrt({\n platform,\n read: manager.getFsReadConfig(),\n write: manager.getFsWriteConfig(),\n filesystemDisabled: adopted\n ? Boolean(filesystem.disabled)\n : options.policy.filesystem.disabled,\n // In adoption mode these are literal foreign lists. In particular, ['*'] is not evidence\n // that the foreign consumer used ADK's disabled mode.\n network: {\n // ADOPTION ⇒ always `false`: we did not construct this session, so \"we were constructed in\n // disabled mode\" cannot be true of it. OWNED ⇒ the ADK policy's own value, which is what makes\n // the drift SKIP branch and the `false → true` widening check implementable.\n disabled: adopted ? false : (options.policy.network.disabled ?? false),\n allowedDomains: adopted\n ? Array.isArray(network.allowedDomains)\n ? network.allowedDomains\n : []\n : options.policy.network.disabled\n ? undefined\n : nonEmpty(options.policy.network.allowedDomains),\n deniedDomains: adopted\n ? Array.isArray(network.deniedDomains)\n ? network.deniedDomains\n : []\n : options.policy.network.disabled\n ? []\n : nonEmpty(options.policy.network.deniedDomains),\n },\n mandatoryDeny: {\n form: platform === 'linux' ? 'expanded-paths' : 'glob',\n entries: reproduceMandatoryDeny({\n cwd,\n allowGitConfig,\n platform,\n dotGitIsDirectory: dotGit,\n }),\n allowGitConfig,\n searchDepth,\n ...(platform === 'linux' ? { dotGitWasDirectory: dotGit } : {}),\n },\n })\n }\n // CAPTURE the derived baseline immediately after our initialize, or the live foreign baseline\n // when adopting. It is deliberately derived from SRT's getters, not from the requested policy.\n const derived: DerivedRules = derive()\n // PRIME THE GLOB MATCHER with upstream's own `globToRegex` for every rule in the derived lists.\n // This is the whole reason `srtEnforcer` is async at the right moment: the evaluator is synchronous\n // (it is consulted per path) while the upstream import is not, so unless priming happens HERE the\n // synchronous fallback becomes the only path that ever runs in production — making the plan's\n // \"deep-import the matcher, never port it\" rule true on paper and false in fact.\n await primeGlobMatcher([\n ...derived.read.denyOnly,\n ...derived.read.allowWithinDeny,\n ...derived.write.allowOnly,\n ...derived.write.denyWithinAllow,\n ...derived.mandatoryDeny.entries,\n ])\n const enforcer: SandboxPolicyEnforcer = {\n isSupported: () => manager.isSupportedPlatform(),\n adopted,\n checkDependencies: async () => manager.checkDependenciesAsync(),\n run: async (op) => {\n // PER-CALL ADMISSION, NETWORK AXIS. No per-call network section is enforceable under SRT: its\n // mux proxy is started once at `initialize()` and filters every request against the SESSION\n // config, so a per-call section that differs from the session one — whether WIDER (a new\n // domain) or NARROWER (a shorter allow-list, an added deny) — is silently ignored at\n // enforcement time. Both directions are refused rather than ignored: a narrowing would also be\n // a lie (the child runs under the session list, not the narrower one the caller asked for).\n // The per-call FILESYSTEM axis needs no such gate — its policy is baked into that child's\n // profile/argv, a real per-child grant.\n //\n // The comparison reads the LIVE session state (re-derived per call, never the cached\n // `derived`): an adopted session can be widened by a foreign `updateConfig()`, and reading the\n // stale snapshot would reject sections the session already matches.\n const liveBaseline = derive()\n const divergence = networkDivergence(\n liveBaseline,\n op.policy,\n reasonMap(manager.getConfig()?.network?.deniedDomainReasons)\n )\n if (divergence.length > 0)\n throw new E_SANDBOX_NETWORK_GRANT_UNSUPPORTED([\n `the per-call policy's network section differs from the sandbox session's, which SRT ` +\n `cannot enforce for a single child (its proxy filters every request against the SESSION ` +\n `config, not the per-call one), so the child would run under the session policy while ` +\n `you believed it ran under yours. Differences: ${divergence.join('; ')}. A network ` +\n `policy is per SESSION under SRT: repeat the session's network section for per-call ` +\n `filesystem policies, or establish a new srtEnforcer + createSandbox pair with the ` +\n `network policy you need.`,\n ])\n const mapped = mapPolicy(op.policy)\n const command = await quoteShellArgs(op.argv)\n const wrapped = await manager.wrapWithSandboxArgv(\n command,\n binShell,\n mapped,\n op.signal,\n op.cwd,\n { commandId: op.correlationId }\n )\n const child = spawn(wrapped.argv[0], wrapped.argv.slice(1), {\n cwd: op.cwd,\n // SRT's `wrapped.env` is the unchanged process environment, not sandbox plumbing. Merging it\n // here would defeat the allow-list by reintroducing every host variable. SRT's proxy, CA\n // bundle, and git safe-directory plumbing are encoded in `wrapped.argv` instead. The caller's\n // per-call environment remains the final overlay, by contract.\n env: { ...hostEnv, ...(op.env ?? {}) },\n stdio: ['ignore', 'pipe', 'pipe'],\n shell: false,\n detached: true,\n })\n let terminate: (() => void) | undefined\n if (op.signal) {\n terminate = () => {\n try {\n if (child.pid) process.kill(-child.pid, 'SIGKILL')\n else child.kill('SIGKILL')\n } catch {\n child.kill('SIGKILL')\n }\n }\n if (op.signal.aborted) terminate()\n else op.signal.addEventListener('abort', terminate, { once: true })\n }\n const cleanup = () => {\n if (terminate && op.signal) op.signal.removeEventListener('abort', terminate)\n terminate = undefined\n }\n const completed = new Promise<{\n exitCode: number\n failed: boolean\n signalCode?: string\n }>((settle) => {\n // 'error' MUST be handled, and not only so `completed` settles: an unhandled 'error' on a\n // ChildProcess is an uncaught exception that terminates the HOST process. A missing wrapper\n // binary or an unusable `cwd` would therefore kill the agent instead of failing one command.\n // Both listeners are `once` and the promise settles first-write-wins, so the pair is safe:\n // a spawn failure emits 'error' then 'close', and the later 'close' is discarded.\n child.once('error', () => {\n cleanup()\n // No `signalCode`: a spawn failure is not a signal kill.\n settle({ exitCode: 1, failed: true })\n })\n // `close` carries the REAL terminating signal (`signal`), which Node derives from the wait\n // status — the one source of truth for whether the child was signalled and by which signal,\n // rather than inferring it from what we asked for. The field is OMITTED on a normal exit so\n // the settlement of an exiting child stays byte-identical to its previous shape.\n child.once('close', (code, signal) => {\n cleanup()\n settle({\n exitCode: code ?? 1,\n failed: (code ?? 1) !== 0,\n ...(signal ? { signalCode: signal } : {}),\n })\n })\n })\n return {\n stdout: toWeb(child.stdout!),\n stderr: toWeb(child.stderr!),\n completed,\n }\n },\n // Owned sessions are immutable from this adapter's perspective and retain the cheap cached\n // snapshot. An adopted session must re-read SRT on every call: a foreign updateConfig() can widen\n // the live sandbox between invocations, and drift() must compare against that live state.\n effectivePolicy: () => (adopted ? derive() : derived),\n diagnosticsFor: (id) =>\n manager.getSandboxViolationStore().getViolationsForCommand(id).map(String),\n dispose: async () => {\n // Adoption is reported as a no-op. Resetting here would tear down ACEs owned by the host\n // application; only the manager we initialized may be reset.\n // ADOPTION IS A REPORTED NO-OP: resetting here would tear down ACEs owned by the host\n // application. Only a session we established may be reset.\n //\n // `selfInitialized` is deliberately NOT cleared. `reset()` leaves upstream's `config` set, so\n // `isSandboxingEnabled()` stays `true` forever after the first initialise — and clearing our\n // marker would make the NEXT construction see \"enabled, not ours\" and adopt a dead session,\n // silently enforcing the disposed policy. Ownership is a property of this process having\n // initialised at all, not of a session still being live.\n if (!adopted && manager.isSandboxingEnabled()) {\n await manager.reset()\n // Release the claim so a later construction may establish a new session. `selfInitialized`\n // deliberately stays true: upstream's `config` survives `reset()`, so clearing it would make\n // the next construction see \"enabled, not ours\" and adopt a dead session.\n selfSessionClaimed = false\n }\n },\n }\n return enforcer\n}\n\nexport { mapPolicy }\n","import { assertArgvValue, assertAllowedRipgrepFlag } from '../escape'\nimport type { HitFrame, PathFrame, SandboxPolicy } from '../types'\nimport type { SandboxPolicyEnforcer } from '../contracts/policy_enforcer'\n\n/**\n * A classified ripgrep outcome.\n *\n * @remarks\n * CLASSIFICATION ORDER IS LOAD-BEARING: diagnostics are checked BEFORE the exit status, because `rg`\n * runs under the sandbox and a denied path surfaces as a non-zero exit *plus* a violation record.\n * Triage generically first and a policy refusal is permanently mislabelled `io-failure` — the model\n * is told \"search broke\" when the truth is \"you may not read there\", and `denied-by-policy` becomes\n * unreachable despite being in the tool's outcome list.\n *\n * `no-matches` is a RESULT, not an error: `rg` exits 1 when it ran correctly and matched nothing.\n */\nexport type RipgrepFailure =\n | { kind: 'denied-by-policy'; diagnostics: readonly string[] }\n | { kind: 'invalid-pattern'; message: string }\n | { kind: 'no-matches' }\n | { kind: 'io-failure'; message: string; exitCode: number }\n\n/**\n * Convert a classified ripgrep failure into the error the searcher throws.\n *\n * @remarks\n * Exhaustive by construction: a new {@link RipgrepFailure} arm is a compile error here rather than\n * a silently generic message. `denied-by-policy` carries its diagnostics into the message — the\n * classification is checked BEFORE the generic exit-code triage precisely so a policy refusal is\n * not mislabelled `io-failure`, and flattening it back to a bare exit code here would discard the\n * only thing that makes that ordering worth having.\n *\n * @param failure - A classified failure other than `no-matches`, which is a result, not an error.\n * @returns The error to throw.\n */\nconst toRipgrepError = (failure: Exclude<RipgrepFailure, { kind: 'no-matches' }>): Error => {\n switch (failure.kind) {\n case 'denied-by-policy':\n return new Error(`denied-by-policy: ${failure.diagnostics.join('; ')}`)\n case 'invalid-pattern':\n return new Error(failure.message)\n case 'io-failure':\n return new Error(failure.message || `ripgrep exited ${failure.exitCode}`)\n }\n}\n\nconst bytes = new TextDecoder()\nconst collect = async (\n stream: ReadableStream<Uint8Array>,\n onText: (text: string) => void\n): Promise<void> => {\n const reader = stream.getReader()\n try {\n for (;;) {\n const next = await reader.read()\n if (next.done) return\n onText(bytes.decode(next.value, { stream: true }))\n }\n } finally {\n reader.releaseLock()\n }\n}\n\n/**\n * Validate an explicit `limit`, permitting full omission (unbounded).\n *\n * @remarks\n * Issue #48: the contract previously mandated `limit: number` and the adapter rejected everything\n * but a positive integer, so an UNBOUNDED search was inexpressible — the searcher forced a cap, and\n * `Number.MAX_SAFE_INTEGER` is a disguised one. Omission is now the documented unbounded mode: no\n * post-collection cap, the scan finishes `complete: true`. An EXPLICIT value must still be a positive\n * integer — `0`, negatives, non-integers, `Infinity` and `NaN` remain rejections, so a caller cannot\n * accidentally disable the bound they named.\n *\n * @param limit - The requested limit, or `undefined` for unbounded.\n * @returns The validated limit, or `undefined` when unbounded.\n */\nexport const resolveSearchLimit = (limit: number | undefined): number | undefined => {\n if (limit === undefined) return undefined\n if (!Number.isInteger(limit) || limit < 1)\n throw new Error('limit must be a positive integer, or omitted for an unbounded search')\n return limit\n}\n\n/**\n * Emit `--max-depth N` only when a depth was EXPLICITLY requested.\n *\n * @remarks\n * Issue #48: the adapter emitted this flag unconditionally, so omitting `maxDepth` produced the\n * literal argv `--max-depth undefined`, rg exited 2, and every omitted-depth search failed. Omission\n * now means unbounded — rg's own behaviour — and the flag is simply not emitted.\n *\n * @param maxDepth - The requested depth, or `undefined` for unbounded.\n * @returns The flag pair, or an empty array when unbounded.\n */\nexport const resolveMaxDepthArgv = (maxDepth: number | undefined): readonly string[] => {\n if (maxDepth === undefined) return []\n if (!Number.isInteger(maxDepth) || maxDepth < 0)\n throw new Error('maxDepth must be a non-negative integer, or omitted for an unbounded scan')\n return ['--max-depth', String(maxDepth)]\n}\n\n/** Stop yielding after `limit` items; `undefined` never stops. */\nconst wantMore = (shown: number, limit: number | undefined): boolean =>\n limit === undefined || shown < limit\n\n/** Ripgrep backend. Both child pipes are drained immediately and concurrently. */\nexport const createRipgrepSearch = (\n enforcer: SandboxPolicyEnforcer,\n policy: SandboxPolicy\n): {\n searchContent(o: {\n root: string\n pattern: string\n /** Omit for an unbounded scan (no `--max-depth`); an explicit integer sets the boundary. */\n maxDepth?: number\n /** Omit for no result cap: every match is returned and the scan finishes `complete: true`. Note\n * the whole scan is buffered before results are yielded, so an unbounded search over a very\n * large tree uses memory in proportion to the output — pass a `limit` where that matters. */\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 findPaths(o: {\n root: string\n glob: string\n /** Omit for an unbounded scan (no `--max-depth`); an explicit integer sets the boundary. */\n maxDepth?: number\n /** Omit for no result cap: every match is returned and the scan finishes `complete: true`. Note\n * the whole scan is buffered before results are yielded, so an unbounded search over a very\n * large tree uses memory in proportion to the output — pass a `limit` where that matters. */\n limit?: number\n iglob?: string\n follow?: boolean\n hidden?: boolean\n noIgnore?: boolean\n signal?: AbortSignal\n }): AsyncIterable<PathFrame>\n} => {\n const run = async (argv: string[], cwd: string, signal?: AbortSignal) => {\n const correlationId = `${crypto.randomUUID()}-${Date.now().toString(36)}`\n const spawned = await enforcer.run({ argv, cwd, policy, correlationId, signal })\n let out = ''\n let err = ''\n const stdout = collect(spawned.stdout, (chunk) => {\n out += chunk\n })\n const stderr = collect(spawned.stderr, (chunk) => {\n err += chunk\n })\n const [, , completed] = await Promise.all([stdout, stderr, spawned.completed])\n const diagnostics = enforcer.diagnosticsFor(correlationId)\n const exitCode = completed.exitCode\n if (diagnostics.length > 0)\n return { failure: { kind: 'denied-by-policy', diagnostics } as RipgrepFailure, out, err }\n if (exitCode === 2 && err.startsWith('regex parse error'))\n return { failure: { kind: 'invalid-pattern', message: err } as RipgrepFailure, out, err }\n if (exitCode === 1) return { failure: { kind: 'no-matches' } as RipgrepFailure, out, err }\n if (exitCode !== 0)\n return { failure: { kind: 'io-failure', message: err, exitCode } as RipgrepFailure, out, err }\n return { failure: undefined, out, err }\n }\n /**\n * Defence-in-depth check that this adapter only ever emits flags it declared.\n *\n * @remarks\n * Scans the WHOLE argv rather than a fixed index window: the previous `slice(1, 5)` silently depended\n * on argv layout, so adding or reordering an argument moved the window off the flags. It also stops at\n * `--`, because everything after the terminator is a model-supplied VALUE — a pattern like `--foo` is\n * a legitimate search string there, not a flag, and `assertArgvValue` already owns that half.\n */\n const assertAdapterFlags = (argv: readonly string[]): void => {\n for (const arg of argv.slice(1)) {\n if (arg === '--') break\n if (arg.startsWith('--')) assertAllowedRipgrepFlag(arg)\n }\n }\n return {\n async *searchContent(o) {\n const limit = resolveSearchLimit(o.limit)\n if (o.follow)\n throw new Error('follow is refused: descendant symlink containment audit pending')\n const argv = [\n 'rg',\n '--json',\n ...(o.ignoreCase ? ['--ignore-case'] : []),\n ...(o.literal ? ['--fixed-strings'] : []),\n ...(o.glob ? ['--glob', assertArgvValue(o.glob)] : []),\n ...(o.iglob ? ['--iglob', assertArgvValue(o.iglob)] : []),\n ...(o.hidden ? ['--hidden'] : []),\n ...(o.noIgnore ? ['--no-ignore'] : []),\n ...resolveMaxDepthArgv(o.maxDepth),\n '--',\n assertArgvValue(o.pattern),\n assertArgvValue(o.root),\n ]\n assertAdapterFlags(argv)\n const result = await run(argv, o.root, o.signal)\n if (result.failure) {\n if (result.failure.kind === 'no-matches') {\n yield { kind: 'done', complete: true }\n return\n }\n throw toRipgrepError(result.failure)\n }\n let shown = 0\n let overLimit = false\n for (const line of result.out.split('\\n')) {\n if (!line) continue\n try {\n const item = JSON.parse(line) as {\n type: string\n data?: { path?: { text?: string }; line_number?: number; lines?: { text?: string } }\n }\n if (\n item.type === 'match' &&\n item.data?.path?.text &&\n item.data.line_number &&\n item.data.lines\n ) {\n if (!wantMore(shown, limit)) {\n overLimit = true\n break\n }\n yield {\n kind: 'item',\n path: item.data.path.text,\n line: item.data.line_number,\n text: item.data.lines.text ?? '',\n }\n shown++\n }\n } catch {\n /* malformed rg diagnostics are an I/O failure in the real adapter */\n }\n }\n yield overLimit\n ? { kind: 'done', complete: false, omitted: 'over-limit', bound: 'limit', shown }\n : { kind: 'done', complete: true }\n },\n async *findPaths(o) {\n const limit = resolveSearchLimit(o.limit)\n if (o.follow)\n throw new Error('follow is refused: descendant symlink containment audit pending')\n const argv = [\n 'rg',\n '--files',\n '--glob',\n assertArgvValue(o.glob),\n ...(o.iglob ? ['--iglob', assertArgvValue(o.iglob)] : []),\n ...(o.hidden ? ['--hidden'] : []),\n ...(o.noIgnore ? ['--no-ignore'] : []),\n ...resolveMaxDepthArgv(o.maxDepth),\n '--',\n assertArgvValue(o.root),\n ]\n assertAdapterFlags(argv)\n const result = await run(argv, o.root, o.signal)\n if (result.failure) {\n if (result.failure.kind === 'no-matches') {\n yield { kind: 'done', complete: true }\n return\n }\n throw toRipgrepError(result.failure)\n }\n let shown = 0\n let overLimit = false\n for (const path of result.out.split('\\n')) {\n if (!path) continue\n if (!wantMore(shown, limit)) {\n overLimit = true\n break\n }\n yield { kind: 'item', path }\n shown++\n }\n yield overLimit\n ? { kind: 'done', complete: false, omitted: 'over-limit', bound: 'limit', shown }\n : { kind: 'done', complete: true }\n },\n }\n}\n"],"mappings":";;;;;;;;;;AAoDA,IAAM,oBAA2B;CAC/B,MAAM,IAAI,mBAAA,0BAA0B,CAClC,iC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K,GAAG;KAC3B,YAAY;KACZ;IACF;IACA,MAAM;KAAE,MAAM;KAAQ;IAAK;IAC3B;GACF;GACA,MAAM,YACF;IAAE,MAAM;IAAQ,UAAU;IAAO,SAAS;IAAc,OAAO;IAAS;GAAM,IAC9E;IAAE,MAAM;IAAQ,UAAU;GAAK;EACrC;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"node.cjs","names":[],"sources":["../../../src/batteries/sandbox/node/srt_enforcer.ts","../../../src/batteries/sandbox/node/search_ripgrep.ts"],"sourcesContent":["import { statSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { spawn } from 'node:child_process'\nimport { isObject } from '@nhtio/adk/guards'\nimport { quoteShellArgs, validateAbsoluteBinaryPath, validateBinShell } from '../escape'\nimport { derivedRulesFromSrt, primeGlobMatcher, reproduceMandatoryDeny } from './fs_node'\nimport {\n E_INVALID_SANDBOX_CONFIG,\n E_SANDBOX_UNSUPPORTED_ENV,\n E_SANDBOX_POLICY_CONFLICT,\n E_SANDBOX_NETWORK_GRANT_UNSUPPORTED,\n} from '../exceptions'\nimport type { BinarySandbox } from '../executor'\nimport type { SandboxPolicy, DerivedRules } from '../types'\nimport type { SandboxPolicyEnforcer } from '../contracts/policy_enforcer'\n\n/**\n * The internal SRT bridge both execution routes share: admit a per-call policy, quote the argv,\n * and ask SRT for the wrapped argv.\n *\n * @remarks\n * Deliberately NOT part of `SandboxPolicyEnforcer` — the contract stays backend-neutral, so an\n * SRT-shaped internal field would make the \"ADK-owned types\" firewall nominal. It is exported only\n * as a type so the factory that consumes it can be typed; the value lives on the enforcer object\n * as a hidden carrier field.\n */\ntype SrtWrapFn = (\n argv: readonly string[],\n policy: SandboxPolicy,\n signal: AbortSignal | undefined,\n cwd: string | undefined,\n correlationId?: string\n) => Promise<{ argv: string[]; env: Record<string, string> }>\n\n/** What {@link srtBinarySandbox} probes for on the enforcer: the internal SRT carrier fields. */\ntype SrtCarrier = SandboxPolicyEnforcer & {\n wrapInvocation?: SrtWrapFn\n sessionPolicy?: SandboxPolicy\n hostEnv?: Record<string, string>\n}\n\ntype SrtManager = {\n initialize(config: SrtConfig): Promise<void>\n isSupportedPlatform(): boolean\n isSandboxingEnabled(): boolean\n checkDependenciesAsync(): Promise<{ errors: string[]; warnings: string[] }>\n wrapWithSandboxArgv(\n command: string,\n shell?: string,\n custom?: unknown,\n signal?: AbortSignal,\n cwd?: string,\n options?: { commandId?: string }\n ): Promise<{ argv: string[]; env: Record<string, string> }>\n getFsReadConfig(): { denyOnly: string[]; allowWithinDeny?: string[] }\n getFsWriteConfig(): { allowOnly: string[]; denyWithinAllow: string[] }\n getNetworkRestrictionConfig(): {\n allowedHosts?: string[]\n deniedHosts?: string[]\n }\n getConfig(): SrtConfig | undefined\n getSandboxViolationStore(): {\n getViolationsForCommand(command: string): unknown[]\n }\n reset(): Promise<void>\n}\ntype SrtConfig = {\n filesystem: Record<string, unknown>\n network?: Record<string, unknown>\n /** SRT's Linux mandatory-deny scan depth is session-level. */\n mandatoryDenySearchDepth?: number\n git?: { safeDirectories: string[] }\n /** Top-level and session-level: SRT reads this from the config `initialize()` stored, not per call. */\n enableWeakerNestedSandbox?: boolean\n bwrapPath?: string\n socatPath?: string\n}\n\nconst unsupported = (): never => {\n throw new E_SANDBOX_UNSUPPORTED_ENV([\n `SRT sandbox is unavailable on ${process.platform}; use WSL2 or the SES browser path`,\n ])\n}\n\nconst json = (value: unknown): string => JSON.stringify(value)\n\n/**\n * Why a per-call policy's network section is not the session baseline, or an empty list when it\n * EQUALS the baseline.\n *\n * @remarks\n * SRT enforces network allow/deny per REQUEST against the process-global SESSION config, never the\n * per-call `customConfig`: its mux proxy is started once at `initialize()` and `filterNetworkRequest`\n * reads `config.network.*` on every request (see the docs page for the source receipts). An\n * embedder hook exists — `network.filterRequest` and the `initialize()` ask callback — but neither\n * can scope enforcement to one child: the ask callback is handed only `{host, port}`, is suppressed\n * entirely while `strictAllowlist` is set (which this battery always sets), and its identity input\n * (the proxy username) is client-controlled and forgeable; `filterRequest` runs only AFTER the\n * session list has allowed a host, so it can deny within the list but never grant beyond it. A\n * per-call network section that differs from the session one — WIDER or NARROWER — would therefore be\n * silently ignored at enforcement time.\n *\n * Refusing every divergence turns that silent ignore into a typed, immediate error. Equality is\n * exact: the same `disabled` flag, and — compared as SETS, so order does not matter — the same\n * allowed and denied domain patterns and the same denial reasons. `deniedDomainReasons` is read from\n * the LIVE session config (`manager.getConfig()`), which is what SRT's filter actually consults.\n */\nconst networkDivergence = (\n baseline: DerivedRules,\n policy: SandboxPolicy,\n sessionReasons: Readonly<Record<string, string>>\n): readonly string[] => {\n // A disabled policy may not carry domains (`mapPolicy` throws for that combination), so its\n // canonical section is just the flag. A disabled BASELINE is unrestricted by definition, so it has\n // no domain lists or reasons to compare against.\n const policyDisabled = Boolean(policy.network.disabled)\n const policyAllowed = policyDisabled ? [] : nonEmpty(policy.network.allowedDomains)\n const policyDenied = policyDisabled ? [] : nonEmpty(policy.network.deniedDomains)\n const policyReasons = policyDisabled ? {} : { ...(policy.network.deniedDomainReasons ?? {}) }\n const baselineDisabled = baseline.network.disabled\n const baselineAllowed = baselineDisabled ? [] : baseline.network.allowedDomains\n const baselineDenied = baselineDisabled ? [] : baseline.network.deniedDomains\n const baselineReasons = baselineDisabled ? {} : sessionReasons\n\n const differences: string[] = []\n if (policyDisabled !== baselineDisabled)\n differences.push(`disabled ${baselineDisabled} → ${policyDisabled}`)\n if (!sameSet(asSet(policyAllowed), asSet(baselineAllowed)))\n differences.push(`allowedDomains ${json(baselineAllowed)} → ${json(policyAllowed)}`)\n if (!sameSet(asSet(policyDenied), asSet(baselineDenied)))\n differences.push(`deniedDomains ${json(baselineDenied)} → ${json(policyDenied)}`)\n if (!sameReasons(policyReasons, baselineReasons))\n differences.push(`deniedDomainReasons ${json(baselineReasons)} → ${json(policyReasons)}`)\n return differences\n}\nconst nonEmpty = (v: readonly string[] | undefined): string[] => [...(v ?? [])]\nconst asSet = (v: readonly string[]): ReadonlySet<string> => new Set(v)\nconst sameSet = (a: ReadonlySet<string>, b: ReadonlySet<string>): boolean =>\n a.size === b.size && [...a].every((item) => b.has(item))\nconst sameReasons = (\n a: Readonly<Record<string, string>>,\n b: Readonly<Record<string, string>>\n): boolean => {\n const aKeys = Object.keys(a)\n return aKeys.length === Object.keys(b).length && aKeys.every((key) => b[key] === a[key])\n}\n/** Coerce an arbitrary upstream value into the string→string denial-reason map SRT expects. */\nconst reasonMap = (value: unknown): Record<string, string> =>\n isObject(value)\n ? Object.fromEntries(\n Object.entries(value).filter(\n (entry): entry is [string, string] => typeof entry[1] === 'string'\n )\n )\n : {}\n\n/**\n * Host variables a sandboxed child inherits when the caller names no allow-list.\n *\n * @remarks\n * `PATH` ONLY, and it is the minimum rather than a convenience. The ripgrep searcher spawns `rg` by\n * BARE NAME, so with no `PATH` the child sees only the one a shell synthesises\n * (`/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.`) — which does not contain `/opt/homebrew/bin` or a Nix\n * profile, so `search_files` would fail as `io-failure` on any such host and present as *\"the search\n * tool is broken\"* rather than as a configuration error.\n *\n * `PATH` is not a credential: a model that runs `env` learns where binaries live, not a secret. Every\n * genuinely sensitive variable — and `HOME`, `USER`, `TMPDIR`, which leak host layout — stays out.\n */\nconst DEFAULT_ENV_ALLOW_LIST: readonly string[] = ['PATH']\n\n/** POSIX environment-variable names. Anything else could not be exported by a shell anyway. */\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/\n\n/**\n * Resolve the host half of a sandboxed child's environment ONCE, at construction.\n *\n * @remarks\n * DENY BY DEFAULT. Before this existed the enforcer spread the entire `process.env` into every child,\n * so a model directing the shell's argv could run `env` and read the host's credentials straight back\n * into its own context — which no filesystem or network policy prevents, because the secret arrives in\n * the tool result rather than over the wire.\n *\n * The allow-list REPLACES this default rather than extending it; that is stated on the option, because\n * the opposite assumption is the natural one and would silently drop `PATH`.\n *\n * @param options - The enforcer's construction options.\n * @returns The host variables to seed the child's environment with.\n */\nconst resolveHostEnv = (options: SrtEnforcerOptions): Record<string, string> => {\n if (options.inheritHostEnv === true) {\n const all: Record<string, string> = {}\n for (const [name, value] of Object.entries(process.env))\n if (value !== undefined) all[name] = value\n return all\n }\n const names = options.envAllowList ?? DEFAULT_ENV_ALLOW_LIST\n const picked: Record<string, string> = {}\n for (const name of names) {\n if (!ENV_NAME.test(name))\n throw new E_INVALID_SANDBOX_CONFIG([\n `envAllowList entry ${JSON.stringify(name)} is not a valid environment variable name`,\n ])\n const value = process.env[name]\n if (value !== undefined) picked[name] = value\n }\n return picked\n}\n\n/**\n * Whether `<cwd>/.git` is a real DIRECTORY.\n *\n * @remarks\n * Load-bearing on Linux only: upstream pushes the workspace-root `.git/hooks` and `.git/config` deny\n * entries just when `.git` is a directory, because in a worktree it is a FILE and denying it would\n * make bubblewrap fail. Treating a worktree as a directory would deny what the profile permits.\n */\nconst dotGitIsDirectory = (cwd: string): boolean => {\n try {\n return statSync(resolve(cwd, '.git')).isDirectory()\n } catch {\n return false\n }\n}\n\n/**\n * The sole ADK-to-SRT translation point. Keep the upstream type behind this local firewall.\n *\n * @remarks\n * `runtime` carries ADAPTER-level settings that are deliberately absent from `SandboxPolicy`. That\n * type is ADK-owned, SRT-neutral vocabulary — naming an SRT feature in it would make the firewall\n * nominal and leave a non-SRT enforcer unable to implement the contract — so an SRT-specific switch\n * belongs on the adapter's own options, exactly as `binShell` already does.\n */\nconst mapPolicy = (\n policy: SandboxPolicy,\n runtime: {\n enableWeakerNestedSandbox?: boolean\n bwrapPath?: string\n socatPath?: string\n } = {}\n): SrtConfig => {\n const fs = policy.filesystem\n const net = policy.network\n if (\n net.disabled &&\n (net.deniedDomains?.length ||\n Object.keys(net.deniedDomainReasons ?? {}).length ||\n (net.allowedDomains && !(net.allowedDomains.length === 1 && net.allowedDomains[0] === '*')))\n )\n throw new E_INVALID_SANDBOX_CONFIG(['network.disabled contradicts network domain restrictions'])\n const allowedDomains = net.disabled ? ['*'] : nonEmpty(net.allowedDomains)\n const deniedDomains = net.disabled ? [] : nonEmpty(net.deniedDomains)\n const deniedDomainReasons = net.disabled ? {} : { ...(net.deniedDomainReasons ?? {}) }\n return {\n ...(fs.mandatoryDenySearchDepth !== undefined\n ? { mandatoryDenySearchDepth: fs.mandatoryDenySearchDepth }\n : {}),\n // Emitted only when enabled, so an untouched configuration is byte-identical to before this\n // option existed — a drift snapshot taken either side of the upgrade compares equal.\n ...(runtime.enableWeakerNestedSandbox === true ? { enableWeakerNestedSandbox: true } : {}),\n ...(runtime.bwrapPath !== undefined ? { bwrapPath: runtime.bwrapPath } : {}),\n ...(runtime.socatPath !== undefined ? { socatPath: runtime.socatPath } : {}),\n filesystem: {\n ...(fs.disabled ? { disabled: true } : {}),\n denyRead: nonEmpty(fs.denyRead),\n allowRead: nonEmpty(fs.allowRead),\n allowWrite: nonEmpty(fs.allowWrite),\n denyWrite: nonEmpty(fs.denyWrite),\n allowGitConfig: fs.allowGitConfig ?? false,\n },\n // SRT keys network restriction by presence of this object. There is no schema-valid allow-all\n // domain pattern, so disabled deliberately omits the key instead of emitting the rejected '*'.\n ...(!net.disabled\n ? {\n network: {\n allowedDomains,\n deniedDomains,\n deniedDomainReasons,\n strictAllowlist: true,\n allowLocalBinding: false,\n allowUnixSockets: [],\n allowMachLookup: [],\n },\n }\n : {}),\n git: {\n safeDirectories: nonEmpty(fs.gitSafeDirectories ?? [process.cwd()]),\n },\n }\n}\n\nconst toWeb = (stream: NodeJS.ReadableStream): ReadableStream<Uint8Array> =>\n (\n ReadableStream as unknown as {\n from?: (x: unknown) => ReadableStream<Uint8Array>\n }\n ).from\n ? (\n ReadableStream as unknown as {\n from: (x: unknown) => ReadableStream<Uint8Array>\n }\n ).from(stream)\n : new ReadableStream({\n start(controller) {\n stream.on('data', (x: Buffer) => controller.enqueue(new Uint8Array(x)))\n stream.on('end', () => controller.close())\n stream.on('error', (e) => controller.error(e))\n },\n })\n\n/** Options for {@link srtEnforcer}. */\n/**\n * Whether an enforcer in THIS process performed the `initialize()` that is currently in force.\n *\n * @remarks\n * UPSTREAM'S OWN FLAG CANNOT ANSWER THIS. `isSandboxingEnabled()` is literally `config !== undefined`\n * (`sandbox-manager.js:672-675`) and `reset()` clears `managerContext`, the proxies, the registries —\n * **but never `config`**. So after any reset the flag stays `true` forever, and an enforcer that\n * trusted it would \"adopt\" a sandbox that is no longer in force, silently reporting a stale policy\n * and refusing to re-initialise. Verified: initialize, reset, and `isSandboxingEnabled()` is still\n * `true`.\n *\n * We therefore track what WE established. `true` here means this module owns the live session, so a\n * subsequent construction must re-initialise rather than adopt. `false` with upstream reporting\n * enabled means somebody else got there first — the genuine adoption case.\n */\nlet selfInitialized = false\n\n/**\n * Whether the session THIS module established is still claimed by a live enforcer.\n *\n * @remarks\n * FIRST-WRITER-WINS IS ENFORCED HERE, not only in the manager. `manager.ts` admits or refuses a\n * second handle by comparing policies — but that check runs AFTER `srtEnforcer()` has already\n * constructed, and construction is what touches the process-global. So a reset-and-reinitialise in the\n * constructor would tear down a live policy before anything could refuse it: caller 2 widens the real\n * sandbox, the manager then throws, and caller 1 carries on against a baseline that is no longer in\n * force. The refusal would arrive after the damage.\n *\n * `claimed` is therefore set when we initialise and cleared only by `dispose()`. While it is `true`,\n * re-initialising is refused outright; once cleared, the next construction may re-establish a session,\n * which is what makes sequential owned handles work.\n */\nlet selfSessionClaimed = false\n\n/**\n * Relinquish this module's ownership marker.\n *\n * @remarks\n * TEST SEAM, and a narrow one. The marker exists because upstream's `isSandboxingEnabled()` is\n * `config !== undefined` and `reset()` never clears `config` — so after the first `initialize()` the\n * flag is permanently `true` and cannot by itself distinguish *\"a session we established\"* from\n * *\"somebody else's\"*. Ownership therefore persists for the life of the module, which is correct in\n * production (a process that initialised once keeps re-initialising its own session) but makes the\n * ADOPTION branch unreachable in a test file that has already constructed an owned enforcer.\n *\n * Production code has no reason to call this: relinquishing ownership while a session we established\n * is still live would make the next construction adopt it and refuse to re-initialise.\n */\nexport const releaseSrtOwnershipForTests = (): void => {\n selfInitialized = false\n selfSessionClaimed = false\n}\n\n/** Construction options for {@link srtEnforcer}. */\nexport type SrtEnforcerOptions = {\n /**\n * Absolute path to the POSIX shell used to invoke wrapped commands. Defaults to `/bin/bash`.\n *\n * @remarks\n * Validated at construction in TWO checks, both required: it must be ABSOLUTE (a bare `bash` passes\n * any basename test while remaining `PATH`-dependent — the exact hazard the absolute default\n * avoids), and its basename must be on the allow-list (`sh`, `bash`, `dash`, `zsh`, `ksh`) — the\n * shells whose quoting the single escaper is correct for. An allow-list rather than a deny-list is\n * deliberate: `fish` and `nu` are POSIX-ish enough to look safe and different enough to break\n * single-quote escaping, so an unverified shell must fail closed.\n */\n binShell?: string\n /**\n * The ADK-owned policy to enforce.\n *\n * @remarks\n * Mapped to SRT's config inside this module and nowhere else. The derived baseline is captured\n * immediately after `initialize()`, because `SandboxManager` is a process-global singleton whose\n * SECOND `initialize()` is a no-op — a later call with a different policy silently keeps the first.\n */\n policy: SandboxPolicy\n /**\n * Host environment variable NAMES a sandboxed child may inherit. Defaults to `['PATH']`.\n *\n * @remarks\n * The child inherits NOTHING from the host beyond these names. That default is deliberate: a model\n * that can direct the shell's argv can run `env`, so anything inherited is readable back into its\n * context — and no filesystem or network policy stops it, because the value arrives in the tool\n * result rather than over the wire.\n *\n * **This REPLACES the default, it does not extend it.** A caller who needs `CARGO_HOME` and still\n * wants binaries to resolve must pass BOTH: `['PATH', 'CARGO_HOME']`. Passing `['CARGO_HOME']` alone\n * drops `PATH`, which breaks `search_files` on any host where `rg` lives outside `/usr/bin`.\n *\n * An entry that is not a valid POSIX environment-variable name throws `E_INVALID_SANDBOX_CONFIG` at\n * construction rather than being skipped, so a typo surfaces as a startup error instead of a\n * variable that silently never arrives.\n */\n envAllowList?: readonly string[]\n /**\n * Pass the ENTIRE host environment to sandboxed children. Defaults to `false`.\n *\n * @remarks\n * The escape hatch for a deployment that genuinely needs ambient configuration, and it is worth\n * being blunt about what it re-opens: **every secret in the host process becomes readable by the\n * model**, because `run_shell_command` exists precisely to run commands the model chose and `env` is\n * one of them. Prefer naming what you need in `envAllowList`.\n */\n inheritHostEnv?: boolean\n /**\n * Absolute path to a Linux bubblewrap wrapper or binary. SRT reads it from the config passed to\n * `initialize()`; on the Linux launch path it becomes argv[0] of the bwrap command\n * (`linux-sandbox-utils.js:1539`). A wrapper script placed at this path therefore receives every\n * bwrap argument and can strip or rewrite options such as `--unshare-net`. On Linux a nonexistent\n * path fails in SRT's `initialize()`; on macOS it is neither validated nor used.\n */\n bwrapPath?: string\n /**\n * Absolute path to a Linux socat binary or wrapper. SRT passes it to `initializeLinuxNetworkBridge`\n * on Linux. A nonexistent path fails in SRT's `initialize()`; on macOS it is neither validated nor\n * used.\n */\n socatPath?: string\n /**\n * Enable SRT's weaker nested-sandbox mode, for running inside an unprivileged container.\n *\n * @remarks\n * Bubblewrap cannot mount a fresh `/proc` inside an unprivileged container, so the sandbox fails to\n * start at all — the symptom is `apply-seccomp: write /proc/self/uid_map: Operation not permitted`\n * with exit 1, an empty stdout and NO diagnostics, which is indistinguishable from a policy denial.\n * This flag makes the inner sandbox bind-mount the container's EXISTING `/proc` instead.\n *\n * **It considerably weakens the boundary**, in upstream's own words: the bind-mounted `/proc`\n * exposes process information a fresh mount would hide. Only enable it when the OUTER container\n * already provides the isolation you need — it trades inner isolation for the sandbox running at all.\n *\n * Session-level: SRT reads it from the config given to `initialize()`, never per call.\n */\n enableWeakerNestedSandbox?: boolean\n}\n\n/**\n * Construct the SRT-backed policy enforcer — the OS boundary.\n *\n * @remarks\n * REFUSES rather than degrades on an unsupported platform: native `win32` throws\n * `E_SANDBOX_UNSUPPORTED_ENV` naming WSL2, because Windows folds all four filesystem-policy lists\n * case-insensitively and throws on per-exec allows. A half-built branch there would be a DIVERGENT\n * boundary rather than a limited one, so there is deliberately no native-Windows evaluator.\n *\n * `run()` resolves on SPAWN with live streams plus a separate `completed` promise, never a settled\n * exit code. That split is not stylistic: one promise cannot both hand over unread child streams AND\n * carry an exit code, because settling requires the streams to have ended and they cannot end before\n * someone drains them. A caller MUST drain both concurrently — pipe buffers are per-fd, so draining\n * one to completion first can block the other and hang the child.\n *\n * @param options - Shell and policy configuration.\n * @returns An enforcer whose derived baseline is already captured.\n */\nexport const srtEnforcer = async (options: SrtEnforcerOptions): Promise<SandboxPolicyEnforcer> => {\n if (process.platform !== 'darwin' && process.platform !== 'linux') return unsupported()\n const binShell = validateBinShell(options.binShell)\n const bwrapPath = validateAbsoluteBinaryPath(options.bwrapPath, 'bwrapPath')\n const socatPath = validateAbsoluteBinaryPath(options.socatPath, 'socatPath')\n // Resolved ONCE: the allow-list is fixed for the enforcer's life, so re-picking per spawn would only\n // add a chance for the two to disagree. Validation throws here, at construction, so a typo'd variable\n // name is a startup error rather than a variable that silently never arrives.\n const hostEnv = resolveHostEnv(options)\n const srt = (await import('@anthropic-ai/sandbox-runtime')) as unknown as {\n SandboxManager: SrtManager\n }\n const manager = srt.SandboxManager\n // SandboxManager is process-global and first-writer-wins. Detect before initialize: an already\n // enabled manager belongs to somebody else, and initializing it (even with a different policy)\n // would leave this handle describing a sandbox that is not in force.\n // ADOPT only when the live session is somebody ELSE'S. See `selfInitialized`: upstream's flag is\n // sticky across `reset()`, so it alone would make every enforcer after the first one adopt.\n // CLAIM FIRST, CLASSIFY SECOND — and both synchronously, because the boundary is a process-global\n // with no lock to take. An earlier revision computed `adopted` from `isSandboxingEnabled()` and only\n // claimed after `initialize()` resolved, which left TWO windows for concurrent constructions:\n // · both read `claimed === false`, both proceeded, and the second re-initialised over the first;\n // · worse, the second saw `enabled === true` (the first had just initialised) with our marker not\n // yet set, so it classified a session WE established as FOREIGN and adopted it — reporting the\n // other caller's policy as though it were an adopted third-party sandbox.\n // Verified both: `Promise.all` of two enforcers resolved BOTH, the second with `adopted: true` and\n // the first's derived lists. Claiming before any await closes them together.\n const claimedByUs = selfSessionClaimed\n const alreadyLive = manager.isSandboxingEnabled()\n const adopted = alreadyLive && !selfInitialized && !claimedByUs\n if (!adopted) {\n // RESET BEFORE RE-INITIALISING OUR OWN SESSION. Upstream's `initialize()` assigns `config`\n // unconditionally, but the DERIVED getters are computed from the managerContext built during\n // initialisation — so calling it twice without a reset leaves the FIRST policy's derived lists in\n // force. Verified: init A, then init B, and `getFsReadConfig()` still reports A; reset then init C\n // reports C. Without this, a second `srtEnforcer()` in one process silently enforces the previous\n // policy while reporting the new one.\n //\n // Only ever our OWN session: `adopted` is false here, and `selfInitialized` proves we established\n // what is currently live rather than inheriting somebody else's.\n //\n // AND ONLY A RELEASED ONE. Resetting a session a live handle still holds would silently replace\n // that handle's policy with this one — first-writer-wins broken in the constructor, before the\n // manager's admission check can refuse anything. Refuse here instead, where nothing has changed\n // yet: the caller must dispose the existing handle before establishing a different policy.\n if (selfSessionClaimed) {\n throw new E_SANDBOX_POLICY_CONFLICT([\n 'a sandbox session established by this process is still live; dispose that handle before ' +\n 'constructing another enforcer, or reuse it — replacing it here would widen the live ' +\n 'policy before admission could refuse it',\n ])\n }\n // CLAIM SYNCHRONOUSLY, BEFORE THE FIRST AWAIT. Setting this after `initialize()` leaves a window\n // in which two concurrent constructions both read `false`, both proceed, and the second silently\n // re-initialises over the first — verified: `Promise.all` of two enforcers with different policies\n // resolved BOTH, and the second reported the first's derived lists. The check and the claim must be\n // one synchronous step, because there is no lock to take: the boundary is a process-global.\n selfSessionClaimed = true\n try {\n if (selfInitialized && manager.isSandboxingEnabled()) await manager.reset()\n // THE nested-sandbox flag MUST ride this call and only this one. SRT resolves it from the\n // module-level config `initialize()` stored (`getEnableWeakerNestedSandbox()` reads\n // `config?.enableWeakerNestedSandbox`), NOT from the per-call config handed to\n // `wrapWithSandboxArgv` — so passing it only at the `run()` site below would compile, ship, and\n // silently do nothing.\n await manager.initialize(\n mapPolicy(options.policy, {\n enableWeakerNestedSandbox: options.enableWeakerNestedSandbox,\n bwrapPath,\n socatPath,\n })\n )\n selfInitialized = true\n } catch (error) {\n // A failed establishment must not leave the claim held, or the process is permanently wedged\n // with no live session to dispose.\n selfSessionClaimed = false\n throw error\n }\n }\n\n const platform = process.platform === 'linux' ? 'linux' : 'darwin'\n const cwd = process.cwd()\n const derive = (): DerivedRules => {\n const config = manager.getConfig()\n const filesystem = config?.filesystem ?? {}\n const network = config?.network ?? {}\n const allowGitConfig = adopted\n ? Boolean(filesystem.allowGitConfig)\n : (options.policy.filesystem.allowGitConfig ?? false)\n const searchDepth = adopted\n ? (config?.mandatoryDenySearchDepth ?? 3)\n : (options.policy.filesystem.mandatoryDenySearchDepth ?? 3)\n const dotGit = dotGitIsDirectory(cwd)\n return derivedRulesFromSrt({\n platform,\n read: manager.getFsReadConfig(),\n write: manager.getFsWriteConfig(),\n filesystemDisabled: adopted\n ? Boolean(filesystem.disabled)\n : options.policy.filesystem.disabled,\n // In adoption mode these are literal foreign lists. In particular, ['*'] is not evidence\n // that the foreign consumer used ADK's disabled mode.\n network: {\n // ADOPTION ⇒ always `false`: we did not construct this session, so \"we were constructed in\n // disabled mode\" cannot be true of it. OWNED ⇒ the ADK policy's own value, which is what makes\n // the drift SKIP branch and the `false → true` widening check implementable.\n disabled: adopted ? false : (options.policy.network.disabled ?? false),\n allowedDomains: adopted\n ? Array.isArray(network.allowedDomains)\n ? network.allowedDomains\n : []\n : options.policy.network.disabled\n ? undefined\n : nonEmpty(options.policy.network.allowedDomains),\n deniedDomains: adopted\n ? Array.isArray(network.deniedDomains)\n ? network.deniedDomains\n : []\n : options.policy.network.disabled\n ? []\n : nonEmpty(options.policy.network.deniedDomains),\n },\n mandatoryDeny: {\n form: platform === 'linux' ? 'expanded-paths' : 'glob',\n entries: reproduceMandatoryDeny({\n cwd,\n allowGitConfig,\n platform,\n dotGitIsDirectory: dotGit,\n }),\n allowGitConfig,\n searchDepth,\n ...(platform === 'linux' ? { dotGitWasDirectory: dotGit } : {}),\n },\n })\n }\n // CAPTURE the derived baseline immediately after our initialize, or the live foreign baseline\n // when adopting. It is deliberately derived from SRT's getters, not from the requested policy.\n const derived: DerivedRules = derive()\n // PRIME THE GLOB MATCHER with upstream's own `globToRegex` for every rule in the derived lists.\n // This is the whole reason `srtEnforcer` is async at the right moment: the evaluator is synchronous\n // (it is consulted per path) while the upstream import is not, so unless priming happens HERE the\n // synchronous fallback becomes the only path that ever runs in production — making the plan's\n // \"deep-import the matcher, never port it\" rule true on paper and false in fact.\n await primeGlobMatcher([\n ...derived.read.denyOnly,\n ...derived.read.allowWithinDeny,\n ...derived.write.allowOnly,\n ...derived.write.denyWithinAllow,\n ...derived.mandatoryDeny.entries,\n ])\n /**\n * PER-CALL ADMISSION plus the SRT argv wrap — the one path BOTH execution routes take.\n *\n * @remarks\n * `run()` spawns the result itself; {@link srtBinarySandbox} hands it to a `BinaryExecutor`\n * instead. Factoring it out is what keeps those two routes from drifting apart: the network\n * admission gate, the single `mapPolicy` translation, the single shell quoting step and the\n * `wrapWithSandboxArgv` call are shared, so a change to any of them lands on both.\n *\n * The network axis is refused rather than degraded: SRT's mux proxy is started once at\n * `initialize()` and filters every request against the SESSION config, so a per-call section that\n * differs from the session one — whether WIDER (a new domain) or NARROWER (a shorter allow-list,\n * an added deny) — is silently ignored at enforcement time. Both directions are refused: a\n * narrowing would also be a lie (the child runs under the session list, not the narrower one the\n * caller asked for). The per-call FILESYSTEM axis needs no such gate — its policy is baked into\n * that child's profile/argv, a real per-child grant.\n *\n * The comparison reads the LIVE session state (re-derived per call, never the cached `derived`):\n * an adopted session can be widened by a foreign `updateConfig()`, and reading the stale snapshot\n * would reject sections the session already matches.\n */\n const admitAndWrap = async (\n argv: readonly string[],\n policy: SandboxPolicy,\n signal: AbortSignal | undefined,\n workingDir: string | undefined,\n correlationId?: string\n ): Promise<{ argv: string[]; env: Record<string, string> }> => {\n const liveBaseline = derive()\n const divergence = networkDivergence(\n liveBaseline,\n policy,\n reasonMap(manager.getConfig()?.network?.deniedDomainReasons)\n )\n if (divergence.length > 0)\n throw new E_SANDBOX_NETWORK_GRANT_UNSUPPORTED([\n `the per-call policy's network section differs from the sandbox session's, which SRT ` +\n `cannot enforce for a single child (its proxy filters every request against the SESSION ` +\n `config, not the per-call one), so the child would run under the session policy while ` +\n `you believed it ran under yours. Differences: ${divergence.join('; ')}. A network ` +\n `policy is per SESSION under SRT: repeat the session's network section for per-call ` +\n `filesystem policies, or establish a new srtEnforcer + createSandbox pair with the ` +\n `network policy you need.`,\n ])\n const mapped = mapPolicy(policy)\n const command = await quoteShellArgs(argv)\n const wrapped = await manager.wrapWithSandboxArgv(\n command,\n binShell,\n mapped,\n signal,\n workingDir,\n {\n commandId: correlationId,\n }\n )\n // `env` is the HOST half only, deliberately NOT `wrapped.env`: SRT returns the unchanged host\n // environment there, so using it would defeat the allow-list wholesale (the `run()` spawn\n // documents the same trap). Callers overlay THEIR values on top of this, never beneath it.\n return { argv: wrapped.argv, env: hostEnv }\n }\n const enforcer: SandboxPolicyEnforcer & {\n /** Internal SRT bridge consumed by {@link srtBinarySandbox} — see `SrtWrapFn`. */\n wrapInvocation: SrtWrapFn\n /** The SESSION policy this enforcer established or adopted (for the wrap path's default). */\n sessionPolicy: SandboxPolicy | undefined\n /** The host-env allow-list resolved at construction (see `resolveHostEnv`). */\n hostEnv: Record<string, string>\n } = {\n isSupported: () => manager.isSupportedPlatform(),\n adopted,\n checkDependencies: async () => manager.checkDependenciesAsync(),\n run: async (op) => {\n const wrapped = await admitAndWrap(op.argv, op.policy, op.signal, op.cwd, op.correlationId)\n const child = spawn(wrapped.argv[0], wrapped.argv.slice(1), {\n cwd: op.cwd,\n // SRT's `wrapped.env` is the unchanged process environment, not sandbox plumbing. Merging it\n // here would defeat the allow-list by reintroducing every host variable. SRT's proxy, CA\n // bundle, and git safe-directory plumbing are encoded in `wrapped.argv` instead. The caller's\n // per-call environment remains the final overlay, by contract.\n env: { ...hostEnv, ...(op.env ?? {}) },\n stdio: ['ignore', 'pipe', 'pipe'],\n shell: false,\n detached: true,\n })\n let terminate: (() => void) | undefined\n if (op.signal) {\n terminate = () => {\n try {\n if (child.pid) process.kill(-child.pid, 'SIGKILL')\n else child.kill('SIGKILL')\n } catch {\n child.kill('SIGKILL')\n }\n }\n if (op.signal.aborted) terminate()\n else op.signal.addEventListener('abort', terminate, { once: true })\n }\n const cleanup = () => {\n if (terminate && op.signal) op.signal.removeEventListener('abort', terminate)\n terminate = undefined\n }\n const completed = new Promise<{\n exitCode: number\n failed: boolean\n signalCode?: string\n }>((settle) => {\n // 'error' MUST be handled, and not only so `completed` settles: an unhandled 'error' on a\n // ChildProcess is an uncaught exception that terminates the HOST process. A missing wrapper\n // binary or an unusable `cwd` would therefore kill the agent instead of failing one command.\n // Both listeners are `once` and the promise settles first-write-wins, so the pair is safe:\n // a spawn failure emits 'error' then 'close', and the later 'close' is discarded.\n child.once('error', () => {\n cleanup()\n // No `signalCode`: a spawn failure is not a signal kill.\n settle({ exitCode: 1, failed: true })\n })\n // `close` carries the REAL terminating signal (`signal`), which Node derives from the wait\n // status — the one source of truth for whether the child was signalled and by which signal,\n // rather than inferring it from what we asked for. The field is OMITTED on a normal exit so\n // the settlement of an exiting child stays byte-identical to its previous shape.\n child.once('close', (code, signal) => {\n cleanup()\n settle({\n exitCode: code ?? 1,\n failed: (code ?? 1) !== 0,\n ...(signal ? { signalCode: signal } : {}),\n })\n })\n })\n return {\n stdout: toWeb(child.stdout!),\n stderr: toWeb(child.stderr!),\n completed,\n }\n },\n // THE SRT-BRIDGE CAPABILITY. Not part of the `SandboxPolicyEnforcer` contract — a hidden\n // carrier field {@link srtBinarySandbox} probes for (structurally, so a duck-typed enforcer of\n // the same shape but SRT-free origin is refused, not silently misused). It shares the closure\n // state above, which is what makes the two execution routes one policy.\n wrapInvocation: admitAndWrap,\n sessionPolicy: options.policy,\n hostEnv,\n // Owned sessions are immutable from this adapter's perspective and retain the cheap cached\n // snapshot. An adopted session must re-read SRT on every call: a foreign updateConfig() can widen\n // the live sandbox between invocations, and drift() must compare against that live state.\n effectivePolicy: () => (adopted ? derive() : derived),\n diagnosticsFor: (id) =>\n manager.getSandboxViolationStore().getViolationsForCommand(id).map(String),\n dispose: async () => {\n // Adoption is reported as a no-op. Resetting here would tear down ACEs owned by the host\n // application; only the manager we initialized may be reset.\n // ADOPTION IS A REPORTED NO-OP: resetting here would tear down ACEs owned by the host\n // application. Only a session we established may be reset.\n //\n // `selfInitialized` is deliberately NOT cleared. `reset()` leaves upstream's `config` set, so\n // `isSandboxingEnabled()` stays `true` forever after the first initialise — and clearing our\n // marker would make the NEXT construction see \"enabled, not ours\" and adopt a dead session,\n // silently enforcing the disposed policy. Ownership is a property of this process having\n // initialised at all, not of a session still being live.\n if (!adopted && manager.isSandboxingEnabled()) {\n await manager.reset()\n // Release the claim so a later construction may establish a new session. `selfInitialized`\n // deliberately stays true: upstream's `config` survives `reset()`, so clearing it would make\n // the next construction see \"enabled, not ours\" and adopt a dead session.\n selfSessionClaimed = false\n }\n },\n }\n return enforcer\n}\n\n/**\n * Options for {@link srtBinarySandbox}.\n */\nexport type SrtBinarySandboxOptions = {\n /**\n * The per-invocation policy this wrapper applies. Defaults to the enforcer's own session policy.\n *\n * @remarks\n * This is the SAME per-call policy contract {@link SandboxPolicyEnforcer.run} takes, so it is\n * admitted identically: the FILESYSTEM section is baked into this child's profile (and replaces\n * the session baseline for it, exactly as `run()` does), while a NETWORK section that differs\n * from the live session is refused with `E_SANDBOX_NETWORK_GRANT_UNSUPPORTED`. Omitted means the\n * enforcer's established session policy, which is the only policy that can never diverge from\n * the session's network state.\n */\n policy?: SandboxPolicy\n /**\n * The DEFAULT working directory, used when the invocation carries none — the invocation's own\n * `cwd` wins. Falls back to the current process directory when neither names one.\n *\n * @remarks\n * ONE effective directory is computed from those layers and used for BOTH the SRT profile and the\n * returned invocation's `cwd`, so the profile and the spawn can never disagree. That matters\n * because SRT derives its git `safe.directory` injection and (on Linux) its mandatory-deny scan\n * from this directory: a profile generated for one directory while the executor spawns in\n * another is a sandbox that does not describe the process it is supposedly enforcing.\n */\n cwd?: string\n}\n\n/**\n * Expose an existing {@link SandboxPolicyEnforcer} as a {@link BinarySandbox} for the media\n * pipeline — the bridge between the sandbox battery and {@link sandboxedExecutor}.\n *\n * @remarks\n * DELIBERATELY DERIVED FROM {@link srtEnforcer}, NOT A SECOND SRT ADAPTER. It holds no state of its\n * own: the wrapper closes over the enforcer's single live `SandboxManager` session, its validated\n * `binShell`, its `mapPolicy` translation, its network-divergence admission gate and its host-env\n * allow-list. One process-global session, one translation point, one admission policy — the two\n * execution routes (`run()` for streaming tools, this for settled media invocations) share the\n * internal admission+wrapping step so they cannot drift.\n *\n * The wrapped invocation is what the inner executor spawns: `cmd` is the wrapper binary\n * (`bwrap`/`sandbox-exec`), `args` are the rest of the generated argv, and the caller's own argv is\n * already inside that generated command. The adapter therefore must not re-append the original args.\n *\n * THE ENVIRONMENT SPLITS IN TWO, AND ONLY ONE HALF INHERITS FROM THE HOST. The host-env allow-list is\n * what decides which HOST variables a child may inherit from `process.env`; it is the adapter's\n * decision, taken at construction. The caller's `env` is its own EXPLICIT values, applied last, and\n * may add names or override allow-listed ones. The wrap composes the two into\n * `{ ...hostEnv, ...(invocation.env ?? {}) }` and sets `extendEnv: false`, so the executor hands the\n * child EXACTLY those variables. This is load-bearing: execa's default `extendEnv: true` would merge\n * the full `process.env` back in, which would silently hand the model every host secret whenever it\n * ran `env` — the exact leak the allow-list exists to prevent. So the invariant this adapter\n * enforces is the contract's: `env` may add or override, but NOTHING from the host beyond the\n * allow-list reaches the child, and `env` is never a reason to inherit more from the host.\n *\n * REFUSES rather than degrades in the same places `run()` does: the network gate throws\n * `E_SANDBOX_NETWORK_GRANT_UNSUPPORTED` before anything runs, and an unavailable platform throws\n * `E_SANDBOX_UNSUPPORTED_ENV` (surfaced by `srtEnforcer`'s construction). After the enforcer is\n * disposed the process-global session is gone, so a wrap still generates argv but the child is\n * refused by the OS — the same honest failure mode `run()` presents. Prefer disposing the\n * executor alongside the enforcer.\n *\n * POSIX-only, like the session it wraps: there is no `process.kill(-pid, signal)` equivalent on\n * Windows, which is why `srtEnforcer` never constructs there.\n *\n * @param enforcer - The live enforcer whose session, shell, policy mapping and env allow-list this\n * wrapper reuses. Construct it with {@link srtEnforcer} and dispose it when the executor goes away.\n * @param opts - The per-invocation policy and the DEFAULT working directory (the invocation's own\n * `cwd` wins); the same directory is used for the SRT profile and for the returned invocation.\n * @returns A {@link BinarySandbox} whose `wrap` returns the sandboxed argv the inner executor runs.\n */\nexport const srtBinarySandbox = (\n enforcer: SandboxPolicyEnforcer,\n opts: SrtBinarySandboxOptions = {}\n): BinarySandbox => ({\n async wrap(invocation) {\n // The factory can only reuse state it can actually reach. A BYO enforcer of the same interface\n // has no SRT session behind it, so wrapping through one would either do nothing (and read as\n // sandboxed) or throw somewhere unhelpful; refuse at the seam that knows the answer.\n const carrier = enforcer as SrtCarrier\n if (typeof carrier.wrapInvocation !== 'function')\n throw new E_INVALID_SANDBOX_CONFIG([\n 'srtBinarySandbox requires an enforcer constructed by srtEnforcer: this adapter only ' +\n \"forwards to the enforcer's own SRT session, and the supplied enforcer exposes none\",\n ])\n const policyForCall = opts.policy ?? carrier.sessionPolicy\n if (!policyForCall)\n throw new E_INVALID_SANDBOX_CONFIG([\n 'srtBinarySandbox requires a policy: the supplied enforcer was adopted (it holds no ' +\n 'ADK policy of its own), so name the session policy explicitly in the wrap options',\n ])\n // ONE effective directory for both the SRT profile and the spawn — never two that can drift.\n // Precedence is the documented one: the invocation's own cwd wins, then this factory's default,\n // then the current process directory (what execa would spawn in with no cwd set at all).\n const cwd = invocation.cwd ?? opts.cwd ?? process.cwd()\n const wrapped = await carrier.wrapInvocation(\n [invocation.cmd, ...invocation.args],\n policyForCall,\n invocation.signal,\n cwd,\n undefined\n )\n return {\n ...invocation,\n cmd: wrapped.argv[0]!,\n args: wrapped.argv.slice(1),\n // THE SAME directory the profile was generated for: SRT's profile is derived from this and\n // the executor then spawns in it, so the two cannot disagree.\n cwd,\n // `wrapped.env` is `admitAndWrap`'s host-env allow-list (never SRT's unchanged host\n // environment); the caller's explicit values are applied last, exactly as in `run()`.\n env: { ...wrapped.env, ...(invocation.env ?? {}) },\n // The executor must not merge `process.env` back in — see the factory docs above.\n extendEnv: false,\n }\n },\n})\n\nexport { mapPolicy }\n","import { assertArgvValue, assertAllowedRipgrepFlag } from '../escape'\nimport type { HitFrame, PathFrame, SandboxPolicy } from '../types'\nimport type { SandboxPolicyEnforcer } from '../contracts/policy_enforcer'\n\n/**\n * A classified ripgrep outcome.\n *\n * @remarks\n * CLASSIFICATION ORDER IS LOAD-BEARING: diagnostics are checked BEFORE the exit status, because `rg`\n * runs under the sandbox and a denied path surfaces as a non-zero exit *plus* a violation record.\n * Triage generically first and a policy refusal is permanently mislabelled `io-failure` — the model\n * is told \"search broke\" when the truth is \"you may not read there\", and `denied-by-policy` becomes\n * unreachable despite being in the tool's outcome list.\n *\n * `no-matches` is a RESULT, not an error: `rg` exits 1 when it ran correctly and matched nothing.\n */\nexport type RipgrepFailure =\n | { kind: 'denied-by-policy'; diagnostics: readonly string[] }\n | { kind: 'invalid-pattern'; message: string }\n | { kind: 'no-matches' }\n | { kind: 'io-failure'; message: string; exitCode: number }\n\n/**\n * Convert a classified ripgrep failure into the error the searcher throws.\n *\n * @remarks\n * Exhaustive by construction: a new {@link RipgrepFailure} arm is a compile error here rather than\n * a silently generic message. `denied-by-policy` carries its diagnostics into the message — the\n * classification is checked BEFORE the generic exit-code triage precisely so a policy refusal is\n * not mislabelled `io-failure`, and flattening it back to a bare exit code here would discard the\n * only thing that makes that ordering worth having.\n *\n * @param failure - A classified failure other than `no-matches`, which is a result, not an error.\n * @returns The error to throw.\n */\nconst toRipgrepError = (failure: Exclude<RipgrepFailure, { kind: 'no-matches' }>): Error => {\n switch (failure.kind) {\n case 'denied-by-policy':\n return new Error(`denied-by-policy: ${failure.diagnostics.join('; ')}`)\n case 'invalid-pattern':\n return new Error(failure.message)\n case 'io-failure':\n return new Error(failure.message || `ripgrep exited ${failure.exitCode}`)\n }\n}\n\nconst bytes = new TextDecoder()\nconst collect = async (\n stream: ReadableStream<Uint8Array>,\n onText: (text: string) => void\n): Promise<void> => {\n const reader = stream.getReader()\n try {\n for (;;) {\n const next = await reader.read()\n if (next.done) return\n onText(bytes.decode(next.value, { stream: true }))\n }\n } finally {\n reader.releaseLock()\n }\n}\n\n/**\n * Validate an explicit `limit`, permitting full omission (unbounded).\n *\n * @remarks\n * Issue #48: the contract previously mandated `limit: number` and the adapter rejected everything\n * but a positive integer, so an UNBOUNDED search was inexpressible — the searcher forced a cap, and\n * `Number.MAX_SAFE_INTEGER` is a disguised one. Omission is now the documented unbounded mode: no\n * post-collection cap, the scan finishes `complete: true`. An EXPLICIT value must still be a positive\n * integer — `0`, negatives, non-integers, `Infinity` and `NaN` remain rejections, so a caller cannot\n * accidentally disable the bound they named.\n *\n * @param limit - The requested limit, or `undefined` for unbounded.\n * @returns The validated limit, or `undefined` when unbounded.\n */\nexport const resolveSearchLimit = (limit: number | undefined): number | undefined => {\n if (limit === undefined) return undefined\n if (!Number.isInteger(limit) || limit < 1)\n throw new Error('limit must be a positive integer, or omitted for an unbounded search')\n return limit\n}\n\n/**\n * Emit `--max-depth N` only when a depth was EXPLICITLY requested.\n *\n * @remarks\n * Issue #48: the adapter emitted this flag unconditionally, so omitting `maxDepth` produced the\n * literal argv `--max-depth undefined`, rg exited 2, and every omitted-depth search failed. Omission\n * now means unbounded — rg's own behaviour — and the flag is simply not emitted.\n *\n * @param maxDepth - The requested depth, or `undefined` for unbounded.\n * @returns The flag pair, or an empty array when unbounded.\n */\nexport const resolveMaxDepthArgv = (maxDepth: number | undefined): readonly string[] => {\n if (maxDepth === undefined) return []\n if (!Number.isInteger(maxDepth) || maxDepth < 0)\n throw new Error('maxDepth must be a non-negative integer, or omitted for an unbounded scan')\n return ['--max-depth', String(maxDepth)]\n}\n\n/** Stop yielding after `limit` items; `undefined` never stops. */\nconst wantMore = (shown: number, limit: number | undefined): boolean =>\n limit === undefined || shown < limit\n\n/** Ripgrep backend. Both child pipes are drained immediately and concurrently. */\nexport const createRipgrepSearch = (\n enforcer: SandboxPolicyEnforcer,\n policy: SandboxPolicy\n): {\n searchContent(o: {\n root: string\n pattern: string\n /** Omit for an unbounded scan (no `--max-depth`); an explicit integer sets the boundary. */\n maxDepth?: number\n /** Omit for no result cap: every match is returned and the scan finishes `complete: true`. Note\n * the whole scan is buffered before results are yielded, so an unbounded search over a very\n * large tree uses memory in proportion to the output — pass a `limit` where that matters. */\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 findPaths(o: {\n root: string\n glob: string\n /** Omit for an unbounded scan (no `--max-depth`); an explicit integer sets the boundary. */\n maxDepth?: number\n /** Omit for no result cap: every match is returned and the scan finishes `complete: true`. Note\n * the whole scan is buffered before results are yielded, so an unbounded search over a very\n * large tree uses memory in proportion to the output — pass a `limit` where that matters. */\n limit?: number\n iglob?: string\n follow?: boolean\n hidden?: boolean\n noIgnore?: boolean\n signal?: AbortSignal\n }): AsyncIterable<PathFrame>\n} => {\n const run = async (argv: string[], cwd: string, signal?: AbortSignal) => {\n const correlationId = `${crypto.randomUUID()}-${Date.now().toString(36)}`\n const spawned = await enforcer.run({ argv, cwd, policy, correlationId, signal })\n let out = ''\n let err = ''\n const stdout = collect(spawned.stdout, (chunk) => {\n out += chunk\n })\n const stderr = collect(spawned.stderr, (chunk) => {\n err += chunk\n })\n const [, , completed] = await Promise.all([stdout, stderr, spawned.completed])\n const diagnostics = enforcer.diagnosticsFor(correlationId)\n const exitCode = completed.exitCode\n if (diagnostics.length > 0)\n return { failure: { kind: 'denied-by-policy', diagnostics } as RipgrepFailure, out, err }\n if (exitCode === 2 && err.startsWith('regex parse error'))\n return { failure: { kind: 'invalid-pattern', message: err } as RipgrepFailure, out, err }\n if (exitCode === 1) return { failure: { kind: 'no-matches' } as RipgrepFailure, out, err }\n if (exitCode !== 0)\n return { failure: { kind: 'io-failure', message: err, exitCode } as RipgrepFailure, out, err }\n return { failure: undefined, out, err }\n }\n /**\n * Defence-in-depth check that this adapter only ever emits flags it declared.\n *\n * @remarks\n * Scans the WHOLE argv rather than a fixed index window: the previous `slice(1, 5)` silently depended\n * on argv layout, so adding or reordering an argument moved the window off the flags. It also stops at\n * `--`, because everything after the terminator is a model-supplied VALUE — a pattern like `--foo` is\n * a legitimate search string there, not a flag, and `assertArgvValue` already owns that half.\n */\n const assertAdapterFlags = (argv: readonly string[]): void => {\n for (const arg of argv.slice(1)) {\n if (arg === '--') break\n if (arg.startsWith('--')) assertAllowedRipgrepFlag(arg)\n }\n }\n return {\n async *searchContent(o) {\n const limit = resolveSearchLimit(o.limit)\n if (o.follow)\n throw new Error('follow is refused: descendant symlink containment audit pending')\n const argv = [\n 'rg',\n '--json',\n ...(o.ignoreCase ? ['--ignore-case'] : []),\n ...(o.literal ? ['--fixed-strings'] : []),\n ...(o.glob ? ['--glob', assertArgvValue(o.glob)] : []),\n ...(o.iglob ? ['--iglob', assertArgvValue(o.iglob)] : []),\n ...(o.hidden ? ['--hidden'] : []),\n ...(o.noIgnore ? ['--no-ignore'] : []),\n ...resolveMaxDepthArgv(o.maxDepth),\n '--',\n assertArgvValue(o.pattern),\n assertArgvValue(o.root),\n ]\n assertAdapterFlags(argv)\n const result = await run(argv, o.root, o.signal)\n if (result.failure) {\n if (result.failure.kind === 'no-matches') {\n yield { kind: 'done', complete: true }\n return\n }\n throw toRipgrepError(result.failure)\n }\n let shown = 0\n let overLimit = false\n for (const line of result.out.split('\\n')) {\n if (!line) continue\n try {\n const item = JSON.parse(line) as {\n type: string\n data?: { path?: { text?: string }; line_number?: number; lines?: { text?: string } }\n }\n if (\n item.type === 'match' &&\n item.data?.path?.text &&\n item.data.line_number &&\n item.data.lines\n ) {\n if (!wantMore(shown, limit)) {\n overLimit = true\n break\n }\n yield {\n kind: 'item',\n path: item.data.path.text,\n line: item.data.line_number,\n text: item.data.lines.text ?? '',\n }\n shown++\n }\n } catch {\n /* malformed rg diagnostics are an I/O failure in the real adapter */\n }\n }\n yield overLimit\n ? { kind: 'done', complete: false, omitted: 'over-limit', bound: 'limit', shown }\n : { kind: 'done', complete: true }\n },\n async *findPaths(o) {\n const limit = resolveSearchLimit(o.limit)\n if (o.follow)\n throw new Error('follow is refused: descendant symlink containment audit pending')\n const argv = [\n 'rg',\n '--files',\n '--glob',\n assertArgvValue(o.glob),\n ...(o.iglob ? ['--iglob', assertArgvValue(o.iglob)] : []),\n ...(o.hidden ? ['--hidden'] : []),\n ...(o.noIgnore ? ['--no-ignore'] : []),\n ...resolveMaxDepthArgv(o.maxDepth),\n '--',\n assertArgvValue(o.root),\n ]\n assertAdapterFlags(argv)\n const result = await run(argv, o.root, o.signal)\n if (result.failure) {\n if (result.failure.kind === 'no-matches') {\n yield { kind: 'done', complete: true }\n return\n }\n throw toRipgrepError(result.failure)\n }\n let shown = 0\n let overLimit = false\n for (const path of result.out.split('\\n')) {\n if (!path) continue\n if (!wantMore(shown, limit)) {\n overLimit = true\n break\n }\n yield { kind: 'item', path }\n shown++\n }\n yield overLimit\n ? { kind: 'done', complete: false, omitted: 'over-limit', bound: 'limit', shown }\n : { kind: 'done', complete: true }\n },\n }\n}\n"],"mappings":";;;;;;;;;;AA8EA,IAAM,oBAA2B;CAC/B,MAAM,IAAI,mBAAA,0BAA0B,CAClC,iCAAiC,QAAQ,SAAS,mCACpD,CAAC;AACH;AAEA,IAAM,QAAQ,UAA2B,KAAK,UAAU,KAAK;;;;;;;;;;;;;;;;;;;;;;AAuB7D,IAAM,qBACJ,UACA,QACA,mBACsB;CAItB,MAAM,iBAAiB,QAAQ,OAAO,QAAQ,QAAQ;CACtD,MAAM,gBAAgB,iBAAiB,CAAC,IAAI,SAAS,OAAO,QAAQ,cAAc;CAClF,MAAM,eAAe,iBAAiB,CAAC,IAAI,SAAS,OAAO,QAAQ,aAAa;CAChF,MAAM,gBAAgB,iBAAiB,CAAC,IAAI,EAAE,GAAI,OAAO,QAAQ,uBAAuB,CAAC,EAAG;CAC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AAW,CAAC,aAAa,IAAI,CAAC;IACpC,GAAG,oBAAoB,EAAE,QAAQ;IACjC;IACA,eAAA,gBAAgB,EAAE,IAAI;GACxB;GACA,mBAAmB,IAAI;GACvB,MAAM,SAAS,MAAM,IAAI,MAAM,EAAE,MAAM,EAAE,MAAM;GAC/C,IAAI,OAAO,SAAS;IAClB,IAAI,OAAO,QAAQ,SAAS,cAAc;KACxC,MAAM;MAAE,MAAM;MAAQ,UAAU;KAAK;KACrC;IACF;IACA,MAAM,eAAe,OAAO,OAAO;GACrC;GACA,IAAI,QAAQ;GACZ,IAAI,YAAY;GAChB,KAAK,MAAM,QAAQ,OAAO,IAAI,MAAM,IAAI,GAAG;IACzC,IAAI,CAAC,MAAM;IACX,IAAI,CAAC,SAAS,OAAO,KAAK,GAAG;KAC3B,YAAY;KACZ;IACF;IACA,MAAM;KAAE,MAAM;KAAQ;IAAK;IAC3B;GACF;GACA,MAAM,YACF;IAAE,MAAM;IAAQ,UAAU;IAAO,SAAS;IAAc,OAAO;IAAS;GAAM,IAC9E;IAAE,MAAM;IAAQ,UAAU;GAAK;EACrC;CACF;AACF"}
|
|
@@ -281,16 +281,43 @@ var srtEnforcer = async (options) => {
|
|
|
281
281
|
...derived.write.denyWithinAllow,
|
|
282
282
|
...derived.mandatoryDeny.entries
|
|
283
283
|
]);
|
|
284
|
+
/**
|
|
285
|
+
* PER-CALL ADMISSION plus the SRT argv wrap — the one path BOTH execution routes take.
|
|
286
|
+
*
|
|
287
|
+
* @remarks
|
|
288
|
+
* `run()` spawns the result itself; {@link srtBinarySandbox} hands it to a `BinaryExecutor`
|
|
289
|
+
* instead. Factoring it out is what keeps those two routes from drifting apart: the network
|
|
290
|
+
* admission gate, the single `mapPolicy` translation, the single shell quoting step and the
|
|
291
|
+
* `wrapWithSandboxArgv` call are shared, so a change to any of them lands on both.
|
|
292
|
+
*
|
|
293
|
+
* The network axis is refused rather than degraded: SRT's mux proxy is started once at
|
|
294
|
+
* `initialize()` and filters every request against the SESSION config, so a per-call section that
|
|
295
|
+
* differs from the session one — whether WIDER (a new domain) or NARROWER (a shorter allow-list,
|
|
296
|
+
* an added deny) — is silently ignored at enforcement time. Both directions are refused: a
|
|
297
|
+
* narrowing would also be a lie (the child runs under the session list, not the narrower one the
|
|
298
|
+
* caller asked for). The per-call FILESYSTEM axis needs no such gate — its policy is baked into
|
|
299
|
+
* that child's profile/argv, a real per-child grant.
|
|
300
|
+
*
|
|
301
|
+
* The comparison reads the LIVE session state (re-derived per call, never the cached `derived`):
|
|
302
|
+
* an adopted session can be widened by a foreign `updateConfig()`, and reading the stale snapshot
|
|
303
|
+
* would reject sections the session already matches.
|
|
304
|
+
*/
|
|
305
|
+
const admitAndWrap = async (argv, policy, signal, workingDir, correlationId) => {
|
|
306
|
+
const divergence = networkDivergence(derive(), policy, reasonMap(manager.getConfig()?.network?.deniedDomainReasons));
|
|
307
|
+
if (divergence.length > 0) throw new E_SANDBOX_NETWORK_GRANT_UNSUPPORTED([`the per-call policy's network section differs from the sandbox session's, which SRT cannot enforce for a single child (its proxy filters every request against the SESSION config, not the per-call one), so the child would run under the session policy while you believed it ran under yours. Differences: ${divergence.join("; ")}. A network policy is per SESSION under SRT: repeat the session's network section for per-call filesystem policies, or establish a new srtEnforcer + createSandbox pair with the network policy you need.`]);
|
|
308
|
+
const mapped = mapPolicy(policy);
|
|
309
|
+
const command = await quoteShellArgs(argv);
|
|
310
|
+
return {
|
|
311
|
+
argv: (await manager.wrapWithSandboxArgv(command, binShell, mapped, signal, workingDir, { commandId: correlationId })).argv,
|
|
312
|
+
env: hostEnv
|
|
313
|
+
};
|
|
314
|
+
};
|
|
284
315
|
return {
|
|
285
316
|
isSupported: () => manager.isSupportedPlatform(),
|
|
286
317
|
adopted,
|
|
287
318
|
checkDependencies: async () => manager.checkDependenciesAsync(),
|
|
288
319
|
run: async (op) => {
|
|
289
|
-
const
|
|
290
|
-
if (divergence.length > 0) throw new E_SANDBOX_NETWORK_GRANT_UNSUPPORTED([`the per-call policy's network section differs from the sandbox session's, which SRT cannot enforce for a single child (its proxy filters every request against the SESSION config, not the per-call one), so the child would run under the session policy while you believed it ran under yours. Differences: ${divergence.join("; ")}. A network policy is per SESSION under SRT: repeat the session's network section for per-call filesystem policies, or establish a new srtEnforcer + createSandbox pair with the network policy you need.`]);
|
|
291
|
-
const mapped = mapPolicy(op.policy);
|
|
292
|
-
const command = await quoteShellArgs(op.argv);
|
|
293
|
-
const wrapped = await manager.wrapWithSandboxArgv(command, binShell, mapped, op.signal, op.cwd, { commandId: op.correlationId });
|
|
320
|
+
const wrapped = await admitAndWrap(op.argv, op.policy, op.signal, op.cwd, op.correlationId);
|
|
294
321
|
const child = spawn(wrapped.argv[0], wrapped.argv.slice(1), {
|
|
295
322
|
cwd: op.cwd,
|
|
296
323
|
env: {
|
|
@@ -345,6 +372,9 @@ var srtEnforcer = async (options) => {
|
|
|
345
372
|
completed
|
|
346
373
|
};
|
|
347
374
|
},
|
|
375
|
+
wrapInvocation: admitAndWrap,
|
|
376
|
+
sessionPolicy: options.policy,
|
|
377
|
+
hostEnv,
|
|
348
378
|
effectivePolicy: () => adopted ? derive() : derived,
|
|
349
379
|
diagnosticsFor: (id) => manager.getSandboxViolationStore().getViolationsForCommand(id).map(String),
|
|
350
380
|
dispose: async () => {
|
|
@@ -355,6 +385,68 @@ var srtEnforcer = async (options) => {
|
|
|
355
385
|
}
|
|
356
386
|
};
|
|
357
387
|
};
|
|
388
|
+
/**
|
|
389
|
+
* Expose an existing {@link SandboxPolicyEnforcer} as a {@link BinarySandbox} for the media
|
|
390
|
+
* pipeline — the bridge between the sandbox battery and {@link sandboxedExecutor}.
|
|
391
|
+
*
|
|
392
|
+
* @remarks
|
|
393
|
+
* DELIBERATELY DERIVED FROM {@link srtEnforcer}, NOT A SECOND SRT ADAPTER. It holds no state of its
|
|
394
|
+
* own: the wrapper closes over the enforcer's single live `SandboxManager` session, its validated
|
|
395
|
+
* `binShell`, its `mapPolicy` translation, its network-divergence admission gate and its host-env
|
|
396
|
+
* allow-list. One process-global session, one translation point, one admission policy — the two
|
|
397
|
+
* execution routes (`run()` for streaming tools, this for settled media invocations) share the
|
|
398
|
+
* internal admission+wrapping step so they cannot drift.
|
|
399
|
+
*
|
|
400
|
+
* The wrapped invocation is what the inner executor spawns: `cmd` is the wrapper binary
|
|
401
|
+
* (`bwrap`/`sandbox-exec`), `args` are the rest of the generated argv, and the caller's own argv is
|
|
402
|
+
* already inside that generated command. The adapter therefore must not re-append the original args.
|
|
403
|
+
*
|
|
404
|
+
* THE ENVIRONMENT SPLITS IN TWO, AND ONLY ONE HALF INHERITS FROM THE HOST. The host-env allow-list is
|
|
405
|
+
* what decides which HOST variables a child may inherit from `process.env`; it is the adapter's
|
|
406
|
+
* decision, taken at construction. The caller's `env` is its own EXPLICIT values, applied last, and
|
|
407
|
+
* may add names or override allow-listed ones. The wrap composes the two into
|
|
408
|
+
* `{ ...hostEnv, ...(invocation.env ?? {}) }` and sets `extendEnv: false`, so the executor hands the
|
|
409
|
+
* child EXACTLY those variables. This is load-bearing: execa's default `extendEnv: true` would merge
|
|
410
|
+
* the full `process.env` back in, which would silently hand the model every host secret whenever it
|
|
411
|
+
* ran `env` — the exact leak the allow-list exists to prevent. So the invariant this adapter
|
|
412
|
+
* enforces is the contract's: `env` may add or override, but NOTHING from the host beyond the
|
|
413
|
+
* allow-list reaches the child, and `env` is never a reason to inherit more from the host.
|
|
414
|
+
*
|
|
415
|
+
* REFUSES rather than degrades in the same places `run()` does: the network gate throws
|
|
416
|
+
* `E_SANDBOX_NETWORK_GRANT_UNSUPPORTED` before anything runs, and an unavailable platform throws
|
|
417
|
+
* `E_SANDBOX_UNSUPPORTED_ENV` (surfaced by `srtEnforcer`'s construction). After the enforcer is
|
|
418
|
+
* disposed the process-global session is gone, so a wrap still generates argv but the child is
|
|
419
|
+
* refused by the OS — the same honest failure mode `run()` presents. Prefer disposing the
|
|
420
|
+
* executor alongside the enforcer.
|
|
421
|
+
*
|
|
422
|
+
* POSIX-only, like the session it wraps: there is no `process.kill(-pid, signal)` equivalent on
|
|
423
|
+
* Windows, which is why `srtEnforcer` never constructs there.
|
|
424
|
+
*
|
|
425
|
+
* @param enforcer - The live enforcer whose session, shell, policy mapping and env allow-list this
|
|
426
|
+
* wrapper reuses. Construct it with {@link srtEnforcer} and dispose it when the executor goes away.
|
|
427
|
+
* @param opts - The per-invocation policy and the DEFAULT working directory (the invocation's own
|
|
428
|
+
* `cwd` wins); the same directory is used for the SRT profile and for the returned invocation.
|
|
429
|
+
* @returns A {@link BinarySandbox} whose `wrap` returns the sandboxed argv the inner executor runs.
|
|
430
|
+
*/
|
|
431
|
+
var srtBinarySandbox = (enforcer, opts = {}) => ({ async wrap(invocation) {
|
|
432
|
+
const carrier = enforcer;
|
|
433
|
+
if (typeof carrier.wrapInvocation !== "function") throw new E_INVALID_SANDBOX_CONFIG(["srtBinarySandbox requires an enforcer constructed by srtEnforcer: this adapter only forwards to the enforcer's own SRT session, and the supplied enforcer exposes none"]);
|
|
434
|
+
const policyForCall = opts.policy ?? carrier.sessionPolicy;
|
|
435
|
+
if (!policyForCall) throw new E_INVALID_SANDBOX_CONFIG(["srtBinarySandbox requires a policy: the supplied enforcer was adopted (it holds no ADK policy of its own), so name the session policy explicitly in the wrap options"]);
|
|
436
|
+
const cwd = invocation.cwd ?? opts.cwd ?? process.cwd();
|
|
437
|
+
const wrapped = await carrier.wrapInvocation([invocation.cmd, ...invocation.args], policyForCall, invocation.signal, cwd, void 0);
|
|
438
|
+
return {
|
|
439
|
+
...invocation,
|
|
440
|
+
cmd: wrapped.argv[0],
|
|
441
|
+
args: wrapped.argv.slice(1),
|
|
442
|
+
cwd,
|
|
443
|
+
env: {
|
|
444
|
+
...wrapped.env,
|
|
445
|
+
...invocation.env ?? {}
|
|
446
|
+
},
|
|
447
|
+
extendEnv: false
|
|
448
|
+
};
|
|
449
|
+
} });
|
|
358
450
|
//#endregion
|
|
359
451
|
//#region src/batteries/sandbox/node/search_ripgrep.ts
|
|
360
452
|
/**
|
|
@@ -621,6 +713,6 @@ var createRipgrepSearch = (enforcer, policy) => {
|
|
|
621
713
|
};
|
|
622
714
|
};
|
|
623
715
|
//#endregion
|
|
624
|
-
export { DANGEROUS_DIRECTORIES, DANGEROUS_FILES, createFsNode, createRipgrepSearch, derivedRulesFromSrt, loadGlobToRegex, mapPolicy, primeGlobMatcher, reproduceMandatoryDeny, resolveMaxDepthArgv, resolveSearchLimit, srtEnforcer };
|
|
716
|
+
export { DANGEROUS_DIRECTORIES, DANGEROUS_FILES, createFsNode, createRipgrepSearch, derivedRulesFromSrt, loadGlobToRegex, mapPolicy, primeGlobMatcher, reproduceMandatoryDeny, resolveMaxDepthArgv, resolveSearchLimit, srtBinarySandbox, srtEnforcer };
|
|
625
717
|
|
|
626
718
|
//# sourceMappingURL=node.mjs.map
|