RBSM v4.9.5 Manual
Robust Browser Stealth Management
Gateway › RBSM Engine › User Documentation & Reference

RBSM User Manual & Command Reference

Complete end-user documentation for RBSM v4.9.5 (Robust Browser Stealth Management) — learn all CLI options, proxy resolution modes, IP reuse limits, modern .js & legacy .mac macro automation, live recording, built-in Chrome downloader, native fingerprint generator, and Claude/AI MCP server integration.

Choose Target OS:

⚡ 1. Quickstart & License Setup

RBSM is a zero-dependency, single-binary anti-detect browser engine. It has no external Python or Node.js runtime requirements.

Step 1: Download & Extract

Choose between the visual RBSM Command Center (GUI Control Panel) or the raw Headless Core Engine (CLI):

🖥️ RBSM Command Center (Visual GUI Web Control Panel · Port 8800)
Recommended Folder Layout
rbsm/
├── rbsm-gui-windows-amd64.exe  (Visual Command Center Web GUI)
├── rbsm_windows_amd64.exe      (or rbsm_linux_amd64 on Linux)
├── license.lic                 (placed in the same folder)
├── proxies.txt                 (optional proxy list)
├── ip-log.txt                  (auto-generated for tracking used IPs)
├── macros/                     (automation scripts: modern .js or legacy .mac)
└── rules/                      (optional JSON network rules)

Step 2: Obtain Your Machine Hardware ID (HWID)

Windows Command Prompt / PowerShell
.\rbsm_windows_amd64.exe -hwid
💡 Linux / Cloud VPS Note: Always Use Sudo

Always run -hwid and RBSM with sudo on Linux (e.g. sudo ./rbsm_linux_amd64 ...). Standard Linux kernel security restricts immutable hardware DMI tables (/sys/class/dmi/id/*) and disk serials to root. Running with sudo guarantees a permanent, 100% stable hardware fingerprint that remains identical across all user sessions and reboots.

Step 3: Activate Your License

  • Claim a Free 24h Trial at rbsm.nexustrc.app using your email & Machine ID.
  • Place license.lic in the exact same directory as your RBSM binary.

Step 4: Run Your First Test

Windows CMD
rbsm_windows_amd64.exe -macros=macros\creep.js

Step 5: (Optional) Launch the Visual Web GUI Control Panel

If you prefer orchestrating your profiles, proxies, and cookies visually through a web dashboard instead of typing CLI arguments, launch the RBSM Command Center:

Windows PowerShell / CMD
.\rbsm-gui-windows-amd64.exe -port=8800

Then open your browser to http://localhost:8800 to create isolated browser profiles, test proxy latency, inspect stored cookies, and trigger macros with 1-click execution.

⚙️ 2. Complete CLI Flags & Options Reference

A comprehensive list of every command-line flag and option available in the RBSM executable:

A. Core Engine & Operation Modes

Option / Flag Type Default Description Example
-agent bool false Launch autonomous AI agent execution loop driven by mcp-data.json or prompt string. -agent "Search news"
-agent-verbose bool false Print real-time thoughts, step previews, and detailed execution logs in AI agent mode. -agent -agent-verbose
-interactive bool false Start autonomous zero-token interactive terminal chat REPL. -interactive=true
-macros string "" Path to automation script (modern .js recommended, or legacy .mac). -macros=macros/login.js
-macros-continue-on-error bool false Continue executing remaining steps even if an individual macro command encounters an error. -macros=flow.mac -macros-continue-on-error
-record string "" Record live browser clicks & typing into a clean .mac file. -record=my_flow.mac
-mcp-server bool false Start RBSM in stdio MCP Server mode for Claude Desktop & Cursor. -mcp-server=true
-headless bool false Run browser headlessly without opening a GUI window (0% lies on CreepJS). -headless=true
-thread int 1 Number of concurrent isolated browser worker instances. -thread=10
-human int 2 Human interaction physics level (0=instant, 1=fast, 2=normal, 3=careful). -human=2
-debug bool false Enable verbose engine, CDP protocol, and execution debug logging. -debug=true
-hwid bool false Display local machine Hardware ID for licensing and exit. -hwid=true
-update-license bool false Automatically download or update license.lic from server for this machine HWID. -update-license
-check-license bool false Verify and inspect local license.lic and live online standing (alias: -license-info). -check-license
-license string "license.lic" Path to signed license file. -license="custom.lic"
-version bool false Display current RBSM version and exit. -version

B. Proxy & Network Pool Management

Option / Flag Type Default Description Example
-build bool false Compile MaxMind GeoLite2-City.mmdb into optimized binary database iprbsm.bin for ultra-fast offline IP geolocation. rbsm -build
-db string "GeoLite2-City.mmdb" Source MMDB file path for -build (optional; defaults to GeoLite2-City.mmdb). -build -db="custom.mmdb"
-proxy[=<file>] string proxies.txt Enable proxy rotation from proxy list file (default: proxies.txt). -proxy or -proxy=proxies.txt
-country string "" Filter proxies or enforce country profile (comma-separated ISO codes). -country=US,DE,GB
-no-judges bool false Skip startup proxy judge reachability test (0ms instant startup latency). -no-judges=true
-limit-proxy int 0 Max allowed uses per unique exit IP before auto-rotating. Recorded in ip-log.txt. Set to 1 for strict 1-session-per-IP isolation. -limit-proxy=1
-limit-timeout int 300 Maximum rotation retry attempts to acquire an unexhausted IP before graceful termination. -limit-timeout=300
-ipv6 bool false Enable IPv6 address binding support and IPv6 proxy connections. -ipv6=true
-retry int 1 Worker iteration / target retry count. -retry=3
-timeout int 15 Default page navigation and load timeout in seconds. -timeout=20
-cdp-timeout int 30 Low-level CDP communication timeout in seconds. -cdp-timeout=45
-cdp-retry int 0 Number of CDP retry attempts on connection drops. -cdp-retry=2

C. URLs, Security & Browser Profiles

Option / Flag Description Example
-bypass[=<file>] Redirect configured target URLs from file to localhost for local testing (default: urls.txt). -bypass or -bypass=urls.txt
-rules <file> Load startup network interception and ad-blocking rules JSON. -rules=rules/block_ads.json
-spoof-tcp <cmd> TCP stack / p0f fingerprint spoofing (start, run, stop). (Linux environment only) -spoof-tcp=run
-disable-cors Disable web security and bypass CORS (--disable-web-security & CSP bypass). -disable-cors
-save-cookies[=<file>] Save active browser session cookies to JSON file on exit (default: cookies.json). -save-cookies=acc1.cookies.json
-set-cookies[=<file>] Load / restore cookies from JSON file into the browser upon launch (default: cookies.json). -set-cookies=acc1.cookies.json
-save-fp[=<file>] Save active session fingerprint profile to disk without touching the master fp-ua.json pool (default: session-fp.json). -save-fp=acc1.fp.json
-load-fp[=<file>] Lock browser to specific saved fingerprint profile on launch instead of sampling from the pool (default: session-fp.json). -load-fp=acc1.fp.json
-download Allow and enable automatic browser file downloads (required for DOWNLOAD macro and download_file tool). -download
-doh <template> Configure DNS-over-HTTPS resolver preset (cloudflare, google, quad9, adguard) or custom https://... URL. -doh cloudflare
-agent-config <file> Path to LLM configuration file for autonomous AI agent mode (default: mcp-data.json). -agent-config="mcp-data.json"
-plugin <plugins> Load unpacked Chrome extensions/plugins into browser instances (e.g. canvas,webgl). -plugin="canvas,webgl"
🐧 Linux Only: -spoof-tcp

The -spoof-tcp flag modifies low-level OS kernel TCP SYN packets, window sizes, and TTL to spoof OS passive OS fingerprints (p0f). This flag is supported for Linux environments only and requires root / sudo / raw packet capabilities.

🍪 Cookie Persistence (-save-cookies & -set-cookies)

Use -save-cookies (or -save-cookies=acc1.cookies.json) to dump active session cookies on exit, and -set-cookies to inject them upon browser startup for persistent logins across runs.

🎭 Session Fingerprint (-save-fp & -load-fp)

Save the single active fingerprint chosen for this session using -save-fp (default: session-fp.json) without modifying the 5,000-profile pool in fp-ua.json. Re-load it anytime with -load-fp to lock into that exact identity.

🌐 3. Proxy Setup & IP Resolution Modes

RBSM supports HTTP, HTTPS, SOCKS5, and SOCKS4 proxies with or without authentication.

Accepted Formats in proxies.txt

proxies.txt
# Standard (No Auth): <protocol>://<host>:<port>
http://192.168.1.100:8080
https://proxy.example.com:8443
socks5://192.168.1.100:1080
socks4://192.168.1.100:1080

# Authenticated: <username>:<password>#<protocol>://<host>:<port>
myuser:mypass#http://192.168.1.100:8080
myuser:mypass#socks5://proxy.provider.com:1080
customer123:secret#http://gate.smartproxy.com:7000

Proxy Operating Modes Matrix

Command Combination Proxy Tested? Target IP Geolocation, Timezone & WebRTC
rbsm -proxy Yes (judge) Real Proxy Exit IP Auto-follows and matches the actual Proxy Server IP location, timezone, and WebRTC candidate.
rbsm -proxy -country=US Yes (judge) Synthetic US IP Tests proxy, then overrides and spoofs geolocation, timezone, and WebRTC to US IP.
rbsm -proxy -no-judges -country=US No (0ms delay) Synthetic US IP Skips judge test (saves bandwidth) and spoofs geolocation, timezone, and WebRTC to US IP.
rbsm -proxy -no-judges No (0ms delay) Local / VPS IP Skips judge test and resolves geolocation, timezone, and WebRTC to Local / VPS IP.
rbsm (direct) No Local / VPS IP Direct connection without proxy; resolves geolocation, timezone, and WebRTC to Local / VPS IP.

Compiling Offline GeoIP Database (-build → iprbsm.bin)

By default, RBSM resolves proxy geolocation through embedded heuristics and rapid judges. For 100% offline, zero-latency microsecond lookups without querying any remote IP APIs or leaking DNS lookups, you can compile the MaxMind City database into a native binary index:

Terminal / Command Prompt
# 1. Standard build (looks for GeoLite2-City.mmdb in current directory):
# Windows:
rbsm_windows_amd64.exe -build

# Linux VPS:
./rbsm_linux_amd64 -build

# 2. Specify a custom MMDB source file using -db=FILE:
# Windows:
rbsm_windows_amd64.exe -build -db="C:\data\GeoLite2-City.mmdb"

# Linux VPS:
./rbsm_linux_amd64 -build -db="/var/data/GeoIP2-City.mmdb"
⚡ How iprbsm.bin Works

The -build command reads the specified source MMDB file (default: GeoLite2-City.mmdb or path passed via -db=FILE), optimizes the CIDR radix tree, and outputs a compact iprbsm.bin binary database file.

  • Custom Source Path: Use -db="path/to/database.mmdb" if your MMDB file is located in a different directory or named differently.
  • Instant Startup: Sub-millisecond in-memory IP to City, Country, Latitude/Longitude, and Timezone resolution.
  • 100% Zero-Leak: Never contacts external IP lookup services (e.g. ipinfo, ip-api) that could log your proxy IPs or trigger rate limits.
  • Automatic Detection: Once iprbsm.bin exists in the same folder as the RBSM executable, RBSM automatically uses it for all proxy fingerprint syntheses.

🛡️ 4. IP Reuse Limits & Mid-Flight Shift Guards

Strict 1-Session-Per-IP Isolation (-limit-proxy)

When running airdrop farming, high-volume account creation, or strict scraping tasks, prevent IP reuse across sessions:

  • Used IPs are recorded in ip-log.txt (e.g. 95.131.86.220 1x).
  • Once an IP reaches n uses, RBSM automatically requests a fresh IP rotation from your proxy provider.
  • -limit-timeout=300 sets the maximum retry attempts before terminating safely.
Command Line
rbsm_windows_amd64.exe -macros=macros\flow.mac -proxy=true -limit-proxy=1 -limit-timeout=300

Mid-Flight IP Shift Guard (GUARD_IP_SHIFT)

If your rotating residential proxy silently shifts its exit IP during an active session, activate GUARD_IP_SHIFT in your .mac script or "guard_ip_shift": true in rules.json. RBSM will instantly abort the contaminated session, kill the browser, and allow the worker to launch cleanly with a fresh proxy.

🧑 5. Human Physics & Typing Simulation

Control natural mouse trajectories (Bézier curves), randomized click hold times, and typing jitter with -human=<0-3>:

Level Flag Characteristics
0 -human=0 Instant: Zero artificial delays. Fastest mode for high-speed scraping on sites without behavioral bot detection.
1 -human=1 Fast Human: Light keystroke jitter and rapid natural mouse movements.
2 -human=2 Normal Human (Default): Recommended balance of natural timing, Bézier mouse paths, and keystroke latency.
3 -human=3 Careful Human: Smooth Bézier mouse trajectories, randomized click hold times, and realistic pauses.

📥 6. Built-in Chrome Downloader

RBSM bundles a native Chrome downloader directly inside the core binary, eliminating the need for Python or external scripts.

Option Description
-download-chrome / -chrome-download Download Chrome for Testing builds by major version.
<versions...> / -majors <csv> Specific Chrome major versions to download (e.g. 113 120 151 or -majors="113,120,151").
-from-ua[=file] Auto-download market-share active major browser versions from browser-data.json.
-output <dir> / -o <dir> Output directory for downloaded browser binaries (default: browsers).
-platform <plat> Override platform (win64, win32, linux64, mac-arm64, mac-x64).
-map-only Regenerate chrome-map.json mapping without downloading.
-cooldown <sec> Cooldown between consecutive downloads (default: 30 seconds).
-force Force re-download and re-extract even if the CFT version is already installed locally.
Downloader Examples
# Download specific stable milestones (automatically skips already installed builds):
rbsm -download-chrome 113 120 151

# Force re-download even if version is already installed:
rbsm -download-chrome 120 -force

# Auto-download active market-share versions from browser-data.json:
rbsm -download-chrome -from-ua

# Download to custom folder:
rbsm -download-chrome 120 -o D:\browsers

# Rebuild chrome-map.json mapping:
rbsm -download-chrome -map-only
⚡ Smart Skip & Local Version Cache

Before downloading, RBSM inspects the target output directory (default: browsers/<major>/). If the major version binary (chrome.exe or chrome) already exists and is valid, RBSM automatically skips the download and displays the existing version.

  • Zero Redundant Downloads: Saves gigabytes of bandwidth by never re-downloading builds already stored on disk.
  • No Unnecessary Cooldown: When all requested or active versions are already installed, execution completes in seconds without waiting on network cooldown timers.
  • Safe Override: Pass -force if you ever want to wipe and re-download an installed version.

🎭 7. Built-in Fingerprint & User-Agent Generator

Generate realistic browser fingerprint profiles directly into fp-ua.json using market-share weighted distributions.

Option Description
-generate-fp / -generate-ua Generate realistic browser fingerprint profiles to fp-ua.json.
-total <n> Number of fingerprints to generate (default: 10).
-os <list> Target operating systems (windows, macos, android).
-browser <list> Target browser families (chrome, edge).
-weighted Use market-share weighted distribution (default: true).
-out <file> Output JSON file path (default: fp-ua.json).
-update Fetch latest browser releases and StatCounter shares from live APIs.
Fingerprint Generator Examples
# Generate 5,000 realistic fingerprints with market-share weighting:
rbsm -generate-fp -os android windows macos -browser chrome edge -total=5000

# Sync browser-data.json with latest StatCounter shares and Chrome/Edge APIs:
rbsm -generate-ua -update

🎭 Deterministic Session Fingerprint & Cookie Persistence

When running multi-account automations, users often generate a large pool (e.g. 5,000 profiles in fp-ua.json) but need individual accounts to preserve the exact same device fingerprint and authenticated cookies across runs:

Account Session Identity Workflow
# 1. Login session: sample a profile from the 5k pool, log in, and persist both active FP & cookies:
rbsm -macros=login.mac -save-fp=acc1.fp.json -save-cookies=acc1.cookies.json

# 2. Automation run: lock onto the exact saved device identity and inject authenticated cookies:
rbsm -macros=scrape.mac -load-fp=acc1.fp.json -set-cookies=acc1.cookies.json

# Or use standard defaults (session-fp.json & cookies.json):
rbsm -macros=login.mac -save-fp -save-cookies
rbsm -macros=scrape.mac -load-fp -set-cookies

📖 8. Pre-Built Macro Template Library (Starter Pack)

📦 Download All Templates (.zip)

RBSM bundles ready-to-run automation templates in both modern .js (recommended) and legacy .mac formats in the macros/ folder. Run any recipe instantly with rbsm -macros=macros/<filename>.js (or .mac) or download directly below.

Template File Use Case / Target CLI Execution Command Action
cloudflare.mac Cloudflare Turnstile 5s Challenge Solver rbsm -macros=macros/cloudflare.mac -proxy=true ⬇ Download
datadome_bypass_test.mac DataDome & Akamai Stealth Behavioral Audit rbsm -macros=macros/datadome_bypass_test.mac -generate-fp=desktop ⬇ Download
ecom_scraper.mac E-Commerce Catalog & Dynamic Pricing Scraper rbsm -macros=macros/ecom_scraper.mac -headless=true ⬇ Download
scraper_suite.mac Full-Stack Web Scraper Pipeline (Tables, CSV, Markdown, PDF, Popups) rbsm -macros=macros/scraper_suite.mac -headless=true ⬇ Download
social_login_flow.mac Form Login with Human Typing & IP Shift Guard rbsm -macros=macros/social_login_flow.mac ⬇ Download
search_engine_extractor.mac SERP Search Engine Result Harvesting rbsm -macros=macros/search_engine_extractor.mac -country=US ⬇ Download
infinite_scroll_crawler.mac Infinite Scrolling & Dynamic Lazy-Load Feeds rbsm -macros=macros/infinite_scroll_crawler.mac -headless=true ⬇ Download
creep.mac Full-Spectrum CreepJS 513-Check Fingerprint Suite rbsm -macros=macros/creep.mac -headless=true ⬇ Download
creep_3isolated_concurrent.mac Multi-Tab Isolated Browser Concurrency rbsm -macros=macros/creep_3isolated_concurrent.mac ⬇ Download
test_workers.mac Web Worker & Platform Cross-Scope Validator rbsm -macros=macros/test_workers.mac ⬇ Download

Recipe 1: Automated Login with Verification

macros/social_login_flow.mac
# 1. Open login page with randomized referrer
GOTO "https://example.com/login" "https://google.com,https://bing.com"
WAIT_SEL "form, input[type='email'], body" 10

# 2. Type credentials with natural human keystroke jitter
SMART_CLICK "input[type='email'], input[name='username']"
TYPE_HUMAN "input[type='email']" "admin@enterprise-target.com"

SMART_CLICK "input[type='password']"
TYPE_HUMAN "input[type='password']" "SecretKeyP@ssword2026!"

# 3. Submit form and guard IP shift
SMART_CLICK "button[type='submit']"
GUARD_IP_SHIFT
SS "output/login_session.png"

Recipe 2: Cookie Banners & Conditional Popups

macros/popup.mac
GOTO "https://target-site.com"
WAIT 2 3

# Automatically dismiss cookie banners / GDPR dialogs
DISMISS_POPUPS

# Custom fallback check if special banner persists
IF SMART_EXIST "#accept-cookies-btn, .cookie-accept, button[title*='Accept']"
  SMART_CLICK "#accept-cookies-btn, .cookie-accept, button[title*='Accept']"
  ECHO "Custom cookie banner dismissed"
END

Recipe 3: E-Commerce & Multi-Page Pagination Loop

macros/ecom_scraper.mac
GOTO "https://shop.example.com/search?q=laptops"
WAIT_SEL ".product-card" 10

LOOP 5
  SS "output/page_results_<random>.png"
  SCROLL down 600
  WAIT 1 2

  IF SMART_EXIST ".pagination-next-btn, a[rel='next']"
    SMART_CLICK ".pagination-next-btn, a[rel='next']"
    WAIT_SEL ".product-card" 10
  ELSE
    ECHO "Reached final page"
    BREAK
  END
END

Recipe 4: Parallel Tab Broadcasting

macros/broadcast.mac
# Open 3 isolated tabs
NEW_ISOLATED_TAB "https://example.com/page1"
NEW_ISOLATED_TAB "https://example.com/page2"
NEW_ISOLATED_TAB "https://example.com/page3"

# Mirror all subsequent actions simultaneously across all 3 tabs
BROADCAST ON
SCROLL down 500
SMART_CLICK ".claim-button"
BROADCAST OFF

Recipe 5: Full-Stack Web Scraping & Data Pipeline

macros/scraper_suite.mac
# 1. Custom runtime variables
VAR target_domain = "https://example.com/catalog"
VAR run_id = <datetime>
ECHO "Starting Scraper Pipeline <run_id> for <target_domain>"

# 2. Navigate and clean popups
GOTO "<target_domain>"
WAIT 2
DISMISS_POPUPS

# 3. Dynamic search & filter batch fill
FILL_FORM "{\"input[name='search']\":\"electronics\",\"#in_stock\":true}"
CLICK "button[type='submit']"
WAIT_TEXT ".results-header" "Results" 10

# 4. Scroll until at least 25 items load
SCROLL_UNTIL ".product-card" 25 15 400

# 5. Extract JSON-LD, Metadata, Links, and Images
EXTRACT_JSON_LD "output/schema_<run_id>.json"
EXTRACT_METADATA "output/meta_<run_id>.json"
EXTRACT_LINKS "a.product-link" "output/links_<run_id>.csv"
DOWNLOAD_IMAGES ".product-card img" "output/images/<run_id>" 15

# 6. Extract Table to CSV & Export Markdown Report
IF EXIST "table.specs-table"
    EXTRACT_TABLE "table.specs-table" "output/specs_<run_id>.csv"
END
SAVE_MARKDOWN "output/summary_<run_id>.md" "main.content"
SAVE_PDF "output/catalog_<run_id>.pdf" false true

🎥 9. Live Action Recorder (-record)

Instead of hand-coding macros, record your live browser actions in real time:

Recording Workflow
# 1. Start live recording mode
rbsm_windows_amd64.exe -record=my_flow.mac

# 2. A browser opens. Navigate, click, and type naturally.
# 3. Close the browser window or press Ctrl+C to save my_flow.mac.

# 4. Replay the macro anytime
rbsm_windows_amd64.exe -macros=my_flow.mac

🎲 10. Dynamic Variables & Placeholders

RBSM macros evaluate dynamic placeholders at runtime to generate unique usernames, delay jitter, and dynamic session parameters:

Placeholder Description Example Usage Sample Output
<random> Random 6-char lowercase alphanumeric string. TYPE "#user" "user_<random>" user_x8a4f9
<random:N> Random N-character alphanumeric string. TYPE "#user" "test_<random:8>" test_k9x2m4p1
<random:min-max> Random integer within [min, max] range. SS "shot_<random:100-999>.png" shot_482.png
<random:alpha:N> Random alphabetic letters only (N chars). TYPE "#name" "<random:alpha:10>" JqLmpWtxZe
<random:digits:N> Random numeric digits only (N digits). TYPE "#phone" "081<random:digits:8>" 08194827103
<uuid> Random UUID v4 string. GOTO "https://site.com?id=<uuid>" c4a8d09f-6e1b-4f72-9b6a-8b1e4f3a2c1d
<timestamp> Current Unix timestamp in milliseconds. SS "debug_<timestamp>.png" debug_1723824000123.png
<datetime> Formatted date and time (YYYYMMDD_HHMMSS). SS "backup_<datetime>.png" backup_20260906_173000.png
<date> Current date (YYYY-MM-DD). COOKIE "session_date" "<date>" 2026-09-06
<time> Current time (HHMMSS). COOKIE "session_time" "<time>" 173000
<rbsm_ip> Active session proxy exit IP address. ECHO "Connected via <rbsm_ip>" Connected via 198.51.100.42
<rbsm_country> Active session 2-letter country code. ECHO "Country: <rbsm_country>" Country: US
<i> / <I> / <loop_i> Current zero-based index of innermost LOOP. ECHO "Iteration: <i>" Iteration: 0
<index> / <loop_index> Alias for current zero-based loop index. ECHO "Index: <index>" Index: 0
<i+1> / <loop_count> Current 1-based iteration step count of innermost LOOP. ECHO "Step: <i+1>" Step: 1
<tabs> / <tab_count> Current count of open browser tabs in active context. ECHO "Tabs: <tabs>" Tabs: 2
<variable_name> Dynamic runtime variable defined via VAR or SET_VAR. TYPE #tok "<auth_token>" eyJhbGciOi...

⚡ 11. Modern JavaScript Macro Engine (.js) RECOMMENDED

RBSM features a native in-process JavaScript execution engine compiled directly into the binary. It delivers sub-millisecond execution and full ECMAScript flexibility with zero external dependencies — no Node.js, Python, or npm installation is required.

⚡ Zero External Dependencies
Runs standalone inside the single RBSM executable. No Node.js runtime, Python packages, or external drivers required.
🧠 Native JS Language Power
Use standard let/const variables, for/while loops, functions, try/catch blocks, regex, and JSON parsing.
🔄 Dual Syntax Support
All methods support both modern camelCase (e.g. smartClick()) and legacy-familiar snake_case (e.g. smart_click()).
🛡️ Complete 1:1 Engine Parity
Direct access to human Bézier mouse trajectories, Turnstile piercing, IP shift guards, DoH encryption, and network mocking.
Executing JavaScript Macros
# Execute modern JavaScript macro on Windows
rbsm_windows_amd64.exe -macros=macros/checkout.js

# Headless execution on Linux Cloud VPS
sudo ./rbsm_linux_amd64 -macros=macros/checkout.js -headless=true -proxy=true

JavaScript Macro API Catalog

The Goja runtime provides 302 native method bindings across 18 distinct automation categories. Every API method supports both camelCase and snake_case conventions:

1. Navigation & Page Lifecycle

Function (camelCase) Aliases (snake_case) Parameters Description
goto(url, [referrer]) navigate url: string
referrer: optional string
Navigates the current tab to the target URL (supports comma-separated rotation).
waitLoad() wait_load none Waits until the DOM and network idle states settle.
reload() - none Reloads the current page.
back() goBack, go_back none Navigates one step backward in browser history.
forward() goForward, go_forward none Navigates one step forward in browser history.
getUrl() get_url none Returns the current page URL as a string.
getTitle() get_title none Returns the document title as a string.
Example: 1. Navigation & Page Lifecycle
goto("https://example.com", "https://google.com,https://bing.com");
waitLoad();
console.log("On page:", getTitle(), getUrl());

2. Mouse & Coordinates (Bézier Physics)

Function (camelCase) Aliases (snake_case) Parameters Description
smartClick(target) smart_click target: selector or visible text Intelligent click targeting text or CSS selector across Main DOM, Shadow DOM & frames.
click(target) - selector: string OR x, y: numbers Clicks element by selector or at exact viewport coordinates (x, y) with Bézier curve.
clickRandom(selector) click_random selector: CSS selector Clicks a random visible element matching the selector.
clickAt(x, y) click_at x, y: integer coordinates Dispatches physical mouse click at coordinates (Canvas, sliders, games).
hover(selector) - selector: CSS selector OR x, y: numbers Moves mouse cursor smoothly over element or coordinates.
hoverAt(x, y) hover_at x, y: coordinates Moves mouse cursor to explicit viewport coordinates.
drag(x1, y1, x2, y2) - x1, y1, x2, y2: coordinates Drags mouse from (x1, y1) to (x2, y2) with interpolated intermediate movements.
Example: 2. Mouse & Coordinates (Bézier Physics)
click("button#submit");
smartClick("Sign In");
clickAt(450, 320);
drag(100, 100, 300, 100);

3. Keyboard & Input Form

Function (camelCase) Aliases (snake_case) Parameters Description
type(selector, text) typeText, type_text selector: string
text: string
Types text into input element.
typeHuman(selector, text) type_human selector: string
text: string
Types text with humanized jitter & variable cadence (defeats bot biometrics).
clear(selector) - selector: string Clears the value of an input or textarea via select-all and backspace.
pressKey(key) press_key key: string Presses key (e.g. "Enter", "Tab", "Escape", "Backspace", "Control+a").
select(selector, value) selectOption selector: string
value: option value
Selects <option> value in a <select> dropdown.
fillForm(formData) fill_form formData: object or JSON string Batch fills entire form fields automatically.
Example: 3. Keyboard & Input Form
clear("input[name='query']");
typeHuman("input[name='query']", "search query");
pressKey("Enter");
select("select#country", "US");

4. Resilient Scrolling

Function (camelCase) Aliases (snake_case) Parameters Description
scrollToBottom([maxScrolls], [delayMs]) scroll_to_bottom maxScrolls: default 5
delayMs: default 500ms
Progressively scrolls to page bottom until settled (fail-safe).
scrollIntoView(selector) scroll_into_view selector: CSS selector Scrolls element into viewport smoothly.
scrollUntil(selector, targetCount, [maxScrolls], [delayMs]) scroll_until selector: CSS selector
targetCount: int target
Scrolls until N matching elements are rendered in DOM.
scroll(direction, [pixels]) - direction: "down", "up", "bottom", "top"
pixels: int (default 500)
Scrolls in specified direction by pixels.
Example: 4. Resilient Scrolling
scroll("down", 400);
scrollIntoView("footer");
scrollToBottom(5, 300);
scrollUntil(".item-card", 20, 10, 500);

5. Waiting & Timing

Function (camelCase) Aliases (snake_case) Parameters Description
wait(seconds) sleep(ms) seconds: number OR min, max range Pauses execution for fixed or randomized seconds (e.g. wait(1, 3)).
waitFor(selector, [timeoutSec]) wait_for, waitSel, wait_sel selector: string
timeoutSec: default 10s
Waits until element appears and renders in DOM.
waitForGone(selector, [timeoutSec]) wait_for_gone, waitSelGone, wait_sel_gone selector: string
timeoutSec: default 10s
Waits until element is removed or hidden.
waitForText(text, [timeoutSec], [selector]) wait_for_text text: string
timeoutSec: int
selector: optional
Waits until text appears on page.
Example: 5. Waiting & Timing
wait(2);            // Fixed 2s wait
wait(1, 3);         // Random wait between 1s and 3s
waitFor(".modal-content", 15);
waitForGone("#loading-spinner", 10);
waitForText("Payment Successful", 10);

6. DOM & Element Inspection

Function (camelCase) Aliases (snake_case) Returns Description
exist(selector) - boolean Checks if element matches CSS selector.
smartExist(target) smart_exist boolean Checks if text or selector exists across Main DOM, Shadow DOM & frames.
getText(selector) get_text string Retrieves inner text of element.
getHtml([selector]) get_html string Retrieves outer HTML of element or full page.
getAttribute(selector, attribute) get_attribute string Reads specific HTML attribute value.
getElementCount(selector) get_element_count number Returns number of elements matching selector.
getInteractiveElements() get_interactive_elements string Dumps discovered buttons, inputs, links & selectors.
getDomSnapshot([savePath]) get_dom_snapshot string Captures full DOM snapshot (and saves if path given).
Example: 6. DOM & Element Inspection
if (exist("div.alert-danger")) {
    console.warn("Error message:", getText("div.alert-danger"));
}
var count = getElementCount("article.post");
console.log("Posts on page:", count);

7. In-Browser Evaluation (Chrome V8)

Runs arbitrary JavaScript inside the page's isolated Chrome V8 sandbox over CDP. Multiline & Callback Support: evaluate() accepts single-line strings, multiline template literals (backticks), or native JavaScript functions directly:

Function (camelCase) Aliases (snake_case) Parameters Description
evaluate(codeOrFn) runScript, run_script string OR function Evaluates code in browser V8 context and returns value (synchronously awaits Promises).
addInitScript(codeOrFn) add_init_script string OR function Injects script to run automatically before any page script executes.
Example: 7. In-Browser Evaluation (Chrome V8)
// 1. Single-line evaluation
var href = evaluate("location.href");

// 2. Multiline evaluation using ES6 Template Literals (Backticks)
var pageData = evaluate(`
    (() => {
        const title = document.title;
        const links = Array.from(document.querySelectorAll("a")).map(a => a.href);
        const user = localStorage.getItem("username");
        return { title, linkCount: links.length, user };
    })()
`);
console.log("Extracted page data:", pageData.title, pageData.linkCount);

// 3. Multiline evaluation passing a native JavaScript Function directly
var metrics = evaluate(() => {
    const perf = window.performance.timing;
    const loadTime = perf.loadEventEnd - perf.navigationStart;
    const memory = window.performance.memory ? window.performance.memory.usedJSHeapSize : 0;
    return { loadTime, memory };
});
console.log("Page load time (ms):", metrics.loadTime);

// 4. Injected init script (runs before any page script on every navigation)
addInitScript(() => {
    Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
    window.__custom_injected__ = true;
});

8. Assertions & Operational Gates

Assertions validate application state and fail the macro if unsatisfied (unless -macros-continue-on-error is enabled).

Function (camelCase) Aliases (snake_case) Description
assert(condition, [msg]) assert Asserts condition is truthy, optionally with custom message.
assertEquals(actual, expected, [msg]) assert_equals, assertEq, assert_eq Asserts strict equality between two values.
assertExist(selector) assert_exist Asserts element matching selector is present.
assertSmartExist(target) assert_smart_exist Asserts text or element is present across all DOM trees and frames.
assertUrl(pattern) assert_url Asserts current URL contains pattern.
assertTitle(pattern) assert_title Asserts document title contains pattern.
assertText(selector, expected) assert_text Asserts element text matches expected exactly.
assertContains(target, sub) assert_contains Asserts element DOM text or in-memory JS variable contains substring.
assertEvaluate(exprOrFn) assert_evaluate Asserts JS expression or multiline callback () => { ... } evaluates truthy.
assertConsole(sub) assert_console Asserts browser console contains substring.
assertDownload(filename) assert_download Asserts downloaded file exists.
assertRequestContain(pattern) assert_request_contain Asserts URL pattern was captured in network requests.
assertRequestModified(rule) assert_request_modified Asserts rule intercepted and modified a network request.
Example: 8. Assertions & Operational Gates
assertUrl("dashboard");
assertText("h1", "Welcome Back");

// In-memory variable & state equality assertions
assertEquals(getTabsCount(), 2);
assert(getContextTabsCount() >= 1, "Context must have at least 1 tab");
assert(getCtr() <= 3.5, "CTR rate exceeded limit");
const userIP = getIp();
assertContains(userIP, "44.60");

// Multiline Callback AssertEvaluate
assertEvaluate(() => {
    return document.querySelectorAll(".item").length > 5;
});

9. Web Scraping & Data Extraction

Function (camelCase) Aliases (snake_case) Parameters Description
extractTable(selector, [path]) extract_table selector: table selector
path: optional file
Parses HTML <table> into array of row objects / CSV.
extractList(selector, [path]) extract_list selector: list item selector Extracts all list items matching selector into an array.
extractLinks([selector], [path]) extract_links selector: default "a" Extracts array of { text, href } links.
extractMarkdown([path], [selector]) extract_markdown path: optional file Converts page or element to Markdown article.
extractMetadata([path]) extract_metadata path: optional file Extracts OpenGraph, meta tags & page metadata.
extractJsonLd([path]) extract_json_ld path: optional file Extracts schema.org JSON-LD structured data.
Example: 9. Web Scraping & Data Extraction
var links = extractLinks("a.nav-link");
for (var i = 0; i < links.length; i++) {
    console.log(links[i].text, "->", links[i].href);
}

var rows = extractTable("table.data-grid", "output/table.json");
var md = extractMarkdown("output/page.md");

10. Screenshots, PDF & Native File System I/O (`fs`)

Browser Output Generation
Function (camelCase) Aliases (snake_case) Parameters Description
screenshot([path]) - path: optional output path Captures full page screenshot (.png).
elementScreenshot(sel, [path]) element_screenshot sel: selector
path: file
Captures cropped screenshot of specific element.
saveHtml([path], [selector]) save_html path: output path Saves rendered page or element HTML.
savePdf([path], [landscape], [bg]) save_pdf path: file path Prints page to PDF.
saveSnapshot([path]) save_snapshot path: file path Saves comprehensive DOM snapshot.
saveTracking([path]) save_tracking path: file path Saves captured network requests to file.
appendCsv(path, valuesArray) append_csv path: CSV path
valuesArray: array
Appends a row of values to CSV file.
download(path, [url]) - path: save path
url: optional URL
Downloads remote file or awaits browser download.
downloadImages(sel, dir, [max]) download_images sel: selector
dir: folder
Downloads all images matching selector to folder.
Native File System I/O (fs)

Available via the fs object (matching Node.js conventions) or directly as top-level global functions:

Function / Method Global Alias Description
fs.readFile(path), fs.readFileSync readFile(path), read_file Reads file contents as UTF-8 string.
fs.writeFile(path, content), fs.writeFileSync writeFile(path, content), write_file Writes string to file (auto-creates parent dirs).
fs.appendFile(path, content), fs.appendFileSync appendFile(path, content), append_file Appends text to file (auto-creates parent dirs).
fs.exists(path), fs.existsSync fileExists(path), file_exists Checks if a file or directory exists (returns boolean).
fs.unlink(path), fs.unlinkSync, fs.removeFile removeFile, remove_file, deleteFile, delete_file Deletes a local file.
fs.mkdir(path), fs.mkdirSync mkdir(path) Creates a directory tree recursively.
fs.readJson(path) readJson(path), read_json Reads file and parses as JSON object/array.
fs.writeJson(path, data, [indent]) writeJson(path, data), write_json Serializes data and writes formatted JSON to file.
Example: 10. Screenshots, PDF & Native File System I/O (`fs`)
// Native File System Example
writeFile("reports/data.txt", "Initial content\n");
appendFile("reports/data.txt", "Appended line\n");

if (fileExists("reports/data.txt")) {
    const text = readFile("reports/data.txt");
    console.log("File content:", text);
}

// JSON helpers
writeJson("output/result.json", { status: "success", ip: getIp() });
const config = readJson("output/result.json");
console.log("Parsed JSON:", config.ip);

11. Multi-Tab & Context Isolation

Function (camelCase) Aliases (snake_case) Description
newTab([url]) new_tab Opens a new browser tab and navigates to URL.
newIsolatedTab([url], [config]) new_isolated_tab Opens an isolated/incognito browser tab with independent cookies & storage.
switchTab(tabId) switch_tab Switches active focus to specified Tab ID, relative index (0, 1), or special target ("popup", "main").
closeTab([tabId]) close_tab Closes tab (defaults to current active tab).
listTabs() list_tabs Returns array of all open tabs across the entire browser { id, url, title, type }.
listContextTabs() list_context_tabs Returns array of open tabs strictly within this execution context.
hasPopup() has_popup Returns true if current context (or any worker in broadcast) has a popup open.
switchPopup() switch_popup Switches focus to context's popup tab. Safe no-op if no popup opened.
closePopup() close_popup Closes context's popup tab and restores focus to main tab. Safe no-op if no popup.
switchMain() switch_main Switches focus back to context's primary/root tab.
getContextTabsCount() contextTabsCount, get_context_tabs_count Returns count of tabs strictly within this worker's context.
Example: 11. Multi-Tab & Context Isolation
// Context-Locked Popup Handling (Single-Tab & Broadcast Mode):
if (hasPopup()) {
    incClick();
    wait(2, 4);

    // Switch this worker to its popup:
    switchPopup();
    hover(200, 300);
    scroll("down", 500);
    wait(3, 5);

    // Closes popup and automatically restores focus to context root tab:
    closePopup();
}

12. Frames & iFrames

Function (camelCase) Aliases (snake_case) Description
enterFrame(selector) enter_frame, enterIframe, enter_iframe Enters context of an iframe / OOPIF by CSS selector.
exitFrame([mode]) exit_frame, exitIframe, exit_iframe Exits frame context back to "top" (default) or "parent".
Example: 12. Frames & iFrames
enterFrame("iframe#payment-frame");
type("input#card-number", "424242424242");
exitFrame(); // Return to main page context

13. Dialogs, Popups, Cookies & Storage

Function (camelCase) Aliases (snake_case) Description
dismissPopups() dismiss_popups Closes cookie consent banners and modal overlays.
acceptDialog([promptText]) accept_dialog Accepts JS dialog (alert, confirm, prompt).
dismissDialog() dismiss_dialog Dismisses / cancels JS dialog modal.
setCookie(name, val, [domain]) set_cookie Sets HTTP cookie in active browser context.
getAllCookies() get_all_cookies Returns array of all cookies in context.
setStorage(key, val, [type]) set_storage Sets storage item ("local" default or "session").
getStorage(key, [type]) get_storage Retrieves storage item value.
Example: 13. Dialogs, Popups, Cookies & Storage
dismissPopups();
setCookie("session_id", "xyz123", ".example.com");
setStorage("theme", "dark", "local");

14. Network Interception & Rewriting (Rewrite, Abort, Mock)

URL, Header & Payload Mutation (networkRewrite)

Intercepts and mutates requests and responses matching the URL pattern at the engine layer.

Supported networkRewrite Options:
  • url: Redirect request to target URL.
  • urlAdd: Object or array to append query parameters ({ ref: "rbsm" }).
  • urlDel: Array of query parameters to strip from URL.
  • urlReplace: Array of "old=new" replacements in URL.
  • method: Change HTTP method ("POST", "GET", "PUT").
  • post: Replace POST body entirely.
  • headers: Injected/edited request headers ({ "Authorization": "Bearer ..." }).
  • delHeaders: Array of request headers to delete (["Cookie", "Referer"]).
  • bodyEdit: Array of find/replace pairs in POST body (['"test":false="test":true']).
  • respHeaders: Headers added to the HTTP response ({ "X-Intercepted": "true" }).
  • respDelHeaders: Array of response headers to strip (["Set-Cookie"]).
  • respReplace: Array of find/replace text pairs in response payload (['"free"="pro"']).
  • respBody: Overrides response body completely.
  • json: true to only apply to JSON responses.
  • types: Array or comma-delimited resource types (["xhr", "fetch"]).
  • skipAssets: true to ignore images, fonts, styles.
  • response: true to abort at response stage.
Example: Live Response Replacement
// Example: Live Response Replacement
networkRewrite("*/api/profile*", {
    respHeaders: { "X-RBSM-Patched": "true" },
    respReplace: [
        '"is_premium":false="is_premium":true',
        '"ads":true="ads":false'
    ]
});
Request Aborting & Synthetic Mocking
Example: Blocking Ads & Synthetic Mock Responses
// Block tracker domains
networkAbort([
    "*google-analytics.com*",
    "*doubleclick.net*",
    "*facebook.com/tr*"
]);

// Return synthetic mock response with ZERO network requests:
networkMock("*/api/v1/user*", {
    status: 200,
    body: JSON.stringify({ id: 101, name: "Alice", active: true }),
    headers: { "Content-Type": "application/json" }
});
Convenience Shorthands
Function (camelCase) Aliases (snake_case) Description
networkRedirect(pattern, url) network_redirect Shorthand for redirecting requests to a new URL.
modifyHeaders(pattern, headers) modify_headers Injects or updates request headers.
modifyResponseBody(pattern, old, new) modify_response_body Replaces strings in response payloads.
mockResponse(pattern, body, [status]) mock_response Shorthand for networkMock / network_mock.
networkBlock(pattern) network_block, network_abort Shorthand for networkAbort / network_abort.
getNetworkRules() get_network_rules Returns array of all active network rules.
clearNetworkRules() clear_network_rules Clears all active network interception rules.
Example: Network Shorthands
// Convenience Shorthands
networkRedirect("*/old-endpoint*", "https://new-endpoint.com/api");
modifyHeaders("*/api/*", { "X-Client-ID": "macro-agent-1" });
modifyResponseBody("*/status*", '"status":"error"', '"status":"ok"');
clearNetworkRules(); // Clears all rules

15. Network Inspection & Response Capture

Function (camelCase) Aliases (snake_case) Description
waitResponse(pattern, [savePath], [timeoutSec]) waitForResponse, wait_response, wait_for_response Awaits matching response and returns response body string. Optionally saves to disk.
getNetworkRequests([filter]) get_network_requests Returns array of captured request objects.
getNetworkRequest(idOrUrl) get_network_request Returns single request details by ID or URL filter.
getNetworkResponse(requestId) get_network_response Returns { body: string, base64: bool } for request ID.
getNetworkSummary() get_network_summary Returns stats { total, by_type, by_status, by_host }.
clearNetworkLog() clear_network_log Clears in-memory captured request history.
netLog([filter]) net_log Outputs formatted request summary to results.
netReq(id, [path]) net_req Dumps request metadata as JSON.
netRes(id, [path]) net_res Dumps or saves response body.
getConsoleLogs() get_console_logs Returns array of browser console log objects.
getConsoleErrors() get_console_errors Returns array of console error/assert entries.
Example: 15. Network Inspection & Response Capture
goto("https://httpbin.org/get");

// Wait for a response and read it directly into JavaScript!
var jsonStr = waitResponse("httpbin.org", 10);
var data = JSON.parse(jsonStr);
console.log("Origin IP from response:", data.origin);

// Inspect captured requests
var requests = getNetworkRequests({ url: "httpbin" });
for (var i = 0; i < requests.length; i++) {
    console.log(requests[i].method, requests[i].status, requests[i].url);
}

16. Security, IP Guard & DNS-over-HTTPS (DoH)

Function (camelCase) Aliases (snake_case) Description
getIp() get_ip, getExitIp, get_exit_ip, getProxyExitIp, get_proxy_exit_ip Returns current proxy / spoof exit IP string (resolves isolated tab profile IP or main browser IP).
getRealIp() get_real_ip, getRealIP, realIp, real_ip Returns host machine's actual unproxied external IP (browser.myip).
getCountry() get_country Returns active session country code (resolves isolated tab profile country or main browser country).
guardIp([enabled]) guard_ip, guardIpShift, guard_ip_shift Enables proxy exit IP shift detection (fails if upstream proxy IP changes).
checkIp() check_ip, assertIpUnchanged, assert_ip_unchanged Executes immediate proxy exit IP check; returns boolean or throws error.
proxyAuth(user, pass) proxy_auth Configures HTTP/SOCKS proxy authentication credentials on the fly.
doh(provider, [mode]) dnsOverHttps, dns_over_https Sets DoH DNS provider ("cloudflare", "google", "quad9", "adguard"). Automatically pre-scanned before browser launch!
Dynamic Tab-Isolated <rbsm_ip> & <rbsm_country>: When using networkRewrite("*", { headers: { "X-Forwarded-For": "<rbsm_ip>" } }), <rbsm_ip> and <rbsm_country> dynamically resolve per request: - Requests from the main browser inject the main browser IP/country. - Requests from isolated tabs (newIsolatedTab) automatically inject that tab profile's unique IP/country!
Example: 16. Security, IP Guard & DNS-over-HTTPS (DoH)
doh("cloudflare", "secure");

networkRewrite("*", {
    headers: {
        "X-Forwarded-For": "<rbsm_ip>",
        "X-Client-IP": "<rbsm_ip>"
    },
    skipAssets: true
});

guardIp(true);
console.log("Main Exit IP:", getIp(), "Country:", getCountry());

var tabId = newIsolatedTab("https://site.com");
switchTab(tabId);
console.log("Isolated Tab Exit IP:", getIp(), "Country:", getCountry());

17. Concurrent Multi-Tab Broadcast

Method Aliases Parameters Description
broadcast(callback) broadcast((tabIndex, totalTabs) => { ... }) callback (function) Concurrent Multi-Tab Execution: Spawns independent parallel Goroutines and isolated Goja runtimes for each open tab. Tabs execute their own loops, randomized delays, and popup handling concurrently without stalling siblings. In -debug mode, browser actions and console logs are automatically tagged with [Tab X].
Example: 17. Concurrent Multi-Tab Broadcast
broadcast((tabIndex, totalTabs) => {
    console.log(`Worker tab ${tabIndex + 1} of ${totalTabs} running`);
    scrollToBottom(3, 400);
    click("button.accept");
    wait(2);
});

18. Metrics, Logging & State

Function (camelCase) Aliases (snake_case) Description
console.log(...) - Prints log message to terminal stdout (in debug mode) or routes to worker status.
console.warn(...) - Prints warning message to terminal or routes to worker warning.
console.error(...) - Prints error message to terminal or routes to worker error.
setVar(name, val) set_var Stores macro variable in runner context.
getVar(name) get_var Retrieves macro variable value.
incClick() countClick, count_click, inc_click Increments RBSM click counter metrics.
decClick() deleteClick, delete_click, dec_click Decrements RBSM click counter metrics.
getCtr() get_ctr Returns current session CTR percentage as number (e.g. 2.5 for 2.5%).
getTabsCount() tabsCount, get_tabs_count, tabs_count Returns total count of all open browser tabs (global across entire browser).
getContextTabsCount() contextTabsCount, get_context_tabs_count Returns count of tabs strictly in the current execution context.
clickMarker(bool) click_marker Toggles visual click coordinate crosshair overlay.

Comprehensive Production JavaScript Macro Recipe

This resilient, production-ready recipe demonstrates organic referrer rotation, Cloudflare Turnstile handling, natural human typing, structured table extraction, and audit assertions:

Production Macro: Full E-Commerce Flow (checkout.js)
// macros/checkout_flow.js
// Modern, robust automation script using RBSM JavaScript API

console.log("[*] Launching checkout automation flow...");

// 1. Configure pre-launch DoH & Dynamic Header Injection
doh("cloudflare", "secure");
networkRewrite("*", {
    headers: { "X-Forwarded-For": "<rbsm_ip>" },
    skipAssets: true
});

// 2. Navigate with randomized organic referrer
goto("https://target-portal.com/products", "https://google.com,https://bing.com");
waitLoad();
wait(1.5, 2.5);

// 3. Handle Cloudflare Turnstile or security challenge if present
if (smartExist("#turnstile-box, iframe[src*='challenges.cloudflare']")) {
    console.log("[!] Cloudflare challenge detected — solving with human physics...");
    wait(1.0, 1.8);
    smartClick("#turnstile-box, iframe[src*='challenges.cloudflare']", 10);
    wait(3.0);
}

// 4. Search and select items
waitFor("input[name='search']", 10);
typeHuman("input[name='search']", "mechanical keyboard");
pressKey("Enter");
wait(2.0);

// 5. Scrape search results
let items = extractList(".product-title");
console.log("[+] Found " + items.length + " products on page");

// 6. Click the first matching product
smartClick(".product-card:first-child a", 5);
waitFor(".btn-add-to-cart", 10);
smartClick(".btn-add-to-cart", 5);
wait(1.5);

// 7. Fill checkout form with dynamic data
let orderEmail = "buyer_" + Math.random().toString(36).substring(2, 8) + "@example.com";
type("input[name='email']", orderEmail);
typeHuman("input[name='name']", "Alex Hunter");
type("input[name='address']", "742 Evergreen Terrace");

// 8. Verify order balance and take audit screenshot
assertSmartExist(".order-summary");
screenshot("order_preview.png");
console.log("[✓] Checkout flow completed successfully!");

📑 11.2 Complete Macro Commands Reference (A–Z) (.mac) LEGACY DSL

⚠️ Notice: Legacy .mac Format is in Maintenance Mode (Soft-Deprecated)

All existing .mac scripts remain 100% backward-compatible and fully supported by the RBSM engine runtime. However, all ongoing feature enhancements, performance optimizations, and rich control-flow capabilities are built exclusively for the Modern JavaScript Macro Engine (.js).

We strongly recommend writing all new automation routines in .js.

An exhaustive, field-tested reference guide for all 50+ macro automation commands and aliases in the legacy .mac engine. Each command includes detailed mechanics, parameter schemas, anti-bot advantages, and executable code snippets.

A. Navigation & Tab Management

Command Usage Description
GOTO GOTO "url1,url2" ["ref1,ref2"] Navigate to URL (supports comma-separated URLs and referrers for randomized rotation, alias: NAV).
RELOAD RELOAD Reload the currently active page.
BACK BACK Navigate backward in browser history.
FWD FWD Navigate forward in browser history.
NEW_TAB NEW_TAB ["https://url.com"] Open a new tab in the default browser context and switch active focus to it.
NEW_ISOLATED_TAB NEW_ISOLATED_TAB ["url"] [options...] Open a 100% storage-isolated tab in its own BrowserContext with unique device profile (supports async=true / nowait, alias: NEW_INCOGNITO_TAB).
SWITCH_TAB SWITCH_TAB 0|1|2|pattern|last|next|prev|<id> Switch active tab by 0-based index (0, 1, 2), URL or title pattern (*checkout*, stripe.com), last (most recent popup), next, prev, or target ID.
CLOSE_TAB CLOSE_TAB [0|1|pattern|last|<id>] Close tab by index, URL pattern, last, target ID, or active tab if omitted / "current" (disposes isolated context when last tab closes).
TABS TABS List all open tabs with target IDs, page titles, URLs, and context isolation status.
GOTO / NAV Navigation & Referrer Spoofing
  • Underlying Power: Navigates the browser engine to the target URL with automatic referrer header and document.referrer injection. Supports comma-separated rotation on both URL and Referrer parameters.
  • Parameters: url (string or comma-separated list), referrer (optional string or comma-separated list).
  • Anti-Bot Edge: Spoofs organic search engine traffic (Google, Bing, Yahoo, DuckDuckGo) without leaking CDP automation properties.
  • Example: GOTO "https://target.com/p1,https://target.com/p2" "https://google.com,https://bing.com"
NEW_ISOLATED_TAB / NEW_INCOGNITO_TAB Multi-Context Concurrency
  • Underlying Power: Creates a completely isolated Chromium BrowserContext partition with 100% segregated cookies, localStorage, indexedDB, and cache.
  • Parameters: url (optional target URL), options (optional flags: async=true / nowait).
  • Anti-Bot Edge: Prevents cross-session fingerprint contamination, supercookies, and token correlation across concurrent accounts.
  • Example: NEW_ISOLATED_TAB "https://portal.example.com" async=true
SWITCH_TAB, CLOSE_TAB & Tab Discovery Tab Lifecycle & URL Targeting
  • Underlying Power: Precise tab targeting and zero-guesswork URL inspection. SWITCH_TAB supports 0-based indices, URL/title wildcard patterns (e.g. SWITCH_TAB "*checkout*"), last (auto-focusing new popups or OAuth windows), next, prev, or CDP target IDs. CLOSE_TAB closes matching tabs and automatically cleans up memory.
  • Inspection Primitives: Use VAR total TABS (or placeholder <tabs>) for open tab count, VAR u TAB_URL <idx> for instant tab URL inspection, and VAR idx TAB_FIND "*stripe.com*" to find matching tab indices directly without switching.
  • Example: SWITCH_TAB "*checkout*" or dynamic loop: LOOP <tabs> <idx>

B. Mouse & Keyboard Interaction

Command Usage Description
CLICK CLICK "#submit-btn" | CLICK x y Move mouse with Bézier trajectory and click element matching CSS selector or direct viewport coordinates.
CLICK_AT CLICK_AT 250 400 Click directly at specific viewport coordinates (X, Y).
CLICK_MARKER CLICK_MARKER ON | OFF Toggle visual red dot marker overlay at clicked coordinates for screenshot verification (default: OFF, aliases: SHOW_CLICK, SHOW_CLICKS).
CLICK_RANDOM CLICK_RANDOM "selector" Randomly select and click one visible element among all matches for realistic pagination or browsing (alias: RANDOM_CLICK).
SMART_CLICK SMART_CLICK "skip,close,continue" [timeout_s] Deep multi-frame click: auto-searches main DOM, open/nested Shadow DOMs & iframes with text/CSS fallback list (default timeout: 10s).
SMART_EXIST SMART_EXIST "video,iframe,skip,close" Deep check if element or text exists across main DOM, Shadow DOMs, and all iframes (pushes boolean to condition stack).
DRAG DRAG x1 y1 x2 y2 Drag / swipe smoothly from coordinate (x1, y1) to (x2, y2).
TYPE TYPE "input#search" "laptop" Clear field and type text into input element (pierces Shadow DOM & iframes).
TYPE_HUMAN TYPE_HUMAN "#search" "laptop" Type character-by-character via real keyboard events with natural randomized keystroke delays.
CLEAR CLEAR "input#search" Clear existing text in an input field.
HOVER HOVER "#menu" | HOVER x y Move mouse cursor smoothly over element matching CSS selector OR direct viewport coordinates (X, Y) (dual-syntax). Emulates human Bézier trajectory and settle jitter; safe no-op on mobile profiles.
HOVER_AT HOVER_AT 350 420 Hover mouse cursor directly at specific viewport coordinates (X, Y) with human Bézier curve trajectory (aliases: MOUSE_MOVE, MOVE_TO; safe no-op on mobile profiles).
SELECT SELECT "select#country" "US" Select dropdown option in <select> element by value.
PRESS PRESS "Enter" Dispatch keyboard keypress event (Enter, Tab, Escape, Control+a, Backspace, ArrowDown, aliases: KEY, KEY_PRESS).
SCROLL SCROLL up|down|top|bottom [px] Scroll page direction and optional pixel offset (e.g. SCROLL down 500).
CLICK & CLICK_AT Bézier Trajectory Physics
  • Underlying Power: Generates mathematical cubic Bézier curve paths with realistic acceleration, overshoot, and micro-jitter curves. Emits native hardware events with isTrusted: true.
  • Parameters: CSS selector string OR viewport coordinates (x, y).
  • Anti-Bot Edge: Completely defeats mouse trajectory anomaly models (e.g. Cloudflare Turnstile, DataDome, Shape Security).
  • Example: CLICK "button[type='submit']" or CLICK_AT 420 680
HOVER & HOVER_AT Human Cursor Dynamics
  • Underlying Power: Moves the mouse cursor along smooth cubic Bézier curves with randomized deflection, velocity curves, and settle hesitation. Dispatches native mouseMoved events to trigger hover menus, tooltips, and anti-bot behavioral telemetry.
  • Dual-Syntax Support: Just like CLICK, HOVER accepts both formats:
    • CSS Selector: HOVER "li.nav-dropdown" (auto-resolves element viewport center coordinates)
    • Coordinates $(X, Y)$: HOVER 450 320 (direct coordinate hover, auto-detected when two integers are provided)
  • Dedicated Coordinate Macro: HOVER_AT <x> <y> (aliases: MOUSE_MOVE, MOVE_TO) provides an explicit coordinate-only command matching CLICK_AT.
  • Mobile Anti-Bot Safety: On mobile emulation profiles, safely acts as a clean no-op without dispatching synthetic desktop cursor movements to avoid mobile-anomaly bot detection flags.
  • Examples: HOVER "li.nav-dropdown", HOVER 450 320, or HOVER_AT 450 320
SMART_CLICK & SMART_EXIST Deep Multi-Tree Resolvers
  • Underlying Power: Simultaneously pierces Main DOM, open & closed Shadow DOM subtrees, and nested Out-of-Process iFrames (OOPIFs). Accepts comma-separated CSS and plain-text fallback candidates.
  • Parameters: selector_or_text, timeout_s (default: 10s).
  • Scraping Superpower: Clicks buttons inside embedded checkout widgets, video player controls, and login overlays without manual frame switching.
  • Example: SMART_CLICK "button:contains(Accept), #cookie-agree, 'Agree & Continue'" 15
TYPE_HUMAN Biometric Keystroke Dynamics
  • Underlying Power: Types text character-by-character using non-deterministic Gaussian inter-key latencies (40ms–180ms), including realistic shift-key transitions and keyup/keydown timing.
  • Anti-Bot Edge: Prevents instant-fill detection triggers used by enterprise fraud engines.
  • Example: TYPE_HUMAN "input#password" "P@ssw0rd2026!"

C. Waiting & Timing

Command Usage Description
WAIT WAIT 2 [5] Pause execution for fixed seconds (WAIT 2.5) or random range between [secs, max_secs].
WAIT_SEL WAIT_SEL ".content" [timeout_s] Wait until element appears across DOM, Shadow DOM, or iframes (default timeout: 10s, alias: WAIT_FOR).
WAIT_SEL_GONE WAIT_SEL_GONE ".spinner" [timeout_s] Wait until element disappears or is removed from DOM (aliases: WAIT_GONE, WAIT_FOR_GONE).
WAIT_TEXT WAIT_TEXT [selector] "text" [timeout_s] Poll until specified text appears anywhere on page or within target selector (default timeout: 10s, alias: WAIT_FOR_TEXT).
WAIT_RESPONSE WAIT_RESPONSE "pattern" [save_path] [timeout_s] Wait for asynchronous XHR/Fetch network response matching URL pattern and capture response body (aliases: WAIT_FOR_RESPONSE, CAPTURE_RESPONSE).
WAIT_RESPONSE / CAPTURE_RESPONSE Direct API Sniffing
  • Underlying Power: Hooks CDP network telemetry at the protocol level. Pauses execution until a matching background XHR or Fetch request finishes, extracting the raw HTTP body directly into a JSON file.
  • Parameters: url_pattern (glob string), save_path (optional output path), timeout_s (default: 10s).
  • Scraping Superpower: Captures internal GraphQL or REST payloads behind complex Single Page Apps (SPAs) without reverse engineering headers.
  • Example: WAIT_RESPONSE "*api/v2/products/search*" "output/search_api.json" 20

D. Control Flow, Loops & Broadcasting

Command Usage Description
BROADCAST BROADCAST ON | OFF Execute all enclosed actions 100% asynchronously & independently across all open tabs in parallel (each tab runs on its own clock without waiting until BROADCAST OFF).
LOOP LOOP 5 ... END Repeat block n times with 0-based loop index variable <i> (0, 1, 2, ...).
LOOP (Range) LOOP 0 5 tab ... END Loop over numeric range [start, end] with custom named variable <tab>.
IF / ELSE / END IF SMART_EXIST "#btn" ... END Conditional branching supporting condition stack (EXIST, NOT) or inline assertions (IF CTR <= 3%, IF TABS > 1, IF NOT EXIST ".error").
BREAK BREAK Break out of innermost loop early.
EXIST EXIST "selector" Check element existence in active document and push boolean to condition stack.
NOT NOT Invert the boolean condition on top of condition stack.
Assertion Conditions in IF vs Hard Gates Condition Stack vs Hard Gates
  • Assertion Conditions: Any ASSERT_* command placed inside an IF ... END block acts as a conditional check — it evaluates its condition, pushes the boolean result onto the condition stack for IF to consume, and does not abort the script on failure.
  • Hard Validation Gates: Only standalone (outside IF) do ASSERT_* commands behave as hard validation gates that abort execution.
  • Loop Polling Pattern: This is the correct, resilient way to poll for dynamic JavaScript states or DOM conditions in loops without halting execution:
    # Polling for dynamic JS conditions in a loop without halting execution:
    LOOP 15
        IF ASSERT_EVAL "document.querySelector('.success-badge') !== null"
            ECHO "Target element appeared, exiting polling loop..."
            BREAK
        END
        WAIT 1 2
    END
BROADCAST Independent Parallel Concurrency
  • Underlying Power: Spawns concurrent Goroutines across all open tab contexts. Each tab executes subsequent macro actions on its own clock without waiting for other tabs until BROADCAST OFF synchronizes them.
  • Scraping Superpower: Parallelize page scraping, form submission, and infinite feed scrolling across 5–20 tabs simultaneously in a single process.
  • Example:
    BROADCAST ON
    GOTO "https://target.com/catalog"
    SCROLL down 1200
    BROADCAST OFF

E. Network Interception & Storage

Command Usage Description
NETWORK_ABORT NETWORK_ABORT "*tracker*" [skip_assets=true] Abort and block matching network requests immediately at request or response stage.
NETWORK_MOCK NETWORK_MOCK "*/api/*" "{"ok":true}" [status=200] Intercept request and return synthetic custom JSON/text response body, status code, and headers.
NETWORK_REWRITE NETWORK_REWRITE * [resp_replace=K=V] [resp_body=...] [json_only] Rewrite matching request URLs, redirect targets, HTTP methods, POST bodies, custom headers, or live response payloads with automatic JSON-only protection and compression header hygiene.
NET_LOG NET_LOG ["url_filter"] Print captured network requests list to log with HTTP method, status, resource type, URL, and [REWRITTEN] badge (aliases: PRINT_NET, NET_LIST).
NET_REQ NET_REQ ["id_or_filter"] ["save_path.json"] Inspect request headers, HTTP method, and POST payload (shows all captured requests if omitted), optionally saving to JSON file (alias: PRINT_NETREQ).
NET_RES NET_RES ["id_or_filter"] ["save_path.txt"] Inspect response status, headers, and body (including dynamically rewritten payloads; shows all captured responses if omitted), optionally saving to file (alias: PRINT_NETRES).
PROXY_AUTH PROXY_AUTH "username" "password" Configure credentials for upstream proxy 407 authentication challenges and server 401 basic auth.
SAVE_TRACKING SAVE_TRACKING ["requests.json"] Export captured network traffic logs, HTTP headers, timing metrics, and response statuses to JSON (aliases: SAVE_TRACK, SAVE_NET_REQUESTS).
COOKIE COOKIE "name" "value" ["domain"] Inject session or persistent authentication cookie.
COOKIES COOKIES Retrieve and log all active session cookies (including HttpOnly & Secure cookies).
STORAGE_SET STORAGE_SET local|session "key" "val" Set localStorage or sessionStorage key-value pair.
STORAGE_GET STORAGE_GET local|session "key" Read localStorage or sessionStorage value.
NETWORK_ABORT & NETWORK_MOCK 5x Speedup & API Mocking
  • Underlying Power: In-engine request interception. Aborts resource-heavy media (images, fonts, video streams, analytics) to save 80% proxy bandwidth and speed up page load times up to 5x.
  • Parameters: pattern (glob pattern), json_body (mock payload), status (HTTP status code).
  • Example: NETWORK_ABORT "*google-analytics.com*,*.mp4,*.woff2"
NETWORK_REWRITE & NET_RES Payload Rewriting & Header Hygiene
  • Underlying Power: Live response interception via CDP Fetch domain. Rewrites API responses and spoofs parameters dynamically.
  • Automatic JSON-Only Protection: Key-value substitutions (e.g. resp_replace=region=<rbsm_country>) automatically target JSON responses only, leaving JavaScript tag files (e.g. tag.js), CSS, and images intact.
  • Decompression Hygiene: Automatically strips Content-Encoding (gzip/br) and Content-Length on modified responses, preventing browser decoding crashes.
  • Live Inspection: Use NET_LOG to list traffic with [REWRITTEN] badges, or VAR res = NET_RES *geo* to store modified payloads directly in variables.

F. Assertions & IP Shift Protection

Command Usage Description
ASSERT_CONTAINS ASSERT_CONTAINS "#status" "Paid" Hard gate: fail unless element text contains expected substring.
ASSERT_TEXT ASSERT_TEXT "#price" "$99.00" Hard gate: fail on exact text mismatch.
ASSERT_TITLE ASSERT_TITLE "Checkout" Hard gate: fail unless page title contains expected substring.
ASSERT_URL ASSERT_URL "dashboard" Hard gate: fail unless active URL contains expected substring.
ASSERT_EVAL ASSERT_EVAL "window.ready === true" Hard gate: fail unless JavaScript expression evaluates truthy.
ASSERT_CONSOLE ASSERT_CONSOLE "error_code_0" Hard gate: fail unless console logs contain expected substring.
ASSERT_SMART_EXIST ASSERT_SMART_EXIST "selector" ["text"] Hard gate: fail unless element exists anywhere in DOM, Shadow DOM, or iframes with optional text match (aliases: ASSERT_SEL, ASSERT_EXIST).
ASSERT_DOWNLOAD ASSERT_DOWNLOAD "invoice.pdf" [timeout_ms] Hard gate: wait until downloaded file matching filename is verified on disk (default timeout: 10s).
ASSERT_REQUEST_CONTAIN ASSERT_REQUEST_CONTAIN "analytics/collect" Hard gate: fail unless network captured at least one request URL containing substring.
ASSERT_REQUEST_MODIFIED ASSERT_REQUEST_MODIFIED "rule_pattern" Hard gate: fail unless network rule intercepted and modified a request.
ASSERT_CTR ASSERT_CTR [<=|>=|==] <percentage> Hard gate: verify global CTR percentage satisfies condition (e.g. ASSERT_CTR <= 3%). Supports IF CTR <= 3% branching.
ASSERT_TABS ASSERT_TABS [<=|>=|==] <count> Hard gate: verify number of open browser tabs (e.g. ASSERT_TABS > 1, alias: ASSERT_TABS_COUNT). Supports IF TABS > 1 branching.
GUARD_IP_SHIFT GUARD_IP_SHIFT [ON | OFF] Enable continuous residential proxy IP shift guarding (instantly halts execution if proxy rotates IP mid-session, alias: GUARD_IP).
ASSERT_IP_UNCHANGED ASSERT_IP_UNCHANGED Hard gate point-in-time check asserting proxy exit IP matches initial session IP (alias: CHECK_IP).
Assertion Conditions: Polling & Branching Soft Checks in IF
  • Soft Checks Inside IF: Any ASSERT_* command placed inside an IF ... END block acts as a conditional check — it evaluates its condition, pushes the boolean result onto the condition stack for IF to consume, and does not abort the script on failure.
  • Hard Gates Standalone: Only standalone (outside IF) do ASSERT_* commands behave as hard validation gates that abort execution.
  • Loop Polling: This is the correct way to poll for JS or DOM conditions in loops without risking abrupt script termination.
GUARD_IP_SHIFT / GUARD_IP Anti-Ban IP Shield
  • Underlying Power: Activates a continuous background watchdog monitoring outbound TCP connections. If the upstream residential proxy rotates to a new IP mid-flow, execution halts immediately.
  • Security Edge: Prevents session hijacking, account bans, and payment gateway fraud flags caused by mid-session IP mutations.
  • Example: GUARD_IP_SHIFT ON

G. Screenshots, JavaScript & Inspection

Command Usage Description
SS SS ["screenshot.png"] Capture full page high-resolution screenshot to file (default: screenshot_N.png, alias: SCREENSHOT).
SS_SEL SS_SEL "#card" ["item.png"] Capture element-only bounding box screenshot (default: element_N.png, alias: SCREENSHOT_SEL).
SAVE_HTML SAVE_HTML ["page.html"] [selector] Save rendered HTML of the full page or a specific element with Declarative Shadow DOM and inlined iframes (aliases: HTML_SAVE, SAVEHTML).
SAVE_SNAPSHOT SAVE_SNAPSHOT ["snapshot.json"] Save multi-session CDP DOM Snapshot graph (.json) or text tree (.txt). Both formats unified to pierce all OOPIFs and open/closed Shadow Roots (alias: SNAPSHOT_SAVE).
SNAPSHOT SNAPSHOT ["debug.json"] Dump full Accessibility DOM Tree to console/memory, or save to disk if path is provided (pierces through cross-origin iframes & Shadow DOMs).
ELEMENTS ELEMENTS Dump all actionable links, buttons, inputs, selects, captcha widgets, and iframes across main DOM, open Shadow DOMs, and Out-of-Process iFrames (OOPIFs) (alias: INTERACTIVE_ELEMENTS).
CONSOLE CONSOLE Dump captured browser console logs (alias: CONSOLE_ERRORS for error logs).
DOWNLOAD DOWNLOAD "downloads/" ["https://url..."] Configure download directory and optionally trigger file download.
EVAL EVAL "window.scrollBy(0, 500)" Execute custom JavaScript expression in active page context and log return value.
ECHO ECHO "Processing run <datetime>" Print a progress or debug message to the output log (supports dynamic <placeholders>).
TEXT TEXT "selector" Read and log inner text content of matching element.
TITLE TITLE Log current document title to console.
URL URL Log current page URL to console.

H. Web Scraping & Data Extraction Suite

Command Usage Description
VAR / SET_VAR VAR name = [EVAL|TEXT|ATTR|NET_RES|NET_REQ] <expr> Define dynamic runtime variable from text, attribute, eval, response body, request payload, or literal string. Supports multiline JS blocks (VAR name JS ... END) and self-referential updates (VAR c EVAL <c> + 1). Expandable anywhere via <name>.
EXTRACT_TABLE EXTRACT_TABLE "table.data" ["data.csv"] Extract table headers and rows directly into standard RFC-4180 CSV file or console output (aliases: TABLE_EXTRACT, SCRAPE_TABLE).
EXTRACT_ATTR EXTRACT_ATTR "a.link" "href" ["links.txt"] Extract attribute values from all matching elements, one per line (aliases: EXTRACT_ATTRIBUTES, ATTR_EXTRACT).
EXTRACT_JSON_LD EXTRACT_JSON_LD ["schema.json"] Extract structured JSON-LD <script type="application/ld+json"> schemas into formatted JSON file or stdout (alias: JSON_LD_EXTRACT).
EXTRACT_METADATA EXTRACT_METADATA ["meta.json"] Extract page metadata (OpenGraph og:*, Twitter Cards twitter:*, canonical URL, description, keywords) into structured JSON (aliases: METADATA_EXTRACT, SAVE_METADATA).
EXTRACT_LIST EXTRACT_LIST "h2.title" ["titles.txt"] Scrape inner text of all matching elements and write one item per line (aliases: SCRAPE_LIST, LIST_EXTRACT).
EXTRACT_LINKS EXTRACT_LINKS ["a.item"] ["links.csv"] Extract text, href, and title of all anchor links matching selector (default: "a") into JSON or CSV (aliases: SAVE_LINKS, LINKS_EXTRACT).
SCROLL_UNTIL SCROLL_UNTIL ".product-card" 50 [20] [400] Scroll page dynamically until count of matching elements reaches target count or max scroll attempts are reached.
FILL_FORM FILL_FORM "{"#user":"admin","#terms":true}" Batch fill multiple form inputs, checkboxes, radios, and textareas from inline JSON string or .json file (alias: BATCH_INPUT).
DOWNLOAD_IMAGES DOWNLOAD_IMAGES "img.gallery" "images/" [20] Batch extract and download images matching selector to local folder (supports HTTP/HTTPS URLs & inline base64 Data URIs, aliases: SAVE_IMAGES, IMAGES_SAVE).
SAVE_MARKDOWN SAVE_MARKDOWN ["article.md"] [selector] Convert full page DOM or specific element tree into clean GitHub-flavored Markdown (aliases: MARKDOWN_SAVE, SAVEMARKDOWN).
APPEND_CSV APPEND_CSV "data.csv" "val1" "val2"... Append a row of delimited columns directly into a CSV file (auto-creates directory and file headers, alias: CSV_APPEND).
SCROLL_TO_BOTTOM SCROLL_TO_BOTTOM [max_scrolls] [delay_ms] [stop_sel] Smoothly scroll down long pages or infinite-scroll feeds until bottom or stop selector appears (aliases: SCROLL_BOTTOM, SCROLL_ALL).
SCROLL_INTO_VIEW SCROLL_INTO_VIEW ".load-more" Smoothly center any element into the active viewport (alias: SCROLL_TO).
DISMISS_POPUPS DISMISS_POPUPS [custom_selectors...] Automatically detect and dismiss GDPR cookie consent banners, OneTrust dialogs, and newsletter overlays (aliases: CLOSE_POPUPS, DISMISS_BANNERS).
SAVE_PDF SAVE_PDF ["page.pdf"] [landscape] [print_bg] Export pixel-perfect A4 PDF document with background colors/graphics preserved (aliases: PDF_SAVE, SAVEPDF).
EXTRACT_TABLE & APPEND_CSV Structured Data Export
  • Underlying Power: Converts rendered HTML table elements into RFC-4180 CSV files directly with zero external Python or Node.js dependencies. Handles merged headers and complex spans cleanly.
  • Example: EXTRACT_TABLE "table.finance-grid" "output/stocks_.csv"
EXTRACT_JSON_LD & EXTRACT_METADATA Clean Semantic Data
  • Underlying Power: Harvests Schema.org JSON-LD structured blocks and OpenGraph/Twitter card tags into pristine JSON files without having to parse complex DOM wrappers.
  • Example: EXTRACT_JSON_LD "output/product_schema.json"
SCROLL_UNTIL & FILL_FORM Dynamic Scraper Primitives
  • Underlying Power: SCROLL_UNTIL automates infinite scroll feeds until a minimum element threshold is met. FILL_FORM batch-inputs entire forms with a single JSON payload.
  • Example: SCROLL_UNTIL ".product-card" 60 15 400
SAVE_MARKDOWN & DOWNLOAD_IMAGES LLM Ingestion & Media
  • Underlying Power: SAVE_MARKDOWN strips clutter and converts rich web articles into markdown ready for RAG pipelines and AI analysis. DOWNLOAD_IMAGES concurrently saves web and Base64 images to disk.
  • Example: SAVE_MARKDOWN "output/doc.md" "main.content"
VAR & SET_VAR Multiline JS & Dynamic State
  • Multiline JavaScript Evaluation: Write clean multiline JavaScript algorithms or validation logic and store the result directly into a variable without single-line escaping:
    VAR offer_status JS
    (() => {
        const invalidList = ["travellechicago.com", "chrome-error://", "google."];
        const url = location.href;
        const hit = invalidList.find(d => url.includes(d));
        return hit ? 'invalid' : 'valid';
    })()
    END_JS
  • Self-Referential Math & Composition: Update or increment variables dynamically (e.g. VAR counter EVAL <counter> + 1 or VAR s_val "<s_val> extra").
  • Tab Discovery & Inspection: Store tab properties natively: VAR total TABS (tab count), VAR u TAB_URL <idx> (direct tab URL), VAR t TAB_TITLE <idx> (tab title), VAR idx TAB_FIND <pattern> (search matching tab index), and VAR cur URL (current page URL).
💡 Advanced Scraping: Choosing Between SAVE_HTML vs SAVE_SNAPSHOT

RBSM gives you both full visual DOM serialization and raw Blink layout engine AST graphs to defeat anti-bot honeypots and extract deeply nested elements.

Feature / Use Case SAVE_HTML SAVE_SNAPSHOT
Output Format Standard HTML Markup (.html) CDP AST Graph (.json) or Text Tree (.txt)
Viewable in Web Browser ✔ Yes (Open .html directly) ✖ No (Structured JSON / Text)
Shadow DOM Preservation ✔ Declarative Shadow DOM (<template shadowrootmode="open">) ✔ Full serialized AST subtree
IFrame Content Inlining ✔ Inlined into srcdoc across same & cross-origin sessions ✔ Frame offsets [x, y, w, h] and frame sub-trees
Visual Bounding Boxes [x, y, w, h] ✖ None (Uncomputed) ✔ Exact pixel coordinates for every rendered node
Anti-Bot / Honeypot Detection ✖ Cannot detect zero-size traps without CSS math ✔ Instantly filters hidden decoy links (w=0 or h=0)
Best For Visual archives, BeautifulSoup, Cheerio, JSON-LD extraction Advanced anti-bot scrapers, LLM ingestion, coordinate math

I. IFrame & Subframe Navigation

Command Usage Description
ENTER_IFRAME ENTER_IFRAME "iframe#widget" Retarget script execution directly into an iframe or OOPIF context (alias: ENTER_FRAME).
EXIT_IFRAME EXIT_IFRAME Return context back to the top-level main document (alias: EXIT_FRAME).
EXIT_IFRAME_PARENT EXIT_IFRAME_PARENT Return one level up in a nested iframe stack (alias: EXIT_FRAME_PARENT).
ENTER_IFRAME & EXIT_IFRAME OOPIF Frame Traversal
  • Underlying Power: Attaches directly to the target frame's CDP session, allowing deep script execution inside sandboxed and cross-origin frames.
  • Example: ENTER_IFRAME "iframe[title*='reCAPTCHA']"

J. JavaScript Dialogs & TUI Counters

Command Usage Description
ACCEPT_DIALOG ACCEPT_DIALOG ["prompt_text"] Accept active JavaScript alert(), confirm(), or prompt() with optional input text.
DISMISS_DIALOG DISMISS_DIALOG Dismiss active JavaScript dialog (Cancel / close modal).
COUNT_CLICK COUNT_CLICK Increment the global click counter displayed on the live terminal TUI dashboard (alias: INC_CLICK).
DELETE_CLICK DELETE_CLICK Decrement the global click counter on the live terminal TUI dashboard (alias: DEC_CLICK).
ACCEPT_DIALOG & DISMISS_DIALOG Modal Resolution
  • Underlying Power: Programmatically answers native browser JavaScript alert, confirm, and prompt dialogs without blocking execution threads.
  • Example: ACCEPT_DIALOG "Confirmed Order"

🛡️ 12. Ad-Blocking & Network Rules (5x Speedup)

Block heavy media, tracker scripts, and analytics to boost page load speed up to 5x and save 80% bandwidth on metered residential proxy pools.

Option 1: Inline Macro Commands

macros/fast_flow.mac
NETWORK_ABORT "*google-analytics.com*"
NETWORK_ABORT "*doubleclick.net*"
NETWORK_ABORT "*.mp4"
NETWORK_ABORT "*.png,*.jpg,*.gif"

GOTO "https://news-site.com"

Option 2: Declarative JSON Rules File (-rules)

Load declarative request/response interception, header injection, URL rewriting, ad blocking, and IP shift guards at browser startup before initial navigation:

rules/rules.json
{
  "guard_ip_shift": true,
  "proxy_auth": {
    "username": "proxyuser",
    "password": "proxypass"
  },
  "request": {
    "abort": [
      { "pattern": "*doubleclick.net*" },
      { "pattern": "*googlesyndication.com*" }
    ],
    "url": [
      { "pattern": "*track*", "replace": "https://cdn.example.com/track" },
      { "pattern": "*/api/*", "add": "debug=1" },
      { "pattern": "*/sess/*", "delete": ["token=abc123&", "&sid=xyz789"] },
      { "pattern": "*/cdn/*", "edit": ["old.cdn:new.cdn", "http://:https://"] }
    ],
    "body": {
      "add":    [ { "pattern": "*/api/upload", "body": ["dry_run=true"] } ],
      "delete": [ { "pattern": "*/api/upload", "body": ["user_agent"] } ],
      "edit":   [ { "pattern": "*/api/upload", "body": ["user_agent=test-bot"] } ]
    },
    "headers": {
      "add":    [ { "pattern": "*/api/*", "headers": ["X-Tenant:acme"] } ],
      "delete": [ { "pattern": "*doubleclick.net*", "headers": ["User-Agent"] } ],
      "edit":   [ { "pattern": "*/api/*", "headers": ["Authorization:Bearer test-token"] } ]
    }
  },
  "response": {
    "abort": [
      { "pattern": "*malicious-ad*" }
    ],
    "body": {
      "add": [
        { "pattern": "*/api/v1/data", "body": ["{\"ok\":1}"], "status": 200, "content_type": "application/json" }
      ]
    },
    "headers": {
      "add":    [ { "pattern": "*/api/*", "headers": ["X-Rate-Limit:100"] } ],
      "delete": [ { "pattern": "*asset*", "headers": ["Server"] } ],
      "edit":   [ { "pattern": "*/api/*", "headers": ["Cache-Control:no-store"] } ]
    }
  }
}
Execution Command
rbsm_windows_amd64.exe -rules=rules\rules.json -agent -interactive

💬 13. Zero-Token Interactive Agent CLI Mode

Run RBSM in interactive terminal mode (-interactive=true) to control browser inspection, dynamic rules, and network debugging without consuming LLM API tokens:

Category CLI Command Description
Session & Rules /help, /? Display available commands and interactive power reference.
Session & Rules /rule add <guideline> Add active macro rule constraint or behavior guideline to LLM session.
Session & Rules /rule list, /rules List all active session rules and available macro commands.
Session & Rules /rule clear Clear all custom injected session rules.
Session & Rules /rule load <file.mac> Load and execute an entire .mac script file inside the live browser.
Session & Rules /clear, /new Clear conversational memory (browser remains on current page).
Session & Rules /reset Reset memory and navigate browser to about:blank.
Session & Rules /stats, /history Display token usage, message count, and scratchpad memory.
Session & Rules /verbose [on|off] Toggle step-by-step thoughts and tool previews.
Session & Rules /export [file.md] Export conversation history and findings to a Markdown report.
Session & Rules /exit, /quit Terminate interactive session and cleanly close browser.
Network Traffic /net [url_filter] List captured network requests, status codes, methods, and mime types.
Network Traffic /netres <req_id> View full response body & headers for captured request ID.
Network Traffic /netreq <req_id> View full request headers, method, and POST payload for request ID.
Network Traffic /netsummary Aggregate network statistics by resource type, status code, and host.
Network Traffic /netclear Clear captured network request/response log buffer.
Network Traffic /netrule mock <pat> <body> Set live network mock rule returning custom JSON/text body.
Network Traffic /netrule abort <pat> Set live network abort rule to block matching requests.
Network Traffic /netrule clear Clear all live network interception rules.
Console & Errors /console [type] View captured browser console messages (log, warn, error, info).
Console & Errors /errors, /err Instant display of captured runtime JS exceptions & promise rejections.
Console & Errors /clearconsole Clear captured browser console log buffer.
Direct Browser /url Print current page URL and document title.
Direct Browser /goto <url> Instantly navigate to URL without calling LLM.
Direct Browser /elements, /inspect Scan active DOM and dump interactive links, buttons, inputs, and selectors.
Direct Browser /snapshot, /dom Print complete accessibility tree / DOM snapshot.
Direct Browser /click <selector> Click element matching CSS selector directly.
Direct Browser /type <sel> <text> Type text into input element directly.
Direct Browser /eval <js> Execute JavaScript expression in active page console.
Direct Browser /tabs List all open browser tabs and targets.
Direct Browser /tab <index> Switch active focus to tab by index.
Direct Browser /reload Reload the active page.
Direct Browser /back, /forward Browser history navigation shortcuts.
Direct Browser /screenshot [path] Save page screenshot (default: screenshot_<timestamp>.png).

🤖 14. AI Agent, Cursor & Claude Desktop (MCP Server)

RBSM has built-in support for the Model Context Protocol (MCP) over stdio, enabling Claude Desktop, Cursor, and autonomous AI agents to drive anti-detect browser sessions with zero setup.

⚠️ Important Working Directory Note: When external AI apps (Claude Desktop, Cursor, VS Code) spawn MCP servers, they run from their own parent directory. You must ensure RBSM runs in its workspace directory (where license.lic, iprbsm.bin, fp-ua.json, and browser binaries reside) either by setting cwd in the config or using a launcher script (.bat / .sh).

Method 1: Direct JSON Configuration (with cwd)

Add RBSM to your claude_desktop_config.json or .cursor/mcp.json, explicitly specifying the cwd path:

claude_desktop_config.json (Windows)
{
  "mcpServers": {
    "rbsm": {
      "command": "C:\\Work\\rbsm\\rbsm_windows_amd64.exe",
      "args": [
        "-mcp-server=true",
        "-headless=false",
        "-human=2"
      ],
      "cwd": "C:\\Work\\rbsm"
    }
  }
}
claude_desktop_config.json (Linux / macOS)
{
  "mcpServers": {
    "rbsm": {
      "command": "/usr/local/bin/rbsm",
      "args": [
        "-mcp-server=true",
        "-headless=true"
      ],
      "cwd": "/home/user/rbsm"
    }
  }
}

Method 2: Launcher Script (Recommended for Maximum Portability)

Create a small wrapper script inside your RBSM folder that automatically switches directory before execution, then point Claude / Cursor directly to the script:

run_mcp.bat (Windows)
@echo off
cd /d "%~dp0"
rbsm_windows_amd64.exe -mcp-server=true -headless=false -human=2
claude_desktop_config.json (Windows - Launcher Script)
{
  "mcpServers": {
    "rbsm": {
      "command": "C:\\Work\\rbsm\\run_mcp.bat"
    }
  }
}
run_mcp.sh (Linux / macOS)
#!/usr/bin/env bash
cd "$(dirname "$0")"
./rbsm_linux_amd64 -mcp-server=true -headless=true
claude_desktop_config.json (Linux / macOS - Launcher Script)
{
  "mcpServers": {
    "rbsm": {
      "command": "/home/user/rbsm/run_mcp.sh"
    }
  }
}

Option C: Autonomous AI Agent (-agent)

mcp-data.json
{
  "apiKey": "sk-proj-...",
  "baseURL": "https://api.openai.com/v1",
  "model": "gpt-4o",
  "maxContextTokens": 120000,
  "maxSteps": 30,
  "disableScreenshot": false,
  "goal": "Navigate to target website and complete task."
}
Execution Command
rbsm_windows_amd64.exe -agent=true -agent-config=mcp-data.json -headless=true

Available Native MCP & Agent Tools Exposed (59 Engine Tools)

All tools below are natively exposed over JSON-RPC 2.0 (MCP Protocol) when starting RBSM with -mcp-server=true or running in autonomous agent mode (-agent=true):

Category Tool Name Parameters & Types Description & Macro Mapping
DOM Navigation & Read navigate url (string, req), referrer (string, opt) Navigate active tab to URL with optional Referer header spoofing. (GOTO)
get_current_url (none) Get the current page URL and verify navigation or redirects. (ASSERT_URL / URL)
get_page_title (none) Get the current page document title. (ASSERT_TITLE / TITLE)
get_page_state (none) Lightweight post-action snapshot: URL, title, readyState, and visible error banners.
get_dom_snapshot (none) Dump full Accessibility Tree piercing all Shadow DOMs and cross-origin OOPIFs. (SNAPSHOT)
save_dom_snapshot path (string, opt = "snapshot.json") Save CDP DOM snapshot graph (.json) or text tree (.txt) to disk. (SAVE_SNAPSHOT)
get_interactive_elements (none) Dump all actionable links, buttons, inputs, selects, captcha widgets, and selectors across Main DOM, open Shadow DOMs, and OOPIF frames. (ELEMENTS)
get_html selector (string, opt) Get rendered outer HTML of full page or target element with inlined Shadow DOMs.
save_html path (string, opt = "page.html"), selector (string, opt) Save rendered HTML of full page or element to file on disk. (SAVE_HTML)
get_text selector (string, req) Extract inner text content of matching element. (TEXT / ASSERT_TEXT)
get_attribute selector (string, req), attribute (string, req) Read attribute value (href, value, src, checked, disabled, aria-label).
is_visible selector (string, req) Check if element exists and has non-zero bounding box dimensions. (EXIST / SMART_EXIST)
get_viewport_metrics (none) Get scrollY, scrollHeight, innerHeight, innerWidth for detecting infinite scroll.
wait selector (string, opt), time_ms (num, opt = 1000), time_ms_max (num, opt) Wait fixed duration, random range (human pacing), or poll for element visibility. (WAIT / WAIT_SEL)
screenshot (none) Capture full viewport PNG screenshot as base64 data URI. (SS / SCREENSHOT)
element_screenshot selector (string, req), path (string, opt) Capture screenshot of a specific bounding element to file or base64. (SS_SEL)
Human Mouse & Input click_element selector (string, req), wait_for_element (bool, opt = true) Humanized Bézier curve mouse movement and organic click with micro-jitter. (CLICK)
smart_click selector (string, req), timeout_ms (int, opt = 10000) Multi-context click piercing main DOM, Shadow DOMs, and cross-origin Turnstile iframes. (SMART_CLICK)
click_at x (num, req), y (num, req) Coordinate-based click fallback for dynamic canvas or SVG elements. (CLICK_AT)
type_text selector (string, req), text (string, req), clear_first (bool, opt = true), mode ("instant" | "human", opt) Type text with human keystroke intervals or instant dispatch; handles React/Vue controlled inputs. (TYPE)
press_key key (string, req) Dispatch keyboard keypress event (Enter, Tab, Escape, Backspace, ArrowDown, etc.). (KEYPRESS)
select_option selector (string, req), value (string, req) Select option in dropdown element with synthetic input/change events. (SELECT)
hover selector (string, req) Hover cursor over element to trigger hover menus and tooltips. (HOVER)
hover_at x (num, req), y (num, req) Move/hover mouse at exact coordinates with realistic human Bézier trajectory. Safe no-op on mobile. (HOVER_AT)
focus selector (string, req) Set keyboard focus to element by CSS selector. (FOCUS)
drag_element x (num, req), y (num, req), x2 (num, req), y2 (num, req) Drag from (x, y) to (x2, y2) coordinate with smooth trajectory. (DRAG)
scroll_page direction ("up" | "down" | "top" | "bottom", req), pixels (num, opt = 500) Scroll viewport smoothly in given direction. (SCROLL)
Tabs, Storage & Dialogs new_tab url (string, opt = "about:blank") Open a new tab in shared browser profile and return target_id. (NEW_TAB)
new_isolated_tab url (string, opt = "about:blank"), config (string, opt) Open a 100% storage-isolated tab in its own BrowserContext. (NEW_ISOLATED_TAB)
switch_tab tab_id (string, req) Switch active browser tab by its target_id. (SWITCH_TAB)
close_tab tab_id (string, opt = "current") Close a browser tab by target_id or close the active tab. (CLOSE_TAB)
list_tabs (none) List all open browser tabs with target_id, title, URL, and context info.
get_cookies (none) Retrieve all session and HttpOnly cookies via CDP Network domain. (COOKIES)
set_cookie name (string, req), value (string, req), domain (string, opt) Inject cookie into browser session (domain defaults to current origin). (COOKIE)
get_storage key (string, req), type ("local" | "session", opt = "local") Read value from localStorage or sessionStorage by key. (STORAGE_GET)
set_storage key (string, req), value (string, req), type ("local" | "session", opt = "local") Write key-value pair to localStorage or sessionStorage. (STORAGE_SET)
accept_dialog prompt_text (string, opt) Accept JavaScript alert, confirm, or prompt dialog with optional text. (DIALOG_ACCEPT)
dismiss_dialog (none) Dismiss/Cancel JavaScript modal dialog. (DIALOG_DISMISS)
Scripting & Files execute_js script (string, req) Execute JavaScript expression in active page context and return result. (EVAL / JS)
add_init_script script (string, req) Inject JavaScript evaluated at document_start across Main DOM, all iframes, OOPIFs, and Web Workers. (INIT_SCRIPT)
reload_page (none) Reload active document. (RELOAD)
go_back / go_forward (none) Navigate backward or forward in browser history. (BACK / FORWARD)
file_upload selector (string, req), file_path (string, req) Upload file from local filesystem to <input type="file">. (UPLOAD)
download_file download_path (string, req), url (string, opt) Set download folder and optionally trigger file download from URL. Requires -download startup flag; URL navigates active tab; disk save applies to binary/attachment responses. (DOWNLOAD)
check_download name (string, req), timeout_ms (num, opt = 10000) Wait for downloaded file matching name to land in configured download directory and verify size. Requires -download flag. (ASSERT_DOWNLOAD)
Network & Diagnostics set_network_rules rules (array of rule objects, req) Apply declarative blocking (abort), synthetic API mocking (mock), or URL/header rewriting (continue). (NETWORK_MOCK / NETWORK_ABORT / NETWORK_REWRITE)
clear_network_rules (none) Disable all active network interception rules. (NETWORK_CLEAR)
set_proxy_auth username (string, req), password (string, opt) Configure credentials for upstream proxy 407 and server 401 basic auth challenges. (PROXY_AUTH)
get_network_requests url_filter (string, opt), method (string, opt), status (num, opt), resource_type (string, opt) List captured network traffic with request_id, method, URL, status, and MIME type.
get_network_response request_id (string, req) Retrieve full response body and Content-Type for captured request ID.
get_network_request request_id (string, req) Inspect request headers, HTTP method, and POST payload for captured request ID.
clear_network_log (none) Clear in-memory captured network traffic buffer.
get_network_summary (none) Get aggregate traffic metrics grouped by resource type, HTTP status, and host.
save_tracking path (string, opt = "tracking.json") Export all captured network requests, headers, and timings to JSON file. (SAVE_TRACKING)
get_console_logs type ("log" | "warning" | "error" | "info" | "debug", opt) Retrieve browser console output and caller source line numbers. (CONSOLE)
get_console_errors (none) Get only error-level console messages, uncaught JS exceptions, and failed promises. (CONSOLE_ERRORS)
clear_console_logs (none) Clear browser console log history.
guard_ip_shift enabled (bool, opt = true) Enable continuous background watchdog monitoring against residential IP drift. (GUARD_IP_SHIFT)
check_ip (none) Verify current proxy exit IP matches initial session IP. (ASSERT_IP_UNCHANGED / CHECK_IP)

💻 15. Advanced Developer & Polyglot Integration Guide

Advanced engineers combine RBSM with their preferred programming language (Python, Node.js, TypeScript, Go, Rust, or Bash) to build custom automated scraping pipelines, AI embeddings, and high-throughput data extraction engines.

⚡ Architecture: The Best of Both Worlds

Let RBSM handle all browser-level stealth (Cloudflare Turnstile, DataDome, Akamai, residential proxy pooling, Bézier trajectories, inlined Shadow DOMs & OOPIFs). Let Python / Node.js / Go parse the clean rendered HTML (via BeautifulSoup, Cheerio, Selectolax), store items in databases (PostgreSQL, SQLite, MongoDB), and trigger your business logic.

Pattern 1: Python Scraper (Movie & Streaming Metadata Pipeline)

In this production example, Python spawns RBSM via subprocess to solve Cloudflare Turnstile, dumps the rendered DOM with SAVE_HTML, and extracts movie title, rating, release year, cast list, synopsis, and poster URL using BeautifulSoup4:

movie_scraper.py
#!/usr/bin/env python3
import json, os, subprocess, sys
from pathlib import Path
from bs4 import BeautifulSoup

RBSM_BIN = "./rbsm_windows_amd64.exe" if os.name == "nt" else "./rbsm_linux_amd64"
OUTPUT_DIR = Path("output")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

def scrape_movie_details(target_url: str) -> dict:
    html_out = OUTPUT_DIR / "movie_page.html"
    schema_out = OUTPUT_DIR / "movie_schema.json"
    macro_file = OUTPUT_DIR / "fetch_movie.mac"

    # 1. Generate dynamic RBSM macro script
    macro_content = f"""
GOTO "{target_url}" "https://google.com,https://bing.com"
WAIT 2.0 3.5
DISMISS_POPUPS

# Check and solve Cloudflare Turnstile if present
IF SMART_EXIST "#turnstile-box, iframe[src*='challenges.cloudflare']"
    ECHO "[*] Turnstile challenge detected — solving with human physics..."
    SMART_CLICK "#turnstile-box, iframe[src*='challenges.cloudflare']" 15
    WAIT 4.0
END

WAIT_SEL "h1, .movie-title, [itemprop='name']" 15
SCROLL down 600
WAIT 1.0 2.0

SAVE_HTML "{html_out.as_posix()}"
EXTRACT_JSON_LD "{schema_out.as_posix()}"
ECHO "[+] HTML and Schema.org dumped successfully."
"""
    macro_file.write_text(macro_content.strip(), encoding="utf-8")

    # 2. Spawn RBSM engine via subprocess
    cmd = [
        RBSM_BIN,
        f"-macros={macro_file}",
        "-headless=true",
        "-human=2",
        "-limit-proxy=1"
    ]
    print(f"[*] Launching RBSM engine for {target_url}...")
    subprocess.run(cmd, check=True)

    # 3. Parse rendered DOM with BeautifulSoup4
    soup = BeautifulSoup(html_out.read_text(encoding="utf-8"), "html.parser")

    title = soup.select_one("h1.movie-title") or soup.select_one("[itemprop='name']") or soup.find("h1")
    rating = soup.select_one(".rating-score, [itemprop='ratingValue'], .imdb-score")
    year = soup.select_one(".release-year, .year, time")
    synopsis = soup.select_one(".synopsis, .movie-description, [itemprop='description'], p.plot")
    poster = soup.select_one(".poster img, .movie-cover img, [itemprop='image']")
    cast = [c.get_text(strip=True) for c in soup.select(".cast-list .actor, .credits .name, [itemprop='actor']")]

    movie_data = {
        "url": target_url,
        "title": title.get_text(strip=True) if title else "N/A",
        "rating": rating.get_text(strip=True) if rating else "N/A",
        "year": year.get_text(strip=True) if year else "N/A",
        "synopsis": synopsis.get_text(strip=True) if synopsis else "N/A",
        "poster_url": poster.get("src") if poster else "N/A",
        "cast": cast[:10]
    }

    # 4. Save structured JSON to disk
    out_json = OUTPUT_DIR / "movie_data.json"
    out_json.write_text(json.dumps(movie_data, indent=2, ensure_ascii=False), encoding="utf-8")
    print(f"[✔] Movie scraped: {movie_data['title']} ({movie_data['year']}) -> {out_json}")
    return movie_data

if __name__ == "__main__":
    scrape_movie_details("https://example.com/movies/inception-2010")

Pattern 2: Node.js & TypeScript Scraper (E-Commerce Catalog Harvester)

Node.js developers can use child_process.spawn with cheerio to build asynchronous catalog crawlers:

ecommerce_scraper.js
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const cheerio = require('cheerio');

const RBSM_BIN = process.platform === 'win32' ? 'rbsm_windows_amd64.exe' : './rbsm_linux_amd64';
const OUTPUT_DIR = path.join(__dirname, 'output');
if (!fs.existsSync(OUTPUT_DIR)) fs.mkdirSync(OUTPUT_DIR, { recursive: true });

async function scrapeProducts(categoryUrl) {
    const macroPath = path.join(OUTPUT_DIR, 'scrape_products.mac');
    const htmlPath = path.join(OUTPUT_DIR, 'catalog_rendered.html');

    // 1. Write macro script with infinite scroll
    const macroScript = `
GOTO "${categoryUrl}" "https://google.com"
WAIT 2.0 3.0
DISMISS_POPUPS
SCROLL_UNTIL ".product-card" 40 15 400
SAVE_HTML "${htmlPath.replace(/\\/g, '/')}"
ECHO "[+] Products rendered and exported."
`;
    fs.writeFileSync(macroPath, macroScript.trim(), 'utf8');

    // 2. Execute RBSM
    console.log(`[*] Running RBSM engine for: ${categoryUrl}`);
    await new Promise((resolve, reject) => {
        const proc = spawn(RBSM_BIN, [`-macros=${macroPath}`, '-headless=true', '-human=2']);
        proc.on('close', (code) => code === 0 ? resolve() : reject(new Error(`Exit code ${code}`)));
    });

    // 3. Parse with Cheerio
    const rawHtml = fs.readFileSync(htmlPath, 'utf8');
    const $ = cheerio.load(rawHtml);
    const products = [];

    $('.product-card, .item-card').each((i, el) => {
        const title = $(el).find('h2, .product-title').text().trim();
        const price = $(el).find('.price, .current-price').first().text().trim();
        const link = $(el).find('a.product-link').attr('href');
        if (title && price) {
            products.push({ index: i + 1, title, price, url: link || 'N/A' });
        }
    });

    const jsonPath = path.join(OUTPUT_DIR, 'products.json');
    fs.writeFileSync(jsonPath, JSON.stringify(products, null, 2), 'utf8');
    console.log(`[✔] Extracted ${products.length} products to ${jsonPath}`);
    return products;
}

scrapeProducts('https://example.com/category/electronics');

Pattern 3: High-Concurrency Go Pipeline (Goroutines & Channels)

main.go
package main

import (
    "context"
    "fmt"
    "os"
    "os/exec"
    "path/filepath"
    "sync"
    "time"
)

func runScraperJob(ctx context.Context, jobID int, targetURL string) error {
    macroFile := filepath.Join("output", fmt.Sprintf("job_%d.mac", jobID))
    htmlOut := filepath.Join("output", fmt.Sprintf("page_%d.html", jobID))
    
    script := fmt.Sprintf("GOTO "%s" "https://google.com"
WAIT 2
DISMISS_POPUPS
SAVE_HTML "%s"", targetURL, filepath.ToSlash(htmlOut))
    _ = os.WriteFile(macroFile, []byte(script), 0644)

    cmd := exec.CommandContext(ctx, "./rbsm_linux_amd64",
        fmt.Sprintf("-macros=%s", macroFile),
        "-headless=true",
        "-limit-proxy=1",
    )
    return cmd.Run()
}

Pattern 4: Bash One-Liner Pipelines & Automated Cron Tasks

Combine headless RBSM with Unix pipes (awk, jq, curl) for cron jobs and automated data delivery:

nightly_pipeline.sh
#!/usr/bin/env bash
# Nightly Automated Price Monitoring Pipeline

# 1. Run headless RBSM with speed rules
./rbsm_linux_amd64 -macros=macros/price_check.mac -headless=true -rules=rules/speed.json

# 2. Process extracted CSV with awk
if [ -f "output/prices.csv" ]; then
    echo "[+] Processing extracted prices..."
    cat output/prices.csv | awk -F',' '{print "Product: " $1 " | Price: " $2}'
    
    # 3. Post summary webhook to Slack / Discord
    curl -X POST -H 'Content-type: application/json' \
      --data '{"text":"✅ Daily price scrape completed successfully."}' \
      https://hooks.slack.com/services/YOUR/WEBHOOK/URL
fi

Pattern 5: Programmatic JSON-RPC Driver (Playwright/Puppeteer Alternative)

Run RBSM as a persistent background engine using standard JSON-RPC 2.0 (MCP Protocol) over stdin / stdout. Execute any tool—including pre-navigation multi-frame/worker script injection (add_init_script)—directly from Python or Node.js:

rbsm_driver.py
#!/usr/bin/env python3
import json, os, subprocess

class RBSM:
    def __init__(self, bin_path="./rbsm_windows_amd64.exe" if os.name == "nt" else "./rbsm_linux_amd64", headless=False):
        self.proc = subprocess.Popen(
            [bin_path, "-mcp-server=true", f"-headless={str(headless).lower()}", "-human=2"],
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1
        )
        self._id = 0
        # 1. MCP Handshake
        self._send("initialize", {
            "protocolVersion": "2024-11-05", "capabilities": {},
            "clientInfo": {"name": "python-rbsm-client", "version": "1.0"}
        })

    def _send(self, method: str, params: dict) -> dict:
        self._id += 1
        payload = {"jsonrpc": "2.0", "id": self._id, "method": method, "params": params}
        self.proc.stdin.write(json.dumps(payload) + "\n")
        self.proc.stdin.flush()
        return json.loads(self.proc.stdout.readline())

    def call(self, tool_name: str, **kwargs) -> str:
        res = self._send("tools/call", {"name": tool_name, "arguments": kwargs})
        content = res.get("result", {}).get("content", [{}])
        return content[0].get("text", "") if content else ""

    def add_init_script(self, script: str): return self.call("add_init_script", script=script)
    def goto(self, url: str): return self.call("navigate", url=url)
    def click(self, selector: str): return self.call("smart_click", selector=selector)
    def type(self, selector: str, text: str, clear=True): return self.call("type_text", selector=selector, text=text, clear=clear)
    def get_network_response(self, request_id: str): return self.call("get_network_response", request_id=request_id)
    def snapshot(self) -> str: return self.call("get_dom_snapshot")
    def close(self): self.proc.terminate()

# Usage
if __name__ == "__main__":
    page = RBSM(headless=False)
    page.add_init_script("window.__PY_STEALTH__ = true;")
    page.goto("https://example.com")
    print("Page Title:", page.call("get_page_title"))
    print("DOM Length:", len(page.snapshot()))
    page.close()
rbsm_driver.js
const { spawn } = require('child_process');
const readline = require('readline');

class RBSMDriver {
    constructor(binPath = process.platform === 'win32' ? 'rbsm_windows_amd64.exe' : './rbsm_linux_amd64') {
        this.proc = spawn(binPath, ['-mcp-server=true', '-headless=false', '-human=2']);
        this.rl = readline.createInterface({ input: this.proc.stdout });
        this.reqId = 0;
        this.pending = new Map();

        this.rl.on('line', (line) => {
            if (!line.trim()) return;
            const res = JSON.parse(line);
            if (this.pending.has(res.id)) {
                const resolve = this.pending.get(res.id);
                this.pending.delete(res.id);
                resolve(res);
            }
        });

        // Initialize MCP Protocol
        this._send('initialize', {
            protocolVersion: '2024-11-05',
            capabilities: {},
            clientInfo: { name: 'node-rbsm', version: '1.0' }
        });
    }

    _send(method, params) {
        return new Promise((resolve) => {
            const id = ++this.reqId;
            this.pending.set(id, resolve);
            this.proc.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
        });
    }

    async call(name, args = {}) {
        const res = await this._send('tools/call', { name, arguments: args });
        return res.result?.content?.[0]?.text || '';
    }

    async addInitScript(script) { return this.call('add_init_script', { script }); }
    async goto(url) { return this.call('navigate', { url }); }
    async click(selectors) { return this.call('smart_click', { selectors }); }
    async snapshot() { return this.call('get_dom_snapshot', {}); }
    close() { this.proc.kill(); }
}

// Usage
(async () => {
    const page = new RBSMDriver();
    await page.addInitScript("window.__NODE_STEALTH__ = true;");
    await page.goto('https://example.com');
    const html = await page.snapshot();
    console.log('[✔] Page loaded via Node.js JSON-RPC driver, DOM size:', html.length);
    page.close();
})();

❓ 16. Troubleshooting & FAQ

"License Invalid or Expired" / Machine HWID Mismatch

  • Verify license.lic is located in the exact same folder as your RBSM binary.
  • Verify the machine Hardware ID (from rbsm -hwid) matches the ID provided during license checkout.
  • Linux / VPS Users: Ensure you ran both sudo ./rbsm -hwid and the execution with sudo. Without sudo, unprivileged Linux access cannot read hardware DMI tables (/sys/class/dmi/id/*), resulting in an inconsistent or changing HWID.

Running Headless on Minimal Linux Cloud VPS

On freshly deployed minimal Ubuntu / Debian servers, install essential browser dependencies:

Ubuntu / Debian Shell
sudo apt-get update && sudo apt-get install -y libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libasound2
Headless Execution
sudo ./rbsm_linux_amd64 -macros=macros/scrape.mac -headless=true

Proxy Connection Timeouts

  • Check that the proxy host, port, and credentials are correct in proxies.txt.
  • If using strict residential pools, test with -proxy=true to let RBSM automatically detect the exit IP location.
  • If you know your proxy pool is healthy and want to skip reachability checks, pass -no-judges=true.

🔄 17. Engine Self-Update & Releases

RBSM features automated version detection and atomic, in-place binary upgrades. Routine CLI and macro operations run with zero background network latency.

💡 Automatic Non-Intrusive Release Notification

Whenever a new release is available, RBSM automatically displays a notification banner in your console. You retain complete control over when to trigger an upgrade.

CLI Update Flags

Flag Type Default Description
-update-bin / -self-update / -upgrade bool false Automatically queries the gateway, downloads the latest binary for your OS & architecture, and upgrades the executable in-place.
-check-update bool false Checks if a new release is available without downloading or modifying files.
-server-url <url> string https://rbsm.nexustrc.app Custom update gateway server URL.

Self-Upgrade Examples

Windows CMD / PowerShell
# In-place self-upgrade:
.\rbsm_windows_amd64.exe -update-bin

# Check for new version:
.\rbsm_windows_amd64.exe -check-update