Skip to content

An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.

feat(cli): uninstall in one command, and let update replace its own stale copy

Shahriar4517fda29eae
diff --git a/README.md b/README.md
index 504f31b..6056007 100644
--- a/README.md
+++ b/README.md
@@ -41,7 +41,7 @@ Then open the side panel and say what you want.
You also need one agent CLI on your `PATH` and logged in — `claude`, `codex` or `agy`. Full prerequisites in the [install guide](docs/guide/install.md), which also covers [building from source](docs/guide/install.md#from-source).
-Later, `npx browsentic@latest update` refreshes the extension in place. The install path never changes, so your browser stays paired.
+Later, `npx browsentic update` refreshes the command and the extension in place. The install path never changes, so your browser stays paired. `npx browsentic uninstall` removes the lot.
## How It Works
diff --git a/docs/guide/install.md b/docs/guide/install.md
index 70eaf90..f2be3a1 100644
--- a/docs/guide/install.md
+++ b/docs/guide/install.md
@@ -56,12 +56,22 @@ npm i -g browsentic
### Updating
```sh
-npx browsentic@latest update
+npx browsentic update
```
-That refreshes the installed extension in place and restarts the daemon. The install path never
-changes, so your browser stays paired. Press ↻ on the Browsentic card at `chrome://extensions` to
-pick up the new build. See [Maintenance](maintenance.md).
+That replaces the command itself if the registry has something newer, refreshes the installed
+extension in place, and restarts the daemon. The install path never changes, so your browser stays
+paired. Press ↻ on the Browsentic card at `chrome://extensions` to pick up the new build.
+
+### Uninstalling
+
+```sh
+npx browsentic uninstall
+```
+
+One command for the daemon, both directories and the `npx` cache. It prints the plan and asks first.
+Remove the card at `chrome://extensions` yourself, ideally before running it. See
+[Maintenance](maintenance.md).
### Firefox
diff --git a/docs/guide/maintenance.md b/docs/guide/maintenance.md
index fc4fd92..b1c36c8 100644
--- a/docs/guide/maintenance.md
+++ b/docs/guide/maintenance.md
@@ -5,20 +5,35 @@
## Updating
```sh
-git pull
-yarn setup
+browsentic update
```
-Then reload the extension at `chrome://extensions` (↻ on the Browsentic card) and restart the
-daemon:
+That refreshes two things, in order: **the command itself**, then the extension it carries.
+
+The first half matters more than it sounds. `npx browsentic setup` does not put anything on your
+`PATH` — it runs the package out of npm's own throwaway cache, and npm names that directory after
+the spec it was asked for, records the version it resolved *the first time*, and reuses it forever
+without asking the registry again. So a machine set up with `npx` keeps running whatever version it
+first saw, and since the extension ships inside the package, `update` had nothing newer to install
+and reported "already current" every time. It now checks the registry, replaces the stale cache, and
+re-runs itself under the new version.
+
+`--no-self-update` skips the check, and a pinned `npx browsentic@<version>` is never upgraded past —
+a pin is a decision, not a stale cache.
+
+From a clone, `update` says so and leaves the checkout alone:
```sh
-browsentic restart
+git pull
+yarn setup
```
-Both steps are needed, for the same reason in two places: **nothing reloads itself.** Chrome does
-not auto-reload an unpacked extension, and a running daemon keeps the old build in memory until it
-is replaced.
+Either way the last step is yours: **nothing reloads itself.** Chrome does not auto-reload an
+unpacked extension, so press ↻ on the Browsentic card at `chrome://extensions`. `browsentic update`
+has already replaced the daemon; from a clone, `browsentic restart` is that half, because a running
+daemon keeps the old build in memory until it is swapped out.
+
+`browsentic status` names both versions when they disagree, and says which one to reload.
**Rebuild both halves together.** If only one side is rebuilt, `browsentic status` reports
`manifest: DRIFTED`. The daemon then falls back to the tools the browser actually has and tells
@@ -50,43 +65,51 @@ the fresh build.
## Uninstalling
-Four steps, and the order matters. Only the second one depends on how you installed.
-
-**1. Unpair the browsers and stop the daemon.**
-
```sh
-browsentic revoke # unpair every browser
-browsentic stop # stop the daemon
+browsentic uninstall
```
-`revoke` asks the running daemon to drop its session keys, so it has to come before `stop` rather
-than after. If you installed through `npx` and never installed the command permanently, these are
-`npx browsentic revoke` and `npx browsentic stop`.
+It prints exactly what it is about to remove and asks before removing any of it:
-**2. Remove the command**, if you have one on your PATH. This is the step that differs:
+| | |
+| --- | --- |
+| daemon | Whatever is *answering* on 8765–8767, not what the lockfile claims. Sessions are revoked through it first, so a connected browser is told it is unpaired rather than left to discover it |
+| state | `~/.browsentic` — pairing keys, config, approvals, logs |
+| files | `~/browsentic` — the unpacked extension, skills, site maps, screenshots, captured downloads |
+| npx cache | Every `~/.npm/_npx/*` directory holding a copy of the package |
-| How you installed | What to remove |
+| Flag | Does |
| --- | --- |
-| `npx browsentic setup` | Nothing. `npx` runs the package from its own cache and never puts anything on your PATH. |
-| `npm i -g browsentic` | `npm rm -g browsentic` |
-| From a clone | `yarn daemon:unlink`, which removes the global link `yarn daemon:link` created |
+| `--dry-run` | Print the plan and stop |
+| `--yes` / `-y` | Skip the confirmation. Required when stdin is not a terminal, since there is nobody to ask |
+| `--keep-skills` | Leave `skills/` behind. Nothing else has a copy of your site maps |
-**3. Remove the extension** at `chrome://extensions`.
+**Remove the card at `chrome://extensions` first.** That is the one step no command can do for you,
+and doing it afterwards leaves the browser holding a folder that is no longer there. It is also what
+clears recordings and held secrets, which live in extension storage rather than on disk.
-Do this *before* the next step. The folder Chrome loaded is `~/browsentic/extension/chrome-mv3`,
-which step 4 deletes — remove the directory first and the browser is left holding a broken card.
-Removing the extension also clears recordings and stored files, which live in extension storage
-rather than on disk.
+Two things it names but will not touch: the command itself (`npm rm -g browsentic`, or
+`yarn daemon:unlink` from a clone) and the entry in your MCP client
+(`claude mcp remove browsentic`). It also names, without deleting, any directory you pointed
+somewhere else with `screenshotDir`, `downloadDir` or `skillsDir` — you put those there.
-**4. Delete the two directories.**
+### Why the manual procedure was not enough
-```sh
-rm -rf ~/.browsentic ~/browsentic
-```
+It could not reach two of these, and both fail quietly:
+
+**The npx cache.** Deleting `~/.browsentic` and `~/browsentic` leaves it untouched, so the reinstall
+afterwards runs the same cached CLI and lays down the same old extension. It looks like the installer
+is broken.
+
+**An orphaned daemon.** `rm -rf ~/.browsentic` takes the lockfile with it, and the running daemon
+never notices — it holds its port for as long as the machine is up, and nothing that reads
+`~/.browsentic` can see it any more. `browsentic stop` now probes the ports instead of trusting the
+lockfile, so it finds that one too.
-`~/.browsentic` holds pairing keys, config, approvals and logs; `~/browsentic` holds the extension
-you just removed, plus skills, screenshots and captured downloads. If you set `BROWSENTIC_HOME`,
-the first one is wherever you pointed it.
+If you would rather do it by hand, the order is: `browsentic revoke`, `browsentic stop`, remove the
+card at `chrome://extensions`, `rm -rf ~/.browsentic ~/browsentic`, then delete every
+`~/.npm/_npx/*` directory containing `node_modules/browsentic`. `revoke` needs the daemon, so it
+comes before `stop`; the cache is the step people miss.
What those directories held is listed in [internals/state.md](../internals/state.md) — worth a look
before deleting, since `~/browsentic/skills/` contains any site maps you generated and any notes you
diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.md
index ef84c60..84c5072 100644
--- a/docs/guide/troubleshooting.md
+++ b/docs/guide/troubleshooting.md
@@ -28,6 +28,8 @@ Those three answer most questions. The daemon log also lives at `~/.browsentic/d
| "Load unpacked" cannot see `~/browsentic` | A Flatpak or Snap browser, sandboxed away from your home directory. Snap Chromium is the Ubuntu default | Grant it: `flatpak override --user --filesystem=~/browsentic com.google.Chrome`. Or install somewhere the sandbox can read: `browsentic setup --dir ~/snap/chromium/common/browsentic-extension` |
| The folder picker does not show `~/browsentic` | It is there; some pickers open elsewhere by default | macOS: press ⇧⌘G and paste the path. Linux: Ctrl+L |
| Updated with `npx`, but the browser still runs the old build | Chrome never auto-reloads an unpacked extension | `browsentic status` names both versions. Press ↻ on the Browsentic card |
+| `browsentic update` says "already current" forever, and reinstalling still lands on an old build | npm's `npx` cache serves the version it first resolved and never asks the registry again | `browsentic update` now replaces the cached command before installing. To clear it by hand, delete every `~/.npm/_npx/*` directory containing `node_modules/browsentic` |
+| Deleted `~/.browsentic`, but a daemon is still holding port 8765 | The lockfile went with it; the process did not notice | `browsentic stop` probes the ports rather than the lockfile, so it finds that one. `browsentic uninstall` does it as part of the sweep |
## MCP clients
diff --git a/docs/internals/state.md b/docs/internals/state.md
index aa856e5..81d95cc 100644
--- a/docs/internals/state.md
+++ b/docs/internals/state.md
@@ -29,6 +29,14 @@ Nothing lives in the repository.
| `approvals.json` | **Always on ‹host›** | One action + host per entry. Only short-circuits a `confirm` |
| `daemon.log` | The daemon | `browsentic logs`. Local [instant commands](../guide/features/instant-commands.md) never appear here, by design |
+## The one that is not yours
+
+`~/.npm/_npx/<hash>/` is npm's, not Browsentic's, but a machine set up with `npx browsentic setup`
+keeps the whole package there — CLI and extension payload both — and npm reuses it without ever
+re-checking the registry. It therefore behaves like state: it decides which version you run, it
+survives deleting both directories above, and it is why a reinstall could land on a months-old
+build. `browsentic update` replaces it; `browsentic uninstall` deletes it.
+
## The three exceptions
**Held secrets** never reach disk at all. A credential the sanitizer seals out of a page is kept in
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index 5d2edb2..ea39af5 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -5,7 +5,8 @@ browsentic <command>
```
With no command it prints usage. Most commands start the daemon if one is not already running;
-`status`, `stop`, `logs`, `token`, `tools`, `skills`, `approvals` and `downloads` do not.
+`status`, `stop`, `logs`, `token`, `tools`, `skills`, `approvals`, `downloads` and `uninstall` do
+not — an uninstall that started a daemon would be absurd.
---
@@ -14,7 +15,8 @@ With no command it prints usage. Most commands start the daemon if one is not al
| Command | Does |
| --- | --- |
| `browsentic setup` | Install the extension, start the daemon, print a pairing code |
-| `browsentic update` | Refresh the installed extension in place and restart the daemon |
+| `browsentic update` | Pull the newest build: the command itself first, then the extension, then restart the daemon |
+| `browsentic uninstall` | Stop the daemon and remove everything Browsentic wrote |
`setup` writes the extension to `~/browsentic/extension/chrome-mv3` and leaves you two steps: load
that folder at `chrome://extensions` with Developer mode on, and paste the code into the popup.
@@ -29,9 +31,30 @@ origin, so a versioned path would unpair the browser on every update.
| `--no-pair` | Install and start the daemon, mint no code |
| `--force` | Rewrite every file even when the installed build already matches |
| `--browser <name>` | `chrome` only for now. See [install](../guide/install.md) for the Firefox situation |
-| `--json` | Machine-readable result |
+| `--no-self-update` | Install what this copy carries, without asking the registry whether a newer one exists |
+| `--json` | Machine-readable result. Progress goes to stderr, so stdout stays parseable |
-See [guide/install.md](../guide/install.md).
+`setup` and `update` both replace the command itself when the registry has something newer, because
+the extension ships *inside* the package — a stale CLI installs a stale extension and says
+"already current". Under `npx` that lasts as long as the cache does, which is what made `update`
+look like it did nothing. A pinned `npx browsentic@<version>` is never upgraded past, and a source
+checkout is told rather than touched.
+
+### Uninstall
+
+| Flag | Does |
+| --- | --- |
+| `--dry-run` | Print the plan and stop |
+| `--yes` / `-y` | Skip the confirmation. Required when stdin is not a terminal |
+| `--keep-skills` | Leave `skills/` behind — site maps and hand-written notes have no other copy |
+
+It removes the daemon (found by probing 8765–8767, so an orphan whose lockfile was deleted is still
+caught), `~/.browsentic`, `~/browsentic`, and every `~/.npm/_npx/*` directory holding a copy of the
+package. It names, but will not touch, the extension card at `chrome://extensions`, the command
+itself, your MCP client's entry, and any directory you moved with `screenshotDir`, `downloadDir` or
+`skillsDir`.
+
+See [guide/install.md](../guide/install.md) and [guide/maintenance.md](../guide/maintenance.md).
## Pairing
@@ -84,7 +107,7 @@ configurations written against the older name keep working.
| Command | Does |
| --- | --- |
-| `browsentic stop` | Stop the background daemon |
+| `browsentic stop` | Stop the background daemon, whichever of 8765–8767 is answering |
| `browsentic restart` | Stop the daemon and bring up a fresh one |
| `browsentic --version` / `-v` | Print the version |
| `browsentic help` / `--help` / `-h` | Usage |
diff --git a/src/daemon/cli.ts b/src/daemon/cli.ts
index 2f4c0b4..40b1591 100644
--- a/src/daemon/cli.ts
+++ b/src/daemon/cli.ts
@@ -1,4 +1,5 @@
import { readFileSync } from 'node:fs';
+import { createInterface } from 'node:readline/promises';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { describeActions } from '@/lib/actions/registry';
import { AGENTS, AGENT_KINDS, isAgentKind } from '@/lib/agents/catalog';
@@ -10,19 +11,23 @@ import { forgetGrants, listGrants } from './agent/approvals';
import { clearDownloads, downloadDir, storedDownloads } from './downloads';
import { readAgentConfig, rememberExtensionDir } from './agent/config';
import { loadSkills, skillDirNames, uploadedSkillsDir } from './agent/skills';
-import { ensureDaemon, probeExisting } from './ensure-daemon';
+import { ensureDaemon, probeExisting, runningDaemons, stopDaemons } from './ensure-daemon';
import { install, InstallError, readStamp } from './install';
-import { clearLockfile, isRunning, logPath, readLockfile } from './lockfile';
+import { logPath, readLockfile } from './lockfile';
import { log } from './log';
+import { installKind } from './npx';
import { extensionDir } from './paths';
import { RemoteBridge } from './remote-bridge';
+import { upgradeCli } from './self-update';
import { createMcpServer } from './server';
+import { planUninstall, purgeNpxCache, removeAll } from './uninstall';
import pkg from './package.json';
const USAGE = `browsentic ${pkg.version} — hand your real browser to the agent you already run
browsentic setup install the extension, start the daemon, print a pairing code
- browsentic update refresh the installed extension and restart the daemon
+ browsentic update pull the newest build — the command itself, then the extension
+ browsentic uninstall stop the daemon and remove everything Browsentic wrote
browsentic pair issue a one-time code to type into the extension
browsentic status daemon, extension and agent state
browsentic sessions list paired browsers
@@ -74,6 +79,9 @@ switch (command) {
case 'update':
await setup(['--no-pair', '--restart', ...process.argv.slice(3)]);
break;
+ case 'uninstall':
+ await uninstall(process.argv.slice(3));
+ break;
case 'pair':
await pair();
break;
@@ -93,7 +101,7 @@ switch (command) {
await showStatus();
break;
case 'stop':
- stop();
+ await stop();
break;
case 'restart':
await restart();
@@ -221,28 +229,23 @@ async function showStatus(): Promise<void> {
if (!status.pairedBrowsers) console.log('\nRun "browsentic setup" to install the extension, or "browsentic pair" if it is already loaded.');
}
-function stop(): void {
- const lock = readLockfile();
- if (!lock) return console.log('No daemon lockfile; nothing to stop.');
- try {
- process.kill(lock.pid, 'SIGTERM');
- console.log(`Stopped daemon (pid ${lock.pid}).`);
- } catch {
- console.log(`Daemon (pid ${lock.pid}) was not running; clearing the lockfile.`);
- clearLockfile();
+// Stops what is *answering*, not what the lockfile claims. A daemon outlives a deleted
+// ~/.browsentic and goes on holding its port, and that orphan is the one people hit.
+async function stop(): Promise<void> {
+ const { stopped, stubborn } = await stopDaemons();
+ for (const daemon of stopped) console.log(`Stopped daemon (pid ${daemon.pid}) on 127.0.0.1:${daemon.port}.`);
+ for (const daemon of stubborn) {
+ console.error(`Daemon (pid ${daemon.pid}) on 127.0.0.1:${daemon.port} would not exit — kill it by hand.`);
}
+ if (!stopped.length && !stubborn.length) console.log('No daemon is answering; nothing to stop.');
+ if (stubborn.length) process.exitCode = 1;
}
async function restart(): Promise<void> {
- const lock = readLockfile();
- stop();
- const deadline = Date.now() + 5_000;
- while (lock && isRunning(lock.pid)) {
- if (Date.now() > deadline) {
- console.error(`Daemon (pid ${lock.pid}) is still exiting — try again in a moment.`);
- process.exit(1);
- }
- await new Promise((resolve) => setTimeout(resolve, 150));
+ const { stubborn } = await stopDaemons();
+ if (stubborn.length) {
+ console.error(`Daemon (pid ${stubborn[0].pid}) is still exiting — try again in a moment.`);
+ process.exit(1);
}
const fresh = await ensureDaemon();
console.log(`Daemon running on 127.0.0.1:${fresh.port} (pid ${fresh.pid}, v${fresh.daemonVersion}).`);
@@ -293,6 +296,14 @@ async function setup(argv: string[]): Promise<void> {
return at === -1 ? undefined : argv[at + 1];
};
+ // A stale command installs a stale extension, silently, and under npx it will keep doing so
+ // for as long as the cache lives — which is what makes `update` look like it does nothing.
+ // Replace the command first and let the fresh one do the install.
+ if (!flag('no-self-update')) {
+ const code = await upgradeCli(pkg.version, process.argv.slice(2));
+ if (code !== null) process.exit(code);
+ }
+
const browser = valueOf('browser') ?? 'chrome';
if (browser === 'firefox') {
console.log(`
@@ -339,15 +350,14 @@ async function setup(argv: string[]): Promise<void> {
if (flag('restart')) await restart();
const lock = await ensureDaemon();
- let code: string | undefined;
- let alreadyPaired = false;
- if (!flag('no-pair')) {
- const bridge = await RemoteBridge.connect(lock.port, lock.token);
- const sessions = await bridge.sessions();
- alreadyPaired = sessions.some((session) => session.origin.startsWith('chrome-extension://'));
- if (!alreadyPaired) code = (await bridge.pair()).code;
- await bridge.close();
- }
+ // --no-pair means mint no code, not learn nothing: `update` still has to know whether this
+ // browser is paired, because that decides whether what is left to do is "load unpacked" or
+ // the one step an update actually needs, which is pressing ↻.
+ const bridge = await RemoteBridge.connect(lock.port, lock.token);
+ const sessions = await bridge.sessions();
+ const alreadyPaired = sessions.some((session) => session.origin.startsWith('chrome-extension://'));
+ const code = alreadyPaired || flag('no-pair') ? undefined : (await bridge.pair()).code;
+ await bridge.close();
if (json) {
console.log(
@@ -383,10 +393,111 @@ async function setup(argv: string[]): Promise<void> {
console.log(` 2. Open the Browsentic popup and paste this code:\n`);
console.log(` ${groupCode(code)}\n`);
console.log(` Single use, expires in 10 minutes. Need another? "browsentic pair"\n`);
+ } else {
+ console.log(` 2. Run "browsentic pair" and paste the code into the Browsentic popup.\n`);
}
console.log(` Then open the side panel and say what you want.\n`);
}
+/**
+ * Remove Browsentic in one command.
+ *
+ * The manual procedure this replaces could not reach two of these: an npx cache, which is
+ * invisible and goes on serving the version it first resolved, and a daemon whose lockfile was
+ * deleted before it was stopped, which keeps its port for as long as the machine is up. Between
+ * them they made a reinstall land on the old build, which looked like the installer was broken.
+ */
+async function uninstall(argv: string[]): Promise<void> {
+ const flag = (name: string) => argv.includes(`--${name}`);
+ const plan = planUninstall({ keepSkills: flag('keep-skills') });
+ const daemons = await runningDaemons();
+ const kind = installKind();
+
+ console.log(`\n Browsentic ${pkg.version} — uninstall\n`);
+ if (!daemons.length && !plan.removals.length && !plan.npx.length) {
+ console.log(' Nothing to remove; this machine is already clean.\n');
+ return;
+ }
+
+ console.log(' This removes:\n');
+ for (const daemon of daemons) console.log(` daemon 127.0.0.1:${daemon.port}, pid ${daemon.pid}`);
+ for (const removal of plan.removals) {
+ console.log(` ${removal.label.padEnd(11)} ${removal.path}`);
+ console.log(` ${removal.holds}${removal.keep ? ' — keeping skills/' : ''}`);
+ }
+ for (const entry of plan.npx) {
+ const running = entry.running ? ', the copy running right now' : '';
+ console.log(` npx cache ${entry.dir}`);
+ console.log(` browsentic ${entry.version ?? 'unknown'}${running}`);
+ }
+
+ if (plan.elsewhere.length) {
+ console.log('\n Left alone — configuration put these outside the two roots:\n');
+ for (const dir of plan.elsewhere) console.log(` ${dir.label.padEnd(11)} ${dir.path} (${dir.holds})`);
+ }
+
+ console.log('\n You will have to remove these yourself:\n');
+ console.log(' the Browsentic card at chrome://extensions. Do that first — remove the');
+ console.log(' directory while the card is loaded and the browser is left holding a');
+ console.log(' broken one. It is also what clears recordings and held secrets, which');
+ console.log(' live in extension storage rather than on disk.');
+ if (kind === 'global') console.log('\n the command itself: npm rm -g browsentic');
+ if (kind === 'repo') console.log('\n the global link: yarn daemon:unlink');
+ console.log('\n the entry in your MCP client, e.g. claude mcp remove browsentic');
+
+ if (flag('dry-run')) {
+ console.log('\n --dry-run: nothing was removed.\n');
+ return;
+ }
+
+ if (!flag('yes') && !argv.includes('-y')) {
+ if (!process.stdin.isTTY) {
+ console.error('\n Nothing was removed — this is not a terminal, so there is nobody to ask.');
+ console.error(' Re-run it with --yes.\n');
+ process.exit(1);
+ }
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
+ const answer = await rl.question('\n Remove all of it? [y/N] ');
+ rl.close();
+ if (!/^y(es)?$/i.test(answer.trim())) return console.log('\n Nothing was removed.\n');
+ }
+
+ console.log();
+
+ // Ask the daemon to drop its session keys before killing it, so a browser still holding the
+ // socket is told it is unpaired instead of discovering it. Never spawn one to do this.
+ const lock = await probeExisting();
+ if (lock) {
+ try {
+ const bridge = await RemoteBridge.connect(lock.port, lock.token);
+ const revoked = await bridge.revoke();
+ await bridge.close();
+ if (revoked) console.log(` ✓ Unpaired ${revoked} browser${revoked === 1 ? '' : 's'}`);
+ } catch {
+ console.log(' · Unpair skipped, the daemon did not answer');
+ }
+ }
+
+ const { stopped, stubborn } = await stopDaemons();
+ if (stopped.length) console.log(` ✓ Daemon stopped (pid ${stopped.map((daemon) => daemon.pid).join(', ')})`);
+ for (const daemon of stubborn) console.log(` ✗ Daemon pid ${daemon.pid} would not exit — kill it by hand`);
+
+ for (const outcome of removeAll(plan.removals)) {
+ if (!outcome.removed) console.log(` ✗ ${outcome.removal.path} — ${outcome.error}`);
+ else if (outcome.kept.length) console.log(` ✓ Emptied ${outcome.removal.path} — kept ${outcome.kept.join(', ')}/`);
+ else console.log(` ✓ Removed ${outcome.removal.path}`);
+ }
+
+ // Last, because it deletes the directory this process is running out of.
+ for (const purge of purgeNpxCache(plan.npx)) {
+ if (purge.removed) console.log(` ✓ Cleared ${purge.entry.dir}`);
+ else console.log(` ✗ ${purge.entry.dir} — ${purge.error}`);
+ }
+
+ console.log('\n Done. Remove the card at chrome://extensions if you have not.\n');
+ if (stubborn.length) process.exitCode = 1;
+}
+
async function showSessions(): Promise<void> {
const bridge = await connect();
const sessions = await bridge.sessions();
diff --git a/src/daemon/ensure-daemon.ts b/src/daemon/ensure-daemon.ts
index e068290..55a25e0 100644
--- a/src/daemon/ensure-daemon.ts
+++ b/src/daemon/ensure-daemon.ts
@@ -2,7 +2,7 @@ import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { DAEMON_PORTS } from '@/lib/actions/protocol';
-import { isRunning, readLockfile, type Lockfile } from './lockfile';
+import { clearLockfile, isRunning, readLockfile, type Lockfile } from './lockfile';
import { log } from './log';
const SPAWN_TIMEOUT_MS = 8_000;
@@ -51,7 +51,66 @@ export async function probeExisting(): Promise<Lockfile | null> {
return null;
}
-async function healthyPid(port: number): Promise<number | null> {
+export interface RunningDaemon {
+ pid: number;
+ port: number;
+}
+
+/**
+ * Every daemon actually answering on a Browsentic port.
+ *
+ * Discovered by probe rather than from the lockfile, because the failure this is here for is a
+ * daemon whose lockfile is gone — deleted by hand, or by an uninstall that ran in the wrong
+ * order. Such a daemon holds its port and keeps serving forever, and nothing that reads
+ * ~/.browsentic can see it. Probing also rules out killing an unrelated process that inherited
+ * a recorded pid.
+ */
+export async function runningDaemons(): Promise<RunningDaemon[]> {
+ const found = new Map<number, number>();
+ for (const port of DAEMON_PORTS) {
+ const pid = await healthyPid(port);
+ if (pid !== null && !found.has(pid)) found.set(pid, port);
+ }
+ return [...found].map(([pid, port]) => ({ pid, port }));
+}
+
+export interface StopResult {
+ stopped: RunningDaemon[];
+ stubborn: RunningDaemon[];
+}
+
+/** SIGTERM every daemon, then SIGKILL whatever is still standing, and drop the lockfile. */
+export async function stopDaemons(graceMs = 5_000): Promise<StopResult> {
+ const daemons = await runningDaemons();
+ for (const { pid } of daemons) kill(pid, 'SIGTERM');
+
+ const remaining = await waitForExit(daemons, graceMs);
+ for (const { pid } of remaining) kill(pid, 'SIGKILL');
+ const stubborn = await waitForExit(remaining, 2_000);
+
+ clearLockfile();
+ return { stopped: daemons.filter((daemon) => !stubborn.includes(daemon)), stubborn };
+}
+
+function kill(pid: number, signal: NodeJS.Signals): void {
+ try {
+ process.kill(pid, signal);
+ } catch {
+ // Already gone, or ours to signal no longer. Either way the wait below settles it.
+ }
+}
+
+async function waitForExit(daemons: RunningDaemon[], timeoutMs: number): Promise<RunningDaemon[]> {
+ const deadline = Date.now() + timeoutMs;
+ let alive = daemons.filter((daemon) => isRunning(daemon.pid));
+ while (alive.length && Date.now() < deadline) {
+ await delay(POLL_INTERVAL_MS);
+ alive = alive.filter((daemon) => isRunning(daemon.pid));
+ }
+ return alive;
+}
+
+export async function healthyPid(port: number): Promise<number | null> {
try {
const response = await fetch(`http://127.0.0.1:${port}/health`, {
signal: AbortSignal.timeout(1_000),
diff --git a/src/daemon/npx.ts b/src/daemon/npx.ts
new file mode 100644
index 0000000..99da0b4
--- /dev/null
+++ b/src/daemon/npx.ts
@@ -0,0 +1,108 @@
+import { existsSync, readFileSync, readdirSync, realpathSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { dirname, join, resolve, sep } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+/** The installed package, whatever tree it landed in. The bundle sits one level down, in dist/. */
+export const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+
+export type InstallKind = 'npx' | 'global' | 'repo';
+
+const inNpxCache = (path: string) => path.split(sep).includes('_npx');
+
+/**
+ * How this CLI got here, which decides how it can replace itself and whether a throwaway
+ * cache is what is pinning an old version in place.
+ */
+export function installKind(): InstallKind {
+ if (inNpxCache(packageRoot)) return 'npx';
+ // A build config the `files` allowlist never ships. Checking for the extension payload
+ // instead would misread a checkout that still has src/daemon/extension/ staged from a
+ // previous `npm pack`, which is the normal state of a maintainer's tree.
+ if (existsSync(join(packageRoot, 'tsup.config.ts'))) return 'repo';
+ return 'global';
+}
+
+export interface NpxEntry {
+ dir: string;
+ /** The version of browsentic sitting in it, when its package.json can be read. */
+ version: string | null;
+ /** What the user asked for, e.g. `browsentic@latest`. npm keys the directory on this. */
+ packages: string[];
+ /** True for the entry this very process is running out of. */
+ running: boolean;
+}
+
+function real(path: string): string {
+ try {
+ return realpathSync(path);
+ } catch {
+ return path;
+ }
+}
+
+function cacheRoots(): string[] {
+ const roots = [
+ process.env.npm_config_cache,
+ process.platform === 'win32' ? join(process.env.LOCALAPPDATA ?? homedir(), 'npm-cache') : null,
+ join(homedir(), '.npm'),
+ ].filter((root): root is string => !!root);
+ return [...new Set(roots.map((root) => join(root, '_npx')))];
+}
+
+function readJson(path: string): Record<string, unknown> | null {
+ try {
+ return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Every throwaway npx install holding a copy of this package.
+ *
+ * This is the whole reason `npx browsentic setup` can keep installing a months-old extension:
+ * npm names the directory after the spec it was asked for, writes the version it resolved
+ * *that first time* into it as a caret range, and every later `npx browsentic` satisfies
+ * itself from that without consulting the registry again. Deleting the directory is the only
+ * thing that makes npm look a second time.
+ */
+export function npxEntries(): NpxEntry[] {
+ const own = inNpxCache(packageRoot) ? real(resolve(packageRoot, '..', '..')) : null;
+ const scanned = cacheRoots().flatMap((root) => {
+ try {
+ return readdirSync(root, { withFileTypes: true })
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => real(join(root, entry.name)));
+ } catch {
+ return [];
+ }
+ });
+
+ const entries = new Map<string, NpxEntry>();
+ for (const dir of [...scanned, ...(own ? [own] : [])]) {
+ if (entries.has(dir)) continue;
+ const manifest = readJson(join(dir, 'node_modules', 'browsentic', 'package.json'));
+ if (!manifest) continue;
+ const requested = readJson(join(dir, 'package.json'))?._npx as { packages?: unknown } | undefined;
+ entries.set(dir, {
+ dir,
+ version: typeof manifest.version === 'string' ? manifest.version : null,
+ packages: Array.isArray(requested?.packages) ? (requested.packages as string[]) : [],
+ running: dir === own,
+ });
+ }
+ return [...entries.values()];
+}
+
+/**
+ * The spec this process was launched with, when it is an npx run — `browsentic@latest` for a
+ * bare `npx browsentic`, or an exact version when the user pinned one. A pin is a decision,
+ * not a stale cache, so nothing may upgrade past it.
+ */
+export function pinnedVersion(): string | null {
+ const own = npxEntries().find((entry) => entry.running);
+ const spec = own?.packages.find((name) => name === 'browsentic' || name.startsWith('browsentic@'));
+ const requested = spec?.slice('browsentic@'.length);
+ return requested && /^\d+\.\d+\.\d+/.test(requested) ? requested : null;
+}
diff --git a/src/daemon/screenshots.ts b/src/daemon/screenshots.ts
index bcfe9cd..c88f143 100644
--- a/src/daemon/screenshots.ts
+++ b/src/daemon/screenshots.ts
@@ -7,7 +7,7 @@ import { uploadedSkillsDir } from './agent/skills';
export function saveScreenshot(dataUrl: string, opts: { filename?: string; dir?: string } = {}): string {
const { mime, bytes } = parseDataUrl(dataUrl);
- const dir = opts.dir ? containedSkillDir(opts.dir) : resolveDir();
+ const dir = opts.dir ? containedSkillDir(opts.dir) : screenshotDir();
mkdirSync(dir, { recursive: true, mode: 0o700 });
const ext = extensionFor(mime);
@@ -27,7 +27,7 @@ function containedSkillDir(dir: string): string {
return target;
}
-function resolveDir(): string {
+export function screenshotDir(): string {
const configured = readAgentConfig().screenshotDir;
if (typeof configured === 'string' && configured.trim()) return expandHome(configured.trim());
return join(homedir(), 'browsentic', 'screenshot');
diff --git a/src/daemon/self-update.ts b/src/daemon/self-update.ts
new file mode 100644
index 0000000..c3d40ec
--- /dev/null
+++ b/src/daemon/self-update.ts
@@ -0,0 +1,92 @@
+import { spawnSync } from 'node:child_process';
+import { rmSync } from 'node:fs';
+import { installKind, npxEntries, pinnedVersion } from './npx';
+
+const REGISTRY = process.env.BROWSENTIC_REGISTRY ?? 'https://registry.npmjs.org';
+
+/** The published version, or null when the registry is unreachable — offline is not an error here. */
+export async function publishedVersion(timeoutMs = 4_000): Promise<string | null> {
+ try {
+ const response = await fetch(`${REGISTRY}/browsentic/latest`, {
+ headers: { accept: 'application/vnd.npm.install-v1+json' },
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ if (!response.ok) return null;
+ const manifest = (await response.json()) as { version?: unknown };
+ return typeof manifest.version === 'string' ? manifest.version : null;
+ } catch {
+ return null;
+ }
+}
+
+export function isNewer(candidate: string, current: string): boolean {
+ const release = (version: string) => version.split('-')[0].split('.').map((part) => Number.parseInt(part, 10) || 0);
+ const [a, b] = [release(candidate), release(current)];
+ for (let i = 0; i < 3; i++) if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) > (b[i] ?? 0);
+
+ // Same release: a final beats the prerelease that led to it, and two prereleases fall back
+ // to string order, which is right for the -rc.1 / -rc.2 shape this project actually uses.
+ const [pre, currentPre] = [candidate.split('-')[1], current.split('-')[1]];
+ if (pre === currentPre) return false;
+ if (!pre) return true;
+ if (!currentPre) return false;
+ return pre > currentPre;
+}
+
+/**
+ * Replace this CLI with the published one, then re-run the original command under it.
+ *
+ * Returns the exit code of that second run, or null when nothing needed doing — the caller
+ * exits on a number and carries on otherwise.
+ *
+ * The reason this exists: a stale CLI installs a stale extension, silently and for as long as
+ * the cache lives. `update` and `setup` both promise the current build, so both have to be
+ * able to reach past whatever is pinning them.
+ */
+export async function upgradeCli(current: string, forward: string[]): Promise<number | null> {
+ const pinned = pinnedVersion();
+ if (pinned) return null;
+
+ const latest = await publishedVersion();
+ if (!latest || !isNewer(latest, current)) return null;
+
+ const kind = installKind();
+ // stderr throughout: `setup --json` promises a parseable stdout, and progress is not part of it.
+ if (kind === 'repo') {
+ console.error(`\n ! browsentic ${latest} is published; this is ${current}, from a source checkout.`);
+ console.error(` Update it with "git pull && yarn setup".\n`);
+ return null;
+ }
+
+ console.error(`\n ↻ Updating the command itself, ${current} → ${latest}\n`);
+ const rerun = [...forward, '--no-self-update'];
+
+ if (kind === 'npx') {
+ // Every entry, not just ours: they are all stale by definition now, and the next bare
+ // `npx browsentic` would otherwise pick one of them back up.
+ for (const entry of npxEntries()) rmSync(entry.dir, { recursive: true, force: true });
+ const code = run('npx', ['-y', `browsentic@${latest}`, ...rerun]);
+ if (code !== 0) {
+ console.error(`\n That did not run, but nothing is broken: the cache is cleared, so a plain`);
+ console.error(` \`npx browsentic ${forward[0] ?? 'setup'}\` fetches ${latest} fresh next time.\n`);
+ }
+ return code;
+ }
+
+ const installed = run('npm', ['install', '-g', `browsentic@${latest}`]);
+ if (installed !== 0) {
+ console.error(`\n Could not replace the global install. Run this yourself, then try again:\n`);
+ console.error(` npm install -g browsentic@${latest}\n`);
+ return installed;
+ }
+ return run('browsentic', rerun);
+}
+
+function run(command: string, args: string[]): number {
+ const result = spawnSync(command, args, { stdio: 'inherit', shell: process.platform === 'win32' });
+ if (result.error) {
+ console.error(`\n Could not run \`${command}\`: ${result.error.message}\n`);
+ return 1;
+ }
+ return result.status ?? 1;
+}
diff --git a/src/daemon/uninstall.ts b/src/daemon/uninstall.ts
new file mode 100644
index 0000000..1154eba
--- /dev/null
+++ b/src/daemon/uninstall.ts
@@ -0,0 +1,125 @@
+import { existsSync, readdirSync, rmSync } from 'node:fs';
+import { isAbsolute, join, relative } from 'node:path';
+import { readAgentConfig } from './agent/config';
+import { uploadedSkillsDir } from './agent/skills';
+import { downloadDir } from './downloads';
+import { npxEntries, type NpxEntry } from './npx';
+import { extensionDir, stateDir, userDir } from './paths';
+import { screenshotDir } from './screenshots';
+
+export interface Removal {
+ label: string;
+ path: string;
+ holds: string;
+ /** Paths under `path` to leave behind, relative to it. */
+ keep?: string[];
+}
+
+export interface UninstallPlan {
+ removals: Removal[];
+ /** Configured directories outside the two roots. Named, never deleted — the user put them there. */
+ elsewhere: Removal[];
+ npx: NpxEntry[];
+}
+
+function contains(root: string, path: string): boolean {
+ const inside = relative(root, path);
+ return !inside.startsWith('..') && !isAbsolute(inside);
+}
+
+/**
+ * What removing Browsentic means on this machine, resolved rather than assumed: an install can
+ * have been pointed elsewhere with `setup --dir`, and skills, screenshots and downloads each
+ * take a config override.
+ */
+export function planUninstall(options: { keepSkills?: boolean } = {}): UninstallPlan {
+ const config = readAgentConfig();
+ const extension = extensionDir(config.extensionDir);
+ const roots = [stateDir, userDir];
+
+ const removals: Removal[] = [];
+ if (!roots.some((root) => contains(root, extension)) && existsSync(extension)) {
+ removals.push({ label: 'extension', path: extension, holds: 'the unpacked build Chrome loads' });
+ }
+ removals.push({
+ label: 'state',
+ path: stateDir,
+ holds: 'pairing keys, config, approvals, logs',
+ keep: options.keepSkills ? ['skills'] : undefined,
+ });
+ removals.push({
+ label: 'files',
+ path: userDir,
+ holds: 'the extension, skills, site maps, screenshots, captured downloads',
+ keep: options.keepSkills ? ['skills'] : undefined,
+ });
+
+ const elsewhere: Removal[] = [];
+ const outside = (label: string, path: string, holds: string) => {
+ if (!roots.some((root) => contains(root, path)) && existsSync(path)) elsewhere.push({ label, path, holds });
+ };
+ outside('skills', uploadedSkillsDir(), 'site maps and uploaded skills');
+ outside('screenshots', screenshotDir(), 'captures taken with save: true');
+ outside('downloads', downloadDir(), 'files captured from pages');
+
+ return {
+ removals: removals.filter((removal) => existsSync(removal.path)),
+ elsewhere,
+ npx: npxEntries(),
+ };
+}
+
+export interface RemovalOutcome {
+ removal: Removal;
+ removed: boolean;
+ /** What was left behind, so the report can say "emptied" rather than claim a clean sweep. */
+ kept: string[];
+ error?: string;
+}
+
+export function removeAll(removals: Removal[]): RemovalOutcome[] {
+ return removals.map((removal) => {
+ try {
+ const kept = removal.keep?.length ? keepingSome(removal.path, removal.keep) : [];
+ if (!kept.length) rmSync(removal.path, { recursive: true, force: true });
+ return { removal, removed: true, kept };
+ } catch (error) {
+ return { removal, removed: false, kept: [], error: (error as Error).message };
+ }
+ });
+}
+
+/** Empties `dir` apart from `keep`, and reports what survived — nothing means delete the lot. */
+function keepingSome(dir: string, keep: string[]): string[] {
+ const kept: string[] = [];
+ for (const entry of readdirSync(dir)) {
+ if (keep.includes(entry)) kept.push(entry);
+ else rmSync(join(dir, entry), { recursive: true, force: true });
+ }
+ return kept;
+}
+
+export interface CachePurge {
+ entry: NpxEntry;
+ removed: boolean;
+ error?: string;
+}
+
+/**
+ * Delete the npx caches, including the one this process is running out of.
+ *
+ * Self-deletion is deliberate and safe on POSIX: the CLI is a single bundled file that Node has
+ * already read, and an unlinked inode stays readable to whoever holds it open. Windows can
+ * refuse, which is why the failure is reported rather than thrown — the directory is a cache,
+ * and a user who deletes it by hand loses nothing.
+ */
+export function purgeNpxCache(entries: NpxEntry[]): CachePurge[] {
+ return entries.map((entry) => {
+ try {
+ rmSync(entry.dir, { recursive: true, force: true });
+ return { entry, removed: true };
+ } catch (error) {
+ return { entry, removed: false, error: (error as Error).message };
+ }
+ });
+}