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.
274 lines
9.5 KiB
Python
Executable File
274 lines
9.5 KiB
Python
Executable File
#!/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-<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())
|