# The user's browser

zelk driving the user's own Chrome, with their logins, instead of the
headless Chrome it runs for itself. It builds on
[zelk's own browser](/internals/browser/) and reuses its driver; read that first.
The pieces are `core/browser`'s `Attach`, `Linked` and `UserTools`, the
extension in `core/browser/extension`, and `-user-browser` on both hosts.

[Automating the user's browser](/internals/browser-automation/) extends this design
for automation: page script, watches, data out, trusted sites and tabs,
paced input and cookies. It changes U3, U5 and U15 below.

## Goals

- **The user's sessions.** The agent works in pages the user is signed in
  to: reproduce a bug that needs an account, check the user's own app as
  the user sees it, do a task the user hands over in a tab.
- **The user stays in charge.** zelk sees only the tabs it opened or the
  user handed it, acts on a site only with the user's approval, and stops
  the moment the user says so, from the browser itself.
- **Nothing private leaves.** zelk never reads the user's cookies, storage,
  passwords or other tabs, and never types a credential.
- **The same driver.** Snapshots, refs, input, waits, console, screenshots
  and the safety checks of zelk's own browser, unchanged where they still
  apply.
- **Linux, macOS, native Windows, and WSL2 driving a Windows browser**,
  with one zelk executable for the host.

- **Clean and smooth.** Setting up is one command and one paste; a flow on
  one site asks once; every refusal says what to do next; the user never
  has to tidy up after zelk.

Chrome, Brave and Edge are all Chromium and behave identically (S3).

Not goals: browsers not built on Chromium; Chrome on another
machine; running unattended on real accounts beyond the sites a rule
allows (A6); anything the user's Chrome would show only through zelk's own
browser's sandbox or network policy, which don't apply here.

## What differs from zelk's own browser

| | zelk's own browser | The user's browser |
|---|---|---|
| Process | started and killed by zelk | the user's; zelk never starts or closes it |
| Profile | fresh, thrown away | the user's, with every login |
| Transport | pipes, fds 3 and 4 | the user’s extension, over loopback directly or through native messaging on Windows (U1) |
| Tabs | all of the browser's | only zelk's tab group (U2) |
| Sandbox, network policy | the session's | none: the user's Chrome runs as the user |
| File policy | pages load workspace and scratch files | no `file:` at all |
| Who else acts | nobody | the user, at the same time |
| Approvals | domain rules; auto mode's reviewer | a person, per site; never the reviewer alone (U3) |

## How zelk attaches

Three ways in, judged on Linux, macOS and WSL2:

**Chrome's remote-debugging port.** Since Chrome 136 `--remote-debugging-port`
and `--remote-debugging-pipe` are ignored for the default data directory:
they need `--user-data-dir` pointing elsewhere, and another directory has
another encryption key, so the logins don't come with it. Google made the
change because infostealers used the port to take cookies
([Chrome blog](https://developer.chrome.com/blog/remote-debugging-port)).
Chrome for Testing and Chromium still honour the flags, but they aren't
the user's browser. Ruled out.

**Chrome 144's "remote debugging" toggle** (`chrome://inspect/#remote-debugging`,
what Chrome DevTools MCP's `--autoConnect` uses). The user turns it on;
each connection then shows a dialog the user must allow, and Chrome shows
"Chrome is being controlled by automated test software" while one is open
([auto-connect](https://developer.chrome.com/docs/devtools/agents/use-cases/auto-connect)).
It gives the whole browser over CDP: every tab, and, in Google's words,
"all data in your browser profile, including open tabs, session storage,
local storage, cookies". Any limit on that would be zelk's own code
alone. While it is on, any local program can ask, and one click lets it
in. From WSL2 in its default NAT mode the port on Windows' loopback isn't
reachable. Rejected for now (U1); it could become a second transport later
for users who won't install an extension, with the same driver limits but
nothing behind them.

**An extension** using `chrome.debugger`. It attaches to tabs one by one,
so it can hold to a set of tabs and pass on only the CDP calls it lists.
It works on the default profile in every Chrome since long before 136,
needs no flag and no restart, and shows Chrome's own bar "zelk started
debugging this browser" with a Cancel button whenever it is attached. The
extension dials zelk, not the other way round, so Windows Chrome can reach
zelk inside WSL2 (below). Chosen (U1).

Native Windows also uses Chromium's native messaging API. The Windows
zelk executable has a stdio entry point that relays the link to the same
loopback service. The browser launches it for the extension, using an HKCU
registration and a manifest allowing zelk's fixed extension origin. The
relay forwards opaque messages and holds no pairing key. The extension
and zelk still prove the pairing and seal CDP end to end. Linux and
macOS bundles use direct loopback, including the bundle that Linux zelk
writes for Windows browsers under WSL2.

## Prior art: opencode's browse

[anomalyco/browse](https://github.com/anomalyco/browse) drives the user's browser
the same way: an extension using `chrome.debugger`, connected over a
WebSocket to a local relay (Rust), with agents limited to tabs they opened
or the user lent, opened in the background in a collapsed group in the
last-used window, and Chrome's bar's Cancel disconnecting every tab. That
another team reached the same shape independently is some evidence for U1
and U2. What it does differently, and what this design takes:

- **Pairing** is a one-time code (`XXXX-XXXX`, ten minutes, five wrong
  tries void it) exchanged over ECDH for a key of the browser's own; both
  sides prove the key before anything is obeyed; only known extension IDs
  are accepted. Taken (U12): no long secret for the user to paste.
- **Handoff:** the agent asks the user to do something in a tab (sign in,
  a CAPTCHA), and only a real click on the extension's own UI, never the
  page, ends it. Taken (U13): it is how sign-in works with the credential
  guard.
- **Bot challenges** are reported and handed to the user, never solved.
  Taken as a hard limit in the skill and the handoff.
- **Different here:**
  - browse allows `eval` and reads cookies and storage for the tab's own
    hosts, with switches to widen it. zelk runs page script only in
    trusted tabs, never reads storage, and never gives cookie values to
    the model (U5, A1, A9).
  - browse has no approval per action: lending a tab is the consent. In
    zelk too, a tab the user shared or approved is trusted (A13), but
    opening a tab on a new site asks a person (U3), and auto mode's
    reviewer never stands in for one, since it would otherwise act on
    real accounts unreviewed.
  - browse avoids `Runtime.enable`. zelk keeps it, with the known traps in
    its tests (A8), and paces input like a person (A7).
  - browse needs extra host permissions (`scripting`, `webNavigation`,
    all sites) for an injected script. zelk's snapshots come from CDP, so
    the extension needs none of those.
  - browse's README says the relay token file can be used by any local
    process running as the user, and that `allowedOrigins` doesn't filter
    the page's own requests. Both hold for zelk too: the pairing file is
    kept from zelk's tools, but not from other programs, and per-site
    approval governs actions, not what a page loads.
  - browse doesn't mention WSL; its remote mode binds the relay off
    loopback, unencrypted. This design keeps loopback only and relies on
    WSL2's forwarding (S3.4).

## Architecture

```
model ── user_browser_* tools ── Browser (attached, no process)
                                    │  CDP over cdp.Transport
                                    ▼
             zelk: WebSocket listener on 127.0.0.1:PORT (paired, U9)
                                    ▲  extension dials in
                                    │
     the user's Chrome ── zelk extension ── chrome.debugger ── tabs in zelk's group
```

- **The driver** (`core/browser`) has a `Browser` with no process:
  `browser.Attach(ctx, transport, AttachConfig)`. `Close` releases instead
  of killing: it detaches from the tabs and never sends `Browser.close`.
  `Exited` means "the connection ended".
- **`cdp.Conn`** reads messages from a `Transport`. The NUL-framed pipe
  is one transport; the WebSocket the other.
- **The extension speaks CDP to zelk.** It plays the browser's own target
  for the few `Target.*` calls the driver makes (`getTargets`,
  `createTarget`, `attachToTarget`, `closeTarget`), answering from
  `chrome.tabs` and `chrome.debugger.attach`, limited to zelk's group, and
  forwards tab sessions' calls through `chrome.debugger.sendCommand`,
  child sessions (out-of-process iframes) included *(S3)*. So `tabs.go`,
  `tab.go` and the rest of the driver run as they are.
- **Mode.** An attached browser carries `user` mode: the tools, the file
  policy and the redactions below read it. Nothing in the driver decides
  by the transport.

## The extension

Plain JavaScript, no build step, a few hundred lines, in
`core/browser/extension/` and embedded in zelk. `zelk browser extension
-dir DIR` writes it out; the user loads it unpacked
(`chrome://extensions`, developer mode). Its manifest carries a fixed
`key`, so its ID is the same everywhere and zelk can check it. It is not
published to the Web Store (U10).

**Permissions:** `debugger`, `tabs`, `tabGroups`, `storage`, `alarms`;
`downloads`, to report a download a zelk tab starts (A10); `sidePanel`
and `notifications`, to show what zelk does. No host permissions, no
content scripts, no `cookies`, `history` or `bookmarks`.

**What it enforces**, whatever zelk sends it:

1. **Only zelk's tabs.** It attaches only to tabs in its group, and
   detaches from a tab the moment it leaves the group (the user dragged it
   out) or shows a page it refuses (`file:`, `chrome:`, `chrome-extension:`,
   `devtools:`, the Web Store; `chrome.debugger` refuses most of these
   itself).
2. **Only listed methods.** A table of the CDP methods and events the user
   mode's tools need. Anything else is an error, never forwarded. Never
   listed: `Network.getCookies` (but for a session export the user
   allows in the panel, A9), `getAllCookies`, `setCookie`(s),
   `deleteCookies`, `clearBrowserCookies`, `Storage.*`, `DOMStorage.*`,
   `IndexedDB.*`, `CacheStorage.*`, `Fetch.*`, `DOM.setFileInputFiles`,
   `HeapProfiler.*`, `Browser.*` other than the `getVersion` it answers
   itself, `Target.*` other than the four above and `setAutoAttach`, and
   `DOM.getDocument`. S3.1 found Chrome gives an extension all of these
   but `HeapProfiler`, `Browser`, `DOMStorage` and `Target.getTargets`:
   from one tab, `Network.getAllCookies` returns the profile's cookies,
   `Target.createTarget` opens an active tab outside the group, and
   `DOM.setFileInputFiles` attaches a local file. The list is the only
   thing between those and zelk.
3. **No credentials in what it forwards** (S3.7). It removes `Cookie`,
   `Set-Cookie`, `Authorization` and `Proxy-Authorization` from every
   header map, and `postData`, `postDataEntries` and the cookie lists
   (`associatedCookies`, `blockedCookies`, `exemptedCookies`) from the
   network events (`requestWillBeSent`, `responseReceived` and their
   `ExtraInfo`); and it blanks every `inputValue` in
   `DOMSnapshot.captureSnapshot`'s result, which held password values
   in full (S3.8; the driver uses it only for boxes).
4. **The user's stop is final.** Cancel on Chrome's bar, or Stop in the
   extension's panel, detaches every tab and tells zelk; it attaches again
   only after the user presses Resume. Chrome doesn't hold the stop
   itself: after Cancel (`onDetach` reason `canceled_by_user`) it lets an
   extension attach again at once, with no prompt, though the bar comes back (S3.5). So the stop is the
   extension's own state, kept in `chrome.storage` so a restarted worker
   keeps it.

**What it can't enforce.** The driver needs `Runtime.evaluate` and
`callFunctionOn` for its own work (reading a ref's frame, the ready state,
finding elements), and script in a page can read `document.cookie` and
storage. So the extension can't stop a zelk that is itself compromised
from reading what a page's script can. Against the model it doesn't need
to: the model has no way to run script (U5), and the driver's own scripts
are fixed in zelk's source.

**Side panel** (the extension's button opens it; it stays open while the
user works in the page, where a popup closed at the first click outside):
the connection's state, Pair (type the code `zelk browser pair` prints),
the tab zelk is working in, Share this tab / Stop sharing, Done / Decline
for a handoff, zelk's watches with End, Stop / Resume.

**Idle tabs:** a tab zelk opened that no call used for 10 minutes is
closed, while zelk is connected; never one with a watch, one in front,
one a handoff or export waits on, or one the user shared.

**Badge:** OFF while the user stopped zelk, WAIT while a handoff or an
export waits on them, ON while zelk acts (until 3 s after its last call),
nothing otherwise. A handoff or an export also raises a system
notification; clicking it opens the side panel and shows the tab.

## Pairing and the connection

- **`zelk browser pair`** (U12) prints a one-time code (`XXXX-XXXX`, ten
  minutes; five wrong tries void it) and listens. The terminal UI pairs
  the same way from Settings › Tools › Pair with your browser (or
  `/pair-browser`), showing the code in a dialog, and turning on Your
  browser while unpaired pairs first; a link the UI holds takes the new
  key at once (`Linked.SetPairing`), with no restart. The user types it into
  the panel. The two sides make X25519 keys (`crypto/ecdh`), exchange
  them, and each proves it knows the code with an HMAC of the exchange's
  transcript under it, so a party in the middle without the code fails. The
  shared key is kept by the extension and in zelk's configuration
  directory, `$XDG_CONFIG_HOME/zelk/browser.json` or
  `~/.config/zelk/browser.json` (mode 0600), and on native Windows in
  `%APPDATA%\zelk\browser.json` (private ACL) or the configured keychain.
  It includes the port (default
  27823, below the ranges operating systems use for outgoing connections),
  the first of the range of eight zelk processes listen on
  ([browser-processes.md](/internals/browser-processes/), P1). The code is short enough to type and is worthless after the
  exchange. The extension proves the code first, so a caller without it
  learns nothing from zelk to guess it with offline. The file sits with
  zelk's other credentials, in the directory the sandbox hides from
  commands; outside a sandbox a read of it, being outside the workspace,
  is never allowed without asking.
- **zelk listens**, on `127.0.0.1:PORT` only, from the first user-browser
  call to its release, on the first free port of a range of eight from
  the paired one. The extension dials the range every half minute, and
  at once when the user opens its panel, with a link to each zelk
  process listening ([browser-processes.md](/internals/browser-processes/)).
- **Both sides prove the secret** before any CDP passes: zelk checks the
  request's `Origin` is the extension's fixed ID and its `Host` is the
  loopback address (no DNS rebinding), then each side answers the other's
  random challenge with an HMAC-SHA256 of it under the paired key. A web page
  can open a WebSocket to localhost, and another local program can listen
  on the port while zelk isn't: the first fails the origin check and the
  proof, the second the proof. One paired extension at a time; a second
  connection is refused.
- **Every message after the proofs is sealed.** A program on the port
  could otherwise pass both proofs along, the extension's to zelk and
  zelk's back, and then read the pages and send its own calls. Each
  direction has its own AES-256-GCM key, derived (HKDF-SHA256) from the
  paired key and both nonces, and numbers its messages as the nonce. A
  message that doesn't open in its turn ends the connection, so a relay
  can only drop it.
- **Messages** are CDP's JSON plus a few of the extension's own (hello with
  its protocol version, `link.Version`; tab shared, tab released, stopped
  by the user, and those of [browser automation](/internals/browser-automation/)
  and [several processes](/internals/browser-processes/)).
  A version zelk doesn't speak fails with "update the extension: run zelk
  browser extension".
- **WebSocket** is the minimum zelk needs (RFC 6455 server side, text
  frames, ping, close; no compression), written in
  `core/internal/wsock` with the standard library and fuzzed
  (U9). No new dependency in core.
- **Keeping alive** (S3.3). With the socket open and a ping every 20 s
  the worker stayed up through 2.5 idle minutes. A worker that is stopped
  anyway comes back on its 30 s alarm (it reconnected in 21 s), and the
  tabs stay attached meanwhile: the new worker drives them at once, and
  `attach` says another debugger is already attached. So the extension
  keeps its group and the user's stop in `chrome.storage`. A new worker
  has no connection, so it detaches the group's tabs a stopped one left
  attached, and zelk attaches them again when it reconnects, under the
  same target IDs; "already attached" counts as attached.

## Platforms

- **Linux and macOS.** The user's Chrome or Chromium with the extension;
  zelk on the same machine. The same on both.
- **Native Windows.** Run `zelk browser extension` and `zelk browser
  native-messaging`, then load the unpacked extension and pair. The
  registration uses the default `REG_SZ` value of
  `HKCU\Software\<vendor>\NativeMessagingHosts\com.zelk.browser`.
  The value names a private manifest, whose `path` is the current
  `zelk.exe`. Use the executable from a trusted install. No installed
  browsers are scanned or started. The CLI registers these paths:

  | Browser | HKCU vendor path below Software |
  | --- | --- |
  | Chrome and Chrome for Testing | `Google\Chrome` |
  | Chromium | `Chromium` (also checks Chrome) |
  | Edge | `Microsoft\Edge` (also checks Chromium and Chrome) |
  | Brave | `BraveSoftware\Brave-Browser` (and Chrome) |
  | Vivaldi | `Vivaldi` (and Chrome) |
  | Opera | `Opera Software\Opera Stable` (and Chrome) |
  | Opera GX | `Opera Software\Opera GX Stable` (and Chrome) |

  Arc for Windows has no independently verified registry location here.
  A Chromium build that reads the Chrome registration may work without
  a separate entry. The automated acceptance uses only Chrome for
  Testing. See [Chromium's lookup](https://chromium.googlesource.com/chromium/src/+/main/chrome/browser/extensions/api/messaging/launch_context_win.cc)
  and [Edge's lookup](https://learn.microsoft.com/en-us/microsoft-edge/extensions/developer-guide/native-messaging).

  The registry and browser manifest scope discovery and launch to the
  Windows account and extension: the manifest (`path` to `zelk.exe`,
  `allowed_origins` pinned to zelk's fixed extension ID) and the
  extension bundle live in user-private ACL directories (`hostfile`),
  and `zelk` verifies the caller's origin argument before relaying.
  The private pairing secret (`%APPDATA%\zelk\browser.json` with a
  user-only ACL, or Windows Credential Manager) and authenticated
  AES-256-GCM encryption protect CDP end to end even from another local
  program that can reach or impersonate the TCP listener. Another local
  Windows user cannot read the pairing secret, the manifest, or the
  browser's `chrome.storage.local` profile; an untrusted process under
  the same Windows account could connect to `127.0.0.1` and spend
  pairing guesses or block a port, and any process that can already read
  the user's browser profile, pairing file, or Credential Manager acts
  as that user.

- **WSL2 with a Windows browser.** Run `zelk browser extension -dir
  /mnt/c/Users/<you>/zelk-extension` in WSL2. Load that bundle in Windows
  and pair with the Linux zelk. The browser dials its Windows loopback,
  forwarded or shared with WSL2's loopback. Binding stays on
  `127.0.0.1`; no Windows helper, public listener or Windows firewall
  exception is required. Mirrored networking was verified in S3.4.
  Default NAT with `localhostForwarding` needs an end-to-end run.

  The extension and Linux zelk use the same `Host` / `Origin` check,
  X25519 pairing proofs, mutual HMAC challenge-response, and AES-256-GCM
  sealed link across the VM boundary. Another WSL account or process
  that cannot read the Linux credential (`~/.config/zelk/browser.json`,
  mode `0600`, or the user's Secret Service keyring) cannot act as a peer
  or read CDP frames, even if it can reach loopback; another Windows
  user cannot read the extension's `chrome.storage.local` profile.
  Linux ACLs protect the state from other UIDs, and zelk's bwrap sandbox
  hides `~/.config/zelk` from sandboxed commands. A process running under
  the same Linux UID outside the sandbox shares that UID's file access,
  so keep the pairing in a trusted account or a keyring if the account
  runs untrusted code.

  Downloads on standard Windows drive mounts map to `/mnt/<drive>`;
  UNC paths for the current distro's WSL share map to Linux paths. Other
  UNC shares and nonstandard mounts need a mapping supplied by the
  host. Cookie-jar exports and captures are created by Linux zelk in
  private Linux state, with Linux paths. They never need reverse path
  translation.

- **Not supported:** Firefox and Safari; Chrome on another machine (the
  listener is loopback only); Chrome's mobile builds.

## What zelk may touch

**Tabs** (U2). zelk works in one tab group, titled `zelk`, in the window
the user last used:

- Tabs zelk opens go into it, in the background; zelk never brings a tab
  or window to the front.
- The user hands zelk a tab with the extension's Share (or by dragging it
  into the group); the tool results say a tab was shared.
- A popup a zelk tab opens (a sign-in window, a checkout) joins the group,
  so flows across windows keep working.
- Everything else is invisible to zelk: not attached, and not listed,
  not even by title or URL.
- zelk closes only tabs it opened. "Closing" a tab the user shared
  releases it: zelk detaches and takes it out of the group, and the tab
  stays.

**Sites and tabs** (U3, changed by A5 and then by
[A13](/internals/browser-automation/#trusted-tabs-a13)). Every acting call names
its page's origin, as in zelk's own browser (`tool.WithURL`), and the
tool checks it against the tab just before acting. In the user's
browser:

- Every tab in zelk's group is trusted: the user shared it, approved
  opening it, or a trusted tab opened it as a popup. A call in one runs
  without asking while a person attends, wherever the tab has
  navigated.
- Opening a new tab (`user_browser_open` with `new_tab`; in the user's
  browser no other call opens one) asks a person, unless an allow rule
  the user wrote names the site (`user_browser_*(domain:localhost)`).
  The prompt offers that site for the rest of the session, or for good
  ("Trust this site"). `handoff` asks nothing: it only asks the user.
- **Auto mode doesn't decide them.** Its reviewer is never enough on its
  own: a call no rule allows goes to a person, as protected paths do. A
  wrong "allow" here spends the user's real account.
- `dont-ask` mode refuses opening a tab no rule allows. Headless
  sessions act only where a matching allow rule (site or tool) or one of
  the user's hooks allows, trusted tab or not (A6).
- Read-only calls (snapshot, screenshot, console, the network list, wait,
  find, frames, inspect, tabs list, compare, audit, the measurements) ask
  nothing: they read only tabs the user gave or approved.

The rules for `browser_*` (zelk's own browser) never apply to
`user_browser_*`, and the reverse (U6): a rule written for testing
`localhost` headless can't spend a real account.

## Hard limits

The skill's rules for zelk's own browser are advice. Here, where the
driver can see the case, they are refused in code (U4):

- **No credentials.** `fill`, `press` and every other input are refused
  into a password field, a field whose `autocomplete` names a credential
  or payment (`current-password`, `new-password`, `one-time-code`,
  `cc-number`, `cc-csc`, `cc-exp*`), or while the focus is in one. The
  refusal tells the model to hand the tab to the user. Signing in is the
  user's job.
- **Handoff** (U13). `user_browser_handoff` asks the user to do something
  in a tab (sign in, pass a CAPTCHA, confirm a payment themselves): the
  extension marks the tab and its button, and the call waits until the
  user presses Done or Decline in the extension's panel. Nothing a page
  does can end it, since the page can't reach the extension's UI. zelk
  names each request, so it can withdraw one it gave up on even before
  the extension answered; closing the tab or the user's stop ends it,
  and so does half an hour without an answer. It needs
  no approval: it only asks. Bot challenges are never solved, only handed
  over.
- **Values hidden.** Snapshots, `find` and `inspect` show such fields
  without their value. Chrome's accessibility tree masks only passwords:
  card numbers and one-time codes come through in full (S3.8). The driver
  hides them by the field's type and `autocomplete`, read from the DOM.
- **How the guard decides.** A field is secret by its type, its
  `autocomplete`, Chrome's masking, or a secret's word in its name, id,
  label or placeholder, judged in an isolated world the page can't
  reach. The focus is judged again after zelk focuses a field and before
  every chord that could type, so a focus handler or a `Tab` can't steer
  keys into a password. Where zelk can't see the focus (another site's
  frame, a closed shadow root) it doesn't type. A page's own script can
  still move the focus between zelk's check and its key, in the
  milliseconds between two protocol calls; closing that gap would need
  Chrome to type only into a node zelk names, which it doesn't offer.
- **No `file:`, `chrome:`, `javascript:`, `data:`, `view-source:` or
  extension pages**, opened or shared. Only `http`, `https` and
  `about:blank`.
- **Real-world effects** (paying, sending, deleting) can't be told from a
  click by code. A click in a trusted tab doesn't ask (A13), so the
  limit is the model's: the skill tells it to do one only when the user
  asked for exactly that, and otherwise to stop and ask in the
  conversation, saying what the click would do.

## Privacy: the tools in this mode

The user's browser gets its own tools, `user_browser_*` (U6): twenty-five
of the thirty-two, with the same behaviour unless the table says
otherwise (U5), and `handoff` (U13), offered always.

| Tool | In the user's browser |
|---|---|
| open, snapshot, click, fill, press, wait, screenshot, console, tabs | yes; the limits above; tabs lists only zelk's group |
| network | the request list (URL, method, type, status, failure, timing) and one request's headers, with credentials removed (U15): `Cookie`, `Set-Cookie`, `Authorization`, `Proxy-Authorization`, and the value of any header whose name holds `auth`, `token`, `key`, `secret`, `session`, `cookie` or `csrf`, shown as `[removed]`. No bodies, no post data |
| select, check, hover, drag, scroll, dialog, find, frames, inspect, compare, audit, record | yes |
| trace | yes: `Tracing` with a stream read by `IO.read` works (S3.1) |
| coverage | CSS only: Chrome refuses an extension `Profiler`, so JavaScript coverage can't run |
| profile | **no**: Chrome refuses an extension `Profiler` (S3.1) |
| evaluate | **no**: page script can read cookies, storage and any same-site API with the user's session |
| storage | **no**: cookies and storage are the user's |
| route | **no**: needs `Fetch`, which sees every request's headers, and would change what the user's real sites return |
| heap | **no**: a heap snapshot holds every string in the page's memory, tokens included |
| upload | **no**: sends a local file to a real site; may come later behind its own approval |
| downloads | **no**: the user's Chrome saves to the user's own folder, which zelk doesn't read |
| emulate | only on tabs zelk opened (U14): device, colour scheme, reduced motion, network and CPU throttling. Never on a tab the user shared. Chrome refuses an extension the locale and time-zone overrides |

[Automating the user's browser](/internals/browser-automation/) changes the rows
for evaluate, network and downloads: page script in trusted tabs (A1),
response bodies there (A4), and downloads fetched in the page (A10).

Console messages and page text may hold personal data. They reach the
model, fenced as untrusted, because the user handed or approved that tab;
that is the point of the feature. The prompt and the hosts' startup line
say page content goes to the model's provider.

## What still protects the user

The sandbox and the network policy don't apply: the user's Chrome runs as
the user, with the user's network. What stands between the model and the
user's accounts is:

1. **A person decides** which tabs zelk works in and which sites it
   opens tabs on (U3, A13), and auto mode's reviewer can't stand in.
2. **The driver's limits:** tab scope, the origin named and re-checked
   before every action, a ref acting only in its own frame's site, no
   credential input, hidden values, refused schemes, the tools left out.
   They hold against the model, which can't change zelk's code.
3. **The extension's limits:** tab scope, the method list, headers
   stripped. They hold against anything on the socket too, a compromised
   zelk included, except page script (above).
4. **The pairing:** nothing but the paired extension and the zelk holding
   the secret can speak.
5. **Untrusted content stays fenced**, and the skill says page text is
   never instructions.
6. **Chrome itself:** its bar shows whenever zelk is attached, and Cancel
   stops it; its renderer sandbox and site isolation are unchanged.
7. **The user's stop is final** until they resume.

What none of that does: an approved click on a real site has its real
effect; pages the user handed zelk are read in full and sent to the
model's provider; downloads a page starts land where Chrome puts them;
and without a sandbox a command the user approves can do anything the user
can, this included.

## Lifecycle

- **Starting.** The host starts the listener when the session starts, or
  the first `user_browser_*` call does. The extension's worker sleeps when
  idle and wakes to dial every 30 seconds (opening its panel dials at
  once), so a call waits up to 35 seconds; then it fails, saying to ask
  the user to open zelk's extension. Nothing starts Chrome.
- **One holder** (U8). One zelk process and, in it, one root session hold
  the user's browser at a time, shared with that session's subagents
  (each with its own current tab). Another session is told which
  holds it.
- **The user at the same time.** zelk never activates, focuses, moves or
  resizes tabs or windows. The user may click and type in a zelk tab; the
  driver's checks already catch what follows: a page that moved fails the
  origin check, a removed element's ref is stale, a covered one isn't
  clicked. A tab the user closes or drags out is gone for zelk
  (`ErrTabClosed`). Hidden tabs (S3.2): in a tab behind the user's,
  clicks, snapshots and screenshots work, the page reports itself visible
  and focused with focus emulation, timers run on time, but animation
  frames drop to about 3 a second and a screenshot takes 1.6 s, not
  30 ms. The driver never waits on animation frames. A minimised
  window behaves like a visible one under WSLg, which may not really
  minimise.
- **Lost connection** (the extension's worker restarted, Chrome
  restarted, a network blip). The listener stays; the extension dials
  again. Tab numbers survive, as the extension names targets by Chrome's
  tab ID; refs are stale and the next result says so, as after a browser
  restart in zelk's own browser.
- **Releasing.** With the session's background work
  (`StopBackground`, `Close`), after 30 idle minutes (as D7), or when the
  user deletes the session: zelk detaches, the group's tabs stay open
  and the group is renamed `<label> (done)`, as `zelk · shop (done)`.
  The listener closes.
- **The user's stop** (Cancel or the close button on Chrome's bar, Stop
  in the panel): everything detaches, and each later call fails with
  `ErrStopped`, "the user stopped zelk's use of their browser: ask them
  before going on", until they press Resume. zelk's watches are paused,
  not ended: they stay kept, their sources stay live, and Resume installs
  them again; each one's next wake says it wasn't running from the
  stop to the Resume ([browser automation](/internals/browser-automation/), Gaps
  are told). Chrome reports its bar's close button as the user's
  cancel too, so a bar closed only to get it out of the way stops zelk;
  it mustn't lose the user's watches. The extension marks each tab it
  lets go for the stop (`Target.detachedFromTarget` with `reason:
  "stopped"`), so a watch on it pauses rather than ending as a closed
  tab's does. A stop that outlasts zelk holds a new zelk's watches
  paused until Resume.

## What the model sees

- The tools are `user_browser_*`, offered and deferred as zelk's own are
  (the eleven offered, evaluate among them), and `handoff`, offered too: every
  sign-in needs it, and a refused credential field names it. Their descriptions say they act in
  the user's own Chrome, signed in.
- A skill of its own, `user-browser`: the loop and refs as in `browser`,
  plus what is different: which tabs it sees, that it can't type
  credentials and hands sign-in and challenges to the user with
  `handoff`, which calls ask the user, what each refusal means, and to say what a click
  will do before an irreversible one.
- With `-browser` too, both sets are offered and the prompt names which is
  which; nothing crosses between them.

## Host wiring

- `-user-browser` on both hosts, a saved default and a TUI setting.
- `zelk browser extension [-dir DIR]` writes the extension;
  `zelk browser pair` makes the pairing and prints the code;
  `zelk browser status` says whether zelk is paired. Whether the
  extension is connected is known only to a running zelk, which shows it.
- The TUI's footer and background list show the user's browser
  (connected, waiting, stopped by the user) and release it.
- The hosts' startup line: "user browser: yours, through zelk's
  extension: only tabs you share or it opens, opening a tab asks you once
  and zelk then acts in it without asking, and what it reads of your
  pages goes to the model's provider (<api>); listening on
  127.0.0.1:<port>". The host listens at startup;
  a port another zelk holds isn't fatal, the first call tries again.

## Testing

- **Unit:** the transport seam (pipe and WebSocket against the same `Conn`
  tests); the WebSocket framing and handshake, fuzzed, with each check of
  the handshake (origin, host, both proofs, version) shown to matter by a
  mutation check; the credential guard and redaction against fake pages,
  mutation-checked; the tool set and its permission marks; the attached
  browser's release never sending `Browser.close`.
- **Real Chrome** (`-tags=chrome`, `-chrome=... -chrome-libs=...`): Chrome
  for Testing still loads unpacked extensions with `--load-extension` in a
  throwaway profile *(S3)*, so every test drives the real extension: tabs
  outside the group unreachable, each refused method refused, headers
  stripped from events, a password field refused, the user's stop via
  `chrome.debugger.detach`, the worker restarted mid-session, a popup from
  a zelk tab joining the group. Mutation checks for the extension's tab
  scope and method list.
- **Live checks** with a model, never in the user's real profile: a separate Chrome profile signed in to a local app's test
  account, on Linux and on Windows Chrome from WSL2.
- `goleak`, `-race` throughout.

## What Chrome gives an extension (S3)

The design rests on these properties of Chrome for Testing 157 (Linux,
headless and visible), Edge 157 and Brave 1.99 on Windows, driven through
`chrome.debugger` by an extension relaying it over a WebSocket. Test pages
planted fake secrets (cookies, an `Authorization` header, `Set-Cookie`, a
POST body, typed password, card and one-time code) to find where each
turns up. Each finding has an ID that code comments cite.

| # | Finding | Consequence |
|---|---|---|
| S3.1 | Through `chrome.debugger`, on the tab and on a cross-site iframe's child session: page, lifecycle, network (bodies, `loadNetworkResource`), runtime, log, accessibility tree, `DOMSnapshot`, DOM boxes and hit tests, input (clicks landed, in the iframe too), screenshots, screencast, dialogs, reload, history, device metrics, media, CPU and network throttling, CSS rule usage, `Tracing` streamed and read with `IO.read`, `Fetch`. Refused by Chrome: `Profiler.*`, `HeapProfiler.*`, `DOMStorage.*`, `Browser.*`, `Target.getTargets`, the locale and time-zone overrides. Allowed by Chrome: every cookie call, `Network.getAllCookies` included; `Target.createTarget` (an active tab outside the group); `DOM.setFileInputFiles` with `/etc/hostname`. | The driver runs nearly unchanged. No CPU profile or JS coverage in this mode. The extension's method list is essential, not defence in depth. |
| S3.2 | A tab behind the user's: clicks in 11 ms, snapshots, screenshots in 1.6 s, timers on time, animation frames about 3 a second, visible and focused with focus emulation. A minimised window under WSLg behaved as a visible one. | Background tabs are usable. |
| S3.3 | With the socket open and pinging every 20 s, the worker stayed up 2.5 idle minutes. Stopped, it came back on its alarm in 21 s; the tab stayed attached throughout, the new worker drove it without attaching again, and `attach` said another debugger was attached. | Keep the extension's state in `chrome.storage`; "already attached" means attached. |
| S3.4 | Edge 157 on Windows, temporary profile, loaded the unpacked extension from the command line, reached the listener in WSL2 on `127.0.0.1` in 1.9 s (mirrored networking), and drove a page served from WSL2. Brave 1.99 (Chromium 157) on Windows did the same, through its Shields, and its method matrix and leaks matched Chrome's line for line. NAT mode is untested. | U11 holds in mirrored mode. Edge (and so likely other Chromium browsers) works the same. Windows tests can load the extension by flag. |
| S3.5 | Cancel on the bar: `onDetach` with `canceled_by_user`; the extension can then attach again at once, with no prompt. The bar came back on that attach, and Cancel worked again. | The user's stop must be held by the extension itself; the bar still shows each time zelk attaches, so a silent re-attach is never invisible. |
| S3.6 | Chrome for Testing 157 loads the extension with `--load-extension`, headless (0.3–0.8 s to connect) and visible. The request's `Origin` is `chrome-extension://<id>`; unpacked IDs differ by install path (two IDs seen). | Real-Chrome tests drive the real extension. The manifest needs its fixed `key` for the origin check. |
| S3.7 | Fake secrets in forwarded events: cookies in `requestWillBeSentExtraInfo` and `responseReceivedExtraInfo`; `Authorization` in `requestWillBeSent` and its `ExtraInfo`; `Set-Cookie` in `responseReceivedExtraInfo`; the POST body in `requestWillBeSent.postData`. | The extension strips post data and cookie lists as well as headers. |
| S3.8 | The accessibility tree shows a password as bullets but a card number and a one-time code in full. `DOMSnapshot.captureSnapshot` and `DOM.getDocument` return every field's value, the password's included. | The driver hides sensitive values itself; the extension blanks `DOMSnapshot`'s values and doesn't list `getDocument`. |

## Decisions

Each decision has an ID that the sections above and code comments cite.

| ID | Question | Decision | Why |
|---|---|---|---|
| U1 | How zelk attaches. | An extension using `chrome.debugger` and the authenticated loopback link. Native Windows relays it over Chromium native messaging. | Tab-scoped debugging keeps the browser’s own bar and Cancel. |
| U2 | Which tabs. | zelk's tab group: tabs zelk opened, tabs the user shared, popups they open. Nothing else, not even listed. zelk closes only its own; shared ones are released. | The user decides what zelk sees by where a tab is, and can see it. |
| U3 | Approvals. (Changed by A5, then by A13: trusted tabs.) | Every acting call asks a person unless a user-written rule allows the site; the prompt offers the site for the session. Auto mode's reviewer never allows alone; `dont-ask` and headless refuse. Read-only calls ask nothing. | Real accounts: a wrong allow can't be undone. Per-site session grants keep a flow to one prompt. |
| U4 | Hard limits. | In the driver: no input into credential, OTP or card fields; their values hidden; only `http`, `https`, `about:blank`. | These are the cases code can see; the rest is the approval. |
| U5 | Privacy. (Changed by A1, A4 and A9.) | Off: evaluate, storage, route, heap, upload, downloads, emulate, and profile (Chrome refuses it, S3.1); coverage CSS only. Network: list only. The extension never forwards cookie, storage, `Fetch`, file-input, target-creating or heap calls, strips credential headers, post data and cookie lists from events, and blanks `DOMSnapshot`'s field values. | Each one off reads or changes what the user's session holds. |
| U6 | Names. | `user_browser_*`, separate from `browser_*`; both can be on. | Rules and approvals for the two can't be confused. |
| U7 | Lifecycle. | Never close the browser; release (detach, keep tabs) on stop, close, idle 30 min, session deleted; the user's stop holds until Resume; reconnect keeps tab numbers, refs go stale. | The browser and its tabs are the user's. |
| U8 | Holders. | One zelk process, one root session at a time, its subagents sharing. | One group, one approval story; two agents in one user's browser would trip over each other and the user. |
| U9 | WebSocket. | Our own, minimal, stdlib only, fuzzed, in `core/internal/wsock`. | No dependency in core for a few hundred lines; we own the framing as we own CDP's. |
| U10 | Distribution. | Unpacked, written by `zelk browser extension`, fixed ID from the manifest's key. Web Store after a release. | Pre-release; no store review to wait on. |
| U11 | WSL2. | The Linux-generated extension in Windows dials WSL2 loopback directly. | Uses mirrored networking or WSL’s localhost forwarding without a Windows relay. |
| U12 | Pairing. | A one-time code, ten minutes, five tries, authenticating an X25519 exchange; the derived key proves both sides on every connection. After opencode's browse. | Easy to type, nothing long-lived on screen, and a stolen code is useless once used. |
| U13 | Handoff. | `user_browser_handoff`: the user does a step in the tab and ends it in the extension's UI, which a page can't reach. Bot challenges are only handed over. After opencode's browse. | Sign-in and CAPTCHAs are the user's; the agent needs a way to ask for them and know when they are done. |
| U14 | Emulate? | On tabs zelk opened only, without locale and time zone (Chrome refuses those). | Checking a signed-in app on a phone or in dark mode is common; a tab the user shared is never changed under them. |
| U15 | Network headers? (Bodies changed by A4.) | Shown, with credential headers removed and any header whose name looks like a credential blanked. Bodies and post data stay off. | Debugging the user's own app needs status and headers; bodies hold the most private data. |
| U16 | Where zelk's tabs go? | A collapsed group titled `zelk` in the last-used window, as opencode's browse does. | Visible, out of the way, one click to look. A window of its own would hide what zelk does. |
| U17 | Ask before reading after a navigation? | No: the navigation was approved, and reading is what it was for. | One prompt per site, not two. |
