From d306474f950c44cd05ef7d2ce8e07ed5866273da Mon Sep 17 00:00:00 2001 From: Ziad Arafat Date: Wed, 2 Dec 2026 12:18:08 -0700 Subject: [PATCH] deck-browser: read the Deck's Chrome from arceus over CDP The user browses on the Steam Deck; agents run on arceus. Chrome's per-instance remote debugging (chrome://inspect toggle) exposes CDP only as a WebSocket at /devtools/browser, so playwright attach cannot use it and the HTTP /json paths return 403. bin/deck-browser speaks CDP directly with the standard library: tabs, text, html, shot, status, plus an opt-in unsafe-eval. Read-only by design - no click, type or navigate - because driving authenticated sessions is what gets accounts restricted. Opens the SSH tunnel itself and reuses an existing one. Registers the skill for every harness and tells agents it exists. --- bin/deck-browser | 273 ++++++++++++++++++++++++++++ config/free-pi/AGENTS.md | 6 + config/pi/AGENTS.md | 1 + config/skills/deck-browser/SKILL.md | 52 ++++++ home/agents.nix | 1 + 5 files changed, 333 insertions(+) create mode 100755 bin/deck-browser create mode 100644 config/skills/deck-browser/SKILL.md diff --git a/bin/deck-browser b/bin/deck-browser new file mode 100755 index 0000000..9f0c697 --- /dev/null +++ b/bin/deck-browser @@ -0,0 +1,273 @@ +#!/usr/bin/env python3 +"""deck-browser — read (do not drive) the Chrome running on the Steam Deck. + +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. + +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. + +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 + +Environment: DECK_HOST (default "deck"), DECK_CDP_PORT (default 9222). +""" + +from __future__ import annotations + +import argparse +import atexit +import base64 +import json +import os +import socket +import struct +import subprocess +import sys +import time +import urllib.parse + +HOST = os.environ.get("DECK_HOST", "deck") +PORT = int(os.environ.get("DECK_CDP_PORT", "9222")) +LOCAL = "127.0.0.1" + + +# --- 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: + try: + self.sock.close() + except OSError: + pass + + +# --- 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-