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.
This commit is contained in:
1 parent
acb8191f13
commit
d306474f95
5 files changed
+333
No files matched your search
Executable
+273
@@ -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-<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())
|
||||
@@ -11,6 +11,12 @@ Locate, outline, then read a window — never paste a file body you have not nar
|
||||
- `context-guard` blocks unbounded large reads; follow its hint rather than retrying.
|
||||
- Full playbook: `/skill:context-discipline`. Policies: `/skill:homelab-policies`.
|
||||
|
||||
## Reaching the user's browser
|
||||
|
||||
The user browses on the **Steam Deck**, not on this host. `deck-browser` reads their Chrome (tabs, page text,
|
||||
screenshots) over CDP through an SSH tunnel they enable per session. Read-only: never click or navigate an
|
||||
authenticated session. Details: `/skill:deck-browser`.
|
||||
|
||||
## Document every change in the Wiki.js homelab docs
|
||||
|
||||
After any infrastructure, service, application or configuration change, write it up in the wiki — every time, without being asked again.
|
||||
|
||||
@@ -37,3 +37,4 @@ Load the skill that matches the task instead of asking for it up front:
|
||||
| memory, secrets, host safety, forges, codemode, stack defaults | `/skill:homelab-policies` |
|
||||
| delegate a well-specified task to free models, then review it | `/skill:cli/handoff` |
|
||||
| runtimes and project tools | `/skill:mise-cli` |
|
||||
| reading the user's Chrome on the Steam Deck | `/skill:deck-browser` |
|
||||
@@ -0,0 +1,52 @@
|
||||
---
|
||||
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.
|
||||
---
|
||||
|
||||
# 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`.
|
||||
|
||||
## Requirements (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`.
|
||||
|
||||
## 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 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
|
||||
```
|
||||
|
||||
Prefer `--match` over `--index`: tabs reorder and indices drift between calls.
|
||||
|
||||
## 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.
|
||||
|
||||
## Why not Playwright
|
||||
|
||||
`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.
|
||||
@@ -9,6 +9,7 @@ let
|
||||
sharedSkills = [
|
||||
"git" "gt" "mise-cli" "secrets_man" "searxng" "playwright-cli"
|
||||
"context-discipline" "homelab-policies" "memory-layer" "roku-tv" "zsa-moonlander"
|
||||
"deck-browser"
|
||||
];
|
||||
cliSkills = [ "infra-change" "wiki-update" "wiki-view" "lapis-memory" "handoff" ];
|
||||
allSkills = sharedSkills ++ cliSkills;
|
||||
|
||||
Reference in new issue
Block a user