deck-browser: drive playwright-cli instead of a hand-rolled CDP client

Playwright documents connectOverCDP with a ws:// endpoint, and
playwright-cli attach --cdp=ws://127.0.0.1:9222/devtools/browser works against
the Deck's chrome://inspect toggle. That makes the 270-line stdlib CDP client
redundant: the wrapper is now 130 lines of bash that opens the tunnel, attaches
once and maps tabs/text/html/shot onto playwright-cli (plus a 'cli' passthrough
so agents can reach console, network and the rest without new code).
This commit is contained in:
Ziad Arafat committed 2026-12-02 12:20:43 -07:00
1 parent d306474f95
commit 8999c687f9
2 files changed
+162 -291

No files matched your search

+130 -261
View File
@@ -1,273 +1,142 @@
#!/usr/bin/env python3
"""deck-browser — read (do not drive) the Chrome running on the Steam Deck.
#!/usr/bin/env bash
# deck-browser — read the Chrome running on the Steam Deck from arceus.
#
# Chrome on the Deck exposes a CDP WebSocket at 127.0.0.1:9222/devtools/browser once
# "Allow remote debugging for this browser instance" is ticked at
# chrome://inspect/#remote-debugging. Playwright attaches to a ws:// endpoint directly
# (connectOverCDP accepts one), so this is a thin wrapper that opens the SSH tunnel and
# drives `playwright-cli` — not a protocol client of its own.
#
# deck-browser tabs list tabs (index, title, url)
# deck-browser text --match linkedin innerText of a tab
# deck-browser html --index 3 outerHTML
# deck-browser shot --out /tmp/x.png screenshot (default /tmp/deck-shot-<ts>.png)
# deck-browser status user agent of the attached browser
# deck-browser cli tab-select 2 pass any playwright-cli command through
#
# Options: --index N | --match SUBSTR (default: current tab), --limit CHARS (default 8000).
# Read-only by intent: no click/type/navigate helper exists here, because driving an
# authenticated session is what gets accounts restricted.
#
# Env: DECK_HOST (deck), DECK_CDP_PORT (9222), DECK_SESSION (deck)
set -euo pipefail
Chrome on the Deck exposes a CDP WebSocket at 127.0.0.1:9222/devtools/browser once
"Allow remote debugging for this browser instance" is ticked at
chrome://inspect/#remote-debugging. This tool opens an SSH tunnel to that loopback
port and talks CDP directly, using only the Python standard library.
HOST=${DECK_HOST:-deck}
PORT=${DECK_CDP_PORT:-9222}
SESSION=${DECK_SESSION:-deck}
WS="ws://127.0.0.1:${PORT}/devtools/browser"
Deliberately read-only: list tabs, dump text/HTML, take a screenshot. There is no
click, type or navigate command, because driving a logged-in session is what gets
accounts restricted. `--unsafe-eval` exists for one-off inspection and is opt-in.
die() { echo "deck-browser: $*" >&2; exit 1; }
Usage:
deck-browser tabs
deck-browser text [--index N | --match SUBSTR] [--limit CHARS]
deck-browser html [--index N | --match SUBSTR] [--limit CHARS]
deck-browser shot [--index N | --match SUBSTR] [--out FILE.png]
deck-browser status
port_open() { (exec 3<>"/dev/tcp/127.0.0.1/${PORT}") 2>/dev/null; }
Environment: DECK_HOST (default "deck"), DECK_CDP_PORT (default 9222).
"""
ensure_tunnel() {
port_open && return 0
ssh -o BatchMode=yes -o ExitOnForwardFailure=yes -f -N \
-L "${PORT}:127.0.0.1:${PORT}" "$HOST" \
|| die "cannot open tunnel to ${HOST} — is the Deck awake?"
for _ in $(seq 1 25); do port_open && return 0; sleep 0.2; done
die "no CDP endpoint on 127.0.0.1:${PORT}.
On the Deck: chrome://inspect/#remote-debugging → tick
'Allow remote debugging for this browser instance', then retry."
}
from __future__ import annotations
ensure_attached() {
ensure_tunnel
playwright-cli -s="$SESSION" eval '1' >/dev/null 2>&1 && return 0
playwright-cli -s="$SESSION" attach --cdp="$WS" >/dev/null 2>&1 \
|| die "playwright-cli could not attach to ${WS} (is the box still ticked?)"
}
import argparse
import atexit
import base64
import json
import os
import socket
import struct
import subprocess
import sys
import time
import urllib.parse
# tab_list → "INDEX<TAB>TITLE<TAB>URL"
tab_list() {
playwright-cli -s="$SESSION" tab-list 2>/dev/null \
| sed -n 's/^- \([0-9]\+\): \(.*\)\[\(.*\)\](\(.*\))$/\1\t\3\t\4/p'
}
HOST = os.environ.get("DECK_HOST", "deck")
PORT = int(os.environ.get("DECK_CDP_PORT", "9222"))
LOCAL = "127.0.0.1"
resolve_tab() { # args: --index N | --match SUBSTR
local idx="" match=""
while [ $# -gt 0 ]; do
case "$1" in
--index) idx=${2:-}; shift 2 ;;
--match) match=${2:-}; shift 2 ;;
*) shift ;;
esac
done
if [ -n "$match" ]; then
idx=$(tab_list | awk -F'\t' -v m="$(echo "$match" | tr 'A-Z' 'a-z')" \
'tolower($0) ~ m {print $1; exit}')
[ -n "$idx" ] || die "no tab matching '$match'"
fi
printf '%s' "${idx:-}"
}
# --- minimal WebSocket client -------------------------------------------------
class WS:
"""Just enough of RFC 6455 to speak CDP: text frames, fragmentation, ping."""
def __init__(self, host: str, port: int, path: str, timeout: float = 10.0):
self.sock = socket.create_connection((host, port), timeout=timeout)
self.sock.settimeout(timeout)
key = base64.b64encode(os.urandom(16)).decode()
req = (
f"GET {path} HTTP/1.1\r\nHost: {host}:{port}\r\nUpgrade: websocket\r\n"
f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\n"
"Sec-WebSocket-Version: 13\r\n\r\n"
)
self.sock.sendall(req.encode())
resp = self._read_until(b"\r\n\r\n")
if b"101" not in resp.split(b"\r\n")[0]:
head = resp.split(b"\r\n")[0].decode(errors="replace")
raise RuntimeError(f"CDP handshake failed: {head}")
def _read_until(self, marker: bytes) -> bytes:
buf = b""
while marker not in buf:
chunk = self.sock.recv(4096)
if not chunk:
raise RuntimeError("connection closed during handshake")
buf += chunk
return buf
def _recv_exact(self, n: int) -> bytes:
buf = b""
while len(buf) < n:
chunk = self.sock.recv(n - len(buf))
if not chunk:
raise RuntimeError("connection closed")
buf += chunk
return buf
def send(self, text: str) -> None:
payload = text.encode()
header = bytearray([0x81]) # FIN + text
n = len(payload)
if n < 126:
header.append(0x80 | n)
elif n < (1 << 16):
header.append(0x80 | 126)
header += struct.pack(">H", n)
else:
header.append(0x80 | 127)
header += struct.pack(">Q", n)
mask = os.urandom(4)
header += mask
masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
self.sock.sendall(bytes(header) + masked)
def recv(self) -> str:
chunks = []
while True:
b0, b1 = self._recv_exact(2)
opcode = b0 & 0x0F
fin = b0 & 0x80
n = b1 & 0x7F
if n == 126:
n = struct.unpack(">H", self._recv_exact(2))[0]
elif n == 127:
n = struct.unpack(">Q", self._recv_exact(8))[0]
if b1 & 0x80: # server frames should not be masked
self._recv_exact(4)
payload = self._recv_exact(n)
if opcode == 0x9: # ping -> pong
self.sock.sendall(bytes([0x8A, 0x80]) + os.urandom(4))
continue
if opcode == 0x8: # close
raise RuntimeError("server closed the CDP socket")
chunks.append(payload)
if fin:
return b"".join(chunks).decode(errors="replace")
def close(self) -> None:
# json_unquote turns playwright's JSON-quoted eval result into plain text.
json_unquote() {
python3 -c '
import json, sys
for line in sys.stdin.read().splitlines():
line = line.strip()
if line[:1] == chr(34) and line[-1:] == chr(34):
try:
self.sock.close()
except OSError:
sys.stdout.write(json.loads(line)); break
except Exception:
pass
'
}
OPTS=()
for a in "$@"; do :; done
CMD=${1:-}; shift || true
# --- CDP helper ---------------------------------------------------------------
class CDP:
def __init__(self, ws: WS):
self.ws = ws
self._id = 0
def call(self, method: str, params: dict | None = None, session: str | None = None):
self._id += 1
msg = {"id": self._id, "method": method, "params": params or {}}
if session:
msg["sessionId"] = session
self.ws.send(json.dumps(msg))
while True:
reply = json.loads(self.ws.recv())
if reply.get("id") != self._id:
continue # event, not our reply
if "error" in reply:
raise RuntimeError(f"{method}: {reply['error'].get('message')}")
return reply.get("result", {})
def pages(self):
targets = self.call("Target.getTargets")["targetInfos"]
return [t for t in targets if t.get("type") == "page"]
def attach(self, target_id: str) -> str:
return self.call("Target.attachToTarget", {"targetId": target_id, "flatten": True})["sessionId"]
# --- tunnel -------------------------------------------------------------------
_tunnel: subprocess.Popen | None = None
def _port_open() -> bool:
with socket.socket() as s:
s.settimeout(0.6)
return s.connect_ex((LOCAL, PORT)) == 0
def ensure_tunnel() -> None:
global _tunnel
if _port_open():
return
_tunnel = subprocess.Popen(
["ssh", "-o", "BatchMode=yes", "-o", "ExitOnForwardFailure=yes",
"-N", "-L", f"{PORT}:{LOCAL}:{PORT}", HOST],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
atexit.register(lambda: _tunnel and _tunnel.terminate())
for _ in range(25):
if _port_open():
return
time.sleep(0.2)
sys.exit(
f"deck-browser: no CDP endpoint on {LOCAL}:{PORT}.\n"
" On the Deck, open chrome://inspect/#remote-debugging and tick\n"
" 'Allow remote debugging for this browser instance'.\n"
f" Then check: ssh {HOST} 'ss -ltn | grep {PORT}'"
)
def connect() -> CDP:
ensure_tunnel()
return CDP(WS(LOCAL, PORT, "/devtools/browser"))
def pick(pages, index: int | None, match: str | None):
if match:
for p in pages:
hay = f"{p.get('url','')} {p.get('title','')}".lower()
if match.lower() in hay:
return p
sys.exit(f"deck-browser: no tab matching {match!r}")
if index is None:
index = 0
if index >= len(pages):
sys.exit(f"deck-browser: index {index} out of range (have {len(pages)})")
return pages[index]
def main() -> int:
ap = argparse.ArgumentParser(prog="deck-browser", description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="cmd", required=True)
for name in ("tabs", "status"):
sub.add_parser(name)
for name in ("text", "html", "shot"):
p = sub.add_parser(name)
p.add_argument("--index", type=int, default=None, help="tab index from `tabs` (default 0)")
p.add_argument("--match", default=None, help="substring of the tab URL or title")
if name in ("text", "html"):
p.add_argument("--limit", type=int, default=8000, help="characters to print (default 8000)")
else:
p.add_argument("--out", default=None, help="output PNG (default /tmp/deck-shot-<time>.png)")
p = sub.add_parser("unsafe-eval", help="run JS in a tab (opt-in; not for authenticated sites)")
p.add_argument("expression")
p.add_argument("--index", type=int, default=None)
p.add_argument("--match", default=None)
args = ap.parse_args()
if args.cmd == "status":
ensure_tunnel()
cdp = connect()
print(json.dumps(cdp.call("Browser.getVersion"), indent=2))
return 0
cdp = connect()
if args.cmd == "tabs":
for i, t in enumerate(cdp.pages()):
print(f"{i:2d} {t.get('title','')[:52]:52} {t.get('url','')[:70]}")
return 0
target = pick(cdp.pages(), getattr(args, "index", None), getattr(args, "match", None))
session = cdp.attach(target["targetId"])
if args.cmd in ("text", "html"):
expr = "document.body.innerText" if args.cmd == "text" else "document.documentElement.outerHTML"
res = cdp.call("Runtime.evaluate",
{"expression": expr, "returnByValue": True, "awaitPromise": True},
session=session)
value = res.get("result", {}).get("value") or ""
print(value[: args.limit])
if len(value) > args.limit:
print(f"\n[deck-browser: truncated {len(value) - args.limit} more characters]")
return 0
if args.cmd == "shot":
res = cdp.call("Page.captureScreenshot", {"format": "png"}, session=session)
out = args.out or f"/tmp/deck-shot-{int(time.time())}.png"
with open(out, "wb") as fh:
fh.write(base64.b64decode(res["data"]))
print(out)
return 0
if args.cmd == "unsafe-eval":
res = cdp.call("Runtime.evaluate",
{"expression": args.expression, "returnByValue": True, "awaitPromise": True},
session=session)
print(json.dumps(res.get("result", {}).get("value"), indent=2))
return 0
return 1
if __name__ == "__main__":
sys.exit(main())
case "$CMD" in
tabs)
ensure_attached
tab_list | awk -F'\t' '{printf "%2s %-52s %s\n", $1, substr($2,1,52), $3}'
;;
status)
ensure_attached
playwright-cli -s="$SESSION" eval 'navigator.userAgent' | json_unquote
;;
text|html)
LIMIT=8000
args=()
while [ $# -gt 0 ]; do
case "$1" in
--limit) LIMIT=${2:-8000}; shift 2 ;;
*) args+=("$1"); shift ;;
esac
done
ensure_attached
idx=$(resolve_tab ${args+"${args[@]}"})
[ -n "$idx" ] && playwright-cli -s="$SESSION" tab-select "$idx" >/dev/null
if [ "$CMD" = text ]; then expr='document.body.innerText'; else expr='document.documentElement.outerHTML'; fi
out=$(playwright-cli -s="$SESSION" eval "$expr" | json_unquote)
printf '%s' "$out" | head -c "$LIMIT"
[ "${#out}" -gt "$LIMIT" ] && printf '\n[deck-browser: truncated %s more characters]\n' "$(( ${#out} - LIMIT ))"
echo
;;
shot)
out=/tmp/deck-shot-$(date +%s).png
args=()
while [ $# -gt 0 ]; do
case "$1" in
--out) out=${2:-$out}; shift 2 ;;
*) args+=("$1"); shift ;;
esac
done
ensure_attached
idx=$(resolve_tab ${args+"${args[@]}"})
[ -n "$idx" ] && playwright-cli -s="$SESSION" tab-select "$idx" >/dev/null
playwright-cli -s="$SESSION" screenshot --filename="$out" >/dev/null
echo "$out"
;;
cli)
ensure_attached
playwright-cli -s="$SESSION" "$@"
;;
*)
sed -n '2,22p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
exit 1
;;
esac
+32 -30
View File
@@ -1,52 +1,54 @@
---
name: deck-browser
description: Read the user's Chrome on the Steam Deck from arceus — list tabs, dump page text/HTML, take screenshots over CDP. Use when the user says "look at my browser", "what's on my screen", "read this page I have open", or when a page they can see on the Deck is unreachable from this host. Read-only; never drive authenticated sessions.
description: Read the user's Chrome on the Steam Deck from arceus — list tabs, dump page text/HTML, take screenshots. Use when the user says "look at my browser", "what's on my screen", "read this page I have open", or when a page they can see on the Deck is unreachable from this host. Read-only; never drive authenticated sessions.
---
# Reading the Steam Deck's browser
The user runs Chrome on the **Steam Deck** (hostname `deck`, `192.168.129.204`) and talks to agents on
**arceus (ziadpve)**. When they say "look at my browser" or "the page I have open", this is how you see it: a CDP
connection to the Deck's Chrome over an SSH tunnel, wrapped by `deck-browser`.
The user browses on the **Steam Deck** (`deck`, `192.168.129.204`) and talks to agents on **arceus (ziadpve)**.
When they say "look at my browser" or "the page I have open", this is how you see it.
## Requirements (user-side, already enabled)
Under the hood it is Playwright: `playwright-cli attach --cdp=ws://127.0.0.1:9222/devtools/browser` connects to
Chrome over CDP (Playwright's `connectOverCDP` accepts a `ws://` endpoint), and `bin/deck-browser` is a thin
wrapper that opens the SSH tunnel and picks the tab for you.
In the Chrome they want read, `chrome://inspect/#remote-debugging` → tick **"Allow remote debugging for this
## Requirement (user-side, already enabled)
In the Chrome they want read: `chrome://inspect/#remote-debugging` → tick **"Allow remote debugging for this
browser instance."** That binds CDP to `127.0.0.1:9222` **on the Deck only**. If the tool reports no endpoint, ask
them to tick it again — do not try to enable it yourself, and never expose the port on `0.0.0.0`.
them to tick it again — never try to enable it yourself, and never expose the port on `0.0.0.0`.
## Usage
`deck-browser` opens the tunnel (`ssh -N -L 9222:127.0.0.1:9222 deck`) automatically and reuses it if present.
```bash
deck-browser tabs # index, title, url
deck-browser status # Chrome version over CDP
deck-browser text --index 3 --limit 4000 # innerText of a tab
deck-browser text --match linkedin --limit 2000 # pick by URL/title substring
deck-browser status # user agent of the browser
deck-browser text --match linkedin --limit 4000 # innerText of that tab
deck-browser text --index 3 # by index from `tabs`
deck-browser html --index 0 --limit 20000 # outerHTML
deck-browser shot --index 3 --out /tmp/shot.png # PNG screenshot
deck-browser unsafe-eval 'document.title' --index 0 # opt-in JS, see rules
deck-browser shot --index 3 --out /tmp/x.png # PNG screenshot
deck-browser cli tab-select 2 # any playwright-cli command, same session
```
Prefer `--match` over `--index`: tabs reorder and indices drift between calls.
Prefer `--match` over `--index`: tabs reorder between calls. The tunnel opens itself and is reused.
For anything beyond reading (console, network, storage state), pass a `playwright-cli` command through
`deck-browser cli …` rather than writing a new tool.
## Rules
- **Read-only.** There is no click/type/navigate command on purpose. Driving an authenticated session (LinkedIn,
Gmail, banking) risks the account being restricted for automated access, and the user's own instructions treat
that as off-limits. If a task seems to need clicking, say so and ask them to do it.
- **Screenshots may contain private data.** Save to `/tmp` (never a Git repo), mention the path, and do not
describe credentials, tokens, session cookies or payment details seen in a shot.
- `chrome://` pages (newtab, inspect, apps, settings) return no text — Chrome blocks script access there. Use
`shot` for those instead.
- Output is truncated by `--limit` (default 8000 chars). Increase for long articles, but read specific tabs rather
than dumping the whole session.
- If a capture says the socket closed, the user probably closed that tab or the toggle; re-run `deck-browser tabs`.
- Teardown when finished for a while: `pkill -f "ssh -N -L 9222"` and ask them to untick the box.
- **Read-only.** No click/type/navigate helper exists on purpose. Driving an authenticated session (LinkedIn,
Gmail, banking) risks the account being restricted; the user explicitly ruled that out. If a task needs clicking,
say so and ask them to do it.
- **Screenshots may contain private data.** Write to `/tmp` (never a Git repo), name the path, and never restate
credentials, tokens, cookies or payment details seen in a capture.
- `chrome://` tabs (newtab, apps, inspect) return little or no text — Chrome blocks script there. Use `shot`.
- If attach fails mid-task, the user probably unticked the box or closed the tab: re-run `deck-browser tabs`.
- Teardown when finished: `pkill -f "ssh -N -L 9222"` and ask them to untick the box.
## Why not Playwright
## Background worth knowing
`playwright-cli attach --cdp=...` expects an HTTP `/json/version` endpoint. Chrome's per-instance toggle exposes
only the WebSocket at `/devtools/browser` (HTTP paths return 403/404), so `deck-browser` speaks CDP directly with
the standard library. Verified against Chrome 158 on SteamOS.
Chrome ≥136 ignores `--remote-debugging-port` on a normal profile, so the `chrome://inspect` toggle is the only way
in (verified on Chrome 158 flatpak: no listener, no `DevToolsActivePort`). That endpoint serves **only** the
WebSocket at `/devtools/browser` — HTTP `/json/version` and `/json/list` return 403/404 — which is why the endpoint
must be given to Playwright as `ws://`, not `http://`.