Pankaj Garkoti

GitHub pages

View My GitHub Profile

Teaching the browser to the agent

I ran the same form fill three times last week without the model in the room. One process, one websocket to the agent Chromium on 127.0.0.1:9222, a stored script, and one line on the bus when it finished. The --trace output was the whole proof: every CDP frame in both directions, timestamped, with nothing else in it. That is the part I keep coming back to, because everything before it cost a model call per button.

The setup around it is magi, the Fedora/Hyprland install where the main interface is one orchestrator agent in tmux. The browser piece has two halves. The senses are browser-bus, which runs small probe scripts inside matching tabs in an isolated world and turns what they see into orch-bus events. The muscle is magi-reflex, built in PR #8: a flow recorded once, replayed forever, with no model on the replay path. The contract lives in docs/magi-reflex.md, and everything below is my reading of that document against the code that implements it.

The thesis predates magi. In March I built FlowPilot: explore a site once with an agent, compile scripts that replay it without LLM calls, hand the live browser to a human over CDP at a login or a CAPTCHA. Reflexes are that thesis moved inside the house, with a registry, a lifecycle, and guards that were written down as law after things broke on the 24th and 25th of November.

A reflex is a JSON document. It names its domain, its entry URL, its inputs, and its phases. The clearest example is the practice reflex local-fill-form, which serves a tiny page from the repo’s own testpage directory over python3 -m http.server on 127.0.0.1:8765, then fills name, email and message, uploads one small file, submits, and verifies the echoed values. Four phases: fill, upload, submit, verify-echo. Each phase carries the same anatomy, and the anatomy is the point.

Every phase has five things. A target_assert, a small script that proves the exact intended target exists before anything acts. A reflex_script, plain JavaScript that does the step, with ARGS for the run’s inputs and helpers on h: click, clickAt, focus, text, key, eval, files, sleep, now. A verify_script that proves the step worked and never acts — it reads the DOM the way a probe reads it. A steady_rule for when the page has settled enough to trust the verify. And timeouts: a per-phase budget plus a verify poll with interval_ms and timeout_ms that retries the verify instead of failing on the first miss.

The fill phase shows the discipline at its most boring, which is where I trust it most. Its target assertion is await h.eval('!!document.querySelector("#test-form") && !!document.querySelector("#name")'). Its reflex script focuses each field, sets the value, and dispatches input and change events. Its verify reads the three field values back and compares them to ARGS, returning {ok, why} with the mismatch serialized into why when they differ. Nothing clever. The script does one thing, the verify proves it, and the proof is a value comparison, not a screenshot that looks about right.

The runner that executes this is runner.py, and it is deliberately generic: all site knowledge lives in the reflex document, so the next reflex is new JSON, not new code. magi-reflex run NAME --args '{…}' opens its own tab — never touches another — navigates to the entry URL, and per phase enforces the entry-domain lock, runs target assertion, then the reflex script, then steady, then verify, then closes its tab on every exit path. The CLI surface in cli.py is ls, show, suggest --url, install, run, seal, lease, dogma. Success emits one bus line with elapsed milliseconds; any failure stops the run and emits one line, magi-reflex <name> FAILED at <phase>: <why>. The store records per-phase and run audit rows with zero_model_calls=1, pruned to the last 100 rows per reflex name.

The transport underneath is cdp.py, a stdlib-Python websocket client ported from the browser-bus connection pattern: endpoint discovery through /json/version, id and event dispatch, the same shape as the JavaScript side. Scripts run in an isolated world with a helper binding channel, __mrCmd, backed by trusted CDP input — Input.insertText, real mouse clicks at the element’s center, real key events — not synthetic DOM events where it matters. The click helper re-finds the element fresh on every try, because a re-render between find and click cost a run on the 24th and now costs one retry instead. The verify loop retries for up to its timeout, because message sync waits and slow renders are normal and the first check is rarely the honest one. Verify always runs in the runner’s own tab, and the tab closes only after the whole phase list ends.

Four guards decide what a reflex may never do, and all four are enforced in code, not advised in prose.

The first is the pre-action target assertion. Every phase must carry target_assert, and the runner refuses a reflex that is missing one. The assertion runs before the phase types or clicks anything. No target, no action. This is the structural fix for the oldest failure in browser automation: acting on an element that is almost the right one.

The second is the entry-domain lock. After navigation and during each phase, the runner compares the tab’s origin against the reflex domain and aborts if it leaves. A redirect to somewhere unexpected ends the run instead of being followed. Reflexes never act on messaging or social surfaces; that exclusion is a check in the loop, with the same instinct as the event bus guard from PR #1, where untrusted page text is framed as data and the dangerous action is refused rather than detected.

The third is the harmless-surface allowlist in store.py: 127.0.0.1, localhost, example.com, httpbin.org, the-internet.herokuapp.com. Before a run opens a tab, the reflex domain is checked against that list. Outside it, with owner_registered=0, the run is refused with one exact bus line — magi-reflex <name> REFUSED: domain <d> not owner-registered — phrased so operators and tests can key on it. With owner_registered=1 the owner has explicitly armed the reflex, and the exact entry URL is still required. The other two practice reflexes show what the allowlist is for: httpbin-submit fills the public form at https://httpbin.org/forms/post and verifies the echoed JSON contains our values; theinternet-login logs in with the demo credentials printed on the page itself and verifies the success flash. Nothing touches a real account.

The fourth is the credential rule. Reflexes never learn or run flows that type passwords, OTPs, or solve challenges. Phases like that end with an ASK OWNER handoff. This is FlowPilot’s CDP handoff carried over unchanged: the moment the page asks for the owner’s identity, the machine stops and the owner gets the live browser.

The registry holding all of this is SQLite with write-ahead logging at ~/.local/state/magi/reflexes.db, busy_timeout 10 seconds like orch.db, shared across tabs and agent instances. The schema is two tables, and the statuses are a lifecycle, not labels. candidate means new, never replayed successfully. active means proven by at least one successful replay, and only active reflexes are offered by lookup. stale means the network signature drifted; replay refuses and lookup stops offering it until it is re-sealed. broken means demoted after consecutive failures — two in a row, so a single flake does not kill a working flow — and broken reflexes are never offered. A regenerated script for an active reflex waits in the candidate column as a full next-version document and never clobbers the serving one; the next successful replay promotes it. lease_until and lease_by give a learn-exclusive lease so two agents never re-learn the same page concurrently, and leases expire on their own.

Recorded scripts rot. Sites redesign, endpoints move, and most replay tools rot silently: they click where the button was and report success. Reflexes rot loudly, through the drift detection in signature.py.

A phase may declare a net_filter: a positive list of URL substrings or globs for the API calls that actually matter, counting only Document, XHR and Fetch requests. While the phase runs, from the action through steady state, the runner records those requests, drops the query string and fragment, and normalizes opaque path segments — numbers, UUIDs, long hex or base64-ish ids — to :id, so a fresh upload id does not look like drift. The ordered METHOD /path lines are hashed with sha256. A filter of [] means the phase should make no matching call at all.

The signature stays null until magi-reflex seal NAME captures it from a verified replay. Once sealed, every replay compares the observed signature before verify is trusted. A mismatch fails the phase as STALE and emits one bus line with expected and observed counts. The reflex becomes stale: run refuses it and suggest no longer offers it. seal runs the flow again in capture mode — verify still gates it — writes the fresh signatures, and returns the reflex to active. Re-sealing is signature re-learning only. An agentic re-learn of a changed script is a later slice, deliberately: the machine tells you the page changed and waits. It never flails at a redesign, clicking hopefully.

The filters must stay narrow, and the document says so plainly, because the measurements behind it are blunt. An unfiltered ordered hash of one app entry fired 376 XHR and fetch requests, with ids changing every load. That is noise, not a signature. The positive filter is what turns traffic into evidence.

Between acting and verifying sits the steady question: when has the page settled enough that verify is worth running? Three candidates were measured on real pages with magi-reflex dogma, and the results are in the repo at dogma-2026-11-25.json, implemented in dogma_filter.py: DOM-stable (no mutation for quiet_ms), network-quiesce, and fixed delay. DOM-stable at quiet_ms=700 was safe on the measured loads. Network quiesce false-settled on chatty single-page apps — one measurement showed hundreds of requests arriving after a 1.2-second quiesce fired — and fixed delays fired before content existed. The default steady rule is DOM-stable, with a timeout backstop, and verify is the real authority regardless: a steady timeout proceeds to verify, and verify decides. The offline suite in test_offline.py pins this behavior without a browser, and the matrix run of 27 November records where the live harness still hurts.

That ordering — verify over steady, refusal over detection — is the consistent choice across the whole bus-and-reflex stack. The bus guard scores injection patterns and quarantines the full text, but the delivery gate itself is a refusal: no typing into a busy pane, no typing over a half-written input, with the poll interval moved from 2 seconds to 15 in PR #11 once delivery went event-gated and change-only. The prompt-API path in PR #9 needed no draft guard at all, which is why its logging fix in PR #12 is a logging fix and nothing more. Urgent delivery in PR #10 and the install-layer fix in PR #13 are the same kind of work: narrow the path, name the failure, keep the audit. The default-agent change in PR #7 matters here because the idle gate reads each agent’s own state — opencode’s local server API, Claude Code’s session files, Codex’s rollout files — and the gate is only as honest as that read.

What ships, then, is record once, replay forever, refuse loudly. Replay is agent-assisted only at author time. The run path has no model on it, and the claim is not in the architecture diagram but in the database: per phase, per replay, zero_model_calls=1, with the trace to check. What does not ship yet is named honestly in the doc: the agentic learn listener, script re-learn, and arming on bus events come later. The practice reflexes stay on harmless surfaces until then.

Four years ago I built a bot people talked to. Three years ago, one assistant with fourteen specialists behind a router, and a search service whose cutoff adapted per query instead of trusting a fixed number. Two years ago, the agent loop with its wishlist item about checking a long task without interrupting it — which the bus now answers from the other side, delivering only into idle with an empty input. This year, workers in tmux windows, probes in the signed-in browser, and now the muscle that acts in it. The senses watch, the muscle replays, the bus carries one line, the ledger remembers. Each piece does only what it can prove, and says which part is next.