Documentation
From docs/cleanup.md · e31dc91 · Built 2026-11-17
Cleanup has two owners: the runner and the main session. Follow the steps below after every browser job, including a failed or stopped run. The cleanup command handles leased processes; tabs, other shell tasks and scratch files also need their owner's checks.
Cleanup steps
Record ownership in the brief: existing user tabs, tabs opened for the job, process IDs, scratch paths and the evidence handoff path. Keep existing user tabs and the user's browser profile open.
The runner completes steps 1-5 at the end of every run, on success, failure or a reached bound. Save evidence at the handoff path first. Main completes steps 6-9 after the runner reports, before calling the task done.
- Runner: close run tabs. Close every tab this run created, plus any tab the brief says main opened for this run. Closing the run's tabs ends the browser control. The extension's control banner goes with the last run tab; closing the last pane tab closes the pane. Closing a tab with the Chrome extension's
tabs_close_mcpclears the pick, so close run tabs once at the end, never mid-task. Keep tabs the user already had open. - Close the in-app Browser pane if this run opened it and nothing else uses it. Closing its last tab closes the pane. Closing a tab in the in-app Browser pane keeps its pick.
- Stop anything this run started from the shell outside
spawn, including background commands, scripts and watchers. Delete run-owned scratch files, keeping evidence at the handoff path for main. - Use
tabs_contextortabs_context_mcpto confirm no run-owned tab remains. Check processes started outsidespawn, for example withpgrepscoped to what the run started, and confirm they have ended. The next step checks leased processes. If no process was started, report the initial and final resource snapshots. A cleanup claim needs these checks; report an unavailable check asUNVERIFIEDwith the remaining tab or process IDs and paths. - Run
npx --yes lean-browser-use cleanup --applyas the last command. Copy itscleanup:line into the report, alongside the tab and process checks and any pending IDs. - Main session: close remaining job tabs. Close any tab main opened for this job that the runner did not close, including a tab used to pick or identify the browser profile. Closing the run's tabs ends the browser control. The extension's control banner goes with the last run tab; closing the last pane tab closes the pane. Keep existing user tabs open.
- Stop every background task, monitor or watcher main started for this job, including any local preview or dev server.
- Run
npx lean-browser-use doctor. Exit 1 can indicate leftover leased processes: runnpx lean-browser-use cleanup --applyand re-check withnpx lean-browser-use doctor. Resolve any other reported health failures before calling the task done; retain unavailable checks asUNVERIFIED. - Verify the runner's saved evidence and cleanup report, then delete the handoff scratch. Keep it available until verification is complete.
The stop gate
The stop gate is on by default. PostToolUse touch records browser actions and successful closes for Chrome and the in-app Browser pane. Probes and desktop tools do nothing. State is separate for the main session and each subagent. It stores timestamps, counts and a session hash, not page text or tab IDs, in the selected config directory's lean-browser-use/state/use folder. LBU_STATE_DIR overrides the state root. State older than a day is pruned when a hook accesses it.
At Stop, an action since the last successful close makes a surface dirty. The gate blocks once and names the close tool: tabs_close_mcp for Chrome or tabs_close for the pane. Close only run-owned tabs. Closing them ends the browser control. Tabs the user already had open stay open. SubagentStop applies the same check only to aun-browser-runner and its own state. Stop waits when the payload lists background tasks.
The hook prints a block decision but never closes a tab or ends a process itself. On the repeated Stop, including stop_hook_active: true, it resolves the warning and stays silent. It cannot block twice for one dirty stretch. A new action re-arms it. Resolution is not proof of closure: keep the tab probes in the cleanup steps.
If the user must act on a tab, run:
npx lean-browser-use keep --reason "Review the prepared form"
Then name what stays open and why in the reply. keep holds every recorded surface of the session, including its subagents. The session defaults to the environment; use --session ID outside it. --claude-dir DIR selects the config directory. A later action clears holds on that action's main or subagent key.
Install with --no-stop-gate to omit the touch and stop-gate registrations, removing those registrations on a reinstall. The hook files remain installed for inspection. --no-hooks --no-stop-gate also omits them from the printed paste snippet. Uninstall removes owned registrations and unchanged hook files.
These hooks depend on Node and the matching tool payloads; malformed input or an unavailable state path fails open. doctor checks malformed-payload behavior and reports dirty surfaces older than ten minutes. Run it by hand after cleanup. There is no background watcher. The hook files and settings template are the source of truth.
Process leases
A lease is a small file that lean-browser-use spawn writes for each process it starts. The cleanup command acts on leases and on nothing else. Use spawn for every browser or helper process the run needs.
Start a process with a lease
npx lean-browser-use spawn -- chromium --headless --user-data-dir=/tmp/run-profile --remote-debugging-port=0
spawn starts the command detached, then records the process id, its start time, its exact command line and the Claude Code session id. It prints one line and returns. A command that fails the checks below is refused before it starts, and a process whose lease cannot be written is stopped again.
| Option | Effect |
|---|---|
--session ID | Session that owns the lease. Defaults to the session id Claude Code puts in the environment. |
--run NAME | Optional name, so cleanup --run NAME can end one run's processes. |
Clean up
npx lean-browser-use cleanup # dry run: lists what would end
npx lean-browser-use cleanup --apply # ends it and prints one summary line
The summary line reads cleanup: tabs_closed=1 ended=chrome:9 left=0. It counts the page tabs closed through the leased Chrome's own loopback debugging port, the processes ended by name, and the leased processes still alive. Tabs are closed only when lsof confirms that the leased Chrome tree is the listener on that port; otherwise the processes simply end.
| Option | Effect |
|---|---|
--apply | End the processes. Without it nothing is touched. |
--all | Every lease. Without --session, a run inside Claude Code covers its own session; a plain terminal covers all. |
--session ID / --run NAME | Narrow the scope. |
--json | Print the result as JSON. |
| Exit | Meaning |
|---|---|
| 0 | Dry run, or every leased process ended. |
| 1 | A leased process is still alive, a lease was refused, or the process list could not be read. |
| 2 | Usage error. |
What it ends
A process is ended when all of these hold:
- A lease names it, in a lease directory only your user can write.
- The live process has the same id, start time, command line and owner as its lease. A recycled process id fails this check, and its stale lease is cleared. The check repeats right before each signal.
- It passes the signature check, judged on the running command line, since wrappers and interpreters can re-exec. Chrome needs
--headlessor--remote-debugging-port=Nand an explicit absolute--user-data-dirthat is not a real browser profile and does not contain one. Other commands are leased as helpers. - It is not an ancestor of the cleanup run itself.
Its children go first. Each process gets SIGTERM, then a 3 second wait, then SIGKILL only if the same process (same id, start time and command line) is still alive.
What is left alone
- Your normal Chrome windows and profile, and any Chrome without automation flags.
- Any directory under the real Chrome, Chromium, Edge, Brave, Vivaldi or Opera profile roots.
- A Chrome or desktop app found below a leased helper that lacks automation flags, uses a real profile, or lives outside the helper's own bundle: it stays running and the line reports
kept_other_chrome=N. - Desktop app executables, other browsers, and processes with no lease.
- Processes of other users.
Trust
Lease files are mode 0600 in a directory only your user can write, and a lease with looser permissions is ignored. A lease names a process; it never replaces the live checks above. Anyone able to write inside that directory can already signal your processes directly, so the lease directory is the boundary to protect.
Hooks
The installer registers these additive cleanup entries, all removed by uninstall:
| Event | Scope |
|---|---|
SubagentStop, matcher aun-browser-runner | The session's leases when the runner stops. |
| Stop | The session's leases at the end of a turn, unless a subagent is still running. |
| SessionEnd | The session's leases when the session ends. |
PostToolUse touch | Browser actions and successful closes, per session and subagent. |
Stop stop-gate | One reminder to close dirty main-session browser surfaces. |
SubagentStop stop-gate, matcher aun-browser-runner | One reminder for that runner's dirty surfaces. |
Runners that work in parallel inside one session share its scope: when one stops, the hook ends the session's leases. Give each its own --run NAME and clean with cleanup --run NAME when their helpers must outlive one another.
The lease cleanup hooks read session_id (and agent_type for SubagentStop) from the hook payload and end that session's leases. All hooks exit 0 on every path. Only the stop gate can request a block through JSON on stdout. A malformed payload does nothing. doctor runs the hooks against a malformed payload to prove this.
Check for leftovers
npx lean-browser-use doctor lists leased processes still running, with their age and process count, and exits 1 when any exist. Run cleanup --apply to end them. LBU_LEASE_DIR moves the lease directory; the default is ~/.local/state/lean-browser-use/leases.
The open-surfaces check also exits 1 for recorded dirty surfaces whose last action is older than ten minutes. Close the run's tabs, or use keep --reason with their owning session ID. Kept surfaces do not count.
From docs/guards.md
Guards for browser work
The guards turn common mistakes into a prompt to choose a better next step. They receive Claude Code hook JSON on stdin. Exit 0 allows a call; exit 2 blocks it with a message for the agent. The non-blocking nudge suggests batching.
What each guard does
| Guard | Behavior |
|---|---|
| aun-pick-guard | Requires a browser pick for the current session before page actions. Probe tools remain available. |
| aun-retry-guard | Stops repeated waits, reloads, and fruitless reads per run and tab. |
| aun-batch-nudge | Suggests a browser_batch after a streak of 3 single actions. |
The pick guard records successful select_browser or switch_browser results. Page reads count as actions. Closing a tab with the Chrome extension's tabs_close_mcp clears the pick on PostToolUse, so close run tabs once at the end. Closing a tab in the in-app Browser pane keeps its pick. A missing session id blocks because a pick needs a session key. A runner uses its own session and may reselect only the deviceId in its brief. For the in-app Browser pane, record its explicitly selected target with:
node hooks/pick-guard.mjs --pick '<profile label>' --session '<session id>'
node hooks/pick-guard.mjs --reset --session '<session id>'
The retry guard caps cumulative waits on a tab at 60 s by default (LBU_WAIT_CAP_SECONDS changes it). It blocks the third consecutive navigation to the same URL. After two fruitless reads, the next wait or navigate and a third identical read are blocked. A different query is a new approach. Another origin, a targeted click or type, or changed read text resets the counters. For supported native tools, the third identical attempt after two identical errors is blocked. Probe calls remain available.
The nudge shares its streak across supported browser and native actions. A probe or browser_batch resets the streak. The nudge informs and always allows.
Registration
The installer merges hooks.settings.json, replacing ${HOOKS_DIR} with the installed path. Browser matchers cover claude-in-chrome, Claude_Browser, and Control_Chrome. Native matchers cover computer-use and cua-driver.
| Event | Tools | Script |
|---|---|---|
| PreToolUse | Browser tools | pick-guard.sh |
| PreToolUse | Browser and native tools | retry-guard.sh |
| PostToolUse | Chrome extension select_browser, switch_browser, and tabs_close_mcp (clears the pick; close run tabs once at the end); the in-app pane keeps its pick | pick-guard.sh |
| PostToolUse | Browser and native tools | retry-guard.sh |
| PostToolUse | Browser and native tools | batch-nudge.sh, timeout 10 s |
| SubagentStop (runner), Stop, SessionEnd | The session's leased processes | cleanup.sh, timeout 20 s; see cleanup |
State is keyed by session for picking, and by agent run plus tab for retries. $LBU_STATE_DIR overrides the state directory; the default is under the Claude config directory's lean-browser-use/state. State files use mode 0600 and the directory uses 0700. Retry state is pruned after 24 h.
Try a payload
From the repository root, this page action should block with exit 2 because its isolated session has no pick:
state_dir=$(mktemp -d)
printf '%s\n' '{"session_id":"demo","hook_event_name":"PreToolUse","tool_name":"mcp__claude-in-chrome__read_page","tool_input":{"tabId":"demo-tab"}}' |
LBU_STATE_DIR="$state_dir" sh hooks/pick-guard.sh
echo "$?"
rm -rf -- "$state_dir"
Run node --test test/ for allow, block, reset, fail-open, and RED-proof fixtures. The RED-proof cases confirm that an always-allow stub cannot satisfy the blocking expectations.
Fail-open behavior
Each shim locates its sibling script and passes through only the intentional blocking exit. Missing Node, missing script files, malformed input, or state failures allow the call. This keeps a broken guard deployment from blocking the browser itself. Fail-open protects availability; it does not prove the guard is healthy. Use npx lean-browser-use doctor after installation and inspect failures before relying on enforcement.
From docs/PROVENANCE.md
Provenance
Own tools and concepts
| Public name | Contribution |
|---|---|
| aun-web-use | The browser process, packet briefs, route table, verification, and cleanup practices. |
| aun-runner | Fresh-context execution, shipped as aun-browser-runner. |
| aun-chrome | Logged-in work through Claude in Chrome on the profile the user selects. |
| aun-pick-guard | Session-bound browser selection, implemented fresh as public code. |
| aun-retry-guard | Bounded retries and waits, implemented fresh as public code. |
| aun-batch-nudge | Advice to group predictable actions, implemented fresh as public code. |
| aun-screen | Optional screening of fetched text for prompt-injection attempts. |
| aun-keep | Optional storage of long output by id with a bounded view. |
| aun-squeeze | Shell-output compression practice inspired by rtk. |
| aun-privacy-gate | Public tree, filename, and history checks in scripts/gate.mjs. |
| aun-acceptance | Observable success checks in each brief and verification against the artifact. |
| aun-cross-review | Review by a different model family from the writer. |
The method and templates are generalized rewrites. The guards, installer, and meter are fresh public implementations. The reader and search companion adapt the author's code to public configuration and command contracts. The reader accepts an explicit stdin compiler command; its extraction design reimplements the compile-once idea from scratch.
The sibling lean-computer-use carries aun-desk-use for native apps.
Public upstreams
The Jev research client, typesafe-sdk, and browser-use/jev-ultrafast informed packet and index-choice techniques. Crawl4AI provides fetching and text extraction. SearXNG supplies the optional search service. Anthropic's Claude in Chrome supplies the connected browser tools. The compile-once idea comes from fetchapi.co. trycua/cua supplies the sibling's native-app driver; rtk informed shell-output compression. Keep a Changelog and Contributor Covenant inform repository conventions.
See CREDITS.md for links, licenses, and the contribution of each upstream. A credit describes influence or use and never implies endorsement.
Evidence boundaries
proof/results.json holds package measurements. Generated rows carry a command, measurement date, and expiry. The 20 paired benchmark rows (ids starting paired_) are static records copied or derived from proof/benchmark.json, carry the measurement date and no expiry by the owner's ruling, and are never re-measured by the proof script. The local meter compares a user's own transcripts. Saved reader fixtures establish offline extraction behavior; live page values need a current fetch and independent verification.
From CREDITS.md
Credits
This package builds on public tools and techniques. Credits describe contribution and use; they do not imply endorsement.
| Upstream | License or terms | Contribution |
|---|---|---|
| trycua/cua | MIT | Background native-app driver used by the sibling lean-computer-use. |
| Jev research client / typesafe-sdk, source | MIT | Index-choice and packet techniques. |
| browser-use/jev-ultrafast | MIT | Packet ideas for compact browser work. |
| Crawl4AI | Apache-2.0 | Fetching inside the reader and the text-extraction step. |
| SearXNG | AGPL-3.0 | Optional search container. This repository ships configuration and a container reference, not SearXNG code. |
| rtk | Apache-2.0 | Shell-output compression, called aun-squeeze in the optional practice. |
| fetchapi.co | Idea credit; no upstream code copied | The idea of compiling a page extractor once and running later reads as code. This reader reimplements the idea from scratch. |
| Anthropic's Claude in Chrome | Anthropic service terms; proprietary integration | Browser access to the profile the user selects, including logged-in pages. |
| Keep a Changelog | MIT | Changelog structure. |
| Contributor Covenant | CC-BY-4.0 | Conduct guidance linked from this repository. |
The package's own code and generalized method text are MIT licensed. Optional services and tools retain their own licenses and terms. See provenance for the public names used for the author's concepts.
hook
Pick guard: claude-in-chrome
Records a successful browser selection for the current session and requires that pick before page actions. Probe calls remain available, a missing session id blocks, and closing a supported tab clears the pick. An explicit pane marker can record or reset a session pick. Malformed payloads and state failures allow calls, so doctor is needed to check guard health.
node hooks/pick-guard.mjs --pick 'Work' --session 'demo'node hooks/pick-guard.mjs --reset --session 'demo'hook
Retry guard: hooks
Bounds cumulative waits per run and tab, repeated navigation to the same URL, fruitless reads and identical native errors. A targeted action, changed origin or changed read text resets relevant counters. Probe calls stay available; malformed input and state failures allow the call. A block returns its reason so main can choose a new approach within the brief.
hook
Batch nudge: browser-automation
Shares a streak across supported browser and native post-action events and suggests returning fields together when the streak reaches its threshold. A probe or browser_batch resets the streak. The suggestion is non-blocking and always allows the next call, including when input is malformed or state is unavailable.