Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Enable CDPDownloadInterceptor for remote browser connections (#4921)
Shuchang Zheng74340adfaf81
diff --git a/skyvern/cli/commands/browser.py b/skyvern/cli/commands/browser.pyindex 125eda62f..40eb58be1 100644--- a/skyvern/cli/commands/browser.py+++ b/skyvern/cli/commands/browser.py@@ -6,7 +6,10 @@ import sysfrom dataclasses import asdict, dataclassfrom datetime import datetime, timezonefrom pathlib import Path-from typing import Any, Literal+from typing import TYPE_CHECKING, Any, Literal++if TYPE_CHECKING:+ from skyvern.cli.core.browser_launcher import LocalBrowserInfoimport typer@@ -918,3 +921,271 @@ def login(output_error(str(e), hint="Check credential inputs, active connection, and timeout settings.", json_mode=json_output)+++# ---------------------------------------------------------------------------+# Browser serve command (POC for local browser + tunnel)+# ---------------------------------------------------------------------------+++@browser_app.command("serve")+def serve(+ port: int = typer.Option(9222, help="Server port (exposes CDP proxy + file server)."),+ profile_dir: str | None = typer.Option(+ None,+ "--profile-dir",+ help="Chrome user data directory. Uses existing cookies/auth if specified.",+ ),+ download_dir: str | None = typer.Option(+ None,+ "--download-dir",+ help="Directory where browser downloads files. Defaults to ~/.skyvern/downloads/{browser_id}.",+ ),+ api_key: str | None = typer.Option(+ None,+ "--api-key",+ envvar="SKYVERN_BROWSER_SERVE_API_KEY",+ help="API key for authenticating requests. If set, requires x-api-key header.",+ ),+ headless: bool = typer.Option(False, "--headless", help="Run Chrome in headless mode."),+ chrome_path: str | None = typer.Option(+ None,+ "--chrome-path",+ help="Path to Chrome executable. Auto-detects if not specified.",+ ),+ json_output: bool = typer.Option(False, "--json", help="Output connection info as JSON."),+) -> None:+ """Launch a local Chrome browser with CDP server for Skyvern Cloud.++ This command starts a unified server that provides:+ - CDP WebSocket proxy at /devtools/* (forwards to Chrome)+ - CDP JSON API at /json/* (for listing targets)++ \b+ Downloads are automatically captured by Skyvern via CDP and saved to the+ Skyvern worker's disk.++ \b+ Quick start:+ 1. Start the browser serve:+ skyvern browser serve++ 2. In another terminal, set up a single HTTP tunnel:+ ngrok http 9222++ 3. Use the tunnel URL for browser_address in your task:+ wss://YOUR_TUNNEL_URL/devtools/browser/...+ """+ import signal++ from skyvern.cli.core.browser_launcher import (+ generate_browser_id,+ get_default_chrome_path,+ get_default_download_dir,+ get_default_profile_dir,+ launch_chrome_with_cdp,+ terminate_browser,+ )+ from skyvern.cli.core.unified_server import UnifiedServer, UnifiedServerConfig+ from skyvern.cli.run_commands import get_pids_on_port++ # Chrome runs on internal port, unified server on exposed port+ chrome_internal_port = port + 1000 # e.g., 9222 -> 10222++ # Check for port conflicts+ for check_port, name in [(port, "unified server"), (chrome_internal_port, "Chrome CDP (internal)")]:+ existing_pids = get_pids_on_port(check_port)+ if existing_pids:+ output_error(+ f"Port {check_port} ({name}) is already in use by process(es): {existing_pids}",+ hint="Use a different --port or stop the existing process.",+ json_mode=json_output,+ )+ raise SystemExit(1)++ # Generate unique browser ID for this instance+ browser_id = generate_browser_id()++ # Resolve paths for display+ resolved_chrome_path = chrome_path or get_default_chrome_path()+ resolved_profile_dir = profile_dir or get_default_profile_dir()+ # Use unique download directory if not specified+ resolved_download_dir = download_dir or get_default_download_dir(browser_id)++ if not json_output:+ output(+ {+ "status": "starting",+ "browser_id": browser_id,+ "chrome_path": resolved_chrome_path,+ "profile_dir": resolved_profile_dir,+ "download_dir": resolved_download_dir,+ "port": port,+ "headless": headless,+ "auth_enabled": api_key is not None,+ },+ action="serve_starting",+ json_mode=False,+ )++ browser_info: LocalBrowserInfo | None = None+ unified_server: UnifiedServer | None = None+ shutdown_requested = False++ def signal_handler(signum: int, frame: Any) -> None:+ nonlocal shutdown_requested+ shutdown_requested = True++ # Set up signal handlers+ original_sigint = signal.signal(signal.SIGINT, signal_handler)+ original_sigterm = signal.signal(signal.SIGTERM, signal_handler)++ async def run_serve() -> None:+ nonlocal browser_info, unified_server, shutdown_requested++ # Launch Chrome on internal port+ browser_info = await launch_chrome_with_cdp(+ port=chrome_internal_port,+ profile_dir=profile_dir,+ headless=headless,+ chrome_path=chrome_path,+ download_dir=resolved_download_dir,+ )++ # Start unified server on exposed port+ config = UnifiedServerConfig(+ port=port,+ chrome_cdp_port=chrome_internal_port,+ api_key=api_key,+ )+ unified_server = UnifiedServer(config)+ await unified_server.start()++ # Extract browser path from Chrome's CDP URL+ browser_path = browser_info.cdp_ws_url.split("/devtools/browser/")[-1]++ # Output success info+ result = {+ "status": "running",+ "browser_id": browser_id,+ "server_url": f"http://127.0.0.1:{port}",+ "cdp_ws_url": f"ws://127.0.0.1:{port}/devtools/browser/{browser_path}",+ "port": port,+ "profile_dir": browser_info.profile_dir,+ "auth_enabled": api_key is not None,+ }++ if json_output:+ output(result, action="serve", json_mode=True)+ else:+ _print_serve_instructions_unified(result, browser_path)++ # Keep the event loop running while server is active+ # This is required because aiohttp's TCPSite needs the event loop to accept connections+ try:+ while not shutdown_requested:+ # Check if Chrome process is still alive+ if browser_info.process.poll() is not None:+ if not json_output:+ output_error(+ "Chrome process exited unexpectedly",+ hint="Check Chrome logs or try restarting with a different profile.",+ json_mode=False,+ )+ raise SystemExit(1)++ # Sleep briefly to avoid busy-waiting+ await asyncio.sleep(0.5)+ except asyncio.CancelledError:+ pass++ try:+ asyncio.run(run_serve())+ except FileNotFoundError as e:+ output_error(+ str(e),+ hint="Install Chrome or specify the path with --chrome-path.",+ json_mode=json_output,+ )+ raise SystemExit(1)+ except TimeoutError as e:+ output_error(+ str(e),+ hint="Chrome may have failed to start. Check if the port is available.",+ json_mode=json_output,+ )+ raise SystemExit(1)+ except KeyboardInterrupt:+ pass # Normal shutdown via Ctrl+C+ except Exception as e:+ output_error(str(e), hint="Failed to launch Chrome or unified server.", json_mode=json_output)+ raise SystemExit(1)+ finally:+ # Restore signal handlers+ signal.signal(signal.SIGINT, original_sigint)+ signal.signal(signal.SIGTERM, original_sigterm)++ if not json_output:+ output({"status": "shutting_down"}, action="serve_shutdown", json_mode=False)++ # Stop unified server+ if unified_server is not None:+ asyncio.run(unified_server.stop())++ # Clean up browser+ if browser_info is not None:+ terminate_browser(browser_info)++ if not json_output:+ output({"status": "stopped"}, action="serve_stopped", json_mode=False)+++def _print_serve_instructions_unified(result: dict[str, Any], browser_path: str) -> None:+ """Print user-friendly instructions for using the unified server."""+ from rich.panel import Panel++ from skyvern.cli.console import console++ console.print()+ console.print(+ Panel(+ "[bold green]Unified Browser Server Running[/bold green]",+ border_style="green",+ expand=False,+ )+ )+ console.print()+ console.print(f" [bold]Browser ID:[/bold] [cyan]{result['browser_id']}[/cyan]")+ console.print(f" [bold]Server URL:[/bold] [cyan]{result['server_url']}[/cyan]")+ console.print(f" [bold]CDP WebSocket URL:[/bold] [cyan]{result['cdp_ws_url']}[/cyan]")+ console.print(f" [bold]Port:[/bold] [cyan]{result['port']}[/cyan]")+ console.print(f" [bold]Profile directory:[/bold] [cyan]{result['profile_dir']}[/cyan]")+ console.print(+ f" [bold]Authentication:[/bold] [cyan]{'Enabled' if result['auth_enabled'] else 'Disabled'}[/cyan]"+ )+ console.print()++ console.print("[bold yellow]Endpoints:[/bold yellow]")+ console.print()+ console.print(" [bold]CDP Proxy:[/bold]")+ console.print(" GET /json - CDP browser info")+ console.print(" GET /json/list - List browser targets")+ console.print(" WS /devtools/... - CDP WebSocket connection")+ console.print()++ console.print("[bold yellow]Next steps:[/bold yellow]")+ console.print()+ console.print(f" [bold]1.[/bold] Set up a single HTTP tunnel (port {result['port']}):")+ console.print()+ console.print(f" [green]ngrok http {result['port']}[/green]")+ console.print()++ console.print(" [bold]2.[/bold] Use the tunnel URL for browser_address in your task:")+ console.print()+ console.print(f" [cyan]wss://YOUR_TUNNEL_URL/devtools/browser/{browser_path}[/cyan]")+ console.print()+ console.print(" [dim](Replace YOUR_TUNNEL_URL with the ngrok URL)[/dim]")+ console.print()++ console.print("[bold]Press Ctrl+C to stop.[/bold]")+ console.print()diff --git a/skyvern/cli/core/browser_launcher.py b/skyvern/cli/core/browser_launcher.pynew file mode 100644index 000000000..cf097ea49--- /dev/null+++ b/skyvern/cli/core/browser_launcher.py@@ -0,0 +1,205 @@+"""Chrome browser launcher for CDP-based browser serve command."""++from __future__ import annotations++import asyncio+import platform+import subprocess+import uuid+from dataclasses import dataclass+from pathlib import Path+from typing import TYPE_CHECKING++import httpx++if TYPE_CHECKING:+ from subprocess import Popen++# Default Skyvern directory for browser data+SKYVERN_DATA_DIR = Path.home() / ".skyvern"+++@dataclass+class LocalBrowserInfo:+ """Information about a locally launched browser instance."""++ cdp_ws_url: str+ profile_dir: str+ process: Popen[bytes]+++def generate_browser_id() -> str:+ """Generate a unique browser ID for this browser instance."""+ return f"br_{uuid.uuid4().hex[:12]}"+++def get_default_chrome_path() -> str:+ """Get the default Chrome executable path based on the platform."""+ system = platform.system()++ paths: list[Path]+ if system == "Darwin":+ # macOS+ paths = [+ Path("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),+ Path("/Applications/Chromium.app/Contents/MacOS/Chromium"),+ Path.home() / "Applications/Google Chrome.app/Contents/MacOS/Google Chrome",+ ]+ elif system == "Windows":+ # Windows+ paths = [+ Path.home() / "AppData/Local/Google/Chrome/Application/chrome.exe",+ Path("C:/Program Files/Google/Chrome/Application/chrome.exe"),+ Path("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"),+ ]+ else:+ # Linux+ paths = [+ Path("/usr/bin/google-chrome"),+ Path("/usr/bin/google-chrome-stable"),+ Path("/usr/bin/chromium"),+ Path("/usr/bin/chromium-browser"),+ Path("/snap/bin/chromium"),+ ]++ for path in paths:+ if path.exists():+ return str(path)++ raise FileNotFoundError(+ f"Chrome executable not found. Searched paths: {paths}. Install Chrome or specify the path with --chrome-path."+ )+++def get_default_profile_dir() -> str:+ """Get the default Chrome profile directory."""+ profile_dir = SKYVERN_DATA_DIR / "chrome-profile"+ profile_dir.mkdir(parents=True, exist_ok=True)+ return str(profile_dir)+++def get_default_download_dir(browser_id: str) -> str:+ """Get the default download directory for a browser instance."""+ download_dir = SKYVERN_DATA_DIR / "downloads" / browser_id+ download_dir.mkdir(parents=True, exist_ok=True)+ return str(download_dir)+++async def launch_chrome_with_cdp(+ port: int,+ profile_dir: str | None = None,+ headless: bool = False,+ chrome_path: str | None = None,+ download_dir: str | None = None,+) -> LocalBrowserInfo:+ """Launch Chrome with CDP enabled and wait for it to be ready.++ Args:+ port: The port for Chrome's CDP server.+ profile_dir: Chrome user data directory. Uses default if not specified.+ headless: Whether to run in headless mode.+ chrome_path: Path to Chrome executable. Auto-detects if not specified.+ download_dir: Directory for downloads. Uses default if not specified.++ Returns:+ LocalBrowserInfo with connection details.++ Raises:+ FileNotFoundError: If Chrome executable is not found.+ TimeoutError: If Chrome fails to start within timeout.+ """+ resolved_chrome_path = chrome_path or get_default_chrome_path()+ resolved_profile_dir = profile_dir or get_default_profile_dir()++ # Build Chrome args+ args = [+ resolved_chrome_path,+ f"--remote-debugging-port={port}",+ f"--user-data-dir={resolved_profile_dir}",+ "--no-first-run",+ "--no-default-browser-check",+ "--disable-background-networking",+ "--disable-sync",+ "--disable-translate",+ "--metrics-recording-only",+ ]++ if headless:+ args.append("--headless=new")++ if download_dir:+ # Ensure download directory exists+ Path(download_dir).mkdir(parents=True, exist_ok=True)++ # Launch Chrome process+ process = subprocess.Popen(+ args,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )++ # Wait for CDP to be ready+ cdp_ws_url = await _wait_for_cdp_ready(port, timeout=30)++ return LocalBrowserInfo(+ cdp_ws_url=cdp_ws_url,+ profile_dir=resolved_profile_dir,+ process=process,+ )+++async def _wait_for_cdp_ready(port: int, timeout: int = 30) -> str:+ """Wait for Chrome's CDP server to be ready and return the WebSocket URL.++ Args:+ port: CDP port to poll.+ timeout: Max seconds to wait.++ Returns:+ CDP WebSocket URL for browser connection.++ Raises:+ TimeoutError: If CDP doesn't become ready within timeout.+ """+ url = f"http://127.0.0.1:{port}/json/version"+ deadline = asyncio.get_event_loop().time() + timeout++ async with httpx.AsyncClient() as client:+ while asyncio.get_event_loop().time() < deadline:+ try:+ response = await client.get(url, timeout=2)+ if response.status_code == 200:+ data = response.json()+ ws_url = data.get("webSocketDebuggerUrl")+ if ws_url:+ return ws_url+ except (httpx.RequestError, httpx.TimeoutException):+ pass++ await asyncio.sleep(0.5)++ raise TimeoutError(f"Chrome CDP did not become ready on port {port} within {timeout}s")+++def terminate_browser(browser_info: LocalBrowserInfo) -> None:+ """Terminate the browser process gracefully.++ Args:+ browser_info: The browser info containing the process to terminate.+ """+ process = browser_info.process++ if process.poll() is not None:+ # Process already exited+ return++ # Try graceful termination first+ process.terminate()++ try:+ # Wait up to 5 seconds for graceful shutdown+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ # Force kill if it doesn't respond+ process.kill()+ process.wait(timeout=2)diff --git a/skyvern/cli/core/unified_server.py b/skyvern/cli/core/unified_server.pynew file mode 100644index 000000000..0dba53613--- /dev/null+++ b/skyvern/cli/core/unified_server.py@@ -0,0 +1,187 @@+"""Unified HTTP/WebSocket server for browser serve command.++This server provides:+- CDP WebSocket proxy at /devtools/*+- CDP JSON API at /json/*+"""++from __future__ import annotations++from dataclasses import dataclass++import httpx+from aiohttp import WSMsgType, web+++@dataclass+class UnifiedServerConfig:+ """Configuration for the unified server."""++ port: int+ chrome_cdp_port: int+ api_key: str | None = None+++class UnifiedServer:+ """Unified HTTP/WebSocket server that proxies CDP connections."""++ def __init__(self, config: UnifiedServerConfig) -> None:+ self.config = config+ self.app = web.Application(middlewares=[self._auth_middleware])+ self._setup_routes()+ self._runner: web.AppRunner | None = None+ self._site: web.TCPSite | None = None++ @web.middleware+ async def _auth_middleware(self, request: web.Request, handler: web.RequestHandler) -> web.StreamResponse:+ """Check API key if configured."""+ if self.config.api_key:+ provided_key = request.headers.get("x-api-key")+ if provided_key != self.config.api_key:+ return web.json_response(+ {"error": "Unauthorized", "message": "Invalid or missing x-api-key"},+ status=401,+ )+ return await handler(request)++ def _setup_routes(self) -> None:+ """Set up all routes for the unified server."""+ # CDP JSON API routes (with and without trailing slashes)+ self.app.router.add_get("/json", self._handle_json)+ self.app.router.add_get("/json/", self._handle_json)+ self.app.router.add_get("/json/version", self._handle_json_version)+ self.app.router.add_get("/json/version/", self._handle_json_version)+ self.app.router.add_get("/json/list", self._handle_json_list)+ self.app.router.add_get("/json/list/", self._handle_json_list)+ self.app.router.add_get("/json/protocol", self._handle_json_protocol)+ self.app.router.add_get("/json/protocol/", self._handle_json_protocol)++ # CDP WebSocket proxy+ self.app.router.add_route("GET", "/devtools/{path:.*}", self._handle_devtools_ws)++ # Health check+ self.app.router.add_get("/health", self._handle_health)++ async def start(self) -> None:+ """Start the unified server."""+ self._runner = web.AppRunner(self.app)+ await self._runner.setup()+ self._site = web.TCPSite(self._runner, "0.0.0.0", self.config.port)+ await self._site.start()++ async def stop(self) -> None:+ """Stop the unified server."""+ if self._runner:+ await self._runner.cleanup()++ # -------------------------------------------------------------------------+ # CDP JSON API handlers+ # -------------------------------------------------------------------------++ async def _proxy_json_endpoint(self, endpoint: str) -> web.Response:+ """Proxy a request to Chrome's CDP JSON API."""+ url = f"http://127.0.0.1:{self.config.chrome_cdp_port}{endpoint}"+ async with httpx.AsyncClient() as client:+ try:+ response = await client.get(url, timeout=10)+ data = response.json()++ # Rewrite WebSocket URLs to point to our proxy+ if isinstance(data, list):+ for item in data:+ self._rewrite_ws_urls(item)+ elif isinstance(data, dict):+ self._rewrite_ws_urls(data)++ return web.json_response(data)+ except httpx.RequestError as e:+ return web.json_response(+ {"error": "CDP connection failed", "message": str(e)},+ status=502,+ )++ def _rewrite_ws_urls(self, data: dict) -> None:+ """Rewrite Chrome's CDP WebSocket URLs to point to our proxy."""+ for key in ["webSocketDebuggerUrl", "devtoolsFrontendUrl"]:+ if key in data and data[key]:+ # Replace Chrome's internal port with our proxy port+ data[key] = data[key].replace(+ f"127.0.0.1:{self.config.chrome_cdp_port}",+ f"127.0.0.1:{self.config.port}",+ )++ async def _handle_json(self, request: web.Request) -> web.Response:+ """Handle /json endpoint."""+ return await self._proxy_json_endpoint("/json")++ async def _handle_json_version(self, request: web.Request) -> web.Response:+ """Handle /json/version endpoint."""+ return await self._proxy_json_endpoint("/json/version")++ async def _handle_json_list(self, request: web.Request) -> web.Response:+ """Handle /json/list endpoint."""+ return await self._proxy_json_endpoint("/json/list")++ async def _handle_json_protocol(self, request: web.Request) -> web.Response:+ """Handle /json/protocol endpoint."""+ return await self._proxy_json_endpoint("/json/protocol")++ # -------------------------------------------------------------------------+ # CDP WebSocket proxy handler+ # -------------------------------------------------------------------------++ async def _handle_devtools_ws(self, request: web.Request) -> web.WebSocketResponse:+ """Proxy WebSocket connections to Chrome's CDP."""+ import asyncio++ import aiohttp++ path = request.match_info["path"]+ chrome_ws_url = f"ws://127.0.0.1:{self.config.chrome_cdp_port}/devtools/{path}"++ # Set up client-facing WebSocket+ ws_client = web.WebSocketResponse()+ await ws_client.prepare(request)++ # Connect to Chrome's CDP WebSocket+ async with aiohttp.ClientSession() as session:+ try:+ async with session.ws_connect(chrome_ws_url) as ws_chrome:+ # Bidirectional message relay+ async def relay_client_to_chrome() -> None:+ async for msg in ws_client:+ if msg.type == WSMsgType.TEXT:+ await ws_chrome.send_str(msg.data)+ elif msg.type == WSMsgType.BINARY:+ await ws_chrome.send_bytes(msg.data)+ elif msg.type in (WSMsgType.CLOSE, WSMsgType.ERROR):+ break++ async def relay_chrome_to_client() -> None:+ async for msg in ws_chrome:+ if msg.type == WSMsgType.TEXT:+ await ws_client.send_str(msg.data)+ elif msg.type == WSMsgType.BINARY:+ await ws_client.send_bytes(msg.data)+ elif msg.type in (WSMsgType.CLOSE, WSMsgType.ERROR):+ break++ # Run both relay tasks concurrently+ await asyncio.gather(+ relay_client_to_chrome(),+ relay_chrome_to_client(),+ return_exceptions=True,+ )+ except aiohttp.ClientError as e:+ if not ws_client.closed:+ await ws_client.close(code=1011, message=str(e).encode())++ return ws_client++ # -------------------------------------------------------------------------+ # Health check+ # -------------------------------------------------------------------------++ async def _handle_health(self, request: web.Request) -> web.Response:+ """Health check endpoint."""+ return web.json_response({"status": "ok"})diff --git a/skyvern/forge/sdk/artifact/storage/azure.py b/skyvern/forge/sdk/artifact/storage/azure.pyindex 3b35e3eb5..506825d97 100644--- a/skyvern/forge/sdk/artifact/storage/azure.py+++ b/skyvern/forge/sdk/artifact/storage/azure.py@@ -19,7 +19,10 @@ from skyvern.forge.sdk.api.files import ()from skyvern.forge.sdk.api.real_azure import RealAsyncAzureStorageClientfrom skyvern.forge.sdk.artifact.models import Artifact, ArtifactType, LogEntityType-from skyvern.forge.sdk.artifact.storage.base import FILE_EXTENTSION_MAP, BaseStorage+from skyvern.forge.sdk.artifact.storage.base import (+ FILE_EXTENTSION_MAP,+ BaseStorage,+)from skyvern.forge.sdk.models import Stepfrom skyvern.forge.sdk.schemas.ai_suggestions import AISuggestionfrom skyvern.forge.sdk.schemas.files import FileInfo@@ -351,12 +354,34 @@ class AzureStorage(BaseStorage):file_infos.sort(key=lambda f: (f.modified_at is not None, f.modified_at), reverse=True)return file_infos- async def save_downloaded_files(self, organization_id: str, run_id: str | None) -> None:- download_dir = get_download_dir(run_id=run_id)- files = os.listdir(download_dir)+ async def save_downloaded_files(+ self,+ organization_id: str,+ run_id: str | None,+ ) -> None:tier = await self._get_storage_tier_for_org(organization_id)tags = await self._get_tags_for_org(organization_id)base_uri = f"azure://{settings.AZURE_STORAGE_CONTAINER_UPLOADS}/{DOWNLOAD_FILE_PREFIX}/{settings.ENV}/{organization_id}/{run_id}"++ await self._save_downloaded_files_from_local(+ organization_id=organization_id,+ base_uri=base_uri,+ run_id=run_id,+ tier=tier,+ tags=tags,+ )++ async def _save_downloaded_files_from_local(+ self,+ organization_id: str,+ base_uri: str,+ run_id: str | None,+ tier: StandardBlobTier,+ tags: dict[str, str] | None,+ ) -> None:+ """Save files from local download directory to Azure."""+ download_dir = get_download_dir(run_id=run_id)+ files = os.listdir(download_dir)for file in files:fpath = os.path.join(download_dir, file)if not os.path.isfile(fpath):diff --git a/skyvern/forge/sdk/artifact/storage/base.py b/skyvern/forge/sdk/artifact/storage/base.pyindex e4d6f2ec7..2154e8f23 100644--- a/skyvern/forge/sdk/artifact/storage/base.py+++ b/skyvern/forge/sdk/artifact/storage/base.py@@ -161,7 +161,11 @@ class BaseStorage(ABC):pass@abstractmethod- async def save_downloaded_files(self, organization_id: str, run_id: str | None) -> None:+ async def save_downloaded_files(+ self,+ organization_id: str,+ run_id: str | None,+ ) -> None:pass@abstractmethoddiff --git a/skyvern/forge/sdk/artifact/storage/s3.py b/skyvern/forge/sdk/artifact/storage/s3.pyindex 426549c48..4d5f1488d 100644--- a/skyvern/forge/sdk/artifact/storage/s3.py+++ b/skyvern/forge/sdk/artifact/storage/s3.py@@ -19,7 +19,10 @@ from skyvern.forge.sdk.api.files import (unzip_files,)from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType, LogEntityType-from skyvern.forge.sdk.artifact.storage.base import FILE_EXTENTSION_MAP, BaseStorage+from skyvern.forge.sdk.artifact.storage.base import (+ FILE_EXTENTSION_MAP,+ BaseStorage,+)from skyvern.forge.sdk.models import Stepfrom skyvern.forge.sdk.schemas.ai_suggestions import AISuggestionfrom skyvern.forge.sdk.schemas.files import FileInfo@@ -363,13 +366,33 @@ class S3Storage(BaseStorage):file_infos.sort(key=lambda f: (f.modified_at is not None, f.modified_at), reverse=True)return file_infos- async def save_downloaded_files(self, organization_id: str, run_id: str | None) -> None:- download_dir = get_download_dir(run_id=run_id)- files = os.listdir(download_dir)+ async def save_downloaded_files(+ self,+ organization_id: str,+ run_id: str | None,+ ) -> None:sc = await self._get_storage_class_for_org(organization_id, settings.AWS_S3_BUCKET_UPLOADS)base_uri = (f"s3://{settings.AWS_S3_BUCKET_UPLOADS}/{DOWNLOAD_FILE_PREFIX}/{settings.ENV}/{organization_id}/{run_id}")++ await self._save_downloaded_files_from_local(+ organization_id=organization_id,+ run_id=run_id,+ base_uri=base_uri,+ storage_class=sc,+ )++ async def _save_downloaded_files_from_local(+ self,+ organization_id: str,+ run_id: str | None,+ base_uri: str,+ storage_class: S3StorageClass,+ ) -> None:+ """Save files from local download directory to S3."""+ download_dir = get_download_dir(run_id=run_id)+ files = os.listdir(download_dir)for file in files:fpath = os.path.join(download_dir, file)if not os.path.isfile(fpath):@@ -381,14 +404,14 @@ class S3Storage(BaseStorage):file=file,checksum=checksum,organization_id=organization_id,- storage_class=sc,+ storage_class=storage_class,)# Upload file with checksum metadataawait self.async_client.upload_file_from_path(uri=uri,file_path=fpath,metadata={"sha256_checksum": checksum, "original_filename": file},- storage_class=sc,+ storage_class=storage_class,)async def get_downloaded_files(self, organization_id: str, run_id: str | None) -> list[FileInfo]:diff --git a/skyvern/webeye/browser_factory.py b/skyvern/webeye/browser_factory.pyindex 9e8be07a3..3d76f16f3 100644--- a/skyvern/webeye/browser_factory.py+++ b/skyvern/webeye/browser_factory.py@@ -31,6 +31,7 @@ from skyvern.forge.sdk.api.files import get_download_dir, make_temp_directoryfrom skyvern.forge.sdk.core.skyvern_context import current, ensure_contextfrom skyvern.schemas.runs import ProxyLocation, get_tzinfo_from_proxyfrom skyvern.webeye.browser_artifacts import BrowserArtifacts, VideoArtifact+from skyvern.webeye.cdp_download_interceptor import CDPDownloadInterceptorLOG = structlog.get_logger()@@ -637,6 +638,12 @@ async def _connect_to_cdp_browser(extra_http_headers: dict[str, str] | None = None,apply_download_behaviour: bool = False,) -> tuple[BrowserContext, BrowserArtifacts, BrowserCleanupFunc]:+ # Check if CDP download interception is enabled and remove from headers+ # so it doesn't get sent as an actual HTTP header+ enable_download: bool = False+ if extra_http_headers:+ enable_download = bool(extra_http_headers.pop("enable_download", None))+browser_args = BrowserContextFactory.build_browser_args(extra_http_headers=extra_http_headers)browser_artifacts = BrowserContextFactory.build_browser_artifacts(@@ -662,6 +669,34 @@ async def _connect_to_cdp_browser(viewport=browser_args["viewport"],extra_http_headers=browser_args["extra_http_headers"],)++ # Enable CDPDownloadInterceptor when enable_download is set.+ # This captures downloads via the Fetch domain and saves them locally.+ if enable_download:+ download_dir = initialize_download_dir()+ interceptor = CDPDownloadInterceptor(output_dir=download_dir)++ # Enable interception on all existing pages+ for page in browser_context.pages:+ try:+ await interceptor.enable_for_page(page)+ except Exception:+ LOG.warning("Failed to enable CDP intercept on page", page_url=page.url, exc_info=True)++ # Auto-enable interception on new pages (e.g., target="_blank" links)+ async def _on_new_page(page: Page) -> None:+ try:+ await interceptor.enable_for_page(page)+ except Exception:+ LOG.warning("Failed to enable CDP intercept on new page", page_url=page.url, exc_info=True)++ browser_context.on("page", lambda page: asyncio.ensure_future(_on_new_page(page)))+ LOG.info(+ "CDP download interceptor enabled",+ download_dir=download_dir,+ existing_page_count=len(browser_context.pages),+ )+LOG.info("Launched browser CDP connection",remote_browser_url=remote_browser_url,diff --git a/skyvern/webeye/cdp_download_interceptor.py b/skyvern/webeye/cdp_download_interceptor.pyindex 28f1ce2cc..0a1e9b9fe 100644--- a/skyvern/webeye/cdp_download_interceptor.py+++ b/skyvern/webeye/cdp_download_interceptor.py@@ -243,7 +243,8 @@ class CDPDownloadInterceptor:"""Async handler for paused requests."""request_id = event["requestId"]response_status = event.get("responseStatusCode", 0)- response_headers = _parse_headers(event.get("responseHeaders", []))+ raw_response_headers = event.get("responseHeaders", [])+ response_headers = _parse_headers(raw_response_headers)url = event.get("request", {}).get("url", "<unknown>")resource_type = event.get("resourceType", "")@@ -257,7 +258,9 @@ class CDPDownloadInterceptor:content_type=response_headers.get("content-type", ""),content_disposition=response_headers.get("content-disposition", ""),)- await self._handle_download(cdp_session, request_id, url, response_headers)+ await self._handle_download(+ cdp_session, request_id, url, response_headers, response_status, raw_response_headers+ )else:await self._continue_response(cdp_session, request_id)except Exception as e:@@ -283,8 +286,10 @@ class CDPDownloadInterceptor:request_id: str,url: str,headers: dict[str, str],+ response_status: int,+ raw_response_headers: list[dict[str, str]],) -> None:- """Extract a download file and save it to disk."""+ """Extract a download file, save it to disk, and replay the response to the browser."""if not self._output_dir:LOG.warning("CDP download intercepted but no output_dir set, passing through", url=url)await self._continue_response(cdp_session, request_id)@@ -376,27 +381,33 @@ class CDPDownloadInterceptor:passreturn- # Block the browser from saving the file locally by fulfilling with an empty response.- # After body extraction (especially via takeResponseBodyAsStream), failRequest may- # return "Invalid parameters". fulfillRequest with empty body works reliably.+ # Replay the original response to the browser so it also gets the download.+ # After body extraction, we fulfill with the same status, headers, and body.try:- await self._fulfill_empty(cdp_session, request_id)+ await self._fulfill_with_body(cdp_session, request_id, response_status, raw_response_headers, data)except Exception as e:LOG.warning("fulfillRequest failed after download", filename=filename, url=url, error=str(e))- try:- await self._continue_response(cdp_session, request_id)- except Exception:- pass+ # Can't continue response after body extraction, just log the error++ async def _fulfill_with_body(+ self,+ cdp_session: CDPSession,+ request_id: str,+ response_status: int,+ raw_response_headers: list[dict[str, str]],+ body: bytes,+ ) -> None:+ """Fulfill a request by replaying the original response with the extracted body.- async def _fulfill_empty(self, cdp_session: CDPSession, request_id: str) -> None:- """Fulfill a request with an empty response to block browser-side download."""+ This allows both server-side capture AND browser-side download to happen.+ """await cdp_session.send("Fetch.fulfillRequest",{"requestId": request_id,- "responseCode": 200,- "responseHeaders": [{"name": "Content-Type", "value": "text/plain"}],- "body": base64.b64encode(b"").decode(),+ "responseCode": response_status,+ "responseHeaders": raw_response_headers,+ "body": base64.b64encode(body).decode(),},)