How the Agent Reach Configure Command Extracts Browser Cookies Automatically
The agent-reach configure --from-browser command extracts authentication cookies from Chrome, Firefox, and other supported browsers by reading native SQLite databases via the rookiepy or browser-cookie3 libraries, then maps them to platform-specific configuration keys for Twitter/X, XiaoHongShu, Bilibili, and Xueqiu.
The open-source project Panniantong/Agent-Reach streamlines social media data acquisition by automating the population of authentication credentials. Instead of manually copying cookie strings, the Agent Reach configure command extract browser cookies functionality reads directly from your existing browser sessions. This article examines the complete technical implementation, from CLI argument parsing in agent_reach/cli.py to the persistence layer in agent_reach/config.py.
CLI Argument Parsing and Dispatch
The entry point for cookie extraction resides in agent_reach/cli.py. The argument parser defines the --from-browser flag with strict choices: chrome, firefox, edge, brave, and opera (lines 24-33).
When a user invokes agent-reach configure --from-browser chrome, the _cmd_configure handler detects the flag and dispatches execution to the configure_from_browser function. This architectural separation keeps CLI concerns distinct from extraction logic, allowing the cookie engine to be invoked programmatically by other modules.
The --from-browser Validation
The argparse configuration validates browser names at the command-line level before any database access occurs, preventing runtime errors from invalid inputs and ensuring only supported browser profiles reach the extraction engine.
The Cookie Extraction Engine
The core implementation lives in agent_reach/cookie_extract.py. The extract_all(browser) function serves as the primary entry point, returning a structured dictionary mapping platforms to their respective authentication tokens.
Dual Library Architecture
Agent Reach implements a resilient fallback system to maximize compatibility across environments:
- Primary:
rookiepy(Rust-based) provides high-performance, cross-platform cookie reading with native decryption support. - Fallback:
browser-cookie3(Python-based) serves as the backup whenrookiepyis unavailable.
The code attempts to import rookiepy and invokes browser-specific functions such as rookiepy.chrome or rookiepy.firefox (lines 77-89). If the import fails, execution falls back to browser_cookie3.chrome or browser_cookie3.firefox (lines 99-108).
Platform Specifications (PLATFORM_SPECS)
The global PLATFORM_SPECS list (lines 15-42) acts as the extraction schema, defining rules for each supported service:
- Twitter/X: Extracts specific cookies
auth_tokenandct0. - XiaoHongShu: Captures all domain-matching cookies as a single concatenated header string.
- Bilibili: Retrieves
SESSDATAand optionallybili_jctfor CSRF protection. - Xueqiu: Validates the presence of
xq_a_tokenbefore storing any data.
Each specification contains domain patterns to match (e.g., .twitter.com), the required cookie names (or None for wildcard capture), and the target config_key used for persistence.
Reading Browser Databases
Both underlying libraries access the browser's SQLite cookie store directly. On macOS and Windows, these databases remain encrypted while the browser process is active. The implementation checks for running browser instances and raises a descriptive error if the database is locked, requiring the user to close the browser before proceeding.
Filtering and Cookie Mapping Logic
The extraction loop (lines 18-48) iterates through raw cookie objects returned by the browser libraries, applying two-stage filtering:
- Domain Matching: Cookies are kept only if their
domainattribute ends with one of the patterns defined inPLATFORM_SPECS. - Name Filtering: When a specification defines concrete cookie names, only those specific values are retained. When
cookiesisNone, all matching cookies are concatenated into a single string (e.g., XiaoHongShu's full cookie header).
The result is a dictionary keyed by config_key, such as {"twitter": {"auth_token": "...", "ct0": "..."}, "xhs": {"cookie_string": "..."}}.
Configuration Persistence and Legacy Sync
Back in _cmd_configure, the returned dictionary is written to Agent Reach's YAML-backed configuration store:
- Twitter: Maps to
twitter_auth_tokenandtwitter_ct0. - XiaoHongShu: Stores as
xhs_cookie. - Bilibili: Saves
SESSDATAasbilibili_sessdataandbili_jctasbilibili_csrf. - Xueqiu: Persists only if
xq_a_tokenis present in the extracted set.
Legacy Tool Synchronization
For Twitter credentials specifically, the system maintains backward compatibility with existing workflows by synchronizing tokens to legacy tools. The _sync_xfetch_session and _sync_bird_env helpers (lines 51-73) write the extracted auth_token and ct0 to the appropriate environment files or directories used by xfetch and bird.
Practical Usage Examples
Extract cookies from your default Chrome profile via the command line:
agent-reach configure --from-browser chrome
Expected output displays per-platform extraction status:
Extracting cookies from chrome...
✅ Twitter/X: auth_token + ct0
✅ XiaoHongShu: 12 cookies
✅ Bilibili: SESSDATA + bili_jct
✅ Xueqiu: 8 cookies (含 xq_a_token)
✅ Cookies configured! Run `agent-reach doctor` to verify.
Access the extraction engine programmatically from custom scripts:
from agent_reach.cookie_extract import extract_all, configure_from_browser
from agent_reach.config import Config
cfg = Config()
# Extract raw cookies from Firefox
raw = extract_all("firefox")
print(raw)
# Output: {'twitter': {'auth_token': 'abc123', 'ct0': 'xyz789'}, 'xhs': {'cookie_string': '...'}}
# Auto-populate Agent Reach configuration with results
results = configure_from_browser("firefox", cfg)
for platform, ok, msg in results:
print(f"{platform}: {'✅' if ok else '❌'} {msg}")
Summary
agent_reach/cli.pyimplements the--from-browserargument parsing and delegates to the extraction handler at lines 24-33.agent_reach/cookie_extract.pycontains theextract_allandconfigure_from_browserfunctions, implementing a priority fallback fromrookiepytobrowser-cookie3.PLATFORM_SPECSdefines platform-specific rules for Twitter/X, XiaoHongShu, Bilibili, and Xueqiu, specifying domain patterns and required cookie names.- The browser process must be closed during extraction to avoid encrypted database locks on macOS and Windows systems.
- Extracted values map to specific configuration keys including
twitter_auth_token,xhs_cookie, andbilibili_sessdata. - Legacy synchronization helpers (
_sync_xfetch_session,_sync_bird_env) maintain compatibility with existing Twitter tooling.
Frequently Asked Questions
Which browsers does Agent Reach support for automatic cookie extraction?
Agent Reach supports Chrome, Firefox, Edge, Brave, and Opera. The CLI validates these choices through the --from-browser argument definition in agent_reach/cli.py, while the underlying extraction libraries handle each browser's unique SQLite database location and encryption method.
Why must I close my browser before running the configure command?
The Agent Reach configure command extract browser cookies process requires exclusive access to the browser's SQLite database files. On macOS and Windows, these files remain encrypted and locked while the browser process is running. The extraction engine detects active instances and raises a clear error message to prevent permission failures or corrupted reads.
What happens if rookiepy is not installed on my system?
The system automatically falls back to browser-cookie3, a pure Python library with similar cross-platform capabilities. The implementation in agent_reach/cookie_extract.py (lines 99-108) wraps the rookiepy import in a try-except block, ensuring the command functions regardless of which library is available, though rookiepy provides superior Rust-based performance.
How does the system determine which cookies belong to which platform?
The PLATFORM_SPECS configuration table in agent_reach/cookie_extract.py (lines 15-42) defines domain suffix patterns (e.g., .twitter.com, .xhslink.com) and specific cookie names for each service. For Twitter, it extracts only auth_token and ct0; for XiaoHongShu, it concatenates all matching cookies into a single header string. These are then mapped to typed configuration keys like twitter_auth_token or xhs_cookie in the YAML config store.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →