Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

feat(x): extra bird cookie lookups on Linux and Mac mini (MacBook unchanged; grok pin-only) (#1087)

Matt Van Horn08af1f827bf1
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 381bec5d..8dd54e6a 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -176,6 +176,17 @@ python3 skills/last30days/scripts/last30days.py "MCP servers" \
**X on cookie-less hosts.** Bird (the free X source) scrapes X using your logged-in browser cookies (`AUTH_TOKEN`/`CT0`), which agent hosts like OpenClaw, CI, or headless runs often can't supply — and scraping carries some account risk. On those, set `XQUIK_API_KEY` (or `XAI_API_KEY`) for full, ranked X coverage from a single API key: the same engagement-based ranking, first-party authorship, and handle (from/mentions) lanes the native X source gets. `--diagnose` reports whether the key is working (and flags an unpaid key).
+**Extra bird cookie lookups on Linux and Mac mini.** On a MacBook the X cookie path is unchanged (Firefox/Safari/Chrome extract, gated by `FROM_BROWSER`). On **extra hosts** the engine adds two more ways to hand bird a complete `auth_token`+`ct0` pair, tried in order (first COMPLETE pair wins; no half-pair merge; nothing is ever written to the `.env` and cookie values are never printed):
+
+1. an explicit env `AUTH_TOKEN`+`CT0` (never overwritten);
+2. the [`agentcookie`](https://github.com/) sidecar CLI — `agentcookie cookies --domain .x.com --json` — a soft dependency (absent = skipped; `AGENTCOOKIE=off` disables it) that delivers cookies on Linux, where the on-disk Chrome store can't be decrypted here;
+3. a live signed-in Chrome/Chromium session over the DevTools Protocol (`Network.getAllCookies`);
+4. the mainline browser extract, when `FROM_BROWSER` already lists a browser (on a Mac mini with a browser opted in, this native read runs *before* the CDP read).
+
+A host counts as an "extra host" when ANY of these hold: `AGENTCOOKIE=on` (explicit opt-in, any OS); the platform is Linux; a Darwin **Mac mini** (`sysctl -n hw.model` prefix `Macmini`); or a Darwin **agentcookie sink** role. The host is never inferred from the home directory, PATH, or Hermes/OpenClaw env — only those signals. A plain MacBook does no agentcookie spawn and opens no CDP socket unless `AGENTCOOKIE=on`.
+
+CDP endpoint resolution (extra hosts only, no port scan): `BROWSER_CDP_URL` if set, else port `18800` when it answers as Chrome, else `9222` + the X display number. Port `18800` is the last30days extras **NUX convention** — the agent launches a throwaway login Chrome with `SAND_CHROME_REMOTE_DEBUG_PORT=18800` (see SKILL.md's "X on Linux / Grok Bot / Mac mini"), so it is not confused with a daily Chrome profile on `9222`+display (box-chrome's own built-in default). `18800` is tried first but falls through when it yields no complete pair, so a logged-out Chrome there never shadows a logged-in profile; pin `BROWSER_CDP_URL` if a stale session answers there. A Node `--inspect` endpoint is rejected; a Chrome page target is required.
+
**Example `.env` skeleton** (placeholders only - replace with your own values):
```bash
@@ -442,6 +453,8 @@ Every live run writes its JSON result to `~/.config/last30days/doctor-cache.json
| `LAST30DAYS_DOCTOR_TTL` | Freshness window for `doctor --cached`, in **seconds**. Defaults to `900` (15 minutes). `0` makes every `--cached` call run live. |
| `LAST30DAYS_DOCTOR_PROBE_TIMEOUT` | Per-source deadline (**seconds**) for `doctor --probe` live checks. Defaults to `10`. Caps each concurrent probe so a slow source cannot hang the command. |
| `LAST30DAYS_X_BACKEND` | Pins the X backend (`bird` / `xai` / `xurl` / `xquik` / `grok`); doctor renders the pin and predicts "will use" accordingly. The unpinned auto chain is bird → xai → xurl → xquik (grok is opt-in only). Pin `grok` to enable it; a leftover `~/.grok/auth.json` is never auto-selected. |
+| `AGENTCOOKIE` | `on` opts any host (incl. a MacBook) into the extra bird cookie lookups (agentcookie sidecar + live Chrome CDP); `off` disables the agentcookie sidecar reader. Unset uses host detection (Linux / Mac mini / Darwin sink get the extras). See "Extra bird cookie lookups" above. |
+| `BROWSER_CDP_URL` | Explicit Chrome DevTools endpoint (e.g. `http://127.0.0.1:18800`) for the extra-host CDP cookie lookup. Preferred over the `18800` / `9222`+`$DISPLAY` defaults. Extra hosts only. |
| `LAST30DAYS_REDDIT_BACKEND` | `scrapecreators` makes ScrapeCreators the primary Reddit backend; doctor renders Reddit's conditional routing with the pin applied. |
| `LAST30DAYS_REDDIT_SC_MIN_ITEMS` | Integer thinness floor for ScrapeCreators Reddit **search** backfill. Default `0` = empty-only (free path keeps any non-empty result; no credit spend). Set above `0` to backfill when free yield is below that count; merged results dedupe by post id. Requires `SCRAPECREATORS_API_KEY`. Ignored when `LAST30DAYS_REDDIT_BACKEND=scrapecreators` (SC is already primary). |
diff --git a/changelog.d/+bird-cookies-linux-macmini.added.md b/changelog.d/+bird-cookies-linux-macmini.added.md
new file mode 100644
index 00000000..bd8717a8
--- /dev/null
+++ b/changelog.d/+bird-cookies-linux-macmini.added.md
@@ -0,0 +1 @@
+On Linux and Mac mini hosts (and any host that sets `AGENTCOOKIE=on`), X search can now hand Bird a complete `auth_token`+`ct0` pair from two additional sources: the `agentcookie` sidecar CLI and a live signed-in Chrome/Chromium session read over the DevTools Protocol (`Network.getAllCookies`). The first complete pair wins, cookies are never written to the `.env` or logged, and a Node `--inspect` endpoint is never mistaken for Chrome. A MacBook is unchanged — it uses only the existing browser-cookie extract unless `AGENTCOOKIE=on`. The X backend chain and grok's pin-only status are unchanged from `main`.
diff --git a/docs/plans/2026-08-31-feat-bird-cookies-linux-macmini-plan.md b/docs/plans/2026-08-31-feat-bird-cookies-linux-macmini-plan.md
new file mode 100644
index 00000000..f498583b
--- /dev/null
+++ b/docs/plans/2026-08-31-feat-bird-cookies-linux-macmini-plan.md
@@ -0,0 +1,70 @@
+# Bird X cookies on Linux and Mac mini - Plan
+
+Ship path: rewrite PR 1087 in place. Same branch. Do not open a second PR.
+
+Goal: Feed bird a complete auth_token+ct0 from env, agentcookie cookies, or live Chrome login on Linux, a Mac mini (`sysctl -n hw.model` starts with `Macmini`), or Darwin agentcookie sink role. Leave a MacBook on main. grok pin-only everywhere. Do not detect Hermes or OpenClaw by install.
+
+R1 extra-host sidecar → bird posts.
+R2 macOS extract stays as main.
+R3 never write AUTH_TOKEN/CT0 to .env.
+R4 never print cookie values.
+R5 doctor names real bird source.
+R6 unpinned chain bird→xai→xurl→xquik; grok `_X_BACKEND_OPT_IN`; pin no failover.
+R7 MacBook no agentcookie/CDP unless AGENTCOOKIE=on. Linux/Mac mini/sink: agentcookie if CLI present and not AGENTCOOKIE=off.
+R8 missing sidecar is not a crash.
+R9 no marketplace X plugin.
+R10 Linux/Mac-mini Chrome login via CDP `Network.getAllCookies`, not SQLite.
+R11 extra probe: env pair, agentcookie, CDP, extract if FROM_BROWSER set. First complete pair. No half-pair merge.
+R12 MacBook FROM_BROWSER unset/off = no CDP.
+R13 Darwin Keychain extract still works when FROM_BROWSER=auto or chrome.
+R14 CDP extras-only.
+R15 diagnose/preflight/doctor plan-only.
+R16 Firefox/Safari/Windows/--no-browser-cookies as main.
+R17 grok pin-only every OS.
+R18 MacBook doctor must not predict bird from agentcookie-on-PATH.
+R19 Mac mini: extract before CDP if FROM_BROWSER already opted in.
+R20 CDP ports: BROWSER_CDP_URL, 18800 if Chrome, 9222+$DISPLAY. Chrome page target. No MacBook 9222-9232 scan.
+R21 MacBook never reads sidecar.
+R22 leftover grok + XAI_API_KEY uses xai.
+
+AE8 MacBook hw.model MacBookPro, FROM_BROWSER unset, agentcookie on PATH, fake CDP, grok AUTH_OK, XAI_API_KEY → xai, no CDP, no agentcookie subprocess.
+AE10 Darwin hw.model=Macmini9,1 sidecar pair FROM_BROWSER unset → bird from agentcookie. MacBook + ~/.hermes still AE8.
+AE7 Linux no bird cookies, grok AUTH_OK, XAI_API_KEY → xai not grok.
+
+KTD1 spawn `agentcookie cookies --domain .x.com --json` only when extras apply. Never open cookies-plain.db.
+KTD5 do not change `_X_BACKEND_ORDER` or `_X_BACKEND_OPT_IN` vs main.
+KTD7 CDP extras-only, Chrome page target.
+KTD8 first complete pair, no merge.
+
+Mac mini detect: `sysctl -n hw.model` prefix `Macmini`; sysctl failure → MacBook.
+Darwin agentcookie sink role still gets extras on non-mini Darwin. Source role on a MacBook does not.
+
+## Implementation notes (as shipped)
+
+- `env.x_extras_enabled(config)` is the single gate: True when `AGENTCOOKIE=on`, or platform is Linux, or a Darwin Mac mini (`_mac_model()` prefix `Macmini`), or a Darwin agentcookie sink (`agentcookie.role_is_sink`, a subprocess-free config-file read; parse failure = not sink). Never consults home dir, PATH, or Hermes/OpenClaw env.
+- `env._discover_and_apply_x_credentials` runs in `read` mode only: env pair (never overwritten) → agentcookie (extras) → CDP (extras) → mainline browser extract; on a Mac mini with a browser opted in, the extract runs before CDP (R19). Sources apply atomically (no half-pair merge); labels `env` / `agentcookie` / `chrome cdp` / `browser`.
+- `chrome_cdp` resolves `BROWSER_CDP_URL`, else `18800` (only if `/json/version` reports Chrome/Chromium), else `9222`+`$DISPLAY`; requires a Chrome page target; rejects a Node inspector. No port scan.
+- `env.x_pending_browser_auth` counts the agentcookie sidecar as a pending source only on extra hosts, so a MacBook never predicts bird from an agentcookie binary on PATH (R18).
+- grok, backends, and doctor are unchanged from `main` (grok pin-only; `_X_BACKEND_ORDER = bird, xai, xurl, xquik`; `_X_BACKEND_OPT_IN = grok`).
+
+Copy this plan to `docs/plans/` in the PR. Update the PR title/body: extras on Linux and Mac mini; MacBook last30days unchanged; grok pin-only.
+
+## Delta 2026-09-01 — the login recipe (proven live on Grok Bot)
+
+CDP harvest alone was not enough: on a fresh Grok Bot NUX the Auto path only ran `setup --allow-browser-cookies`, which on Linux tries a sqlite extract, finds nothing, and never opens a login window. Two human logins hours apart proved the working recipe is: the agent launches a throwaway-profile Chrome via the host `box-chrome` wrapper on the last30days extras port, opens `x.com/login`, then **hands the desktop to the human to type** — driving the form itself (computerUse/overlay on the login) plus X rate-limit was the failure mode.
+
+- **Port fact:** `18800` is NOT box-chrome's built-in default. box-chrome uses `SAND_CHROME_REMOTE_DEBUG_PORT` or `9222 + DISPLAY_NUM` (on Grok Bot `DISPLAY=:7` → `9229`). `18800` is the last30days extras NUX convention: the agent launches the throwaway with `SAND_CHROME_REMOTE_DEBUG_PORT=18800` so `chrome_cdp._BOX_CHROME_PORT` finds it. Fixed the `chrome_cdp.py` docstrings/constant comment and SKILL.md that wrongly called 18800 "the box-Chrome default."
+- **Endpoint order unchanged:** `BROWSER_CDP_URL` exclusive if set, else 18800 if Chrome, else 9222+`$DISPLAY`; fall through on empty pair; pin `BROWSER_CDP_URL` after NUX as the guard against a stale session answering on 18800. No port scan.
+- **SKILL.md recipe** added to BOTH the first-run Auto setup (Claude Code Modal Flow and Non-Modal Prose Flow, after "Yes — X cookies") and the "X on Linux / Grok Bot / Mac mini" repair section: `AGENTCOOKIE=off` for the harvest; launch box-chrome throwaway on 18800; do NOT fill/drive the form; hand off to the human; confirm signed in; pin `BROWSER_CDP_URL=http://127.0.0.1:18800` (never `AUTH_TOKEN`/`CT0`); run `setup --allow-browser-cookies`; stop on block/rate-limit. A MacBook skips all of this (Keychain/Firefox/Safari extract). R3 still holds — cookies are never written to `.env`.
+- **Helper:** `skills/last30days/scripts/box_chrome_login.py` prints the exact host-correct launch command (or `--exec` launches it), extras-gated, no-op on a MacBook, reads no cookies and prints no cookie values. Tests lock: MacBook never spawns it; extras + box-chrome on PATH documents 18800; `candidate_endpoints` order unchanged; `FROM_BROWSER=off` still skips CDP.
+- Greptile constraints preserved: same host/path/partition cookie pairing; refuse `wss://`/`https://` CDP bases.
+
+### Delta 2026-09-01b — harvest confirmed; flag delta corrected
+
+A live harvest with exclusive `BROWSER_CDP_URL=http://127.0.0.1:9334` returned a complete same-host `x.com` `auth_token`+`ct0` (path `/`, unpartitioned); doctor reported `bird=ok` and the `~/.config/last30days/.env` sha256 was unchanged (R3 holds — no cookie values persisted).
+
+The working-vs-failing difference was the launcher, not the user-agent:
+- **Working (9334):** launched via `box-chrome` → `--class=box-chrome`, `--enable-unsafe-swiftshader`, no `--ignore-gpu-blocklist`. The `GrokAgent` UA token was NOT in argv (this box has `/tmp/sand-ua-token-disabled`).
+- **Failed (18800 the night before):** a raw Chrome with `--class=l30d-pr1087-chrome` (NOT `box-chrome`), same swiftshader, same absence of the GrokAgent UA.
+
+So: launch via `box-chrome` (class `box-chrome`); do NOT launch raw Chrome with a custom `--class`; do NOT claim the `GrokAgent` UA is required or was present. The human types the login; the agent never drives the form. Pin `BROWSER_CDP_URL` to the debug port the Chrome actually listens on (`18800` for the convention launch, or the real port such as `9334`). `18800` remains the last30days NUX convention, not box-chrome's built-in default. SKILL.md, the helper, and CONFIGURATION.md updated accordingly; a test locks that the helper command goes through `box-chrome` with no custom `--class`.
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.md
index b683f051..94de5d7b 100644
--- a/skills/last30days/SKILL.md
+++ b/skills/last30days/SKILL.md
@@ -588,6 +588,8 @@ Options (give each option the description shown):
The consented `setup --allow-browser-cookies` run extracts cookies (Chrome/Chromium family first via the Keychain with no Full Disk Access, then Firefox and Safari as fallbacks; the winning browser is pinned for future runs only when it is Firefox or Safari, so Chrome never re-triggers the Keychain prompt on later runs) and best-effort installs yt-dlp (YouTube), the free keyless Digg CLI (`digg-pp-cli` via `@mvanhorn/printing-press-library install digg --cli-only`; Digg activates only when the binary is on the **agent subprocess PATH**, typically `$HOME/.local/bin`; setup reports honestly if installed off-PATH; recommend-only if `npx` is unavailable), plus the free keyless arXiv and Techmeme CLIs. Show the user what was found and installed - including whether Digg landed on PATH (active) or off-PATH (installed but not yet active).
+**Extras-host X login (Linux / Grok Bot / Mac mini / Darwin agentcookie sink — a MacBook SKIPS this).** On a MacBook the Keychain/Firefox/Safari extract above is all X needs. On an extras host the local Chrome store can't be decrypted, so that extract finds nothing and X stays empty unless you also capture a LIVE login over CDP. After the cookie-consent setup run: run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/box_chrome_login.py` — it prints the exact host-correct command (or launches it with `--exec`), and on a MacBook it prints "no launch needed" and spawns nothing. When `box-chrome` is on PATH it launches a throwaway profile on the last30days extras port **18800** (the last30days convention `SAND_CHROME_REMOTE_DEBUG_PORT=18800`, not box-chrome's default): `CHROME_USER_DATA_DIR=/tmp/last30days-x-chrome SAND_CHROME_REMOTE_DEBUG_PORT=18800 box-chrome --new-window https://x.com/login`. Wait for the x.com login page, then HAND THE DESKTOP to the human to type — do NOT fill or drive the form. After they sign in, append `BROWSER_CDP_URL=http://127.0.0.1:18800` to `.env` (never `AUTH_TOKEN`/`CT0`; keep `AGENTCOOKIE=off` during the harvest), then re-run `setup --allow-browser-cookies` so extras CDP reads the live pair. Full steps and the block/rate-limit stop rule are in **X on Linux / Grok Bot / Mac mini** below.
+
**macOS Full Disk Access remediation (Safari fallback only).** Chrome and Firefox need no Full Disk Access; only the Safari fallback does. After the `setup` run, inspect its stderr. If it contains `Permission denied reading Cookies.binarycookies` and the platform is macOS, the OS blocked the Safari read - surface the fix instead of swallowing it: `macOS blocked the Safari cookie read. If your x.com login is in Chrome, you don't need this. To use Safari: System Settings > Privacy & Security > Full Disk Access > enable your terminal (or the Claude app), then I can retry.` Offer ONE retry of the `setup` command. If the user skips, continue.
**Step 4: ScrapeCreators offer (every first run).** Show this as plain text, then a modal:
@@ -651,6 +653,7 @@ For hosts without interactive modal prompts (OpenClaw, Codex, Cursor, Gemini CLI
**3. Cookie consent (ask BEFORE reading anything).** First check if `BROWSER_CONSENT=true` already exists in `~/.config/last30days/.env` (e.g. granted in a prior Claude Code session); if so, skip this prompt and run `setup --allow-browser-cookies` directly. Otherwise ask. Example: `I can read your browser cookies to unlock X/Twitter and other logged-in sources - I check Chrome first (a one-time macOS Keychain prompt may appear; click Always Allow), then Firefox and Safari. Want me to? (yes / no)` **Wait for the answer.**
- On **yes** → run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --allow-browser-cookies` (and append `BROWSER_CONSENT=true` to `.env` after it completes). Extracts cookies (Chrome/Chromium family first via the Keychain with no Full Disk Access, then Firefox and Safari; only a Firefox/Safari winner is pinned for later runs, so Chrome never re-prompts) and best-effort installs yt-dlp (YouTube), the free keyless Digg CLI (`digg-pp-cli` via `@mvanhorn/printing-press-library install digg --cli-only`; activates only when on the agent subprocess PATH, typically `$HOME/.local/bin`; reports honestly if off-PATH; recommend-only if `npx` is unavailable), plus the free keyless arXiv and Techmeme CLIs.
+ - **Extras hosts (Linux / Grok Bot / Mac mini / Darwin agentcookie sink) — a MacBook SKIPS this.** On these hosts the Chrome cookie store can't be decrypted, so the extract above finds nothing and X stays empty unless you capture a LIVE login over CDP. Run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/box_chrome_login.py` (prints the host-correct command; `--exec` launches it; a MacBook prints "no launch needed" and spawns nothing). When `box-chrome` is on PATH it launches a throwaway profile on the last30days extras port **18800** (`SAND_CHROME_REMOTE_DEBUG_PORT=18800`, not box-chrome's default): `CHROME_USER_DATA_DIR=/tmp/last30days-x-chrome SAND_CHROME_REMOTE_DEBUG_PORT=18800 box-chrome --new-window https://x.com/login`. Wait for the x.com login page, then HAND THE DESKTOP to the human to type — do NOT drive the form. After they sign in, append `BROWSER_CDP_URL=http://127.0.0.1:18800` to `.env` (never `AUTH_TOKEN`/`CT0`; keep `AGENTCOOKIE=off` during the harvest) and re-run `setup --allow-browser-cookies`. Full steps and the block/rate-limit stop rule: **X on Linux / Grok Bot / Mac mini** below.
- On **no** → run `FROM_BROWSER=off "${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup`. Skips all cookie reads; still installs yt-dlp (YouTube), Digg, arXiv, and Techmeme, still writes `SETUP_COMPLETE`.
**4. Full Disk Access remediation (macOS only).** After `setup`, inspect stderr. If it contains `Permission denied reading Cookies.binarycookies` on macOS, surface: `macOS blocked the cookie read. To enable X/Twitter: System Settings > Privacy & Security > Full Disk Access > enable your terminal (or the Claude app), then I can retry.` Offer ONE retry. If skipped, continue.
@@ -683,6 +686,22 @@ The magic of /last30days is Reddit comments + X posts together - and both are fr
- `XQUIK_API_KEY=xxx` - keyless-style X via Xquik.
- `AUTH_TOKEN=xxx` + `CT0=xxx` - paste your X cookies manually (x.com → F12 → Application → Cookies).
+**X on Linux / Grok Bot / Mac mini (repair).** These hosts can't decrypt a local Chrome cookie store, so if X returns nothing there, feed bird a cookie pair one of these ways (a MacBook does NOT do any of this — it uses its Keychain / Firefox / Safari extract; do not launch box-chrome on a MacBook):
+- **agentcookie sidecar:** install the `agentcookie` CLI so the engine can read your `auth_token`/`ct0` from it automatically. Nothing to configure; `AGENTCOOKIE=off` disables it.
+- **Live Chrome login over CDP (the proven Grok Bot path).** The engine reads a live signed-in Chrome over the DevTools Protocol, but you must LAUNCH that Chrome on the extras port and log in first — `setup --allow-browser-cookies` alone opens no window. Steps (a MacBook skips all of this):
+ 1. Set `AGENTCOOKIE=off` for this harvest so a sidecar can't mix in a different pair (leave it unset again after success).
+ 2. Launch a throwaway login Chrome on the last30days extras port **18800** — this port is the last30days convention (`SAND_CHROME_REMOTE_DEBUG_PORT=18800`), NOT box-chrome's built-in default (`9222` + the display number). **Launch via the host `box-chrome` wrapper** (which sets `--class=box-chrome`); do NOT launch raw `google-chrome-stable`, and in particular do NOT launch raw Chrome with a custom `--class` — a raw Chrome with `--class=l30d-…` failed where `box-chrome` (class `box-chrome`) succeeded. Do NOT rely on any `GrokAgent` user-agent token: it is not required and may be disabled on the host (`/tmp/sand-ua-token-disabled`), so never tell users it must be present. Run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/box_chrome_login.py` to print the exact host-correct command (add `--exec` to launch it); on a MacBook it prints "no launch needed" and spawns nothing. When `box-chrome` is on PATH the command is:
+ ```
+ mkdir -p /tmp/last30days-x-chrome
+ CHROME_USER_DATA_DIR=/tmp/last30days-x-chrome SAND_CHROME_REMOTE_DEBUG_PORT=18800 box-chrome --new-window https://x.com/login
+ ```
+ If `box-chrome` is missing, do NOT invent a google-chrome flag soup (a raw Chrome with a custom `--class` is what failed) — sign into x.com in a Chrome that already exposes a remote-debugging port and pin `BROWSER_CDP_URL` to that endpoint instead.
+ 3. Do NOT fill the login form and do NOT drive the page (no Playwright/Puppeteer/computerUse/xdotool, no typing credentials). Wait until the x.com login page is actually visible, THEN hand the desktop / computer-preview to the human: "Log into X in this Chrome window." (A HUD over the login is OK only as a handoff, never to click the page.)
+ 4. After they hand back, confirm the window is signed in (x.com/home). Append `BROWSER_CDP_URL=http://127.0.0.1:<port>` to `~/.config/last30days/.env` (append-only), using the debug port the Chrome actually listens on — `18800` if you launched with the command above, or the real port otherwise (a live harvest pinned `http://127.0.0.1:9334`). Do NOT write `AUTH_TOKEN` or `CT0` — the pair is read live each run. Then run `setup --allow-browser-cookies`; extras CDP reads the live pair. Pinning `BROWSER_CDP_URL` after login is also the guard if a stale/logged-out Chrome happens to answer on `18800`.
+ 5. If X shows a block / challenge / rate-limit, STOP — tell them to wait and retry later. Do not keep launching Chromes.
+- **`XAI_API_KEY=xxx`** - key-based X, no browser at all.
+- **Grok CLI** - run `grok login`, then pin `LAST30DAYS_X_BACKEND=grok` (pin-only; a leftover grok login never auto-steals the X lane). Needs a Grok plan.
+
**Reddit (free, works out of the box):**
- Free keyless discovery (RSS + shreddit listings) gives threads + top comments with upvote counts. No setup required.
- `SCRAPECREATORS_API_KEY=xxx` - optional Reddit search backup when the free path returns **no items** (default). A non-empty free scrape does **not** escalate — set `LAST30DAYS_REDDIT_SC_MIN_ITEMS` or `LAST30DAYS_REDDIT_BACKEND=scrapecreators` if you want paid backfill/primary (see Reddit backend pin).
diff --git a/skills/last30days/scripts/box_chrome_login.py b/skills/last30days/scripts/box_chrome_login.py
new file mode 100644
index 00000000..5c651cd9
--- /dev/null
+++ b/skills/last30days/scripts/box_chrome_login.py
@@ -0,0 +1,181 @@
+#!/usr/bin/env python3
+"""Extras-host X login helper: print (or ``--exec``) the box-chrome launch.
+
+On extra hosts (Linux, a Darwin Mac mini, a Darwin agentcookie sink, or
+``AGENTCOOKIE=on``) the local Chrome cookie store cannot be decrypted, so the
+only way to hand bird a live X session is to launch a throwaway Chrome with a
+remote-debugging port, let the human log in, and read the pair over CDP. This
+helper prints the exact, host-correct launch command — or launches it with
+``--exec`` — and refuses to do anything on a MacBook (which keeps its Keychain /
+Firefox / Safari extract path).
+
+Contract, matching the rest of the feature:
+* **Extras only.** On a MacBook (and any non-extras host) it prints "no launch
+ needed" and never spawns a browser, even with ``--exec``.
+* Launch on the last30days extras NUX port ``18800``
+ (``SAND_CHROME_REMOTE_DEBUG_PORT=18800``) so ``chrome_cdp`` finds it. This is
+ NOT box-chrome's built-in default (``9222`` + the display number).
+* Uses the host ``box-chrome`` wrapper (which sets ``--class=box-chrome``);
+ never assembles a raw ``google-chrome-stable`` flag soup and never launches
+ raw Chrome with a custom ``--class`` (a raw Chrome with ``--class=l30d-…``
+ failed live where ``box-chrome`` succeeded). No special user-agent is
+ required. If ``box-chrome`` is missing it tells the user to sign into a
+ remote-debugging Chrome and pin ``BROWSER_CDP_URL``.
+* Reads NO cookies and prints NO cookie values. It never writes to the ``.env``.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+SCRIPT_DIR = Path(__file__).parent.resolve()
+sys.path.insert(0, str(SCRIPT_DIR))
+
+from lib import chrome_cdp, env # noqa: E402
+
+# The last30days extras NUX port — single source of truth is chrome_cdp.
+EXTRAS_CDP_PORT = chrome_cdp._BOX_CHROME_PORT
+DEFAULT_PROFILE_DIR = "/tmp/last30days-x-chrome"
+LOGIN_URL = "https://x.com/login"
+BOX_CHROME_BIN = "box-chrome"
+
+
+def build_recipe(
+ config: Dict[str, Any],
+ *,
+ profile_dir: str = DEFAULT_PROFILE_DIR,
+ url: str = LOGIN_URL,
+) -> Dict[str, Any]:
+ """Return the gated launch recipe. Never spawns, never reads cookies.
+
+ Keys: ``applies`` (extras host?), ``box_chrome`` (path or None), ``port``,
+ ``profile_dir``, ``url``, ``env`` (launch env overrides or None),
+ ``command`` (argv or None), ``note`` (human guidance).
+ """
+ if not env.x_extras_enabled(config):
+ return {
+ "applies": False,
+ "box_chrome": None,
+ "port": EXTRAS_CDP_PORT,
+ "profile_dir": profile_dir,
+ "url": url,
+ "env": None,
+ "command": None,
+ "note": (
+ "This host uses the standard browser-cookie path (Keychain / "
+ "Firefox / Safari extract). No box-chrome login is needed; "
+ "run `setup --allow-browser-cookies` as usual."
+ ),
+ }
+
+ box = shutil.which(BOX_CHROME_BIN)
+ if box:
+ return {
+ "applies": True,
+ "box_chrome": box,
+ "port": EXTRAS_CDP_PORT,
+ "profile_dir": profile_dir,
+ "url": url,
+ "env": {
+ "CHROME_USER_DATA_DIR": profile_dir,
+ "SAND_CHROME_REMOTE_DEBUG_PORT": str(EXTRAS_CDP_PORT),
+ },
+ "command": [box, "--new-window", url],
+ "note": (
+ "Launch this throwaway login Chrome, wait for the x.com login "
+ "page, then hand the desktop to the human to type. Do NOT drive "
+ "the page. After they sign in, pin "
+ f"BROWSER_CDP_URL=http://127.0.0.1:{EXTRAS_CDP_PORT} in .env "
+ "(never AUTH_TOKEN/CT0) and run `setup --allow-browser-cookies`."
+ ),
+ }
+
+ return {
+ "applies": True,
+ "box_chrome": None,
+ "port": EXTRAS_CDP_PORT,
+ "profile_dir": profile_dir,
+ "url": url,
+ "env": None,
+ "command": None,
+ "note": (
+ "box-chrome is not on PATH. Do not assemble a raw google-chrome "
+ "command or launch raw Chrome with a custom --class (that is what "
+ "failed live; box-chrome sets --class=box-chrome). Sign into x.com "
+ "in a Chrome that already exposes a remote-debugging port, then pin "
+ "BROWSER_CDP_URL to that endpoint in .env and run "
+ "`setup --allow-browser-cookies`."
+ ),
+ }
+
+
+def render_recipe(recipe: Dict[str, Any]) -> str:
+ """Human-readable recipe. Contains no cookie values (none are read)."""
+ lines: List[str] = []
+ if not recipe["applies"]:
+ lines.append("[box-chrome login] Not an extras host.")
+ lines.append(recipe["note"])
+ return "\n".join(lines)
+
+ if recipe["command"] is None:
+ lines.append("[box-chrome login] Extras host, but box-chrome is unavailable.")
+ lines.append(recipe["note"])
+ return "\n".join(lines)
+
+ env_prefix = " ".join(f"{k}={v}" for k, v in recipe["env"].items())
+ cmd = " ".join(recipe["command"])
+ lines.append("[box-chrome login] Extras host. Launch the throwaway login Chrome:")
+ lines.append("")
+ lines.append(f" mkdir -p {recipe['profile_dir']}")
+ lines.append(f" {env_prefix} {cmd}")
+ lines.append("")
+ lines.append(recipe["note"])
+ lines.append(
+ "For this first-run harvest, set AGENTCOOKIE=off so a sidecar can't mix "
+ "a different pair; leave AGENTCOOKIE unset again after success."
+ )
+ return "\n".join(lines)
+
+
+def main(argv: Optional[List[str]] = None) -> int:
+ argv = list(sys.argv[1:] if argv is None else argv)
+ do_exec = "--exec" in argv
+ as_json = "--json" in argv
+
+ config = env.get_config() # default policy: no cookie reads, no discovery
+ recipe = build_recipe(config)
+
+ if as_json:
+ printable = {k: v for k, v in recipe.items() if k != "box_chrome"}
+ printable["box_chrome_present"] = recipe["box_chrome"] is not None
+ print(json.dumps(printable))
+ else:
+ print(render_recipe(recipe))
+
+ if do_exec:
+ # Refuse to spawn on a non-extras host, or when box-chrome is missing.
+ if not recipe["applies"] or not recipe["command"]:
+ return 0
+ try:
+ os.makedirs(recipe["profile_dir"], exist_ok=True)
+ except OSError:
+ pass
+ launch_env = os.environ.copy()
+ launch_env.update(recipe["env"])
+ try:
+ subprocess.Popen(recipe["command"], env=launch_env)
+ except OSError as exc:
+ print(f"[box-chrome login] failed to launch: {type(exc).__name__}: {exc}",
+ file=sys.stderr)
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/last30days/scripts/lib/agentcookie.py b/skills/last30days/scripts/lib/agentcookie.py
new file mode 100644
index 00000000..b9cccc80
--- /dev/null
+++ b/skills/last30days/scripts/lib/agentcookie.py
@@ -0,0 +1,196 @@
+"""agentcookie sidecar reader — an X cookie source for the bird backend.
+
+``agentcookie`` is an external, user-installed CLI that can deliver browser
+cookies on Linux (where Chrome's SQLite cookie store cannot be decrypted by
+this engine's stdlib extractor). This module shells out to it and pulls the
+``auth_token`` + ``ct0`` pair that the bird backend needs.
+
+Deliberate constraints (see docs/plans/2026-08-31 X plan):
+
+* **Soft dependency.** Activation is gated on ``shutil.which("agentcookie")``
+ resolving on the agent subprocess PATH, exactly like the other CLI-gated
+ optional sources (Digg, yt-dlp). A binary that is absent is not an error.
+* **``AGENTCOOKIE=off`` disables it** regardless of PATH.
+* **Independent of ``FROM_BROWSER``.** Reading the sidecar is not a browser
+ extraction, so it runs even when ``FROM_BROWSER`` is unset (the state in
+ which the in-process browser extractor stays off).
+* We call ``agentcookie cookies --domain .x.com --json`` and parse its stdout.
+ We never open ``cookies-plain.db`` directly, never import an ``agentcookie``
+ Python package, and never add a Python dependency on it.
+* Cookie **values are never logged**. Only counts / names are ever emitted.
+* First complete pair wins: a lone ``auth_token`` or a lone ``ct0`` is not a
+ usable result — both must be present.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+from . import log
+
+AGENTCOOKIE_BIN = "agentcookie"
+X_COOKIE_DOMAIN = ".x.com"
+X_COOKIE_NAMES = ("auth_token", "ct0")
+
+# agentcookie writes its config (including its role: "source" or "sink") here.
+# A SINK receives cookies delivered from another machine; on Darwin, a sink is
+# an "extra host" that gets the extra cookie lookups even though it is not a
+# Mac mini. Reading this file is a plain filesystem read — NEVER a subprocess —
+# so a MacBook (source/unknown role) never spawns agentcookie just to be
+# classified (see the AE8 no-subprocess contract). Override the path for tests
+# or non-default installs with AGENTCOOKIE_CONFIG.
+_DEFAULT_CONFIG_PATH = Path.home() / ".config" / "agentcookie" / "config.json"
+
+# The sidecar read shells out to another process; keep it bounded so a hung
+# agentcookie never stalls config loading.
+_TIMEOUT_SECONDS = 10
+
+
+def _log(msg: str) -> None:
+ log.source_log("agentcookie", msg, tty_only=False)
+
+
+def is_disabled(config: Optional[Dict[str, Any]] = None) -> bool:
+ """True when ``AGENTCOOKIE=off`` in config/env disables the sidecar."""
+ raw = ""
+ if config is not None:
+ raw = config.get("AGENTCOOKIE") or ""
+ if not raw:
+ from . import env
+
+ raw = env.read_secret_env("AGENTCOOKIE") or ""
+ return str(raw).strip().lower() == "off"
+
+
+def is_available(config: Optional[Dict[str, Any]] = None) -> bool:
+ """True when the sidecar could be used: on PATH and not disabled.
+
+ PATH-only, side-effect free (no subprocess). Safe for the doctor /
+ preflight prediction path — it reads no cookies, only whether the binary
+ would be reachable at run time.
+ """
+ if is_disabled(config):
+ return False
+ return shutil.which(AGENTCOOKIE_BIN) is not None
+
+
+def _config_path(config: Optional[Dict[str, Any]] = None) -> Path:
+ """Path to agentcookie's config file (AGENTCOOKIE_CONFIG override wins)."""
+ override = ""
+ if config is not None:
+ override = config.get("AGENTCOOKIE_CONFIG") or ""
+ override = override or os.environ.get("AGENTCOOKIE_CONFIG") or ""
+ return Path(override) if override else _DEFAULT_CONFIG_PATH
+
+
+def role(config: Optional[Dict[str, Any]] = None) -> Optional[str]:
+ """agentcookie's configured role ("source"/"sink"), or None.
+
+ Reads and parses the config FILE only — no subprocess, so it is safe on a
+ MacBook that must not spawn agentcookie. Any failure (missing file, bad
+ JSON, no ``role`` key, wrong type) returns None. "parse failure = not sink".
+ """
+ path = _config_path(config)
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ if not isinstance(data, dict):
+ return None
+ raw = data.get("role")
+ return raw.strip().lower() if isinstance(raw, str) else None
+
+
+def role_is_sink(config: Optional[Dict[str, Any]] = None) -> bool:
+ """True only when agentcookie's configured role parses as ``sink``."""
+ return role(config) == "sink"
+
+
+def _consume_cookie_list(items: List[Any], names: tuple, found: Dict[str, str]) -> None:
+ """Collect ``name -> value`` for wanted cookie names from a cookie list."""
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ name = item.get("name")
+ value = item.get("value")
+ if name in names and isinstance(value, str) and value and name not in found:
+ found[name] = value
+
+
+def _pair_from_json(data: Any, names: tuple) -> Dict[str, str]:
+ """Extract wanted cookies from agentcookie JSON, tolerant of its shape.
+
+ Accepts a list of ``{"name","value",...}`` objects, a ``{"cookies": [...]}``
+ wrapper, or a flat ``{name: value}`` / ``{name: {"value": ...}}`` mapping.
+ """
+ found: Dict[str, str] = {}
+ if isinstance(data, list):
+ _consume_cookie_list(data, names, found)
+ elif isinstance(data, dict):
+ cookies = data.get("cookies")
+ if isinstance(cookies, list):
+ _consume_cookie_list(cookies, names, found)
+ else:
+ for name in names:
+ raw = data.get(name)
+ if isinstance(raw, str) and raw:
+ found[name] = raw
+ elif isinstance(raw, dict) and isinstance(raw.get("value"), str) and raw["value"]:
+ found[name] = raw["value"]
+ return found
+
+
+def read_x_cookies(config: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, str]]:
+ """Return the complete X cookie pair from agentcookie, or None.
+
+ Returns ``{"auth_token": ..., "ct0": ...}`` only when BOTH cookies are
+ present (no half-pair). Any failure (binary absent, disabled, non-zero
+ exit, unparsable JSON, timeout, incomplete pair) returns None so the
+ caller falls through to the next cookie source. Never raises.
+ """
+ if is_disabled(config):
+ return None
+ binary = shutil.which(AGENTCOOKIE_BIN)
+ if binary is None:
+ return None
+
+ try:
+ result = subprocess.run(
+ [binary, "cookies", "--domain", X_COOKIE_DOMAIN, "--json"],
+ capture_output=True,
+ text=True,
+ timeout=_TIMEOUT_SECONDS,
+ )
+ except subprocess.TimeoutExpired:
+ _log(f"timed out after {_TIMEOUT_SECONDS}s; skipping")
+ return None
+ except OSError as exc:
+ _log(f"could not run agentcookie: {type(exc).__name__}")
+ return None
+
+ if result.returncode != 0:
+ # stderr may carry a reason; do not echo it (it can contain values).
+ _log(f"exited {result.returncode}; skipping")
+ return None
+
+ output = (result.stdout or "").strip()
+ if not output:
+ return None
+ try:
+ data = json.loads(output)
+ except json.JSONDecodeError:
+ _log("returned non-JSON output; skipping")
+ return None
+
+ found = _pair_from_json(data, X_COOKIE_NAMES)
+ if all(name in found for name in X_COOKIE_NAMES):
+ _log(f"delivered a complete X cookie pair ({len(found)} of {len(X_COOKIE_NAMES)} names)")
+ return {name: found[name] for name in X_COOKIE_NAMES}
+ if found:
+ _log(f"returned an incomplete pair ({sorted(found)}); ignoring per no-half-pair rule")
+ return None
diff --git a/skills/last30days/scripts/lib/chrome_cdp.py b/skills/last30days/scripts/lib/chrome_cdp.py
new file mode 100644
index 00000000..0bdaf78b
--- /dev/null
+++ b/skills/last30days/scripts/lib/chrome_cdp.py
@@ -0,0 +1,443 @@
+"""Live Chrome cookie reader over the DevTools Protocol (CDP).
+
+An EXTRA-host cookie lookup for the bird backend: when a Chrome/Chromium
+instance is running with a remote-debugging endpoint and the user is signed
+into x.com in it, that live session holds the ``auth_token`` + ``ct0`` cookies
+bird needs — even on Linux, where the on-disk cookie store cannot be decrypted
+here. This module talks to that endpoint and pulls the pair via
+``Network.getAllCookies``.
+
+Deliberate constraints (see docs/plans/2026-08-31 X plan):
+
+* **Extras only.** The engine only calls this on extra hosts (Linux, Mac mini,
+ Darwin agentcookie sink, or ``AGENTCOOKIE=on``); the gating lives in
+ ``env.x_extras_enabled``. On a plain MacBook this is never called, so no
+ socket is opened (AE8).
+* **No port scan.** Endpoint resolution is: ``BROWSER_CDP_URL`` if set, else
+ port ``18800`` if it answers as Chrome, else ``9222`` + the X display number.
+ No 9222..9232 sweep. ``18800`` is NOT box-chrome's built-in default (that is
+ ``9222`` + the display number); it is the last30days extras NUX convention —
+ the agent launches the throwaway login Chrome with
+ ``SAND_CHROME_REMOTE_DEBUG_PORT=18800`` (see SKILL.md), so a leftover daily
+ profile on ``9222``+display is not mistaken for the login session. If ``18800``
+ answers with no complete pair we fall through; if it answers with a stale or
+ wrong pair, pin ``BROWSER_CDP_URL`` after the NUX rather than scanning.
+* **Require a Chrome page target.** ``/json/version`` must report a Chrome /
+ Chromium browser (a Node inspector is rejected) and ``/json`` must expose a
+ ``page`` target.
+* **``FROM_BROWSER=off`` skips CDP.**
+* Stdlib only: a tiny RFC 6455 websocket client, no third-party dependency.
+* Cookie **values are never logged** — only counts and endpoints.
+* First complete pair wins: both ``auth_token`` and ``ct0`` must be present.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import socket
+import struct
+import urllib.request
+from typing import Any, Dict, List, Optional
+
+from . import log
+
+X_COOKIE_NAMES = ("auth_token", "ct0")
+_BASE_DEBUG_PORT = 9222
+# The last30days extras NUX convention port: the agent launches the throwaway
+# login Chrome with SAND_CHROME_REMOTE_DEBUG_PORT=18800 so this lookup finds it.
+# NOT box-chrome's built-in default (which is 9222 + the X display number).
+_BOX_CHROME_PORT = 18800
+
+_HTTP_TIMEOUT = 1.5 # /json and /json/version fetches
+_WS_TIMEOUT = 3.0 # websocket exchange
+
+
+def _log(msg: str) -> None:
+ log.source_log("chrome-cdp", msg, tty_only=False)
+
+
+def _display_number() -> Optional[int]:
+ """Parse the X display number from ``$DISPLAY`` (e.g. ``:99`` -> 99)."""
+ disp = os.environ.get("DISPLAY") or ""
+ match = re.search(r":(\d+)", disp)
+ if not match:
+ return None
+ try:
+ return int(match.group(1))
+ except ValueError:
+ return None
+
+
+def _normalize_base(url: str) -> str:
+ """Return an ``http://host:port`` base for a user-supplied endpoint."""
+ url = url.strip().rstrip("/")
+ if url.startswith(("http://", "https://", "ws://", "wss://")):
+ return url
+ return f"http://{url}"
+
+
+def candidate_endpoints(config: Optional[Dict[str, Any]] = None) -> List[str]:
+ """Debug endpoints to try, most-specific first (no port scan).
+
+ Order: an explicit ``BROWSER_CDP_URL`` (used exclusively when set), else the
+ last30days extras NUX port ``18800`` (where the agent launches the throwaway
+ login Chrome via ``SAND_CHROME_REMOTE_DEBUG_PORT=18800``), then ``9222`` +
+ the X display number (box-chrome's own built-in default). ``18800`` is tried
+ first but read_x_cookies falls through when it yields no complete pair, so a
+ logged-out Chrome there never shadows a logged-in daily profile.
+ """
+ explicit = ""
+ if config is not None:
+ explicit = (config.get("BROWSER_CDP_URL") or "").strip()
+ explicit = explicit or (os.environ.get("BROWSER_CDP_URL") or "").strip()
+ if explicit:
+ return [_normalize_base(explicit)]
+
+ endpoints = [f"http://127.0.0.1:{_BOX_CHROME_PORT}"]
+ display = _display_number()
+ endpoints.append(f"http://127.0.0.1:{_BASE_DEBUG_PORT + (display or 0)}")
+ return endpoints
+
+
+def _http_get_json(url: str) -> Optional[Any]:
+ """GET ``url`` and parse JSON, or None (unreachable/non-JSON)."""
+ try:
+ with urllib.request.urlopen(url, timeout=_HTTP_TIMEOUT) as resp:
+ body = resp.read()
+ except (OSError, ValueError):
+ return None
+ try:
+ return json.loads(body)
+ except (json.JSONDecodeError, TypeError):
+ return None
+
+
+def _is_chrome_endpoint(base: str) -> bool:
+ """True when ``base``/json/version reports a Chrome/Chromium browser.
+
+ Rejects a Node ``--inspect`` endpoint (whose ``Browser`` is ``node.js/...``)
+ so we never mistake an inspector for a browser.
+ """
+ version = _http_get_json(f"{base}/json/version")
+ if not isinstance(version, dict):
+ return False
+ browser = str(version.get("Browser") or "").lower()
+ return "chrome" in browser or "chromium" in browser
+
+
+def _page_ws_url(base: str) -> Optional[str]:
+ """Find a Chrome PAGE target's webSocketDebuggerUrl on ``base``."""
+ targets = _http_get_json(f"{base}/json")
+ if not isinstance(targets, list):
+ return None
+ for target in targets:
+ if not isinstance(target, dict):
+ continue
+ if target.get("type") != "page":
+ continue
+ ws_url = target.get("webSocketDebuggerUrl")
+ if isinstance(ws_url, str) and ws_url.startswith("ws://"):
+ return ws_url
+ return None
+
+
+class _WSConn:
+ """Minimal RFC 6455 websocket client (text frames only) over a TCP socket."""
+
+ def __init__(self, sock: socket.socket) -> None:
+ self._sock = sock
+ self._buf = b""
+
+ def _fill(self, n: int) -> Optional[bytes]:
+ while len(self._buf) < n:
+ try:
+ chunk = self._sock.recv(65536)
+ except OSError:
+ return None
+ if not chunk:
+ return None
+ self._buf += chunk
+ out, self._buf = self._buf[:n], self._buf[n:]
+ return out
+
+ @classmethod
+ def connect(cls, ws_url: str, timeout: float) -> Optional["_WSConn"]:
+ # Plaintext ws:// only. A wss:// URL would need real TLS
+ # (ssl.wrap_socket); this client does not, so refuse it rather than
+ # open a plaintext socket to a TLS endpoint. Defense in depth alongside
+ # the scheme gate in read_x_cookies.
+ match = re.match(r"ws://([^:/]+):(\d+)(/.*)$", ws_url)
+ if not match:
+ return None
+ host, port, path = match.group(1), int(match.group(2)), match.group(3)
+ try:
+ sock = socket.create_connection((host, port), timeout=timeout)
+ except OSError:
+ return None
+ sock.settimeout(timeout)
+ key = base64.b64encode(os.urandom(16)).decode("ascii")
+ handshake = (
+ f"GET {path} HTTP/1.1\r\n"
+ f"Host: {host}:{port}\r\n"
+ "Upgrade: websocket\r\n"
+ "Connection: Upgrade\r\n"
+ f"Sec-WebSocket-Key: {key}\r\n"
+ "Sec-WebSocket-Version: 13\r\n\r\n"
+ )
+ try:
+ sock.sendall(handshake.encode("ascii"))
+ except OSError:
+ sock.close()
+ return None
+ conn = cls(sock)
+ header = conn._read_http_headers()
+ if header is None or b" 101 " not in header.split(b"\r\n", 1)[0]:
+ sock.close()
+ return None
+ return conn
+
+ def _read_http_headers(self) -> Optional[bytes]:
+ while b"\r\n\r\n" not in self._buf:
+ try:
+ chunk = self._sock.recv(65536)
+ except OSError:
+ return None
+ if not chunk:
+ return None
+ self._buf += chunk
+ head, _, rest = self._buf.partition(b"\r\n\r\n")
+ self._buf = rest # any bytes after the header belong to the frame stream
+ return head
+
+ def send_text(self, payload: bytes) -> bool:
+ header = bytearray([0x81]) # FIN + text opcode
+ mask = os.urandom(4)
+ length = len(payload)
+ if length < 126:
+ header.append(0x80 | length)
+ elif length < 65536:
+ header.append(0x80 | 126)
+ header += struct.pack(">H", length)
+ else:
+ header.append(0x80 | 127)
+ header += struct.pack(">Q", length)
+ header += mask
+ masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
+ try:
+ self._sock.sendall(bytes(header) + masked)
+ return True
+ except OSError:
+ return False
+
+ def recv_message(self) -> Optional[bytes]:
+ """Read one (possibly fragmented) data message; skip control frames."""
+ message = b""
+ while True:
+ first = self._fill(2)
+ if first is None:
+ return None
+ fin = first[0] & 0x80
+ opcode = first[0] & 0x0F
+ length = first[1] & 0x7F
+ masked = first[1] & 0x80
+ if length == 126:
+ ext = self._fill(2)
+ if ext is None:
+ return None
+ length = struct.unpack(">H", ext)[0]
+ elif length == 127:
+ ext = self._fill(8)
+ if ext is None:
+ return None
+ length = struct.unpack(">Q", ext)[0]
+ mask = self._fill(4) if masked else b""
+ payload = self._fill(length) if length else b""
+ if length and payload is None:
+ return None
+ if masked and payload:
+ payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
+ if opcode == 0x8: # close
+ return None
+ if opcode in (0x9, 0xA): # ping / pong — ignore
+ continue
+ message += payload or b""
+ if fin:
+ return message
+
+ def close(self) -> None:
+ try:
+ self._sock.close()
+ except OSError:
+ pass
+
+
+def _get_all_cookies(ws_url: str) -> Optional[List[Dict[str, Any]]]:
+ """Run Network.enable then Network.getAllCookies over one CDP websocket."""
+ conn = _WSConn.connect(ws_url, _WS_TIMEOUT)
+ if conn is None:
+ return None
+ try:
+ if not conn.send_text(json.dumps({"id": 1, "method": "Network.enable"}).encode("utf-8")):
+ return None
+ if not conn.send_text(json.dumps({"id": 2, "method": "Network.getAllCookies"}).encode("utf-8")):
+ return None
+ # Read frames until the id=2 response arrives (skipping enable's ack and
+ # any Network.* events the browser pushes after enable).
+ for _ in range(200):
+ raw = conn.recv_message()
+ if raw is None:
+ return None
+ try:
+ msg = json.loads(raw)
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ continue
+ if isinstance(msg, dict) and msg.get("id") == 2:
+ result = msg.get("result")
+ if isinstance(result, dict) and isinstance(result.get("cookies"), list):
+ return result["cookies"]
+ return None
+ return None
+ finally:
+ conn.close()
+
+
+# Registrable X hosts we accept cookies from, in preference order. Matched
+# EXACTLY after stripping a single leading dot (never endswith), so a lookalike
+# like ``notx.com`` is not treated as x.com and cannot contribute a cookie.
+_ALLOWED_X_HOSTS = ("x.com", "twitter.com")
+
+
+def _canonical_partition(raw: Any) -> Optional[str]:
+ """Canonicalize a CDP ``partitionKey`` to a hashable scope tag.
+
+ CDP may send ``partitionKey`` as a string, as an object
+ (``{"topLevelSite": ..., "hasCrossSiteAncestor": ...}``), or omit it for an
+ unpartitioned cookie. Returns None for "unpartitioned" (so all unpartitioned
+ cookies share one scope) and a stable string otherwise (so a partitioned
+ cookie never shares a scope with an unpartitioned one, nor with a different
+ partition).
+ """
+ if raw is None:
+ return None
+ if isinstance(raw, str):
+ return raw.strip() or None
+ if isinstance(raw, dict):
+ try:
+ return json.dumps(raw, sort_keys=True, separators=(",", ":"))
+ except (TypeError, ValueError):
+ return repr(sorted((str(k), str(v)) for k, v in raw.items()))
+ return str(raw)
+
+
+def _pair_from_cookies(cookies: List[Dict[str, Any]]) -> Dict[str, str]:
+ """Extract a complete X cookie pair from ONE cookie scope.
+
+ ``auth_token`` and ``ct0`` are only a usable pair when they share the SAME
+ cookie scope — same registrable host AND same ``path`` AND same partition.
+ Chrome can hold duplicate names across scopes (different ``path`` or
+ ``partitionKey``), so pairing across the whole host jar could hand Bird a
+ token from one session scope and a ct0 from another, and a valid login would
+ look unauthorized. We therefore group by the full scope key
+ ``(host, path, partition)`` and only ever pair WITHIN one scope.
+
+ Host is matched EXACTLY against ``_ALLOWED_X_HOSTS`` after stripping one
+ leading dot (never ``endswith``, so ``notx.com`` never counts). Missing
+ ``path`` is treated as ``/``; ``partitionKey`` is canonicalized so
+ unpartitioned cookies stay together. Preference order for the returned pair:
+ host ``x.com`` before ``twitter.com``; unpartitioned before partitioned;
+ path ``/`` before other paths. A scope with only one of the two cookies is
+ skipped so a later complete scope still wins. When no scope has a complete
+ pair, a single scope's partial is returned for the caller's incomplete-pair
+ log — never a cross-scope mix.
+ """
+ # scopes[host][(path, partition)] -> {name: value}
+ scopes: Dict[str, Dict[tuple, Dict[str, str]]] = {host: {} for host in _ALLOWED_X_HOSTS}
+ for cookie in cookies:
+ if not isinstance(cookie, dict):
+ continue
+ name = cookie.get("name")
+ value = cookie.get("value")
+ if name not in X_COOKIE_NAMES or not (isinstance(value, str) and value):
+ continue
+ host = str(cookie.get("domain") or "").lstrip(".").lower()
+ if host not in scopes:
+ continue
+ path = cookie.get("path")
+ if not isinstance(path, str) or not path:
+ path = "/"
+ scope_key = (path, _canonical_partition(cookie.get("partitionKey")))
+ jar = scopes[host].setdefault(scope_key, {})
+ # First value WITHIN this scope only — never across scopes.
+ jar.setdefault(name, value)
+
+ def _scope_rank(item: tuple) -> tuple:
+ (path, partition), _jar = item
+ # unpartitioned (None) before partitioned; path "/" before others.
+ return (partition is not None, path != "/", path)
+
+ for host in _ALLOWED_X_HOSTS:
+ for _key, jar in sorted(scopes[host].items(), key=_scope_rank):
+ if all(name in jar for name in X_COOKIE_NAMES):
+ return {name: jar[name] for name in X_COOKIE_NAMES}
+
+ for host in _ALLOWED_X_HOSTS:
+ for _key, jar in sorted(scopes[host].items(), key=_scope_rank):
+ if jar:
+ return dict(jar)
+ return {}
+
+
+def read_x_cookies(config: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, str]]:
+ """Return the complete X cookie pair from a live Chrome session, or None.
+
+ Resolves the debug endpoint (BROWSER_CDP_URL, else 18800 if Chrome, else
+ 9222+$DISPLAY), requires a Chrome page target, and calls
+ ``Network.getAllCookies``. Returns ``{"auth_token", "ct0"}`` only when BOTH
+ cookies are found (no half-pair). ``FROM_BROWSER=off`` returns None without
+ opening a socket. Any failure returns None so the caller falls through.
+ Never raises.
+
+ Host gating (extras-only) lives in the caller (``env.x_extras_enabled``);
+ on a plain MacBook this function is never invoked, so no socket is opened.
+ """
+ from_browser = ""
+ if config is not None:
+ from_browser = (config.get("FROM_BROWSER") or "").strip().lower()
+ if from_browser == "off":
+ return None
+
+ for base in candidate_endpoints(config):
+ # TLS CDP is NOT supported: the websocket client speaks plaintext only,
+ # so a wss:// endpoint (or an https:// base, which would yield a wss://
+ # page URL) must fail closed rather than be downgraded to a plaintext
+ # connect. Local Chrome CDP is ws://http://.
+ scheme = base.split("://", 1)[0].lower() if "://" in base else "http"
+ if scheme in ("wss", "https"):
+ _log(f"refusing TLS CDP endpoint {base!r}: only ws://http:// is supported (no TLS)")
+ continue
+ # ws:// endpoints (rare, explicit) connect directly; http bases are
+ # validated as Chrome and asked for a page target.
+ if base.startswith("ws://"):
+ ws_url = base
+ else:
+ if not _is_chrome_endpoint(base):
+ continue
+ ws_url = _page_ws_url(base)
+ if not ws_url:
+ continue
+ cookies = _get_all_cookies(ws_url)
+ if not cookies:
+ continue
+ found = _pair_from_cookies(cookies)
+ if all(name in found for name in X_COOKIE_NAMES):
+ _log(f"read a complete X cookie pair from a live Chrome session at {base}")
+ return {name: found[name] for name in X_COOKIE_NAMES}
+ if found:
+ _log(
+ f"live Chrome at {base} had an incomplete pair "
+ f"({sorted(found)}); ignoring per no-half-pair rule"
+ )
+ return None
diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.py
index 6527bfb7..74308621 100644
--- a/skills/last30days/scripts/lib/env.py
+++ b/skills/last30days/scripts/lib/env.py
@@ -558,6 +558,14 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:
# automated contexts (cron/CI/eval). Read by trustpilot._harvest_allowed.
('LAST30DAYS_TRUSTPILOT_NO_BROWSER', None),
('FROM_BROWSER', None),
+ # agentcookie sidecar: soft-dep X cookie source (lib/agentcookie.py),
+ # active only on extra hosts (Linux / Mac mini / Darwin sink) or when
+ # set to "on". "off" disables the sidecar reader.
+ ('AGENTCOOKIE', None),
+ # Explicit Chrome DevTools endpoint for the extra-host CDP cookie
+ # lookup (lib/chrome_cdp.py), e.g. http://127.0.0.1:18800. Preferred
+ # over the 18800 / 9222+$DISPLAY defaults when set.
+ ('BROWSER_CDP_URL', None),
('LAST30DAYS_TRUST_PROJECT_CONFIG', None),
('SETUP_COMPLETE', None),
('INCLUDE_SOURCES', ''),
@@ -645,15 +653,152 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:
config['_BROWSER_COOKIE_BROWSERS'] = cookie_extraction_browsers(config)
if policy.browser_cookies == "read":
- browser_creds = extract_browser_credentials(config)
- for key, value in browser_creds.items():
- if not config.get(key):
- config[key] = value
- config[f"_{key}_SOURCE"] = "browser"
+ _discover_and_apply_x_credentials(config)
return config
+# ---------------------------------------------------------------------------
+# Extra-host X cookie discovery (Linux, Mac mini, Darwin agentcookie sink)
+# ---------------------------------------------------------------------------
+
+
+def _mac_model() -> str:
+ """Darwin hardware model via ``sysctl -n hw.model``, or "" otherwise.
+
+ Returns "" on non-Darwin and on any sysctl failure (missing binary,
+ non-zero exit, timeout) — the caller treats "" as "not a Mac mini", i.e. a
+ MacBook, which is the conservative default (no extra cookie lookups).
+ """
+ import platform
+ if platform.system() != "Darwin":
+ return ""
+ import subprocess
+ try:
+ out = subprocess.run(
+ ["sysctl", "-n", "hw.model"],
+ capture_output=True, text=True, timeout=3,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return ""
+ if out.returncode != 0:
+ return ""
+ return (out.stdout or "").strip()
+
+
+def _is_mac_mini() -> bool:
+ """True on a Darwin Mac mini (``hw.model`` prefix ``Macmini``).
+
+ sysctl failure yields "" -> False, so an unreadable model is treated as a
+ MacBook (no extras), per the plan.
+ """
+ return _mac_model().startswith("Macmini")
+
+
+def x_extras_enabled(config: dict[str, Any]) -> bool:
+ """Whether the two EXTRA bird cookie lookups (agentcookie sidecar, live
+ Chrome CDP) apply on this host.
+
+ Extras apply when ANY of:
+ * ``AGENTCOOKIE=on`` — explicit per-host opt-in (works on a MacBook too);
+ * platform is Linux;
+ * a Darwin Mac mini (``hw.model`` prefix ``Macmini``);
+ * a Darwin agentcookie **sink** role (parse failure = not sink).
+
+ A plain MacBook (Darwin, source/unknown role, no opt-in) stays on the
+ mainline path — no agentcookie subprocess, no CDP socket. The host is NEVER
+ inferred from the home directory, PATH, or ``HERMES_AGENT``/``OPENCLAW_CLI``
+ env: only the signals above.
+ """
+ import platform
+ raw = (config.get("AGENTCOOKIE") or read_secret_env("AGENTCOOKIE") or "").strip().lower()
+ if raw == "on":
+ return True
+ system = platform.system()
+ if system == "Linux":
+ return True
+ if system == "Darwin":
+ if _is_mac_mini():
+ return True
+ from . import agentcookie
+ return agentcookie.role_is_sink(config)
+ return False
+
+
+def _apply_x_pair(config: dict[str, Any], auth_token: str, ct0: str, source: str) -> None:
+ """Apply a COMPLETE X cookie pair from one source, labeling its origin.
+
+ Atomic on purpose (both keys from the same source) so a half-pair from one
+ source is never merged with a half-pair from another. Never written to the
+ ``.env``; values are never logged.
+ """
+ config["AUTH_TOKEN"] = auth_token
+ config["CT0"] = ct0
+ config["_AUTH_TOKEN_SOURCE"] = source
+ config["_CT0_SOURCE"] = source
+
+
+def _apply_browser_extract(config: dict[str, Any]) -> None:
+ """Run the mainline in-process browser cookie extractor (unchanged from
+ main): fills X (when a browser is opted in via FROM_BROWSER) and non-X
+ cookie domains like truthsocial. Missing keys only; source label ``browser``."""
+ browser_creds = extract_browser_credentials(config)
+ for key, value in browser_creds.items():
+ if not config.get(key):
+ config[key] = value
+ config[f"_{key}_SOURCE"] = "browser"
+
+
+def _discover_and_apply_x_credentials(config: dict[str, Any]) -> None:
+ """Fill AUTH_TOKEN/CT0 for the bird backend, first COMPLETE pair wins.
+
+ Mainline (every host): the in-process browser extractor, gated by
+ FROM_BROWSER exactly as on ``main``. EXTRA lookups (agentcookie sidecar,
+ then live Chrome CDP) run ONLY on extra hosts (``x_extras_enabled``), so a
+ MacBook with FROM_BROWSER unset/off does no agentcookie spawn and no CDP
+ socket. Probe order:
+
+ 1. an explicit env AUTH_TOKEN+CT0 already present — never overwritten;
+ 2. agentcookie sidecar (extras only);
+ 3. live Chrome CDP (extras only);
+ 4. the mainline browser extract (all hosts; X only when FROM_BROWSER
+ lists a browser).
+
+ On a Mac mini that has already opted into browser reads (FROM_BROWSER set),
+ the native extract runs BEFORE CDP (R19) — a local Keychain read beats a
+ debug-port scrape. Never persists cookies; values are never logged.
+ """
+ from . import agentcookie, chrome_cdp
+
+ def have_pair() -> bool:
+ return bool(config.get("AUTH_TOKEN") and config.get("CT0"))
+
+ extras = x_extras_enabled(config)
+
+ # (2) agentcookie sidecar — extras only, complete pair only.
+ if extras and not have_pair():
+ pair = agentcookie.read_x_cookies(config)
+ if pair:
+ _apply_x_pair(config, pair["auth_token"], pair["ct0"], "agentcookie")
+
+ # Mac mini + browser opted in: native extract before CDP (R19).
+ mini_extract_first = (
+ extras and _is_mac_mini() and bool(cookie_extraction_browsers(config))
+ )
+ if mini_extract_first and not have_pair():
+ _apply_browser_extract(config)
+
+ # (3) live Chrome CDP — extras only, complete pair only.
+ if extras and not have_pair():
+ pair = chrome_cdp.read_x_cookies(config)
+ if pair:
+ _apply_x_pair(config, pair["auth_token"], pair["ct0"], "chrome cdp")
+
+ # (4) mainline browser extract (unless already run above for the mini case).
+ if not mini_extract_first:
+ _apply_browser_extract(config)
+
+
# ---------------------------------------------------------------------------
# Browser cookie extraction
# ---------------------------------------------------------------------------
@@ -923,10 +1068,14 @@ def x_pending_browser_auth(config: dict[str, Any], local_only: bool = False) ->
dropped from ``available_sources`` even though a normal run would extract the
same cookies and authenticate X fine. This predicate reports that
"available pending browser auth" state without reading a single cookie — it
- keys only on the already-resolved browser list (``cookie_extraction_browsers``
- derives it from ``FROM_BROWSER`` alone, no secrets), bird being installed, and
- X having a cookie-domain mapping. Side-effect free, so the safe-inspection
- contract of diagnose/preflight is preserved.
+ keys only on the resolved browser list (``cookie_extraction_browsers``
+ derives it from ``FROM_BROWSER`` alone, no secrets) OR — on extra hosts
+ only (``x_extras_enabled``) — the agentcookie sidecar being on PATH (a plain
+ ``which`` lookup), bird being installed, and X having a cookie-domain
+ mapping. A plain MacBook must NOT predict bird from an agentcookie binary on
+ PATH (R18), so the sidecar leg is gated behind ``x_extras_enabled``.
+ Side-effect free, so the safe-inspection contract of diagnose/preflight is
+ preserved.
Returns False whenever X is already available outright (static AUTH_TOKEN/CT0,
or xAI/xurl/xquik backend), and in ``read`` mode (a real run has already
@@ -943,10 +1092,20 @@ def x_pending_browser_auth(config: dict[str, Any], local_only: bool = False) ->
return False
if 'x' not in COOKIE_DOMAINS:
return False
- if not cookie_extraction_browsers(config):
- return False
from . import bird_x
- return bird_x.is_bird_installed()
+ if not bird_x.is_bird_installed():
+ return False
+ # A FROM_BROWSER browser is a run-time cookie source on any host.
+ if cookie_extraction_browsers(config):
+ return True
+ # The agentcookie sidecar is a run-time cookie source ONLY on extra hosts
+ # (Linux / Mac mini / Darwin sink / AGENTCOOKIE=on). Gating this keeps a
+ # plain MacBook from predicting bird off a stray agentcookie binary (R18).
+ if x_extras_enabled(config):
+ from . import agentcookie
+ if agentcookie.is_available(config):
+ return True
+ return False
def is_ytdlp_available() -> bool:
diff --git a/tests/test_agentcookie.py b/tests/test_agentcookie.py
new file mode 100644
index 00000000..f0f3e8fa
--- /dev/null
+++ b/tests/test_agentcookie.py
@@ -0,0 +1,147 @@
+"""U1/U5: agentcookie sidecar reader (lib/agentcookie.py).
+
+Subprocess is always mocked; only obvious dummy cookie values are used
+(test-auth-token / test-ct0). Enforces the soft-dep, AGENTCOOKIE=off,
+FROM_BROWSER-independence, complete-pair, and no-value-logging contracts.
+"""
+
+import json
+import subprocess
+from unittest import mock
+
+from lib import agentcookie
+
+_DUMMY = {"auth_token": "test-auth-token", "ct0": "test-ct0"}
+
+
+def _run_ok(stdout):
+ return mock.Mock(returncode=0, stdout=stdout, stderr="")
+
+
+def test_off_disables_without_subprocess():
+ with (
+ mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
+ mock.patch("subprocess.run", side_effect=AssertionError("should not run")),
+ ):
+ assert agentcookie.read_x_cookies({"AGENTCOOKIE": "off"}) is None
+ assert agentcookie.is_disabled({"AGENTCOOKIE": "off"}) is True
+ assert agentcookie.is_available({"AGENTCOOKIE": "off"}) is False
+
+
+def test_absent_binary_is_soft_skip():
+ with mock.patch("shutil.which", return_value=None):
+ assert agentcookie.read_x_cookies({}) is None
+ assert agentcookie.is_available({}) is False
+
+
+def test_complete_pair_from_list_json():
+ payload = json.dumps([
+ {"name": "auth_token", "value": "test-auth-token", "domain": ".x.com"},
+ {"name": "ct0", "value": "test-ct0", "domain": ".x.com"},
+ {"name": "guest_id", "value": "irrelevant", "domain": ".x.com"},
+ ])
+ with (
+ mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
+ mock.patch("subprocess.run", return_value=_run_ok(payload)) as run,
+ ):
+ result = agentcookie.read_x_cookies({})
+ assert result == _DUMMY
+ # It asks for the x.com domain in JSON.
+ args = run.call_args[0][0]
+ assert "--domain" in args and ".x.com" in args and "--json" in args
+
+
+def test_complete_pair_from_cookies_wrapper():
+ payload = json.dumps({"cookies": [
+ {"name": "auth_token", "value": "test-auth-token"},
+ {"name": "ct0", "value": "test-ct0"},
+ ]})
+ with (
+ mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
+ mock.patch("subprocess.run", return_value=_run_ok(payload)),
+ ):
+ assert agentcookie.read_x_cookies({}) == _DUMMY
+
+
+def test_complete_pair_from_flat_mapping():
+ payload = json.dumps({"auth_token": "test-auth-token", "ct0": "test-ct0"})
+ with (
+ mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
+ mock.patch("subprocess.run", return_value=_run_ok(payload)),
+ ):
+ assert agentcookie.read_x_cookies({}) == _DUMMY
+
+
+def test_half_pair_is_rejected():
+ payload = json.dumps([{"name": "auth_token", "value": "test-auth-token"}])
+ with (
+ mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
+ mock.patch("subprocess.run", return_value=_run_ok(payload)),
+ ):
+ assert agentcookie.read_x_cookies({}) is None
+
+
+def test_nonzero_exit_is_none():
+ with (
+ mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
+ mock.patch("subprocess.run", return_value=mock.Mock(returncode=2, stdout="", stderr="nope")),
+ ):
+ assert agentcookie.read_x_cookies({}) is None
+
+
+def test_timeout_is_none():
+ with (
+ mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
+ mock.patch("subprocess.run", side_effect=subprocess.TimeoutExpired("agentcookie", 10)),
+ ):
+ assert agentcookie.read_x_cookies({}) is None
+
+
+def test_non_json_is_none():
+ with (
+ mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
+ mock.patch("subprocess.run", return_value=_run_ok("<html>blocked</html>")),
+ ):
+ assert agentcookie.read_x_cookies({}) is None
+
+
+def test_never_logs_cookie_values():
+ payload = json.dumps({"auth_token": "test-auth-token", "ct0": "test-ct0"})
+ logged = []
+ with (
+ mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
+ mock.patch("subprocess.run", return_value=_run_ok(payload)),
+ mock.patch("lib.agentcookie.log.source_log", lambda src, msg, **k: logged.append(msg)),
+ ):
+ agentcookie.read_x_cookies({})
+ joined = "\n".join(logged)
+ assert "test-auth-token" not in joined
+ assert "test-ct0" not in joined
+
+
+# --- role detection (subprocess-free config read) --------------------------
+
+
+def test_role_is_sink_reads_config_file(tmp_path):
+ cfg = tmp_path / "config.json"
+ cfg.write_text(json.dumps({"role": "sink"}))
+ config = {"AGENTCOOKIE_CONFIG": str(cfg)}
+ # No subprocess is spawned to classify the role.
+ with mock.patch("subprocess.run", side_effect=AssertionError("no subprocess for role")):
+ assert agentcookie.role(config) == "sink"
+ assert agentcookie.role_is_sink(config) is True
+
+
+def test_role_source_is_not_sink(tmp_path):
+ cfg = tmp_path / "config.json"
+ cfg.write_text(json.dumps({"role": "source"}))
+ config = {"AGENTCOOKIE_CONFIG": str(cfg)}
+ assert agentcookie.role_is_sink(config) is False
+
+
+def test_role_missing_or_unparsable_is_not_sink(tmp_path):
+ missing = {"AGENTCOOKIE_CONFIG": str(tmp_path / "nope.json")}
+ assert agentcookie.role_is_sink(missing) is False
+ bad = tmp_path / "bad.json"
+ bad.write_text("not json {")
+ assert agentcookie.role_is_sink({"AGENTCOOKIE_CONFIG": str(bad)}) is False
diff --git a/tests/test_box_chrome_login.py b/tests/test_box_chrome_login.py
new file mode 100644
index 00000000..c2e05701
--- /dev/null
+++ b/tests/test_box_chrome_login.py
@@ -0,0 +1,148 @@
+"""Extras-host box-chrome X login helper (skills/.../scripts/box_chrome_login.py).
+
+Locks: a MacBook never gets a launch command and never spawns box-chrome (even
+with --exec); an extras host with box-chrome on PATH documents the last30days
+extras port 18800; and the SKILL.md recipe is present in the Auto flow and the
+repair section with the MacBook-skip and no-.env-cookie rules. No cookie values
+are ever produced (the helper reads none).
+"""
+
+from pathlib import Path
+from unittest import mock
+
+import box_chrome_login as bcl
+from lib import chrome_cdp
+
+REPO = Path(__file__).resolve().parent.parent
+SKILL = REPO / "skills" / "last30days" / "SKILL.md"
+
+
+def test_extras_port_is_18800_and_matches_chrome_cdp():
+ assert bcl.EXTRAS_CDP_PORT == 18800
+ assert bcl.EXTRAS_CDP_PORT == chrome_cdp._BOX_CHROME_PORT
+
+
+def test_macbook_gets_no_launch_command():
+ with mock.patch("lib.env.x_extras_enabled", return_value=False):
+ recipe = bcl.build_recipe({})
+ assert recipe["applies"] is False
+ assert recipe["command"] is None
+ assert recipe["env"] is None
+ rendered = bcl.render_recipe(recipe).lower()
+ assert "not an extras host" in rendered or "no box-chrome login" in rendered.replace("-", "")
+
+
+def test_extras_with_box_chrome_documents_18800():
+ with (
+ mock.patch("lib.env.x_extras_enabled", return_value=True),
+ mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
+ ):
+ recipe = bcl.build_recipe({})
+ assert recipe["applies"] is True
+ assert recipe["command"] == ["/usr/local/bin/box-chrome", "--new-window", "https://x.com/login"]
+ assert recipe["env"]["SAND_CHROME_REMOTE_DEBUG_PORT"] == "18800"
+ assert recipe["env"]["CHROME_USER_DATA_DIR"]
+ rendered = bcl.render_recipe(recipe)
+ assert "SAND_CHROME_REMOTE_DEBUG_PORT=18800" in rendered
+ assert "box-chrome" in rendered
+ # The pin guidance names the endpoint but never a cookie value.
+ assert "BROWSER_CDP_URL=http://127.0.0.1:18800" in rendered
+
+
+def test_helper_launches_via_box_chrome_without_custom_class():
+ """Launch through the box-chrome wrapper (it sets --class=box-chrome); never
+ a raw chrome with a custom --class, which is what failed live."""
+ with (
+ mock.patch("lib.env.x_extras_enabled", return_value=True),
+ mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
+ ):
+ recipe = bcl.build_recipe({})
+ assert recipe["command"][0].endswith("box-chrome")
+ assert not any(arg.startswith("--class") for arg in recipe["command"])
+ assert "google-chrome" not in " ".join(recipe["command"])
+
+
+def test_extras_without_box_chrome_guides_pin():
+ with (
+ mock.patch("lib.env.x_extras_enabled", return_value=True),
+ mock.patch("shutil.which", return_value=None),
+ ):
+ recipe = bcl.build_recipe({})
+ assert recipe["applies"] is True
+ assert recipe["command"] is None
+ assert "BROWSER_CDP_URL" in recipe["note"]
+
+
+def test_main_exec_never_spawns_on_macbook():
+ with (
+ mock.patch("lib.env.x_extras_enabled", return_value=False),
+ mock.patch.object(bcl.env, "get_config", return_value={}),
+ mock.patch("subprocess.Popen", side_effect=AssertionError("no spawn on MacBook")),
+ ):
+ assert bcl.main(["--exec"]) == 0
+
+
+def test_main_exec_missing_box_chrome_does_not_spawn():
+ with (
+ mock.patch("lib.env.x_extras_enabled", return_value=True),
+ mock.patch("shutil.which", return_value=None),
+ mock.patch.object(bcl.env, "get_config", return_value={}),
+ mock.patch("subprocess.Popen", side_effect=AssertionError("no spawn without box-chrome")),
+ ):
+ assert bcl.main(["--exec"]) == 0
+
+
+def test_main_exec_spawns_box_chrome_on_extras_with_18800():
+ popen = mock.MagicMock()
+ with (
+ mock.patch("lib.env.x_extras_enabled", return_value=True),
+ mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
+ mock.patch.object(bcl.env, "get_config", return_value={}),
+ mock.patch("os.makedirs"),
+ mock.patch("subprocess.Popen", popen),
+ ):
+ rc = bcl.main(["--exec"])
+ assert rc == 0
+ popen.assert_called_once()
+ args, kwargs = popen.call_args
+ assert args[0] == ["/usr/local/bin/box-chrome", "--new-window", "https://x.com/login"]
+ assert kwargs["env"]["SAND_CHROME_REMOTE_DEBUG_PORT"] == "18800"
+
+
+def test_default_run_prints_but_does_not_spawn():
+ with (
+ mock.patch("lib.env.x_extras_enabled", return_value=True),
+ mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
+ mock.patch.object(bcl.env, "get_config", return_value={}),
+ mock.patch("subprocess.Popen", side_effect=AssertionError("no --exec = no spawn")),
+ ):
+ assert bcl.main([]) == 0
+
+
+# --- SKILL.md recipe contract ---------------------------------------------
+
+
+def _skill():
+ return SKILL.read_text()
+
+
+def test_skill_md_references_helper_in_flows_and_repair():
+ text = _skill()
+ # Auto Modal flow, Non-Modal Prose flow, and the repair section each point
+ # at the helper.
+ assert text.count("box_chrome_login.py") >= 3
+
+
+def test_skill_md_documents_18800_launch_and_macbook_skip():
+ text = _skill()
+ assert "SAND_CHROME_REMOTE_DEBUG_PORT=18800" in text
+ assert "X on Linux / Grok Bot / Mac mini" in text
+ # MacBook must be told to skip the box-chrome path.
+ assert "MacBook SKIPS" in text or "MacBook does NOT" in text
+
+
+def test_skill_md_pins_browser_cdp_url_not_raw_cookies():
+ text = _skill()
+ assert "BROWSER_CDP_URL=http://127.0.0.1:18800" in text
+ # The recipe must forbid writing the raw cookie pair to .env.
+ assert "never `AUTH_TOKEN`/`CT0`" in text or "Do NOT write `AUTH_TOKEN`" in text
diff --git a/tests/test_chrome_cdp.py b/tests/test_chrome_cdp.py
new file mode 100644
index 00000000..0b151133
--- /dev/null
+++ b/tests/test_chrome_cdp.py
@@ -0,0 +1,380 @@
+"""U6/U5: live Chrome cookie reader over CDP (lib/chrome_cdp.py).
+
+Unit tests for port derivation and cookie filtering, plus an end-to-end test
+against a FAKE CDP server (stdlib socket) that exercises the real HTTP target
+lookup and the hand-rolled RFC 6455 websocket client. Only obvious dummy
+cookie values are used (test-auth-token / test-ct0).
+"""
+
+import base64
+import hashlib
+import json
+import socket
+import struct
+import threading
+from unittest import mock
+
+from lib import chrome_cdp
+
+_WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
+
+
+# --- Unit: endpoint derivation + cookie filtering --------------------------
+
+
+def test_display_number_parsing():
+ with mock.patch.dict("os.environ", {"DISPLAY": ":99"}, clear=False):
+ assert chrome_cdp._display_number() == 99
+ with mock.patch.dict("os.environ", {"DISPLAY": "localhost:10.0"}, clear=False):
+ assert chrome_cdp._display_number() == 10
+
+
+def test_candidate_endpoints_default_order_18800_then_display():
+ with mock.patch.dict("os.environ", {"DISPLAY": ":7"}, clear=False):
+ # No BROWSER_CDP_URL in env for this check.
+ with mock.patch.dict("os.environ", {"BROWSER_CDP_URL": ""}, clear=False):
+ endpoints = chrome_cdp.candidate_endpoints({})
+ assert endpoints == ["http://127.0.0.1:18800", "http://127.0.0.1:9229"]
+
+
+def test_candidate_endpoints_prefers_browser_cdp_url_exclusively():
+ endpoints = chrome_cdp.candidate_endpoints({"BROWSER_CDP_URL": "http://127.0.0.1:5555"})
+ assert endpoints == ["http://127.0.0.1:5555"]
+
+
+def test_pair_from_cookies_requires_both_and_filters_domain():
+ cookies = [
+ {"name": "auth_token", "value": "test-auth-token", "domain": ".x.com"},
+ {"name": "ct0", "value": "test-ct0", "domain": ".x.com"},
+ {"name": "auth_token", "value": "someone-else", "domain": ".example.com"},
+ ]
+ pair = chrome_cdp._pair_from_cookies(cookies)
+ assert pair == {"auth_token": "test-auth-token", "ct0": "test-ct0"}
+
+
+def test_pair_from_cookies_half_pair_is_incomplete():
+ cookies = [{"name": "auth_token", "value": "test-auth-token", "domain": ".x.com"}]
+ pair = chrome_cdp._pair_from_cookies(cookies)
+ assert "ct0" not in pair
+
+
+def test_pair_from_cookies_never_mixes_hosts():
+ """A lookalike host (notx.com) must not contribute; the later same-host
+ x.com pair wins, never a cross-host mix (P1)."""
+ cookies = [
+ {"name": "auth_token", "value": "notx-token", "domain": "notx.com"},
+ {"name": "ct0", "value": "test-ct0", "domain": ".x.com"},
+ {"name": "auth_token", "value": "test-auth-token", "domain": ".x.com"},
+ ]
+ pair = chrome_cdp._pair_from_cookies(cookies)
+ assert pair == {"auth_token": "test-auth-token", "ct0": "test-ct0"}
+ assert pair["auth_token"] != "notx-token"
+
+
+def test_pair_from_cookies_prefers_x_com_over_twitter():
+ cookies = [
+ {"name": "auth_token", "value": "tw-token", "domain": ".twitter.com"},
+ {"name": "ct0", "value": "tw-ct0", "domain": ".twitter.com"},
+ {"name": "auth_token", "value": "test-auth-token", "domain": ".x.com"},
+ {"name": "ct0", "value": "test-ct0", "domain": ".x.com"},
+ ]
+ pair = chrome_cdp._pair_from_cookies(cookies)
+ assert pair == {"auth_token": "test-auth-token", "ct0": "test-ct0"}
+
+
+def test_pair_from_cookies_skips_partial_host_for_complete_one():
+ """x.com has only auth_token; twitter.com has both -> the twitter pair wins
+ (same-host), never x.com's auth_token merged with twitter's ct0."""
+ cookies = [
+ {"name": "auth_token", "value": "x-only-token", "domain": ".x.com"},
+ {"name": "auth_token", "value": "test-auth-token", "domain": ".twitter.com"},
+ {"name": "ct0", "value": "test-ct0", "domain": ".twitter.com"},
+ ]
+ pair = chrome_cdp._pair_from_cookies(cookies)
+ assert pair == {"auth_token": "test-auth-token", "ct0": "test-ct0"}
+
+
+def test_pair_from_cookies_does_not_mix_across_paths():
+ """auth_token on path / and ct0 on path /i are different scopes -> no pair."""
+ cookies = [
+ {"name": "auth_token", "value": "test-auth-token", "domain": ".x.com", "path": "/"},
+ {"name": "ct0", "value": "test-ct0", "domain": ".x.com", "path": "/i"},
+ ]
+ pair = chrome_cdp._pair_from_cookies(cookies)
+ assert set(pair) != {"auth_token", "ct0"} # never a cross-path pair
+
+
+def test_pair_from_cookies_does_not_mix_across_partitions():
+ """Same host+path but different partitionKey -> different scopes -> no pair."""
+ cookies = [
+ {"name": "auth_token", "value": "test-auth-token", "domain": ".x.com",
+ "path": "/", "partitionKey": "https://a.example"},
+ {"name": "ct0", "value": "test-ct0", "domain": ".x.com",
+ "path": "/", "partitionKey": "https://b.example"},
+ ]
+ pair = chrome_cdp._pair_from_cookies(cookies)
+ assert set(pair) != {"auth_token", "ct0"}
+
+
+def test_pair_from_cookies_prefers_unpartitioned_root_path_scope():
+ """A complete unpartitioned path-/ pair wins over later partitioned or
+ other-path complete pairs (object-form partitionKey must not crash)."""
+ cookies = [
+ # other-path complete pair
+ {"name": "auth_token", "value": "ipath-token", "domain": ".x.com", "path": "/i"},
+ {"name": "ct0", "value": "ipath-ct0", "domain": ".x.com", "path": "/i"},
+ # partitioned complete pair (object form)
+ {"name": "auth_token", "value": "part-token", "domain": ".x.com", "path": "/",
+ "partitionKey": {"topLevelSite": "https://x.com", "hasCrossSiteAncestor": True}},
+ {"name": "ct0", "value": "part-ct0", "domain": ".x.com", "path": "/",
+ "partitionKey": {"topLevelSite": "https://x.com", "hasCrossSiteAncestor": True}},
+ # the winner: unpartitioned, path /
+ {"name": "auth_token", "value": "test-auth-token", "domain": ".x.com", "path": "/"},
+ {"name": "ct0", "value": "test-ct0", "domain": ".x.com", "path": "/"},
+ ]
+ pair = chrome_cdp._pair_from_cookies(cookies)
+ assert pair == {"auth_token": "test-auth-token", "ct0": "test-ct0"}
+
+
+def test_from_browser_off_skips_endpoints():
+ with mock.patch.object(
+ chrome_cdp, "candidate_endpoints", side_effect=AssertionError("must not probe")
+ ):
+ assert chrome_cdp.read_x_cookies({"FROM_BROWSER": "off"}) is None
+
+
+# --- Fake CDP server (stdlib socket) ---------------------------------------
+
+
+class _FakeCDPServer:
+ """Minimal Chrome-debug endpoint: GET /json/version + /json + a CDP websocket."""
+
+ def __init__(self, cookies, browser="Chrome/120.0.0.0"):
+ self._cookies = cookies
+ self._browser = browser
+ self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ self._sock.bind(("127.0.0.1", 0))
+ self._sock.listen(8)
+ self._sock.settimeout(5)
+ self.port = self._sock.getsockname()[1]
+ self._stop = False
+ self._thread = threading.Thread(target=self._serve, daemon=True)
+
+ def __enter__(self):
+ self._thread.start()
+ return self
+
+ def __exit__(self, *exc):
+ self._stop = True
+ try:
+ self._sock.close()
+ except OSError:
+ pass
+
+ def _serve(self):
+ while not self._stop:
+ try:
+ conn, _ = self._sock.accept()
+ except OSError:
+ return
+ try:
+ self._handle(conn)
+ except OSError:
+ pass
+ finally:
+ try:
+ conn.close()
+ except OSError:
+ pass
+
+ def _read_request(self, conn):
+ buf = b""
+ conn.settimeout(5)
+ while b"\r\n\r\n" not in buf:
+ chunk = conn.recv(4096)
+ if not chunk:
+ return None, b""
+ buf += chunk
+ head, _, rest = buf.partition(b"\r\n\r\n")
+ return head.decode("latin-1"), rest
+
+ def _handle(self, conn):
+ head, rest = self._read_request(conn)
+ if head is None:
+ return # bare reachability probe (connect then close)
+ if "upgrade: websocket" in head.lower():
+ self._handle_ws(conn, head, rest)
+ return
+ request_line = head.splitlines()[0]
+ if request_line.startswith("GET /json/version"):
+ body = json.dumps({"Browser": self._browser, "Protocol-Version": "1.3"}).encode()
+ self._send_http_json(conn, body)
+ elif request_line.startswith("GET /json"):
+ body = json.dumps([
+ {
+ "type": "page",
+ "webSocketDebuggerUrl": f"ws://127.0.0.1:{self.port}/devtools/page/ABC",
+ }
+ ]).encode()
+ self._send_http_json(conn, body)
+
+ def _send_http_json(self, conn, body):
+ conn.sendall(
+ b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
+ b"Content-Length: " + str(len(body)).encode()
+ + b"\r\nConnection: close\r\n\r\n" + body
+ )
+
+ def _handle_ws(self, conn, head, rest):
+ key = ""
+ for line in head.splitlines():
+ if line.lower().startswith("sec-websocket-key:"):
+ key = line.split(":", 1)[1].strip()
+ accept = base64.b64encode(
+ hashlib.sha1((key + _WS_GUID).encode()).digest()
+ ).decode()
+ conn.sendall(
+ b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n"
+ b"Connection: Upgrade\r\nSec-WebSocket-Accept: "
+ + accept.encode() + b"\r\n\r\n"
+ )
+ buf = bytearray(rest)
+ # Respond to each client command until getAllCookies has been answered.
+ for _ in range(4):
+ msg, buf = self._read_frame(conn, buf)
+ if msg is None:
+ return
+ try:
+ data = json.loads(msg)
+ except json.JSONDecodeError:
+ continue
+ mid = data.get("id")
+ if data.get("method") == "Network.getAllCookies":
+ self._send_frame(conn, json.dumps(
+ {"id": mid, "result": {"cookies": self._cookies}}
+ ))
+ return
+ self._send_frame(conn, json.dumps({"id": mid, "result": {}}))
+
+ def _read_frame(self, conn, buf):
+ def need(n):
+ nonlocal buf
+ while len(buf) < n:
+ chunk = conn.recv(4096)
+ if not chunk:
+ return False
+ buf += chunk
+ return True
+
+ if not need(2):
+ return None, buf
+ length = buf[1] & 0x7F
+ masked = buf[1] & 0x80
+ idx = 2
+ if length == 126:
+ if not need(4):
+ return None, buf
+ length = struct.unpack(">H", buf[2:4])[0]
+ idx = 4
+ elif length == 127:
+ if not need(10):
+ return None, buf
+ length = struct.unpack(">Q", buf[2:10])[0]
+ idx = 10
+ mask = b""
+ if masked:
+ if not need(idx + 4):
+ return None, buf
+ mask = bytes(buf[idx:idx + 4])
+ idx += 4
+ if not need(idx + length):
+ return None, buf
+ payload = bytes(buf[idx:idx + length])
+ if masked:
+ payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
+ del buf[:idx + length]
+ return payload.decode("utf-8"), buf
+
+ def _send_frame(self, conn, text):
+ payload = text.encode("utf-8")
+ header = bytearray([0x81]) # FIN + text, unmasked (server)
+ length = len(payload)
+ if length < 126:
+ header.append(length)
+ elif length < 65536:
+ header.append(126)
+ header += struct.pack(">H", length)
+ else:
+ header.append(127)
+ header += struct.pack(">Q", length)
+ conn.sendall(bytes(header) + payload)
+
+
+def test_read_x_cookies_via_fake_cdp():
+ cookies = [
+ {"name": "auth_token", "value": "test-auth-token", "domain": ".x.com"},
+ {"name": "ct0", "value": "test-ct0", "domain": ".x.com"},
+ {"name": "guest_id", "value": "irrelevant", "domain": ".x.com"},
+ ]
+ with _FakeCDPServer(cookies) as server:
+ config = {"BROWSER_CDP_URL": f"http://127.0.0.1:{server.port}"}
+ result = chrome_cdp.read_x_cookies(config)
+ assert result == {"auth_token": "test-auth-token", "ct0": "test-ct0"}
+
+
+def test_read_x_cookies_incomplete_pair_returns_none():
+ cookies = [{"name": "auth_token", "value": "test-auth-token", "domain": ".x.com"}]
+ with _FakeCDPServer(cookies) as server:
+ config = {"BROWSER_CDP_URL": f"http://127.0.0.1:{server.port}"}
+ result = chrome_cdp.read_x_cookies(config)
+ assert result is None
+
+
+def test_read_x_cookies_rejects_node_inspector():
+ """A Node --inspect endpoint (Browser=node.js/...) is not Chrome -> None."""
+ cookies = [
+ {"name": "auth_token", "value": "test-auth-token", "domain": ".x.com"},
+ {"name": "ct0", "value": "test-ct0", "domain": ".x.com"},
+ ]
+ with _FakeCDPServer(cookies, browser="node.js/v20.0.0") as server:
+ config = {"BROWSER_CDP_URL": f"http://127.0.0.1:{server.port}"}
+ result = chrome_cdp.read_x_cookies(config)
+ assert result is None
+
+
+def test_read_x_cookies_from_browser_off_opens_no_socket():
+ with mock.patch("socket.create_connection", side_effect=AssertionError("no socket")):
+ with mock.patch("urllib.request.urlopen", side_effect=AssertionError("no http")):
+ assert chrome_cdp.read_x_cookies({"FROM_BROWSER": "off"}) is None
+
+
+def test_read_x_cookies_rejects_wss_without_plaintext_connect():
+ """wss:// (TLS) is refused; the plaintext client must not connect (P2)."""
+ with (
+ mock.patch("socket.create_connection", side_effect=AssertionError("no plaintext connect to TLS endpoint")),
+ mock.patch("urllib.request.urlopen", side_effect=AssertionError("no http probe of TLS endpoint")),
+ ):
+ assert chrome_cdp.read_x_cookies({"BROWSER_CDP_URL": "wss://127.0.0.1:9222/devtools/page/ABC"}) is None
+
+
+def test_read_x_cookies_rejects_https_base_without_connect():
+ """An https:// debug base (would yield wss) is refused without probing."""
+ with (
+ mock.patch("socket.create_connection", side_effect=AssertionError("no connect")),
+ mock.patch("urllib.request.urlopen", side_effect=AssertionError("no TLS http probe")),
+ ):
+ assert chrome_cdp.read_x_cookies({"BROWSER_CDP_URL": "https://127.0.0.1:18800"}) is None
+
+
+def test_wsconn_connect_refuses_wss():
+ assert chrome_cdp._WSConn.connect("wss://127.0.0.1:9222/devtools/page/ABC", 1.0) is None
+
+
+def test_read_x_cookies_no_reachable_endpoint_returns_none():
+ # A port with nothing listening: connection refused, returns None.
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ dead_port = s.getsockname()[1]
+ config = {"BROWSER_CDP_URL": f"http://127.0.0.1:{dead_port}"}
+ assert chrome_cdp.read_x_cookies(config) is None
diff --git a/tests/test_x_extras_gating.py b/tests/test_x_extras_gating.py
new file mode 100644
index 00000000..e4070c91
--- /dev/null
+++ b/tests/test_x_extras_gating.py
@@ -0,0 +1,193 @@
+"""Host-gated X cookie extras: MacBook stays on main; Linux/Mac mini/sink get
+the two extra bird cookie lookups (agentcookie sidecar, live Chrome CDP).
+
+Locks the acceptance examples:
+ * AE7 Linux, no bird cookies, grok AUTH_OK + XAI_API_KEY -> xai (not grok).
+ * AE8 MacBook (hw.model MacBookPro), FROM_BROWSER unset, agentcookie on PATH,
+ grok AUTH_OK + XAI_API_KEY -> xai; NO agentcookie subprocess, NO CDP.
+ * AE10 Darwin Mac mini (hw.model Macmini9,1), agentcookie sidecar pair,
+ FROM_BROWSER unset -> bird from agentcookie. ~/.hermes never flips a
+ MacBook into extras.
+
+Only obvious dummy cookie values are used (test-auth-token / test-ct0).
+"""
+
+from unittest import mock
+
+from lib import env
+
+_PAIR = {"auth_token": "test-auth-token", "ct0": "test-ct0"}
+
+
+def _no_extract():
+ """Patch the mainline browser extractor to a no-op (FROM_BROWSER unset)."""
+ return mock.patch.object(env, "extract_browser_credentials", return_value={})
+
+
+def _stub_backends():
+ """Local-only backend probes so get_x_source touches no network.
+
+ Returns an ExitStack already entered; use as ``with _stub_backends():``.
+ """
+ import contextlib
+ stack = contextlib.ExitStack()
+ stack.enter_context(mock.patch("lib.bird_x.is_bird_installed", return_value=True))
+ stack.enter_context(mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None))
+ stack.enter_context(mock.patch("lib.xurl_x.is_available", return_value=False))
+ return stack
+
+
+# --- x_extras_enabled matrix ----------------------------------------------
+
+
+def test_extras_enabled_on_linux():
+ with mock.patch("platform.system", return_value="Linux"):
+ assert env.x_extras_enabled({}) is True
+
+
+def test_extras_enabled_on_mac_mini():
+ with (
+ mock.patch("platform.system", return_value="Darwin"),
+ mock.patch.object(env, "_mac_model", return_value="Macmini9,1"),
+ ):
+ assert env.x_extras_enabled({}) is True
+
+
+def test_extras_enabled_on_darwin_sink_role():
+ with (
+ mock.patch("platform.system", return_value="Darwin"),
+ mock.patch.object(env, "_mac_model", return_value="MacBookPro18,2"),
+ mock.patch("lib.agentcookie.role_is_sink", return_value=True),
+ ):
+ assert env.x_extras_enabled({}) is True
+
+
+def test_extras_disabled_on_plain_macbook():
+ with (
+ mock.patch("platform.system", return_value="Darwin"),
+ mock.patch.object(env, "_mac_model", return_value="MacBookPro18,2"),
+ mock.patch("lib.agentcookie.role_is_sink", return_value=False),
+ ):
+ assert env.x_extras_enabled({}) is False
+
+
+def test_agentcookie_on_opts_in_a_macbook():
+ with (
+ mock.patch("platform.system", return_value="Darwin"),
+ mock.patch.object(env, "_mac_model", return_value="MacBookPro18,2"),
+ ):
+ assert env.x_extras_enabled({"AGENTCOOKIE": "on"}) is True
+
+
+def test_agentcookie_off_keeps_macbook_off():
+ with (
+ mock.patch("platform.system", return_value="Darwin"),
+ mock.patch.object(env, "_mac_model", return_value="MacBookPro18,2"),
+ mock.patch("lib.agentcookie.role_is_sink", return_value=False),
+ ):
+ assert env.x_extras_enabled({"AGENTCOOKIE": "off"}) is False
+
+
+def test_windows_has_no_extras():
+ with mock.patch("platform.system", return_value="Windows"):
+ assert env.x_extras_enabled({}) is False
+
+
+def test_hermes_home_and_env_never_flip_extras():
+ """~/.hermes / HERMES_AGENT / OPENCLAW_CLI must NOT enable extras (AE10)."""
+ with (
+ mock.patch("platform.system", return_value="Darwin"),
+ mock.patch.object(env, "_mac_model", return_value="MacBookPro18,2"),
+ mock.patch("lib.agentcookie.role_is_sink", return_value=False),
+ mock.patch.dict("os.environ", {"HERMES_AGENT": "1", "OPENCLAW_CLI": "1"}, clear=False),
+ ):
+ assert env.x_extras_enabled({}) is False
+
+
+# --- AE8: MacBook is untouched --------------------------------------------
+
+
+def test_ae8_macbook_no_extras_no_subprocess_and_picks_xai():
+ config = {"XAI_API_KEY": "dummy-xai-key"} # no AUTH_TOKEN/CT0, FROM_BROWSER unset
+ with (
+ mock.patch("platform.system", return_value="Darwin"),
+ mock.patch.object(env, "_mac_model", return_value="MacBookPro18,2"),
+ mock.patch("lib.agentcookie.role_is_sink", return_value=False),
+ # These MUST NOT run on a MacBook:
+ mock.patch("lib.agentcookie.read_x_cookies", side_effect=AssertionError("no agentcookie subprocess on MacBook")),
+ mock.patch("lib.chrome_cdp.read_x_cookies", side_effect=AssertionError("no CDP on MacBook")),
+ _no_extract(),
+ ):
+ env._discover_and_apply_x_credentials(config)
+ assert config.get("AUTH_TOKEN") is None
+ assert config.get("CT0") is None
+ # Backend selection: leftover grok + XAI_API_KEY must use xai (grok pin-only).
+ with mock.patch("lib.grok_x.has_stored_auth", return_value=True), _stub_backends():
+ assert env.get_x_source(config) == "xai"
+
+
+# --- AE10: Mac mini gets the sidecar pair ---------------------------------
+
+
+def test_ae10_mac_mini_reads_bird_pair_from_agentcookie():
+ config = {} # FROM_BROWSER unset
+ with (
+ mock.patch("platform.system", return_value="Darwin"),
+ mock.patch.object(env, "_mac_model", return_value="Macmini9,1"),
+ mock.patch("lib.agentcookie.read_x_cookies", return_value=dict(_PAIR)),
+ mock.patch("lib.chrome_cdp.read_x_cookies", side_effect=AssertionError("agentcookie already won")),
+ _no_extract(),
+ ):
+ env._discover_and_apply_x_credentials(config)
+ assert config["AUTH_TOKEN"] == "test-auth-token"
+ assert config["CT0"] == "test-ct0"
+ assert config["_AUTH_TOKEN_SOURCE"] == "agentcookie"
+ with mock.patch("lib.grok_x.has_stored_auth", return_value=False), _stub_backends():
+ assert env.get_x_source(config) == "bird"
+
+
+# --- AE7: Linux picks xai over a stale grok --------------------------------
+
+
+def test_ae7_linux_no_cookies_grok_and_xai_picks_xai():
+ config = {"XAI_API_KEY": "dummy-xai-key"}
+ with (
+ mock.patch("platform.system", return_value="Linux"),
+ mock.patch("lib.agentcookie.read_x_cookies", return_value=None),
+ mock.patch("lib.chrome_cdp.read_x_cookies", return_value=None),
+ _no_extract(),
+ ):
+ env._discover_and_apply_x_credentials(config)
+ assert config.get("AUTH_TOKEN") is None
+ assert config.get("CT0") is None
+ with mock.patch("lib.grok_x.has_stored_auth", return_value=True), _stub_backends():
+ assert env.get_x_source(config) == "xai"
+
+
+# --- discovery ordering / no-overwrite ------------------------------------
+
+
+def test_explicit_env_pair_not_overwritten_on_extra_host():
+ config = {"AUTH_TOKEN": "explicit-token", "CT0": "explicit-ct0"}
+ with (
+ mock.patch("platform.system", return_value="Linux"),
+ mock.patch("lib.agentcookie.read_x_cookies", side_effect=AssertionError("no discovery with complete env pair")),
+ mock.patch("lib.chrome_cdp.read_x_cookies", side_effect=AssertionError("no discovery with complete env pair")),
+ _no_extract(),
+ ):
+ env._discover_and_apply_x_credentials(config)
+ assert config["AUTH_TOKEN"] == "explicit-token"
+ assert config["CT0"] == "explicit-ct0"
+
+
+def test_cdp_used_when_agentcookie_empty_on_extra_host():
+ config = {}
+ with (
+ mock.patch("platform.system", return_value="Linux"),
+ mock.patch("lib.agentcookie.read_x_cookies", return_value=None),
+ mock.patch("lib.chrome_cdp.read_x_cookies", return_value=dict(_PAIR)),
+ _no_extract(),
+ ):
+ env._discover_and_apply_x_credentials(config)
+ assert config["AUTH_TOKEN"] == "test-auth-token"
+ assert config["_AUTH_TOKEN_SOURCE"] == "chrome cdp"