# Automating the user's browser

The second stage of [the user's browser](/internals/user-browser/): zelk writes
and runs scripts in the user's pages, watches pages and wakes when
something happens, pulls data out of them for other programs, and acts
the way a person does. Read that design first; this one changes parts
of it, named below.

The extension link is available on Linux and macOS, including a WSL2
host reaching a Windows browser. The native Windows CLI supports zelk's
managed headless Chrome. Native extension pairing and linking are a
separate deliverable.

## Why

The first stage serves checking and doing tasks in a signed-in page,
and sets its limits for that: no page script, no data out, an approval
for every site. Automation needs more, and those limits stop it:

- **Getting data out.** Pull a table, a feed or a whole site's listings
  into a file, a database or another program.
- **Watching.** "Look at my trading charts and tell me when you see an
  opportunity": a script in the page notices a condition and wakes the
  agent, which looks and tells the user.
- **Consolidating.** Two or three services that serve related things,
  gathered into one place the user looks at.
- **Less friction.** On a site the user trusts, zelk works without
  asking.

opencode's browse (prior art in the first design) already allows page
script and data out. This stage takes that, keeps what protects the
user's accounts, and drops browse's remote mode (out of scope).

## What changes

| | First stage | This stage |
|---|---|---|
| Page script | none | `user_browser_evaluate` in trusted sites (A1) |
| Watching | none | `user_browser_watch`: a script that wakes the session (A2) |
| Data out | snapshots and screenshots | results saved to files; response bodies in trusted sites (A3, A4) |
| Approvals | a person per site, per session | a tab is trusted once shared or its opening approved; nothing in it asks (A13); a trusted site opens tabs without asking (A5) |
| Unattended | never | only where the user's rules or hooks allow (A6) |
| Input | instant, exact | paced and placed like a person's (A7) |
| Detection | not considered | nothing on the page's globals; `Runtime.enable` traps in the tests (A8) |
| Cookies | never | values never reach the model; a session can be exported to a file with the user's click in the extension (A9) |

Kept: the tab group (U2), the credential guard and handoff (U4, U13),
the user's stop, the sealed link, refused schemes, and the extension's
method list as the limit on anything on the socket.

## Trusted sites (A5)

The approval prompt for an acting call on a site gets a third answer:

- **Allow once.**
- **Allow on this site for this session.**
- **Trust this site**: a lasting rule, `user_browser_*(domain:example.com)`,
  saved with the user's other rules.

On a trusted site every `user_browser_*` call runs without asking:
actions, `evaluate`, `watch`, response bodies, and opening a tab there.
Two things are never covered by trust: typing credentials (refused
always, U4) and exporting a session (A9, the user's click every time).

With trusted tabs (A13), a session a person attends doesn't need site rules to work
without asking: a tab the user trusted is enough. Site rules are what
let a run no one attends act (A6), and what lets a tab open on a site
without asking.

The trusted sites are listed, with when each was trusted, in the TUI's
permissions view, in `zelk browser status`, and in the extension's
side panel while zelk is connected. Each place can revoke one; the panel's
revoke goes to zelk, which owns the rules.

Trust is by registrable domain and scheme (`https://*.example.com`),
since one service's pages span its subdomains. A trusted domain's
subdomains a different party runs (a shared host like `github.io`) are
the public-suffix list's case: trust stops at a public suffix.

## Trusted tabs (A13)

Per-site approval (A5) alone would mean a prompt for each site a flow
reaches, such as a sign-in's redirect, and one in the TUI for a session
export on top of the user's click in the extension: with the sign-in
handoff, too much back and forth between the agent, the TUI and the
browser. So once the user trusts a tab, it is trusted, as in browse.

- **What trusts a tab.** Sharing it in the extension; approving the call
  that opens it (`user_browser_open` with `new_tab`, which the person
  decides, or a site rule allows); or being a popup a trusted tab
  opened. Every tab in zelk's group is one of these, so the group is
  the trusted set.
- **What trust allows.** Every `user_browser_*` call in a trusted tab
  runs without asking, in every mode but plan (which acts on nothing),
  and auto mode's reviewer isn't asked: the person decided when they
  trusted the tab. That includes `evaluate`, `watch` and
  `export_session`, whose own click in the extension stays (A9).
- **Trust follows the tab.** A trusted tab stays trusted wherever it
  navigates: across a sign-in's redirects, links to other sites, its
  own popups. The hard limits hold everywhere (U4: no credential input,
  only `http`, `https` and `about:blank`; A9: no cookie values).
- **What ends it.** The tab leaving the group (the user drags it out, or
  closes it, or zelk gives a shared tab back) and the user's stop. A tab
  still in the group when a later session starts is still trusted: the
  group is visible, and the user takes a tab back by taking it out.
- **What still asks.** Opening a new tab, unless a site rule allows the
  site, the user approved a tab on the site earlier in the session
  (`Approval.Site`, kept in the session's `TabSites` across rewinds), or
  a message of the user's in the session names the site
  (`permission.SitesIn`: any host written in a URL, as `localhost` or
  `catalog.localhost`, and the site a tab opened at that URL is on; a
  host name alone only under a public suffix, not one whose suffix is
  also a file extension such as `main.py`; a name in a URL's path or
  query isn't one); a call an ask rule the user wrote names. Deny rules and the human-only rules hold as for any
  tool. These exceptions hold only with a person attending; a headless
  run is decided as A6 says, by the user's allow rules or hooks.
- **Unattended** (A6) is unchanged: a headless or scheduled
  run acts only where an allow rule (site or tool) or one of the user's
  hooks allows, trusted tab or not, since no
  person is there and trust given in one session shouldn't spend an
  account in a run no one watches.
- **What the model is told.** With no prompt before a click, an action
  that can't be undone (paying, sending, deleting) is the model's to
  hold back: the skill tells it to do one only when the user asked for
  exactly that, and otherwise to stop and ask in the conversation. That
  is advice, not a gate; it is the cost of the decision, as in browse.

The tool marks it (`tool.WithTrustedTab`), the request carries it
(`permission.Request.TrustedTab`, built from the call's input, so replay
decides the same way), and the decision allows it at step 5 only with
a person attending. The driver keeps it honest: a tool reaches only
tabs in the group, and in the user's browser `open` opens a tab only
when the call says `new_tab`, so no call opens one unasked.

## Page script (A1)

`user_browser_evaluate(tab, origin, script, world, save)`:

- Runs `script` (an expression or an async function body) in the tab's
  page and returns its value as JSON.
- `world`: `page` (the default) sees the page's own JavaScript objects,
  such as a chart library's data; `isolated` sees only the DOM, which the
  page can't observe or tamper with.
- A `fetch()` from the page carries the user's session, so the services'
  own JSON endpoints are reachable with no cookie in zelk's hands.
- `save`: a file name (`rows.csv`, `rows.jsonl`, `rows.json`) to write
  the value to, instead of returning it. The model gets its size and a
  short preview: a scrape of thousands of rows doesn't go through the
  model's context, or to its provider. The file goes where zelk keeps the
  browser's files (its captures, as for traces), not into the workspace:
  a write there is decided by the file rules, and a page that steers the
  model mustn't get one past them by being trusted. A command copies it
  where it is wanted, decided as any command is.
- The origin is checked just before running, as for every act.
- The credential guard still holds for typing. A script can set a field's
  value itself; the skill says not to touch credential fields, and the
  tool refuses a script whose result is a credential field's value (the
  driver knows which fields are secret). This is a speed bump, not a
  wall: a script in a trusted site can do anything that site's own
  scripts can. That is the meaning of trusting it.

## Watching (A2)

`user_browser_watch(tab, origin, script, once, min_interval)` installs a
script that keeps running in the tab after the call returns:

- The script gets a `notify(value)` function. Each call wakes the
  session with the value, the tab and the time, the way a finished
  background job does; the agent then looks and tells the user.
- It runs in an isolated world by default, and `notify` exists only
  there, so the page sees no new global. A watch that needs the page's
  objects reads them through `world: page` (A8 says what that costs).
- It survives the page reloading or navigating within the trusted site:
  the script is installed for new documents too.
- `once` ends it after the first wake; otherwise it lasts until the
  session ends, the agent ends it (`user_browser_unwatch`) or the tab
  closes. The user's stop pauses it until they press Resume
  ([user browser](/internals/user-browser/)). `min_interval` (default 60 s) drops
  wakes that come sooner, so a noisy page can't spend the user's money
  on model calls.
- The script should react to the page changing (a `MutationObserver` on
  the price label, the page's own data feed), not poll: Chrome slows
  timers in background tabs (S3.2).
- A watch lives while zelk has its conversation open; its values reach
  the conversation as notices, through the inbox ([wakes](/internals/wakes/)).
- A session with a watch keeps the user's browser: the 30-minute idle
  release (U7) waits until its last watch ends. The panel and the TUI
  list each watch.
- zelk has to be running for anything to wake, with the TUI open or a
  long-lived session. Watches are kept in a file per session under `watches/` in the user
  browser's data directory, not the session's log, and reinstalled when
  the session resumes.
- **Gaps are told.** A watch that stops running without ending (the
  user's stop, zelk closed, the link to the browser lost) records when
  and why in its kept file. Its next wake after it is installed again
  names each such gap, the latest five, and says that changes then went
  unseen and its script started over, so the model doesn't take a value
  that doesn't follow the last for a change the interval held back, or
  the script's memory of "before" for the page's. A zelk that ended
  without saying records no start: the wake says only when it came back.
  A gap is told once.
- A watch is a wake source of its session ([wakes](/internals/wakes/), Sources). Its
  wakes are recorded in the source's inbox, so one whose session another
  host holds waits there and is admitted once, by that host or the next
  run. A wake that can't be recorded is tried again as the same wake; the
  watch's row says why it waits. A watch's last wake ends its source as
  it is admitted, and unwatching ends it without a run. A wake never
  makes a session: one deleted since the watch began ends the watch.

## Data out (A3, A4)

- **Files.** `evaluate`'s `save` (above) and the scraping skill write
  JSON, JSON Lines or CSV beside the browser's captures, which a command
  copies into the workspace for the user's programs and the code zelk
  writes.
- **Response bodies (A4).** On trusted sites, `user_browser_network` also
  gives a response's body, saved to a file or shown in part. It is how
  zelk finds a service's own API: which request returned the table it
  sees. Request headers keep their credentials removed (U15); post
  bodies are shown, with fields whose names look like credentials
  blanked.
- **The scraping skill.** A section of the `user-browser` skill: prefer
  the service's own API, then its JSON endpoints through `evaluate`'s
  `fetch`, then the visible page; save to files, not the transcript;
  follow pagination; wait for content, not time; re-check selectors when
  a page changes; keep to the pace a person would.

## Unattended (A6)

The first stage keeps real accounts out of unattended runs. With trust,
a scheduled or headless session (`zelk exec`, zelk's schedules) may act
in the user's browser only where the user's own configuration allows it:
a matching allow rule, whether it names the site or only the tool, or one
of the user's hooks (a `PreToolUse` allow, a `PermissionRequest`
approval). A trusted tab doesn't count; anything else is refused, as
`dont-ask` refuses, and read-only calls pass as in any mode. That is what lets a collector refresh every hour
while the user is away. The browser has to be open, with the extension
connected; a run that finds it closed fails saying so.

## Acting like a person (A7)

The driver's input stays exact in zelk's own browser. In the user's
browser it is paced, by default:

- **Pointer.** Moves along a curved path to a point inside the target's
  box, not its centre, with speed that rises and falls; a short rest
  before the press.
- **Keys.** One key event per character, at a varied pace, with longer
  pauses at word ends. No `insertText`.
- **Scroll.** Wheel events in steps.
- **Between actions,** a pause of a person's length.

The randomness comes from an injected source, so tests are exact. A
session setting (`pace: human | fast`) turns it off for the user's own
apps, where speed matters more.

## Not standing out (A8)

The extension's `chrome.debugger` doesn't set `navigator.webdriver`, and
the browser, profile, fingerprint and network are the user's own, which
already puts zelk in the strongest position against bot detection. What
gives it away is the driver:

- **`Runtime.enable`.** The driver turns it on for every tab
  (`tab.go`), and pages used to detect it (the console serialising an
  object whose getters the page watches). None of the known traps works
  in Chrome 157 or Brave (S4.3), so the driver keeps it, and
  the real-Chrome tests carry the traps: a Chrome that leaks it again
  fails a test, and the driver is then reworked to run without it
  (isolated worlds, evaluation by context ID).
- **Nothing on the page's globals.** Watch bindings live in isolated
  worlds; scripts run in the page's world only when asked.
- **Timing.** A7.

Some sites' terms forbid automated access. Acting like a person makes
that harder for them to detect, not allowed; what to automate on the
user's own accounts is the user's call, and zelk doesn't limit it.

## Cookies (A9)

Cookie values never reach the model. A script in a trusted
page can read `document.cookie` (what the page's own scripts can); the
`HttpOnly` cookies that keep the user signed in stay out of the model's
reach. In their place:

- `user_browser_export_session(site, to)` writes one site's cookies to a
  file where zelk keeps the browser's files (mode 0600, a cookie jar curl
  and Python read), never the workspace, for a
  collector that runs without the browser. (Putting them in a command's
  environment instead is left out: the file serves the same collectors.)
- **The user's click in the extension, every time.** The extension shows
  the site and asks; only its panel can say yes, so a compromised zelk
  can't take cookies alone. Trust doesn't cover it.
- The values go from the extension to the file, never into the
  transcript or to the model's provider.

**Why not let the model read them:** a session cookie is the account,
past the password and two-factor sign-in. In a tool result it goes to
the model's provider and into zelk's session log, and a page that steers
the model could carry it off whole. Scraping doesn't need it while the
browser is open: the page's own `fetch` carries the session.

**The limit:** a program zelk writes can read the exported file, and
could send it anywhere. The user's click on each export, and zelk's
usual review of commands that reach the network, are the guard.

**Not chosen:** a `user_browser_cookies` tool returning values to the
model on trusted sites.

## Downloads (A10)

Many services offer "Export CSV". The user's browser saves it to the
user's Downloads folder, which zelk doesn't read, and an extension can't
choose where a download goes or skip a Save As dialog (S4.8). So:

- `user_browser_download(tab, origin, url | selector, to)` fetches the
  export link inside the page, with the page's own session, and saves
  the response where zelk keeps the browser's files, not the workspace,
  whose writes the file rules decide. No dialog; Downloads untouched.
- A download a zelk tab starts some other way (a script that builds the
  file) is reported by the extension (name, size, where it landed), and
  zelk may read that one file, on a trusted site, when the browser saved
  it without asking. On WSL2 the Windows path is mapped (`/mnt/c/...`).
  This needs Chrome's `downloads` permission ("Manage your downloads").
- When the browser asks where to save, that dialog is the user's, and
  the tool says so.

## What still protects the user

1. **Trust is the user's, per tab** (A13): sharing a tab or approving
   its opening, never auto mode's reviewer. Lasting trust of a site is
   listed and revocable in three places, and is all a run no one
   attends may use.
2. **No credentials typed, ever,** and sign-in handed to the user.
3. **Session cookies never reach the model;** exporting one takes the
   user's click in the extension (A9).
4. **The tab group.** zelk sees only tabs it opened or the user shared.
5. **The extension's limits** against anything on the socket: tab scope,
   the method list, cookies only through the panel.
6. **The sealed link** and the pairing.
7. **The user's stop,** in the panel or on Chrome's bar, ends every
   action and pauses every watch until they resume.

What none of that does: a trusted tab runs what the model decides,
with no prompt before an action that can't be undone (A13); a trusted
site is open to anything its own
scripts could do, as the user, including reading what it shows and
calling its APIs; watches spend model calls when they fire; and data
saved to files is as private as the workspace.

## What the user's browser allows (S4)

The design rests on these properties of Chrome for Testing 157 and Brave,
driven through `chrome.debugger`; the two browsers agree on each. Each
has an ID that code comments cite.

| | Finding | What it means |
|---|---|---|
| S4.1 | `Runtime.addBinding` by `executionContextName` works without `Runtime.enable` **only if the isolated world exists first**; then `Runtime.bindingCalled` reaches zelk and the page's world sees no `zelkNotify`. A world made after the binding doesn't get it (unless `Runtime.enable` is on). | A watch makes its world, then the binding, then runs its script. |
| S4.2 | `Page.addScriptToEvaluateOnNewDocument` with `worldName` runs, but its new world has no binding, so after a reload or navigation the watch is silent. Made again by zelk (world, binding, script), it works at once. | zelk reinstalls each watch when the tab's document changes (`Page.frameNavigated`; `Page.enable` is no tell). A change in the few hundred milliseconds before that is missed. |
| S4.3 | None of four known `Runtime.enable` traps (an error's `stack` getter through `console.debug` and `console.log`, an object's getter, a node's getter) fired, with or without it, in either browser. | Chrome 157 no longer leaks it this way. See A8 below. |
| S4.4 | `Network.getResponseBody` and `Network.getRequestPostData` work; a page's own `fetch` carries the session. | A4 as designed. |
| S4.5 | `Network.getCookies` with the site's URLs returns its `HttpOnly` cookies with no `cookies` permission; `Storage.getCookies` and `Network.getAllCookies` (every cookie in the browser) also pass through `chrome.debugger`. `document.cookie` shows only the others. | The extension keeps both browser-wide calls refused and lets `Network.getCookies` through only for the tab's site, after the user's click (A9). |
| S4.6 | Paced input reaches the page as trusted events: 66 pointer moves, a click off the button's centre, keydown, keypress and input for each character at varied gaps. In a background tab a pointer move takes **5 s** without focus emulation and **16 ms** with it; keys take 1–2 ms either way. Chrome answers a pointer event once it has drawn a frame, and draws a tab behind the user's about once a second, so a paced path there takes a second a step: tens of seconds between the click on a field and typing, in both browsers. | The driver's focus emulation is required for paced input; in a tab Chrome still draws slowly, the pointer goes straight to its target, and a timing test holds it. |
| S4.7 | A watch in a hidden tab for an hour in Chrome for Testing, the page changing every 15 s: 239 wakes for about 240 changes (the last fell at the hour's end), the worst delay 5 ms. Chrome's background throttling slows timers, not a `MutationObserver` or the binding. | Watches react to changes, never poll; nothing more is needed for background tabs. |
| S4.8 | A tab can't choose where downloads go: `Page.setDownloadBehavior` is refused to extensions ("browser-level") and `Browser.setDownloadBehavior` doesn't exist for them. Brave asked where to save (a Save As dialog), and the extension's suggested folder (`downloads.onDeterminingFilename`) didn't skip it. Where the browser saves without asking (Chrome for Testing), `chrome.downloads` names the file and zelk read it. Fetching the export link inside the page returned the file's contents directly. | Hence A10. |

## Decisions

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

| ID | Question | Decision | Why |
|---|---|---|---|
| A1 | Page script? | `user_browser_evaluate`, page world by default, isolated on request; results can be saved to a file. Changes U5. | Automation and scraping need it; a page's own `fetch` reaches its data with the user's session and no cookie in zelk's hands. |
| A2 | Waking on a page's change? | `user_browser_watch`: an isolated-world script with `notify`, reinstalled on new documents, debounced, waking the session like a finished background job; it holds the browser past the idle release. | The user's trading example; reacting beats polling a background tab. |
| A3 | Data out? | Files where zelk keeps the browser's files (JSON, JSON Lines, CSV), which a command copies where they are wanted, not the transcript, and a scraping section in the skill. | Large data stays off the model's context and its provider. |
| A4 | Response bodies? | On trusted sites, saved or shown in part; post bodies with credential-named fields blanked. Changes U15. | Finding a service's own API. |
| A5 | Approvals? | A third answer, "Trust this site", a lasting rule by registrable domain; trusted sites ask nothing; untrusted ask a person as before. Listed and revocable in the TUI, `zelk browser status` and the panel. Changes U3. | Less friction where the user has decided; the same care where they haven't. |
| A6 | Unattended? | Scheduled and headless sessions act only where the user's allow rules or hooks allow. | Collectors that refresh while the user is away. |
| A7 | Input? | Paced like a person's in the user's browser by default (curved pointer paths, per-key typing, stepped scrolls, pauses), seeded for tests; `pace: fast` to turn it off. | Sites that watch behaviour. |
| A8 | Detection? | Bindings in isolated worlds; page world only on request. `Runtime.enable` kept, with the known traps in the real-Chrome tests (S4.3). | The traps no longer fire in Chrome 157 or Brave; a test catches it if they return. |
| A9 | Cookies? | Values never to the model; `user_browser_export_session` writes a site's cookies to a file with the user's click in the extension each time. Not chosen: a tool returning values on trusted sites. | A session cookie is the account; scraping in the browser doesn't need it. |
| A10 | Downloads? | `user_browser_download` fetches an export link in the page and saves it where zelk keeps the browser's files; other downloads a zelk tab started, on a trusted site, are read where they landed when the browser saved without asking; a Save As dialog is the user's (S4.8). | "Export CSV" is often the cleanest data; an extension can't skip the dialog. |
| A11 | Remote mode? | Out of scope. | zelk drives the user's own local browser only. |
| A12 | Kept? | The tab group, the credential guard and handoff, the user's stop, the sealed link, refused schemes. | They cost automation nothing and protect the accounts. |
| A13 | Approvals, again? | Trusted tabs: a tab is trusted once the user shares it or approves its opening, or a trusted tab opens it; nothing in it asks, wherever it navigates; site rules stay for opening tabs unasked, and unattended runs are decided as A6 says. Changes A5 and U3. | Per-site prompts mean too much back and forth; browse's model, with unattended runs kept to the user's own rules and hooks. |
