### Local Development Setup Source: https://github.com/cloudflare/moltworker/blob/main/AGENTS.md To set up the local development environment, first install the project dependencies using npm. Then, copy the example environment variables file and edit it with your specific API key. Finally, start the local development server using the `npm run start` command. ```bash npm install cp .dev.vars.example .dev.vars # Edit .dev.vars with your ANTHROPIC_API_KEY npm run start ``` -------------------------------- ### Start Moltworker Server Source: https://github.com/cloudflare/moltworker/blob/main/test/e2e/_setup.txt Starts the Moltworker server. It waits for the server to indicate it's ready by checking if the output ends with 'ready'. ```bash ./start-server -v ``` -------------------------------- ### Start Playwright Browser Source: https://github.com/cloudflare/moltworker/blob/main/test/e2e/_setup.txt Launches a Playwright browser instance. The command waits for the browser to be ready, indicated by the output ending with 'ready'. ```bash ./start-browser ``` -------------------------------- ### Cloudflare Browser Rendering - Script Examples Source: https://github.com/cloudflare/moltworker/blob/main/skills/cloudflare-browser/SKILL.md Provides examples of how to use the provided scripts for common browser automation tasks like taking screenshots and generating videos. ```APIDOC ## Cloudflare Browser Rendering - Script Examples ### Description This section provides command-line examples for using the utility scripts included with the Cloudflare Browser Rendering project to perform common tasks such as capturing screenshots and generating multi-page videos. ### Method Command Line Execution ### Endpoint N/A (Local script execution) ### Parameters #### Script Arguments Arguments vary per script. See individual script examples below. ### Script Examples #### 1. Screenshot Script Captures a screenshot of a given URL and saves it to a file. ##### Usage ```bash node /path/to/skills/cloudflare-browser/scripts/screenshot.js ``` ##### Example ```bash node /path/to/skills/cloudflare-browser/scripts/screenshot.js https://example.com output.png ``` #### 2. Multi-page Video Script Generates a video by navigating through a comma-separated list of URLs. ##### Usage ```bash node /path/to/skills/cloudflare-browser/scripts/video.js ",,..." ``` ##### Example ```bash node /path/to/skills/cloudflare-browser/scripts/video.js "https://site1.com,https://site2.com" output.mp4 ``` ### Request Example (N/A - These are command-line executions) ### Response #### Success Response - **Screenshot Script**: A PNG image file saved to the specified output path. - **Video Script**: An MP4 video file saved to the specified output path. #### Response Example (N/A - Output is file creation) ``` -------------------------------- ### Install Dependencies and Set Secrets with Wrangler Source: https://github.com/cloudflare/moltworker/blob/main/README.md This snippet demonstrates the initial setup steps for deploying OpenClaw on Cloudflare Workers. It covers installing project dependencies using npm and securely setting API keys and gateway tokens as secrets using the `wrangler` CLI. These secrets are essential for authentication and remote access to the deployed assistant. ```bash # Install dependencies npm install # Set your API key (direct Anthropic access) npx wrangler secret put ANTHROPIC_API_KEY # Or use Cloudflare AI Gateway instead (see "Optional: Cloudflare AI Gateway" below) # npx wrangler secret put CLOUDFLARE_AI_GATEWAY_API_KEY # npx wrangler secret put CF_AI_GATEWAY_ACCOUNT_ID # npx wrangler secret put CF_AI_GATEWAY_GATEWAY_ID # Generate and set a gateway token (required for remote access) # Save this token - you'll need it to access the Control UI export MOLTBOT_GATEWAY_TOKEN=$(openssl rand -hex 32) echo "Your gateway token: $MOLTBOT_GATEWAY_TOKEN" echo "$MOLTBOT_GATEWAY_TOKEN" | npx wrangler secret put MOLTBOT_GATEWAY_TOKEN ``` -------------------------------- ### Start Video Recording Source: https://github.com/cloudflare/moltworker/blob/main/test/e2e/_setup.txt Initiates video recording for the Playwright session. It confirms that video recording has started by checking if the output contains the specific string 'Video recording started'. ```bash ./pw --session=moltworker-e2e video-start ``` -------------------------------- ### Local Development Setup (.dev.vars) Source: https://context7.com/cloudflare/moltworker/llms.txt Sets up the local development environment by configuring a `.dev.vars` file. This file allows bypassing authentication and enabling debug routes for testing purposes, along with essential API keys and tokens. ```bash # .dev.vars file for local development DEV_MODE=true # Skip Cloudflare Access auth + bypass device pairing DEBUG_ROUTES=true # Enable /debug/* routes ANTHROPIC_API_KEY=sk-ant-... MOLTBOT_GATEWAY_TOKEN=your-dev-token # Start local development server npm run dev # Or run with wrangler directly npm run start ``` -------------------------------- ### Start video recording with Playwright CLI Source: https://github.com/cloudflare/moltworker/blob/main/test/e2e/README.md Initiates video recording for a specified session using the playwright-cli. This is useful for debugging and analyzing test runs. ```bash playwright-cli --session=test video-start ``` -------------------------------- ### Playwright CLI Browser Automation Commands Source: https://github.com/cloudflare/moltworker/blob/main/test/e2e/README.md Examples of using the playwright-cli tool for browser automation. The `open` command navigates to a URL, while `run-code` executes arbitrary JavaScript within the browser context. ```bash # Open a page playwright-cli --session=test open "https://example.com" # Run arbitrary Playwright code playwright-cli --session=test run-code "async page => { await page.waitForSelector('text=Hello'); }" ``` -------------------------------- ### Build and Deploy Worker Source: https://github.com/cloudflare/moltworker/blob/main/AGENTS.md The project provides npm scripts for common development tasks. `npm run build` compiles the worker and client assets, while `npm run deploy` builds the project and deploys it to Cloudflare. For local testing of the worker, use `npm run start` which utilizes `wrangler dev`. ```bash npm run build # Build worker + client npm run deploy # Build and deploy to Cloudflare npm run start # wrangler dev (local worker) ``` -------------------------------- ### Example: Setting ANTHROPIC_API_KEY Secret Source: https://github.com/cloudflare/moltworker/blob/main/src/assets/config-error.html This is an example of setting a specific environment secret, ANTHROPIC_API_KEY, using the Wrangler CLI. This command is used when the ANTHROPIC_API_KEY variable is reported as missing. ```bash wrangler secret put ANTHROPIC_API_KEY ``` -------------------------------- ### R2 API Token Creation and Secret Setup Source: https://github.com/cloudflare/moltworker/blob/main/README.md Instructions on how to create an R2 API token with necessary permissions and set the corresponding secrets using wrangler. ```APIDOC ## R2 API Token and Secret Setup ### Description This section details the steps to create an R2 API token in the Cloudflare Dashboard and configure the necessary secrets for your worker using `wrangler`. ### Method Manual configuration and `wrangler` CLI commands. ### Endpoint N/A ### Parameters N/A ### Request Example ```bash # Set R2 Access Key ID npx wrangler secret put R2_ACCESS_KEY_ID # Set R2 Secret Access Key npx wrangler secret put R2_SECRET_ACCESS_KEY # Set Cloudflare Account ID npx wrangler secret put CF_ACCOUNT_ID ``` ### Response N/A ### Success Response (200) N/A ### Response Example N/A ``` -------------------------------- ### cctr Test Case Example Source: https://github.com/cloudflare/moltworker/blob/main/test/e2e/README.md An example of a test case written in cctr's plain text format. It demonstrates capturing output into variables and using them to execute Playwright commands. The `%require` directive is used to conditionally skip tests. ```text === navigate to admin page to approve device %require === TOKEN=$(cat "$CCTR_FIXTURE_DIR/gateway-token.txt") WORKER_URL=$(cat "$CCTR_FIXTURE_DIR/worker-url.txt") ./pw --session=moltworker-e2e open "$WORKER_URL/_admin/?token=$TOKEN" --- ``` -------------------------------- ### Start OpenClaw Process with URL Source: https://github.com/cloudflare/moltworker/blob/main/AGENTS.md When invoking the OpenClaw CLI from within the worker, it's crucial to include the `--url ws://localhost:18789` flag. This ensures the CLI connects to the correct WebSocket endpoint for communication. CLI commands may take a significant amount of time to complete due to WebSocket connection overhead. ```typescript sandbox.startProcess('openclaw devices list --json --url ws://localhost:18789') ``` -------------------------------- ### Browser Automation (CDP) Setup and Endpoints Source: https://github.com/cloudflare/moltworker/blob/main/README.md Configuration and API endpoints for enabling browser automation capabilities via a Chrome DevTools Protocol (CDP) shim. ```APIDOC ## Optional: Browser Automation (CDP) ### Description This section covers the setup and available endpoints for the Chrome DevTools Protocol (CDP) shim, enabling browser automation for tasks like web scraping and testing. ### Method `wrangler` CLI commands for setting secrets, followed by redeployment. API requests to specific endpoints. ### Endpoint - `GET /cdp/json/version` - `GET /cdp/json/list` - `GET /cdp/json/new` - `WS /cdp/devtools/browser/{id}` ### Parameters #### Setup Secrets - **CDP_SECRET** (string) - Required - A shared secret for authentication. - **WORKER_URL** (string) - Required - The public URL of your worker (e.g., `https://your-worker.workers.dev`). #### Query Parameters for Endpoints - **secret** (string) - Required - The value of `CDP_SECRET` for authentication. #### Path Parameters for WebSocket - **id** (string) - Required - The ID of the browser target. ### Request Example #### Setup ```bash # Set CDP Secret npx wrangler secret put CDP_SECRET # Enter a secure random string # Set Worker URL npx wrangler secret put WORKER_URL # Enter: https://your-worker.workers.dev # Redeploy npm run deploy ``` #### API Requests ```bash # Get browser version information GET /cdp/json/version?secret=YOUR_CDP_SECRET # List available browser targets GET /cdp/json/list?secret=YOUR_CDP_SECRET # Create a new browser target GET /cdp/json/new?secret=YOUR_CDP_SECRET # WebSocket connection for CDP commands WS /cdp/devtools/browser/YOUR_TARGET_ID?secret=YOUR_CDP_SECRET ``` ### Response #### Success Response (200) - **`/cdp/json/version`**: JSON object with browser version details. - **`/cdp/json/list`**: JSON array of available browser targets. - **`/cdp/json/new`**: JSON object representing the newly created browser target. #### Response Example ```json // Example for /cdp/json/version { "Browser": "CloudflareMoltWorker/1.0", "Protocol-Version": "1.3" } ``` ``` -------------------------------- ### Dump Gateway Logs for Debugging Source: https://github.com/cloudflare/moltworker/blob/main/test/e2e/_teardown.txt This script retrieves gateway process information and logs from a worker URL. It requires `curl-auth` and `jq` to be installed. It outputs the process status, stdout, and stderr, or an error message if the process is not found or logs cannot be parsed. ```shell WORKER_URL=$(cat "$CCTR_FIXTURE_DIR/worker-url.txt" 2>/dev/null || echo "") if [ -n "$WORKER_URL" ]; then PROCS=$(./curl-auth -s "$WORKER_URL/debug/processes" 2>/dev/null || echo "") PROC_ID=$(echo "$PROCS" | jq -r '[.processes[] | select(.command | contains("start-openclaw"))][0].id // empty' 2>/dev/null) if [ -n "$PROC_ID" ]; then echo "=== Gateway process logs ($PROC_ID) ===" LOGS=$(./curl-auth -s "$WORKER_URL/debug/logs?id=$PROC_ID" 2>/dev/null) echo "$LOGS" | jq -r '"STATUS: \(.process_status)\nSTDOUT: \(.stdout)\nSTDERR: \(.stderr)"' 2>/dev/null || echo "Failed to parse logs" else echo "No start-openclaw.sh process found" echo "Processes: $PROCS" fi else echo "No worker URL found" fi echo "dump complete" ``` -------------------------------- ### Deploy Worker with Wrangler (Bash) Source: https://context7.com/cloudflare/moltworker/llms.txt Configures and deploys the worker using Wrangler. This involves installing dependencies, setting required secrets for various integrations (API keys, tokens, Cloudflare Access details), and initiating the deployment process. ```bash # Install dependencies npm install # Set required secrets npx wrangler secret put ANTHROPIC_API_KEY # Your Anthropic API key npx wrangler secret put MOLTBOT_GATEWAY_TOKEN # openssl rand -hex 32 npx wrangler secret put CF_ACCESS_TEAM_DOMAIN # e.g., "myteam.cloudflareaccess.com" npx wrangler secret put CF_ACCESS_AUD # From Cloudflare Access application # Optional: R2 storage for persistence npx wrangler secret put R2_ACCESS_KEY_ID npx wrangler secret put R2_SECRET_ACCESS_KEY npx wrangler secret put CF_ACCOUNT_ID # Optional: Chat platform integrations npx wrangler secret put TELEGRAM_BOT_TOKEN npx wrangler secret put DISCORD_BOT_TOKEN npx wrangler secret put SLACK_BOT_TOKEN npx wrangler secret put SLACK_APP_TOKEN # Optional: Browser automation npx wrangler secret put CDP_SECRET # openssl rand -hex 32 npx wrangler secret put WORKER_URL # https://your-worker.workers.dev # Optional: Use Cloudflare AI Gateway instead of direct Anthropic npx wrangler secret put CLOUDFLARE_AI_GATEWAY_API_KEY npx wrangler secret put CF_AI_GATEWAY_ACCOUNT_ID npx wrangler secret put CF_AI_GATEWAY_GATEWAY_ID # Deploy npm run deploy ``` -------------------------------- ### Built-in Skills: cloudflare-browser Source: https://github.com/cloudflare/moltworker/blob/main/README.md Usage examples for the `cloudflare-browser` skill, which utilizes the CDP shim for browser automation tasks. ```APIDOC ## Built-in Skills: cloudflare-browser ### Description Documentation for the `cloudflare-browser` skill, which leverages the CDP shim to perform browser automation tasks like taking screenshots and creating videos from web pages. ### Method Node.js scripts executed within the container. ### Endpoint N/A (Scripts are executed locally within the container environment). ### Parameters #### Prerequisites - `CDP_SECRET` and `WORKER_URL` must be set (see [Browser Automation](#optional-browser-automation-cdp)). #### `screenshot.js` Parameters - **URL** (string) - Required - The URL to capture a screenshot from. - **output.png** (string) - Required - The filename for the output screenshot. #### `video.js` Parameters - **URLs** (string) - Required - Comma-separated list of URLs to capture frames from. - **output.mp4** (string) - Required - The filename for the output video. - **--scroll** (flag) - Optional - Enables scrolling to capture the full page. ### Request Example ```bash # Capture a screenshot of a URL node /root/clawd/skills/cloudflare-browser/scripts/screenshot.js https://example.com output.png # Create a video from multiple URLs node /root/clawd/skills/cloudflare-browser/scripts/video.js "https://site1.com,https://site2.com" output.mp4 --scroll ``` ### Response N/A ### Success Response (200) N/A ### Response Example N/A ``` -------------------------------- ### Navigate to Main Page and Wait for Worker Source: https://github.com/cloudflare/moltworker/blob/main/test/e2e/_setup.txt Navigates to the main page of the worker and waits for it to be ready. This involves setting up authentication tokens and URLs, then using Playwright to navigate and wait for a specific selector indicating the 'Pairing required' state. The process concludes by confirming the worker is ready. ```bash TOKEN=$(cat "$CCTR_FIXTURE_DIR/gateway-token.txt") WORKER_URL=$(cat "$CCTR_FIXTURE_DIR/worker-url.txt") # Use page.goto() instead of 'open' — 'open' creates a new browser process, # which loses the CF-Access headers set via setExtraHTTPHeaders in start-browser. ./pw --session=moltworker-e2e run-code "async page => { await page.goto('$WORKER_URL/?token=$TOKEN'); }" # Wait for pairing required message (worker shows loading screen first, then UI loads) ./pw --session=moltworker-e2e run-code "async page => { await page.waitForSelector('text=Pairing required', { timeout: 480000 }); }" echo "Worker is ready" ``` -------------------------------- ### Set Environment Secrets with Wrangler CLI Source: https://github.com/cloudflare/moltworker/blob/main/src/assets/config-error.html This command demonstrates how to set environment secrets for Moltworker using the Wrangler CLI. It requires the variable name as an argument. Ensure you have Wrangler installed and configured. ```bash wrangler secret put ``` -------------------------------- ### Local Development Environment Variables Source: https://github.com/cloudflare/moltworker/blob/main/AGENTS.md Defines environment variables for local development using a .dev.vars file. These variables control API keys, development mode, and debug route enablement. ```bash ANTHROPIC_API_KEY=sk-ant-... DEV_MODE=true # Skips CF Access auth + device pairing DEBUG_ROUTES=true # Enables /debug/* routes ``` -------------------------------- ### Get Moltworker Debug Logs (curl) Source: https://context7.com/cloudflare/moltworker/llms.txt Fetches logs for a specific process or the gateway using a JWT assertion. Requires a valid JWT and the process ID if targeting a specific process. ```bash # Get logs for a specific process or the gateway curl -H "CF-Access-Jwt-Assertion: " \ "https://your-worker.workers.dev/debug/logs?id=proc-123" ``` -------------------------------- ### Navigate to Admin Page and Approve Devices Source: https://github.com/cloudflare/moltworker/blob/main/test/e2e/pairing_and_conversation.txt Navigates to the Moltworker admin page using provided URLs and tokens, then waits for and clicks the 'Approve All' button to approve pending devices. This script requires gateway token and worker URLs to be pre-configured. ```bash TOKEN=$(cat "$CCTR_FIXTURE_DIR/gateway-token.txt") WORKER_URL=$(cat "$CCTR_FIXTURE_DIR/worker-url.txt") ./pw --session=moltworker-e2e run-code "async page => { await page.goto('$WORKER_URL/_admin/?token=$TOKEN'); }" ``` ```bash ./pw --session=moltworker-e2e run-code "async page => { await page.waitForSelector('text=Pending Pairing Requests', { timeout: 120000 }); }" ``` ```bash ./pw --session=moltworker-e2e run-code "async page => { const btn = await page.waitForSelector('button:has-text(\"Approve All\")', { timeout: 120000 }); await btn.click(); }" ``` ```bash ./pw --session=moltworker-e2e run-code "async page => { await page.waitForSelector('text=No pending pairing requests', { timeout: 120000 }); }" ``` -------------------------------- ### Execute Cloudflare Browser Skill for Video Creation Source: https://github.com/cloudflare/moltworker/blob/main/README.md This command executes the `video.js` skill from the `cloudflare-browser` skill set. It takes a comma-separated list of URLs and an output file path to create a video from the specified web pages. The `--scroll` flag enables scrolling during capture. ```bash node /root/clawd/skills/cloudflare-browser/scripts/video.js "https://site1.com,https://site2.com" output.mp4 --scroll ``` -------------------------------- ### Get CDP Browser Version and WebSocket URL (curl) Source: https://context7.com/cloudflare/moltworker/llms.txt Retrieves the browser version and the WebSocket URL for establishing CDP connections. Authentication is done via a shared secret query parameter. ```bash # Get browser version and WebSocket URL for CDP connections curl "https://your-worker.workers.dev/cdp/json/version?secret=YOUR_CDP_SECRET" ``` -------------------------------- ### Multi-page Video Script for Cloudflare Browser Source: https://github.com/cloudflare/moltworker/blob/main/skills/cloudflare-browser/SKILL.md A command-line script to capture a video by navigating through multiple specified URLs. The URLs are provided as a comma-separated string. The output is an MP4 video file. This script automates sequential page navigation and frame capture for video creation. ```bash node /path/to/skills/cloudflare-browser/scripts/video.js "https://site1.com,https://site2.com" output.mp4 ``` -------------------------------- ### Debugging Commands for Moltworker Source: https://github.com/cloudflare/moltworker/blob/main/AGENTS.md Provides bash commands for debugging Moltworker. 'wrangler tail' streams live logs, and 'wrangler secret list' displays available secrets. Debug routes can be enabled via an environment variable. ```bash # View live logs npx wrangler tail # Check secrets npx wrangler secret list ``` -------------------------------- ### Manage R2 Storage for Persistence (Bash) Source: https://context7.com/cloudflare/moltworker/llms.txt The storage API interacts with R2 persistent storage for OpenClaw, managing configuration, conversation history, and device data. It allows checking status, configuration, and triggering manual backups. ```bash # Check R2 storage status and last backup time curl -H "CF-Access-Jwt-Assertion: " \ https://your-worker.workers.dev/api/admin/storage # Response when configured: # { # "configured": true, # "lastSync": "2024-01-15T10:30:00Z", # "message": "R2 storage is configured. Your data will persist across container restarts." # } # Response when not configured: # { # "configured": false, # "missing": ["R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY", "CF_ACCOUNT_ID"], # "message": "R2 storage is not configured. Paired devices and conversations will be lost when the container restarts." # } # Trigger a manual backup to R2 curl -X POST \ -H "CF-Access-Jwt-Assertion: " \ https://your-worker.workers.dev/api/admin/storage/sync # Response: # {"success":true,"message":"Sync completed successfully","lastSync":"2024-01-15T12:00:00Z"} ``` -------------------------------- ### Cloudflare Browser Rendering - Common CDP Commands Source: https://github.com/cloudflare/moltworker/blob/main/skills/cloudflare-browser/SKILL.md Demonstrates how to use common Chrome DevTools Protocol (CDP) commands to interact with a headless browser controlled via the Cloudflare Browser Rendering worker. ```APIDOC ## Cloudflare Browser Rendering - Common CDP Commands ### Description This section details how to execute common CDP commands to control browser behavior, such as navigating to URLs, capturing screenshots, evaluating JavaScript, and setting viewport dimensions. These commands are sent over the established WebSocket connection. ### Method CDP Command (sent via WebSocket) ### Endpoint (Sent over the established WebSocket connection) ### Parameters #### Request Body (CDP Command Structure) - **id** (integer) - Required - A unique ID for the command request. - **method** (string) - Required - The CDP method to execute (e.g., `Page.navigate`, `Page.captureScreenshot`). - **params** (object) - Optional - Parameters specific to the CDP method. ### Key CDP Commands and Usage Examples #### 1. Page.navigate Navigates the browser to a specified URL. ##### Parameters - **url** (string) - Required - The URL to navigate to. ##### Request Example ```javascript // Assuming 'send' is a function that sends CDP commands over WebSocket await send('Page.navigate', { url: 'https://example.com' }); ``` #### 2. Page.captureScreenshot Captures a screenshot of the current page. ##### Parameters - **format** (string) - Optional - The format of the screenshot ('png' or 'jpeg'). Defaults to 'png'. - **quality** (integer) - Optional - JPEG quality (0-100). Only applicable for 'jpeg' format. ##### Request Example ```javascript // Wait for page to render after navigation await new Promise(r => setTimeout(r, 3000)); const { data } = await send('Page.captureScreenshot', { format: 'png' }); // 'data' will be a base64 encoded string of the image fs.writeFileSync('out.png', Buffer.from(data, 'base64')); ``` #### 3. Runtime.evaluate Executes arbitrary JavaScript code within the page's context. ##### Parameters - **expression** (string) - Required - The JavaScript expression to evaluate. ##### Request Example ```javascript await send('Runtime.evaluate', { expression: 'window.scrollBy(0, 300)' }); ``` #### 4. Emulation.setDeviceMetricsOverride Sets the viewport size and other device metrics. ##### Parameters - **width** (integer) - Required - Viewport width in pixels. - **height** (integer) - Required - Viewport height in pixels. - **deviceScaleFactor** (number) - Required - Device scale factor. - **mobile** (boolean) - Required - Whether the device is mobile. ##### Request Example ```javascript await send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 720, deviceScaleFactor: 1, mobile: false }); ``` ### Response #### Success Response (CDP Command Result) - **id** (integer) - The ID of the command request. - **result** (object) - The result of the command execution. Structure varies by command. #### Response Example (Page.captureScreenshot) ```json { "id": 1, "result": { "data": "iVBORw0KGgoAAAANSUhEUgAA..." } } ``` ``` -------------------------------- ### Dockerfile Cache Busting for OpenClaw Upgrade Source: https://github.com/cloudflare/moltworker/blob/main/AGENTS.md A comment in the Dockerfile used for cache busting. When the start-openclaw.sh script is modified, this version number should be incremented to ensure a fresh Docker image build. ```dockerfile # Build cache bust: 2026-02-06-v28-openclaw-upgrade ``` -------------------------------- ### Interact with Chat Interface Source: https://github.com/cloudflare/moltworker/blob/main/test/e2e/pairing_and_conversation.txt Waits for the chat interface to load, then sends a '/models' command and a math question. It also clicks the send button to submit the messages. This requires the chat interface to be accessible and functional. ```bash ./pw --session=moltworker-e2e run-code "async page => { await page.waitForSelector('textarea', { timeout: 120000 }); }" ``` ```bash ./pw --session=moltworker-e2e run-code "async page => { const textarea = await page.waitForSelector('textarea'); await textarea.fill('/models'); const btn = await page.waitForSelector('button:has-text(\"Send\")'); await btn.click(); }" ``` ```bash ./pw --session=moltworker-e2e run-code "async page => { const textarea = await page.waitForSelector('textarea'); await textarea.fill('What is 847293 + 651824? Reply with just the number.'); }" ``` ```bash ./pw --session=moltworker-e2e run-code "async page => { const btn = await page.waitForSelector('button:has-text(\"Send\")'); await btn.click(); }" ``` -------------------------------- ### Detect CLI Command Success Source: https://github.com/cloudflare/moltworker/blob/main/AGENTS.md The OpenClaw CLI indicates successful execution by outputting the string 'Approved' (case-sensitive). To reliably detect success, perform a case-insensitive check on the standard output (stdout) of the command. ```typescript stdout.toLowerCase().includes('approved') ``` -------------------------------- ### Manage Paired Devices via API (Bash) Source: https://context7.com/cloudflare/moltworker/llms.txt The device management API allows administrators to list, approve, and manage devices connected to OpenClaw. All requests require a valid Cloudflare Access JWT assertion. ```bash # List all pending and paired devices curl -H "CF-Access-Jwt-Assertion: " \ https://your-worker.workers.dev/api/admin/devices # Response: # { # "pending": [ # {"requestId": "req-123", "platform": "telegram", "displayName": "User Phone"} # ], # "paired": [ # {"deviceId": "dev-456", "platform": "discord", "displayName": "Desktop Client"} # ] # } # Approve a specific pending device curl -X POST \ -H "CF-Access-Jwt-Assertion: " \ https://your-worker.workers.dev/api/admin/devices/req-123/approve # Response: # {"success":true,"requestId":"req-123","message":"Device approved"} # Approve all pending devices at once curl -X POST \ -H "CF-Access-Jwt-Assertion: " \ https://your-worker.workers.dev/api/admin/devices/approve-all # Response: # {"approved":["req-123","req-456"],"failed":[],"message":"Approved 2 of 2 device(s)"} ``` -------------------------------- ### Navigate and Capture Screenshot with Cloudflare Browser Source: https://github.com/cloudflare/moltworker/blob/main/skills/cloudflare-browser/SKILL.md Demonstrates navigating to a specified URL and capturing a screenshot of the rendered page using CDP commands. It includes a delay to allow for page rendering before capturing. The screenshot is saved as a PNG file. Requires a CDP connection and a targetId. ```javascript await send('Page.navigate', { url: 'https://example.com' }); await new Promise(r => setTimeout(r, 3000)); // Wait for render const { data } = await send('Page.captureScreenshot', { format: 'png' }); fs.writeFileSync('out.png', Buffer.from(data, 'base64')); ``` -------------------------------- ### Take screenshot with Playwright CLI Source: https://github.com/cloudflare/moltworker/blob/main/test/e2e/README.md Captures a screenshot for a specified session using the playwright-cli. This is helpful for visual verification during automated tests. ```bash playwright-cli --session=test screenshot ``` -------------------------------- ### Run e2e tests with cctr Source: https://github.com/cloudflare/moltworker/blob/main/test/e2e/README.md Executes the end-to-end test suite using the `cctr` command. Supports running all tests, verbose output, specific test files, and real-time watching for debugging. ```bash cctr test/e2e/ ``` ```bash cctr test/e2e/ -v ``` ```bash cctr test/e2e/ -p pairing ``` ```bash cctr test/e2e/ -vv ``` -------------------------------- ### Access Debug Information (Bash) Source: https://context7.com/cloudflare/moltworker/llms.txt Debug endpoints provide insights into the container's state, including version information and running processes. These endpoints require the DEBUG_ROUTES environment variable to be enabled and Cloudflare Access authentication. ```bash # Get version information from the container curl -H "CF-Access-Jwt-Assertion: " \ https://your-worker.workers.dev/debug/version # Response: # {"moltbot_version":"OpenClaw v2026.2.3","node_version":"v20.10.0"} # List all container processes with optional logs curl -H "CF-Access-Jwt-Assertion: " \ "https://your-worker.workers.dev/debug/processes?logs=true" # Response: # { # "count": 2, # "processes": [ # { # "id": "proc-123", # "command": "/usr/local/bin/start-openclaw.sh", # "status": "running", # "startTime": "2024-01-15T10:00:00Z", ``` -------------------------------- ### Run Playwright code with custom wrapper Source: https://github.com/cloudflare/moltworker/blob/main/test/e2e/README.md Executes arbitrary Playwright JavaScript code within a specified session using a custom `./pw` wrapper. This wrapper handles a known playwright-cli bug where errors might not set a non-zero exit code, ensuring test failures are properly reported. ```bash ./pw --session=moltworker-e2e run-code "async page => { const btn = await page.waitForSelector('button:has-text(\"Approve All\")', { timeout: 120000 }); await btn.click(); }" ``` ```bash ./pw --session=moltworker-e2e run-code "async page => { await page.waitForSelector('text=No pending pairing requests', { timeout: 120000 }); }" ``` ```bash ./pw --session=moltworker-e2e run-code "async page => { const textarea = await page.waitForSelector('textarea'); await textarea.fill('What is 847293 + 651824? Reply with just the number.'); }" ``` ```bash ./pw --session=moltworker-e2e run-code "async page => { await page.waitForSelector('text=1499117', { timeout: 120000 }); }" ``` -------------------------------- ### Execute Cloudflare Browser Skill for Screenshot Source: https://github.com/cloudflare/moltworker/blob/main/README.md This command executes the `screenshot.js` skill from the `cloudflare-browser` skill set. It takes a URL and an output file path as arguments to capture a screenshot. ```bash node /root/clawd/skills/cloudflare-browser/scripts/screenshot.js https://example.com output.png ``` -------------------------------- ### Environment Configuration API Source: https://context7.com/cloudflare/moltworker/llms.txt View the sanitized environment configuration of the worker. Requires authentication via a JWT assertion. ```APIDOC ## GET /debug/env ### Description Retrieves a sanitized view of the worker's environment configuration. ### Method GET ### Endpoint `/debug/env` ### Request Example ```bash curl -H "CF-Access-Jwt-Assertion: " \ https://your-worker.workers.dev/debug/env ``` ### Response #### Success Response (200) - **has_anthropic_key** (boolean) - Indicates if an Anthropic API key is configured. - **has_gateway_token** (boolean) - Indicates if a gateway token is configured. - **has_r2_access_key** (boolean) - Indicates if an R2 access key is configured. - **dev_mode** (string) - The development mode status ('true' or 'false'). - **debug_routes** (string) - The debug routes status ('true' or 'false'). #### Response Example ```json { "has_anthropic_key": true, "has_gateway_token": true, "has_r2_access_key": true, "dev_mode": "false", "debug_routes": "true" } ``` ``` -------------------------------- ### Deploy Slack Integration with Wrangler Source: https://github.com/cloudflare/moltworker/blob/main/README.md This snippet shows how to set the `SLACK_BOT_TOKEN` and `SLACK_APP_TOKEN` secrets using Wrangler and then deploy the worker. This enables Slack notifications for the Moltworker. ```bash npx wrangler secret put SLACK_BOT_TOKEN npx wrangler secret put SLACK_APP_TOKEN npm run deploy ``` -------------------------------- ### Screenshot Script for Cloudflare Browser Source: https://github.com/cloudflare/moltworker/blob/main/skills/cloudflare-browser/SKILL.md A command-line script to capture a screenshot of a given URL using the cloudflare-browser skill. It takes the URL and output file path as arguments. This script automates the navigation and screenshot process. ```bash node /path/to/skills/cloudflare-browser/scripts/screenshot.js https://example.com output.png ``` -------------------------------- ### Save Video Recording Source: https://github.com/cloudflare/moltworker/blob/main/test/e2e/_teardown.txt This script saves any existing video recording files (with a .webm extension) from the ./.playwright-cli directory to a timestamped directory in /tmp/moltworker-e2e-videos. It creates the destination directory if it doesn't exist and always reports completion. ```shell mkdir -p /tmp/moltworker-e2e-videos datetime=$(date +%Y%m%d-%H%M%S) for f in ./.playwright-cli/*.webm; do if [ -f "$f" ]; then cp "$f" "/tmp/moltworker-e2e-videos/${datetime}.webm" echo "video saved to /tmp/moltworker-e2e-videos/${datetime}.webm" fi done # Always succeed even if no video echo "video cleanup complete" ``` -------------------------------- ### Control Headless Chrome via CDP WebSocket (JavaScript) Source: https://context7.com/cloudflare/moltworker/llms.txt Connects to the CDP WebSocket endpoint to control headless Chrome. This script demonstrates setting the viewport, navigating to a page, capturing a screenshot, evaluating JavaScript, and closing the browser. It requires the 'ws' and 'fs' Node.js modules and a CDP_SECRET environment variable. ```javascript const WebSocket = require('ws'); const fs = require('fs'); const CDP_SECRET = process.env.CDP_SECRET; const WS_URL = `wss://your-worker.workers.dev/cdp?secret=${encodeURIComponent(CDP_SECRET)}`; const ws = new WebSocket(WS_URL); let messageId = 1; let targetId = null; // Helper to send CDP commands function send(method, params = {}) { return new Promise((resolve, reject) => { const id = messageId++; const timeout = setTimeout(() => reject(new Error('Timeout')), 30000); const handler = (data) => { const msg = JSON.parse(data.toString()); if (msg.id === id) { clearTimeout(timeout); ws.off('message', handler); msg.error ? reject(new Error(msg.error.message)) : resolve(msg.result); } }; ws.on('message', handler); ws.send(JSON.stringify({ id, method, params })); }); } ws.on('open', async () => { console.log('Connected to CDP'); }); ws.on('message', async (data) => { const msg = JSON.parse(data.toString()); // Wait for target creation event if (msg.method === 'Target.targetCreated' && msg.params?.targetInfo?.type === 'page') { targetId = msg.params.targetInfo.targetId; console.log('Target created:', targetId); // Set viewport size await send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 720, deviceScaleFactor: 1, mobile: false }); // Navigate to a page await send('Page.navigate', { url: 'https://example.com' }); // Wait for page to render await new Promise(r => setTimeout(r, 3000)); // Capture screenshot const { data: screenshot } = await send('Page.captureScreenshot', { format: 'png' }); fs.writeFileSync('screenshot.png', Buffer.from(screenshot, 'base64')); console.log('Screenshot saved'); // Execute JavaScript on the page const { result } = await send('Runtime.evaluate', { expression: 'document.title', returnByValue: true }); console.log('Page title:', result.value); // Close the browser await send('Browser.close'); ws.close(); } }); ws.on('error', (err) => console.error('WebSocket error:', err)); ws.on('close', () => console.log('Connection closed')); ``` -------------------------------- ### Navigate to Main Chat Page Source: https://github.com/cloudflare/moltworker/blob/main/test/e2e/pairing_and_conversation.txt Navigates back to the main chat page of the Moltworker application using a gateway token and worker URL. This is typically done after completing administrative tasks. ```bash TOKEN=$(cat "$CCTR_FIXTURE_DIR/gateway-token.txt") WORKER_URL=$(cat "$CCTR_FIXTURE_DIR/worker-url.txt") ./pw --session=moltworker-e2e run-code "async page => { await page.goto('$WORKER_URL/?token=$TOKEN'); }" ```