Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(agent): share live HMR previews over SSH (#6629)
Wolf Mermelsteine6344552cdb7
diff --git a/.cursor/frontend.sh b/.cursor/frontend.shindex ab28d89a06..1d9aa2c0e9 100755--- a/.cursor/frontend.sh+++ b/.cursor/frontend.sh@@ -51,8 +51,9 @@ fisetsid env \PORT="${FRONTEND_PORT}" \VITE_LOCAL_SERVERS=ALL \- VITE_LOCAL_BACKEND_ORIGIN="${PROXY_ORIGIN}" \- VITE_AI_EDITING_WORKER_URL="${PROXY_ORIGIN}/ai-editing" \+ VITE_LOCAL_BACKEND_ORIGIN="same-origin" \+ MACRO_LOCAL_BACKEND_PROXY="${PROXY_ORIGIN}" \+ VITE_AI_EDITING_WORKER_URL="/ai-editing" \bun run --bun dev >>"${DEV_LOG}" 2>&1 </dev/null &echo "$!" >"${PID_FILE}"diff --git a/.github/services-config.json b/.github/services-config.jsonindex c76e2fa358..9a26758174 100644--- a/.github/services-config.json+++ b/.github/services-config.json@@ -7,7 +7,9 @@"crates/agent_fold/**","crates/agent_session/**","crates/agent_trigger/**",- "crates/agent_runtime_protocol/**"+ "crates/agent_runtime_protocol/**",+ "crates/agent_preview/**",+ "crates/agent_egress/**"],"stack_path": "infra/stacks/agent-harness-service/**","deploy_binaries": [@@ -295,6 +297,17 @@"crates/macro_event_topics/**"],"stack_path": "infra/stacks/kafka-cluster/**"+ },+ "preview-gateway": {+ "bootstrap_pending": "Requires an isolated preview domain, Pulumi stacks, and Doppler configs; see services/preview_gateway/README.md",+ "source_paths": [+ "services/preview_gateway/**",+ "crates/agent_preview/**"+ ],+ "stack_path": "infra/stacks/preview-gateway/**",+ "deploy_binaries": [+ "preview_gateway"+ ]}}}diff --git a/.github/workflows/code_check_cloud_storage.yml b/.github/workflows/code_check_cloud_storage.ymlindex 40750b214d..a2f6361cd6 100644--- a/.github/workflows/code_check_cloud_storage.yml+++ b/.github/workflows/code_check_cloud_storage.yml@@ -63,6 +63,7 @@ jobs:- '.github/actions/setup-nix-dev-shell/**'- '.github/actions/teardown-nix/**'- '.github/actions/setup-sccache/**'+ - '.github/services-config.json'- .github/workflows/code_check_cloud_storage.yml- name: compute changed filesif: steps.filter.outputs.should_run == 'true'diff --git a/.github/workflows/deploy_all_services.yml b/.github/workflows/deploy_all_services.ymlindex 595f4615ae..7c0245f493 100644--- a/.github/workflows/deploy_all_services.yml+++ b/.github/workflows/deploy_all_services.yml@@ -51,10 +51,10 @@ jobs:cfg=.github/services-config.json# Enabled services drive deploy-services; the filtered lists keep each# build matrix to only enabled services that produce that artifact, so- # disabled services and empty artifact jobs consume no runners.- services=$(jq -c '[.services | to_entries[] | select(.value.deploy_enabled != false) | .key]' "$cfg")- binaries=$(jq -c '[.services | to_entries[] | select(.value.deploy_enabled != false) | select((.value.deploy_binaries // []) | length > 0) | .key]' "$cfg")- lambdas=$(jq -c '[.services | to_entries[] | select(.value.deploy_enabled != false) | select((.value.deploy_lambdas // []) | length > 0) | .key]' "$cfg")+ # disabled/unbootstrapped services and empty artifact jobs consume no runners.+ services=$(jq -c '[.services | to_entries[] | select(.value.deploy_enabled != false and .value.bootstrap_pending == null) | .key]' "$cfg")+ binaries=$(jq -c '[.services | to_entries[] | select(.value.deploy_enabled != false and .value.bootstrap_pending == null) | select((.value.deploy_binaries // []) | length > 0) | .key]' "$cfg")+ lambdas=$(jq -c '[.services | to_entries[] | select(.value.deploy_enabled != false and .value.bootstrap_pending == null) | select((.value.deploy_lambdas // []) | length > 0) | .key]' "$cfg")echo "matrix=${services}" >> "$GITHUB_OUTPUT"echo "binaries=${binaries}" >> "$GITHUB_OUTPUT"echo "lambdas=${lambdas}" >> "$GITHUB_OUTPUT"diff --git a/.github/workflows/pulumi_preview_pr.yml b/.github/workflows/pulumi_preview_pr.ymlindex 2c85502811..eb164bccbe 100644--- a/.github/workflows/pulumi_preview_pr.yml+++ b/.github/workflows/pulumi_preview_pr.yml@@ -97,6 +97,11 @@ jobs:# Check each service for changesfor service in $(echo "$config" | jq -r '.services | keys[]'); do+ bootstrap_pending=$(jq -r --arg s "$service" '.services[$s].bootstrap_pending // empty' <<< "$config")+ if jq -e --arg s "$service" '.services[$s].bootstrap_pending != null' <<< "$config" > /dev/null; then+ echo "::notice::Deferring $service live infrastructure checks: $bootstrap_pending"+ continue+ fiservice_changed=false# Workspace/build-system changes can affect every deployable.diff --git a/.github/workflows/reusable_deploy_service.yml b/.github/workflows/reusable_deploy_service.ymlindex 2807f40582..0a9b0db615 100644--- a/.github/workflows/reusable_deploy_service.yml+++ b/.github/workflows/reusable_deploy_service.yml@@ -55,6 +55,11 @@ jobs:run: |set -euo pipefailcfg=.github/services-config.json+ if jq -e --arg service "$SERVICE" '.services[$service].bootstrap_pending != null' "$cfg" > /dev/null; then+ reason=$(jq -r --arg service "$SERVICE" '.services[$service].bootstrap_pending' "$cfg")+ echo "::error::Cannot deploy $SERVICE before bootstrap: $reason"+ exit 1+ fihas_binaries=$(jq -r --arg service "$SERVICE" '((.services[$service].deploy_binaries // []) | length) > 0' "$cfg")has_lambdas=$(jq -r --arg service "$SERVICE" '((.services[$service].deploy_lambdas // []) | length) > 0' "$cfg")echo "has_binaries=$has_binaries" >> "$GITHUB_OUTPUT"diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex e7d898098a..fc682b9d15 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -695,6 +695,45 @@"crates/user_quota","crates/workspace-hack"],+ "agent_preview": [+ "crates/agent",+ "crates/agent_fold",+ "crates/agent_preview",+ "crates/agent_runtime_protocol",+ "crates/ai_toolset",+ "crates/ai_usage",+ "crates/attachment",+ "crates/bot_id",+ "crates/bot_token",+ "crates/cowlike",+ "crates/database_env_vars",+ "crates/document_sub_type",+ "crates/entity_access",+ "crates/genai_telemetry",+ "crates/harness_id",+ "crates/harness_token",+ "crates/macro_auth",+ "crates/macro_authorization",+ "crates/macro_entrypoint",+ "crates/macro_env",+ "crates/macro_env_var",+ "crates/macro_user_id",+ "crates/macro_uuid",+ "crates/model",+ "crates/model-entity",+ "crates/model-error-response",+ "crates/model_file_type",+ "crates/model_owner",+ "crates/model_user",+ "crates/models_bulk_upload",+ "crates/models_entity_access_management",+ "crates/models_pagination",+ "crates/models_permissions",+ "crates/non_empty",+ "crates/prompt",+ "crates/remote_env_var",+ "crates/workspace-hack"+ ],"agent_runtime_protocol": ["crates/agent_runtime_protocol","crates/macro_uuid"@@ -8277,6 +8316,110 @@"predicate-index": ["crates/predicate_index"],+ "preview_gateway": [+ "crates/activity",+ "crates/agent",+ "crates/agent_egress",+ "crates/agent_fold",+ "crates/agent_preview",+ "crates/agent_runtime_protocol",+ "crates/agent_session",+ "crates/ai_toolset",+ "crates/ai_usage",+ "crates/attachment",+ "crates/bot_id",+ "crates/bot_token",+ "crates/bots",+ "crates/broadcast",+ "crates/channel_sender",+ "crates/channels",+ "crates/comms_db_client",+ "crates/connection",+ "crates/connection_gateway_client",+ "crates/connection_gateway_models",+ "crates/contacts",+ "crates/cowlike",+ "crates/database_env_vars",+ "crates/document_sub_type",+ "crates/documents",+ "crates/embedding",+ "crates/entity_access",+ "crates/entity_access_db_utils",+ "crates/entity_access_management",+ "crates/entity_mutation",+ "crates/entity_registry/entity_registry",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry",+ "crates/filter_ast",+ "crates/foreign_entity",+ "crates/frecency",+ "crates/fusionauth",+ "crates/genai_telemetry",+ "crates/github",+ "crates/harness_id",+ "crates/harness_token",+ "crates/invite_email",+ "crates/item_filters",+ "crates/kafka_util",+ "crates/last_online_tracker",+ "crates/lexical_client",+ "crates/macro_auth",+ "crates/macro_authorization",+ "crates/macro_aws_config",+ "crates/macro_config",+ "crates/macro_config_derive",+ "crates/macro_cors",+ "crates/macro_db_client",+ "crates/macro_entrypoint",+ "crates/macro_env",+ "crates/macro_env_var",+ "crates/macro_event_broker",+ "crates/macro_event_topics",+ "crates/macro_service_urls",+ "crates/macro_sync_service_jwt",+ "crates/macro_tower_layers",+ "crates/macro_user_id",+ "crates/macro_uuid",+ "crates/mcp_toolset",+ "crates/mention_utils",+ "crates/messages",+ "crates/model",+ "crates/model-entity",+ "crates/model-error-response",+ "crates/model_file_type",+ "crates/model_notifications",+ "crates/model_owner",+ "crates/model_user",+ "crates/models_bulk_upload",+ "crates/models_dcs",+ "crates/models_entity_access_management",+ "crates/models_opensearch",+ "crates/models_pagination",+ "crates/models_permissions",+ "crates/models_properties",+ "crates/models_sfs",+ "crates/models_team",+ "crates/non_empty",+ "crates/notification",+ "crates/notification_state",+ "crates/pipedream_mcp",+ "crates/prompt",+ "crates/rate_limit",+ "crates/remote_env_var",+ "crates/s3_key",+ "crates/secretsmanager_client",+ "crates/share_permission_db_utils",+ "crates/sqs_worker",+ "crates/static_file_service_client",+ "crates/sync_service",+ "crates/sync_service_client",+ "crates/system_properties",+ "crates/system_skills",+ "crates/task_dedup",+ "crates/user_quota",+ "crates/workspace-hack",+ "services/preview_gateway"+ ],"projects": ["crates/activity","crates/agent",diff --git a/Cargo.lock b/Cargo.lockindex 684928ba14..765bbe4e64 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -56,7 +56,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"dependencies = ["crypto-common 0.1.6",- "generic-array",+ "generic-array 0.14.9",+]++[[package]]+name = "aead"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"+dependencies = [+ "crypto-common 0.2.2",+ "inout 0.2.2",][[package]]@@ -76,25 +86,52 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"dependencies = ["cfg-if",- "cipher",+ "cipher 0.4.4","cpufeatures 0.2.17",]+[[package]]+name = "aes"+version = "0.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32"+dependencies = [+ "cipher 0.5.2",+ "cpubits",+ "cpufeatures 0.3.0",+ "zeroize",+]+[[package]]name = "aes-gcm"version = "0.10.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"dependencies = [- "aead",- "aes",- "cipher",- "ctr",- "ghash",+ "aead 0.5.2",+ "aes 0.8.4",+ "cipher 0.4.4",+ "ctr 0.9.2",+ "ghash 0.5.1","subtle","zeroize",]+[[package]]+name = "aes-gcm"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f2b8006a0c83f52b62ba44a97b58bf76fe2f70a329e588f67f89691d93d498f"+dependencies = [+ "aead 0.6.1",+ "aes 0.9.3",+ "cipher 0.5.2",+ "ctr 0.10.1",+ "ctutils",+ "ghash 0.6.0",+ "zeroize",+]+[[package]]name = "agent"version = "0.1.0"@@ -480,6 +517,42 @@ dependencies = ["workspace-hack",]+[[package]]+name = "agent_preview"+version = "0.1.0"+dependencies = [+ "agent_fold",+ "ai_toolset",+ "async-trait",+ "axum",+ "base64 0.22.1",+ "bytes",+ "entity_access",+ "futures-util",+ "http-body-util",+ "hyper 1.9.0",+ "hyper-util",+ "macro_authorization",+ "macro_user_id",+ "rand 0.9.4",+ "rmcp",+ "rootcause",+ "russh",+ "schemars 1.2.1",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "tempfile",+ "thiserror 2.0.18",+ "tokio",+ "tokio-tungstenite 0.28.0",+ "tokio-util",+ "tower 0.5.3",+ "tracing",+ "url",+ "workspace-hack",+]+[[package]]name = "agent_runtime_protocol"version = "0.1.0"@@ -1159,6 +1232,18 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "argon2"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c"+dependencies = [+ "base64ct",+ "blake2",+ "cpufeatures 0.3.0",+ "password-hash",+]+[[package]]name = "ariadne"version = "0.6.0"@@ -1698,7 +1783,7 @@ dependencies = [name = "authentication_service"version = "0.1.0"dependencies = [- "aes-gcm",+ "aes-gcm 0.10.3","ai_billing","analytics_client","anyhow",@@ -2312,13 +2397,13 @@ dependencies = ["aws-smithy-runtime-api","aws-smithy-types","bytes",- "crypto-bigint",+ "crypto-bigint 0.5.5","form_urlencoded","hex","hmac 0.13.0","http 0.2.12","http 1.4.0",- "p256",+ "p256 0.13.2","percent-encoding","sha2 0.11.0","subtle",@@ -2700,6 +2785,12 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"+[[package]]+name = "base16ct"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6"+[[package]]name = "base64"version = "0.13.1"@@ -2743,6 +2834,17 @@ dependencies = ["serde",]+[[package]]+name = "bcrypt-pbkdf"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "144e573728da132683b9488acd528274c790e07fc06ff81ee29f9d8f8b1041e0"+dependencies = [+ "blowfish",+ "pbkdf2 0.13.0",+ "sha2 0.11.0",+]+[[package]]name = "bebop"version = "3.2.3"@@ -2760,7 +2862,7 @@ checksum = "4d6867f1565b3aad85681f1015055b087fcfd840d6aeee6eee7f2da317603695"dependencies = ["autocfg","libm",- "num-bigint",+ "num-bigint 0.4.6","num-integer","num-traits",]@@ -2851,13 +2953,22 @@ dependencies = ["wyz",]+[[package]]+name = "blake2"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f"+dependencies = [+ "digest 0.11.3",+]+[[package]]name = "block-buffer"version = "0.10.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"dependencies = [- "generic-array",+ "generic-array 0.14.9",][[package]]@@ -2865,6 +2976,16 @@ name = "block-buffer"version = "0.12.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be"+dependencies = [+ "hybrid-array",+ "zeroize",+]++[[package]]+name = "block-padding"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"dependencies = ["hybrid-array",]@@ -2891,6 +3012,16 @@ dependencies = ["piper",]+[[package]]+name = "blowfish"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "62ce3946557b35e71d1bbe07ec385073ce9eda05043f95de134eb578fcf1a298"+dependencies = [+ "byteorder",+ "cipher 0.5.2",+]+[[package]]name = "bollard"version = "0.21.0"@@ -3461,6 +3592,15 @@ dependencies = ["rustversion",]+[[package]]+name = "cbc"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"+dependencies = [+ "cipher 0.5.2",+]+[[package]]name = "cc"version = "1.2.62"@@ -3534,8 +3674,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601"dependencies = ["cfg-if",+ "cipher 0.5.2","cpufeatures 0.3.0","rand_core 0.10.1",+ "zeroize",][[package]]@@ -3759,7 +3901,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"dependencies = ["crypto-common 0.1.6",- "inout",+ "inout 0.1.4",+]++[[package]]+name = "cipher"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"+dependencies = [+ "block-buffer 0.12.0",+ "crypto-common 0.2.2",+ "inout 0.2.2",+ "zeroize",][[package]]@@ -3920,7 +4074,7 @@ dependencies = [name = "codex_connection"version = "0.1.0"dependencies = [- "aes-gcm",+ "aes-gcm 0.10.3","async-trait","aws-sdk-kms","chrono",@@ -4547,6 +4701,12 @@ dependencies = ["either",]+[[package]]+name = "cpubits"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"+[[package]]name = "cpufeatures"version = "0.2.17"@@ -4763,19 +4923,36 @@ version = "0.5.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"dependencies = [- "generic-array",+ "generic-array 0.14.9","rand_core 0.6.4","subtle","zeroize",]+[[package]]+name = "crypto-bigint"+version = "0.7.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a52aa3fcda4e6302a9f48734f234d35d4721b96f8fe07d073f07ce9df4f0271"+dependencies = [+ "cpubits",+ "ctutils",+ "getrandom 0.4.2",+ "hybrid-array",+ "num-traits",+ "rand_core 0.10.1",+ "serdect",+ "subtle",+ "zeroize",+]+[[package]]name = "crypto-common"version = "0.1.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"dependencies = [- "generic-array",+ "generic-array 0.14.9","rand_core 0.6.4","typenum",]@@ -4786,7 +4963,9 @@ version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"dependencies = [+ "getrandom 0.4.2","hybrid-array",+ "rand_core 0.10.1",][[package]]@@ -4842,7 +5021,16 @@ version = "0.9.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"dependencies = [- "cipher",+ "cipher 0.4.4",+]++[[package]]+name = "ctr"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21"+dependencies = [+ "cipher 0.5.2",][[package]]@@ -4852,6 +5040,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"dependencies = ["cmov",+ "subtle",][[package]]@@ -4910,7 +5099,24 @@ dependencies = ["cpufeatures 0.2.17","curve25519-dalek-derive","digest 0.10.7",- "fiat-crypto",+ "fiat-crypto 0.2.9",+ "rustc_version",+ "subtle",+ "zeroize",+]++[[package]]+name = "curve25519-dalek"+version = "5.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.0",+ "curve25519-dalek-derive",+ "digest 0.11.3",+ "fiat-crypto 0.3.0",+ "rand_core 0.10.1","rustc_version","subtle","zeroize",@@ -5179,6 +5385,17 @@ version = "0.1.12"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2"+[[package]]+name = "delegate"+version = "0.13.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "780eb241654bf097afb00fc5f054a09b687dad862e485fdcf8399bb056565370"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "delete_chat_handler"version = "0.1.0"@@ -5238,7 +5455,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"dependencies = ["const-oid 0.9.6",- "pem-rfc7468",+ "pem-rfc7468 0.7.0",+ "zeroize",+]++[[package]]+name = "der"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a"+dependencies = [+ "const-oid 0.10.2",+ "pem-rfc7468 1.0.0","zeroize",]@@ -5340,6 +5568,15 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "des"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "916a94e407b54f9034d71dd748234cd1e516ced6284009906ae246f177eafe5a"+dependencies = [+ "cipher 0.5.2",+]+[[package]]name = "determinator"version = "0.12.0"@@ -6099,12 +6336,27 @@ version = "0.16.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"dependencies = [- "der",+ "der 0.7.10","digest 0.10.7",- "elliptic-curve",- "rfc6979",- "signature",- "spki",+ "elliptic-curve 0.13.8",+ "rfc6979 0.4.0",+ "signature 2.2.0",+ "spki 0.7.3",+]++[[package]]+name = "ecdsa"+version = "0.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0"+dependencies = [+ "der 0.8.2",+ "digest 0.11.3",+ "elliptic-curve 0.14.1",+ "rfc6979 0.6.0",+ "signature 3.0.0",+ "spki 0.8.0",+ "zeroize",][[package]]@@ -6113,8 +6365,18 @@ version = "2.2.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"dependencies = [- "pkcs8",- "signature",+ "pkcs8 0.10.2",+ "signature 2.2.0",+]++[[package]]+name = "ed25519"+version = "3.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"+dependencies = [+ "pkcs8 0.11.0",+ "signature 3.0.0",][[package]]@@ -6123,14 +6385,30 @@ version = "2.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"dependencies = [- "curve25519-dalek",- "ed25519",+ "curve25519-dalek 4.1.3",+ "ed25519 2.2.3","serde","sha2 0.10.9","subtle","zeroize",]+[[package]]+name = "ed25519-dalek"+version = "3.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"+dependencies = [+ "curve25519-dalek 5.0.0",+ "ed25519 3.0.0",+ "rand_core 0.10.1",+ "serde",+ "sha2 0.11.0",+ "signature 3.0.0",+ "subtle",+ "zeroize",+]+[[package]]name = "ego-tree"version = "0.6.3"@@ -6152,17 +6430,39 @@ version = "0.13.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"dependencies = [- "base16ct",- "crypto-bigint",+ "base16ct 0.2.0",+ "crypto-bigint 0.5.5","digest 0.10.7",- "ff",- "generic-array",- "group",- "hkdf",- "pem-rfc7468",- "pkcs8",+ "ff 0.13.1",+ "generic-array 0.14.9",+ "group 0.13.0",+ "hkdf 0.12.4",+ "pem-rfc7468 0.7.0",+ "pkcs8 0.10.2","rand_core 0.6.4",- "sec1",+ "sec1 0.7.3",+ "subtle",+ "zeroize",+]++[[package]]+name = "elliptic-curve"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d65aa39b3a5c1c9c1b745c9a019234bb7a21b77abcb4f4d266d706e2d577d65"+dependencies = [+ "base16ct 1.0.0",+ "crypto-bigint 0.7.5",+ "crypto-common 0.2.2",+ "digest 0.11.3",+ "ff 0.14.0",+ "group 0.14.0",+ "hkdf 0.13.0",+ "hybrid-array",+ "pem-rfc7468 1.0.0",+ "pkcs8 0.11.0",+ "rand_core 0.10.1",+ "sec1 0.8.1","subtle","zeroize",]@@ -6992,12 +7292,28 @@ dependencies = ["subtle",]+[[package]]+name = "ff"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f"+dependencies = [+ "rand_core 0.10.1",+ "subtle",+]+[[package]]name = "fiat-crypto"version = "0.2.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"+[[package]]+name = "fiat-crypto"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"+[[package]]name = "filter_ast"version = "0.1.0"@@ -7391,6 +7707,17 @@ dependencies = ["zeroize",]+[[package]]+name = "generic-array"+version = "1.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb130435a959a8d525e6bca66ff6c40981a300ee96d70e3ef56f046556d614a3"+dependencies = [+ "generic-array 0.14.9",+ "rustversion",+ "typenum",+]+[[package]]name = "generic-btree"version = "0.10.7"@@ -7521,17 +7848,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"dependencies = ["opaque-debug",- "polyval",+ "polyval 0.6.2",][[package]]-name = "gif"-version = "0.14.2"+name = "ghash"+version = "0.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"+checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5"dependencies = [- "color_quant",- "weezl",+ "polyval 0.7.3",+ "zeroize",+]++[[package]]+name = "gif"+version = "0.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"+dependencies = [+ "color_quant",+ "weezl",][[package]]@@ -7924,11 +8261,22 @@ version = "0.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"dependencies = [- "ff",+ "ff 0.13.1","rand_core 0.6.4","subtle",]+[[package]]+name = "group"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4"+dependencies = [+ "ff 0.14.0",+ "rand_core 0.10.1",+ "subtle",+]+[[package]]name = "gtm_invite"version = "0.1.0"@@ -8313,6 +8661,12 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]+name = "hex-literal"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e712f64ec3850b98572bffac52e2c6f282b29fe6c5fa6d42334b30be438d95c1"+[[package]]name = "hickory-net"version = "0.26.1"@@ -8392,6 +8746,15 @@ dependencies = ["hmac 0.12.1",]+[[package]]+name = "hkdf"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"+dependencies = [+ "hmac 0.13.0",+]+[[package]]name = "hmac"version = "0.12.1"@@ -8580,11 +8943,14 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"[[package]]name = "hybrid-array"-version = "0.4.12"+version = "0.4.15"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da"+checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"dependencies = [+ "ctutils",+ "subtle","typenum",+ "zeroize",][[package]]@@ -9248,7 +9614,17 @@ version = "0.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"dependencies = [- "generic-array",+ "generic-array 0.14.9",+]++[[package]]+name = "inout"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"+dependencies = [+ "block-padding",+ "hybrid-array",][[package]]@@ -9596,19 +9972,19 @@ version = "10.3.0"source = "git+https://github.com/whutchinson98/jsonwebtoken#c8c0d19511a0e7ba9d456e21437a79d321e99f16"dependencies = ["base64 0.22.1",- "ed25519-dalek",+ "ed25519-dalek 2.2.0","getrandom 0.2.17","hmac 0.12.1","js-sys",- "p256",- "p384",+ "p256 0.13.2",+ "p384 0.13.1","pem","rand 0.8.6","rsa","serde","serde_json","sha2 0.10.9",- "signature",+ "signature 2.2.0","simple_asn1",]@@ -9619,18 +9995,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "eba32bfb4ffdeaca3e34431072faf01745c9b26d25504aa7a6cf5684334fc4fc"dependencies = ["base64 0.22.1",- "ed25519-dalek",+ "ed25519-dalek 2.2.0","getrandom 0.2.17","hmac 0.12.1","js-sys",- "p256",- "p384",+ "p256 0.13.2",+ "p384 0.13.1","rand 0.8.6","rsa","serde","serde_json","sha2 0.10.9",- "signature",+ "signature 2.2.0","zeroize",]@@ -9653,6 +10029,26 @@ dependencies = ["workspace-hack",]+[[package]]+name = "keccak"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8f198d1db720e4940b5a493201d199d9f24f568f8f746bd13706243a2f71598"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.0",+]++[[package]]+name = "kem"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01737161ba802849cfd486b5bd209d38ba4943494c249a8126005170c7621edd"+dependencies = [+ "crypto-common 0.2.2",+ "rand_core 0.10.1",+]+[[package]]name = "lambda_client"version = "0.1.0"@@ -10190,7 +10586,7 @@ dependencies = ["loro-kv-store","loro-rle","loro_fractional_index",- "md5",+ "md5 0.7.0","nonmax","num","num-traits",@@ -10853,7 +11249,7 @@ dependencies = [name = "mcp_client"version = "0.1.0"dependencies = [- "aes-gcm",+ "aes-gcm 0.10.3","agent","ai_toolset","anyhow",@@ -11004,6 +11400,12 @@ version = "0.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"+[[package]]+name = "md5"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ebb8d8732c6a6df3d8f032a82911cfc747e00efb95cc46e8d0acd5b5b88570c"+[[package]]name = "memchr"version = "2.8.0"@@ -11273,6 +11675,20 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "ml-kem"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e15f3e5b957493873e396a66914e83e616b6afe335cdef7efe5c6e1216aba66"+dependencies = [+ "hybrid-array",+ "kem",+ "module-lattice",+ "pkcs8 0.11.0",+ "rand_core 0.10.1",+ "sha3 0.11.0",+]+[[package]]name = "mobile_welcome_email_db_client"version = "0.1.0"@@ -11642,6 +12058,17 @@ dependencies = ["workspace-hack",]+[[package]]+name = "module-lattice"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c61b87c9683ab7cb1c6871d261ad5479b6b10ceb52c4352aaca3b5d35a8febe"+dependencies = [+ "ctutils",+ "hybrid-array",+ "num-traits",+]+[[package]]name = "moka"version = "0.12.15"@@ -12064,7 +12491,7 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"dependencies = [- "num-bigint",+ "num-bigint 0.4.6","num-complex","num-integer","num-iter",@@ -12082,6 +12509,18 @@ dependencies = ["num-traits",]+[[package]]+name = "num-bigint"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0"+dependencies = [+ "num-integer",+ "num-traits",+ "rand 0.10.1",+ "rand_core 0.10.1",+]+[[package]]name = "num-bigint-dig"version = "0.8.6"@@ -12165,7 +12604,7 @@ version = "0.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"dependencies = [- "num-bigint",+ "num-bigint 0.4.6","num-integer","num-traits",]@@ -12722,24 +13161,65 @@ version = "0.13.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b"dependencies = [- "ecdsa",- "elliptic-curve",- "primeorder",+ "ecdsa 0.16.9",+ "elliptic-curve 0.13.8",+ "primeorder 0.13.6","sha2 0.10.9",]+[[package]]+name = "p256"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a"+dependencies = [+ "ecdsa 0.17.0",+ "elliptic-curve 0.14.1",+ "primefield",+ "primeorder 0.14.0",+ "sha2 0.11.0",+]+[[package]]name = "p384"version = "0.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6"dependencies = [- "ecdsa",- "elliptic-curve",- "primeorder",+ "ecdsa 0.16.9",+ "elliptic-curve 0.13.8",+ "primeorder 0.13.6","sha2 0.10.9",]+[[package]]+name = "p384"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d17b851e6b3e378ab4ecb07fa2ed23f4d15f075735f8fec9fa1e7bdce5f8301f"+dependencies = [+ "ecdsa 0.17.0",+ "elliptic-curve 0.14.1",+ "fiat-crypto 0.3.0",+ "primefield",+ "primeorder 0.14.0",+ "sha2 0.11.0",+]++[[package]]+name = "p521"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ad64cc32c2dc466317c12ee5853e61f159f9eab1fe7efade0395dc2e7b43449"+dependencies = [+ "base16ct 1.0.0",+ "ecdsa 0.17.0",+ "elliptic-curve 0.14.1",+ "primefield",+ "primeorder 0.14.0",+ "sha2 0.11.0",+]+[[package]]name = "pack1"version = "1.1.0"@@ -12749,6 +13229,26 @@ dependencies = ["bytemuck",]+[[package]]+name = "pageant"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d8eab09a361a4afe0b1668be978cd97e4f052e927a92b0b608cf902965d49ce"+dependencies = [+ "base16ct 1.0.0",+ "byteorder",+ "bytes",+ "delegate",+ "futures",+ "log",+ "rand 0.10.1",+ "sha2 0.11.0",+ "thiserror 2.0.18",+ "tokio",+ "windows",+ "windows-strings",+]+[[package]]name = "parking"version = "2.2.1"@@ -12778,6 +13278,15 @@ dependencies = ["windows-link",]+[[package]]+name = "password-hash"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aab41826031698d6ffcd9cff78ef56ef998e39dc7e5067cdfebe373842d4723b"+dependencies = [+ "phc",+]+[[package]]name = "paste"version = "1.0.15"@@ -12852,6 +13361,16 @@ dependencies = ["hmac 0.12.1",]+[[package]]+name = "pbkdf2"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629"+dependencies = [+ "digest 0.11.3",+ "hmac 0.13.0",+]+[[package]]name = "pdfium-render"version = "0.8.37"@@ -12896,6 +13415,15 @@ dependencies = ["base64ct",]+[[package]]+name = "pem-rfc7468"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9"+dependencies = [+ "base64ct",+]+[[package]]name = "percent-encoding"version = "2.3.2"@@ -12977,6 +13505,16 @@ dependencies = ["sqlx",]+[[package]]+name = "phc"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44dc769b75f93afdddd8c7fa12d685292ddeff1e66f7f0f3a234cf1818afe892"+dependencies = [+ "base64ct",+ "ctutils",+]+[[package]]name = "phf"version = "0.10.1"@@ -13210,9 +13748,26 @@ version = "0.7.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"dependencies = [- "der",- "pkcs8",- "spki",+ "der 0.7.10",+ "pkcs8 0.10.2",+ "spki 0.7.3",+]++[[package]]+name = "pkcs5"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63d440a804ec8d6fafbb6b84471e013286658d373248927692ab3366686220ca"+dependencies = [+ "aes 0.9.3",+ "aes-gcm 0.11.1",+ "cbc",+ "der 0.8.2",+ "pbkdf2 0.13.0",+ "rand_core 0.10.1",+ "scrypt",+ "sha2 0.11.0",+ "spki 0.8.0",][[package]]@@ -13221,8 +13776,20 @@ version = "0.10.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"dependencies = [- "der",- "spki",+ "der 0.7.10",+ "spki 0.7.3",+]++[[package]]+name = "pkcs8"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"+dependencies = [+ "der 0.8.2",+ "pkcs5",+ "rand_core 0.10.1",+ "spki 0.8.0",][[package]]@@ -13270,6 +13837,17 @@ version = "0.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"+[[package]]+name = "poly1305"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"+dependencies = [+ "cpufeatures 0.3.0",+ "universal-hash 0.6.1",+ "zeroize",+]+[[package]]name = "polyval"version = "0.6.2"@@ -13279,7 +13857,19 @@ dependencies = ["cfg-if","cpufeatures 0.2.17","opaque-debug",- "universal-hash",+ "universal-hash 0.5.1",+]++[[package]]+name = "polyval"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd"+dependencies = [+ "cpubits",+ "cpufeatures 0.3.0",+ "universal-hash 0.6.1",+ "zeroize",][[package]]@@ -13429,13 +14019,78 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "preview_gateway"+version = "0.1.0"+dependencies = [+ "agent_egress",+ "agent_preview",+ "agent_session",+ "anyhow",+ "async-trait",+ "aws-sdk-secretsmanager",+ "axum",+ "connection_gateway_client",+ "database_env_vars",+ "doppler-config",+ "entity_access",+ "macro_auth",+ "macro_authorization",+ "macro_aws_config",+ "macro_config",+ "macro_cors",+ "macro_entrypoint",+ "macro_env",+ "macro_env_var",+ "macro_service_urls",+ "macro_user_id",+ "macro_uuid",+ "model-entity",+ "rootcause",+ "secretsmanager_client",+ "serde",+ "serde_json",+ "sqlx",+ "tokio",+ "tokio-util",+ "tracing",+ "workspace-hack",+]++[[package]]+name = "primefield"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4"+dependencies = [+ "crypto-bigint 0.7.5",+ "crypto-common 0.2.2",+ "ff 0.14.0",+ "rand_core 0.10.1",+ "subtle",+ "zeroize",+]+[[package]]name = "primeorder"version = "0.13.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6"dependencies = [- "elliptic-curve",+ "elliptic-curve 0.13.8",+]++[[package]]+name = "primeorder"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06"+dependencies = [+ "elliptic-curve 0.14.1",+ "once_cell",+ "primefield",+ "serdect",+ "wnaf",][[package]]@@ -14198,7 +14853,7 @@ dependencies = ["futures-util","itoa","log",- "num-bigint",+ "num-bigint 0.4.6","percent-encoding","pin-project-lite","rand 0.9.4",@@ -14477,6 +15132,16 @@ dependencies = ["subtle",]+[[package]]+name = "rfc6979"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b"+dependencies = [+ "crypto-bigint 0.7.5",+ "hmac 0.13.0",+]+[[package]]name = "rgb"version = "0.8.53"@@ -14705,15 +15370,107 @@ dependencies = ["num-integer","num-traits","pkcs1",- "pkcs8",+ "pkcs8 0.10.2","rand_core 0.6.4","sha1 0.10.6",- "signature",- "spki",+ "signature 2.2.0",+ "spki 0.7.3",+ "subtle",+ "zeroize",+]++[[package]]+name = "russh"+version = "0.63.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "036204edbd199552a5b3832f63c60dcdf395dc44c7f06b4af1c0e8139cc11bce"+dependencies = [+ "aes 0.9.3",+ "bitflags 2.11.1",+ "block-padding",+ "byteorder",+ "bytes",+ "cbc",+ "cipher 0.5.2",+ "crypto-bigint 0.7.5",+ "ctr 0.10.1",+ "curve25519-dalek 5.0.0",+ "data-encoding",+ "delegate",+ "der 0.8.2",+ "digest 0.11.3",+ "ecdsa 0.17.0",+ "ed25519-dalek 3.0.0",+ "elliptic-curve 0.14.1",+ "enum_dispatch",+ "futures",+ "generic-array 1.4.2",+ "getrandom 0.4.2",+ "ghash 0.6.0",+ "hex-literal",+ "hmac 0.13.0",+ "inout 0.2.2",+ "keccak",+ "log",+ "md5 0.8.1",+ "ml-kem",+ "module-lattice",+ "num-bigint 0.5.1",+ "p256 0.14.0",+ "p384 0.14.0",+ "p521",+ "pageant",+ "pbkdf2 0.13.0",+ "pkcs5",+ "pkcs8 0.11.0",+ "polyval 0.7.3",+ "rand 0.10.1",+ "rand_core 0.10.1",+ "ring",+ "russh-cryptovec",+ "russh-util",+ "salsa20",+ "scrypt",+ "sec1 0.8.1",+ "sha1 0.11.0",+ "sha2 0.11.0",+ "sha3 0.12.0",+ "signature 3.0.0",+ "spki 0.8.0",+ "ssh-encoding",+ "ssh-key","subtle",+ "thiserror 2.0.18",+ "tokio",+ "typenum",+ "universal-hash 0.6.1","zeroize",]+[[package]]+name = "russh-cryptovec"+version = "0.62.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3aec6cb630dbe85d72ffd7bcd95f07e1bd69f9f270ee8adfa1afe443a6331438"+dependencies = [+ "log",+ "nix 0.31.3",+ "ssh-encoding",+ "windows-sys 0.61.2",+]++[[package]]+name = "russh-util"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "668424a5dde0bcb45b55ba7de8476b93831b4aa2fa6947e145f3b053e22c60b6"+dependencies = [+ "chrono",+ "tokio",+ "wasm-bindgen",+ "wasm-bindgen-futures",+]+[[package]]name = "rust-embed"version = "8.11.0"@@ -14938,6 +15695,16 @@ dependencies = ["workspace-hack",]+[[package]]+name = "salsa20"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f874456e72520ff1375a06c588eaf074b0f01f9e9e1aada45bd9b7954a6e42c"+dependencies = [+ "cfg-if",+ "cipher 0.5.2",+]+[[package]]name = "same-file"version = "1.0.6"@@ -15114,6 +15881,18 @@ dependencies = ["tendril 0.4.3",]+[[package]]+name = "scrypt"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d87af57419b594aa23fa95f09f0e06d80d84ba01c26148c43844cad6ff4485f0"+dependencies = [+ "cfg-if",+ "pbkdf2 0.13.0",+ "salsa20",+ "sha2 0.11.0",+]+[[package]]name = "sct"version = "0.7.1"@@ -15309,10 +16088,24 @@ version = "0.7.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"dependencies = [- "base16ct",- "der",- "generic-array",- "pkcs8",+ "base16ct 0.2.0",+ "der 0.7.10",+ "generic-array 0.14.9",+ "pkcs8 0.10.2",+ "subtle",+ "zeroize",+]++[[package]]+name = "sec1"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d"+dependencies = [+ "base16ct 1.0.0",+ "ctutils",+ "der 0.8.2",+ "hybrid-array","subtle","zeroize",]@@ -15739,6 +16532,16 @@ dependencies = ["version_check",]+[[package]]+name = "serdect"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e"+dependencies = [+ "base16ct 1.0.0",+ "serde",+]+[[package]]name = "serial_test"version = "3.4.0"@@ -15847,6 +16650,27 @@ dependencies = ["digest 0.11.3",]+[[package]]+name = "sha3"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be176f1a57ce4e3d31c1a166222d9768de5954f811601fb7ca06fc8203905ce1"+dependencies = [+ "digest 0.11.3",+ "keccak",+]++[[package]]+name = "sha3"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bc9bad02c26382724b2d2692c6f179285e4b54eeecd7968f52a50059c3c11759"+dependencies = [+ "digest 0.11.3",+ "keccak",+ "sponge-cursor",+]+[[package]]name = "sha_cleanup_worker"version = "0.1.0"@@ -15981,6 +16805,16 @@ dependencies = ["rand_core 0.6.4",]+[[package]]+name = "signature"+version = "3.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"+dependencies = [+ "digest 0.11.3",+ "rand_core 0.10.1",+]+[[package]]name = "simd-adler32"version = "0.3.9"@@ -16024,7 +16858,7 @@ version = "0.6.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d"dependencies = [- "num-bigint",+ "num-bigint 0.4.6","num-traits","thiserror 2.0.18","time",@@ -16372,9 +17206,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"dependencies = ["base64ct",- "der",+ "der 0.7.10",]+[[package]]+name = "spki"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d9efca8738c78ee9484207732f728b1ef517bbb1833d6fc0879ca898a522f6f"+dependencies = [+ "base64ct",+ "der 0.8.2",+]++[[package]]+name = "sponge-cursor"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620"+[[package]]name = "sqlx"version = "0.8.6"@@ -16484,9 +17334,9 @@ dependencies = ["futures-core","futures-io","futures-util",- "generic-array",+ "generic-array 0.14.9","hex",- "hkdf",+ "hkdf 0.12.4","hmac 0.12.1","itoa","log",@@ -16526,7 +17376,7 @@ dependencies = ["futures-core","futures-util","hex",- "hkdf",+ "hkdf 0.12.4","hmac 0.12.1","home","itoa",@@ -16628,6 +17478,63 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "ssh-cipher"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d801accda99469cde6d73da741422610fdf6508a72d9a69d1b55cb241c720597"+dependencies = [+ "aead 0.6.1",+ "aes 0.9.3",+ "aes-gcm 0.11.1",+ "chacha20",+ "cipher 0.5.2",+ "ctutils",+ "des",+ "poly1305",+ "ssh-encoding",+ "zeroize",+]++[[package]]+name = "ssh-encoding"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b54d0ed0498daf3f78d82e00e28c8eec9d75a067c4cfbcc7a0f7d0f4077749e"+dependencies = [+ "base64ct",+ "bytes",+ "ctutils",+ "digest 0.11.3",+ "pem-rfc7468 1.0.0",+ "zeroize",+]++[[package]]+name = "ssh-key"+version = "0.7.0-rc.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9a32fae177b74a22aa9c5b01bf7e68b33545be32d9e381e248058d2adc15ce3"+dependencies = [+ "argon2",+ "bcrypt-pbkdf",+ "ctutils",+ "ed25519-dalek 3.0.0",+ "hex",+ "hmac 0.13.0",+ "p256 0.14.0",+ "p384 0.14.0",+ "p521",+ "rand_core 0.10.1",+ "sec1 0.8.1",+ "sha1 0.11.0",+ "sha2 0.11.0",+ "signature 3.0.0",+ "ssh-cipher",+ "ssh-encoding",+ "zeroize",+]+[[package]]name = "stable_deref_trait"version = "1.2.1"@@ -18030,8 +18937,8 @@ version = "0.8.0-pre.3"source = "git+https://github.com/tursodatabase/turso?rev=79163249538197d01dec5ea7f65519454ed792e2#79163249538197d01dec5ea7f65519454ed792e2"dependencies = ["aegis",- "aes",- "aes-gcm",+ "aes 0.8.4",+ "aes-gcm 0.10.3","allocator-api2 0.4.0","antithesis_sdk","arc-swap",@@ -18061,7 +18968,7 @@ dependencies = ["libm","loom","miette",- "num-bigint",+ "num-bigint 0.4.6","num-traits","pack1","parking_lot",@@ -18305,6 +19212,16 @@ dependencies = ["subtle",]+[[package]]+name = "universal-hash"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96"+dependencies = [+ "crypto-common 0.2.2",+ "ctutils",+]+[[package]]name = "unsafe-libyaml"version = "0.2.11"@@ -19110,6 +20027,27 @@ version = "0.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"+[[package]]+name = "windows"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"+dependencies = [+ "windows-collections",+ "windows-core",+ "windows-future",+ "windows-numerics",+]++[[package]]+name = "windows-collections"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"+dependencies = [+ "windows-core",+]+[[package]]name = "windows-core"version = "0.62.2"@@ -19123,6 +20061,17 @@ dependencies = ["windows-strings",]+[[package]]+name = "windows-future"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"+dependencies = [+ "windows-core",+ "windows-link",+ "windows-threading",+]+[[package]]name = "windows-implement"version = "0.60.2"@@ -19151,6 +20100,16 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"+[[package]]+name = "windows-numerics"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"+dependencies = [+ "windows-core",+ "windows-link",+]+[[package]]name = "windows-registry"version = "0.6.1"@@ -19271,6 +20230,15 @@ dependencies = ["windows_x86_64_msvc 0.52.6",]+[[package]]+name = "windows-threading"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"+dependencies = [+ "windows-link",+]+[[package]]name = "windows_aarch64_gnullvm"version = "0.42.2"@@ -19556,6 +20524,18 @@ dependencies = ["wayland-protocols-wlr",]+[[package]]+name = "wnaf"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa"+dependencies = [+ "ff 0.14.0",+ "group 0.14.0",+ "hybrid-array",+ "primefield",+]+[[package]]name = "worker"version = "0.8.1"@@ -19655,7 +20635,7 @@ dependencies = [name = "workspace-hack"version = "0.1.0"dependencies = [- "aes-gcm",+ "aes-gcm 0.10.3","ahash","aho-corasick","anyhow",@@ -19682,19 +20662,24 @@ dependencies = ["bzip2","bzip2-sys","cc",+ "chacha20","chrono",+ "cipher 0.5.2","crossbeam-epoch","crossbeam-utils",- "crypto-bigint",+ "crypto-bigint 0.5.5","crypto-common 0.1.6",+ "crypto-common 0.2.2",+ "ctutils","data-encoding","derive_more 2.1.1","derive_more-impl","digest 0.10.7",+ "digest 0.11.3","doppleganger","doppleganger-core","either",- "elliptic-curve",+ "elliptic-curve 0.13.8","errno","event-listener 5.4.2","fastrand 2.4.1",@@ -19709,7 +20694,7 @@ dependencies = ["futures-sink","futures-task","futures-util",- "generic-array",+ "generic-array 0.14.9","getrandom 0.2.17","getrandom 0.3.4","getrandom 0.4.2",@@ -19717,6 +20702,7 @@ dependencies = ["hashbrown 0.16.1","hashbrown 0.17.1","hmac 0.12.1",+ "hybrid-array","hyper 0.14.32","hyper 1.9.0","hyper-rustls 0.24.2",@@ -19724,6 +20710,7 @@ dependencies = ["hyper-util","idna","indexmap 2.14.0",+ "inout 0.2.2","insta","ipnet","itertools 0.13.0",@@ -19735,7 +20722,8 @@ dependencies = ["mime_guess","miniz_oxide","mio 1.2.0",- "num-bigint",+ "nix 0.31.3",+ "num-bigint 0.4.6","num-integer","num-traits","objc2",@@ -19891,6 +20879,8 @@ version = "0.1.0"dependencies = ["anyhow","guppy",+ "serde",+ "serde_json","xtask_graph",]@@ -19981,6 +20971,7 @@ dependencies = ["indoc","serde_json","serde_yaml",+ "tempfile","xtask_paths",]@@ -20077,18 +21068,18 @@ dependencies = [[[package]]name = "zeroize"-version = "1.8.2"+version = "1.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"dependencies = ["zeroize_derive",][[package]]name = "zeroize_derive"-version = "1.4.3"+version = "1.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e"+checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"dependencies = ["proc-macro2","quote",@@ -20136,7 +21127,7 @@ version = "2.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50"dependencies = [- "aes",+ "aes 0.8.4","arbitrary","bzip2","constant_time_eq",@@ -20150,7 +21141,7 @@ dependencies = ["indexmap 2.14.0","lzma-rs","memchr",- "pbkdf2",+ "pbkdf2 0.12.2","sha1 0.10.6","thiserror 2.0.18","time",diff --git a/Cargo.toml b/Cargo.tomlindex 176493eb07..2155d27839 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -5,6 +5,7 @@ members = ["crates/activity","crates/agent", "crates/agent_changes", "crates/agent_egress", "crates/agent_fold","crates/agent_harness",+ "crates/agent_preview","crates/agent_inmem","crates/agent_runtime_protocol", "crates/agent_session","crates/agent_trigger",@@ -99,6 +100,7 @@ members = ["crates/worker-rs-otel","crates/workspace-hack","services/agent_harness_service",+ "services/preview_gateway","services/agent_trigger_service","services/ai_projections_refresh_handler","services/authentication_service",diff --git a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx b/apps/web/src/features/agents-view/components/AgentSessionPane.tsxindex d72c8535d0..f68d7b076e 100644--- a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx+++ b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx@@ -7,6 +7,7 @@ import {} from '@app/features/agent-changes/agent-changes';import { AgentSessionProvider } from '@app/features/block-agent/agent-session-provider';import { AgentComposer } from '@app/features/block-agent/component/AgentComposer';+import { AgentPreviewBanner } from '@app/features/block-agent/component/AgentPreviewBanner';import { AgentPullRequestChip } from '@app/features/block-agent/component/AgentPullRequestChip';import { AgentSessionReadMarker } from '@app/features/block-agent/component/AgentSessionReadMarker';import {@@ -269,6 +270,7 @@ function SessionContent(props: {</Show>}>+ <AgentPreviewBanner /><div class="transcript-host"><Transcript /></div>diff --git a/apps/web/src/features/block-agent/component/AgentPreviewBanner.tsx b/apps/web/src/features/block-agent/component/AgentPreviewBanner.tsxnew file mode 100644index 0000000000..51dbf2b091--- /dev/null+++ b/apps/web/src/features/block-agent/component/AgentPreviewBanner.tsx@@ -0,0 +1,128 @@+import { useUserId } from '@core/context/user';+import { useAgentPreview } from '@queries/agent-session/preview';+import { createSignal, Show } from 'solid-js';+import { useAgentSession } from '../context/AgentSessionContext';++/** Persistent session preview state, independent of transcript/tool-call rendering. */+export function AgentPreviewBanner() {+ const { sessionId, session } = useAgentSession();+ const userId = useUserId();+ const preview = useAgentPreview(sessionId);+ const state = () =>+ preview.query.isSuccess ? preview.query.data.preview : undefined;+ const [busy, setBusy] = createSignal(false);+ const [error, setError] = createSignal<string>();++ const open = async () => {+ // Reserve the tab in the click gesture, before waiting for authorization.+ const tab = window.open('', '_blank');+ if (!tab) {+ setError('Allow popups to open the preview.');+ return;+ }+ tab.opener = null;+ tab.document.title = 'Opening preview…';+ tab.document.body.textContent = 'Opening preview…';+ setError(undefined);+ setBusy(true);+ try {+ const launch = await preview.open();+ if (tab.closed) return;+ if (+ launch.action !== `${state()?.url}/.macro-preview/auth` ||+ !launch.action.startsWith('https://')+ )+ throw new Error('Invalid preview destination');+ const policy = tab.document.createElement('meta');+ policy.name = 'referrer';+ policy.content = 'strict-origin';+ tab.document.head.append(policy);+ const form = tab.document.createElement('form');+ form.method = 'POST';+ form.action = launch.action;+ const input = tab.document.createElement('input');+ input.type = 'hidden';+ input.name = 'ticket';+ input.value = launch.ticket;+ form.append(input);+ tab.document.body.replaceChildren(form);+ form.submit();+ } catch {+ tab.close();+ setError(+ 'Unable to open this preview. It may have ended or your access may have changed.'+ );+ } finally {+ setBusy(false);+ }+ };+ const stop = async () => {+ setBusy(true);+ setError(undefined);+ try {+ await preview.stop();+ } catch {+ setError('Unable to stop sharing. Please try again.');+ } finally {+ setBusy(false);+ }+ };+ const label = () => {+ switch (state()?.status) {+ case 'starting':+ return 'Agent is connecting a preview…';+ case 'ready':+ return 'Agent is sharing a preview';+ case 'expired':+ return 'Preview expired. Ask the agent to share again.';+ case 'offline':+ return 'Preview disconnected. Ask the agent to reconnect.';+ case 'stopped':+ return 'Preview sharing stopped';+ default:+ return '';+ }+ };+ return (+ <Show when={state()}>+ <div+ class="shrink-0 border-b border-edge bg-panel px-4 py-2 text-sm"+ aria-live="polite"+ >+ <div class="flex flex-wrap items-center gap-3">+ <span class="text-ink">{label()}</span>+ <Show when={state()?.status === 'ready'}>+ <button+ type="button"+ class="text-accent hover:underline disabled:opacity-50"+ disabled={busy()}+ onClick={open}+ >+ View preview ↗+ </button>+ </Show>+ <Show+ when={+ session()?.ownerId === userId() &&+ (state()?.status === 'ready' || state()?.status === 'starting')+ }+ >+ <button+ type="button"+ class="text-ink-muted hover:underline disabled:opacity-50"+ disabled={busy()}+ onClick={stop}+ >+ Stop sharing+ </button>+ </Show>+ </div>+ <Show when={error()}>+ <p role="alert" class="mt-1 text-ink-muted">+ {error()}+ </p>+ </Show>+ </div>+ </Show>+ );+}diff --git a/apps/web/src/features/block-agent/component/Block.tsx b/apps/web/src/features/block-agent/component/Block.tsxindex d0d9a59e67..5472cf6e64 100644--- a/apps/web/src/features/block-agent/component/Block.tsx+++ b/apps/web/src/features/block-agent/component/Block.tsx@@ -25,6 +25,7 @@ import { useAgentSession } from '../context/AgentSessionContext';import { forgetPendingSession } from '../context/pending-session';import { parseAgentMessageTarget } from '../core/search-location';import { AgentComposer } from './AgentComposer';+import { AgentPreviewBanner } from './AgentPreviewBanner';import { AgentSessionReadMarker } from './AgentSessionReadMarker';import { AgentSplitHeader } from './AgentSplitHeader';import { AgentSidePanelSections } from './sidepanel/AgentSidePanelSections';@@ -119,6 +120,7 @@ function AgentBlockContent(props: {session={session()}title={metadata()?.title ?? undefined}/>+ <AgentPreviewBanner />{/* The Changes pane opens beside the transcript; closed, thetranscript keeps the whole width. */}<AgentChangesSplit>diff --git a/apps/web/src/features/block-agent/component/session-read-hosts.test.tsx b/apps/web/src/features/block-agent/component/session-read-hosts.test.tsxindex 8f361f48c1..3c0d05ca56 100644--- a/apps/web/src/features/block-agent/component/session-read-hosts.test.tsx+++ b/apps/web/src/features/block-agent/component/session-read-hosts.test.tsx@@ -82,6 +82,9 @@ vi.mock('@core/component/EntityLoadGate', () => ({LoadErrorPanel: () => <div>Unable to load</div>,}));vi.mock('@core/component/EntityIcon', () => ({ EntityIcon: () => null }));+// Chrome, and query-backed: both hosts render it, and this file mounts them+// without a QueryClientProvider.+vi.mock('./AgentPreviewBanner', () => ({ AgentPreviewBanner: () => null }));vi.mock('@core/component/AI/component/ProviderIcon', () => ({modelProvider: () => undefined,ProviderIcon: () => null,diff --git a/apps/web/src/lib/core/constant/servers.ts b/apps/web/src/lib/core/constant/servers.tsindex e84df82377..3470722f7c 100644--- a/apps/web/src/lib/core/constant/servers.ts+++ b/apps/web/src/lib/core/constant/servers.ts@@ -18,6 +18,7 @@ const serverHostLocal: Servers = {'image-proxy-service': 'http://localhost:8097','scheduled-action': 'http://localhost:8099','agent-harness': 'http://localhost:8101',+ preview: 'http://localhost:8110',} as const;const devServerSuffix = import.meta.env.MODE === 'development' ? '-dev' : '';@@ -49,6 +50,7 @@ const serverHostRemote = {'image-proxy-service': `${gatewayHost}/image-proxy`,'scheduled-action': `${gatewayHost}/scheduled-action`,'agent-harness': `${gatewayHost}/agent-harness`,+ preview: `${gatewayHost}/preview`,} as const;type Servers = Record<keyof typeof serverHostRemote, string>;@@ -107,6 +109,7 @@ function proxyServers(): Servers | undefined {'static-file': `${proxyOrigin}/static-file`,'unfurl-service': `${proxyOrigin}/unfurl`,'agent-harness': `${proxyOrigin}/agent-harness`,+ preview: `${proxyOrigin}/preview`,contacts: `${proxyOrigin}/contacts`,'email-service': `${proxyOrigin}/email`,// calendar_service is in the local inventory, so the proxy has a /calendardiff --git a/apps/web/src/lib/queries/agent-session/preview.ts b/apps/web/src/lib/queries/agent-session/preview.tsnew file mode 100644index 0000000000..edeaf651ed--- /dev/null+++ b/apps/web/src/lib/queries/agent-session/preview.ts@@ -0,0 +1,42 @@+import { throwOnErr } from '@core/util/result';+import { useQuery, useQueryClient } from '@tanstack/solid-query';+import { type Accessor, onCleanup } from 'solid-js';+import { previewServiceClient } from '../../service-clients/service-preview/client';+import { subscribeSocketSessionStarted } from './queue-sync';++const listeners = new Set<(sessionId: string) => void>();+/** Paired with preview_gateway's agent_session_preview invalidation event. */+export function handleAgentSessionPreview(event: { agentSessionId: string }) {+ for (const listener of listeners) listener(event.agentSessionId);+}+const key = (sessionId: string | undefined) =>+ ['agentSession', 'preview', sessionId ?? ''] as const;++export function useAgentPreview(sessionId: Accessor<string | undefined>) {+ const client = useQueryClient();+ const invalidate = () =>+ client.invalidateQueries({ queryKey: key(sessionId()) });+ const listener = (id: string) => {+ if (id === sessionId()) void invalidate();+ };+ listeners.add(listener);+ onCleanup(() => listeners.delete(listener));+ onCleanup(subscribeSocketSessionStarted(() => void invalidate()));+ const query = useQuery(() => ({+ queryKey: key(sessionId()),+ queryFn: () => throwOnErr(() => previewServiceClient.get(sessionId()!)),+ enabled: Boolean(sessionId()),+ staleTime: 0,+ // Repairs missed events and gateway restarts; also renews the viewer's event subscription.+ refetchInterval: 30_000,+ retry: false,+ }));+ return {+ query,+ open: () => throwOnErr(() => previewServiceClient.open(sessionId()!)),+ stop: async () => {+ await throwOnErr(() => previewServiceClient.stop(sessionId()!));+ await invalidate();+ },+ };+}diff --git a/apps/web/src/lib/queries/sync/SyncProvider.tsx b/apps/web/src/lib/queries/sync/SyncProvider.tsxindex 4bb3fb6987..611d1d25c0 100644--- a/apps/web/src/lib/queries/sync/SyncProvider.tsx+++ b/apps/web/src/lib/queries/sync/SyncProvider.tsx@@ -6,6 +6,7 @@ import {} from '@core/constant/featureFlags';import { WebsocketEvent } from '@macro-inc/collaboration/websocket';import { handleAgentSessionChanges } from '@queries/agent-session/changes-sync';+import { handleAgentSessionPreview } from '@queries/agent-session/preview';import { handleAgentSessionQueue } from '@queries/agent-session/queue-sync';import {AGENT_SESSION_CHANGES_EVENT,@@ -93,6 +94,13 @@ export function QuerySyncProvider(props: SyncProviderProps) {void handlePullRequestUpdated(payload);});})+ .with({ type: 'agent_session_preview' }, () => {+ withParsedWebsocketPayload<{ agentSessionId: string }>(+ data.type,+ data.data,+ handleAgentSessionPreview+ );+ }).with({ type: 'contacts_invalidation' }, () => {invalidateContacts();})diff --git a/apps/web/src/lib/service-clients/service-preview/client.ts b/apps/web/src/lib/service-clients/service-preview/client.tsnew file mode 100644index 0000000000..85d7054b5c--- /dev/null+++ b/apps/web/src/lib/service-clients/service-preview/client.ts@@ -0,0 +1,34 @@+import { SERVER_HOSTS } from '@core/constant/servers';+import { fetchWithToken } from '@core/util/fetchWithToken';++/** Wire contract with agent_preview::domain::Preview. No credentials in snapshots. */+export type AgentPreview = {+ id: string;+ agentSessionId: string;+ url: string;+ status: 'starting' | 'ready' | 'offline' | 'expired' | 'stopped';+ expiresAt: number;+};+export type PreviewLaunch = { action: string; ticket: string };+const host = SERVER_HOSTS.preview;++export const previewServiceClient = {+ get(sessionId: string) {+ return fetchWithToken<{ preview: AgentPreview | null }>(+ `${host}/agent-sessions/${encodeURIComponent(sessionId)}`,+ { method: 'GET' }+ );+ },+ open(sessionId: string) {+ return fetchWithToken<PreviewLaunch>(+ `${host}/agent-sessions/${encodeURIComponent(sessionId)}/open`,+ { method: 'POST' }+ );+ },+ stop(sessionId: string) {+ return fetchWithToken<Record<string, never>>(+ `${host}/agent-sessions/${encodeURIComponent(sessionId)}`,+ { method: 'DELETE' }+ );+ },+};diff --git a/crates/agent_egress/src/domain/model.rs b/crates/agent_egress/src/domain/model.rsindex 23c829be1f..eb85b18cb0 100644--- a/crates/agent_egress/src/domain/model.rs+++ b/crates/agent_egress/src/domain/model.rs@@ -619,6 +619,7 @@ impl EgressTarget {pub fn name(&self) -> String {match self {Self::McpServer(McpDestination::Macro) => "macro".to_owned(),+ Self::McpServer(McpDestination::Preview) => "macro-preview".to_owned(),Self::McpServer(McpDestination::Connected(slug)) => slug.as_str().to_owned(),Self::GitHubGit { endpoint } => format!("git {}", endpoint.path_and_query()),}@@ -632,6 +633,8 @@ impl EgressTarget {/// is no reserved word to shadow, and no connected app a name could hide.#[derive(Clone, Debug, PartialEq, Eq)]pub enum McpDestination {+ /// Internal, session-scoped live preview tools.+ Preview,/// Macro's own MCP server, available to every session.Macro,/// One of the owner's Pipedream-connected apps.@@ -651,6 +654,9 @@ impl McpDestination {/// same egress URLs a sandbox is, so it reads them the same way the/// router does rather than being told the answer a second way.pub fn from_path(path: &str) -> Option<Self> {+ if path == "/mcp-preview" {+ return Some(Self::Preview);+ }if path == MACRO_MCP_PATH {return Some(Self::Macro);}diff --git a/crates/agent_egress/src/domain/service.rs b/crates/agent_egress/src/domain/service.rsindex e56f701d3b..81aada130f 100644--- a/crates/agent_egress/src/domain/service.rs+++ b/crates/agent_egress/src/domain/service.rs@@ -35,6 +35,7 @@ pub struct EgressServiceImpl<Sessions, Credentials, Tokens, Forward> {credentials: Credentials,tokens: Tokens,forward: Forward,+ preview_mcp: Option<(url::Url, bool)>,}impl<Sessions, Credentials, Tokens, Forward>@@ -45,6 +46,22 @@ whereTokens: GithubTokens,Forward: Forwarder,{+ /// Configure the fixed internal preview MCP destination. Cleartext is local-only.+ pub fn with_preview_mcp(+ mut self,+ url: url::Url,+ local_cleartext: bool,+ ) -> Result<Self, EgressError> {+ if !local_cleartext {+ crate::domain::model::UpstreamCall::bearer(+ url.clone(),+ crate::domain::model::BearerToken::new("validation"),+ )?;+ }+ self.preview_mcp = Some((url, local_cleartext));+ Ok(self)+ }+/// Build the service over its adapters.pub fn new(sessions: Sessions,@@ -57,6 +74,7 @@ wherecredentials,tokens,forward,+ preview_mcp: None,}}}@@ -92,11 +110,11 @@ wherespan.record("session", tracing::field::display(&grant.session));span.record("owner", tracing::field::display(&grant.owner));- // Staff-only for now, checked here so every target - git, connected- // MCP servers, Macro's own - passes one gate. The refusal names- // itself ("not Macro staff") so the sandbox can report an actionable- // reason; the reason is our own static wording, never the request's.- if !is_macro_staff(&grant.owner) {+ // Workspace and Git egress remain staff-only. Session-scoped preview tools+ // are available to every session owner, like the internal MCP tools.+ if !matches!(&target, EgressTarget::McpServer(McpDestination::Preview))+ && !is_macro_staff(&grant.owner)+ {tracing::warn!(owner = %grant.owner, "refusing egress for a session owned outside macro.com");return Err(EgressError::Unauthenticated("the session owner is not Macro staff",@@ -104,6 +122,23 @@ where}let call = match &target {+ EgressTarget::McpServer(McpDestination::Preview) => {+ let (url, local) = self.preview_mcp.as_ref().ok_or_else(|| {+ EgressError::Unroutable("preview service is not configured".into())+ })?;+ // Unlike user tools, this tool must retain the authenticated session identity.+ // The destination is deployment configuration, never supplied by an agent.+ let bearer = crate::domain::model::BearerToken::new(token.as_str());+ if *local {+ crate::domain::model::UpstreamCall::bearer_over_local_cleartext(+ url.clone(),+ bearer,+ )+ } else {+ crate::domain::model::UpstreamCall::bearer(url.clone(), bearer)?+ }+ }+EgressTarget::McpServer(destination @ McpDestination::Macro) => {match self.credentials.resolve(&grant.owner, destination).await? {McpResolution::Connected(call) | McpResolution::Unconnected(call) => call,diff --git a/crates/agent_egress/src/domain/service/test.rs b/crates/agent_egress/src/domain/service/test.rsindex 8998ca55c9..c9eda96186 100644--- a/crates/agent_egress/src/domain/service/test.rs+++ b/crates/agent_egress/src/domain/service/test.rs@@ -148,6 +148,7 @@ impl McpCredentials for SpyCredentials {) -> Result<McpResolution, EgressError> {let slug = match destination {McpDestination::Connected(slug) => slug.clone(),+ McpDestination::Preview => unreachable!("preview must never resolve owner credentials"),McpDestination::Macro => McpServerSlug::parse("macro").expect("slug"),};self.asked@@ -1018,3 +1019,87 @@ async fn a_session_without_a_repository_can_use_mcp_but_cannot_mint_git_credenti));assert!(service.tokens.asked.lock().expect("lock").is_empty());}++#[tokio::test]+async fn preview_uses_only_the_authenticated_session_token_at_a_fixed_destination() {+ let service = EgressServiceImpl::new(+ StubSessions::granting(),+ SpyCredentials::knowing(),+ SpyGithubTokens::default(),+ SpyForwarder::answering(&[]),+ )+ .with_preview_mcp(+ "https://preview-control.example/mcp".parse().unwrap(),+ false,+ )+ .unwrap();+ service+ .proxy(+ &SessionToken::new("session-token"),+ EgressTarget::McpServer(McpDestination::Preview),+ request(Method::POST, &[("authorization", "Bearer attacker-token")]),+ )+ .await+ .unwrap();+ assert_eq!(+ service.forward.forwarded(|parts| parts.uri.to_string()),+ "https://preview-control.example/mcp"+ );+ assert_eq!(+ service+ .forward+ .forwarded(|parts| parts.headers[AUTHORIZATION].to_str().unwrap().to_owned()),+ "Bearer session-token"+ );+ assert!(service.credentials.asked.lock().unwrap().is_empty());+}++#[tokio::test]+async fn non_staff_session_owners_can_share_previews_without_workspace_or_git_access() {+ let service = EgressServiceImpl::new(+ StubSessions(Ok(SessionGrant {+ session: AgentSessionId::new(),+ owner: MacroUserIdStr::try_from_email("[email protected]").unwrap(),+ repo: None,+ mcp_servers: Vec::new(),+ })),+ SpyCredentials::knowing(),+ SpyGithubTokens::default(),+ SpyForwarder::answering(&[]),+ )+ .with_preview_mcp(+ "https://preview-control.example/mcp".parse().unwrap(),+ false,+ )+ .unwrap();+ service+ .proxy(+ &SessionToken::new("session-token"),+ EgressTarget::McpServer(McpDestination::Preview),+ request(Method::POST, &[]),+ )+ .await+ .unwrap();+ assert!(matches!(+ service+ .proxy(+ &SessionToken::new("session-token"),+ EgressTarget::McpServer(McpDestination::Macro),+ request(Method::POST, &[])+ )+ .await,+ Err(EgressError::Unauthenticated(_))+ ));+ assert!(matches!(+ service+ .proxy(+ &SessionToken::new("session-token"),+ git(GitEndpoint::UploadPack),+ request(Method::POST, &[])+ )+ .await,+ Err(EgressError::Unauthenticated(_))+ ));+ assert!(service.credentials.asked.lock().unwrap().is_empty());+ assert!(service.tokens.asked.lock().unwrap().is_empty());+}diff --git a/crates/agent_egress/src/inbound/axum_router.rs b/crates/agent_egress/src/inbound/axum_router.rsindex c95fb42f06..1b27c2bfc4 100644--- a/crates/agent_egress/src/inbound/axum_router.rs+++ b/crates/agent_egress/src/inbound/axum_router.rs@@ -65,6 +65,7 @@ where.route("/health", get(health)).route("/mcp/{slug}", any(mcp_handler::<Service>)).route("/mcp-macro", any(macro_mcp_handler::<Service>))+ .route("/mcp-preview", any(preview_mcp_handler::<Service>)).route("/git/{*path}",get(git_handler::<Service>).post(git_handler::<Service>),@@ -97,6 +98,14 @@ wheremcp_proxy(state, McpDestination::Connected(slug), request).await}+#[tracing::instrument(skip_all, err)]+async fn preview_mcp_handler<Service: EgressService>(+ State(state): State<EgressRouterState<Service>>,+ request: Request,+) -> Result<Response, EgressError> {+ mcp_proxy(state, McpDestination::Preview, request).await+}+/// Macro's own MCP server, on its own route rather than under `/mcp/{slug}`:/// with no name shared between the built-in server and the owner's connected/// apps, no connected app can collide with it.diff --git a/crates/agent_fold/src/domain/log.rs b/crates/agent_fold/src/domain/log.rsindex bcbee2d157..a910a5972a 100644--- a/crates/agent_fold/src/domain/log.rs+++ b/crates/agent_fold/src/domain/log.rs@@ -47,6 +47,22 @@ impl AgentSessionId {}}+/// A string that does not name an agent session.+#[derive(Debug, thiserror::Error)]+#[error("invalid agent session id")]+pub struct InvalidAgentSessionId;++impl std::str::FromStr for AgentSessionId {+ type Err = InvalidAgentSessionId;++ fn from_str(value: &str) -> Result<Self, Self::Err> {+ value+ .parse::<Uuid>()+ .map(Self)+ .map_err(|_| InvalidAgentSessionId)+ }+}+impl std::fmt::Display for AgentSessionId {fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {self.0.fmt(formatter)diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rsindex 8c996cfe87..46784d1573 100644--- a/crates/agent_harness/src/domain/model.rs+++ b/crates/agent_harness/src/domain/model.rs@@ -852,6 +852,10 @@ impl SandboxEgress {INTERNAL_MCP_NAME.to_owned(),format!("{}/mcp/internal", self.base_url),),+ (+ "macro-preview".to_owned(),+ format!("{}/mcp-preview", self.base_url),+ ),].into_iter().chain(@@ -872,6 +876,18 @@ impl SandboxEgress {)}+ /// Preview-only MCP endpoint, authenticated by the same session credential.+ pub fn preview_mcp_server(&self) -> AcpMcpServer {+ AcpMcpServer::Http(+ McpServerHttp::new("macro-preview", format!("{}/mcp-preview", self.base_url)).headers(+ vec![HttpHeader::new(+ "Authorization",+ self.authorization_header(),+ )],+ ),+ )+ }+/// The MCP servers an ACP agent is handed in `session/new`, `session/load`/// and `session/resume`.///diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rsindex 899eb1902f..5e4bc83ecb 100644--- a/crates/agent_harness/src/domain/ports.rs+++ b/crates/agent_harness/src/domain/ports.rs@@ -343,6 +343,14 @@ pub trait RuntimeConnections: Send + Sync + 'static {/// the owner's MCP servers needs their rows. What the domain keeps is *when* -/// once, at spawn, for the session's own owner.pub trait SandboxEgressProvisioner: Send + Sync + 'static {+ /// Internal session tools at an address reachable by an external runtime.+ fn external_mcp_servers(+ &self,+ egress: &SandboxEgress,+ ) -> Vec<agent_client_protocol::schema::v1::McpServer> {+ vec![egress.internal_mcp_server(), egress.preview_mcp_server()]+ }+/// The egress environment for one session, on behalf of `owner`, and the/// hash its session row must carry for that environment to mean anything.///diff --git a/crates/agent_harness/src/domain/service/deliver.rs b/crates/agent_harness/src/domain/service/deliver.rsindex d2a92b69e8..ea593d99a6 100644--- a/crates/agent_harness/src/domain/service/deliver.rs+++ b/crates/agent_harness/src/domain/service/deliver.rs@@ -132,7 +132,7 @@ wheresession_id,attachment.permission_policy(permission_policy)- .mcp_servers(vec![egress.sandbox.internal_mcp_server()]),+ .mcp_servers(self.egress.external_mcp_servers(&egress.sandbox)),).await?;self.restore_queue(session_id).await?;diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rsindex 41adedb191..ffd264c405 100644--- a/crates/agent_harness/src/domain/service/test.rs+++ b/crates/agent_harness/src/domain/service/test.rs@@ -2756,7 +2756,12 @@ async fn an_external_open_provisions_nothing_and_prompts_nobody() {let ClientRequest::NewSessionRequest(open) = &requests[1] else {panic!("expected session/new")};- assert_eq!(open.mcp_servers.len(), 1);+ assert_eq!(open.mcp_servers.len(), 2);+ let agent_client_protocol::schema::v1::McpServer::Http(preview) = &open.mcp_servers[1] else {+ panic!("expected preview HTTP MCP");+ };+ assert_eq!(preview.name, "macro-preview");+ assert!(preview.url.ends_with("/mcp-preview"));let agent_client_protocol::schema::v1::McpServer::Http(server) = &open.mcp_servers[0] else {panic!("expected HTTP MCP")};diff --git a/crates/agent_harness/src/outbound/egress.rs b/crates/agent_harness/src/outbound/egress.rsindex a1a8682a3c..edfdf40339 100644--- a/crates/agent_harness/src/outbound/egress.rs+++ b/crates/agent_harness/src/outbound/egress.rs@@ -26,6 +26,7 @@ mod test;pub struct EgressProvisioner<Connections> {connections: Arc<Connections>,base_url: String,+ external_base_url: Option<String>,}impl<Connections> EgressProvisioner<Connections>@@ -38,9 +39,16 @@ whereSelf {connections,base_url: base_url.into().trim_end_matches('/').to_owned(),+ external_base_url: None,}}+ /// Override only the address advertised to external runtimes, such as host macrod in a local stack.+ pub fn with_external_base_url(mut self, url: Option<String>) -> Self {+ self.external_base_url = url.map(|url| url.trim_end_matches('/').to_owned());+ self+ }+/// The slugs to advertise for one session, verbatim.////// `app_slug`, exactly as the proxy resolves it - the same value at both@@ -115,6 +123,20 @@ impl<Connections> SandboxEgressProvisioner for EgressProvisioner<Connections>whereConnections: ConnectionStore,{+ fn external_mcp_servers(+ &self,+ egress: &SandboxEgress,+ ) -> Vec<agent_client_protocol::schema::v1::McpServer> {+ let mut external = egress.clone();+ if let Some(url) = &self.external_base_url {+ external.base_url = url.clone();+ }+ vec![+ external.internal_mcp_server(),+ external.preview_mcp_server(),+ ]+ }+#[tracing::instrument(err, skip(self), fields(%session, %owner))]async fn provision(&self,diff --git a/crates/agent_harness/src/outbound/egress/test.rs b/crates/agent_harness/src/outbound/egress/test.rsindex 99d1d35be2..51bd9ad7f8 100644--- a/crates/agent_harness/src/outbound/egress/test.rs+++ b/crates/agent_harness/src/outbound/egress/test.rs@@ -238,6 +238,11 @@ fn points_every_acp_server_at_the_proxy() {"https://egress.macro.com/mcp/internal".to_owned(),authorization.clone(),),+ (+ "macro-preview".to_owned(),+ "https://egress.macro.com/mcp-preview".to_owned(),+ authorization.clone(),+ ),("datadog".to_owned(),"https://egress.macro.com/mcp/datadog".to_owned(),@@ -267,6 +272,10 @@ fn an_owner_with_no_connected_apps_still_gets_the_macro_server() {("macro_internal".to_owned(),"https://egress.macro.com/mcp/internal".to_owned()+ ),+ (+ "macro-preview".to_owned(),+ "https://egress.macro.com/mcp-preview".to_owned())]);@@ -295,3 +304,24 @@ fn the_egress_environment_does_not_print_its_secrets() {]);}++#[test]+fn external_runtime_uses_host_reachable_urls_with_the_existing_session_credential() {+ use agent_client_protocol::schema::v1::McpServer;+ let provisioner = EgressProvisioner::new(+ Arc::new(FixedConnections(vec![])),+ "http://agent-harness-service:8102",+ )+ .with_external_base_url(Some("http://localhost:28102/".into()));+ let sandbox = egress(&[]);+ let servers = provisioner.external_mcp_servers(&sandbox);+ assert_eq!(servers.len(), 2);+ for (server, path) in servers.iter().zip(["/mcp/internal", "/mcp-preview"]) {+ let McpServer::Http(server) = server else {+ panic!("expected HTTP MCP");+ };+ assert_eq!(server.url, format!("http://localhost:28102{path}"));+ assert_eq!(server.headers[0].value, sandbox.authorization_header());+ }+ assert_eq!(sandbox.base_url, "https://egress.macro.com");+}diff --git a/crates/agent_preview/Cargo.toml b/crates/agent_preview/Cargo.tomlnew file mode 100644index 0000000000..2430375a21--- /dev/null+++ b/crates/agent_preview/Cargo.toml@@ -0,0 +1,42 @@+[package]+name = "agent_preview"+version = "0.1.0"+edition = "2024"+publish = false++[dependencies]+# The agent-session id vocabulary only. `default-features = false` drops the+# fold's developer binaries, which want clap and tokio; the newtype does not.+agent_fold = { path = "../agent_fold", default-features = false }+ai_toolset = { path = "../ai_toolset" }+async-trait = { workspace = true }+axum = { workspace = true, features = ["ws", "form"] }+base64 = { workspace = true }+bytes = { workspace = true }+entity_access = { path = "../entity_access", default-features = false, features = ["ports", "inbound"] }+macro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum"] }+macro_user_id = { path = "../macro_user_id" }+http-body-util = { workspace = true }+hyper = { version = "1", features = ["client", "http1"] }+hyper-util = { version = "0.1", features = ["tokio"] }+rand = { workspace = true }+rootcause = { workspace = true }+russh = { version = "0.63.3", default-features = false, features = ["ring"] }+rmcp = { workspace = true, features = ["transport-streamable-http-server"] }+schemars = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+sha2 = { workspace = true }+thiserror = { workspace = true }+tokio = { workspace = true, features = ["net", "io-util", "sync", "time", "process"] }+tokio-util = { workspace = true, features = ["rt"] }+tracing = { workspace = true }+url = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+tokio = { workspace = true, features = ["test-util"] }+tempfile = "3"+tower = { workspace = true }+tokio-tungstenite = { workspace = true }+futures-util = "0.3"diff --git a/crates/agent_preview/src/domain/ids.rs b/crates/agent_preview/src/domain/ids.rsnew file mode 100644index 0000000000..7ff32f4968--- /dev/null+++ b/crates/agent_preview/src/domain/ids.rs@@ -0,0 +1,53 @@+//! The routing identity of one preview.++use super::PreviewError;+use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};+use rand::RngCore;+use serde::Serialize;+use sha2::{Digest, Sha256};++/// Length of a routing ID in characters, and so of its DNS label.+const LENGTH: usize = 32;++/// A preview's public routing ID: one DNS label, never an authorization credential.+///+/// Distinct from the agent session that owns the preview. Both reach this crate+/// as user-supplied strings - one in a `Host` header, one in an entity access+/// receipt - and the registry is keyed by the session while credentials point at+/// the preview, so the two must not be interchangeable.+#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]+#[serde(transparent)]+pub struct PreviewId(String);++impl PreviewId {+ /// Mint an unguessable ID.+ ///+ /// DNS labels are case insensitive, so the 256-bit seed is rendered as hex:+ /// unambiguous, and still 128 bits wide.+ #[must_use]+ pub fn generate() -> Self {+ let mut seed = [0u8; 32];+ rand::rng().fill_bytes(&mut seed);+ let digest: [u8; 32] = Sha256::digest(URL_SAFE_NO_PAD.encode(seed).as_bytes()).into();+ Self(+ digest[..LENGTH / 2]+ .iter()+ .map(|byte| format!("{byte:02x}"))+ .collect(),+ )+ }++ /// Accept a routing ID from a request, rejecting anything not of this shape.+ pub fn parse(value: &str) -> Result<Self, PreviewError> {+ if value.len() != LENGTH || !value.bytes().all(|b| b.is_ascii_hexdigit()) {+ return Err(PreviewError::Invalid);+ }+ Ok(Self(value.to_ascii_lowercase()))+ }+}++impl std::fmt::Display for PreviewId {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ self.0.fmt(formatter)+ }+}diff --git a/crates/agent_preview/src/domain/mod.rs b/crates/agent_preview/src/domain/mod.rsnew file mode 100644index 0000000000..38899cee65--- /dev/null+++ b/crates/agent_preview/src/domain/mod.rs@@ -0,0 +1,7 @@+//! Preview leases and authorization.+mod ids;+/// Capabilities supplied by the application composition root.+pub mod ports;+mod service;+pub use ids::PreviewId;+pub use service::*;diff --git a/crates/agent_preview/src/domain/ports.rs b/crates/agent_preview/src/domain/ports.rsnew file mode 100644index 0000000000..1bceaec76f--- /dev/null+++ b/crates/agent_preview/src/domain/ports.rs@@ -0,0 +1,47 @@+//! Capabilities needed to expose an authenticated preview.+use super::{AgentIdentity, Preview, PreviewError};+use agent_fold::domain::log::AgentSessionId;+use async_trait::async_trait;+use macro_user_id::user_id::MacroUserIdStr;+use tokio::io::{AsyncRead, AsyncWrite};++/// Duplex byte stream; independent of its SSH transport.+pub trait Duplex: AsyncRead + AsyncWrite + Unpin + Send {}+impl<T: AsyncRead + AsyncWrite + Unpin + Send> Duplex for T {}+/// A stream opened through a registered reverse tunnel.+pub type Stream = Box<dyn Duplex>;++/// A registered remote forward, never an arbitrary server-side socket address.+#[async_trait]+pub trait Tunnel: Send + Sync {+ /// Open a new connection to the client-selected destination.+ async fn open(&self) -> Result<Stream, PreviewError>;+ /// Terminate the SSH transport and all its streams.+ async fn close(&self);+}++/// Existing session authentication and entity access, supplied by Macro.+#[async_trait]+pub trait Authority: Send + Sync {+ /// Authenticate an agent's existing session token.+ async fn agent(&self, token: &str) -> Result<AgentIdentity, PreviewError>;+ /// Recheck view access and whether the session is still open.+ async fn viewer(+ &self,+ session: AgentSessionId,+ user: &MacroUserIdStr<'_>,+ ) -> Result<(), PreviewError>;+ /// Whether the originating agent session remains open.+ async fn active(&self, session: AgentSessionId) -> Result<(), PreviewError>;+}++/// Publish preview state changes to the existing connection gateway.+#[async_trait]+pub trait Events: Send + Sync {+ /// Notify subscribed viewers; the read endpoint remains authoritative.+ async fn changed(+ &self,+ preview: &Preview,+ viewers: &[MacroUserIdStr<'static>],+ ) -> Result<(), PreviewError>;+}diff --git a/crates/agent_preview/src/domain/service.rs b/crates/agent_preview/src/domain/service.rsnew file mode 100644index 0000000000..eee1b6b241--- /dev/null+++ b/crates/agent_preview/src/domain/service.rs@@ -0,0 +1,694 @@+use super::{+ PreviewId,+ ports::{Authority, Events, Tunnel},+};+use agent_fold::domain::log::AgentSessionId;+use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};+use entity_access::domain::models::{+ EditAccessLevel, EntityAccessReceipt, EntityType, RequiredPermission, ViewAccessLevel,+};+use macro_user_id::user_id::MacroUserIdStr;+use rand::RngCore;+use serde::Serialize;+use sha2::{Digest, Sha256};+use std::{+ collections::HashMap,+ sync::{Arc, Mutex},+ time::{Duration, Instant, SystemTime, UNIX_EPOCH},+};+use tokio::sync::Semaphore;+use tokio_util::sync::CancellationToken;++const LEASE: Duration = Duration::from_secs(3600);+const IDLE: Duration = Duration::from_secs(900);+const TOKEN_TTL: Duration = Duration::from_secs(120);+const TICKET_TTL: Duration = Duration::from_secs(30);++/// Authenticated agent identity, resolved from its session credential.+#[derive(Clone)]+pub struct AgentIdentity {+ /// Agent-session entity ID.+ pub session: AgentSessionId,+ /// Account whose preview quota is charged.+ pub owner: MacroUserIdStr<'static>,+}+/// Public state of one preview; contains no credentials.+#[derive(Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Preview {+ /// Opaque routing ID, not an authorization credential.+ pub id: PreviewId,+ /// Agent-session entity that controls visibility.+ pub agent_session_id: AgentSessionId,+ /// Clean HTTPS origin, with no application path prefix.+ pub url: String,+ /// Current state of the lease.+ pub status: PreviewStatus,+ /// Unix milliseconds at which this lease ends.+ pub expires_at: u64,+}+/// Preview lifecycle visible in the session UI.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum PreviewStatus {+ /// Waiting for SSH and a reachable HTTP server.+ Starting,+ /// HTTP traffic has successfully crossed the tunnel.+ Ready,+ /// The SSH connection closed.+ Offline,+ /// The time or idle lease elapsed.+ Expired,+ /// A user explicitly stopped sharing.+ Stopped,+}+/// A refusal at a preview boundary. Credentials are never included in errors.+#[derive(Debug, thiserror::Error)]+pub enum PreviewError {+ /// Invalid input.+ #[error("invalid preview request")]+ Invalid,+ /// Unknown, expired, revoked, or otherwise unauthorized credential.+ #[error("preview access denied")]+ Denied,+ /// No live preview for this session.+ #[error("preview is offline")]+ Offline,+ /// A resource quota was exceeded.+ #[error("preview resource limit reached")]+ Limited,+ /// An upstream or infrastructure failure.+ #[error("preview service unavailable")]+ Unavailable,+}+/// Deployment addresses and pinned SSH identity; validated on startup.+#[derive(Clone)]+pub struct Settings {+ /// DNS suffix used by per-preview hosts, without a wildcard.+ pub domain: String,+ /// HTTPS port (443 in production; configurable for local TLS).+ pub https_port: u16,+ /// Public SSH hostname.+ pub ssh_host: String,+ /// Public SSH port.+ pub ssh_port: u16,+ /// Optional local Docker endpoint when the host loopback address is unreachable.+ pub local_ssh_fallback: bool,+ /// Local-only public ingress: a Cloudflare quick-tunnel hostname carrying this+ /// SSH listener, for agents that run outside this machine entirely.+ pub ssh_proxy_host: Option<String>,+ /// OpenSSH public host key, algorithm and base64 blob.+ pub host_key: String,+ /// Allowed Macro application origin for browser ticket handoff.+ pub app_origin: String,+}+impl Settings {+ /// Reject invalid shell/host components and Macro's shared cookie domain.+ pub fn validate(&self) -> Result<(), PreviewError> {+ fn host(s: &str) -> bool {+ !s.is_empty()+ && s.len() < 254+ && s.split('.').all(|label| {+ !label.is_empty()+ && label.len() <= 63+ && !label.starts_with('-')+ && !label.ends_with('-')+ && label+ .bytes()+ .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')+ })+ }+ let key: Vec<_> = self.host_key.split_whitespace().collect();+ let app = url::Url::parse(&self.app_origin).map_err(|_| PreviewError::Invalid)?;+ let app_host = app.host_str().ok_or(PreviewError::Invalid)?;+ let local =+ self.domain == "preview.localhost" && app.scheme() == "http" && app_host == "localhost";+ if !host(&self.domain)+ || !host(&self.ssh_host)+ || self.ssh_port == 0+ || self.https_port == 0+ || self.domain == "macro.com"+ || self.domain.ends_with(".macro.com")+ || self.domain == app_host+ // Neither may sit under the other: every non-gateway cookie is+ // forwarded upstream, so a shared parent hands the app's cookies to+ // agent-controlled code. The local stack is the deliberate exception+ // (`preview.localhost` under `localhost`), where the app origin is+ // cleartext loopback and sets nothing worth stealing.+ || app_host.ends_with(&format!(".{}", self.domain))+ || (!local && self.domain.ends_with(&format!(".{app_host}")))+ || (app.scheme() != "https" && !local)+ || (self.local_ssh_fallback && !local)+ || self+ .ssh_proxy_host+ .as_ref()+ .is_some_and(|proxy| !local || !host(proxy))+ || app.origin().ascii_serialization() != self.app_origin+ || key.len() != 2+ || key[0] != "ssh-ed25519"+ || base64::engine::general_purpose::STANDARD+ .decode(key[1])+ .is_err()+ {+ return Err(PreviewError::Invalid);+ }+ Ok(())+ }+ /// Public origin for a routing ID.+ pub fn origin(&self, id: &PreviewId) -> String {+ let port = if self.https_port == 443 {+ String::new()+ } else {+ format!(":{}", self.https_port)+ };+ format!("https://{id}.{}{port}", self.domain)+ }+}+/// Credentials returned only to the authenticated agent's tool call.+pub struct Share {+ /// State initially shown as waiting for connection.+ pub preview: Preview,+ /// Single-use SSH username. Do not log it.+ pub token: String,+ /// Local port the agent requested.+ pub port: u16,+}+/// Browser handoff, posted to the preview origin without touching app URLs.+#[derive(Serialize)]+pub struct Launch {+ /// Cross-origin form action.+ pub action: String,+ /// One-use, 30-second ticket. Do not log it.+ pub ticket: String,+}+struct Credential {+ preview: PreviewId,+ /// Absent on an SSH token: it authenticates the agent's tunnel, not a viewer.+ user: Option<MacroUserIdStr<'static>>,+ expires: Instant,+}+/// Per-owner creation pacing. Traffic itself is unmetered: a shared dev server+/// moves tens of MB per cold load, and every ceiling we tried severed it.+struct AccountBudget {+ last_created: Instant,+}+struct Registry {+ sessions: HashMap<AgentSessionId, Arc<Lease>>,+ accounts: HashMap<MacroUserIdStr<'static>, AccountBudget>,+ ssh_tokens: HashMap<[u8; 32], Credential>,+ tickets: HashMap<[u8; 32], Credential>,+ browsers: HashMap<[u8; 32], Credential>,+ watchers: HashMap<AgentSessionId, HashMap<MacroUserIdStr<'static>, Instant>>,+}+/// Live lease, with cancellation and stream slots shared by every request/upgrade.+pub struct Lease {+ preview: Mutex<Preview>,+ owner: MacroUserIdStr<'static>,+ port: u16,+ expires: Instant,+ activity: Mutex<Instant>,+ tunnel: Mutex<Option<Arc<dyn Tunnel>>>,+ /// Cancellation closes existing HTTP and WebSocket traffic on revocation.+ pub cancel: CancellationToken,+ /// Total HTTP streams, held until response completion.+ pub requests: Arc<Semaphore>,+ /// Upgraded streams, separately capped.+ pub upgrades: Arc<Semaphore>,+}+impl Lease {+ /// Snapshot with no credentials.+ pub fn preview(&self) -> Preview {+ self.preview.lock().expect("preview mutex").clone()+ }+ /// Original local port for generic Host rewriting.+ pub fn port(&self) -> u16 {+ self.port+ }+ /// Check hard and idle deadlines even between sweeper ticks.+ pub fn live(&self) -> bool {+ !self.cancel.is_cancelled()+ && Instant::now() < self.expires+ && self.activity.lock().expect("activity mutex").elapsed() < IDLE+ }+ /// Registered tunnel capability.+ pub fn tunnel(&self) -> Result<Arc<dyn Tunnel>, PreviewError> {+ if !self.live() {+ return Err(PreviewError::Offline);+ }+ self.tunnel+ .lock()+ .expect("tunnel mutex")+ .clone()+ .ok_or(PreviewError::Offline)+ }+}+/// Core use cases; holds ephemeral leases because an SSH transport cannot survive a restart.+#[derive(Clone)]+pub struct PreviewService {+ settings: Arc<Settings>,+ authority: Arc<dyn Authority>,+ events: Arc<dyn Events>,+ registry: Arc<Mutex<Registry>>,+}+impl PreviewService {+ /// Wire authority and notifications around a single-replica registry.+ pub fn new(+ settings: Settings,+ authority: Arc<dyn Authority>,+ events: Arc<dyn Events>,+ ) -> Result<Self, PreviewError> {+ settings.validate()?;+ Ok(Self {+ settings: Arc::new(settings),+ authority,+ events,+ registry: Arc::new(Mutex::new(Registry {+ sessions: HashMap::new(),+ accounts: HashMap::new(),+ ssh_tokens: HashMap::new(),+ tickets: HashMap::new(),+ browsers: HashMap::new(),+ watchers: HashMap::new(),+ })),+ })+ }+ /// Deployment settings for the transport adapters.+ pub fn settings(&self) -> &Settings {+ &self.settings+ }+ /// Authenticate the existing agent session credential.+ pub async fn agent(&self, token: &str) -> Result<AgentIdentity, PreviewError> {+ self.authority.agent(token).await+ }+ /// Create one lease per session, replacing and closing any previous tunnel.+ pub async fn share(&self, identity: AgentIdentity, port: u16) -> Result<Share, PreviewError> {+ if port == 0 {+ return Err(PreviewError::Invalid);+ }+ self.authority.active(identity.session).await?;+ let id = PreviewId::generate();+ let token = random();+ let preview = Preview {+ id: id.clone(),+ agent_session_id: identity.session,+ url: self.settings.origin(&id),+ status: PreviewStatus::Starting,+ expires_at: (SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ + LEASE)+ .as_millis() as u64,+ };+ {+ let mut registry = self.registry.lock().expect("registry mutex");+ if registry.accounts.len() >= 1000 && !registry.accounts.contains_key(&identity.owner) {+ return Err(PreviewError::Limited);+ }+ let account = registry+ .accounts+ .entry(identity.owner.clone())+ .or_insert_with(|| AccountBudget {+ last_created: Instant::now() - TOKEN_TTL,+ });+ if account.last_created.elapsed() < Duration::from_secs(10) {+ return Err(PreviewError::Limited);+ }+ account.last_created = Instant::now();+ }+ let lease = Arc::new(Lease {+ preview: Mutex::new(preview.clone()),+ owner: identity.owner,+ port,+ expires: Instant::now() + LEASE,+ activity: Mutex::new(Instant::now()),+ tunnel: Mutex::new(None),+ cancel: CancellationToken::new(),+ requests: Arc::new(Semaphore::new(512)),+ upgrades: Arc::new(Semaphore::new(8)),+ });+ let old = {+ let mut registry = self.registry.lock().expect("registry mutex");+ if registry.sessions.len() >= 1000 && !registry.sessions.contains_key(&identity.session)+ {+ return Err(PreviewError::Limited);+ }+ if registry+ .sessions+ .values()+ .filter(|l| {+ l.owner == lease.owner+ && l.live()+ && l.preview().agent_session_id != identity.session+ })+ .count()+ >= 5+ {+ return Err(PreviewError::Limited);+ }+ if let Some(previous) = registry.sessions.get(&identity.session) {+ let old_id = previous.preview().id;+ registry.ssh_tokens.retain(|_, c| c.preview != old_id);+ registry.tickets.retain(|_, c| c.preview != old_id);+ registry.browsers.retain(|_, c| c.preview != old_id);+ }+ registry.ssh_tokens.insert(+ digest(&token),+ Credential {+ preview: id,+ user: None,+ expires: Instant::now() + TOKEN_TTL,+ },+ );+ registry.sessions.insert(identity.session, lease)+ };+ if let Some(old) = old {+ self.finish(&old, PreviewStatus::Stopped).await;+ }+ self.publish(&preview).await;+ Ok(Share {+ preview,+ token,+ port,+ })+ }+ /// Resolve a session's state only with an entity view receipt.+ pub fn get(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<Option<Preview>, PreviewError> {+ let session = session_id(&receipt)?;+ let mut registry = self.registry.lock().expect("registry mutex");+ if let Some(user) = receipt.acting_user_id()+ && (registry.watchers.len() < 4096 || registry.watchers.contains_key(&session))+ {+ let watchers = registry.watchers.entry(session).or_default();+ if watchers.len() < 256 || watchers.contains_key(user) {+ watchers.insert(user.clone(), Instant::now());+ }+ }+ Ok(registry.sessions.get(&session).map(|l| l.preview()))+ }+ /// Stop requires entity edit permission; viewing never grants control.+ pub async fn stop(+ &self,+ receipt: EntityAccessReceipt<EditAccessLevel>,+ ) -> Result<(), PreviewError> {+ let lease = self+ .registry+ .lock()+ .expect("registry mutex")+ .sessions+ .get(&session_id(&receipt)?)+ .cloned();+ if let Some(lease) = lease {+ self.finish(&lease, PreviewStatus::Stopped).await;+ }+ Ok(())+ }+ /// Mint a browser ticket after entity access was checked by the standard extractor.+ pub fn launch(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<Launch, PreviewError> {+ let user = receipt+ .get_authenticated_user()+ .map_err(|_| PreviewError::Denied)?+ .clone();+ let mut registry = self.registry.lock().expect("registry mutex");+ let lease = registry+ .sessions+ .get(&session_id(&receipt)?)+ .cloned()+ .ok_or(PreviewError::Offline)?;+ if !lease.live() || lease.preview().status != PreviewStatus::Ready {+ return Err(PreviewError::Offline);+ }+ registry.tickets.retain(|_, c| c.expires > Instant::now());+ if registry.tickets.len() >= 4096 {+ return Err(PreviewError::Limited);+ }+ let ticket = random();+ let preview = lease.preview();+ registry.tickets.insert(+ digest(&ticket),+ Credential {+ preview: preview.id,+ user: Some(user),+ expires: Instant::now() + TICKET_TTL,+ },+ );+ Ok(Launch {+ action: format!("{}/.macro-preview/auth", preview.url),+ ticket,+ })+ }+ /// Redeem an SSH token exactly once; it is scoped to a single lease.+ pub fn authenticate_ssh(&self, token: &str) -> Result<Arc<Lease>, PreviewError> {+ let mut registry = self.registry.lock().expect("registry mutex");+ let credential = registry+ .ssh_tokens+ .remove(&digest(token))+ .ok_or(PreviewError::Denied)?;+ if credential.expires <= Instant::now() {+ return Err(PreviewError::Denied);+ }+ let lease = find(®istry, &credential.preview)?;+ if !lease.live() {+ return Err(PreviewError::Denied);+ }+ Ok(lease)+ }+ /// Accept exactly one logical reverse forward. No TCP listener is created.+ pub fn register(+ &self,+ lease: &Arc<Lease>,+ address: &str,+ port: u32,+ tunnel: Arc<dyn Tunnel>,+ ) -> Result<(), PreviewError> {+ if address != "127.0.0.1" || port != 1 || !lease.live() {+ return Err(PreviewError::Denied);+ }+ let mut current = lease.tunnel.lock().expect("tunnel mutex");+ if current.is_some() {+ return Err(PreviewError::Denied);+ }+ *current = Some(tunnel);+ Ok(())+ }+ /// Mark ready only after receiving a real HTTP response through the tunnel.+ pub async fn ready(&self, lease: &Arc<Lease>) {+ let preview = {+ let mut preview = lease.preview.lock().expect("preview mutex");+ if preview.status != PreviewStatus::Starting || !lease.live() {+ return;+ }+ preview.status = PreviewStatus::Ready;+ preview.clone()+ };+ self.publish(&preview).await;+ }+ /// Mark disconnected/expired and cancel all current traffic.+ pub async fn finish(&self, lease: &Arc<Lease>, status: PreviewStatus) {+ if lease.cancel.is_cancelled() {+ return;+ }+ lease.cancel.cancel();+ let preview = {+ let mut preview = lease.preview.lock().expect("preview mutex");+ preview.status = status;+ preview.clone()+ };+ let tunnel = lease.tunnel.lock().expect("tunnel mutex").take();+ if let Some(tunnel) = tunnel {+ tunnel.close().await;+ }+ self.publish(&preview).await;+ }+ /// Exchange a host-bound, one-use ticket for a host-only browser credential.+ pub async fn redeem(&self, id: &PreviewId, ticket: &str) -> Result<String, PreviewError> {+ let credential = {+ let mut registry = self.registry.lock().expect("registry mutex");+ let credential = registry+ .tickets+ .get(&digest(ticket))+ .ok_or(PreviewError::Denied)?;+ if &credential.preview != id || credential.expires <= Instant::now() {+ return Err(PreviewError::Denied);+ }+ registry+ .tickets+ .remove(&digest(ticket))+ .ok_or(PreviewError::Denied)?+ };+ // A ticket is only ever minted for an authenticated viewer.+ let user = credential.user.ok_or(PreviewError::Denied)?;+ let lease = self.by_id(id)?;+ self.authority+ .viewer(lease.preview().agent_session_id, &user)+ .await?;+ let cookie = random();+ let mut registry = self.registry.lock().expect("registry mutex");+ registry.browsers.retain(|_, c| c.expires > Instant::now());+ if registry.browsers.len() >= 8192 {+ return Err(PreviewError::Limited);+ }+ registry.browsers.insert(+ digest(&cookie),+ Credential {+ preview: id.clone(),+ user: Some(user),+ expires: lease.expires,+ },+ );+ Ok(cookie)+ }+ /// Authenticate every HTTP request. WebSockets call this periodically too.+ pub async fn viewer(+ &self,+ id: &PreviewId,+ cookie: &str,+ activity: bool,+ ) -> Result<Arc<Lease>, PreviewError> {+ let (lease, user) = {+ let registry = self.registry.lock().expect("registry mutex");+ let credential = registry+ .browsers+ .get(&digest(cookie))+ .ok_or(PreviewError::Denied)?;+ if &credential.preview != id || credential.expires <= Instant::now() {+ return Err(PreviewError::Denied);+ }+ let user = credential.user.clone().ok_or(PreviewError::Denied)?;+ (find(®istry, id)?, user)+ };+ if !lease.live() {+ return Err(PreviewError::Offline);+ }+ let _authorization_slot = if activity {+ Some(+ lease+ .requests+ .clone()+ .try_acquire_owned()+ .map_err(|_| PreviewError::Limited)?,+ )+ } else {+ None+ };+ self.authority+ .viewer(lease.preview().agent_session_id, &user)+ .await?;+ if activity {+ *lease.activity.lock().expect("activity mutex") = Instant::now();+ }+ Ok(lease)+ }+ fn by_id(&self, id: &PreviewId) -> Result<Arc<Lease>, PreviewError> {+ let lease = find(&self.registry.lock().expect("registry mutex"), id)?;+ if !lease.live() {+ return Err(PreviewError::Offline);+ }+ Ok(lease)+ }+ /// Expire leases, including agent-session revocation, and reclaim bounded state.+ pub async fn sweep(&self) {+ let leases: Vec<_> = self+ .registry+ .lock()+ .expect("registry mutex")+ .sessions+ .values()+ .cloned()+ .collect();+ for lease in leases {+ if !lease.cancel.is_cancelled()+ && (!lease.live()+ || self+ .authority+ .active(lease.preview().agent_session_id)+ .await+ .is_err())+ {+ self.finish(&lease, PreviewStatus::Expired).await;+ }+ }+ let mut registry = self.registry.lock().expect("registry mutex");+ registry+ .ssh_tokens+ .retain(|_, c| c.expires > Instant::now());+ registry.tickets.retain(|_, c| c.expires > Instant::now());+ registry.browsers.retain(|_, c| c.expires > Instant::now());+ registry+ .sessions+ .retain(|_, l| Instant::now() < l.expires + Duration::from_secs(300));+ registry+ .accounts+ .retain(|_, a| a.last_created.elapsed() < LEASE + LEASE);+ registry.watchers.retain(|_, users| {+ users.retain(|_, time| time.elapsed() < Duration::from_secs(300));+ !users.is_empty()+ });+ }+ async fn publish(&self, preview: &Preview) {+ let candidates = {+ let registry = self.registry.lock().expect("registry mutex");+ let mut users: Vec<MacroUserIdStr<'static>> = registry+ .watchers+ .get(&preview.agent_session_id)+ .map(|w| w.keys().cloned().collect())+ .unwrap_or_default();+ if let Some(lease) = registry.sessions.get(&preview.agent_session_id) {+ users.push(lease.owner.clone());+ }+ users.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));+ users.dedup();+ users+ };+ let mut viewers = Vec::new();+ for user in candidates {+ if self+ .authority+ .viewer(preview.agent_session_id, &user)+ .await+ .is_ok()+ {+ viewers.push(user);+ }+ }+ let _ = self+ .events+ .changed(preview, &viewers)+ .await+ .inspect_err(|error| tracing::warn!(error = ?error, "preview notification failed"));+ }+}+/// The agent session a receipt authorizes, rejecting receipts for anything else.+fn session_id<T: RequiredPermission>(+ receipt: &EntityAccessReceipt<T>,+) -> Result<AgentSessionId, PreviewError> {+ let entity = receipt.entity();+ if entity.entity_type != EntityType::AgentSession {+ return Err(PreviewError::Denied);+ }+ entity.entity_id.parse().map_err(|_| PreviewError::Denied)+}+fn find(registry: &Registry, id: &PreviewId) -> Result<Arc<Lease>, PreviewError> {+ registry+ .sessions+ .values()+ .find(|l| &l.preview().id == id)+ .cloned()+ .ok_or(PreviewError::Offline)+}+fn random() -> String {+ let mut bytes = [0u8; 32];+ rand::rng().fill_bytes(&mut bytes);+ URL_SAFE_NO_PAD.encode(bytes)+}+fn digest(value: &str) -> [u8; 32] {+ Sha256::digest(value.as_bytes()).into()+}++#[cfg(test)]+mod test;diff --git a/crates/agent_preview/src/domain/service/test.rs b/crates/agent_preview/src/domain/service/test.rsnew file mode 100644index 0000000000..9ad11fd70e--- /dev/null+++ b/crates/agent_preview/src/domain/service/test.rs@@ -0,0 +1,203 @@+use super::*;+use crate::testing::*;+use entity_access::domain::models::AccessLevel;++#[tokio::test]+async fn ssh_credentials_are_single_use_and_forward_is_scoped() {+ let (service, _, _) = fixture(2222);+ let share = service.share(identity(), 3000).await.unwrap();+ assert!(service.authenticate_ssh("wrong").is_err());+ let lease = service.authenticate_ssh(&share.token).unwrap();+ assert!(service.authenticate_ssh(&share.token).is_err());+ let tunnel = Arc::new(TcpTunnel("127.0.0.1:1".parse().unwrap()));+ assert!(+ service+ .register(&lease, "0.0.0.0", 1, tunnel.clone())+ .is_err()+ );+ assert!(+ service+ .register(&lease, "127.0.0.1", 3000, tunnel.clone())+ .is_err()+ );+ service+ .register(&lease, "127.0.0.1", 1, tunnel.clone())+ .unwrap();+ assert!(service.register(&lease, "127.0.0.1", 1, tunnel).is_err());+ assert!(service.launch(receipt(AccessLevel::View)).is_err());+ service.ready(&lease).await;+ assert_eq!(+ service+ .get(receipt(AccessLevel::View))+ .unwrap()+ .unwrap()+ .status,+ PreviewStatus::Ready+ );+}+#[tokio::test]+async fn browser_tickets_are_host_bound_single_use_and_permissions_rechecked() {+ let (service, authority, _) = fixture(2222);+ let share = service.share(identity(), 3000).await.unwrap();+ let lease = service.authenticate_ssh(&share.token).unwrap();+ service.ready(&lease).await;+ let launch = service.launch(receipt(AccessLevel::View)).unwrap();+ assert!(+ service+ .redeem(&PreviewId::generate(), &launch.ticket)+ .await+ .is_err()+ );+ let cookie = service+ .redeem(&share.preview.id, &launch.ticket)+ .await+ .unwrap();+ assert!(+ service+ .redeem(&share.preview.id, &launch.ticket)+ .await+ .is_err()+ );+ assert!(+ service+ .viewer(&PreviewId::generate(), &cookie, true)+ .await+ .is_err()+ );+ assert!(+ service+ .viewer(&share.preview.id, &cookie, true)+ .await+ .is_ok()+ );+ authority+ .0+ .store(false, std::sync::atomic::Ordering::SeqCst);+ assert!(+ service+ .viewer(&share.preview.id, &cookie, true)+ .await+ .is_err()+ );+ service.sweep().await;+ assert!(lease.cancel.is_cancelled());+}+#[tokio::test]+async fn expiry_stop_and_token_timeout_close_access() {+ let (service, _, _) = fixture(2222);+ let share = service.share(identity(), 3000).await.unwrap();+ service+ .registry+ .lock()+ .unwrap()+ .ssh_tokens+ .get_mut(&digest(&share.token))+ .unwrap()+ .expires = Instant::now();+ assert!(service.authenticate_ssh(&share.token).is_err());+ let lease = service.by_id(&share.preview.id).unwrap();+ service.ready(&lease).await;+ let launch = service.launch(receipt(AccessLevel::View)).unwrap();+ service+ .registry+ .lock()+ .unwrap()+ .tickets+ .get_mut(&digest(&launch.ticket))+ .unwrap()+ .expires = Instant::now();+ assert!(+ service+ .redeem(&share.preview.id, &launch.ticket)+ .await+ .is_err()+ );+ service.stop(receipt(AccessLevel::Edit)).await.unwrap();+ assert!(lease.cancel.is_cancelled());+ assert!(service.launch(receipt(AccessLevel::View)).is_err());+}+#[tokio::test]+async fn quotas_bound_sessions_and_request_loops() {+ let (service, _, _) = fixture(2222);+ assert!(service.share(identity(), 0).await.is_err());+ for _ in 0..5 {+ let mut identity = identity();+ identity.session = AgentSessionId::new();+ service+ .registry+ .lock()+ .unwrap()+ .accounts+ .values_mut()+ .for_each(|a| a.last_created = Instant::now() - TOKEN_TTL);+ service.share(identity, 3000).await.unwrap();+ }+ service+ .registry+ .lock()+ .unwrap()+ .accounts+ .values_mut()+ .for_each(|a| a.last_created = Instant::now() - TOKEN_TTL);+ assert!(matches!(+ service.share(identity(), 3000).await,+ Err(PreviewError::Limited)+ ));+}+#[test]+fn isolated_domains_and_shell_fields_are_validated() {+ let (service, _, _) = fixture(2222);+ let mut settings = service.settings().clone();+ for domain in [+ "macro.com",+ "preview.macro.com",+ "bad;hostname",+ "UPPERCASE.test",+ "macro.test",+ // Nested either way: the app under the preview domain, and the preview+ // domain under the app.+ "test",+ "preview.macro.test",+ ] {+ settings.domain = domain.into();+ assert!(settings.validate().is_err());+ }+}++#[tokio::test]+async fn stopping_a_preview_does_not_bypass_the_creation_interval() {+ let (service, _, _) = fixture(2222);+ service.share(identity(), 3000).await.unwrap();+ assert!(matches!(+ service.share(identity(), 3000).await,+ Err(PreviewError::Limited)+ ));+ // Stopping releases the session slot but not the owner's pacing: otherwise+ // a stop/share loop is an unbounded lease mint.+ service.stop(receipt(AccessLevel::Edit)).await.unwrap();+ assert!(matches!(+ service.share(identity(), 3000).await,+ Err(PreviewError::Limited)+ ));+ service+ .registry+ .lock()+ .unwrap()+ .accounts+ .values_mut()+ .for_each(|a| a.last_created = Instant::now() - TOKEN_TTL);+ service.share(identity(), 3000).await.unwrap();+}+#[test]+fn only_local_stack_accepts_loopback_http_handoff_and_docker_ssh_fallback() {+ let (service, _, _) = fixture(2222);+ let mut settings = service.settings().clone();+ settings.domain = "preview.localhost".into();+ settings.app_origin = "http://localhost:3000".into();+ settings.local_ssh_fallback = true;+ assert!(settings.validate().is_ok());+ settings.app_origin = "http://macro.test".into();+ assert!(settings.validate().is_err());+ settings.app_origin = "https://macro.test".into();+ assert!(settings.validate().is_err());+}diff --git a/crates/agent_preview/src/inbound/control.rs b/crates/agent_preview/src/inbound/control.rsnew file mode 100644index 0000000000..aa15c90a06--- /dev/null+++ b/crates/agent_preview/src/inbound/control.rs@@ -0,0 +1,103 @@+use crate::domain::{Launch, Preview, PreviewError, PreviewService};+use axum::{+ Json, Router,+ extract::{FromRef, State},+ http::StatusCode,+ routing::{get, post},+};+use entity_access::{+ domain::{+ models::{EditAccessLevel, ViewAccessLevel},+ ports::EntityAccessService,+ },+ inbound::axum_extractors::AgentSessionAccessLevelExtractor,+};+use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};+use std::sync::Arc;++/// State shared by Macro control routes and the standard authorization extractors.+pub struct ControlState<Access, Auth> {+ service: PreviewService,+ access: Arc<Access>,+ auth: MacroAuthorizationState<Auth>,+}+impl<Access, Auth> ControlState<Access, Auth> {+ /// Compose service and existing Macro authentication/entity-access implementations.+ pub fn new(+ service: PreviewService,+ access: Arc<Access>,+ auth: MacroAuthorizationState<Auth>,+ ) -> Self {+ Self {+ service,+ access,+ auth,+ }+ }+}+impl<Access, Auth> Clone for ControlState<Access, Auth> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ access: self.access.clone(),+ auth: self.auth.clone(),+ }+ }+}+impl<Access, Auth> FromRef<ControlState<Access, Auth>> for Arc<Access> {+ fn from_ref(state: &ControlState<Access, Auth>) -> Self {+ state.access.clone()+ }+}+impl<Access, Auth> FromRef<ControlState<Access, Auth>> for MacroAuthorizationState<Auth> {+ fn from_ref(state: &ControlState<Access, Auth>) -> Self {+ state.auth.clone()+ }+}+/// Current session preview, including the absence of a lease after a gateway restart.+#[derive(serde::Serialize)]+pub struct PreviewSnapshot {+ /// Current lease, or no preview.+ pub preview: Option<Preview>,+}++/// Control endpoints; mount under `/preview` on Macro's authenticated API gateway.+pub fn router<Access: EntityAccessService, Auth: MacroAuthorizationService>(+ state: ControlState<Access, Auth>,+) -> Router {+ Router::new()+ .route(+ "/agent-sessions/{session_id}",+ get(read::<Access, Auth>).delete(stop::<Access, Auth>),+ )+ .route(+ "/agent-sessions/{session_id}/open",+ post(open::<Access, Auth>),+ )+ .with_state(state)+}+async fn read<Access: EntityAccessService, Auth: MacroAuthorizationService>(+ State(state): State<ControlState<Access, Auth>>,+ receipt: AgentSessionAccessLevelExtractor<ViewAccessLevel, Access, Auth>,+) -> Result<Json<PreviewSnapshot>, PreviewError> {+ state+ .service+ .get(receipt.entity_access_receipt)+ .map(|preview| Json(PreviewSnapshot { preview }))+}+async fn open<Access: EntityAccessService, Auth: MacroAuthorizationService>(+ State(state): State<ControlState<Access, Auth>>,+ receipt: AgentSessionAccessLevelExtractor<ViewAccessLevel, Access, Auth>,+) -> Result<Json<Launch>, PreviewError> {+ state+ .service+ .launch(receipt.entity_access_receipt)+ .map(Json)+}+async fn stop<Access: EntityAccessService, Auth: MacroAuthorizationService>(+ State(state): State<ControlState<Access, Auth>>,+ receipt: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,+) -> Result<StatusCode, PreviewError> {+ state.service.stop(receipt.entity_access_receipt).await?;+ Ok(StatusCode::NO_CONTENT)+}diff --git a/crates/agent_preview/src/inbound/http.rs b/crates/agent_preview/src/inbound/http.rsnew file mode 100644index 0000000000..6952a72b4e--- /dev/null+++ b/crates/agent_preview/src/inbound/http.rs@@ -0,0 +1,421 @@+use crate::domain::{Lease, PreviewError, PreviewId, PreviewService};+use axum::{+ Router,+ body::Body,+ extract::{Request, State},+ http::{HeaderMap, HeaderValue, Method, StatusCode, header},+ response::{IntoResponse, Response},+ routing::any,+};+use http_body_util::Limited;+use hyper_util::rt::TokioIo;+use std::{sync::Arc, time::Duration};++const COOKIE: &str = "__Host-macro-preview";+const AUTH_PATH: &str = "/.macro-preview/auth";++impl IntoResponse for PreviewError {+ fn into_response(self) -> Response {+ let status = match self {+ Self::Invalid => StatusCode::BAD_REQUEST,+ Self::Denied => StatusCode::FORBIDDEN,+ Self::Offline => StatusCode::GONE,+ Self::Limited => StatusCode::TOO_MANY_REQUESTS,+ Self::Unavailable => StatusCode::BAD_GATEWAY,+ };+ (+ status,+ [+ (header::CACHE_CONTROL, "no-store"),+ (header::REFERRER_POLICY, "no-referrer"),+ ],+ self.to_string(),+ )+ .into_response()+ }+}+/// Public listener. Mount only on the isolated preview domain, never a Macro cookie domain.+pub fn router(service: PreviewService) -> Router {+ Router::new().fallback(any(handle)).with_state(service)+}+async fn handle(+ State(service): State<PreviewService>,+ mut request: Request,+) -> Result<Response, PreviewError> {+ let host = request+ .headers()+ .get(header::HOST)+ .and_then(|v| v.to_str().ok())+ .ok_or(PreviewError::Invalid)?+ .to_ascii_lowercase();+ let settings = service.settings();+ let suffix = if settings.https_port == 443 {+ format!(".{}", settings.domain)+ } else {+ format!(".{}:{}", settings.domain, settings.https_port)+ };+ let id = PreviewId::parse(host.strip_suffix(&suffix).ok_or(PreviewError::Invalid)?)?;+ let origin = settings.origin(&id);+ if request.uri().path() == AUTH_PATH {+ if request.method() != Method::POST+ || request+ .headers()+ .get(header::ORIGIN)+ .and_then(|v| v.to_str().ok())+ != Some(settings.app_origin.as_str())+ {+ return Err(PreviewError::Denied);+ }+ let body = tokio::time::timeout(+ Duration::from_secs(10),+ axum::body::to_bytes(request.into_body(), 1024),+ )+ .await+ .map_err(|_| PreviewError::Invalid)?+ .map_err(|_| PreviewError::Invalid)?;+ let ticket = url::form_urlencoded::parse(&body)+ .find(|(k, _)| k == "ticket")+ .map(|(_, v)| v.into_owned())+ .ok_or(PreviewError::Invalid)?;+ let cookie = service.redeem(&id, &ticket).await?;+ return Ok((+ StatusCode::SEE_OTHER,+ [+ (+ header::SET_COOKIE,+ format!(+ "{COOKIE}={cookie}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=3600"+ ),+ ),+ (header::LOCATION, "/".into()),+ (header::CACHE_CONTROL, "no-store".into()),+ (header::REFERRER_POLICY, "no-referrer".into()),+ (+ header::CONTENT_SECURITY_POLICY,+ "default-src 'none'; frame-ancestors 'none'".into(),+ ),+ ],+ )+ .into_response());+ }+ // Disallow cross-origin unsafe requests and upgrades; host-only cookies alone do not prevent CSRF.+ let upgrade = request+ .headers()+ .get(header::UPGRADE)+ .is_some_and(|v| v.as_bytes().eq_ignore_ascii_case(b"websocket"));+ if request.method() == Method::CONNECT+ || (request.headers().contains_key(header::UPGRADE) && !upgrade)+ {+ return Err(PreviewError::Invalid);+ }+ let incoming_origin = request+ .headers()+ .get(header::ORIGIN)+ .and_then(|v| v.to_str().ok())+ .map(str::to_owned);+ let navigation = matches!(*request.method(), Method::GET | Method::HEAD)+ && request+ .headers()+ .get("sec-fetch-mode")+ .is_some_and(|v| v == "navigate")+ && request+ .headers()+ .get("sec-fetch-dest")+ .is_some_and(|v| v == "document");+ if !navigation+ && (incoming_origin+ .as_deref()+ .is_some_and(|value| value != origin)+ || ((upgrade+ || !matches!(+ *request.method(),+ Method::GET | Method::HEAD | Method::OPTIONS+ ))+ && incoming_origin.is_none())+ || request+ .headers()+ .get("sec-fetch-site")+ .is_some_and(|v| v == "cross-site"))+ {+ return Err(PreviewError::Denied);+ }+ let cookie = cookie_value(request.headers()).ok_or(PreviewError::Denied)?;+ let lease = service.viewer(&id, &cookie, true).await?;+ let permit = Arc::new(+ lease+ .requests+ .clone()+ .try_acquire_owned()+ .map_err(|_| PreviewError::Limited)?,+ );+ let upgrade_permit = if upgrade {+ Some(+ lease+ .upgrades+ .clone()+ .try_acquire_owned()+ .map_err(|_| PreviewError::Limited)?,+ )+ } else {+ None+ };+ let upstream = format!("localhost:{}", lease.port());+ clean_request(request.headers_mut(), &host, &origin, &upstream, upgrade)?;+ // Hyper's client sends origin-form URIs. Preserve the exact application path and query.+ *request.uri_mut() = request+ .uri()+ .path_and_query()+ .map(|p| p.as_str())+ .unwrap_or("/")+ .parse()+ .map_err(|_| PreviewError::Invalid)?;+ let downstream_upgrade = if upgrade {+ Some(hyper::upgrade::on(&mut request))+ } else {+ None+ };+ let stream = lease.tunnel()?.open().await?;+ let (mut sender, connection) = hyper::client::conn::http1::Builder::new()+ .max_headers(64)+ .max_buf_size(32 * 1024)+ .handshake(TokioIo::new(stream))+ .await+ .map_err(|_| PreviewError::Unavailable)?;+ let cancel = lease.cancel.clone();+ let (parts, body) = request.into_parts();+ let request =+ hyper::Request::from_parts(parts, Body::new(Limited::new(body, 16 * 1024 * 1024)));+ // The permit must live through the response body, not merely its headers.+ let connection_permit = permit.clone();+ let connection_service = service.clone();+ let connection_id = id.clone();+ let connection_cookie = cookie.clone();+ tokio::spawn(async move {+ let _permit = connection_permit;+ let connection = connection.with_upgrades();+ tokio::pin!(connection);+ loop {+ tokio::select! {+ _ = cancel.cancelled() => break,+ _ = &mut connection => break,+ _ = tokio::time::sleep(Duration::from_secs(30)) => {+ if connection_service.viewer(&connection_id, &connection_cookie, false).await.is_err() { break; }+ }+ }+ }+ });+ let mut response = tokio::time::timeout(Duration::from_secs(30), sender.send_request(request))+ .await+ .map_err(|_| PreviewError::Unavailable)?+ .map_err(|_| PreviewError::Unavailable)?;+ if response.status() == StatusCode::SWITCHING_PROTOCOLS {+ let downstream = downstream_upgrade.ok_or(PreviewError::Invalid)?;+ let upstream_upgrade = hyper::upgrade::on(&mut response);+ let lease = lease.clone();+ tokio::spawn(async move {+ let _request_permit = permit;+ let _upgrade_permit = upgrade_permit;+ let upgraded = tokio::time::timeout(Duration::from_secs(10), async {+ Ok::<_, hyper::Error>((downstream.await?, upstream_upgrade.await?))+ })+ .await;+ let Ok(Ok((downstream, upstream))) = upgraded else {+ return;+ };+ let mut downstream = TokioIo::new(downstream);+ let mut upstream = TokioIo::new(upstream);+ // Revoke already-open sockets as well as future handshakes. HMR pings do not renew idle leases.+ let copy = tokio::io::copy_bidirectional(&mut downstream, &mut upstream);+ tokio::pin!(copy);+ loop {+ tokio::select! {+ _ = lease.cancel.cancelled() => break,+ _ = &mut copy => break,+ _ = tokio::time::sleep(Duration::from_secs(30)) => {+ if service.viewer(&id, &cookie, false).await.is_err() { break; }+ }+ }+ }+ });+ }+ let upgraded = response.status() == StatusCode::SWITCHING_PROTOCOLS;+ clean_response(response.headers_mut(), &origin, &upstream, upgraded);+ Ok(response.map(Body::new))+}+fn cookie_value(headers: &HeaderMap) -> Option<String> {+ headers+ .get_all(header::COOKIE)+ .iter()+ .filter_map(|v| v.to_str().ok())+ .flat_map(|v| v.split(';'))+ .find_map(|part| {+ let (name, value) = part.trim().split_once('=')?;+ (name.trim() == COOKIE && value.len() <= 128).then(|| value.to_owned())+ })+}+fn clean_request(+ headers: &mut HeaderMap,+ host: &str,+ origin: &str,+ upstream: &str,+ upgrade: bool,+) -> Result<(), PreviewError> {+ let cookies = headers+ .get_all(header::COOKIE)+ .iter()+ .filter_map(|v| v.to_str().ok())+ .flat_map(|v| v.split(';'))+ .filter(|p| {+ p.trim()+ .split_once('=')+ .is_some_and(|(name, _)| name.trim() != COOKIE)+ })+ .map(str::trim)+ .collect::<Vec<_>>()+ .join("; ");+ headers.remove(header::COOKIE);+ if !cookies.is_empty() {+ headers.insert(+ header::COOKIE,+ HeaderValue::from_str(&cookies).map_err(|_| PreviewError::Invalid)?,+ );+ }+ strip_hop_headers(headers);+ let remove: Vec<_> = headers+ .keys()+ .filter(|k| k.as_str().starts_with("x-forwarded-") || k.as_str().starts_with("x-macro-"))+ .cloned()+ .collect();+ for key in remove {+ headers.remove(key);+ }+ headers.remove("forwarded");+ headers.insert(+ header::HOST,+ HeaderValue::from_str(upstream).map_err(|_| PreviewError::Invalid)?,+ );+ headers.insert(+ "x-forwarded-host",+ HeaderValue::from_str(host).map_err(|_| PreviewError::Invalid)?,+ );+ headers.insert("x-forwarded-proto", HeaderValue::from_static("https"));+ if headers.get(header::ORIGIN).is_some_and(|v| v == origin) {+ headers.insert(+ header::ORIGIN,+ HeaderValue::from_str(&format!("http://{upstream}"))+ .map_err(|_| PreviewError::Invalid)?,+ );+ }+ if upgrade {+ headers.insert(header::CONNECTION, HeaderValue::from_static("upgrade"));+ headers.insert(header::UPGRADE, HeaderValue::from_static("websocket"));+ }+ Ok(())+}+fn strip_hop_headers(headers: &mut HeaderMap) {+ let named: Vec<String> = headers+ .get_all(header::CONNECTION)+ .iter()+ .filter_map(|v| v.to_str().ok())+ .flat_map(|v| v.split(','))+ .map(|v| v.trim().to_owned())+ .collect();+ for name in named {+ headers.remove(name);+ }+ for name in [+ "connection",+ "keep-alive",+ "proxy-authenticate",+ "proxy-authorization",+ "te",+ "trailer",+ "transfer-encoding",+ "upgrade",+ ] {+ headers.remove(name);+ }+}+fn clean_response(headers: &mut HeaderMap, origin: &str, upstream: &str, upgrade: bool) {+ let cookies: Vec<_> = headers+ .get_all(header::SET_COOKIE)+ .iter()+ .filter_map(|v| v.to_str().ok())+ .filter_map(|cookie| {+ let mut parts = cookie.split(';');+ let pair = parts.next()?;+ if pair+ .trim()+ .split_once('=')+ .is_some_and(|(name, _)| name.trim() == COOKIE)+ {+ return None;+ }+ let parts = std::iter::once(pair).chain(parts.filter(|p| {+ !p.trim()+ .split_once('=')+ .is_some_and(|(k, _)| k.eq_ignore_ascii_case("domain"))+ }));+ HeaderValue::from_str(&parts.collect::<Vec<_>>().join(";")).ok()+ })+ .collect();+ headers.remove(header::SET_COOKIE);+ for cookie in cookies {+ headers.append(header::SET_COOKIE, cookie);+ }+ strip_hop_headers(headers);+ if upgrade {+ headers.insert(header::CONNECTION, HeaderValue::from_static("upgrade"));+ headers.insert(header::UPGRADE, HeaderValue::from_static("websocket"));+ }+ if let Some(location) = headers.get(header::LOCATION).and_then(|v| v.to_str().ok()) {+ let local = format!("http://{upstream}");+ if let Some(path) = location.strip_prefix(&local).filter(|p| {+ p.is_empty() || p.starts_with('/') || p.starts_with('?') || p.starts_with('#')+ }) && let Ok(value) = HeaderValue::from_str(&format!("{origin}{path}"))+ {+ headers.insert(header::LOCATION, value);+ }+ }+ // The gateway serves private developer content, even if the app marks it public.+ headers.insert(+ header::CACHE_CONTROL,+ HeaderValue::from_static("private, no-store"),+ );+ headers.insert(+ header::REFERRER_POLICY,+ HeaderValue::from_static("same-origin"),+ );+ headers.insert(+ "x-content-type-options",+ HeaderValue::from_static("nosniff"),+ );+}+/// Readiness probe traverses the actual forwarded HTTP server, without following redirects.+pub(super) async fn probe(lease: &Arc<Lease>) -> Result<(), PreviewError> {+ tokio::time::timeout(Duration::from_secs(3), async {+ let stream = lease.tunnel()?.open().await?;+ let (mut sender, connection) = hyper::client::conn::http1::handshake(TokioIo::new(stream))+ .await+ .map_err(|_| PreviewError::Unavailable)?;+ let task = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(connection));+ let request = hyper::Request::builder()+ .method(Method::HEAD)+ .uri("/")+ .header(header::HOST, format!("localhost:{}", lease.port()))+ .body(Body::empty())+ .map_err(|_| PreviewError::Invalid)?;+ let result = sender+ .send_request(request)+ .await+ .map(|_| ())+ .map_err(|_| PreviewError::Unavailable);+ task.abort();+ result+ })+ .await+ .map_err(|_| PreviewError::Unavailable)?+}++#[cfg(test)]+mod test;diff --git a/crates/agent_preview/src/inbound/http/test.rs b/crates/agent_preview/src/inbound/http/test.rsnew file mode 100644index 0000000000..ca23cc11df--- /dev/null+++ b/crates/agent_preview/src/inbound/http/test.rs@@ -0,0 +1,243 @@+use super::*;+use crate::testing::*;+use axum::http::Request;+use entity_access::domain::models::AccessLevel;+use futures_util::StreamExt;+use http_body_util::BodyExt;+use tower::ServiceExt;++#[test]+fn proxy_preserves_app_cookies_but_never_forwards_gateway_credentials() {+ let mut headers = HeaderMap::new();+ headers.append(+ header::COOKIE,+ "app=one; __Host-macro-preview=secret".parse().unwrap(),+ );+ headers.append(header::COOKIE, "another=two".parse().unwrap());+ headers.insert("x-forwarded-host", "attacker.test".parse().unwrap());+ headers.insert("x-macro-internal-key", "secret".parse().unwrap());+ headers.insert(header::ORIGIN, "https://public.test".parse().unwrap());+ clean_request(+ &mut headers,+ "public.test",+ "https://public.test",+ "localhost:3000",+ true,+ )+ .unwrap();+ assert_eq!(headers[header::COOKIE], "app=one; another=two");+ assert_eq!(headers[header::HOST], "localhost:3000");+ assert_eq!(headers["x-forwarded-host"], "public.test");+ assert_eq!(headers[header::ORIGIN], "http://localhost:3000");+ assert!(!headers.contains_key("x-macro-internal-key"));+}+#[test]+fn response_cannot_replace_gateway_cookie_or_poison_sibling_hosts() {+ let mut headers = HeaderMap::new();+ headers.append(+ header::SET_COOKIE,+ "__Host-macro-preview=attacker; Path=/".parse().unwrap(),+ );+ headers.append(+ header::SET_COOKIE,+ "app=one; Domain=preview.test; Path=/; HttpOnly"+ .parse()+ .unwrap(),+ );+ headers.insert(+ header::LOCATION,+ "http://localhost:3000/login?next=%2F".parse().unwrap(),+ );+ clean_response(&mut headers, "https://public.test", "localhost:3000", false);+ assert_eq!(headers.get_all(header::SET_COOKIE).iter().count(), 1);+ assert_eq!(headers[header::SET_COOKIE], "app=one; Path=/; HttpOnly");+ assert_eq!(+ headers[header::LOCATION],+ "https://public.test/login?next=%2F"+ );+}+#[tokio::test]+async fn gateway_requires_ticket_and_preserves_request_target_and_streamed_response() {+ let (service, _, _) = fixture(2222);+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let upstream = tokio::spawn(async move {+ axum::serve(+ listener,+ Router::new().fallback(|request: axum::extract::Request| async move {+ format!(+ "{}|{}|{}",+ request.uri(),+ request.headers()[header::HOST].to_str().unwrap(),+ request+ .headers()+ .get(header::COOKIE)+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")+ )+ }),+ )+ .await+ .unwrap();+ });+ let share = service.share(identity(), address.port()).await.unwrap();+ let lease = service.authenticate_ssh(&share.token).unwrap();+ service+ .register(&lease, "127.0.0.1", 1, Arc::new(TcpTunnel(address)))+ .unwrap();+ probe(&lease).await.unwrap();+ service.ready(&lease).await;+ let launch = service.launch(receipt(AccessLevel::View)).unwrap();+ let host = format!("{}.preview.test", share.preview.id);+ let gateway = router(service.clone());+ let denied = gateway+ .clone()+ .oneshot(+ Request::builder()+ .uri("/")+ .header(header::HOST, &host)+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(denied.status(), StatusCode::FORBIDDEN);+ let response = gateway+ .clone()+ .oneshot(+ Request::builder()+ .method("POST")+ .uri(AUTH_PATH)+ .header(header::HOST, &host)+ .header(header::ORIGIN, "https://macro.test")+ .body(Body::from(format!("ticket={}", launch.ticket)))+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::SEE_OTHER);+ assert_eq!(response.headers()[header::LOCATION], "/");+ let cookie = response.headers()[header::SET_COOKIE]+ .to_str()+ .unwrap()+ .split(';')+ .next()+ .unwrap()+ .to_owned();+ // Redirecting the cross-origin ticket POST preserves cross-site fetch metadata.+ let response = gateway+ .clone()+ .oneshot(+ Request::builder()+ .uri("/")+ .header(header::HOST, &host)+ .header(header::COOKIE, &cookie)+ .header("sec-fetch-mode", "navigate")+ .header("sec-fetch-dest", "document")+ .header("sec-fetch-site", "cross-site")+ .header(header::ORIGIN, "null")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(response.headers()[header::REFERRER_POLICY], "same-origin");+ // A sibling preview is same-site, but must not fetch this viewer's private content.+ let denied = gateway+ .clone()+ .oneshot(+ Request::builder()+ .uri("/")+ .header(header::HOST, &host)+ .header(header::COOKIE, &cookie)+ .header("sec-fetch-site", "same-site")+ .header(header::ORIGIN, "https://sibling.preview.test")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(denied.status(), StatusCode::FORBIDDEN);+ let response = gateway+ .oneshot(+ Request::builder()+ .uri("/nested?q=a%2Fb&x=2")+ .header(header::HOST, &host)+ .header(header::COOKIE, format!("{cookie}; app=test"))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ let body = response.into_body().collect().await.unwrap().to_bytes();+ assert_eq!(+ body,+ format!("/nested?q=a%2Fb&x=2|localhost:{}|app=test", address.port())+ );+ upstream.abort();+}++#[tokio::test(start_paused = true)]+async fn non_upgraded_stream_holds_permit_and_rechecks_viewer_permission() {+ let (service, authority, _) = fixture(2222);+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let upstream = tokio::spawn(async move {+ axum::serve(+ listener,+ Router::new().fallback(|| async {+ Body::from_stream(+ futures_util::stream::once(async {+ Ok::<_, std::io::Error>(bytes::Bytes::from_static(b"first"))+ })+ .chain(futures_util::stream::pending()),+ )+ }),+ )+ .await+ .unwrap();+ });+ let share = service.share(identity(), address.port()).await.unwrap();+ let lease = service.authenticate_ssh(&share.token).unwrap();+ service+ .register(&lease, "127.0.0.1", 1, Arc::new(TcpTunnel(address)))+ .unwrap();+ service.ready(&lease).await;+ let ticket = service.launch(receipt(AccessLevel::View)).unwrap();+ let cookie = service+ .redeem(&share.preview.id, &ticket.ticket)+ .await+ .unwrap();+ let host = format!("{}.preview.test", share.preview.id);+ // A server may decline an Upgrade with a streaming 200 response.+ let response = router(service)+ .oneshot(+ Request::builder()+ .uri("/events")+ .header(header::HOST, &host)+ .header(header::COOKIE, format!("{COOKIE}={cookie}"))+ .header(header::ORIGIN, format!("https://{host}"))+ .header(header::CONNECTION, "upgrade")+ .header(header::UPGRADE, "websocket")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ let mut body = response.into_body();+ // The point is that the slot is held across the body, not the pool's size.+ let idle = lease.requests.available_permits() + 1;+ body.frame().await.unwrap().unwrap();+ assert_eq!(lease.requests.available_permits(), idle - 1);+ authority+ .0+ .store(false, std::sync::atomic::Ordering::SeqCst);+ tokio::time::advance(Duration::from_secs(31)).await;+ tokio::task::yield_now().await;+ assert!(body.frame().await.is_none_or(|frame| frame.is_err()));+ assert_eq!(lease.requests.available_permits(), idle);+ upstream.abort();+}diff --git a/crates/agent_preview/src/inbound/mod.rs b/crates/agent_preview/src/inbound/mod.rsnew file mode 100644index 0000000000..14344d59e2--- /dev/null+++ b/crates/agent_preview/src/inbound/mod.rs@@ -0,0 +1,9 @@+//! Transport adapters for preview use cases.+/// Authenticated Macro control routes.+pub mod control;+/// Root-mounted HTTP and WebSocket gateway.+pub mod http;+/// SSH listener accepting only the provisioned remote forward.+pub mod ssh;+/// Internal session-scoped MCP server.+pub mod toolset;diff --git a/crates/agent_preview/src/inbound/ssh.rs b/crates/agent_preview/src/inbound/ssh.rsnew file mode 100644index 0000000000..e21e6a6996--- /dev/null+++ b/crates/agent_preview/src/inbound/ssh.rs@@ -0,0 +1,177 @@+use crate::domain::{Lease, PreviewService, PreviewStatus, ports::Tunnel};+use russh::server::{Auth, Config, Handler, Session};+use std::{+ sync::{Arc, Mutex},+ time::Duration,+};+use tokio::{net::TcpListener, sync::Semaphore};+use tokio_util::sync::CancellationToken;++/// Composition-root factory for the outbound tunnel capability.+pub type TunnelFactory = Arc<dyn Fn(russh::server::Handle) -> Arc<dyn Tunnel> + Send + Sync>;+/// Load the persistent server host key. The client never needs a private key.+pub fn host_key(pem: &str) -> Result<russh::keys::PrivateKey, rootcause::Report> {+ Ok(russh::keys::PrivateKey::from_openssh(pem).map_err(|e| rootcause::report!(e))?)+}+/// Public key material embedded in each generated known_hosts file.+pub fn public_key(key: &russh::keys::PrivateKey) -> Result<String, rootcause::Report> {+ Ok(key+ .public_key()+ .to_openssh()+ .map_err(|e| rootcause::report!(e))?+ .split_whitespace()+ .take(2)+ .collect::<Vec<_>>()+ .join(" "))+}+/// Serve bounded SSH transports; no shells, exec, direct forwarding, or real remote listeners.+pub async fn serve(+ listener: TcpListener,+ key: russh::keys::PrivateKey,+ service: PreviewService,+ factory: TunnelFactory,+ shutdown: CancellationToken,+) -> Result<(), rootcause::Report> {+ let config = Arc::new(Config {+ keys: vec![key],+ max_auth_attempts: 1,+ auth_rejection_time: Duration::from_secs(1),+ auth_rejection_time_initial: Some(Duration::from_secs(1)),+ inactivity_timeout: Some(Duration::from_secs(90)),+ keepalive_interval: Some(Duration::from_secs(30)),+ keepalive_max: 2,+ maximum_packet_size: 32 * 1024,+ window_size: 256 * 1024,+ channel_buffer_size: 8,+ event_buffer_size: 32,+ ..Config::default()+ });+ let capacity = Arc::new(Semaphore::new(1024));+ loop {+ let (socket, _) = tokio::select! {+ _ = shutdown.cancelled() => return Ok(()),+ connection = listener.accept() => connection.map_err(|e| rootcause::report!(e))?,+ };+ let Ok(permit) = capacity.clone().try_acquire_owned() else {+ continue;+ };+ let config = config.clone();+ let service = service.clone();+ let factory = factory.clone();+ let shutdown = shutdown.clone();+ tokio::spawn(async move {+ let _permit = permit;+ let lease = Arc::new(Mutex::new(None));+ let authenticated = CancellationToken::new();+ let handler = Connection {+ service: service.clone(),+ factory,+ lease: lease.clone(),+ authenticated: authenticated.clone(),+ };+ let running = tokio::time::timeout(+ Duration::from_secs(10),+ russh::server::run_stream(config, socket, handler),+ )+ .await;+ if let Ok(Ok(mut running)) = running {+ let handle = running.handle();+ // The run_stream future only waits for the SSH identification, not authentication.+ let authenticated_in_time = tokio::select! {+ _ = shutdown.cancelled() => false,+ _ = &mut running => false,+ result = tokio::time::timeout(Duration::from_secs(15), authenticated.cancelled()) => result.is_ok(),+ };+ if authenticated_in_time {+ tokio::select! { _ = shutdown.cancelled() => {}, _ = &mut running => {} }+ }+ let _ = handle+ .disconnect(+ russh::Disconnect::ByApplication,+ "connection ended".into(),+ "en".into(),+ )+ .await;+ }+ let connected = lease.lock().expect("connection mutex").clone();+ if let Some(lease) = connected {+ service.finish(&lease, PreviewStatus::Offline).await;+ }+ });+ }+}+struct Connection {+ service: PreviewService,+ factory: TunnelFactory,+ lease: Arc<Mutex<Option<Arc<Lease>>>>,+ authenticated: CancellationToken,+}+impl Handler for Connection {+ type Error = russh::Error;+ async fn auth_none(&mut self, user: &str) -> Result<Auth, Self::Error> {+ if user.len() > 128 {+ return Ok(Auth::reject());+ }+ match self.service.authenticate_ssh(user) {+ Ok(lease) => {+ *self.lease.lock().expect("connection mutex") = Some(lease);+ self.authenticated.cancel();+ Ok(Auth::Accept)+ }+ Err(_) => Ok(Auth::reject()),+ }+ }+ async fn tcpip_forward(+ &mut self,+ address: &str,+ port: &mut u32,+ session: &mut Session,+ ) -> Result<bool, Self::Error> {+ let lease = self.lease.lock().expect("connection mutex").clone();+ let Some(lease) = lease else {+ return Ok(false);+ };+ if self+ .service+ .register(&lease, address, *port, (self.factory)(session.handle()))+ .is_err()+ {+ return Ok(false);+ }+ let service = self.service.clone();+ tokio::spawn(async move {+ // Yield until the SSH success response has reached the client's forward table.+ tokio::time::sleep(Duration::from_millis(100)).await;+ for _ in 0..60 {+ if !lease.live() {+ return;+ }+ if super::http::probe(&lease).await.is_ok() {+ service.ready(&lease).await;+ return;+ }+ tokio::select! { _ = lease.cancel.cancelled() => return, _ = tokio::time::sleep(Duration::from_secs(1)) => {} }+ }+ service.finish(&lease, PreviewStatus::Offline).await;+ });+ Ok(true)+ }+ async fn cancel_tcpip_forward(+ &mut self,+ address: &str,+ port: u32,+ _: &mut Session,+ ) -> Result<bool, Self::Error> {+ if address != "127.0.0.1" || port != 1 {+ return Ok(false);+ }+ let lease = self.lease.lock().expect("connection mutex").clone();+ if let Some(lease) = lease {+ self.service.finish(&lease, PreviewStatus::Stopped).await;+ }+ Ok(true)+ }+}++#[cfg(test)]+mod test;diff --git a/crates/agent_preview/src/inbound/ssh/test.rs b/crates/agent_preview/src/inbound/ssh/test.rsnew file mode 100644index 0000000000..552dd96230--- /dev/null+++ b/crates/agent_preview/src/inbound/ssh/test.rs@@ -0,0 +1,290 @@+use super::*;+use crate::{domain::PreviewId, outbound::ssh_tunnel::SshTunnel, testing::*};+use axum::{+ Router,+ extract::ws::{Message, WebSocketUpgrade},+ response::IntoResponse,+ routing::get,+};+use entity_access::domain::models::AccessLevel;+use macro_user_id::user_id::MacroUserIdStr;+use tokio::io::{AsyncReadExt, AsyncWriteExt};++#[tokio::test]+async fn stock_openssh_forwards_http_and_websockets_and_stop_closes_them() {+ let upstream = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = upstream.local_addr().unwrap().port();+ let upstream_task = tokio::spawn(async move {+ axum::serve(+ upstream,+ Router::new()+ .route("/", get(|| async { "live preview" }))+ .route(+ "/socket",+ get(|ws: WebSocketUpgrade| async {+ ws.on_upgrade(|mut socket| async move {+ while let Some(Ok(message)) = socket.recv().await {+ if let Message::Text(text) = message+ && socket.send(Message::Text(text)).await.is_err()+ {+ break;+ }+ }+ })+ .into_response()+ }),+ ),+ )+ .await+ .unwrap();+ });+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let ssh_port = listener.local_addr().unwrap().port();+ let (service, _, key) = fixture(ssh_port);+ let shutdown = CancellationToken::new();+ let server = tokio::spawn(serve(+ listener,+ key,+ service.clone(),+ Arc::new(|h| Arc::new(SshTunnel::new(h))),+ shutdown.clone(),+ ));+ // Exercise the real stateless MCP transport and execute its exact returned script.+ use http_body_util::BodyExt;+ use tower::ServiceExt;+ let mcp = crate::inbound::toolset::router(service.clone(), vec!["localhost".into()]);+ let call = || {+ axum::http::Request::builder().method("POST").uri("/mcp")+ .header("host", "localhost")+ .header("content-type", "application/json")+ .header("accept", "application/json, text/event-stream")+ .body(axum::body::Body::from(serde_json::json!({"jsonrpc":"2.0", "id":1, "method":"tools/call", "params":{"name":"SharePreview", "arguments":{"port":port}}}).to_string())).unwrap()+ };+ let denied = mcp.clone().oneshot(call()).await.unwrap();+ let denied: serde_json::Value =+ serde_json::from_slice(&denied.into_body().collect().await.unwrap().to_bytes()).unwrap();+ assert!(denied.get("error").is_some());+ let mut request = call();+ request+ .headers_mut()+ .insert("authorization", "Bearer session-secret".parse().unwrap());+ let result = mcp.oneshot(request).await.unwrap();+ assert_eq!(result.status(), axum::http::StatusCode::OK);+ let result: serde_json::Value =+ serde_json::from_slice(&result.into_body().collect().await.unwrap().to_bytes()).unwrap();+ assert!(result.get("error").is_none());+ let output: serde_json::Value =+ serde_json::from_str(result["result"]["content"][0]["text"].as_str().unwrap()).unwrap();+ let preview_id = output["preview"]["id"].as_str().unwrap().to_owned();+ let preview = PreviewId::parse(&preview_id).unwrap();+ let dir = tempfile::tempdir().unwrap();+ let script = dir.path().join("connect.sh");+ std::fs::write(&script, output["script"].as_str().unwrap()).unwrap();+ let status = tokio::time::timeout(+ Duration::from_secs(15),+ tokio::process::Command::new("sh")+ .arg(&script)+ .kill_on_drop(true)+ .status(),+ )+ .await+ .unwrap()+ .unwrap();+ assert!(status.success(), "generated script failed");+ tokio::time::timeout(Duration::from_secs(15), async {+ loop {+ let preview = service.get(receipt(AccessLevel::View)).unwrap().unwrap();+ if preview.status == PreviewStatus::Ready {+ break;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ })+ .await+ .unwrap();+ let ticket = service.launch(receipt(AccessLevel::View)).unwrap();+ let cookie = service.redeem(&preview, &ticket.ticket).await.unwrap();+ let lease = service.viewer(&preview, &cookie, true).await.unwrap();+ let mut stream = lease.tunnel().unwrap().open().await.unwrap();+ stream+ .write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")+ .await+ .unwrap();+ let mut bytes = Vec::new();+ tokio::time::timeout(Duration::from_secs(5), stream.read_to_end(&mut bytes))+ .await+ .unwrap()+ .unwrap();+ assert!(String::from_utf8(bytes).unwrap().contains("live preview"));+ // Traverse the public HTTP proxy and its real 101 upgrade over the SSH channel.+ let public = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let public_addr = public.local_addr().unwrap();+ let gateway = tokio::spawn(+ axum::serve(public, super::super::http::router(service.clone())).into_future(),+ );+ use futures_util::{SinkExt, StreamExt};+ use tokio_tungstenite::tungstenite::client::IntoClientRequest;+ let host = format!("{}.preview.test", preview_id);+ let mut request = format!("ws://{host}/socket?token=app-owned")+ .into_client_request()+ .unwrap();+ request+ .headers_mut()+ .insert("origin", format!("https://{host}").parse().unwrap());+ request.headers_mut().insert(+ "cookie",+ format!("__Host-macro-preview={cookie}").parse().unwrap(),+ );+ let connection = tokio::net::TcpStream::connect(public_addr).await.unwrap();+ let (mut ws, _) = tokio_tungstenite::client_async(request, connection)+ .await+ .unwrap();+ ws.send(tokio_tungstenite::tungstenite::Message::Text(+ "hmr-update".into(),+ ))+ .await+ .unwrap();+ assert_eq!(+ ws.next().await.unwrap().unwrap().into_text().unwrap(),+ "hmr-update"+ );+ service.stop(receipt(AccessLevel::Edit)).await.unwrap();+ assert!(lease.cancel.is_cancelled());+ assert!(+ tokio::time::timeout(Duration::from_secs(3), ws.next())+ .await+ .is_ok()+ );+ shutdown.cancel();+ server.await.unwrap().unwrap();+ gateway.abort();+ upstream_task.abort();+}++/// The gateway must never be usable as anything but a reverse tunnel for its own+/// previews. Shell/exec and `direct-tcpip` are refused only because `Connection`+/// leaves those handlers unimplemented and russh drops the reply handle, which+/// fails closed — a library default, not an explicit deny, so assert it here:+/// were it ever to flip, this service would become an open TCP relay running+/// inside the services network.+#[tokio::test]+async fn gateway_refuses_outbound_relay_and_shell() {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let ssh_port = listener.local_addr().unwrap().port();+ let (service, _, key) = fixture(ssh_port);+ let shutdown = CancellationToken::new();+ let server = tokio::spawn(serve(+ listener,+ key.clone(),+ service.clone(),+ Arc::new(|h| Arc::new(SshTunnel::new(h))),+ shutdown.clone(),+ ));+ let share = service+ .share(crate::testing::identity(), 3000)+ .await+ .unwrap();+ let dir = tempfile::tempdir().unwrap();+ let known = dir.path().join("known_hosts");+ std::fs::write(+ &known,+ format!(+ "[localhost]:{ssh_port} {}\n",+ crate::inbound::ssh::public_key(&key).unwrap()+ ),+ )+ .unwrap();+ let base = |token: &str| {+ let mut c = tokio::process::Command::new("ssh");+ c.args([+ "-F",+ "/dev/null",+ "-o",+ "BatchMode=yes",+ "-o",+ "PubkeyAuthentication=no",+ "-o",+ "StrictHostKeyChecking=yes",+ "-o",+ "ConnectTimeout=10",+ ])+ .arg("-o")+ .arg(format!("UserKnownHostsFile={}", known.display()))+ .args(["-p", &ssh_port.to_string(), "-l", token, "localhost"]);+ c.kill_on_drop(true);+ c+ };++ // 1. A session channel (shell/exec) must be refused.+ let exec = tokio::time::timeout(+ Duration::from_secs(20),+ base(&share.token).arg("echo pwned").output(),+ )+ .await+ .unwrap()+ .unwrap();+ println!(+ "exec status={:?}\n stderr: {}",+ exec.status.code(),+ String::from_utf8_lossy(&exec.stderr).trim()+ );+ assert!(+ !exec.status.success(),+ "the gateway granted a session channel"+ );+ assert!(!String::from_utf8_lossy(&exec.stdout).contains("pwned"));++ // 2. direct-tcpip: an outbound relay to a third party must be refused.+ // The token is single-use, and a second share for the same owner would hit+ // the creation rate limit, so charge it to another account.+ let other = crate::domain::AgentIdentity {+ session: "00000000-0000-0000-0000-000000000002".parse().unwrap(),+ owner: MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap(),+ };+ let share2 = service.share(other, 3000).await.unwrap();+ let relay = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let relay_port = relay.local_addr().unwrap().port();+ let hit = Arc::new(std::sync::atomic::AtomicBool::new(false));+ let hit2 = hit.clone();+ tokio::spawn(async move {+ if relay.accept().await.is_ok() {+ hit2.store(true, std::sync::atomic::Ordering::SeqCst);+ }+ });+ let local = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let local_port = local.local_addr().unwrap().port();+ drop(local);+ let mut forward = base(&share2.token)+ .args([+ "-N",+ "-L",+ &format!("127.0.0.1:{local_port}:127.0.0.1:{relay_port}"),+ ])+ .spawn()+ .unwrap();+ tokio::time::sleep(Duration::from_secs(2)).await;+ // Drive traffic through the forward: ssh only opens the direct-tcpip+ // channel when something actually connects to the listening side.+ let probe = tokio::net::TcpStream::connect(("127.0.0.1", local_port)).await;+ println!("local forward accepted a client: {}", probe.is_ok());+ if let Ok(mut probe) = probe {+ use tokio::io::AsyncWriteExt;+ let _ = probe.write_all(b"GET / HTTP/1.0\r\n\r\n").await;+ let mut sink = Vec::new();+ let _ = tokio::time::timeout(+ Duration::from_secs(3),+ tokio::io::AsyncReadExt::read_to_end(&mut probe, &mut sink),+ )+ .await;+ }+ tokio::time::sleep(Duration::from_secs(1)).await;+ let _ = forward.kill().await;+ assert!(+ !hit.load(std::sync::atomic::Ordering::SeqCst),+ "the gateway opened an outbound TCP connection on a client's behalf"+ );+ println!("direct-tcpip relay: refused");++ shutdown.cancel();+ let _ = server.await;+}diff --git a/crates/agent_preview/src/inbound/toolset.rs b/crates/agent_preview/src/inbound/toolset.rsnew file mode 100644index 0000000000..6aa0323713--- /dev/null+++ b/crates/agent_preview/src/inbound/toolset.rs@@ -0,0 +1,297 @@+//! Internal MCP tools. Session identity comes from egress authentication, never tool arguments.+use crate::domain::{AgentIdentity, PreviewService};+use ai_toolset::{+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,+};+use axum::Router;+use rmcp::{+ ServerHandler,+ model::{+ CallToolRequestParams, CallToolResult, Content, ListToolsResult, PaginatedRequestParams,+ ServerCapabilities, ServerInfo, Tool,+ },+ service::RequestContext as McpContext,+ transport::{+ StreamableHttpService,+ streamable_http_server::{StreamableHttpServerConfig, session::local::LocalSessionManager},+ },+};+use rootcause::compat::anyhow1::IntoAnyhow;+use schemars::JsonSchema;+use serde::Deserialize;+use std::sync::Arc;++/// Shell functions appended only for local stacks that published a quick tunnel.+///+/// Cloudflare's edge proxies HTTP ports only, so a raw SSH dial to the minted+/// hostname is dropped: the stream has to be wrapped in a WebSocket, which is+/// what `cloudflared access ssh` does as an OpenSSH `ProxyCommand`. That helper+/// therefore has to exist on the agent's machine, so fetch it when missing. Its+/// directory is deliberately not cleaned up: the backgrounded `ssh` keeps+/// `cloudflared` as a child for the life of the tunnel.+const PROXY_SUPPORT: &str = r#"preview_cloudflared() {+if command -v cloudflared >/dev/null 2>&1; then return 0; fi+preview_arch=$(uname -m)+case "$preview_arch" in+ x86_64|amd64) preview_arch=amd64 ;;+ aarch64|arm64) preview_arch=arm64 ;;+ *) printf '%s\n' "no cloudflared build for $preview_arch" >&2; return 1 ;;+esac+preview_os=$(uname -s | tr '[:upper:]' '[:lower:]')+preview_bin=$(mktemp -d)+curl -fsSL --max-time 120 -o "$preview_bin/cloudflared" \+ "https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-$preview_os-$preview_arch" || return 1+chmod +x "$preview_bin/cloudflared"+PATH="$preview_bin:$PATH"+export PATH+}+preview_connect_proxy() {+preview_cloudflared || return 1+ssh -F /dev/null -fNT \+ -o BatchMode=yes \+ -o PubkeyAuthentication=no \+ -o PasswordAuthentication=no \+ -o KbdInteractiveAuthentication=no \+ -o StrictHostKeyChecking=yes \+ -o HostKeyAlgorithms=ssh-ed25519 \+ -o UserKnownHostsFile="$preview_known_hosts" \+ -o GlobalKnownHostsFile=/dev/null \+ -o ControlMaster=no \+ -o ControlPath=none \+ -o ConnectTimeout=30 \+ -o ExitOnForwardFailure=yes \+ -o ServerAliveInterval=15 \+ -o ServerAliveCountMax=3 \+ -o ProxyCommand="cloudflared access ssh --hostname $1" \+ -R 127.0.0.1:1:127.0.0.1:PREVIEW_LOCAL_PORT \+ -p 22 -l 'PREVIEW_TOKEN' "$1"+}+"#;++/// The name `ssh` looks up in `known_hosts`: bracketed only on a non-default port.+fn known_hosts_name(host: &str, port: u16) -> String {+ if port == 22 {+ host.to_owned()+ } else {+ format!("[{host}]:{port}")+ }+}++/// Authenticated session context; constructed per request, never shared across agents.+#[derive(Clone)]+pub struct PreviewToolContext {+ service: PreviewService,+ identity: AgentIdentity,+}+/// Expose the current agent's local HTTP server as an entity-authorized live preview.+#[derive(Deserialize, JsonSchema)]+#[serde(deny_unknown_fields)]+#[schemars(+ title = "SharePreview",+ description = "Share a running local HTTP development server with viewers of this agent session. Returns a shell script: execute it in the same machine/container as the server. Requires only OpenSSH, no helper or client key. Supports HTTP, WebSocket and HMR. The preview appears in Macro once reachable. Keep the dev server running; edits remain live. Call again to reconnect after the tunnel ends. Do not publish credentials or the script in a chat message."+)]+pub struct SharePreview {+ /// The local HTTP server port, such as 3000 or 5173.+ #[schemars(description = "Port of the running local HTTP server (1 through 65535).")]+ pub port: u16,+}+impl ToolAnnotated for SharePreview {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Share live preview");+}+#[async_trait::async_trait]+impl AsyncTool<PreviewToolContext> for SharePreview {+ type Output = serde_json::Value;+ async fn call(+ &self,+ context: ServiceContext<PreviewToolContext>,+ _: RequestContext,+ ) -> ToolResult<Self::Output> {+ let share = context+ .service+ .share(context.identity.clone(), self.port)+ .await+ .map_err(|e| ai_toolset::ToolCallError {+ description: e.to_string(),+ internal_error: rootcause::report!(e).into_anyhow(),+ })?;+ let settings = context.service.settings();+ // Endpoints are tried in order until one connects: the agent may share this+ // machine, the Docker network, or neither. Each contributes its own+ // known_hosts name, because all of them reach the same pinned host key.+ let mut endpoints = vec![(+ known_hosts_name(&settings.ssh_host, settings.ssh_port),+ format!(+ "preview_connect '{}' {}",+ settings.ssh_host, settings.ssh_port+ ),+ )];+ if settings.local_ssh_fallback {+ endpoints.push((+ known_hosts_name("preview-gateway", 2222),+ "preview_connect preview-gateway 2222".to_owned(),+ ));+ }+ if let Some(proxy) = &settings.ssh_proxy_host {+ // Cloudflare's edge only proxies HTTP ports, so the quick tunnel is+ // reached over a WebSocket ProxyCommand rather than a TCP dial.+ endpoints.push((+ known_hosts_name(proxy, 22),+ format!("preview_connect_proxy '{proxy}'"),+ ));+ }+ let known_host = endpoints+ .iter()+ .map(|(name, _)| format!("{name} {}", settings.host_key))+ .collect::<Vec<_>>()+ .join("\n");+ let connect = endpoints+ .iter()+ .map(|(_, call)| call.as_str())+ .collect::<Vec<_>>()+ .join(" || ");+ let proxy_support = if settings.ssh_proxy_host.is_some() {+ PROXY_SUPPORT+ .replace("PREVIEW_LOCAL_PORT", &share.port.to_string())+ .replace("PREVIEW_TOKEN", &share.token)+ } else {+ String::new()+ };+ // Every interpolated field is validated at startup or generated locally; no shell input from the model.+ let script = format!(+ r#"#!/bin/sh+set -eu+umask 077+preview_known_hosts=$(mktemp)+trap 'rm -f "$preview_known_hosts"' EXIT HUP INT TERM+cat > "$preview_known_hosts" <<'MACRO_PREVIEW_HOST_KEY'+{known_host}+MACRO_PREVIEW_HOST_KEY+preview_connect() {{+ssh -F /dev/null -fNT \+ -o BatchMode=yes \+ -o PubkeyAuthentication=no \+ -o PasswordAuthentication=no \+ -o KbdInteractiveAuthentication=no \+ -o StrictHostKeyChecking=yes \+ -o HostKeyAlgorithms=ssh-ed25519 \+ -o UserKnownHostsFile="$preview_known_hosts" \+ -o GlobalKnownHostsFile=/dev/null \+ -o ControlMaster=no \+ -o ControlPath=none \+ -o ConnectTimeout=10 \+ -o ExitOnForwardFailure=yes \+ -o ServerAliveInterval=15 \+ -o ServerAliveCountMax=3 \+ -R 127.0.0.1:1:127.0.0.1:{port} \+ -p "$2" -l '{token}' "$1"+}}+{proxy_support}{connect}+printf '%s\n' 'Preview tunnel connected. Keep the local server running; Macro shows the preview once HTTP is reachable.'+"#,+ port = share.port,+ token = share.token+ );+ Ok(+ serde_json::json!({ "preview": share.preview, "script": script, "instructions": "Execute this shell script within 120 seconds on the machine running the local server. The gateway forwards the root path unchanged and rewrites Host to localhost. If the app hardcodes a browser-facing localhost URL, configure its public origin. The tunnel expires after one hour or 15 minutes without browser requests. Do not print the script in your final response." }),+ )+ }+}+#[derive(Clone)]+struct Mcp(PreviewService);+impl Mcp {+ async fn identity(+ &self,+ context: &McpContext<rmcp::RoleServer>,+ ) -> Result<AgentIdentity, rmcp::ErrorData> {+ let token = context+ .extensions+ .get::<axum::http::request::Parts>()+ .and_then(|p| p.headers.get(axum::http::header::AUTHORIZATION))+ .and_then(|v| v.to_str().ok())+ .and_then(|v| v.strip_prefix("Bearer "))+ .filter(|v| v.len() <= 256)+ .ok_or_else(|| {+ rmcp::ErrorData::invalid_request("agent session authentication required", None)+ })?;+ self.0.agent(token).await.map_err(|_| {+ rmcp::ErrorData::invalid_request("agent session authentication failed", None)+ })+ }+}+impl ServerHandler for Mcp {+ fn get_info(&self) -> ServerInfo {+ let mut info = ServerInfo::new(ServerCapabilities::builder().enable_tools().build());+ info.server_info =+ rmcp::model::Implementation::new("macro-preview", env!("CARGO_PKG_VERSION"));+ info.instructions = Some("Use SharePreview to share a local development server with viewers of the current Macro session. Execute the returned SSH script, then continue editing; WebSocket hot reload is forwarded automatically. Credentials must stay in tool execution, never final messages.".into());+ info+ }+ async fn list_tools(+ &self,+ _: Option<PaginatedRequestParams>,+ context: McpContext<rmcp::RoleServer>,+ ) -> Result<ListToolsResult, rmcp::ErrorData> {+ self.identity(&context).await?;+ let schema = schemars::schema_for!(SharePreview);+ let value = serde_json::to_value(schema)+ .map_err(|_| rmcp::ErrorData::internal_error("tool schema unavailable", None))?;+ let object = value+ .as_object()+ .cloned()+ .ok_or_else(|| rmcp::ErrorData::internal_error("tool schema unavailable", None))?;+ Ok(ListToolsResult {+ tools: vec![Tool::new(+ "SharePreview",+ "Share a local HTTP development server with this session's viewers. Execute the returned OpenSSH script to connect it; supports WebSockets and HMR.",+ Arc::new(object),+ )],+ ..Default::default()+ })+ }+ async fn call_tool(+ &self,+ request: CallToolRequestParams,+ context: McpContext<rmcp::RoleServer>,+ ) -> Result<CallToolResult, rmcp::ErrorData> {+ let identity = self.identity(&context).await?;+ if request.name != "SharePreview" {+ return Err(rmcp::ErrorData::invalid_params(+ "unknown preview tool",+ None,+ ));+ }+ let tool: SharePreview = serde_json::from_value(serde_json::Value::Object(+ request.arguments.unwrap_or_default(),+ ))+ .map_err(|_| rmcp::ErrorData::invalid_params("expected {port: 1..65535}", None))?;+ let user = identity.owner.clone();+ let result = tool+ .call(+ ServiceContext(PreviewToolContext {+ service: self.0.clone(),+ identity,+ }),+ RequestContext::new(user),+ )+ .await;+ Ok(match result {+ Ok(value) => CallToolResult::success(vec![Content::text(value.to_string())]),+ Err(error) => CallToolResult::error(vec![Content::text(error.to_string())]),+ })+ }+}+/// Build a stateless MCP server: every tool request authenticates its session credential.+pub fn router(service: PreviewService, allowed_hosts: Vec<String>) -> Router {+ let mut config = StreamableHttpServerConfig::default().with_allowed_hosts(allowed_hosts);+ config.stateful_mode = false;+ config.json_response = true;+ let transport = StreamableHttpService::new(+ move || Ok(Mcp(service.clone())),+ Arc::new(LocalSessionManager::default()),+ config,+ );+ Router::new().nest_service("/mcp", transport)+}++#[cfg(test)]+mod test;diff --git a/crates/agent_preview/src/inbound/toolset/test.rs b/crates/agent_preview/src/inbound/toolset/test.rsnew file mode 100644index 0000000000..d48ff01b69--- /dev/null+++ b/crates/agent_preview/src/inbound/toolset/test.rs@@ -0,0 +1,119 @@+use super::*;+use crate::testing::{fixture_with, identity};++/// Settings for a local stack that published a quick tunnel: every reachability+/// path at once, which is also the only configuration that allows a proxy host.+fn local_stack(proxy: Option<&str>) -> (PreviewService, String) {+ let proxy = proxy.map(str::to_owned);+ let (service, _, _) = fixture_with(2222, |settings| {+ settings.domain = "preview.localhost".into();+ settings.https_port = 8443;+ settings.app_origin = "http://localhost:3000".into();+ settings.local_ssh_fallback = true;+ settings.ssh_proxy_host = proxy;+ });+ let key = service.settings().host_key.clone();+ (service, key)+}++async fn script(service: &PreviewService) -> String {+ let context = ServiceContext(PreviewToolContext {+ service: service.clone(),+ identity: identity(),+ });+ let user = identity().owner;+ let value = SharePreview { port: 5173 }+ .call(context, RequestContext::new(user))+ .await+ .unwrap();+ let script = value["script"].as_str().unwrap().to_owned();+ // The forward is what carries the agent's port into the tunnel; every+ // endpoint has to request it, proxied or not.+ assert_eq!(+ script.matches("-R 127.0.0.1:1:127.0.0.1:5173").count(),+ 1 + usize::from(script.contains("preview_connect_proxy"))+ );+ script+}++#[tokio::test]+async fn a_local_stack_without_a_tunnel_offers_only_on_machine_endpoints() {+ let (service, _) = local_stack(None);+ let script = script(&service).await;++ assert!(script.contains("preview_connect 'localhost' 2222"));+ assert!(script.contains("preview_connect preview-gateway 2222"));+ assert!(!script.contains("preview_connect_proxy"));+ assert!(!script.contains("cloudflared"));+}++#[tokio::test]+async fn a_published_tunnel_is_tried_after_the_on_machine_endpoints() {+ let (service, _) = local_stack(Some("odds-and-ends.trycloudflare.com"));+ let script = script(&service).await;++ let connect = script+ .lines()+ .find(|line| line.starts_with("preview_connect '"))+ .expect("the connect chain is one line");+ assert_eq!(+ connect,+ "preview_connect 'localhost' 2222 || preview_connect preview-gateway 2222 || \+ preview_connect_proxy 'odds-and-ends.trycloudflare.com'"+ );+ assert!(script.contains("-o ProxyCommand=\"cloudflared access ssh --hostname $1\""));+ // The helper has to be fetched when absent: agent images do not ship it.+ assert!(script.contains("releases/latest/download/cloudflared-$preview_os-$preview_arch"));+}++#[tokio::test]+async fn every_endpoint_pins_the_same_host_key_under_its_own_name() {+ let (service, key) = local_stack(Some("odds-and-ends.trycloudflare.com"));+ let script = script(&service).await;++ let known_hosts: Vec<_> = script+ .lines()+ .skip_while(|line| !line.starts_with("cat > \"$preview_known_hosts\""))+ .skip(1)+ .take_while(|line| *line != "MACRO_PREVIEW_HOST_KEY")+ .collect();+ assert_eq!(+ known_hosts,+ vec![+ format!("[localhost]:2222 {key}"),+ format!("[preview-gateway]:2222 {key}"),+ // Dialled through a ProxyCommand on the default port, so `ssh` looks+ // this one up unbracketed.+ format!("odds-and-ends.trycloudflare.com {key}"),+ ]+ );+}++#[tokio::test]+async fn a_deployed_gateway_never_advertises_a_proxy_or_docker_endpoint() {+ let (service, _, _) = crate::testing::fixture(22);+ let script = script(&service).await;++ assert!(script.contains("preview_connect 'localhost' 22\n"));+ assert!(!script.contains("preview-gateway"));+ assert!(!script.contains("cloudflared"));+ assert!(script.contains("\nlocalhost "), "unbracketed on port 22");+}++#[test]+fn a_proxy_host_is_rejected_outside_a_local_stack() {+ let (service, _, _) = crate::testing::fixture(2222);+ let mut settings = service.settings().clone();+ settings.ssh_proxy_host = Some("odds-and-ends.trycloudflare.com".into());+ assert!(+ settings.validate().is_err(),+ "a public deployment must not reach its SSH listener through someone's quick tunnel"+ );++ settings.domain = "preview.localhost".into();+ settings.app_origin = "http://localhost:3000".into();+ assert!(settings.validate().is_ok());++ settings.ssh_proxy_host = Some("not a hostname".into());+ assert!(settings.validate().is_err());+}diff --git a/crates/agent_preview/src/lib.rs b/crates/agent_preview/src/lib.rsnew file mode 100644index 0000000000..8d00d79eba--- /dev/null+++ b/crates/agent_preview/src/lib.rs@@ -0,0 +1,12 @@+#![deny(missing_docs)]+//! Leased, entity-authorized live previews over stock OpenSSH reverse forwarding.++/// Preview policies and capabilities, independent of HTTP and SSH.+pub mod domain;+/// HTTP, MCP and SSH entry points.+pub mod inbound;+/// Transport implementations for domain capabilities.+pub mod outbound;++#[cfg(test)]+mod testing;diff --git a/crates/agent_preview/src/outbound/mod.rs b/crates/agent_preview/src/outbound/mod.rsnew file mode 100644index 0000000000..c7827ed33d--- /dev/null+++ b/crates/agent_preview/src/outbound/mod.rs@@ -0,0 +1,3 @@+//! Implementations of preview transport capabilities.+/// Open forwarded channels on a registered SSH connection.+pub mod ssh_tunnel;diff --git a/crates/agent_preview/src/outbound/ssh_tunnel.rs b/crates/agent_preview/src/outbound/ssh_tunnel.rsnew file mode 100644index 0000000000..f8e1f5f24a--- /dev/null+++ b/crates/agent_preview/src/outbound/ssh_tunnel.rs@@ -0,0 +1,37 @@+use crate::domain::{+ PreviewError,+ ports::{Stream, Tunnel},+};+use async_trait::async_trait;+/// SSH channel transport; the registered tuple is deliberately constant per connection.+pub struct SshTunnel(russh::server::Handle);+impl SshTunnel {+ /// Bind the capability to the authenticated SSH session.+ pub fn new(handle: russh::server::Handle) -> Self {+ Self(handle)+ }+}+#[async_trait]+impl Tunnel for SshTunnel {+ async fn open(&self) -> Result<Stream, PreviewError> {+ let channel = tokio::time::timeout(+ std::time::Duration::from_secs(10),+ self.0+ .channel_open_forwarded_tcpip("127.0.0.1", 1, "127.0.0.1", 0),+ )+ .await+ .map_err(|_| PreviewError::Unavailable)?+ .map_err(|_| PreviewError::Offline)?;+ Ok(Box::new(channel.into_stream()))+ }+ async fn close(&self) {+ let _ = self+ .0+ .disconnect(+ russh::Disconnect::ByApplication,+ "preview ended".into(),+ "en".into(),+ )+ .await;+ }+}diff --git a/crates/agent_preview/src/testing.rs b/crates/agent_preview/src/testing.rsnew file mode 100644index 0000000000..39a72e082b--- /dev/null+++ b/crates/agent_preview/src/testing.rs@@ -0,0 +1,121 @@+use crate::domain::{ports::*, *};+use agent_fold::domain::log::AgentSessionId;+use async_trait::async_trait;+use entity_access::domain::models::{+ AccessLevel, Entity, EntityAccessReceipt, EntityPermission, EntityType, RequiredPermission,+};+use macro_user_id::user_id::MacroUserIdStr;+use std::sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+};+pub const SESSION: &str = "00000000-0000-0000-0000-000000000001";+pub const USER: &str = "macro|[email protected]";+/// The session every fixture receipt and identity refers to.+pub fn session() -> AgentSessionId {+ SESSION.parse().unwrap()+}+/// The user every fixture receipt and identity refers to.+pub fn user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(USER.to_owned()).unwrap()+}+pub struct TestAuthority(pub AtomicBool);+#[async_trait]+impl Authority for TestAuthority {+ async fn agent(&self, token: &str) -> Result<AgentIdentity, PreviewError> {+ if token != "session-secret" {+ return Err(PreviewError::Denied);+ }+ Ok(identity())+ }+ async fn viewer(+ &self,+ session: AgentSessionId,+ _: &MacroUserIdStr<'_>,+ ) -> Result<(), PreviewError> {+ self.active(session).await+ }+ async fn active(&self, _: AgentSessionId) -> Result<(), PreviewError> {+ if self.0.load(Ordering::SeqCst) {+ Ok(())+ } else {+ Err(PreviewError::Denied)+ }+ }+}+pub struct TestEvents;+#[async_trait]+impl Events for TestEvents {+ async fn changed(+ &self,+ _: &Preview,+ _: &[MacroUserIdStr<'static>],+ ) -> Result<(), PreviewError> {+ Ok(())+ }+}+pub fn identity() -> AgentIdentity {+ AgentIdentity {+ session: session(),+ owner: user(),+ }+}+pub fn receipt<T: RequiredPermission>(level: AccessLevel) -> EntityAccessReceipt<T> {+ EntityAccessReceipt::try_new_authenticated_user(+ user(),+ Entity {+ entity_id: SESSION.into(),+ entity_type: EntityType::AgentSession,+ },+ EntityPermission::AccessLevel {+ access_level: level,+ },+ )+ .unwrap()+}+pub fn fixture(ssh_port: u16) -> (PreviewService, Arc<TestAuthority>, russh::keys::PrivateKey) {+ fixture_with(ssh_port, |_| {})+}+/// Same fixture, with deployment settings adjusted before the service validates them.+pub fn fixture_with(+ ssh_port: u16,+ adjust: impl FnOnce(&mut Settings),+) -> (PreviewService, Arc<TestAuthority>, russh::keys::PrivateKey) {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("host_key");+ assert!(+ std::process::Command::new("ssh-keygen")+ .args(["-q", "-t", "ed25519", "-N", "", "-f"])+ .arg(&path)+ .status()+ .unwrap()+ .success()+ );+ let key = crate::inbound::ssh::host_key(&std::fs::read_to_string(path).unwrap()).unwrap();+ let authority = Arc::new(TestAuthority(AtomicBool::new(true)));+ let mut settings = Settings {+ domain: "preview.test".into(),+ https_port: 443,+ local_ssh_fallback: false,+ ssh_proxy_host: None,+ ssh_host: "localhost".into(),+ ssh_port,+ host_key: crate::inbound::ssh::public_key(&key).unwrap(),+ app_origin: "https://macro.test".into(),+ };+ adjust(&mut settings);+ let service = PreviewService::new(settings, authority.clone(), Arc::new(TestEvents)).unwrap();+ (service, authority, key)+}+pub struct TcpTunnel(pub std::net::SocketAddr);+#[async_trait]+impl Tunnel for TcpTunnel {+ async fn open(&self) -> Result<Stream, PreviewError> {+ Ok(Box::new(+ tokio::net::TcpStream::connect(self.0)+ .await+ .map_err(|_| PreviewError::Unavailable)?,+ ))+ }+ async fn close(&self) {}+}diff --git a/crates/macro_entrypoint/src/lib.rs b/crates/macro_entrypoint/src/lib.rsindex 94747212b2..4d3a9de367 100644--- a/crates/macro_entrypoint/src/lib.rs+++ b/crates/macro_entrypoint/src/lib.rs@@ -97,6 +97,8 @@ pub struct MacroEntrypoint {env: Environment,/// describes options that only apply in local devlocal: LocalOptions,+ /// Dependency targets whose instrumentation can include credentials or application payloads.+ suppressed_targets: &'static [&'static str],}impl Default for MacroEntrypoint {@@ -106,6 +108,7 @@ impl Default for MacroEntrypoint {MacroEntrypoint {env: Environment::new_or_prod(),local: Default::default(),+ suppressed_targets: &[],}}}@@ -135,6 +138,12 @@ impl InitializedEntrypoint {}impl MacroEntrypoint {+ /// Suppress credential-bearing dependency diagnostics in every sink, even if RUST_LOG enables trace.+ pub fn suppress_dependency_logs(mut self, targets: &'static [&'static str]) -> Self {+ self.suppressed_targets = targets;+ self+ }+/// create a new instance of [Self] from an input [Environment]pub fn new(env: Environment) -> Self {Self {@@ -171,6 +180,9 @@ impl MacroEntrypoint {});Registry::default()+ .with(tracing_subscriber::filter::filter_fn(move |metadata| {+ dependency_logs_allowed(self.suppressed_targets, metadata.target())+ })).with(RootcauseLayer.with_filter(rootcause_filter)).with(tracing_subscriber::fmt::layer()@@ -185,6 +197,9 @@ impl MacroEntrypoint {.init();} else {Registry::default()+ .with(tracing_subscriber::filter::filter_fn(move |metadata| {+ dependency_logs_allowed(self.suppressed_targets, metadata.target())+ })).with(RootcauseLayer.with_filter(rust_log_filter.clone())).with(tracing_subscriber::fmt::layer()@@ -210,6 +225,9 @@ impl MacroEntrypoint {) => {let rust_log_filter = rust_log_env_filter();let subscriber = Registry::default()+ .with(tracing_subscriber::filter::filter_fn(move |metadata| {+ dependency_logs_allowed(self.suppressed_targets, metadata.target())+ })).with(RootcauseLayer.with_filter(rust_log_filter.clone())).with(HierarchicalLayer::new(level).with_filter(rust_log_filter));tracing::subscriber::set_global_default(subscriber).unwrap();@@ -249,6 +267,9 @@ impl MacroEntrypoint {.with_filter(rust_log_filter);Registry::default()+ .with(tracing_subscriber::filter::filter_fn(move |metadata| {+ dependency_logs_allowed(self.suppressed_targets, metadata.target())+ })).with(RootcauseLayer.with_filter(rootcause_filter)).with(fmt_layer).with(otel_layer)@@ -402,6 +423,7 @@ impl LocalOptionsBuilder {MacroEntrypoint {env: self.prev.env,local: self.next,+ suppressed_targets: self.prev.suppressed_targets,}}}@@ -410,3 +432,12 @@ impl LocalOptionsBuilder {struct LocalOptions {tree_tracing: Option<usize>,}++fn dependency_logs_allowed(suppressed: &[&str], target: &str) -> bool {+ !suppressed.iter().any(|prefix| {+ target == *prefix+ || target+ .strip_prefix(prefix)+ .is_some_and(|suffix| suffix.starts_with("::"))+ })+}diff --git a/crates/macro_entrypoint/src/test.rs b/crates/macro_entrypoint/src/test.rsindex 0ea8f11363..5598848d41 100644--- a/crates/macro_entrypoint/src/test.rs+++ b/crates/macro_entrypoint/src/test.rs@@ -304,3 +304,33 @@ fn explicit_rust_log_still_wins_over_the_floor() {"an explicit RUST_LOG must override the default floor: {output:?}");}++#[test]+fn dependency_suppression_overrides_enabled_logs_without_hiding_service_logs() {+ let output = SharedWriter::default();+ let subscriber = Registry::default()+ .with(tracing_subscriber::filter::filter_fn(|metadata| {+ dependency_logs_allowed(&["russh", "rmcp"], metadata.target())+ }))+ .with(+ tracing_subscriber::fmt::layer()+ .with_ansi(false)+ .with_writer(output.clone())+ .with_filter(EnvFilter::new("info")),+ );+ tracing::subscriber::with_default(subscriber, || {+ tracing::info!(target: "russh::server", username = "test-only-token", "authentication");+ tracing::info!(target: "rmcp::service", "script containing test-only-token");+ tracing::info!(target: "preview_gateway", "gateway ready");+ tracing::info!(target: "russh_unrelated", "unrelated target");+ });+ let text = output.contents();+ assert!(!text.contains("test-only-token"));+ assert!(text.contains("gateway ready"));+ assert!(text.contains("unrelated target"));+ let entrypoint = MacroEntrypoint::default()+ .suppress_dependency_logs(&["russh"])+ .local()+ .build();+ assert_eq!(entrypoint.suppressed_targets, &["russh"]);+}diff --git a/crates/macro_service_urls/src/lib.rs b/crates/macro_service_urls/src/lib.rsindex 4e9a4847f2..e9021abcaa 100644--- a/crates/macro_service_urls/src/lib.rs+++ b/crates/macro_service_urls/src/lib.rs@@ -633,3 +633,12 @@ service_url! {},}}++service_url! {+ /// Control and internal MCP surface of the live preview service.+ pub struct PreviewGatewayUrl {+ local: "http://localhost:8110",+ dev: "https://dev-gateway.macro.com/preview",+ prod: "https://gateway.macro.com/preview",+ }+}diff --git a/crates/workspace-hack/Cargo.toml b/crates/workspace-hack/Cargo.tomlindex 3489129c93..b80c55d838 100644--- a/crates/workspace-hack/Cargo.toml+++ b/crates/workspace-hack/Cargo.toml@@ -40,12 +40,17 @@ byteorder = { version = "1" }bytes = { version = "1", features = ["serde"] }bzip2 = { version = "0.5", features = ["libbz2-rs-sys"] }bzip2-sys = { version = "0.1", default-features = false, features = ["__disabled"] }+chacha20 = { version = "0.10", default-features = false, features = ["legacy", "rng", "zeroize"] }chrono = { version = "0.4", features = ["serde"] }+cipher = { version = "0.5", default-features = false, features = ["block-padding", "rand_core", "stream-wrapper"] }crossbeam-utils = { version = "0.8" }crypto-bigint = { version = "0.5", features = ["generic-array", "zeroize"] }-crypto-common = { version = "0.1", default-features = false, features = ["getrandom", "std"] }+crypto-common-6f8ce4dd05d13bba = { package = "crypto-common", version = "0.2", default-features = false, features = ["getrandom"] }+crypto-common-c65f7effa3be6d31 = { package = "crypto-common", version = "0.1", default-features = false, features = ["getrandom", "std"] }+ctutils = { version = "0.4", default-features = false, features = ["subtle"] }derive_more = { version = "2", features = ["add", "add_assign", "display", "from"] }-digest = { version = "0.10", features = ["mac", "oid", "std"] }+digest-93f6ce9d446188ac = { package = "digest", version = "0.10", features = ["mac", "oid", "std"] }+digest-a6292c17cd707f01 = { package = "digest", version = "0.11", features = ["alloc", "mac", "oid", "rand_core"] }doppleganger = { version = "0.5", default-features = false, features = ["chrono", "uuid"] }doppleganger-core = { version = "0.5", default-features = false, features = ["chrono", "uuid"] }either = { version = "1", features = ["serde", "use_std"] }@@ -65,16 +70,19 @@ futures-util = { version = "0.3", features = ["channel", "io", "sink"] }generic-array = { version = "0.14", default-features = false, features = ["more_lengths", "zeroize"] }getrandom-468e82937335b1c9 = { package = "getrandom", version = "0.3", default-features = false, features = ["std", "wasm_js"] }getrandom-6f8ce4dd05d13bba = { package = "getrandom", version = "0.2", default-features = false, features = ["std"] }+getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-features = false, features = ["std", "sys_rng", "wasm_js"] }hashbrown-582f2526e08bb6a0 = { package = "hashbrown", version = "0.14", features = ["raw"] }hashbrown-9067fe90e8c1f593 = { package = "hashbrown", version = "0.17" }hashbrown-986da7b5efc2b80e = { package = "hashbrown", version = "0.16" }hmac = { version = "0.12", default-features = false, features = ["reset"] }+hybrid-array = { version = "0.4", default-features = false, features = ["alloc", "ctutils", "extra-sizes", "subtle", "zeroize"] }hyper-582f2526e08bb6a0 = { package = "hyper", version = "0.14", default-features = false, features = ["client", "http1", "http2", "runtime", "server", "stream"] }hyper-dff4ba8e3ae991db = { package = "hyper", version = "1", features = ["full"] }hyper-rustls-adf3d7031871b0af = { package = "hyper-rustls", version = "0.24", default-features = false, features = ["acceptor", "http1", "http2", "logging", "tls12", "webpki-tokio"] }hyper-util = { version = "0.1", features = ["client-legacy", "client-proxy", "http1", "http2", "server", "service"] }idna = { version = "1" }indexmap = { version = "2", features = ["serde"] }+inout = { version = "0.2", default-features = false, features = ["block-padding"] }insta = { version = "1", features = ["glob", "json"] }itertools = { version = "0.13" }lazy_static = { version = "1", default-features = false, features = ["spin_no_std"] }@@ -127,7 +135,7 @@ spin = { version = "0.9", default-features = false, features = ["once", "spin_musqlx-core = { version = "0.8", features = ["_rt-tokio", "_tls-rustls-ring-webpki", "any", "chrono", "json", "migrate", "offline", "uuid"] }sqlx-postgres = { version = "0.8", default-features = false, features = ["any", "chrono", "json", "migrate", "offline", "uuid"] }stable_deref_trait = { version = "1" }-subtle = { version = "2" }+subtle = { version = "2", features = ["const-generics"] }sync_wrapper = { version = "1", default-features = false, features = ["futures"] }thiserror = { version = "2" }time = { version = "0.3", features = ["formatting", "macros", "parsing"] }@@ -176,13 +184,18 @@ bytes = { version = "1", features = ["serde"] }bzip2 = { version = "0.5", features = ["libbz2-rs-sys"] }bzip2-sys = { version = "0.1", default-features = false, features = ["__disabled"] }cc = { version = "1", default-features = false, features = ["parallel"] }+chacha20 = { version = "0.10", default-features = false, features = ["legacy", "rng", "zeroize"] }chrono = { version = "0.4", features = ["serde"] }+cipher = { version = "0.5", default-features = false, features = ["block-padding", "rand_core", "stream-wrapper"] }crossbeam-utils = { version = "0.8" }crypto-bigint = { version = "0.5", features = ["generic-array", "zeroize"] }-crypto-common = { version = "0.1", default-features = false, features = ["getrandom", "std"] }+crypto-common-6f8ce4dd05d13bba = { package = "crypto-common", version = "0.2", default-features = false, features = ["getrandom"] }+crypto-common-c65f7effa3be6d31 = { package = "crypto-common", version = "0.1", default-features = false, features = ["getrandom", "std"] }+ctutils = { version = "0.4", default-features = false, features = ["subtle"] }derive_more = { version = "2", features = ["add", "add_assign", "display", "from"] }derive_more-impl = { version = "2", features = ["add", "add_assign", "display", "from"] }-digest = { version = "0.10", features = ["mac", "oid", "std"] }+digest-93f6ce9d446188ac = { package = "digest", version = "0.10", features = ["mac", "oid", "std"] }+digest-a6292c17cd707f01 = { package = "digest", version = "0.11", features = ["alloc", "mac", "oid", "rand_core"] }doppleganger = { version = "0.5", default-features = false, features = ["chrono", "uuid"] }doppleganger-core = { version = "0.5", default-features = false, features = ["chrono", "uuid"] }either = { version = "1", features = ["serde", "use_std"] }@@ -202,16 +215,19 @@ futures-util = { version = "0.3", features = ["channel", "io", "sink"] }generic-array = { version = "0.14", default-features = false, features = ["more_lengths", "zeroize"] }getrandom-468e82937335b1c9 = { package = "getrandom", version = "0.3", default-features = false, features = ["std", "wasm_js"] }getrandom-6f8ce4dd05d13bba = { package = "getrandom", version = "0.2", default-features = false, features = ["std"] }+getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-features = false, features = ["std", "sys_rng", "wasm_js"] }hashbrown-582f2526e08bb6a0 = { package = "hashbrown", version = "0.14", features = ["raw"] }hashbrown-9067fe90e8c1f593 = { package = "hashbrown", version = "0.17" }hashbrown-986da7b5efc2b80e = { package = "hashbrown", version = "0.16" }hmac = { version = "0.12", default-features = false, features = ["reset"] }+hybrid-array = { version = "0.4", default-features = false, features = ["alloc", "ctutils", "extra-sizes", "subtle", "zeroize"] }hyper-582f2526e08bb6a0 = { package = "hyper", version = "0.14", default-features = false, features = ["client", "http1", "http2", "runtime", "server", "stream"] }hyper-dff4ba8e3ae991db = { package = "hyper", version = "1", features = ["full"] }hyper-rustls-adf3d7031871b0af = { package = "hyper-rustls", version = "0.24", default-features = false, features = ["acceptor", "http1", "http2", "logging", "tls12", "webpki-tokio"] }hyper-util = { version = "0.1", features = ["client-legacy", "client-proxy", "http1", "http2", "server", "service"] }idna = { version = "1" }indexmap = { version = "2", features = ["serde"] }+inout = { version = "0.2", default-features = false, features = ["block-padding"] }insta = { version = "1", features = ["glob", "json"] }itertools = { version = "0.13" }lazy_static = { version = "1", default-features = false, features = ["spin_no_std"] }@@ -268,7 +284,7 @@ spin = { version = "0.9", default-features = false, features = ["once", "spin_musqlx-core = { version = "0.8", features = ["_rt-tokio", "_tls-rustls-ring-webpki", "any", "chrono", "json", "migrate", "offline", "uuid"] }sqlx-postgres = { version = "0.8", default-features = false, features = ["any", "chrono", "json", "migrate", "offline", "uuid"] }stable_deref_trait = { version = "1" }-subtle = { version = "2" }+subtle = { version = "2", features = ["const-generics"] }syn-7b89eefb6aaa9bf3 = { package = "syn", version = "3", features = ["extra-traits", "full", "visit-mut"] }syn-dff4ba8e3ae991db = { package = "syn", version = "1", features = ["extra-traits", "fold", "full"] }syn-f595c2ba2a3f28df = { package = "syn", version = "2", features = ["extra-traits", "fold", "full", "visit", "visit-mut"] }@@ -298,12 +314,12 @@ bitflags = { version = "2", default-features = false, features = ["std"] }crossbeam-epoch = { version = "0.9" }data-encoding = { version = "2" }futures-lite = { version = "2" }-getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-features = false, features = ["std", "sys_rng"] }hyper-rustls-754bda37e0fb3874 = { package = "hyper-rustls", version = "0.27", default-features = false, features = ["aws-lc-rs", "http1", "http2", "native-tokio", "ring", "tls12", "webpki-tokio"] }hyper-util = { version = "0.1", default-features = false, features = ["client-proxy-system"] }ipnet = { version = "2", features = ["serde"] }linux-raw-sys = { version = "0.12", default-features = false, features = ["auxvec", "elf", "errno", "general", "if_ether", "ioctl", "net", "netlink", "no_std", "prctl", "system", "xdp"] }mio = { version = "1", features = ["net", "os-ext"] }+nix = { version = "0.31", features = ["feature", "mman"] }once_cell = { version = "1", default-features = false, features = ["critical-section"] }rand-93f6ce9d446188ac = { package = "rand", version = "0.10" }rustix = { version = "1", features = ["event", "fs", "net", "pipe", "process", "system", "time"] }@@ -320,12 +336,12 @@ bitflags = { version = "2", default-features = false, features = ["std"] }crossbeam-epoch = { version = "0.9" }data-encoding = { version = "2" }futures-lite = { version = "2" }-getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-features = false, features = ["std", "sys_rng"] }hyper-rustls-754bda37e0fb3874 = { package = "hyper-rustls", version = "0.27", default-features = false, features = ["aws-lc-rs", "http1", "http2", "native-tokio", "ring", "tls12", "webpki-tokio"] }hyper-util = { version = "0.1", default-features = false, features = ["client-proxy-system"] }ipnet = { version = "2", features = ["serde"] }linux-raw-sys = { version = "0.12", default-features = false, features = ["auxvec", "elf", "errno", "general", "if_ether", "ioctl", "net", "netlink", "no_std", "prctl", "system", "xdp"] }mio = { version = "1", features = ["net", "os-ext"] }+nix = { version = "0.31", features = ["feature", "mman"] }once_cell = { version = "1", default-features = false, features = ["critical-section"] }rand-93f6ce9d446188ac = { package = "rand", version = "0.10" }rustix = { version = "1", features = ["event", "fs", "net", "pipe", "process", "system", "time"] }@@ -343,11 +359,11 @@ crossbeam-epoch = { version = "0.9" }data-encoding = { version = "2" }errno = { version = "0.3" }futures-lite = { version = "2" }-getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-features = false, features = ["std", "sys_rng"] }hyper-rustls-754bda37e0fb3874 = { package = "hyper-rustls", version = "0.27", default-features = false, features = ["aws-lc-rs", "http1", "http2", "native-tokio", "ring", "tls12", "webpki-tokio"] }hyper-util = { version = "0.1", default-features = false, features = ["client-proxy-system"] }ipnet = { version = "2", features = ["serde"] }mio = { version = "1", features = ["net", "os-ext"] }+nix = { version = "0.31", features = ["feature", "mman"] }objc2 = { version = "0.6" }objc2-foundation = { version = "0.3" }once_cell = { version = "1", default-features = false, features = ["critical-section"] }@@ -366,11 +382,11 @@ crossbeam-epoch = { version = "0.9" }data-encoding = { version = "2" }errno = { version = "0.3" }futures-lite = { version = "2" }-getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-features = false, features = ["std", "sys_rng"] }hyper-rustls-754bda37e0fb3874 = { package = "hyper-rustls", version = "0.27", default-features = false, features = ["aws-lc-rs", "http1", "http2", "native-tokio", "ring", "tls12", "webpki-tokio"] }hyper-util = { version = "0.1", default-features = false, features = ["client-proxy-system"] }ipnet = { version = "2", features = ["serde"] }mio = { version = "1", features = ["net", "os-ext"] }+nix = { version = "0.31", features = ["feature", "mman"] }objc2 = { version = "0.6" }objc2-foundation = { version = "0.3" }once_cell = { version = "1", default-features = false, features = ["critical-section"] }diff --git a/docker/docker-compose.yml b/docker/docker-compose.ymlindex bf72fbb09f..d7ed7dc35e 100644--- a/docker/docker-compose.yml+++ b/docker/docker-compose.yml@@ -357,6 +357,21 @@ services:# DEV_DANGEROUS_LOCAL_CONTAINERS and runs sandboxes on the host Docker daemon# instead. Trigger processing and external sessions run without either.# ============================================================================+ preview_gateway:+ <<: [*common-env, *rust-services-image]+ command: ["/app/out/preview_gateway"]+ restart: on-failure+ environment:+ - OVERRIDE_CONNECTION_GATEWAY_URL=http://connection-gateway:8080+ depends_on:+ - postgres+ - connection_gateway+ networks:+ databases:+ services:+ aliases:+ - preview-gateway+agent_harness_service:<<: [*common-env, *rust-services-image]command: ["/app/out/agent_harness_service"]diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex 7b799af048..36a9f8c684 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -726,6 +726,26 @@ with `set_pull_request`, then use **Refresh changes**. An unavailable oroversized PR is explained in the pane; there is no branch or container fallback.Refresh request failures show a retry banner while keeping the last diff visible.The pane does not create PRs or generate their descriptions.+### Live development previews++Coding agents can call the internal **SharePreview** tool with their local HTTP+server port and execute the returned SSH script in that same environment. Keep+the server running while editing; ordinary HTTP and WebSocket HMR traffic are+forwarded. Never paste the script or its credentials into a final chat message.++In an agent session (`/app/coders/<uuid>` for a coding session), the banner+above the transcript moves from **Agent is+connecting a preview…** to **Agent is sharing a preview** once HTTP is reachable.+Click **View preview ↗** to open a new tab. Any viewer of the agent-session entity+can open it; a copied preview URL alone does not authenticate another browser.+Allow popups if opening is blocked. The destination is an isolated HTTPS origin+with normal root paths and no authorization query parameters.++The owner can click **Stop sharing** in the banner; open preview connections+close. Disconnection and expiry leave a banner asking the agent to share again.+Leases last up to one hour and expire after 15 minutes without browser requests.+Continue prompting in the agent session while the preview tab stays open; page+edits should arrive through the app's own HMR connection.### Transcript navigationdiff --git a/infra/bun.lock b/infra/bun.lockindex 2c2c1beb34..1ddcc2426b 100644--- a/infra/bun.lock+++ b/infra/bun.lock@@ -191,6 +191,10 @@"name": "organization-retention-stack","version": "0.0.0",},+ "stacks/preview-gateway": {+ "name": "preview-gateway-stack",+ "version": "0.0.0",+ },"stacks/search-event-queue": {"name": "search-event-queue-stack","version": "0.0.0",@@ -755,6 +759,8 @@"postcss-selector-parser": ["[email protected]", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-HeP7D2wyhkR+XaK6v4W8oRF62Dsz4flyuczALJp61GckGm42u1saSSJ/0auvcBqxs3jMRFEcPK34At/0JBKdOg=="],+ "preview-gateway-stack": ["preview-gateway-stack@workspace:stacks/preview-gateway"],+"proc-log": ["[email protected]", "", {}, "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ=="],"proggy": ["[email protected]", "", {}, "sha512-MbA4R+WQT76ZBm/5JUpV9yqcJt92175+Y0Bodg3HgiXzrmKu7Ggq+bpn6y6wHH+gN9NcyKn3yg1+d47VaKwNAQ=="],diff --git a/infra/packages/shared/src/gateway_priorities.ts b/infra/packages/shared/src/gateway_priorities.tsindex 8ffdaa360e..c3d6f5c603 100644--- a/infra/packages/shared/src/gateway_priorities.ts+++ b/infra/packages/shared/src/gateway_priorities.ts@@ -3,6 +3,7 @@* Add a member when a service migrates onto the gateway.*/export enum GatewayService {+ PREVIEW_GATEWAY = 'PREVIEW_GATEWAY',DOCUMENT_STORAGE_SERVICE = 'DOCUMENT_STORAGE_SERVICE',UNFURL_SERVICE = 'UNFURL_SERVICE',CONVERT_SERVICE = 'CONVERT_SERVICE',@@ -31,6 +32,7 @@ type GatewayPriorityMap = { [K in GatewayService]: number };* Values on this listener must be unique. A missing key is a compile error.*/export const GATEWAY_PRIORITIES: GatewayPriorityMap = {+ [GatewayService.PREVIEW_GATEWAY]: 150,[GatewayService.DOCUMENT_STORAGE_SERVICE]: 10,[GatewayService.UNFURL_SERVICE]: 20,[GatewayService.NOTIFICATION_SERVICE]: 30,diff --git a/infra/stacks/doppler-projects/index.ts b/infra/stacks/doppler-projects/index.tsindex 88a2a915ec..918e9ea046 100644--- a/infra/stacks/doppler-projects/index.ts+++ b/infra/stacks/doppler-projects/index.ts@@ -17,6 +17,7 @@ const SERVICE_NAMES = ['email-service','document-cognition','agent-harness-service',+ 'preview-gateway',];for (const service_name of SERVICE_NAMES) {diff --git a/infra/stacks/preview-gateway/Pulumi.yaml b/infra/stacks/preview-gateway/Pulumi.yamlnew file mode 100644index 0000000000..2cfef7ace2--- /dev/null+++ b/infra/stacks/preview-gateway/Pulumi.yaml@@ -0,0 +1,3 @@+name: preview-gateway+runtime: nodejs+description: Entity-authorized HTTP/WebSocket previews over reverse SSHdiff --git a/infra/stacks/preview-gateway/index.ts b/infra/stacks/preview-gateway/index.tsnew file mode 100644index 0000000000..a650a08a47--- /dev/null+++ b/infra/stacks/preview-gateway/index.ts@@ -0,0 +1,328 @@+import * as aws from '@pulumi/aws';+import * as awsx from '@pulumi/awsx';+import * as pulumi from '@pulumi/pulumi';+import * as dopplerProvider from '@pulumiverse/doppler';+import { ServiceTargetGroup } from '../../packages/resources';+import { EcrImage } from '../../packages/service';+import {+ config,+ DopplerEcsEnvironment,+ getGatewayAlb,+ getMacroApiToken,+ GatewayService,+ stack,+} from '../../packages/shared';+import { get_coparse_api_vpc } from '../../packages/vpc';++const name = 'preview-gateway';+const tags = {+ environment: stack,+ env: stack,+ project: name,+ service: name,+ tech_lead: 'wolf',+};+const vpc = get_coparse_api_vpc();+const gateway = getGatewayAlb();+// A separate registrable domain is mandatory: previews execute agent-authored JavaScript.+const domain = config.require('preview_domain');+if (+ domain === 'macro.com' ||+ domain.endsWith('.macro.com') ||+ !/^[a-z0-9.-]+$/.test(domain)+) {+ throw new Error(+ 'preview_domain must be an isolated DNS name outside macro.com'+ );+}+const zoneId = config.require('preview_zone_id');+const sshHost = `ssh.${domain}`;+const certificate = new aws.acm.Certificate(`${name}-${stack}`, {+ domainName: `*.${domain}`,+ validationMethod: 'DNS',+ tags,+});+const validation = certificate.domainValidationOptions.apply((options) =>+ options.map(+ (option, i) =>+ new aws.route53.Record(`${name}-validation-${i}-${stack}`, {+ zoneId,+ name: option.resourceRecordName,+ type: option.resourceRecordType,+ records: [option.resourceRecordValue],+ ttl: 60,+ })+ )+);+const validated = new aws.acm.CertificateValidation(`${name}-${stack}`, {+ certificateArn: certificate.arn,+ validationRecordFqdns: validation.apply((records) =>+ records.map((record) => record.fqdn)+ ),+});+const albSg = new aws.ec2.SecurityGroup(`${name}-http-${stack}`, {+ vpcId: vpc.vpcId,+ tags,+ ingress: [+ { protocol: 'tcp', fromPort: 443, toPort: 443, cidrBlocks: ['0.0.0.0/0'] },+ ],+ egress: [+ {+ protocol: 'tcp',+ fromPort: 8110,+ toPort: 8111,+ cidrBlocks: ['0.0.0.0/0'],+ },+ ],+});+const sshSg = new aws.ec2.SecurityGroup(`${name}-ssh-${stack}`, {+ vpcId: vpc.vpcId,+ tags,+ ingress: [+ { protocol: 'tcp', fromPort: 22, toPort: 22, cidrBlocks: ['0.0.0.0/0'] },+ ],+ egress: [2222, 8110].map((port) => ({+ protocol: 'tcp',+ fromPort: port,+ toPort: port,+ cidrBlocks: ['0.0.0.0/0'],+ })),+});+const taskSg = new aws.ec2.SecurityGroup(`${name}-task-${stack}`, {+ vpcId: vpc.vpcId,+ tags,+});+for (const [index, rule] of [+ { fromPort: 8110, toPort: 8111, source: albSg.id },+ { fromPort: 2222, toPort: 2222, source: sshSg.id },+ { fromPort: 8110, toPort: 8110, source: sshSg.id },+].entries()) {+ new aws.vpc.SecurityGroupIngressRule(+ `${name}-task-ingress-${index}-${stack}`,+ {+ securityGroupId: taskSg.id,+ ipProtocol: 'tcp',+ fromPort: rule.fromPort,+ toPort: rule.toPort,+ referencedSecurityGroupId: rule.source,+ }+ );+}+new aws.vpc.SecurityGroupEgressRule(`${name}-task-egress-${stack}`, {+ securityGroupId: taskSg.id,+ ipProtocol: '-1',+ cidrIpv4: '0.0.0.0/0',+});++const control = new ServiceTargetGroup(`${name}-${stack}`, {+ tags,+ listenerArn: gateway.httpsListenerArn,+ vpcId: vpc.vpcId,+ containerPort: 8110,+ service: GatewayService.PREVIEW_GATEWAY,+ healthCheckPath: '/health',+ pathPatterns: ['/preview', '/preview/*'],+ serviceSecurityGroupId: taskSg.id,+ albSecurityGroupId: gateway.albSecurityGroupId,+});+const httpAlb = new aws.lb.LoadBalancer(`${name}-http-${stack}`, {+ loadBalancerType: 'application',+ subnets: vpc.publicSubnetIds,+ securityGroups: [albSg.id],+ idleTimeout: 3600,+ dropInvalidHeaderFields: true,+ tags,+});+const httpTarget = new aws.lb.TargetGroup(`${name}-http-${stack}`, {+ port: 8111,+ protocol: 'HTTP',+ targetType: 'ip',+ vpcId: vpc.vpcId,+ deregistrationDelay: 0,+ healthCheck: { protocol: 'HTTP', port: '8110', path: '/health' },+ tags,+});+const httpListener = new aws.lb.Listener(`${name}-https-${stack}`, {+ loadBalancerArn: httpAlb.arn,+ port: 443,+ protocol: 'HTTPS',+ certificateArn: validated.certificateArn,+ sslPolicy: 'ELBSecurityPolicy-TLS13-1-2-2021-06',+ defaultActions: [{ type: 'forward', targetGroupArn: httpTarget.arn }],+ tags,+});+const sshNlb = new aws.lb.LoadBalancer(`${name}-ssh-${stack}`, {+ loadBalancerType: 'network',+ subnets: vpc.publicSubnetIds,+ securityGroups: [sshSg.id],+ enableCrossZoneLoadBalancing: true,+ tags,+});+const sshTarget = new aws.lb.TargetGroup(`${name}-ssh-${stack}`, {+ port: 2222,+ protocol: 'TCP',+ targetType: 'ip',+ vpcId: vpc.vpcId,+ deregistrationDelay: 0,+ healthCheck: { protocol: 'HTTP', port: '8110', path: '/health' },+ tags,+});+const sshListener = new aws.lb.Listener(`${name}-ssh-${stack}`, {+ loadBalancerArn: sshNlb.arn,+ port: 22,+ protocol: 'TCP',+ defaultActions: [{ type: 'forward', targetGroupArn: sshTarget.arn }],+});+new aws.route53.Record(`${name}-wildcard-${stack}`, {+ zoneId,+ name: `*.${domain}`,+ type: 'A',+ aliases: [+ {+ name: httpAlb.dnsName,+ zoneId: httpAlb.zoneId,+ evaluateTargetHealth: true,+ },+ ],+});+new aws.route53.Record(`${name}-ssh-${stack}`, {+ zoneId,+ name: sshHost,+ type: 'A',+ aliases: [+ { name: sshNlb.dnsName, zoneId: sshNlb.zoneId, evaluateTargetHealth: true },+ ],+});+const image = new EcrImage(`${name}-${stack}`, {+ repositoryId: `${name}-ecr-${stack}`,+ repositoryName: `${name}-${stack}`,+ imageId: `${name}-image-${stack}`,+ imagePath: '../../..',+ dockerfile: 'docker/Dockerfile',+ platform: { family: 'linux', architecture: 'amd64' },+ buildArgs: { SERVICE_NAME: 'preview_gateway' },+ tags,+});+// MacroConfig reads APP_SECRETS_JSON as a complete configuration. Keep deployment+// addresses in Doppler, which syncs that JSON into Secrets Manager for ECS.+const deploymentConfig = {+ PORT: '8110',+ ENVIRONMENT: stack,+ PREVIEW_DOMAIN: domain,+ PREVIEW_SSH_HOST: sshHost,+ // Local stacks reach their SSH listener through a Cloudflare quick tunnel;+ // a deployed gateway is dialled directly and rejects a proxy host outright.+ // Present-but-empty because MacroConfig does not merge missing JSON keys.+ PREVIEW_SSH_PROXY_HOST: '',+ PREVIEW_APP_ORIGIN:+ stack === 'prod' ? 'https://macro.com' : 'https://dev.macro.com',+ PREVIEW_CONTROL_HOSTS:+ stack === 'prod' ? 'gateway.macro.com' : 'dev-gateway.macro.com',+};+const configSecrets = Object.entries(deploymentConfig).map(+ ([key, value]) =>+ new dopplerProvider.Secret(`${name}-${key}-${stack}`, {+ project: name,+ config: stack === 'prod' ? 'prd' : 'dev',+ name: key,+ value,+ })+);+const doppler = new DopplerEcsEnvironment(name, { tags });+const role = new aws.iam.Role(`${name}-${stack}`, {+ assumeRolePolicy: aws.iam.assumeRolePolicyForPrincipal({+ Service: 'ecs-tasks.amazonaws.com',+ }),+ tags,+});+const fusionKey = aws.secretsmanager.getSecretVersionOutput({+ secretId: `fusionauth-jwt-secret-${stack}`,+});+new aws.iam.RolePolicy(`${name}-auth-${stack}`, {+ role: role.id,+ policy: pulumi.jsonStringify({+ Version: '2012-10-17',+ Statement: [+ {+ Effect: 'Allow',+ Action: ['secretsmanager:GetSecretValue'],+ Resource: [fusionKey.arn, getMacroApiToken().macroApiTokenPublicKeyArn],+ },+ ],+ }),+});+const cluster = new pulumi.StackReference(`${name}-cluster`, {+ name: `macro-inc/document-storage/${stack}`,+});+const logs = new aws.cloudwatch.LogGroup(`${name}-${stack}`, {+ retentionInDays: 14,+ tags,+});+const service = new awsx.ecs.FargateService(+ `${name}-${stack}`,+ {+ cluster: cluster.requireOutput(+ 'cloudStorageClusterArn'+ ) as pulumi.Output<string>,+ networkConfiguration: {+ subnets: vpc.privateSubnetIds,+ securityGroups: [taskSg.id],+ },+ // SSH and HTTP must reach the same registry. Do not autoscale or overlap deployments.+ desiredCount: 1,+ deploymentMinimumHealthyPercent: 0,+ deploymentMaximumPercent: 100,+ deploymentCircuitBreaker: { enable: true, rollback: true },+ healthCheckGracePeriodSeconds: 120,+ loadBalancers: [control.target_group, httpTarget, sshTarget].map(+ (target, i) => ({+ targetGroupArn: target.arn,+ containerName: 'service',+ containerPort: [8110, 8111, 2222][i],+ })+ ),+ taskDefinitionArgs: {+ taskRole: { roleArn: role.arn },+ executionRole: { roleArn: doppler.executionRole.arn },+ runtimePlatform: {+ operatingSystemFamily: 'LINUX',+ cpuArchitecture: 'X86_64',+ },+ containers: {+ service: {+ name: 'service',+ image: image.image.imageUri,+ cpu: 1024,+ memory: 2048,+ essential: true,+ stopTimeout: 30,+ secrets: doppler.containerSecrets,+ environment: [+ { name: 'PORT', value: '8110' },+ { name: 'ENVIRONMENT', value: stack },+ { name: 'DD_SERVICE', value: name },+ { name: 'DD_ENV', value: stack },+ ],+ logConfiguration: {+ logDriver: 'awslogs',+ options: {+ 'awslogs-group': logs.name,+ 'awslogs-region': aws.getRegionOutput().name,+ 'awslogs-stream-prefix': 'gateway',+ },+ },+ portMappings: [8110, 8111, 2222].map((port) => ({+ containerPort: port,+ hostPort: port,+ protocol: 'tcp',+ })),+ },+ },+ },+ tags,+ },+ { dependsOn: [httpListener, sshListener, ...configSecrets] }+);+export const previewDomain = domain;+export const previewSshHost = sshHost;+export const previewServiceArn = service.service.id;diff --git a/infra/stacks/preview-gateway/package.json b/infra/stacks/preview-gateway/package.jsonnew file mode 100644index 0000000000..5b5837bead--- /dev/null+++ b/infra/stacks/preview-gateway/package.json@@ -0,0 +1 @@+{"name":"preview-gateway-stack","version":"0.0.0","private":true}diff --git a/infra/stacks/preview-gateway/tsconfig.json b/infra/stacks/preview-gateway/tsconfig.jsonnew file mode 100644index 0000000000..0f6109bbac--- /dev/null+++ b/infra/stacks/preview-gateway/tsconfig.json@@ -0,0 +1 @@+{"extends":"../../tsconfig.json"}diff --git a/nix/cloud-storage.nix b/nix/cloud-storage.nixindex 7ce671abf9..b707f8b743 100644--- a/nix/cloud-storage.nix+++ b/nix/cloud-storage.nix@@ -340,6 +340,11 @@);deployServiceBinaryDefinitions = [+ {+ serviceName = "preview-gateway";+ packageName = "preview_gateway";+ binaries = [ "preview_gateway" ];+ }{serviceName = "agent-harness-service";packageName = "agent_harness_service";@@ -522,6 +527,7 @@);localStackDeployServiceNames = [+ "preview-gateway""agent-harness-service""agent-schedule-service""calendar-service"diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rsindex acae3709a4..3256f805ad 100644--- a/services/agent_harness_service/src/config.rs+++ b/services/agent_harness_service/src/config.rs@@ -156,6 +156,8 @@ pub struct Config {/// The egress router reads sandbox session tokens from `Authorization`.#[macro_config_default(8102)]pub egress_port: u16,+ /// Optional host-reachable egress origin for external runtimes in local stacks.+ pub external_egress_base_url: Option<String>,/// OAuth client ID for the Pipedream API.pub pipedream_client_id: PipedreamClientId,/// OAuth client secret for the Pipedream API.diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 377046c7ab..de5de4e569 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -402,19 +402,28 @@ async fn run() -> anyhow::Result<()> {// The egress proxy: one binary today, its own listener from the start.// Shared with the in-memory runtime, which calls it directly rather than// through that listener.- let egress = Arc::new(EgressServiceImpl::new(- StoredTokenSessionAuthority::new(PgAgentSessionRepo::new(pool.clone())),- mcp_credentials,- GithubAppTokens::new(InstallationTokenService::new(- InstallationTokenConfig {- client_id: config.github_sync_app_client_id.clone(),- private_key_pem: config.github_sync_app_pem_secret_key.as_ref().to_owned(),- },- PgGithubSyncRepo::new(pool.clone()),- GithubSyncClientImpl::default(),- )),- ReqwestForwarder::new()?,- ));+ let egress = Arc::new(+ EgressServiceImpl::new(+ StoredTokenSessionAuthority::new(PgAgentSessionRepo::new(pool.clone())),+ mcp_credentials,+ GithubAppTokens::new(InstallationTokenService::new(+ InstallationTokenConfig {+ client_id: config.github_sync_app_client_id.clone(),+ private_key_pem: config.github_sync_app_pem_secret_key.as_ref().to_owned(),+ },+ PgGithubSyncRepo::new(pool.clone()),+ GithubSyncClientImpl::default(),+ )),+ ReqwestForwarder::new()?,+ )+ .with_preview_mcp(+ url::Url::parse(&format!(+ "{}/mcp",+ macro_service_urls::PreviewGatewayUrl::new()?+ ))?,+ matches!(config.environment, Environment::Local),+ )?,+ );// The proxy's public address, read once: the provisioner builds the// advertised server URLs from it and the in-memory client reads them back@@ -874,7 +883,8 @@ async fn run() -> anyhow::Result<()> {),prompt_context,prompt_composer,- EgressProvisioner::new(Arc::clone(&mcp_connections), egress_base_url),+ EgressProvisioner::new(Arc::clone(&mcp_connections), egress_base_url)+ .with_external_base_url(config.external_egress_base_url.clone()),RedisCommandForwarder::new(redis.clone()),PgPermissionPolicySource::new(PgBotsRepo::new(pool.clone())),PgCodingAgentSource::new(PgBotsRepo::new(pool.clone())),diff --git a/services/preview_gateway/Cargo.toml b/services/preview_gateway/Cargo.tomlnew file mode 100644index 0000000000..fcefb603e0--- /dev/null+++ b/services/preview_gateway/Cargo.toml@@ -0,0 +1,46 @@+[package]+name = "preview_gateway"+version = "0.1.0"+edition = "2024"+publish = false++[[bin]]+name = "preview_gateway_doppler_config"+path = "src/doppler_config.rs"++[dependencies]+doppler-config = { workspace = true }+agent_preview = { path = "../../crates/agent_preview" }+agent_egress = { path = "../../crates/agent_egress" }+agent_session = { path = "../../crates/agent_session" }+async-trait = { workspace = true }+axum = { workspace = true }+aws-sdk-secretsmanager = { workspace = true }+connection_gateway_client = { path = "../../crates/connection_gateway_client" }+database_env_vars = { path = "../../crates/database_env_vars" }+entity_access = { path = "../../crates/entity_access" }+macro_auth = { path = "../../crates/macro_auth" }+macro_authorization = { path = "../../crates/macro_authorization", default-features = false, features = ["axum", "outbound", "postgres"] }+macro_aws_config = { path = "../../crates/macro_aws_config" }+macro_config = { path = "../../crates/macro_config" }+macro_cors = { path = "../../crates/macro_cors" }+macro_entrypoint = { path = "../../crates/macro_entrypoint" }+macro_env = { path = "../../crates/macro_env" }+macro_env_var = { path = "../../crates/macro_env_var" }+macro_service_urls = { path = "../../crates/macro_service_urls" }+macro_user_id = { path = "../../crates/macro_user_id" }+macro_uuid = { path = "../../crates/macro_uuid" }+model-entity = { path = "../../crates/model-entity" }+rootcause = { workspace = true }+anyhow = { workspace = true }+secretsmanager_client = { path = "../../crates/secretsmanager_client" }+serde = { workspace = true }+serde_json = { workspace = true }+sqlx = { workspace = true }+tokio-util = { workspace = true }+tokio = { workspace = true, features = ["signal"] }+tracing = { workspace = true }+workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }++[dev-dependencies]+agent_session = { path = "../../crates/agent_session", features = ["test-utils"] }diff --git a/services/preview_gateway/README.md b/services/preview_gateway/README.mdnew file mode 100644index 0000000000..cc70eac673--- /dev/null+++ b/services/preview_gateway/README.md@@ -0,0 +1,172 @@+# Agent previews++`preview_gateway` shares a development server from a coding agent using stock+OpenSSH. Cursor receives the internal `macro-preview` MCP server through its+existing egress connection. External ACP runtimes (including macrod) receive a+session-scoped MCP endpoint during attachment, using the existing egress credential. An agent calls+`SharePreview({"port":3000})`, executes the returned shell script within two+minutes, and continues editing. HTTP and WebSocket traffic use the same SSH+connection, so HMR works without rebuilding or publishing the app.++The script uses a single-use token as the SSH username, `auth_none`, and a pinned+ed25519 server host key. It does not generate or install a client key or disable+host verification, and installs no helper — except on a local stack's quick-tunnel+endpoint, which needs `cloudflared` as a `ProxyCommand` (see below). The remote forward is a logical+`127.0.0.1:1` registration; the gateway opens `forwarded-tcpip` channels directly.+There is no public TCP listener or allocated port per preview, shell access, or+arbitrary direct forwarding.++## Browser access++Each lease has a random `https://<id>.<preview-domain>/` origin. The ID routes+requests; knowing it does not grant access. Anyone with View access to the agent+session can click **View preview**. The control API uses standard Macro+authentication and entity access receipts to issue a 30-second, one-use ticket.+The browser POSTs it to `/.macro-preview/auth` in a new tab, receives a host-only+Secure HttpOnly cookie, and redirects to `/`. App paths and query strings stay+unchanged. Stop requires Edit access; the UI currently exposes it to the owner.++Entity access is checked again when the ticket is redeemed, on every request,+and every 30 seconds during open HTTP streams and WebSockets. Stop and SSH+disconnection cancel open traffic immediately. Session deletion is checked by+the sweeper every 15 seconds. An idle ACP transport disconnect does not terminate+an otherwise live preview. MCP calls use the existing session credential and its normal lifecycle; external+runtime attachment rotates it. It is never replaced with an owner API token.++New Cursor agents receive this MCP server at creation. Existing Cursor agents+keep their original tool configuration and need a new session. Codex CLI and+Claude CLI can use it through an ACP runtime such as macrod. Hosted Codex Cloud+currently rejects MCP servers in its provider adapter and is not supported.+Claude Cloud receives MCP tools but restricted environments must separately+permit outbound SSH to the configured preview host; that provider networking+path is not verified by this change.++The preview domain **must be separate from macro.com** because Macro's browser+cookies cover its subdomains. The gateway rejects Macro's domain, validates+handoff origins, checks application request origins, strips its credential from+upstream requests, and strips Domain attributes from app cookies. It rewrites+Host and same-origin Origin to `localhost:<port>`, while supplying the original+host and HTTPS scheme in forwarded headers. It does not change HTML or inject+framework-specific code. Apps that hardcode browser-facing localhost URLs must+configure their public origin or use relative URLs. Only HTTP backends are+supported; TLS terminates at the public load balancer.++The gateway sends `agent_session_preview` invalidations through the existing+connection gateway. The session banner also fetches state on mount, reconnect,+and every 30 seconds, so missed events and gateway restarts recover automatically.++## Limits++- One preview per session, five active previews per owner, one creation per owner+ every ten seconds; 1,000 retained leases/accounts per gateway.+- One-hour leases; 15 minutes without a browser HTTP request expires a lease.+ WebSocket pings alone do not keep it alive.+- Traffic itself is unmetered. Request-rate, byte-pacing and total-byte ceilings+ were all tried and all severed live previews: a dev server's cold load is+ thousands of modules and tens of MB, and a per-owner byte total that outlived+ lease replacement accumulated across reloads until every stream was cut.+ Expiry, idle timeout and one-preview-per-session are the controls that bound+ cost.+- Per preview: 512 concurrent HTTP streams and eight WebSockets; 16 MiB request+ bodies, 30-second upstream response-header timeout. Traffic is streamed.+- 1,024 SSH connections, bounded SSH authentication time, 128 concurrent control+ requests, 64 KiB control bodies, 15-second control timeout. Tickets and browser+ credentials also have bounded registries and expiry.++These are basic abuse/cost controls, not a hard cloud-spend ceiling. Load+balancer traffic is still billable before application admission, and nothing+here bounds bytes. Gateway restart closes previews and clears all credentials;+agents must share again.++## Deployment++The `infra/stacks/preview-gateway` Pulumi stack creates wildcard DNS and an ACM+certificate, a public HTTPS ALB, a public SSH NLB, and a Fargate task. Macro's+existing gateway routes `/preview/*` to its separate control listener. The task+runs **one replica**, with non-overlapping replacements and no autoscaling:+SSH, HTTP, and control requests must reach the same in-memory registry. Scaling+requires explicit ownership/routing across gateways first.++Before first deployment:++The service has a `bootstrap_pending` reason in `.github/services-config.json`+until these prerequisites are ready. CI still builds, lints, and tests its Rust+and TypeScript, but explicitly defers live Doppler validation and Pulumi preview;+automatic deployment excludes it and the manual service deployment workflow+rejects it. Direct Pulumi commands remain available for bootstrap. Other services'+checks remain strict, including failures caused by missing configuration.++1. Initialize `macro-inc/preview-gateway/dev` and `macro-inc/preview-gateway/prod`+ Pulumi stacks. Choose a separate preview domain and its Route 53 zone. Set Pulumi+ `preview_domain` and `preview_zone_id` for the dev or prod stack. Dev and prod+ should use distinct DNS suffixes.+2. Deploy the Doppler projects stack to create `preview-gateway` and its secret+ sync. In its `dev` / `prd` config, set `DATABASE_URL` and `INTERNAL_API_KEY`+ using the existing service secret references. Generate a persistent ed25519+ key with `ssh-keygen -t ed25519 -N '' -f <private-temporary-path>` and store+ its private PEM as `PREVIEW_SSH_HOST_KEY` in Doppler. Do not commit the key.+3. The preview stack manages `PORT`, `ENVIRONMENT`, `PREVIEW_DOMAIN`,+ `PREVIEW_SSH_HOST`, `PREVIEW_APP_ORIGIN`, and `PREVIEW_CONTROL_HOSTS` in Doppler.+ They must be present in the synced `APP_SECRETS_JSON` before a task can become+ healthy. MacroConfig does not merge missing JSON keys from ECS environment+ variables. Run `preview_gateway_doppler_config` to validate service config.+4. Remove `bootstrap_pending` from the service inventory and open a PR. This+ inventory-only change triggers live Doppler validation and Pulumi previews+ before enabling the normal deployment pipeline; do not remove it before dev+ and prod configuration are ready. Deploy gateway, harness, and web changes.+ Confirm `/preview/health`, call SharePreview,+ execute the script, and verify a page edit over HMR and Stop sharing.++A domain, DNS zone, and production secrets are deployment prerequisites, not+embedded defaults. Rotating the host key invalidates previously issued scripts;+new tool calls pin the new public key.++## Local stack and verification++`just stack` includes the gateway in the local service inventory and cached Nix+binaries. It generates a persistent key in the instance artifact directory and+publishes control port 8110, SSH port 2222, and preview HTTPS port 8443 (named+instances derive their own ports). Caddy serves `*.preview.localhost` using its+internal CA; trust that instance's Caddy CA for browser use. Its data is stored in+`preview-caddy-data` beside the generated Caddyfile. The root certificate is+`preview-caddy-data/caddy/pki/authorities/local/root.crt`; import it into the+host/browser trust store (container trust does not configure the host). The generated script tries+host loopback first, then the pinned Docker `preview-gateway:2222` endpoint, and+— with `--with-cf-tunnel` — a Cloudflare quick tunnel last.+External host runtimes receive `EXTERNAL_EGRESS_BASE_URL` (the instance's+localhost egress port, or its public egress tunnel when enabled); Docker agents+keep their Docker-network endpoint and the same session credential.+An agent that runs neither on this machine nor in the compose network — a+`@cursor` session on cursor.com — can reach neither of those endpoints. Running+`just run_local --with-cf-tunnel` publishes a third one: a quick tunnel whose+origin is `tcp://localhost:<preview ssh port>`, minted per run and written to+`PREVIEW_SSH_PROXY_HOST`. Cloudflare's edge proxies HTTP ports only, so the+script reaches it through `cloudflared access ssh --hostname <host>` as an+OpenSSH `ProxyCommand`, fetching `cloudflared` first when the agent's image+lacks it. That is the one endpoint that is not pure stock OpenSSH; it still+installs no client key, and the pinned host key, one-use token and every quota+apply unchanged. The hostname itself grants nothing: it only reaches the SSH+listener, which accepts a single unexpired token.++Without the flag, `PREVIEW_SSH_PROXY_HOST` is empty and previews stay reachable+from this machine and the compose network only. A deployed gateway rejects the+setting outright — it is dialled directly, and must never depend on someone's+laptop tunnel.++For the repo frontend, `.cursor/frontend.sh` routes API and WebSocket calls+through the same Vite origin, and Vite derives its HMR address from the browser.+The tunnel itself remains framework-independent.++Run from the repository root, leaving `SQLX_OFFLINE` unset:++```sh+cargo test -p agent_preview+cargo test -p preview_gateway+cargo test -p agent_egress+cargo test -p agent_harness+cargo test -p xtask_local+```++The preview tests use a real OpenSSH client against the russh server, exercise+HTTP and WebSocket forwarding and cancellation, and test ticket replay, host+binding, permission revocation, origin checks, and shared quotas.diff --git a/services/preview_gateway/src/adapters.rs b/services/preview_gateway/src/adapters.rsnew file mode 100644index 0000000000..60f4bc51c7--- /dev/null+++ b/services/preview_gateway/src/adapters.rs@@ -0,0 +1,102 @@+//! Composition-root adapters to existing Macro session, permission and realtime services.+use agent_egress::domain::model::SessionToken;+use agent_preview::domain::{+ AgentIdentity, Preview, PreviewError,+ ports::{Authority, Events},+};+use agent_session::domain::{+ model::{AgentSession, AgentSessionId},+ ports::AgentSessionRepo,+};+use async_trait::async_trait;+use entity_access::domain::{+ models::{EntityType, ViewAccessLevel},+ ports::EntityAccessService,+};+use macro_user_id::user_id::MacroUserIdStr;+use std::sync::Arc;++pub struct MacroAuthority<Repo, Access> {+ pub sessions: Repo,+ pub access: Arc<Access>,+}+impl<Repo: AgentSessionRepo, Access> MacroAuthority<Repo, Access> {+ async fn session(&self, session: AgentSessionId) -> Result<AgentSession, PreviewError> {+ self.sessions+ .get(session)+ .await+ .map_err(|_| PreviewError::Denied)+ }+}+#[async_trait]+impl<Repo: AgentSessionRepo, Access: EntityAccessService> Authority+ for MacroAuthority<Repo, Access>+{+ async fn agent(&self, token: &str) -> Result<AgentIdentity, PreviewError> {+ let token = SessionToken::new(token);+ let session =+ agent_session::domain::credentials::authenticate_session(&self.sessions, &token.hash())+ .await+ .map_err(|_| PreviewError::Denied)?;+ Ok(AgentIdentity {+ session: session.id,+ // Previews are charged to whoever the session acts as, so a+ // non-user owner is refused rather than quietly given a quota.+ owner: session+ .owner_user()+ .map_err(|_| PreviewError::Denied)?+ .clone(),+ })+ }+ async fn viewer(+ &self,+ session: AgentSessionId,+ user: &MacroUserIdStr<'_>,+ ) -> Result<(), PreviewError> {+ self.access+ .generate_entity_access_receipt::<ViewAccessLevel>(+ user,+ None,+ &session.to_string(),+ EntityType::AgentSession,+ )+ .await+ .map_err(|_| PreviewError::Denied)?;+ self.active(session).await+ }+ async fn active(&self, session: AgentSessionId) -> Result<(), PreviewError> {+ // Runtime disconnection is transient (Cursor deliberately detaches idle ACP pipes).+ // Deletion revokes the capability; explicit preview stop and SSH closure end the lease.+ self.session(session).await.map(|_| ())+ }+}++pub struct Realtime(pub connection_gateway_client::ConnectionGatewayClient);+#[async_trait]+impl Events for Realtime {+ async fn changed(+ &self,+ preview: &Preview,+ viewers: &[MacroUserIdStr<'static>],+ ) -> Result<(), PreviewError> {+ if viewers.is_empty() {+ return Ok(());+ }+ // Invalidation rather than a snapshot: a reconnect/read cannot overwrite newer state.+ self.0+ .batch_send_message(+ "agent_session_preview".into(),+ serde_json::json!({"agentSessionId": preview.agent_session_id}),+ viewers+ .iter()+ .map(|user| model_entity::EntityType::User.with_entity_str(user.as_ref()))+ .collect(),+ )+ .await+ .map(|_| ())+ .map_err(|_| PreviewError::Unavailable)+ }+}++#[cfg(test)]+mod test;diff --git a/services/preview_gateway/src/adapters/test.rs b/services/preview_gateway/src/adapters/test.rsnew file mode 100644index 0000000000..ab48521444--- /dev/null+++ b/services/preview_gateway/src/adapters/test.rs@@ -0,0 +1,39 @@+use super::*;+use agent_session::{+ domain::model::SessionStatus,+ testing::{InMemoryAgentSessionRepo, test_agent_session},+};++#[tokio::test]+async fn direct_mcp_credentials_follow_revocation_while_established_previews_survive_detach() {+ let repo = InMemoryAgentSessionRepo::new();+ let id = AgentSessionId::new();+ let mut session = test_agent_session(id);+ repo.insert_session(session.clone());+ let token = SessionToken::new("test-session-token");+ repo.set_egress_token_hash(id, &token.hash()).await.unwrap();+ // This test only exercises session authentication, so no access DB connection is opened.+ let pool = sqlx::postgres::PgPoolOptions::new()+ .connect_lazy("postgres://localhost/unused")+ .unwrap();+ let authority = MacroAuthority {+ sessions: repo.clone(),+ access: Arc::new(+ entity_access::domain::service::EntityAccessServiceImpl::new(+ entity_access::outbound::PgAccessRepository::new(pool),+ ),+ ),+ };+ assert!(authority.agent(token.as_str()).await.is_ok());+ session.status = SessionStatus::Disconnected;+ repo.insert_session(session);+ assert!(matches!(+ authority.agent(token.as_str()).await,+ Err(PreviewError::Denied)+ ));+ assert!(authority.active(id).await.is_ok());+ assert!(matches!(+ authority.agent("unknown").await,+ Err(PreviewError::Denied)+ ));+}diff --git a/services/preview_gateway/src/config.rs b/services/preview_gateway/src/config.rsnew file mode 100644index 0000000000..66b07e3a7a--- /dev/null+++ b/services/preview_gateway/src/config.rs@@ -0,0 +1,33 @@+//! Typed deployment configuration, loaded through macro_env_var by MacroConfig.+use database_env_vars::DatabaseUrl;+use macro_env::Environment;++#[derive(macro_config::MacroConfig)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub struct Config {+ #[macro_config_default(Environment::new_or_prod())]+ pub environment: Environment,+ pub database_url: DatabaseUrl,+ pub internal_api_key: String,+ /// Persistent OpenSSH ed25519 server private key (Doppler secret).+ pub preview_ssh_host_key: String,+ pub preview_domain: String,+ pub preview_ssh_host: String,+ /// Local stacks only: Cloudflare quick-tunnel hostname fronting the SSH listener,+ /// so an agent running off this machine can still reach it.+ pub preview_ssh_proxy_host: Option<String>,+ #[macro_config_default(22)]+ pub preview_ssh_public_port: u16,+ #[macro_config_default(443)]+ pub preview_https_port: u16,+ /// Exact origin allowed to submit the browser authentication form.+ pub preview_app_origin: String,+ /// Comma separated DNS hostnames accepted on the internal MCP listener.+ pub preview_control_hosts: String,+ #[macro_config_default(8110)]+ pub port: u16,+ #[macro_config_default(8111)]+ pub preview_http_port: u16,+ #[macro_config_default(2222)]+ pub preview_ssh_port: u16,+}diff --git a/services/preview_gateway/src/doppler_config.rs b/services/preview_gateway/src/doppler_config.rsnew file mode 100644index 0000000000..64014bf97a--- /dev/null+++ b/services/preview_gateway/src/doppler_config.rs@@ -0,0 +1,16 @@+//! Verify the Doppler-sourced service configuration in dev and production.+#[allow(dead_code)]+mod config;+#[tokio::main]+async fn main() -> anyhow::Result<()> {+ for environment in ["dev", "prd"] {+ doppler_config::DopplerConfig::builder()+ .token_from_env("DOPPLER_TOKEN")+ .config(environment)+ .project("preview-gateway")+ .build()?+ .load::<config::Config>()+ .await?;+ }+ Ok(())+}diff --git a/services/preview_gateway/src/main.rs b/services/preview_gateway/src/main.rsnew file mode 100644index 0000000000..84883a837d--- /dev/null+++ b/services/preview_gateway/src/main.rs@@ -0,0 +1,181 @@+//! Single-replica SSH/HTTP preview gateway, isolated from Macro's browser cookie domain.+mod adapters;+mod config;+use agent_preview::{+ domain::{PreviewService, Settings},+ inbound::{+ control::{self, ControlState},+ http, ssh, toolset,+ },+ outbound::ssh_tunnel::SshTunnel,+};+use axum::{Router, routing::get};+use axum::{+ body::Body,+ extract::{Request, State},+ http::StatusCode,+ middleware::{self, Next},+ response::{IntoResponse, Response},+};+use config::Config;+use macro_authorization::{+ InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationServiceImpl,+ MacroAuthorizationState, PgBotAuthorizationRepo, PgBotAuthorizer,+ PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,+};+use macro_service_urls::ConnectionGatewayUrl;+use std::{sync::Arc, time::Duration};+use tokio::net::TcpListener;++#[tokio::main]+async fn main() -> Result<(), rootcause::Report> {+ let entrypoint = macro_entrypoint::MacroEntrypoint::default()+ .suppress_dependency_logs(&["russh", "russh_util", "rmcp"])+ .init();+ let result = run().await;+ entrypoint.shutdown();+ result+}+async fn run() -> Result<(), rootcause::Report> {+ let config = macro_config::ConfigLoader::load::<Config>()?;+ let aws = macro_aws_config::get_macro_aws_config().await;+ let secrets =+ secretsmanager_client::SecretsManager::new(aws_sdk_secretsmanager::Client::new(&aws));+ let pool = sqlx::postgres::PgPoolOptions::new()+ .max_connections(10)+ .connect(config.database_url.as_ref())+ .await?;+ let access = Arc::new(+ entity_access::domain::service::EntityAccessServiceImpl::new(+ entity_access::outbound::PgAccessRepository::new(pool.clone()),+ ),+ );+ let auth = MacroAuthorizationServiceImpl::new(+ MacroAuthJwtValidator::new(+ macro_auth::middleware::decode_jwt::JwtValidationArgs::new_with_secret_manager(+ config.environment,+ &secrets,+ )+ .await?,+ ),+ InternalAuthConfig {+ api_key: config.internal_api_key.clone(),+ default_user_id: None,+ },+ PgBotAuthorizer::new(PgBotAuthorizationRepo::new(pool.clone())),+ PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(pool.clone())),+ );+ let key = ssh::host_key(&config.preview_ssh_host_key)?;+ let public_key = ssh::public_key(&key)?;+ let service = PreviewService::new(+ Settings {+ local_ssh_fallback: matches!(config.environment, macro_env::Environment::Local),+ domain: config.preview_domain,+ https_port: config.preview_https_port,+ ssh_host: config.preview_ssh_host,+ ssh_port: config.preview_ssh_public_port,+ ssh_proxy_host: config+ .preview_ssh_proxy_host+ .filter(|host| !host.is_empty()),+ host_key: public_key,+ app_origin: config.preview_app_origin,+ },+ Arc::new(adapters::MacroAuthority {+ sessions: agent_session::outbound::postgres::PgAgentSessionRepo::new(pool),+ access: access.clone(),+ }),+ Arc::new(adapters::Realtime(+ connection_gateway_client::ConnectionGatewayClient::new(+ config.internal_api_key,+ ConnectionGatewayUrl::new()?.to_string(),+ ),+ )),+ )?;+ let control = control::router(ControlState::new(+ service.clone(),+ access,+ MacroAuthorizationState::new(Arc::new(auth)),+ ));+ let mcp = toolset::router(+ service.clone(),+ config+ .preview_control_hosts+ .split(',')+ .map(|s| s.trim().to_owned())+ .collect(),+ );+ let app = control+ .merge(mcp)+ .route("/health", get(|| async { "ok" }))+ .layer(macro_cors::cors_layer());+ let app = Router::new()+ .merge(app.clone())+ .nest("/preview", app)+ .layer(middleware::from_fn_with_state(+ Arc::new(tokio::sync::Semaphore::new(128)),+ admit_control,+ ));+ let control_listener = TcpListener::bind(("0.0.0.0", config.port)).await?;+ let public_listener = TcpListener::bind(("0.0.0.0", config.preview_http_port)).await?;+ let ssh_listener = TcpListener::bind(("0.0.0.0", config.preview_ssh_port)).await?;+ let shutdown = tokio_util::sync::CancellationToken::new();+ let signal = shutdown.clone();+ tokio::spawn(async move {+ macro_entrypoint::shutdown_signal().await;+ signal.cancel();+ });+ let sweeper = service.clone();+ let sweep_shutdown = shutdown.clone();+ tokio::spawn(async move {+ loop {+ tokio::select! { _ = sweep_shutdown.cancelled() => break, _ = tokio::time::sleep(Duration::from_secs(15)) => sweeper.sweep().await }+ }+ });+ tokio::try_join!(+ async {+ axum::serve(control_listener, app)+ .with_graceful_shutdown(shutdown.clone().cancelled_owned())+ .await+ .map_err(rootcause::Report::from)+ },+ async {+ axum::serve(public_listener, http::router(service.clone()))+ .with_graceful_shutdown(shutdown.clone().cancelled_owned())+ .await+ .map_err(rootcause::Report::from)+ },+ async {+ ssh::serve(+ ssh_listener,+ key,+ service.clone(),+ Arc::new(|handle| Arc::new(SshTunnel::new(handle))),+ shutdown.clone(),+ )+ .await+ },+ )?;+ Ok(())+}++// MCP is stateless JSON and control responses are small. Bound unauthenticated+// work before it can occupy the database pool or buffer arbitrary request bodies.+async fn admit_control(+ State(slots): State<Arc<tokio::sync::Semaphore>>,+ request: Request,+ next: Next,+) -> Response {+ let Ok(_permit) = slots.try_acquire_owned() else {+ return StatusCode::TOO_MANY_REQUESTS.into_response();+ };+ let work = async {+ let (parts, body) = request.into_parts();+ let Ok(body) = axum::body::to_bytes(body, 64 * 1024).await else {+ return StatusCode::PAYLOAD_TOO_LARGE.into_response();+ };+ next.run(Request::from_parts(parts, Body::from(body))).await+ };+ tokio::time::timeout(Duration::from_secs(15), work)+ .await+ .unwrap_or_else(|_| StatusCode::REQUEST_TIMEOUT.into_response())+}diff --git a/tooling/xtask/crates/xtask_doppler_bins/Cargo.toml b/tooling/xtask/crates/xtask_doppler_bins/Cargo.tomlindex aa8b57bdc2..c1adeec771 100644--- a/tooling/xtask/crates/xtask_doppler_bins/Cargo.toml+++ b/tooling/xtask/crates/xtask_doppler_bins/Cargo.toml@@ -12,4 +12,6 @@ path = "src/main.rs"[dependencies]anyhow = { workspace = true }guppy = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }xtask_graph = { path = "../xtask_graph" }diff --git a/tooling/xtask/crates/xtask_doppler_bins/src/main.rs b/tooling/xtask/crates/xtask_doppler_bins/src/main.rsindex e9b581e828..fb29835b6c 100644--- a/tooling/xtask/crates/xtask_doppler_bins/src/main.rs+++ b/tooling/xtask/crates/xtask_doppler_bins/src/main.rs@@ -10,20 +10,41 @@//! CI only needs to run it for a service when that service's config could have//! changed, i.e. when its `src/config.rs`, `src/doppler_config.rs`, or//! `Cargo.toml` changed.+//! Services explicitly awaiting bootstrap in `.github/services-config.json`+//! defer this live check. Changing the inventory revalidates every ready service,+//! so removing that marker cannot bypass its first config validation.//!//! Input is a newline-delimited file of paths relative to the repository root//! (typically `git diff --name-only ...`). Output is the affected bin names, one//! per line, sorted and deduplicated.-use std::collections::BTreeSet;+use std::collections::{BTreeMap, BTreeSet};use std::path::{Path, PathBuf};use anyhow::{Context, Result, bail};use guppy::graph::{BuildTargetId, PackageGraph};use xtask_graph::build_graph;+#[cfg(test)]+mod test;+/// Source path (relative to a crate root) of a service's doppler-config binary.const DOPPLER_CONFIG_SRC: &str = "src/doppler_config.rs";+const SERVICES_CONFIG: &str = ".github/services-config.json";++#[derive(serde::Deserialize)]+struct ServicesConfig {+ services: BTreeMap<String, ServiceConfig>,+}++#[derive(serde::Deserialize)]+struct ServiceConfig {+ bootstrap_pending: Option<String>,+ #[serde(default)]+ deploy_binaries: Vec<String>,+ #[serde(default)]+ deploy_lambdas: Vec<String>,+}fn main() -> Result<()> {let args: Vec<String> = std::env::args().skip(1).collect();@@ -38,9 +59,11 @@ fn main() -> Result<()> {}fn run(graph: &PackageGraph, changed_files_path: &Path) -> Result<()> {- let workspace = graph.workspace();- let ws_root = workspace.root();- let repo_root = ws_root;+ let repo_root = graph.workspace().root();+ let services: ServicesConfig = serde_json::from_slice(+ &std::fs::read(repo_root.join(SERVICES_CONFIG)).context("reading service inventory")?,+ )+ .context("parsing service inventory")?;let changed_files = std::fs::read_to_string(changed_files_path).with_context(|| {format!(@@ -54,6 +77,20 @@ fn run(graph: &PackageGraph, changed_files_path: &Path) -> Result<()> {.map(|line| repo_root.join(line).into_std_path_buf()).collect();+ for bin in config_bins(graph, &changed, &services)? {+ println!("{bin}");+ }+ Ok(())+}++fn config_bins(+ graph: &PackageGraph,+ changed: &BTreeSet<PathBuf>,+ services: &ServicesConfig,+) -> Result<BTreeSet<String>> {+ let workspace = graph.workspace();+ let inventory_changed =+ changed.contains(&workspace.root().join(SERVICES_CONFIG).into_std_path_buf());let mut bins = BTreeSet::new();for package in workspace.iter() {// Only services that actually ship a `src/doppler_config.rs` binary.@@ -69,6 +106,24 @@ fn run(graph: &PackageGraph, changed_files_path: &Path) -> Result<()> {continue;};+ if let Some((service, reason)) = services.services.iter().find_map(|(name, service)| {+ let reason = service.bootstrap_pending.as_ref()?;+ package+ .build_targets()+ .any(|target| match target.id() {+ BuildTargetId::Binary(name) => service+ .deploy_binaries+ .iter()+ .chain(&service.deploy_lambdas)+ .any(|binary| binary == name),+ _ => false,+ })+ .then_some((name, reason))+ }) {+ eprintln!("Deferring {service} live Doppler validation: {reason}");+ continue;+ }+let dir = package.manifest_path().parent()@@ -80,13 +135,10 @@ fn run(graph: &PackageGraph, changed_files_path: &Path) -> Result<()> {dir.join(DOPPLER_CONFIG_SRC).into_std_path_buf(),dir.join("Cargo.toml").into_std_path_buf(),];- if triggers.iter().any(|trigger| changed.contains(trigger)) {+ if inventory_changed || triggers.iter().any(|trigger| changed.contains(trigger)) {bins.insert(bin_name.to_owned());}}- for bin in bins {- println!("{bin}");- }- Ok(())+ Ok(bins)}diff --git a/tooling/xtask/crates/xtask_doppler_bins/src/test.rs b/tooling/xtask/crates/xtask_doppler_bins/src/test.rsnew file mode 100644index 0000000000..629abedc22--- /dev/null+++ b/tooling/xtask/crates/xtask_doppler_bins/src/test.rs@@ -0,0 +1,42 @@+use super::*;++#[test]+fn bootstrap_defers_only_pending_services_and_activation_validates_them() {+ let graph = build_graph(true).unwrap();+ let root = graph.workspace().root();+ let mut services: ServicesConfig = serde_json::from_value(serde_json::json!({+ "services": {+ "preview-gateway": {+ "bootstrap_pending": "Domain and secrets not configured",+ "deploy_binaries": ["preview_gateway"]+ }+ }+ }))+ .unwrap();+ let changed = [+ "services/preview_gateway/src/config.rs",+ "services/agent_harness_service/src/config.rs",+ ]+ .map(|path| root.join(path).into_std_path_buf())+ .into_iter()+ .collect();++ let bins = config_bins(&graph, &changed, &services).unwrap();+ assert!(!bins.contains("preview_gateway_doppler_config"));+ assert!(bins.contains("agent_harness_service_doppler_config"));++ services+ .services+ .get_mut("preview-gateway")+ .unwrap()+ .bootstrap_pending = None;+ let inventory_only = BTreeSet::from([root.join(SERVICES_CONFIG).into_std_path_buf()]);+ let bins = config_bins(&graph, &inventory_only, &services).unwrap();+ assert!(bins.contains("preview_gateway_doppler_config"));+ assert!(bins.contains("agent_harness_service_doppler_config"));+ assert!(+ config_bins(&graph, &BTreeSet::new(), &services)+ .unwrap()+ .is_empty()+ );+}diff --git a/tooling/xtask/crates/xtask_local/src/local.rs b/tooling/xtask/crates/xtask_local/src/local.rsindex 372b724fba..fa49e626b1 100644--- a/tooling/xtask/crates/xtask_local/src/local.rs+++ b/tooling/xtask/crates/xtask_local/src/local.rs@@ -267,6 +267,34 @@ pub fn run_stack(mode: Mode, args: &cli::RunArgs) -> Result<()> {}).flatten();+ // The preview SSH tunnel, also before env resolution: its hostname is what+ // the SharePreview script dials. A `tcp://` origin rather than the usual+ // `http://` — the far side is an SSH transport, not a web server — so the+ // agent reaches it through `cloudflared access ssh` as a ProxyCommand.+ // Without it a preview is still shareable, just only by an agent running on+ // this machine or in the compose network.+ let preview_ssh_tunnel = (share_app && !stage.is_dry_run())+ .then(|| {+ match cf_tunnel::open_tcp(&instance, "preview-ssh", instance.port(Port::PreviewSsh)) {+ Ok(tunnel) => {+ stage.note(&format!("preview ssh tunnel: {}", tunnel.hostname()));+ Some(tunnel)+ }+ Err(error) => {+ stage.note(&format!(+ "WARNING: no preview ssh tunnel ({error:#}); agents off this machine \+ cannot share a live preview"+ ));+ None+ }+ }+ })+ .flatten();+ // Borrowed by `prepare` below, so the guard itself has to outlive it.+ let preview_ssh_tunnel_host = preview_ssh_tunnel+ .as_ref()+ .map(|tunnel| tunnel.hostname().to_owned());+// The app tunnel does not feed the env, but it degrades the same way: a// failure warns and the stack comes up localhost-only.let app_tunnel = (share_app && !stage.is_dry_run())@@ -298,7 +326,10 @@ pub fn run_stack(mode: Mode, args: &cli::RunArgs) -> Result<()> {share_app,false,false,- egress_tunnel.as_ref().map(|tunnel| tunnel.url.as_str()),+ local_env::Tunnels {+ egress: egress_tunnel.as_ref().map(|tunnel| tunnel.url.as_str()),+ preview_ssh: preview_ssh_tunnel_host.as_deref(),+ },)?;// Build + stage the shareable bundle in the background (pure host-side@@ -646,7 +677,7 @@ fn prepare(static_frontend: bool,pull_app_images: bool,infra_only: bool,- egress_public_url: Option<&str>,+ tunnels: local_env::Tunnels<'_>,) -> Result<(env_layer::ResolvedEnv, arch::Target)> {let env = env_layer::resolve(mode,@@ -654,7 +685,7 @@ fn prepare(args.env.no_doppler,args.env.env_file.as_deref(),static_frontend,- egress_public_url,+ tunnels,args.traces.enabled(),)?;stage.note(&format!("env: {}", env_layer::summarize(&env.merged)));diff --git a/tooling/xtask/crates/xtask_local/src/local/cf_tunnel.rs b/tooling/xtask/crates/xtask_local/src/local/cf_tunnel.rsindex 410cc04ea1..86e31ad2e2 100644--- a/tooling/xtask/crates/xtask_local/src/local/cf_tunnel.rs+++ b/tooling/xtask/crates/xtask_local/src/local/cf_tunnel.rs@@ -1,7 +1,7 @@//! Cloudflare quick tunnels: opt-in public ingress into a local stack.//!//! Nothing here runs unless `--with-cf-tunnel` is passed — a plain `run_local`-//! never dials out. With the flag, two tunnels open:+//! never dials out. With the flag, three tunnels open://!//! - **egress**: a `@cursor` session runs on cursor.com, not in the compose//! network, and the MCP servers the harness hands it point at@@ -18,6 +18,10 @@//! share therefore serves the headless static bundle through the proxy,//! built against the `same-origin` sentinel, so every API and WebSocket call//! follows whatever hostname the visitor loaded the page from.+//! - **preview-ssh**: the preview gateway's SSH listener, so an agent that is+//! not on this machine can tunnel a dev server in for `SharePreview`. Its+//! origin is `tcp://`, not `http://` — see [`open_tcp`] for what that costs+//! the client.//!//! *Quick* tunnels deliberately: no account, no DNS record, a fresh random//! hostname per run — which is fine because the env is regenerated per run@@ -56,6 +60,14 @@ pub struct QuickTunnel {pub url: String,}+impl QuickTunnel {+ /// The minted hostname without its scheme, for clients that dial the name+ /// rather than fetch the URL (`cloudflared access ssh --hostname …`).+ pub fn hostname(&self) -> &str {+ self.url.strip_prefix("https://").unwrap_or(&self.url)+ }+}+impl Drop for QuickTunnel {fn drop(&mut self) {let _ = self.child.kill();@@ -73,14 +85,25 @@ fn pid_path(instance: &Instance, name: &str) -> PathBuf {/// Reaps a same-named tunnel leaked by a previous run first, so at most one/// per (instance, name) exists.pub fn open(instance: &Instance, name: &str, port: u16) -> Result<QuickTunnel> {+ open_origin(instance, name, &format!("http://localhost:{port}"))+}++/// Open a quick tunnel whose origin is a raw TCP service rather than a web+/// server — an SSH listener, here.+///+/// Cloudflare's edge only proxies HTTP ports, so nothing can dial the minted+/// hostname on port 22 directly; a client reaches it by wrapping the stream in+/// a WebSocket, which `cloudflared access ssh --hostname <host>` does as an+/// OpenSSH `ProxyCommand`. The hostname is still minted and logged exactly as+/// for an HTTP origin.+pub fn open_tcp(instance: &Instance, name: &str, port: u16) -> Result<QuickTunnel> {+ open_origin(instance, name, &format!("tcp://localhost:{port}"))+}++fn open_origin(instance: &Instance, name: &str, origin: &str) -> Result<QuickTunnel> {reap_stale(instance, name);let mut child = Command::new("cloudflared")- .args([- "tunnel",- "--no-autoupdate",- "--url",- &format!("http://localhost:{port}"),- ])+ .args(["tunnel", "--no-autoupdate", "--url", origin]).stdout(Stdio::null()).stderr(Stdio::piped()).spawn()diff --git a/tooling/xtask/crates/xtask_local/src/local/env_layer.rs b/tooling/xtask/crates/xtask_local/src/local/env_layer.rsindex 81f3ad7b9a..11b9e35526 100644--- a/tooling/xtask/crates/xtask_local/src/local/env_layer.rs+++ b/tooling/xtask/crates/xtask_local/src/local/env_layer.rs@@ -23,6 +23,7 @@ use std::process::Command;use anyhow::{Context, Result, bail};use super::instance::Instance;+use super::local_env::Tunnels;use super::{Mode, local_env};#[cfg(test)]@@ -46,7 +47,7 @@ pub fn resolve(no_doppler: bool,env_file: Option<&Path>,static_frontend: bool,- egress_public_url: Option<&str>,+ tunnels: Tunnels<'_>,wire_otel: bool,) -> Result<ResolvedEnv> {// Base = Doppler (`lcl_personal`/`dev_personal`); it supplies the@@ -56,9 +57,9 @@ pub fn resolve(// has — unlike the old defaults.env, which Doppler overrode). Dev keeps// Doppler as-is.let spec = mode.spec();- let local = spec.overlay_local_env.then(|| {- local_env::LocalEnv::for_instance(mode, instance, static_frontend, egress_public_url)- });+ let local = spec+ .overlay_local_env+ .then(|| local_env::LocalEnv::for_instance(mode, instance, static_frontend, tunnels));let mut env = BTreeMap::new();// Boot stubs go in FIRST so Doppler overrides them: they only exist to keep// a `--no-doppler` stack's config loaders satisfied, never to replace a@@ -75,6 +76,31 @@ pub fn resolve(for (k, v) in local.to_env() {env.insert(k, v);}+ // Persistent per-instance SSH host identity; never reuse a production key in local stacks.+ let key_path = instance.ensure_artifact_dir()?.join("preview_ssh_host_key");+ if !key_path.exists() {+ let status = Command::new("ssh-keygen")+ .args([+ "-q",+ "-t",+ "ed25519",+ "-N",+ "",+ "-C",+ "macro-local-preview",+ "-f",+ ])+ .arg(&key_path)+ .status()+ .context("generating preview SSH host key (run inside nix develop)")?;+ if !status.success() {+ bail!("ssh-keygen failed generating preview host identity");+ }+ }+ env.insert(+ "PREVIEW_SSH_HOST_KEY".into(),+ std::fs::read_to_string(key_path).context("reading preview host key")?,+ );// Local telemetry export: point services at the local OTLP collector// (docker-network alias `otel-collector`) only when the run asked for// tracing AND one answers on the OTLP HTTP port (so services don'tdiff --git a/tooling/xtask/crates/xtask_local/src/local/gen_compose.rs b/tooling/xtask/crates/xtask_local/src/local/gen_compose.rsindex c2957c96f9..8fbe5cbea8 100644--- a/tooling/xtask/crates/xtask_local/src/local/gen_compose.rs+++ b/tooling/xtask/crates/xtask_local/src/local/gen_compose.rs@@ -102,6 +102,12 @@ pub fn generate(instance.port(Port::AgentHarnessEgress)));}+ if mode.spec().runs_local_infra && svc.compose_name == "preview_gateway" {+ if instance.is_default() {+ ports.push(format!("{}:8080", instance.port(Port::PreviewControl)));+ }+ ports.push(format!("{}:2222", instance.port(Port::PreviewSsh)));+ }if !ports.is_empty() {s.ports = dct::Ports::Short(ports);}@@ -111,7 +117,12 @@ pub fn generate(// The reverse proxy is the frontend's single origin in every mode, and// LocalStack runs in every mode (dev's `dev_personal` notification queue// lives there too).- add_proxy_service(&mut services, instance, static_frontend);+ add_proxy_service(+ &mut services,+ instance,+ static_frontend,+ mode.spec().runs_local_infra,+ );add_localstack_service(&mut services, instance);// The rest of the local infra (FusionAuth, Mailpit, per-instance Postgres/// Redis/OpenSearch port remaps) only for the self-contained local stacks.@@ -273,6 +284,7 @@ fn add_proxy_service(services: &mut IndexMap<String, Option<dct::Service>>,instance: &Instance,static_frontend: bool,+ previews: bool,) {let proxy_port = instance.port(Port::Proxy);let mut volumes = vec![dct::Volumes::Simple(format!(@@ -285,12 +297,20 @@ fn add_proxy_service(super::frontend::static_dir(instance).display())));}+ let mut ports = vec![format!("{proxy_port}:{proxy_port}")];+ if previews {+ ports.push(format!("{}:8443", instance.port(Port::PreviewHttps)));+ volumes.push(dct::Volumes::Simple(format!(+ "{}:/data",+ instance.artifact_dir().join("preview-caddy-data").display()+ )));+ }services.insert("proxy".to_string(),Some(dct::Service {image: Some(CADDY_IMAGE.to_string()),environment: kv(&[("PROXY_PORT", &proxy_port.to_string())]),- ports: dct::Ports::Short(vec![format!("{proxy_port}:{proxy_port}")]),+ ports: dct::Ports::Short(ports),volumes,networks: dct::Networks::Simple(vec!["services".to_string(), "databases".to_string()]),..Default::default()diff --git a/tooling/xtask/crates/xtask_local/src/local/instance.rs b/tooling/xtask/crates/xtask_local/src/local/instance.rsindex 1f04da0b8a..a059d65d1d 100644--- a/tooling/xtask/crates/xtask_local/src/local/instance.rs+++ b/tooling/xtask/crates/xtask_local/src/local/instance.rs@@ -114,6 +114,12 @@ pub enum Port {/// existing per-instance port offsets, which come from declaration order,/// stay stable.Calendar = 8088,+ /// Live-preview control API. Appended after Calendar for the same reason.+ PreviewControl = 8110,+ /// Stock SSH reverse-tunnel listener.+ PreviewSsh = 2222,+ /// Local wildcard preview TLS listener.+ PreviewHttps = 8443,}impl Port {diff --git a/tooling/xtask/crates/xtask_local/src/local/inventory.rs b/tooling/xtask/crates/xtask_local/src/local/inventory.rsindex c5f074d95b..693c9dd2ed 100644--- a/tooling/xtask/crates/xtask_local/src/local/inventory.rs+++ b/tooling/xtask/crates/xtask_local/src/local/inventory.rs@@ -91,6 +91,17 @@ impl RustService {/// The full service inventory of the local service binaries.pub const RUST_SERVICES: &[RustService] = &[+ RustService {+ compose_name: "preview_gateway",+ cargo_bin: "preview_gateway",+ package: "preview_gateway",+ host_port: Some(Port::PreviewControl),+ path_prefix: Some("/preview"),+ is_websocket: false,+ modes: &[Mode::Local],+ opt_in: false,+ no_default_features: false,+ },RustService {compose_name: "authentication-service",cargo_bin: "authentication_service",diff --git a/tooling/xtask/crates/xtask_local/src/local/inventory/test.rs b/tooling/xtask/crates/xtask_local/src/local/inventory/test.rsindex 04679717e1..ced0978422 100644--- a/tooling/xtask/crates/xtask_local/src/local/inventory/test.rs+++ b/tooling/xtask/crates/xtask_local/src/local/inventory/test.rs@@ -3,10 +3,11 @@ use super::*;#[test]fn local_binaries_are_unique_and_complete() {let bins = local_binaries();- // 18 distinct binaries (the bundled set, including scheduled_action,- // calendar_service, the local-only search_processing_service, agent harness,- // mcp_service, and the seed_cli shipped for the gmail_forwarder sidecar).- assert_eq!(bins.len(), 18, "{bins:?}");+ // 19 distinct binaries (the bundled set, including scheduled_action,+ // calendar_service, preview_gateway, the local-only search_processing_service,+ // agent harness, mcp_service, and the seed_cli shipped for the+ // gmail_forwarder sidecar).+ assert_eq!(bins.len(), 19, "{bins:?}");assert!(bins.contains(&"pubsub_workers"));assert!(bins.contains(&"seed_cli"));assert!(bins.contains(&"document_upload_finalizer_local_worker"));diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env.rs b/tooling/xtask/crates/xtask_local/src/local/local_env.rsindex c90c4a50da..55d2331b7f 100644--- a/tooling/xtask/crates/xtask_local/src/local/local_env.rs+++ b/tooling/xtask/crates/xtask_local/src/local/local_env.rs@@ -19,6 +19,21 @@ use std::collections::BTreeMap;use super::instance::{Instance, Port};use super::{Mode, identity, resources};+/// The public hostnames `--with-cf-tunnel` minted for this run.+///+/// Both exist for the same reason: an agent that is not on this machine — a+/// `@cursor` session on cursor.com — can reach neither the compose network nor+/// localhost, so anything it must dial needs a public name instead.+#[derive(Clone, Copy, Default)]+pub struct Tunnels<'a> {+ /// Origin replacing the in-network egress address in the MCP servers the+ /// harness hands that agent.+ pub egress: Option<&'a str>,+ /// Quick-tunnel hostname fronting the preview gateway's SSH listener, so a+ /// shared dev server can be tunnelled in from off-machine.+ pub preview_ssh: Option<&'a str>,+}+/// The full local environment for one instance.pub struct LocalEnv {environment: &'static str,@@ -29,6 +44,10 @@ pub struct LocalEnv {/// `http://localhost:{FRONTEND_PORT}`, so this must track the serving/// mode or every OAuth signup dead-ends on an unused port.frontend_port: u16,+ external_egress_url: String,+ preview_ssh_proxy_host: Option<String>,+ preview_ssh_port: u16,+ preview_https_port: u16,/// Browser-facing route to document cognition's MCP OAuth callback.mcp_public_url: String,/// Browser-facing base the static file service stamps into permalinks.@@ -52,15 +71,17 @@ impl LocalEnv {/// Build the local env for `instance` in `Local` mode (dev sources its env/// from Doppler, not here).///- /// `egress_public_url` is the run's Cursor egress tunnel, when one opened:- /// it replaces the in-network egress address so the MCP servers the- /// harness hands a Cursor cloud agent are reachable from outside the- /// compose network. `None` (no tunnel) keeps the in-network address.+ /// `tunnels` carries the run's public hostnames, when `--with-cf-tunnel`+ /// opened them: the egress one replaces the in-network egress address so+ /// the MCP servers the harness hands a Cursor cloud agent are reachable+ /// from outside the compose network, and the preview one lets that same+ /// agent reach this stack's SSH listener. Absent tunnels keep the+ /// in-network address and leave previews reachable on this machine only.pub fn for_instance(mode: Mode,instance: &Instance,static_frontend: bool,- egress_public_url: Option<&str>,+ tunnels: Tunnels<'_>,) -> Self {let name = instance.name();LocalEnv {@@ -72,6 +93,15 @@ impl LocalEnv {} else {instance.port(Port::Frontend)},+ external_egress_url: tunnels.egress.map(str::to_owned).unwrap_or_else(|| {+ format!(+ "http://localhost:{}",+ instance.port(Port::AgentHarnessEgress)+ )+ }),+ preview_ssh_proxy_host: tunnels.preview_ssh.map(str::to_owned),+ preview_ssh_port: instance.port(Port::PreviewSsh),+ preview_https_port: instance.port(Port::PreviewHttps),mcp_public_url: format!("http://localhost:{}/cognition", instance.port(Port::Proxy)),static_file_public_url: format!("http://localhost:{}/static-file",@@ -81,7 +111,7 @@ impl LocalEnv {storage: StorageEnv::local(),queues: QueueEnv::local(),mail: MailEnv::local(),- agent_harness: AgentHarnessEnv::local(instance.project_name(), egress_public_url),+ agent_harness: AgentHarnessEnv::local(instance.project_name(), tunnels.egress),service_auth: ServiceAuthEnv::for_instance(name),fusionauth: FusionAuthEnv::for_instance(instance),boot_stubs: BootStubEnv,@@ -115,6 +145,38 @@ impl LocalEnv {// Calendar search ships dark too: off in deployed envs until each has// its calendar index created and backfilled.env.insert("CALENDAR_SEARCH_ENABLED".into(), "true".into());+ env.insert(+ "OVERRIDE_PREVIEW_GATEWAY_URL".into(),+ "http://preview-gateway:8080".into(),+ );+ env.insert(+ "EXTERNAL_EGRESS_BASE_URL".into(),+ self.external_egress_url.clone(),+ );+ env.insert("PREVIEW_DOMAIN".into(), "preview.localhost".into());+ env.insert("PREVIEW_SSH_HOST".into(), "localhost".into());+ // Empty rather than absent: the gateway treats both as "no public ingress",+ // and a key that vanishes between runs would be read from a stale layer.+ env.insert(+ "PREVIEW_SSH_PROXY_HOST".into(),+ self.preview_ssh_proxy_host.clone().unwrap_or_default(),+ );+ env.insert(+ "PREVIEW_SSH_PUBLIC_PORT".into(),+ self.preview_ssh_port.to_string(),+ );+ env.insert(+ "PREVIEW_HTTPS_PORT".into(),+ self.preview_https_port.to_string(),+ );+ env.insert(+ "PREVIEW_APP_ORIGIN".into(),+ format!("http://localhost:{}", self.frontend_port),+ );+ env.insert(+ "PREVIEW_CONTROL_HOSTS".into(),+ "localhost,127.0.0.1,preview-gateway".into(),+ );self.infra.write(&mut env);self.storage.write(&mut env);self.queues.write(&mut env);diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rsindex 1257bee72c..5964e1d7ae 100644--- a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs+++ b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs@@ -6,7 +6,7 @@ use crate::local::instance::{Instance, Port};/// authoritative local env on top (mirrors `env_layer::resolve`).fn local_env() -> BTreeMap<String, String> {let instance = Instance::derive(None, None).expect("default instance derives");- let local = LocalEnv::for_instance(Mode::Local, &instance, true, None);+ let local = LocalEnv::for_instance(Mode::Local, &instance, true, Tunnels::default());let mut env = local.boot_stub_env();env.extend(local.to_env());env@@ -110,7 +110,7 @@ fn emits_required_keys() {#[test]fn boot_stubs_do_not_overlap_authoritative_env() {let instance = Instance::derive(None, None).expect("default instance derives");- let local = LocalEnv::for_instance(Mode::Local, &instance, true, None);+ let local = LocalEnv::for_instance(Mode::Local, &instance, true, Tunnels::default());let authoritative = local.to_env();for key in local.boot_stub_env().keys() {assert!(@@ -157,7 +157,7 @@ fn internal_auth_values_are_authoritative_local_env() {Mode::Local,&Instance::derive(None, None).unwrap(),true,- None,+ Tunnels::default(),).to_env();let expected = env.get("INTERNAL_API_SECRET_KEY");@@ -286,8 +286,8 @@ fn aws_creds_are_dummy() {fn instance_secrets_are_scoped_but_identity_is_fixed() {let default = Instance::derive(None, None).unwrap();let agent_a = Instance::derive(Some("agent-a"), None).unwrap();- let a = LocalEnv::for_instance(Mode::Local, &default, true, None).to_env();- let b = LocalEnv::for_instance(Mode::Local, &agent_a, true, None).to_env();+ let a = LocalEnv::for_instance(Mode::Local, &default, true, Tunnels::default()).to_env();+ let b = LocalEnv::for_instance(Mode::Local, &agent_a, true, Tunnels::default()).to_env();assert_ne!(a.get("SERVICE_INTERNAL_AUTH_KEY"),@@ -305,8 +305,9 @@ fn instance_secrets_are_scoped_but_identity_is_fixed() {fn fusionauth_public_url_uses_the_instance_host_port() {let default = Instance::derive(None, None).unwrap();let named = Instance::derive(Some("2508"), None).unwrap();- let default_env = LocalEnv::for_instance(Mode::Local, &default, true, None).to_env();- let named_env = LocalEnv::for_instance(Mode::Local, &named, true, None).to_env();+ let default_env =+ LocalEnv::for_instance(Mode::Local, &default, true, Tunnels::default()).to_env();+ let named_env = LocalEnv::for_instance(Mode::Local, &named, true, Tunnels::default()).to_env();let named_public_url = format!("http://localhost:{}", named.port(Port::FusionAuth));assert_eq!(@@ -353,10 +354,10 @@ fn local_sandboxes_join_the_instances_compose_network() {Mode::Local,&Instance::derive(None, None).unwrap(),true,- None,+ Tunnels::default(),).to_env();- let named_env = LocalEnv::for_instance(Mode::Local, &named, true, None).to_env();+ let named_env = LocalEnv::for_instance(Mode::Local, &named, true, Tunnels::default()).to_env();assert_eq!(default_env@@ -378,8 +379,9 @@ fn local_sandboxes_join_the_instances_compose_network() {fn mcp_public_url_uses_the_proxy_cognition_route() {let default = Instance::derive(None, None).unwrap();let named = Instance::derive(Some("2508"), None).unwrap();- let default_env = LocalEnv::for_instance(Mode::Local, &default, true, None).to_env();- let named_env = LocalEnv::for_instance(Mode::Local, &named, true, None).to_env();+ let default_env =+ LocalEnv::for_instance(Mode::Local, &default, true, Tunnels::default()).to_env();+ let named_env = LocalEnv::for_instance(Mode::Local, &named, true, Tunnels::default()).to_env();let named_public_url = format!("http://localhost:{}/cognition", named.port(Port::Proxy));assert_eq!(@@ -399,7 +401,7 @@ fn mcp_public_url_uses_the_proxy_cognition_route() {#[test]fn the_egress_url_override_is_the_hyphenated_in_network_alias() {let named = Instance::derive(Some("2508"), None).unwrap();- let named_env = LocalEnv::for_instance(Mode::Local, &named, true, None).to_env();+ let named_env = LocalEnv::for_instance(Mode::Local, &named, true, Tunnels::default()).to_env();assert_eq!(named_env@@ -424,7 +426,16 @@ fn the_mcp_service_override_is_an_in_network_base_url() {fn the_public_tunnel_overrides_the_egress_service_url() {let instance = Instance::derive(Some("2508"), None).unwrap();let url = "https://egress-test.trycloudflare.com";- let env = LocalEnv::for_instance(Mode::Local, &instance, true, Some(url)).to_env();+ let env = LocalEnv::for_instance(+ Mode::Local,+ &instance,+ true,+ Tunnels {+ egress: Some(url),+ ..Tunnels::default()+ },+ )+ .to_env();assert_eq!(env.get("OVERRIDE_AGENT_HARNESS_EGRESS_URL")@@ -437,10 +448,70 @@ fn the_public_tunnel_overrides_the_egress_service_url() {#[test]fn named_instance_separates_browser_and_container_aws_endpoints() {let instance = Instance::derive(Some("image"), None).expect("named instance derives");- let env = LocalEnv::for_instance(Mode::Local, &instance, false, None).to_env();+ let env = LocalEnv::for_instance(Mode::Local, &instance, false, Tunnels::default()).to_env();assert_eq!(env["LOCAL_AWS_URL"], "http://localstack:4566");assert_eq!(env["LOCAL_AWS_PUBLIC_URL"],format!("http://localhost:{}", instance.port(Port::LocalStack)));}++#[test]+fn external_runtime_egress_respects_instance_host_ports_and_public_tunnels() {+ let instance = Instance::derive(Some("preview"), None).unwrap();+ let env = LocalEnv::for_instance(Mode::Local, &instance, false, Tunnels::default()).to_env();+ assert_eq!(+ env["EXTERNAL_EGRESS_BASE_URL"],+ format!(+ "http://localhost:{}",+ instance.port(Port::AgentHarnessEgress)+ )+ );+ assert_eq!(+ env["OVERRIDE_AGENT_HARNESS_EGRESS_URL"],+ "http://agent-harness-service:8102"+ );+ let env = LocalEnv::for_instance(+ Mode::Local,+ &instance,+ false,+ Tunnels {+ egress: Some("https://egress.example.test"),+ ..Tunnels::default()+ },+ )+ .to_env();+ assert_eq!(+ env["EXTERNAL_EGRESS_BASE_URL"],+ "https://egress.example.test"+ );+ assert_eq!(+ env["OVERRIDE_AGENT_HARNESS_EGRESS_URL"],+ "https://egress.example.test"+ );+}++#[test]+fn the_preview_ssh_proxy_host_is_empty_without_a_published_tunnel() {+ let instance = Instance::derive(Some("preview"), None).unwrap();+ let env = LocalEnv::for_instance(Mode::Local, &instance, false, Tunnels::default()).to_env();+ assert_eq!(env["PREVIEW_SSH_HOST"], "localhost");+ assert_eq!(env["PREVIEW_SSH_PROXY_HOST"], "");++ let env = LocalEnv::for_instance(+ Mode::Local,+ &instance,+ false,+ Tunnels {+ preview_ssh: Some("odds-and-ends.trycloudflare.com"),+ ..Tunnels::default()+ },+ )+ .to_env();+ assert_eq!(+ env["PREVIEW_SSH_PROXY_HOST"],+ "odds-and-ends.trycloudflare.com"+ );+ // The on-machine endpoint stays first; the tunnel is a fallback, not a swap.+ assert_eq!(env["PREVIEW_SSH_HOST"], "localhost");+}diff --git a/tooling/xtask/crates/xtask_local/src/local/proxy.rs b/tooling/xtask/crates/xtask_local/src/local/proxy.rsindex 23e151a2a5..e609ebc261 100644--- a/tooling/xtask/crates/xtask_local/src/local/proxy.rs+++ b/tooling/xtask/crates/xtask_local/src/local/proxy.rs@@ -70,8 +70,13 @@ fn caddyfile(mode: Mode, static_frontend: bool) -> String {""};let frontend_block = if static_frontend { FRONTEND_STATIC } else { "" };+ let preview_block = if mode.spec().runs_local_infra {+ "\nhttps://*.preview.localhost:8443 {\n tls internal\n reverse_proxy preview_gateway:8111\n}\n"+ } else {+ ""+ };format!(- "{CADDY_HEAD}{routes}{SPECIAL_ROUTES}{mailpit_block}{static_block}{frontend_block}{CADDY_TAIL}",+ "{CADDY_HEAD}{routes}{SPECIAL_ROUTES}{mailpit_block}{static_block}{frontend_block}{CADDY_TAIL}{preview_block}",routes = service_routes(mode))}@@ -150,7 +155,7 @@ fn matcher_name(prefix: &str) -> String {/// and the closing brace follow.const CADDY_HEAD: &str = r#"# GENERATED by `cargo x` — do not edit.{- auto_https off+ auto_https disable_redirectsadmin off}diff --git a/tooling/xtask/crates/xtask_local/src/local/stack.rs b/tooling/xtask/crates/xtask_local/src/local/stack.rsindex 0d17eb05bf..bee78b802d 100644--- a/tooling/xtask/crates/xtask_local/src/local/stack.rs+++ b/tooling/xtask/crates/xtask_local/src/local/stack.rs@@ -18,6 +18,7 @@ use serde_json::json;use super::cli::{EnvArgs, InstanceArgs, RunArgs};use super::instance::{Instance, Port};+use super::local_env::Tunnels;use super::stage::Stage;use super::{Mode, arch, env_layer, frontend, mailpit, proxy, sdk_webhook, snapshot, summary};@@ -174,8 +175,8 @@ pub fn up(mode: Mode, args: &UpArgs) -> Result<Instance> {infra_only,// Headless stacks serve agents on Cursor Cloud dev boxes, which have// no cloudflared and no @cursor sessions to feed; the egress stays- // in-network.- None,+ // in-network and previews stay reachable on that box only.+ Tunnels::default(),)?;// Build + stage the frontend bundle in the background: it's pure host-side@@ -354,7 +355,7 @@ fn update_running(args: &UpdateArgs) -> Result<()> {args.env.no_doppler,args.env.env_file.as_deref(),state.frontend == "static",- None,+ Tunnels::default(),// `update` doesn't know the original `--traces` choice; keep the// running stack's wiring keyed on the port probe as before.true,diff --git a/tooling/xtask/crates/xtask_local/src/local/validate.rs b/tooling/xtask/crates/xtask_local/src/local/validate.rsindex b209f1e0da..58effc7da5 100644--- a/tooling/xtask/crates/xtask_local/src/local/validate.rs+++ b/tooling/xtask/crates/xtask_local/src/local/validate.rs@@ -10,6 +10,7 @@ use serde_json::Value;use super::build::{BinariesDir, RUNTIME_IMAGE_TAG};use super::instance::Port;use super::inventory::services_for_mode;+use super::local_env::Tunnels;use super::{Mode, arch, env_layer, gen_compose, instance::Instance, workspace_root};/// Required non-Rust services that must be present in the rendered local@@ -43,7 +44,15 @@ fn local_compose_flavor(instance: &Instance, mode: Mode, static_frontend: bool)// Resolve first: the gmail_forwarder sidecar is gated on the resolved env// exactly as `prepare` gates it, so the validated compose matches what a// real bring-up with this env would generate.- let resolved = env_layer::resolve(mode, instance, true, None, static_frontend, None, true)?;+ let resolved = env_layer::resolve(+ mode,+ instance,+ true,+ None,+ static_frontend,+ Tunnels::default(),+ true,+ )?;let gmail_forwarder = resolved.merged.get("GMAIL_FORWARDER_SA_KEY")@@ -183,7 +192,7 @@ fn local_env_flavor(no_doppler,env_file,static_frontend,- None,+ Tunnels::default(),true,)?;let env = &resolved.merged;diff --git a/tooling/xtask/crates/xtask_workflows/Cargo.toml b/tooling/xtask/crates/xtask_workflows/Cargo.tomlindex f60e36d93e..fd5c19654e 100644--- a/tooling/xtask/crates/xtask_workflows/Cargo.toml+++ b/tooling/xtask/crates/xtask_workflows/Cargo.toml@@ -17,3 +17,6 @@ gh-workflow = "0.8"indoc = { workspace = true }serde_yaml = { workspace = true }xtask_paths = { path = "../xtask_paths" }++[dev-dependencies]+tempfile = { workspace = true }diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/code_check_cloud_storage.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/code_check_cloud_storage.rsindex b905adf0bf..1192e620b8 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/code_check_cloud_storage.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/code_check_cloud_storage.rs@@ -166,6 +166,7 @@ fn paths_filter() -> Step<gh_workflow::Use> {- '.github/actions/setup-nix-dev-shell/**'- '.github/actions/teardown-nix/**'- '.github/actions/setup-sccache/**'+ - '.github/services-config.json'- .github/workflows/code_check_cloud_storage.yml"#},))diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/code_check_cloud_storage/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/code_check_cloud_storage/test.rsindex dfb976e48f..d01445ed0b 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/code_check_cloud_storage/test.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/code_check_cloud_storage/test.rs@@ -1,5 +1,13 @@use super::*;+#[test]+fn inventory_only_changes_run_live_config_validation() {+ let filters = serde_json::to_string(&paths_filter().value.with).unwrap();+ assert!(filters.contains(".github/services-config.json"));+ let job = serde_json::to_value(check()).unwrap();+ assert!(!job["if"].as_str().unwrap().contains("rust_packages"));+}+#[test]fn package_selection_does_not_pass_lib() {let script = include_str!("../scripts/run_tests.sh");diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_all_services.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_all_services.rsindex 67fd63960c..85aa5ca1b4 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_all_services.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_all_services.rs@@ -15,6 +15,9 @@ use gh_workflow::{use crate::workflows::{runners, steps, vars};+#[cfg(test)]+mod test;+/// The in-VPC self-hosted runner with network access to the databases. Stays/// off Namespace deliberately — migrations need to reach RDS.const DB_MIGRATOR_RUNNER: &str = "db-migrator";@@ -130,10 +133,10 @@ fn set_matrix() -> Step<Run> {cfg=.github/services-config.json# Enabled services drive deploy-services; the filtered lists keep each# build matrix to only enabled services that produce that artifact, so- # disabled services and empty artifact jobs consume no runners.- services=$(jq -c '[.services | to_entries[] | select(.value.deploy_enabled != false) | .key]' "$cfg")- binaries=$(jq -c '[.services | to_entries[] | select(.value.deploy_enabled != false) | select((.value.deploy_binaries // []) | length > 0) | .key]' "$cfg")- lambdas=$(jq -c '[.services | to_entries[] | select(.value.deploy_enabled != false) | select((.value.deploy_lambdas // []) | length > 0) | .key]' "$cfg")+ # disabled/unbootstrapped services and empty artifact jobs consume no runners.+ services=$(jq -c '[.services | to_entries[] | select(.value.deploy_enabled != false and .value.bootstrap_pending == null) | .key]' "$cfg")+ binaries=$(jq -c '[.services | to_entries[] | select(.value.deploy_enabled != false and .value.bootstrap_pending == null) | select((.value.deploy_binaries // []) | length > 0) | .key]' "$cfg")+ lambdas=$(jq -c '[.services | to_entries[] | select(.value.deploy_enabled != false and .value.bootstrap_pending == null) | select((.value.deploy_lambdas // []) | length > 0) | .key]' "$cfg")echo "matrix=${services}" >> "$GITHUB_OUTPUT"echo "binaries=${binaries}" >> "$GITHUB_OUTPUT"echo "lambdas=${lambdas}" >> "$GITHUB_OUTPUT"diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_all_services/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_all_services/test.rsnew file mode 100644index 0000000000..4da4a536b6--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_all_services/test.rs@@ -0,0 +1,47 @@+use super::*;++#[test]+fn bootstrap_excludes_all_deployment_matrices_until_activation() {+ let dir = tempfile::tempdir().unwrap();+ let github = dir.path().join(".github");+ std::fs::create_dir(&github).unwrap();+ let mut config = serde_json::json!({"services": {+ "ready": {"deploy_binaries": ["ready"], "deploy_lambdas": ["ready_lambda"]},+ "pending": {"bootstrap_pending": "Requires first-time setup", "deploy_binaries": ["pending"], "deploy_lambdas": ["pending_lambda"]},+ "paused": {"deploy_enabled": false, "deploy_binaries": ["paused"]}+ }});+ for expected in [+ serde_json::json!(["ready"]),+ serde_json::json!(["pending", "ready"]),+ ] {+ std::fs::write(github.join("services-config.json"), config.to_string()).unwrap();+ let output_path = dir.path().join("output");+ std::fs::write(&output_path, "").unwrap();+ let output = std::process::Command::new("bash")+ .args(["-euo", "pipefail", "-c", &set_matrix().value.run.unwrap()])+ .current_dir(dir.path())+ .env("GITHUB_OUTPUT", &output_path)+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ let result = std::fs::read_to_string(output_path).unwrap();+ for matrix in ["matrix", "binaries", "lambdas"] {+ let prefix = format!("{matrix}=");+ let value = result+ .lines()+ .find_map(|line| line.strip_prefix(&prefix))+ .unwrap();+ let mut actual: Vec<String> = serde_json::from_str(value).unwrap();+ actual.sort();+ assert_eq!(serde_json::json!(actual), expected, "{result}");+ }+ config["services"]["pending"]+ .as_object_mut()+ .unwrap()+ .remove("bootstrap_pending");+ }+}diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/pulumi_preview_pr.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/pulumi_preview_pr.rsindex 369c71512c..61eb0e82f1 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/pulumi_preview_pr.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/pulumi_preview_pr.rs@@ -203,6 +203,11 @@ fn detect_affected_services() -> Step<Run> {# Check each service for changesfor service in $(echo "$config" | jq -r '.services | keys[]'); do+ bootstrap_pending=$(jq -r --arg s "$service" '.services[$s].bootstrap_pending // empty' <<< "$config")+ if jq -e --arg s "$service" '.services[$s].bootstrap_pending != null' <<< "$config" > /dev/null; then+ echo "::notice::Deferring $service live infrastructure checks: $bootstrap_pending"+ continue+ fiservice_changed=false# Workspace/build-system changes can affect every deployable.diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/pulumi_preview_pr/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/pulumi_preview_pr/test.rsindex 2689250acb..307406cccb 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/pulumi_preview_pr/test.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/pulumi_preview_pr/test.rs@@ -1,5 +1,57 @@use super::*;+#[test]+fn bootstrap_defers_preview_until_activation_without_hiding_paused_services() {+ let dir = tempfile::tempdir().unwrap();+ let github = dir.path().join(".github");+ std::fs::create_dir_all(github.join("outputs")).unwrap();+ std::fs::write(+ github.join("outputs/all_modified_files.json"),+ r#"[".github/services-config.json"]"#,+ )+ .unwrap();+ let mut config = serde_json::json!({"services": {+ "ready": {},+ "pending": {"bootstrap_pending": "Requires first-time setup"},+ "paused": {"deploy_enabled": false}+ }});+ for expected in [+ serde_json::json!(["paused", "ready"]),+ serde_json::json!(["paused", "pending", "ready"]),+ ] {+ std::fs::write(github.join("services-config.json"), config.to_string()).unwrap();+ let output_path = dir.path().join("output");+ std::fs::write(&output_path, "").unwrap();+ let output = std::process::Command::new("bash")+ .args([+ "-euo",+ "pipefail",+ "-c",+ &detect_affected_services().value.run.unwrap(),+ ])+ .current_dir(dir.path())+ .env("GITHUB_OUTPUT", &output_path)+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ let result = std::fs::read_to_string(output_path).unwrap();+ assert!(+ result+ .lines()+ .any(|line| line == format!("services={expected}")),+ "{result}"+ );+ config["services"]["pending"]+ .as_object_mut()+ .unwrap()+ .remove("bootstrap_pending");+ }+}+#[test]fn sqlx_changes_preview_every_service() {let detect = detect_affected_services();diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/reusable_deploy_service.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/reusable_deploy_service.rsindex 905f9abee0..d39909de87 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/reusable_deploy_service.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/reusable_deploy_service.rs@@ -92,6 +92,11 @@ fn check_artifact_config() -> Step<Run> {.run(indoc::indoc! {r#"set -euo pipefailcfg=.github/services-config.json+ if jq -e --arg service "$SERVICE" '.services[$service].bootstrap_pending != null' "$cfg" > /dev/null; then+ reason=$(jq -r --arg service "$SERVICE" '.services[$service].bootstrap_pending' "$cfg")+ echo "::error::Cannot deploy $SERVICE before bootstrap: $reason"+ exit 1+ fihas_binaries=$(jq -r --arg service "$SERVICE" '((.services[$service].deploy_binaries // []) | length) > 0' "$cfg")has_lambdas=$(jq -r --arg service "$SERVICE" '((.services[$service].deploy_lambdas // []) | length) > 0' "$cfg")echo "has_binaries=$has_binaries" >> "$GITHUB_OUTPUT"