### Start a Debugging Session (CLI) Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Getting-Started Launches a Chrome instance with the DevTools Protocol enabled, starts a background daemon, and opens the specified URL. This is the initial command to begin debugging. ```bash bdg example.com ``` -------------------------------- ### Example session.json Structure (JSON) Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Getting-Started Illustrates the expected structure of the `session.json` file, which contains details about a debugging session, including URL, timestamps, network requests, console messages, and performance metrics. ```json { "url": "https://example.com", "startTime": "2025-01-01T00:00:00.000Z", "endTime": "2025-01-01T00:05:30.000Z", "network": { "requests": [...], "summary": { "total": 42, "failed": 0 } }, "console": { "messages": [...] }, "performance": { "metrics": {...} } } ``` -------------------------------- ### Execute CDP Commands and Helpers (CLI) Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Getting-Started Demonstrates running specific CDP commands like Network.getCookies, Runtime.evaluate for executing JavaScript, and Page.captureScreenshot. Also shows high-level helper commands for DOM querying and activity monitoring. ```bash # Get cookies bdg cdp Network.getCookies # Execute JavaScript bdg cdp Runtime.evaluate --params '{"expression":"document.title","returnByValue":true}' # Take screenshot bdg cdp Page.captureScreenshot | jq -r '.data' | base64 -d > screenshot.png # Query DOM bdg dom query "button" # Find all buttons bdg dom get "button" # Get semantic info bdg dom get "button" --raw # Get raw HTML # Monitor activity bdg peek # Quick snapshot bdg peek --network # Network only bdg tail # Live updates ``` -------------------------------- ### Development Setup and Build Commands (Bash) Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/CLAUDE.md Installs dependencies, builds the project, and links the CLI for local development. Provides commands for compilation and running in watch mode for continuous development. Assumes Node.js and npm are installed. ```bash npm install && npm run build && npm link # Setup npm run build # Compile npm run watch # Dev mode bdg --help # Run (after npm link) ``` -------------------------------- ### Quick Start Examples for Browser Debugger CLI Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/README.md Demonstrates basic usage patterns for the browser-debugger-cli, including starting a session, discovering commands, executing CDP methods, using high-level helpers, and stopping the session. ```bash bdg example.com # Start session bdg cdp --search cookie # Discover commands bdg cdp Network.getCookies # Run any CDP method bdg dom query "button" # High-level helpers bdg stop # End session ``` -------------------------------- ### Explore Chrome DevTools Protocol (CDP) Commands (CLI) Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Getting-Started Provides commands to list all CDP domains, list methods within a specific domain, search for methods by keyword, and retrieve detailed information about a particular CDP method. ```bash # List all 53 CDP domains bdg cdp --list # List methods in a domain bdg cdp Network --list # Search for methods by keyword bdg cdp --search cookie # Get full details about a method bdg cdp Network.getCookies --describe ``` -------------------------------- ### Generating Command Examples Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/principles/SELF_DOCUMENTING_SYSTEMS.md Generates usage examples for a given domain, method, and schema. It creates examples for minimal usage (required parameters only), common patterns, and full usage (all parameters), providing agents with clear guidance on how to invoke commands. ```typescript function generateExamples( domain: string, method: string, schema: MethodSchema ): string[] { const examples: string[] = []; // Example 1: Minimal usage (required params only) const requiredParams = Object.entries(schema.parameters) .filter(([_, p]) => !p.optional) .map(([name, _]) => name); if (requiredParams.length === 0) { examples.push(`bdg cdp ${domain}.${method}`); } else { const params = buildMinimalParams(requiredParams, schema); examples.push(`bdg cdp ${domain}.${method} --params '${JSON.stringify(params)}'`); } // Example 2: Common usage pattern if (hasCommonPattern(domain, method)) { const params = getCommonPattern(domain, method); examples.push(`bdg cdp ${domain}.${method} --params '${JSON.stringify(params)}'`); } // Example 3: Full usage (all params) const fullParams = buildFullParams(schema.parameters); examples.push(`bdg cdp ${domain}.${method} --params '${JSON.stringify(fullParams)}'`); return examples; } ``` -------------------------------- ### Linux Chrome Installation (Debian/Ubuntu) Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Quick-Reference Instructions for installing Google Chrome stable on Debian-based Linux distributions using apt. This ensures the necessary browser environment is available for the CLI. ```bash sudo apt install google-chrome-stable ``` -------------------------------- ### Manage Debugging Sessions (CLI) Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Getting-Started Commands to stop an active debugging session and manage session files, including checking status verbosely and cleaning up stale files or forcefully killing Chrome processes. ```bash # Stop the Session bdg stop # Check Status bdg status # Basic info bdg status --verbose # Include Chrome diagnostics # Clean Up bdg cleanup # Remove stale files bdg cleanup --force # Force cleanup bdg cleanup --aggressive # Kill all Chrome processes ``` -------------------------------- ### Structured Context Output Examples Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/principles/AGENT_FRIENDLY_TOOLS.md Demonstrates different levels of context output for tool results, ranging from verbose text to structured JSON. The 'Best' example uses JSON for machine readability and efficient parsing by agents. ```json { "connection": "localhost:9222", "summary": { "total_requests": 47, "failed_requests": 3, "time_range_seconds": 30 }, "requests": [ { "id": "req_001", "method": "POST", "url": "/api/data", "status": 500, "duration_ms": 145 } ] } ``` -------------------------------- ### Performance Trace Analysis Examples Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/roadmap/DEVTOOLS_FRONTEND_EVALUATION.md Shows command-line examples for analyzing performance traces and extracting key metrics like Core Web Vitals. It supports specifying trace duration and outputting results in a human-readable format. ```bash bdg perf trace --duration 10s trace.json bdg perf vitals trace.json # Output: # LCP: 2.3s (good) # CLS: 0.15 (needs improvement) # INP: 450ms (poor) ``` -------------------------------- ### Install and Use Browser Debugger CLI (Bash) Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Home This snippet shows how to install the browser-debugger-cli using npm and perform basic operations like starting a session, listing CDP domains, searching for methods, executing CDP commands, and using high-level DOM helpers. It demonstrates the command-line interface for interacting with the browser. ```bash # Install npm install -g browser-debugger-cli@alpha # Start session bdg example.com # Explore what's possible bdg cdp --list # 53 CDP domains bdg cdp --search cookie # Find methods by keyword # Run any CDP command bdg cdp Network.getCookies # High-level helpers bdg dom query "button" bdg dom get 0 # Stop bdg stop ``` -------------------------------- ### DOM Query and Inspect Example Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/CLI_REFERENCE.md An example sequence demonstrating how to first query for an element using a data-test-id and then inspect its accessibility properties using its index. ```bash # Step 1: Query first (caches results) bdg dom query '[data-test-id="marketing-consent"]' # Step 2: Use index to inspect (0-based) bdg dom a11y describe 0 ``` -------------------------------- ### Workflow Example: Fill and Submit Form Source: https://context7.com/szymdzum/browser-debugger-cli/llms.txt Demonstrates a sequence of commands to fill form fields, interact with a checkbox, and submit the form. It includes a check for form readiness using `jq`. Dependencies: `jq`. ```bash # Get form readiness status bdg dom form --json | jq '.forms[0].summary.readyToSubmit' # Fill form fields bdg dom fill 0 "user@example.com" bdg dom fill 1 "SecurePass123" # Interact with elements bdg dom click 4 # Accept terms checkbox bdg dom click 6 # Submit button ``` -------------------------------- ### Semantic Search Implementation Example (Bash) Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/principles/SELF_DOCUMENTING_SYSTEMS.md Highlights the limitation of traditional command-line tools that rely solely on exact matches for finding commands. This serves as a contrast to the semantic search capabilities demonstrated elsewhere in the project. ```bash # Bad (exact match only): $ tool find "getCookie" Error: Method not found ``` -------------------------------- ### bdg Command Examples for Amazon Test Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/benchmarks/BENCHMARK_RESULTS_2025-11-23.md Provides examples of bdg commands utilized in the Amazon test case, demonstrating their effectiveness in interacting with potentially bot-protected sites and retrieving specific data, contributing to the overall token efficiency analysis. ```bash # Example commands for Amazon test (token counts are illustrative) bdg dom query "body" bdg network --list bdg dom tail ".product-title" ``` -------------------------------- ### Verify GitHub CLI Authentication Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/RELEASE_PROCESS.md Checks if the GitHub CLI is installed and authenticated to interact with GitHub repositories. This is a prerequisite for creating GitHub releases. ```bash gh auth status ``` -------------------------------- ### Comparison Example (Markdown Table) Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/benchmarks/BENCHMARK_PROMPT.md A markdown table comparing two browser automation tools, 'bdg' and 'Chrome MCP', across various metrics including commands, tokens, discovery, error handling, and composability. ```markdown | Metric | bdg | Chrome MCP | |--------|-----|------------| | **Avg Commands** | 8 | 4 | | **Avg Tokens** | 2,700 | 42,500 | | **Discovery** | CSS selectors | Accessibility UIDs | | **Error Handling** | Actionable suggestions | Basic confirmations | | **Composability** | Unix pipes ✓ | Limited | | **Network Monitoring** | Built-in | Separate tool call | | **Score** | 86/100 | 79/100 | ``` -------------------------------- ### Create GitHub Release using CLI Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/RELEASE_PROCESS.md Uses the GitHub CLI (`gh`) to create a new release, specifying the tag, title, and detailed release notes. The notes include an overview, highlights, changes, installation instructions, and a link to the full changelog. ```bash gh release create v0.X.Y \ --title "v0.X.Y" \ --notes "$(cat <<'EOF'\n## Overview\n\nBrief overview of the release.\n\n## 🎯 Highlights\n\n- Key feature 1\n- Key feature 2\n- Important fix\n\n## 🔧 Changes\n\n### Added\n- New feature descriptions\n\n### Changed\n- Modified behavior descriptions\n\n### Fixed\n- Bug fix descriptions\n\n## Installation\n\n```bash\nnpm install -g browser-debugger-cli@alpha\n```\n\n**Full Changelog**: https://github.com/szymdzum/browser-debugger-cli/compare/v0.X.Y-1...v0.X.Y\n'EOF)" ``` -------------------------------- ### TypeScript Contract Test Example Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/quality/TEST_GUIDE.md Demonstrates writing a contract test in TypeScript using node:test and assert/strict. It focuses on testing the public API of the `fetchCDPTargets` function, asserting its return type and behavior under different conditions (success and HTTP errors). ```typescript import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import { fetchCDPTargets } from '@/utils/http.js'; void describe('fetchCDPTargets()', () => { void it('returns array of targets when HTTP request succeeds', async () => { // Test the CONTRACT: function returns array on success const result = await fetchCDPTargets(9222); assert.ok(Array.isArray(result)); assert.ok(result.length > 0); }); void it('returns empty array on HTTP errors', async () => { // Test the PROPERTY: always returns array, never throws const result = await fetchCDPTargets(9999); // Bad port assert.ok(Array.isArray(result)); assert.equal(result.length, 0); }); }); ``` -------------------------------- ### JSON Output Format Example Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Commands Example of the JSON output structure for successful operations, including version, timestamp, target information, and data payload. ```json { "version": "0.6.0", "success": true, "timestamp": "2025-11-22T12:00:00.000Z", "duration": 1234, "target": { "url": "http://localhost:3000", "title": "App" }, "data": {...} } ``` -------------------------------- ### macOS Chrome Installation Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Quick-Reference Instructions for installing Google Chrome on macOS using Homebrew, a package manager for macOS. This is often a prerequisite for running the browser debugger CLI. ```bash brew install --cask google-chrome ``` -------------------------------- ### GitHub Actions CI/CD Workflow Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/tests/README.md A GitHub Actions workflow that checks out code, sets up Node.js, installs dependencies, builds the project, links it locally, and runs all tests. ```yaml name: Test Suite on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '20' - run: npm install - run: npm run build - run: npm link - run: ./tests/run-all-tests.sh ``` -------------------------------- ### Install Global Specific Version Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/RELEASE_PROCESS.md This command installs a specific version of the browser-debugger-cli globally on your system using npm. This is useful for testing or using a particular release of the tool. ```bash npm install -g browser-debugger-cli@0.X.Y ``` -------------------------------- ### CLI Command Parsing and Start Handler (TypeScript) Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/architecture/BDG_EXECUTION_FLOW.md Handles command-line argument parsing using Commander. It registers various commands, including 'start', and defines the action handler for the 'start' command. This handler normalizes CLI options and initiates the process to start a debugging session via the daemon. ```typescript main() ├─ new Command() - Initialize Commander ├─ commandRegistry.forEach() - Register commands └─ program.parse() - Parse CLI arguments ``` ```typescript registerStartCommands() └─ .action() ├─ buildSessionOptions() - Normalize CLI options └─ collectorAction() └─ startSessionViaDaemon() ``` -------------------------------- ### CDP Event-Based Domain Description Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/CLI_REFERENCE.md Demonstrates how to describe an event-based CDP domain and provides an example of the output format, including notes on how results are delivered. ```bash bdg cdp Audits --describe ``` -------------------------------- ### Get Help Information with JSON Output (Bash) Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/principles/PRINCIPLES_VERIFICATION.md Retrieves the command-line help information for the `bdg` tool and formats it as JSON. This is the first step for an agent learning about the tool's capabilities, including available commands and exit codes. ```bash $ bdg --help --json # Agent learns: 10 commands, exit codes, task mappings ``` -------------------------------- ### Execute High-Level Command for Network Requests Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/principles/PRINCIPLES_VERIFICATION.md Shows a practical example of using a high-level `bdg peek` command to find failed network requests (status >= 400) and extract their URLs. It highlights the efficiency gained from the tool's self-documenting principles. ```bash # 2. Start session (if needed) $ bdg status || bdg https://example.com # 3. Use high-level command $ bdg peek --network --json | jq '.data.network[] | select(.status >= 400) | .url' ``` -------------------------------- ### Starting a Debugging Session Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Architecture Initiates a new debugging session by starting the bdg CLI with a URL. This process involves checking for an existing daemon, spawning one if necessary, launching Chrome, connecting to it, navigating to the specified URL, and then allowing the daemon to run in the background. ```bash bdg https://example.com ``` -------------------------------- ### bdg CLI Command Sequence (Bash) Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/benchmarks/BENCHMARK_PROMPT.md An example sequence of bash commands for using the 'bdg' browser debugger CLI to interact with Hacker News. ```bash bdg https://news.ycombinator.com --timeout 300 bdg dom query ".athing" bdg dom query ".votelinks a" bdg dom eval "document.querySelector('.score')?.textContent" bdg dom click ".athing:first-child ~ tr .subtext a:last-child" bdg peek --last 10 bdg dom query ".comment" bdg console --list bdg network har /tmp/hn.har bdg stop ``` -------------------------------- ### Enable CDP Domain Command Example (CDP Protocol) Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/architecture/BDG_EXECUTION_FLOW.md An example of enabling a Chrome DevTools Protocol domain, such as 'Page'. This command is sent from the worker to Chrome over a WebSocket. ```json { "id": 1, "guid": "some-guid", "method": "Page.enable" } ``` -------------------------------- ### Composability Example: Piping bdg Output with jq Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/benchmarks/BENCHMARK_RESULTS_2025-11-23.md This example showcases the composability of the bdg tool by piping its output to `jq`, a command-line JSON processor. It demonstrates how bdg's native support for Unix pipes and JSON output allows for powerful data manipulation and filtering directly within the command line. ```bash bdg dom query ".athing" | jq 'length' ``` -------------------------------- ### Run Tests and Take Screenshots using bdg Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Recipes Execute tests by querying the DOM and checking conditions using jq, and take evidence screenshots. This example demonstrates basic command chaining and file output. ```bash bdg dom query ".error" --json | jq -e '.count == 0' || exit 1 bdg dom screenshot evidence.png ``` -------------------------------- ### TypeScript Example Header for Adapted Code Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/roadmap/DEVTOOLS_FRONTEND_EVALUATION.md Provides an example of the required header comment for code adapted from the Chrome DevTools Frontend, ensuring proper attribution and compliance with the BSD-3-Clause license. It includes the source repository link and original license type. ```typescript // Adapted from Chrome DevTools Frontend // https://github.com/ChromeDevTools/devtools-frontend // Original license: BSD-3-Clause ``` -------------------------------- ### Manual Debugging with Browser Debugger CLI Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/tests/agent-benchmark/README.md These commands demonstrate manual reproduction and debugging steps using the browser-debugger-cli ('bdg'). It starts by navigating to a URL, then waits for a specific DOM element, simulating steps that might be part of a failing benchmark scenario. ```bash # Extract commands from scenario and run manually bdg https://github.com/trending bdg dom wait --selector "article.Box-row" --timeout 30000 # ... continue debugging ``` -------------------------------- ### Capture Video (Advanced) Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Recipes Commands to capture video of browser activity, including starting and stopping a screencast. ```APIDOC ## Capture Video (Advanced) ### Description Initiates and stops a screencast to capture video output from the browser. ### Method `bdg` (CLI command) ### Endpoint `https://example.com --headless` (for headless navigation) `cdp Page.startScreencast` `cdp Page.stopScreencast` ### Parameters #### Page.startScreencast - **params** (string) - Required - JSON string with screencast options: - **format** (string) - Image format ('png' or 'jpeg'). - **quality** (integer) - Compression quality (0-100). - **maxWidth** (integer) - Maximum width of the screencast frames. - **maxHeight** (integer) - Maximum height of the screencast frames. ### Request Example ```bash bdg https://example.com --headless # Start screencast bdg cdp Page.startScreencast --params '{ "format": "png", "quality": 80, "maxWidth": 1920, "maxHeight": 1080 }' # Perform actions... # Stop screencast bdg cdp Page.stopScreencast ``` ``` -------------------------------- ### IPC Request Example (CLI to Daemon) Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/architecture/BDG_EXECUTION_FLOW.md Demonstrates sending a handshake request to the daemon using a Unix domain socket and JSONL format. This is a basic connectivity test. ```bash echo '{"type":"handshake_request","sessionId":"test"}' | nc -U ~/.bdg/daemon.sock ``` -------------------------------- ### Discover Tool Capabilities with JSON Help Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/principles/PRINCIPLES_VERIFICATION.md Demonstrates how to use the `--help --json` command to programmatically discover the tool's capabilities, specifically filtering for network-related tasks using `jq`. This showcases the self-documenting nature of the CLI. ```bash # Agent reads 50-page manual # Agent searches StackOverflow # Agent tries commands blindly # 10+ round trips, 30+ minutes # 1. Discover capabilities $ bdg --help --json | jq '.taskMappings[] | select(.task | contains("network"))' ``` -------------------------------- ### Simulate File Upload using bdg Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Recipes Simulates uploading a file via a web form. This example uses the CDP command `DOM.setFileInputFiles`, which requires the file path to be accessible by the browser process. ```bash bdg https://example.com/upload # Set file input value (limited - files must be accessible to Chrome) bdg cdp DOM.setFileInputFiles --params '{ "files": ["/path/to/file.txt"], "nodeId": 123 }' ``` -------------------------------- ### Agent Discovery Pattern Examples Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/README.md Illustrates how an AI agent can explore the capabilities of the browser debugger CLI without prior documentation. It shows how to list domains, methods, describe specific commands, and search for methods across all domains. ```bash # Agent explores what's possible (no docs needed) bdg cdp --list # 53 domains bdg cdp Network --list # 39 methods bdg cdp Network.getCookies --describe # Full schema + examples bdg cdp Network.getCookies # Execute # Search across all domains bdg cdp --search screenshot # Find relevant methods bdg cdp --search cookie # 14 results ``` -------------------------------- ### Get npm Package Information Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/RELEASE_PROCESS.md This command retrieves detailed information about a specific version of the browser-debugger-cli package from npm, including its dependencies, scripts, and metadata. Useful for verifying publication details. ```bash npm info browser-debugger-cli@alpha ``` -------------------------------- ### Describe a Specific CDP Method (Bash) Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/principles/PRINCIPLES_VERIFICATION.md Provides detailed information about a specific CDP method, including its parameters, return types, and usage examples. This is crucial for an agent to understand how to correctly invoke a method. ```bash $ bdg cdp Network.getCookies --describe # Agent learns: parameters, return type, examples ``` -------------------------------- ### Event Listener Inspection (Bash) Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/roadmap/ROADMAP.md Provides examples of how to inspect event listeners attached to DOM elements using bdg. It shows commands for getting a count of listeners per event type and for retrieving verbose details about each listener. ```bash bdg dom listeners # Output: { "click": 2, "submit": 1, "input": 5 } bdg dom listeners --verbose # Output: Full listener details with handler info ``` -------------------------------- ### Implement Timeouts in Bash Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/quality/TEST_GUIDE.md Shows how to prevent scripts or tests from hanging indefinitely by implementing a timeout mechanism. This snippet starts a background process that sends a TERM signal to the current shell after a specified duration, ensuring the process terminates. ```bash # Prevent infinite hangs (sleep 300; kill -TERM $$) 2>/dev/null & TIMEOUT_PID=$! ``` -------------------------------- ### Agent Learning Flow with Browser Debugger CLI (TypeScript) Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/principles/SELF_DOCUMENTING_SYSTEMS.md Provides a TypeScript example of an agent interacting with the browser debugger CLI to discover its capabilities progressively. It demonstrates learning tool capabilities, domain specifics, method schemas, and finally executing commands. ```typescript // Agent starts with zero knowledge const tool = "bdg"; // Level 0: Discover tool capabilities const help = await exec(`${tool} --help --json`); // Agent learns: 10 commands available, including "cdp" // Level 1: Discover domain capabilities const domains = await exec(`${tool} cdp --list`); // Agent learns: 53 CDP domains available // Level 2: Discover domain methods const methods = await exec(`${tool} cdp Network --list`); // Agent learns: 39 Network methods available // Level 3: Discover method schema const schema = await exec(`${tool} cdp Network.getCookies --describe`); // Agent learns: Method signature, parameters, return type, examples // Level 4: Execute with confidence const result = await exec(`${tool} cdp Network.getCookies`); // Agent successfully retrieves cookies ``` -------------------------------- ### Complete Release Workflow One-Liner Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/RELEASE_PROCESS.md A comprehensive bash command that executes the typical steps for a release, including running checks, building, committing changes, tagging, pushing, creating a GitHub release, publishing to npm, and setting the latest dist-tag. ```bash npm run check:enhanced && \ npm run build && \ git add CHANGELOG.md package.json package-lock.json && \ git commit -m "chore: release v0.X.Y" && \ git tag v0.X.Y && \ git push origin main --tags && \ gh release create v0.X.Y --title "v0.X.Y" --notes "Release notes here" && \ npm publish --tag alpha && \ npm dist-tag add browser-debugger-cli@0.X.Y latest ``` -------------------------------- ### Complete Agent Workflow Example: Contact Form Submission Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/roadmap/AGENT_FORM_AUTOMATION.md Provides a comprehensive bash script workflow for an agent tasked with filling out a contact form and submitting it. It includes starting a session, querying fields, filling them, and basic error handling. ```bash #!/bin/bash set -e # Exit on error # Start session bdg https://example.com/contact # === Step 1: Query form fields === FIELDS=$(bdg dom a11y query role=textbox --json) echo "Found $(echo $FIELDS | jq '.count') form fields" # === Step 2: Fill each field === ``` -------------------------------- ### bdg Agent Decision Logic based on Exit Codes Source: https://github.com/szymdzum/browser-debugger-cli/wiki/For-AI-Agents Provides an example of how an AI agent can interpret the exit code returned by the bdg CLI to make informed decisions about subsequent actions. It categorizes exit codes into success, user input errors, and software failures, guiding retry logic and error handling strategies. ```bash exit_code=$? case $exit_code in 0) # Success - proceed 80-89) # User error - don't retry, fix input 100-102) # External failure - retry with backoff esac ``` -------------------------------- ### List CDP Domains with jq Filtering (Bash) Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/principles/PRINCIPLES_VERIFICATION.md This example shows how to list the available Chrome DevTools Protocol (CDP) domains and then use `jq` to extract and display the names of the first five domains. This showcases the tool's composability with standard Unix utilities. ```bash $ node dist/index.js cdp --list | jq -r '.domains[0:5] | .[].name' Accessibility Animation Audits Autofill BackgroundService ``` -------------------------------- ### DOM Query Examples for Amazon Product Page Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/benchmarks/BENCHMARK_RESULTS_2025-11-23.md Demonstrates sample command-line interface (CLI) commands for querying DOM elements on an Amazon product page using the browser-debugger-cli tool. Shows the expected token output for retrieving the product title and price, illustrating efficient data extraction. ```bash bdg dom query "h1#title" bdg dom query ".a-price-whole" bdg stop ``` -------------------------------- ### Install Google Chrome Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Troubleshooting Installs Google Chrome using package managers for macOS and Linux. This is a common solution when Chrome fails to launch due to not being installed. ```bash # macOS brew install --cask google-chrome # Linux sudo apt install google-chrome-stable ``` -------------------------------- ### Capture Video with Page Screencast CDP Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Recipes Advanced command to capture video of browser activity in headless mode. It involves starting the screencast with specified format and quality, performing actions, and then stopping the screencast. Uses Page.startScreencast and Page.stopScreencast CDP commands. ```bash bdg https://example.com --headless # Start screencast bdg cdp Page.startScreencast --params '{ "format": "png", "quality": 80, "maxWidth": 1920, "maxHeight": 1080 }' # Perform actions... # Stop screencast bdg cdp Page.stopScreencast ``` -------------------------------- ### Error JSON Output Format Example Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Commands Example of the JSON output structure for error conditions, indicating failure and providing an error message. ```json { "success": false, "error": "Error message" } ``` -------------------------------- ### Run All Benchmarks Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/tests/agent-benchmark/IMPLEMENTATION_STATUS.md Executes the entire benchmark suite from the agent-benchmark directory. This is the primary command for running all defined tests. ```bash cd tests/agent-benchmark ./run-benchmark.sh ``` -------------------------------- ### Start a New Session Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Troubleshooting Starts a new browser debugging session for a specified domain. This is often a prerequisite for running other commands that interact with the browser context. ```bash # Start a session first bdg example.com # Then run commands bdg dom query "button" ``` -------------------------------- ### Template for Creating New Benchmark Scenarios Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/tests/agent-benchmark/README.md A bash script template for defining new benchmark scenarios. It includes sections for scenario metadata, task description, complexity, expected duration, success criteria, and known challenges. It utilizes helper scripts for metrics and assertions. ```bash #!/bin/bash # Agent Benchmark: [Scenario Name] # # Task: [What the agent is trying to accomplish] # Complexity: Tier [1|2|3] # Expected Duration: X-Y seconds # # Success Criteria: # - [Criterion 1] # - [Criterion 2] # # Known Challenges: # - [Challenge 1] # - [Challenge 2] set -euo pipefail # Benchmark metadata SCENARIO_NAME="scenario-name" SCENARIO_COMPLEXITY="tier2" TARGET_URL="https://example.com" # Load helpers source "$(dirname "$0")/../lib/metrics.sh" source "$(dirname "$0")/../lib/assertions.sh" # Start timing start_time=$(date +%s) start_benchmark "$SCENARIO_NAME" # Step 1: Start session log_step "Starting bdg session" bdg "$TARGET_URL" || die "Failed to start session" # Step 2: Wait for content log_step "Waiting for content to load" bdg dom wait --selector ".target" --timeout 10000 || die "Timeout" # Step 3: Extract data log_step "Extracting data via CDP" RESULT=$(bdg cdp Runtime.evaluate --params '{"expression": "...", "returnByValue": true}') # Step 4: Validate log_step "Validating results" assert_gte "$(echo "$RESULT" | jq '.result.value | length')" 5 "Expected at least 5 items" # Step 5: Stop session bdg stop # Calculate metrics end_time=$(date +%s) duration=$((end_time - start_time)) record_metric "total_duration_seconds" "$duration" # Output results log_success "Benchmark completed successfully" end_benchmark "$SCENARIO_NAME" "success" exit 0 ``` -------------------------------- ### Verify npm Credentials Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/RELEASE_PROCESS.md Confirms that npm credentials are set up correctly, allowing the user to publish packages. This is essential for the 'Publishing to npm' step. ```bash npm whoami ``` -------------------------------- ### Install Browser Debugger CLI Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/README.md Installs the browser-debugger-cli package globally using npm. This command is essential for making the 'bdg' command available in your terminal. ```bash npm install -g browser-debugger-cli@alpha ``` -------------------------------- ### View and Manage GitHub Releases Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/RELEASE_PROCESS.md Useful commands for interacting with GitHub releases using the GitHub CLI. Includes listing all releases, viewing a specific release, editing its notes, and deleting a release. ```bash # View recent releases gh release list # View specific release gh release view v0.X.Y # Edit release notes gh release edit v0.X.Y --notes "Updated notes" # Delete release (use with caution) gh release delete v0.X.Y git tag -d v0.X.Y git push origin :refs/tags/v0.X.Y ``` -------------------------------- ### Monitor Downloads using bdg Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Recipes Sets up the browser to allow and monitor file downloads. It configures a download directory using CDP and then simulates clicking a download link, followed by monitoring download events. ```bash bdg https://example.com # Enable download tracking bdg cdp Browser.setDownloadBehavior --params '{ "behavior": "allow", "downloadPath": "/tmp/downloads" }' # Click download link bdg dom click "a[download]" # Monitor download events via CDP bdg cdp Browser.downloadWillBegin ``` -------------------------------- ### Debug Benchmark Scenario with Screenshots and Verbose Output Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/tests/agent-benchmark/IMPLEMENTATION_STATUS.md Runs a specific benchmark scenario with additional debugging flags enabled. `--screenshot` captures images of the browser state, and `--verbose` provides detailed logging. ```bash ./run-benchmark.sh --scenario 01-github-trending --screenshot --verbose ``` -------------------------------- ### Create Release with GitHub CLI Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/RELEASE_PROCESS.md Command to create a new GitHub release from an existing tag. Requires the tag name, title, and release notes. The notes can be provided directly or via a heredoc for Markdown formatting. ```bash gh release create v0.X.Y --title "..." --notes "..." gh release create v0.X.Y \ --title "..." \ --notes "$(cat <<'EOF'\ # Markdown content here\nEOF )" ``` -------------------------------- ### Machine-Readable Help Output with JSON Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/principles/PRINCIPLES_VERIFICATION.md This snippet demonstrates how to obtain machine-readable help information from the CLI using the `--help --json` flags. The output is a JSON object containing various details about the tool's capabilities, commands, and structure. It's useful for programmatic inspection of the tool's features. ```bash $ node dist/index.js --help --json | jq 'keys' [ "capabilities", "command", "decisionTrees", "description", "exitCodes", "name", "runtimeState", "taskMappings", "version" ] ``` -------------------------------- ### bdg Discovery-Learn-Execute Pattern Source: https://github.com/szymdzum/browser-debugger-cli/wiki/For-AI-Agents Illustrates the core workflow for AI agents using bdg: first discovering relevant commands (e.g., by searching), then learning the specifics of a command (parameters, types, examples) using the --describe flag, and finally executing the command. This structured approach ensures precise and effective browser automation. ```bash # 1. Discover bdg cdp --search storage # Returns: Storage.getCookies, Storage.clearDataForOrigin, ... # 2. Learn bdg cdp Storage.getCookies --describe # Returns: Parameters, types, examples # 3. Execute bdg cdp Storage.getCookies ``` -------------------------------- ### Test Properties, Not Examples in TypeScript Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/quality/TESTING_PHILOSOPHY.md This snippet demonstrates how to write effective unit tests in TypeScript by focusing on testing properties (invariants) rather than specific, brittle examples. It highlights that tests should verify what the output should always be, not how it's achieved, making them more robust to implementation changes. ```typescript import { normalizeUrl } from './utils'; // ❌ Bad: Testing specific examples test('normalizes localhost:3000', () => { expect(normalizeUrl('localhost:3000')).toBe('http://localhost:3000'); }); // ✅ Good: Testing properties/invariants test('result always has a protocol', () => { const inputs = ['localhost:3000', 'example.com', 'http://foo.com']; inputs.forEach(input => { const result = normalizeUrl(input); expect(result).toMatch(/^https?:\/\/./); // Property: always has protocol }); }); ``` -------------------------------- ### Define TelemetryPlugin Contract Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/architecture/TELEMETRY-PLUGIN.md Defines the structure for a telemetry plugin, including its name, whether it should always run, its telemetry type, and a start function that returns a cleanup callback. The start function receives a context object containing CDP connection, configuration, store, and logger. ```typescript export interface TelemetryPlugin { name: string; // unique identifier runAlways?: boolean; // true for mandatory plugins (dialogs, navigation) telemetry?: TelemetryType; // 'network' | 'console' | 'dom' start(ctx: TelemetryPluginContext): Promise; } ``` -------------------------------- ### Discover bdg CLI Commands and Schemas Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/CLAUDE.md Use these commands to programmatically discover the capabilities of the bdg CLI tool. They provide help information, list CDP domains and methods, describe method schemas, and allow searching for methods. This enables agents to understand and utilize the tool's features before implementation. ```bash bdg --help --json # All commands, flags, exit codes bdg cdp --list # 53 CDP domains bdg cdp Network --list # Methods in a domain bdg cdp Network.getCookies --describe # Full method schema bdg cdp --search cookie # Search methods ``` -------------------------------- ### Start, Check, and Stop Debugging Sessions with bdg Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/CLI_REFERENCE.md Manage the lifecycle of your debugging sessions. Start a new session by specifying the browser host and port. Check the status of running sessions with basic or verbose output, including Chrome diagnostics. Stop a session cleanly or forcefully, with options to kill the associated Chrome process. ```bash bdg localhost:3000 # Launches daemon in background # Returns immediately after handshake ``` ```bash bdg status # Basic status information bdg status --verbose # Include Chrome diagnostics bdg status --json # JSON output ``` ```bash bdg stop # Stop session only bdg stop --kill-chrome # Stop session and kill Chrome # OR bdg stop && bdg cleanup --aggressive # Alternative way to kill Chrome ``` -------------------------------- ### Get Full Request/Response and Console Details with bdg details Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/CLI_REFERENCE.md Retrieve comprehensive details for specific network requests or console messages. Use `bdg details network ` to get full request and response information, including bodies. Use `bdg details console ` to view the complete content of a console message and its arguments. ```bash bdg details network # Full request/response with bodies bdg details console # Full console message with args ``` -------------------------------- ### Command Discovery Hierarchy Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/principles/SELF_DOCUMENTING_SYSTEMS.md Illustrates a command discovery hierarchy using bash commands. This allows agents to explore available commands and subcommands, facilitating discovery of the tool's capabilities without needing prior knowledge of exact command names. ```bash tool --list-commands tool command --list-subcommands tool command subcommand --describe ``` -------------------------------- ### Testing Public API vs. Internal Helpers (TypeScript) Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/quality/TESTING_PHILOSOPHY.md This snippet illustrates the principle of testing only the public API. The 'Bad' example shows testing an internal helper function that had to be exported solely for testing purposes. The 'Good' example demonstrates testing the public API directly, adhering to the rule that production code should not be modified to facilitate testing. ```typescript // ❌ Bad: Testing internal helper import { tryExactMatch } from '../../src/connection/finder'; // Had to export this just for tests! // ✅ Good: Testing public API import { findTargetByUrl } from '../../src/connection/finder'; ``` -------------------------------- ### Navigate Through Web Pages using bdg Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Recipes Demonstrates navigation between web pages using the browser-debugger-cli. It includes direct navigation, using CDP commands, and programmatic navigation via JavaScript. ```bash bdg https://example.com # Navigate to another page (Page.navigate waits for load automatically) bdg cdp Page.navigate --params '{"url":"https://example.com/page2"}' # Check current URL bdg dom eval "window.location.href" # Alternative: Navigate via JavaScript bdg dom eval "window.location.href = 'https://example.com'" ``` -------------------------------- ### Retrieve Cookies Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Commands Get cookies from the browser. Can be filtered by URL to retrieve cookies for a specific domain. ```bash bdg network getCookies bdg network getCookies --url https://api.example.com ``` -------------------------------- ### Create New Benchmark Scenario Script Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/tests/agent-benchmark/README.md This command demonstrates how to create a new benchmark scenario file by copying an existing one. It uses 'cp' to duplicate the '01-github-trending.sh' script to '02-reddit-frontpage.sh', which can then be edited to define a new test case. ```bash cp scenarios/01-github-trending.sh scenarios/02-reddit-frontpage.sh # Edit scenario details ``` -------------------------------- ### Chrome MCP (Puppeteer) JavaScript Sequence Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/benchmarks/BENCHMARK_PROMPT.md An example JavaScript sequence for using Chrome MCP (likely Puppeteer or a similar library) to interact with Hacker News. ```javascript new_page({ url: "https://news.ycombinator.com" }) take_snapshot({}) evaluate_script({ function: "() => document.querySelectorAll('.athing').length" }) click({ uid: "2_46" }) // From snapshot UID evaluate_script({ function: "() => document.querySelectorAll('.comment').length" }) ``` -------------------------------- ### Create and Push Git Tag Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/RELEASE_PROCESS.md These commands create a new Git tag locally (e.g., 'v0.X.Y') and then push all local tags to the remote repository ('origin'). This is crucial for marking release points in the project's history and enabling GitHub releases. ```bash git tag v0.X.Y git push origin main --tags ``` -------------------------------- ### Self-Documenting Discovery Hierarchy Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/principles/PRINCIPLES_VERIFICATION.md This sequence of commands illustrates the progressive disclosure hierarchy for discovering tool capabilities, starting from general information and drilling down to specific method schemas. It shows how an agent can explore available commands, domains, methods, and their details without external documentation. The `jq` command is used to parse and extract specific information from the JSON output. ```bash # Level 0: Tool capabilities $ node dist/index.js --help --json # Returns: commands, exit codes, task mappings # Level 1: Domain discovery $ node dist/index.js cdp --list | jq '.count' 53 # All CDP domains # Level 2: Method discovery $ node dist/index.js cdp Network --list | jq '.count' 39 # All Network methods # Level 3: Method schema $ node dist/index.js cdp Network.getCookies --describe | jq 'keys' [ "description", "domain", "example", "method", "name", "parameters", "returns", "type" ] # Level 4: Semantic search $ node dist/index.js cdp --search cookie | jq '.count' 14 # Found 14 cookie-related methods ``` -------------------------------- ### Get Request/Console Message Details Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Commands Retrieve full details for a specific network request or console message. Requires the request ID or message index. ```bash bdg details network # Full request/response bdg details console # Console message details ``` -------------------------------- ### Chrome MCP Commands for Amazon Test Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/benchmarks/BENCHMARK_RESULTS_2025-11-23.md Illustrates the Chrome MCP commands used during the Amazon test, emphasizing the `take_snapshot` command's high token cost and the subsequent evaluation or interaction commands that follow. ```bash # Example commands for Amazon test (token counts are illustrative) take_snapshot({}) evaluate_script("document.querySelector('.product-title').innerText") click({ "selector": "#buy-now-button" }) ``` -------------------------------- ### Display Tool Help Information as JSON Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/principles/AGENT_FRIENDLY_TOOLS.md This command retrieves the tool's capabilities and configuration in a machine-readable JSON format, allowing agents to understand available commands, flags, and output formats. It's crucial for self-describing tools. ```bash $ bdg --help-json { "version": "1.2.0", "commands": { "network": { "description": "Network request inspection", "subcommands": ["requests", "failed", "slow", "timing"], "flags": { "--json": "Output in JSON format", "--limit": "Maximum number of results (default: 50)" } } }, "output_formats": ["text", "json"], "exit_codes": { "0": "success", "85": "invalid_argument", "92": "resource_not_found", "105": "connection_timeout" } } ``` -------------------------------- ### Segmented Range Example Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/roadmap/DEVTOOLS_FRONTEND_EVALUATION.md Demonstrates the usage of a SegmentedRange utility for manipulating time ranges, commonly used in visualizing data like network waterfalls. ```typescript import { SegmentedRange } from './SegmentedRange'; const range = new SegmentedRange(0, 100); range.append(20, 40); range.append(60, 80); console.log(range.segments()); // Output: [{ start: 20, end: 40 }, { start: 60, end: 80 }] console.log(range. அதிகரிக்கிறது(30)); // true console.log(range. அதிகரிக்கிறது(50)); // false ``` -------------------------------- ### Create and Push Git Tag Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/RELEASE_PROCESS.md Creates a Git tag for the current release version and pushes the tag along with the commit to the remote repository. This is essential for linking GitHub Releases to specific commits. ```bash # Create tag git tag v0.X.Y # Push commit and tag git push origin main --tags ``` -------------------------------- ### Throttler Utility Example Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/roadmap/DEVTOOLS_FRONTEND_EVALUATION.md A utility class for implementing debouncing and throttling, useful for rate-limiting high-frequency events, such as those received from the Chrome DevTools Protocol (CDP). ```typescript import { Throttler } from './Throttler'; const throttler = new Throttler(100); // 100ms delay async function handleEvent(event) { await throttler.schedule(() => { // Process the event, this will only run once per 100ms console.log('Processing event:', event); }); } // Simulate high-frequency events setInterval(() => handleEvent({ data: Math.random() }), 50); ``` -------------------------------- ### CLI Formats and Displays Output (Text) Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/architecture/BIDIRECTIONAL_IPC.md Example of the final output formatted and displayed by the CLI to the user after receiving and processing the response from the worker process. ```text Found 3 elements matching "p": [1]

Hello world [2]

Another paragraph [3]

Third element ``` -------------------------------- ### Check Chrome Version Source: https://github.com/szymdzum/browser-debugger-cli/wiki/Troubleshooting Checks the installed version of Google Chrome on Linux and macOS. This is useful for diagnosing compatibility issues between the browser and the debugger CLI. ```bash # Linux google-chrome --version # macOS /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --version ``` -------------------------------- ### Running Tests with npm and Shell Scripts Source: https://github.com/szymdzum/browser-debugger-cli/blob/main/docs/quality/TEST_GUIDE.md This snippet shows commands to execute various test suites within the project using npm scripts and a shell script. It covers running all tests, specific test types like smoke tests, and linting/type checks. ```bash # Run all TypeScript tests (unit, contract, integration, smoke) npm test # Run only smoke tests npm run test:smoke # Run shell-based tests ./tests/run-all-tests.sh # Run lints and type checks npm run lint npm run type-check ```