@mirsella/browser-mcp 1.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "browser",
3
- "version": "1.0.0",
3
+ "version": "2.0.1",
4
4
  "description": "Shared Chromium profile with isolated conversation tabs for Codex and OpenCode.",
5
5
  "author": {
6
6
  "name": "mirsella"
package/CONTRIBUTING.md CHANGED
@@ -84,13 +84,12 @@ Push the versioned source commit to `main` for 2.x, or to
84
84
  `main` with the full source `commit` SHA. It verifies the pinned workflow and
85
85
  source branch, then reuses the checksummed `npm-package` artifact.
86
86
 
87
- Use `npm_mode=stage` to submit a release for approval on npm's Staged Packages
88
- page. For a new npm name, a temporary staging-only `NPM_STAGE_TOKEN` can
89
- bootstrap the first release; remove that secret and revoke the token after
90
- approval. Configure npm's trusted publisher as this repository's `release.yml`
91
- without an environment, then use `npm_mode=publish` for OIDC publication.
92
- Versions 1.x use `opencode1`; 2.x use `latest`. GitHub releases attach the same
93
- tested tarball and `SHA256SUMS`. Keep npm, Cargo and Codex versions synchronized.
87
+ Configure npm's trusted publisher as this repository's `release.yml` without
88
+ an environment. Dispatch with `npm_mode=publish` to publish through OIDC,
89
+ create the GitHub release, and update the Codex marketplace branch for `latest`.
90
+ Use `npm_mode=dry-run` to verify without writing. Versions 1.x use `opencode1`;
91
+ 2.x use `latest`. GitHub releases attach the same tested tarball and
92
+ `SHA256SUMS`. Keep npm, Cargo and Codex versions synchronized.
94
93
 
95
94
  CI runs headed tests against Chrome for Testing 155.0.8059.39. Update the pin
96
95
  when validating a new browser version.
package/README.md CHANGED
@@ -10,13 +10,18 @@ and Codex conversations. The plugin wraps
10
10
  and routes each conversation through its own browser tabs while sharing cookies,
11
11
  logins, local storage, cache, and extensions.
12
12
 
13
- Package 1.x is the OpenCode v1 release line (1.18 or newer, below 2).
14
- Use package 2.x for the native OpenCode v2 adapter. Codex uses the same
15
- standalone Rust server in both release lines.
13
+ Package 2.x targets OpenCode v2 (2.0.27 or newer). Package 1.x retains the
14
+ OpenCode v1 adapter (1.18 or newer, below 2). Codex uses the same Rust MCP
15
+ server and manifests in both releases. The native v2 adapter uses
16
+ `@opencode/plugin`; local directories also expose a physical `server` entrypoint.
17
+
18
+ Install `@mirsella/browser-mcp` for OpenCode v2, or `@mirsella/browser-mcp@opencode1`
19
+ for OpenCode v1. Existing Nix-managed and local-directory installations can keep
20
+ their configured paths.
16
21
 
17
22
  ## Requirements
18
23
 
19
- - OpenCode 1.18 or newer, or Codex with plugin and hook support
24
+ - OpenCode 2.0.27 or newer, or Codex with plugin and hook support
20
25
  - Linux x64
21
26
  - Bun
22
27
  - A local Chromium-family browser
@@ -29,8 +34,8 @@ the browser automation skill available by default:
29
34
 
30
35
  ```json
31
36
  {
32
- "$schema": "https://opencode.ai/config.json",
33
- "plugin": ["@mirsella/browser-mcp@opencode1"]
37
+ "$schema": "https://opencode.ai/v2/config.json",
38
+ "plugins": ["@mirsella/browser-mcp"]
34
39
  }
35
40
  ```
36
41
 
@@ -46,6 +51,34 @@ OpenCode loads the JavaScript `./server` package export. Codex uses the
46
51
  plugin and MCP manifests plus the session hooks. Both integrations launch
47
52
  the same packaged Rust executable.
48
53
 
54
+ ## Timeouts and diagnostics
55
+
56
+ Each browser action has one deadline for catalog discovery, browser startup,
57
+ session locking, execution, and reconciliation. `OPENCODE_BROWSER_OPERATION_SECONDS`
58
+ sets that deadline and defaults to 540 seconds. Catalog discovery and compact
59
+ help have a separate 70-second limit. A failed or panicking catalog discovery
60
+ can be retried without restarting the broker.
61
+
62
+ After an interrupted action, the next call replaces that session's worker and
63
+ reconciles its existing owned tabs. Actions are never replayed automatically.
64
+ Dispatched tab creation finishes registering ownership or closing that exact
65
+ target after caller cancellation. Inspect the page before retrying a write
66
+ because it may already have taken effect.
67
+
68
+ The broker writes diagnostics to
69
+ `$XDG_STATE_HOME/browser-mcp/broker-<profile-hash>.log`, or
70
+ `~/.local/state/browser-mcp/` when `XDG_STATE_HOME` is unset. Its startup message
71
+ prints the exact path. Logs are readable only by your user and also go to stderr.
72
+
73
+ Request tracing records the tool name, session ID, current stage, and elapsed
74
+ time. It does not record tool arguments. If a call stalls, look for its last
75
+ stage and whether the broker recorded a deadline, cancellation, catalog failure,
76
+ or worker replacement. Browser stderr is captured in
77
+ `browser-<profile-hash>.log` in the same directory. Its separate writer survives
78
+ broker replacement and exits when Chromium closes the pipe. Each broker or
79
+ browser log retains an 8 MiB file and one rotated `.log.1` backup. A browser that
80
+ exits during startup reports that exit immediately.
81
+
49
82
  ## Codex setup
50
83
 
51
84
  The release tarball contains the executable, both integrations, and a local
@@ -108,15 +141,15 @@ direct tools so those policies continue to work.
108
141
  Settings:
109
142
 
110
143
  - `enabled` (default `true`): start the server and load the skill. Set it to
111
- `false` to disable both. An explicit `mcp.browser` entry takes precedence.
144
+ `false` to disable both. An explicit `mcp.servers.browser` entry takes precedence.
112
145
  - `compactTools` (default `true`): keep `browser_dispatch` and `browser_help`
113
146
  instead of the direct tools. Set it to `false` to always use direct tools:
114
147
 
115
148
  ```json
116
149
  {
117
- "$schema": "https://opencode.ai/config.json",
118
- "plugin": [
119
- ["@mirsella/browser-mcp@opencode1", { "compactTools": false }]
150
+ "$schema": "https://opencode.ai/v2/config.json",
151
+ "plugins": [
152
+ { "package": "@mirsella/browser-mcp", "options": { "compactTools": false } }
120
153
  ]
121
154
  }
122
155
  ```
@@ -218,7 +251,7 @@ action. Explicitly disabled or disconnected MCP entries stay disabled.
218
251
  - A profile or socket lease error means another live package process owns it or a stale process is still running. Do not bypass the locks.
219
252
  - A process on the configured CDP port must belong to the exact managed browser generation. Stop it or choose another port.
220
253
  - If downstream startup fails, verify that `bunx` is available to OpenCode.
221
- - The plugin refuses to replace an unrelated `mcp.browser` entry.
254
+ - The plugin refuses to replace an unrelated `mcp.servers.browser` entry.
222
255
 
223
256
  ## Security
224
257
 
@@ -267,9 +300,11 @@ See [`CONTRIBUTING.md`](CONTRIBUTING.md) for the development and release workflo
267
300
  CI builds and tests the distributable tarball on every push. Run the `release`
268
301
  workflow from `main` with the full tested source commit: `main` for 2.x, or
269
302
  `release/opencode-v1` for 1.x. The workflow verifies that commit and downloads
270
- its checksummed CI artifact instead of rebuilding it. Use `stage` for npm
271
- browser approval, or `publish` after configuring `release.yml` as an npm
272
- trusted publisher. The channels are `latest` for 2.x and `opencode1` for 1.x.
303
+ its checksummed CI artifact instead of rebuilding it. Dispatch with
304
+ `npm_mode=publish` to publish through npm's OIDC trusted publisher, create the
305
+ GitHub release, and update the Codex marketplace branch for `latest`. Use
306
+ `npm_mode=dry-run` to verify without writing. The channels are `latest` for 2.x
307
+ and `opencode1` for 1.x.
273
308
 
274
309
  ## License
275
310
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mirsella/browser-mcp",
3
- "version": "1.0.0",
3
+ "version": "2.0.1",
4
4
  "description": "Session-isolated browser automation over MCP and Chrome DevTools Protocol",
5
5
  "type": "module",
6
6
  "exports": {
@@ -50,14 +50,22 @@
50
50
  "x64"
51
51
  ],
52
52
  "engines": {
53
- "opencode": ">=1.18.0 <2"
53
+ "opencode": ">=2.0.27 <3"
54
54
  },
55
55
  "devDependencies": {
56
- "@opencode-ai/plugin": "1.18.11"
56
+ "@opencode/plugin": "2.0.28",
57
+ "@types/node": "24.0.0",
58
+ "typescript": "5.9.3"
57
59
  },
58
60
  "publishConfig": {
59
61
  "access": "public",
60
- "tag": "opencode1"
62
+ "tag": "latest"
63
+ },
64
+ "peerDependencies": {
65
+ "@opencode/plugin": ">=2.0.27 <3"
66
+ },
67
+ "dependencies": {
68
+ "yaml": "2.8.3"
61
69
  },
62
70
  "main": "./server.ts",
63
71
  "scripts": {
@@ -1,174 +1,143 @@
1
- import type { Plugin, PluginModule } from "@opencode-ai/plugin";
1
+ import { Plugin, Skill } from "@opencode/plugin";
2
+ import { execFile } from "node:child_process";
3
+ import { readdir, readFile } from "node:fs/promises";
2
4
  import { fileURLToPath } from "node:url";
5
+ import { promisify } from "node:util";
6
+ import { parse } from "yaml";
3
7
 
4
- const SESSION_KEY = "__opencode_session_id";
5
- const SKILLS_PATH = fileURLToPath(new URL("../skills", import.meta.url));
6
- const MCP_CLI = fileURLToPath(new URL("../vendor/browser-mcp", import.meta.url));
7
- const DISPATCH_TOOL = "browser_dispatch";
8
- const DIRECT_TOOLS = `
9
- browser_click browser_close_page browser_drag browser_emulate browser_evaluate_script browser_fill browser_fill_form
10
- browser_get_console_message browser_get_network_request browser_handle_dialog browser_hover browser_lighthouse_audit
11
- browser_list_console_messages browser_list_network_requests browser_list_pages browser_navigate_page browser_new_page
12
- browser_performance_analyze_insight browser_performance_start_trace browser_performance_stop_trace browser_press_key
13
- browser_resize_page browser_take_heapsnapshot browser_take_screenshot browser_take_snapshot browser_type_text
14
- browser_upload_file browser_wait_for
15
- `
16
- .trim()
17
- .split(/\s+/);
8
+ const execute = promisify(execFile);
9
+ const binary = fileURLToPath(new URL("../vendor/browser-mcp", import.meta.url));
10
+ const skills = fileURLToPath(new URL("../skills/", import.meta.url));
11
+ const directTools = `click close_page drag emulate evaluate_script fill fill_form get_console_message
12
+ get_network_request handle_dialog hover lighthouse_audit list_console_messages list_network_requests
13
+ list_pages navigate_page new_page performance_analyze_insight performance_start_trace performance_stop_trace
14
+ press_key resize_page take_heapsnapshot take_screenshot take_snapshot type_text upload_file wait_for`
15
+ .split(/\s+/).map(name => `browser_${name}`);
18
16
 
19
- type ConfigWithPolicies = {
20
- agent?: Record<string, { permission?: unknown; tools?: unknown }>;
21
- permission?: unknown;
22
- skills?: { paths?: string[] };
23
- tools?: unknown;
24
- };
25
-
26
- type BrowserRoutingOptions = {
27
- enabled?: boolean;
28
- compactTools?: boolean;
29
- };
30
-
31
- function hasPartialBrowserPolicy(value: unknown): boolean {
32
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
33
- return Object.keys(value).some((pattern) => {
34
- const expression = pattern
35
- .replace(/[.+^${}()|[\]\\]/g, "\\$&")
36
- .replaceAll("*", ".*")
37
- .replaceAll("?", ".");
38
- const regex = new RegExp(`^${expression}$`);
39
- const matches = (tool: string) => regex.test(tool);
40
- return DIRECT_TOOLS.some(matches) && !(matches(DISPATCH_TOOL) && DIRECT_TOOLS.every(matches));
41
- });
42
- }
43
-
44
- function requiresDirectTools(config: ConfigWithPolicies): boolean {
45
- if (hasPartialBrowserPolicy(config.permission) || hasPartialBrowserPolicy(config.tools)) {
46
- return true;
47
- }
48
- return Object.values(config.agent ?? {}).some(
49
- (agent) => hasPartialBrowserPolicy(agent.permission) || hasPartialBrowserPolicy(agent.tools),
50
- );
17
+ function partialPolicy(agents: Array<{ permissions: readonly { action: string }[] }>) {
18
+ return agents.some(agent => agent.permissions.some(({ action }) => {
19
+ const regex = new RegExp(`^${action.replace(/[.+^${}()|[\]\\]/g, "\\$&").replaceAll("*", ".*").replaceAll("?", ".")}$`);
20
+ return directTools.some(tool => regex.test(tool))
21
+ && !(regex.test("browser_dispatch") && directTools.every(tool => regex.test(tool)));
22
+ }));
51
23
  }
52
24
 
53
- const server: Plugin = async ({ $, client, directory }, options) => {
54
- const { enabled = true, compactTools = true } = (options ?? {}) as BrowserRoutingOptions;
55
- if (typeof enabled !== "boolean") throw new Error("enabled must be a boolean");
56
- if (typeof compactTools !== "boolean") throw new Error("compactTools must be a boolean");
57
- let configured = false;
58
- let disposed = false;
59
- let failures = 0;
60
- let timer: ReturnType<typeof setTimeout> | undefined;
61
- let recovering: Promise<void> | undefined;
62
- const scheduleRecovery = (delay: number) => {
63
- if (timer) clearTimeout(timer);
64
- if (disposed || !configured) return;
65
- timer = setTimeout(() => void recover(), delay);
66
- timer.unref();
67
- };
68
- const recover = (): Promise<void> => {
69
- if (disposed || !configured) return Promise.resolve();
70
- if (recovering) return recovering;
71
- recovering = (async () => {
72
- try {
73
- const status = await client.mcp.status({ query: { directory }, throwOnError: true });
74
- if (disposed) return;
75
- if (!status.data?.browser) throw new Error("Browser MCP status is missing");
76
- // Respect explicit runtime disconnects in the OpenCode UI.
77
- if (status.data?.browser?.status === "failed") {
78
- console.warn("Browser MCP adapter failed; reconnecting");
79
- await client.mcp.connect({ path: { name: "browser" }, query: { directory }, throwOnError: true });
80
- const restored = await client.mcp.status({ query: { directory }, throwOnError: true });
81
- if (restored.data?.browser?.status !== "connected") {
82
- throw new Error(`Browser MCP adapter recovery failed: ${JSON.stringify(restored.data?.browser)}`);
83
- }
84
- console.warn("Browser MCP adapter reconnected");
85
- }
86
- failures = 0;
87
- } catch (error) {
88
- failures++;
89
- console.error("Failed to recover browser MCP adapter; will retry", error);
90
- } finally {
91
- recovering = undefined;
92
- scheduleRecovery(failures ? Math.min(30_000, 1_000 * 2 ** Math.min(failures - 1, 5)) : 5_000);
93
- }
94
- })();
95
- return recovering;
96
- };
97
-
98
- return {
99
- config: async (config) => {
100
- const extended = config as typeof config & ConfigWithPolicies;
101
- const compact = compactTools && !requiresDirectTools(extended);
102
-
103
- config.mcp ??= {};
104
- const existing = config.mcp.browser;
105
- if (
106
- existing &&
107
- ((existing.type !== undefined && existing.type !== "local") ||
108
- (existing.command?.[0] !== undefined && existing.command[0] !== MCP_CLI))
109
- ) {
110
- throw new Error(
111
- "@mirsella/browser-mcp cannot replace the existing mcp.browser configuration",
112
- );
113
- }
114
- const requestedEnabled = existing?.enabled ?? enabled;
115
- config.mcp.browser = {
116
- type: "local",
117
- command: compact ? [MCP_CLI] : [MCP_CLI, "--direct-tools"],
118
- enabled: requestedEnabled,
119
- timeout: 600_000,
120
- };
121
- configured = true;
122
- scheduleRecovery(1_000);
123
- if (!requestedEnabled) return;
124
- if (compactTools && !compact) {
125
- console.warn(
126
- "@mirsella/browser-mcp uses direct tools to preserve per-action browser permissions",
127
- );
128
- }
129
-
130
- extended.skills ??= {};
131
- extended.skills.paths ??= [];
132
- if (!extended.skills.paths.includes(SKILLS_PATH)) extended.skills.paths.push(SKILLS_PATH);
133
- },
134
- "tool.execute.before": async (input, output) => {
135
- if (!input.tool.startsWith("browser_")) return;
136
- if (!input.sessionID) throw new Error("browser tool call has no OpenCode session ID");
137
- if (!output.args || typeof output.args !== "object" || Array.isArray(output.args)) {
138
- throw new Error("browser tool call has invalid arguments");
139
- }
140
- (output.args as Record<string, unknown>)[SESSION_KEY] = input.sessionID;
141
- },
142
- "chat.message": async () => {
143
- await recover();
144
- },
145
- event: async ({ event }) => {
146
- if (event.type === "server.instance.disposed") {
147
- disposed = true;
148
- if (timer) clearTimeout(timer);
149
- return;
150
- }
151
- const change = event as { type: string; properties: { server?: string } };
152
- if (change.type === "mcp.tools.changed" && change.properties.server === "browser") {
153
- // Do not await a callback that can be published by the connect request itself.
154
- void recover();
155
- return;
156
- }
157
- if (event.type !== "session.deleted") return;
158
- const sessionID = event.properties.info.id;
159
- try {
160
- const result = await $`${[MCP_CLI, "release-session", sessionID]}`.quiet().nothrow();
161
- if (result.exitCode !== 0) {
162
- const stderr = String(result.stderr).trim();
163
- console.error(
164
- `Failed to release browser session ${sessionID} with exit code ${result.exitCode}${stderr ? `: ${stderr}` : ""}`,
165
- );
166
- }
167
- } catch (error) {
168
- console.error(`Failed to release browser session ${sessionID}`, error);
169
- }
170
- },
171
- };
172
- };
173
-
174
- export default { id: "@mirsella/browser-mcp", server } satisfies PluginModule;
25
+ export default Plugin.define({
26
+ id: "@mirsella/browser-mcp",
27
+ async setup(ctx) {
28
+ const { enabled = true, compactTools = true } = ctx.options;
29
+ if (typeof enabled !== "boolean") throw new Error("enabled must be a boolean");
30
+ if (typeof compactTools !== "boolean") throw new Error("compactTools must be a boolean");
31
+ let compact = compactTools;
32
+ let reconnectGeneration = 0;
33
+ let active = enabled;
34
+ await ctx.mcp.transform(editor => {
35
+ const existing = editor.get("browser");
36
+ if (existing?.type === "remote" || (existing && existing.command[0] !== binary)) {
37
+ throw new Error("Browser MCP cannot replace an incompatible mcp.servers.browser configuration");
38
+ }
39
+ active = !(existing?.disabled ?? !enabled);
40
+ editor.set("browser", {
41
+ ...existing,
42
+ type: "local", command: compact ? [binary] : [binary, "--direct-tools"],
43
+ disabled: !active, codemode: false,
44
+ environment: { ...existing?.environment, BROWSER_MCP_RECONNECT_GENERATION: String(reconnectGeneration) },
45
+ timeout: { startup: 30_000, catalog: 30_000, execution: 600_000, ...existing?.timeout },
46
+ });
47
+ });
48
+ if (active) {
49
+ const entries = await readdir(skills, { withFileTypes: true });
50
+ const registered = await Promise.all(entries.filter(entry => entry.isDirectory()).map(async entry => {
51
+ const path = `${skills}${entry.name}/SKILL.md`;
52
+ const text = await readFile(path, "utf8");
53
+ const frontmatter = text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
54
+ if (!frontmatter) throw new Error(`Missing skill frontmatter: ${path}`);
55
+ const meta = parse(frontmatter[1]);
56
+ if (!meta || typeof meta.name !== "string" || typeof meta.description !== "string") throw new Error(`Invalid skill metadata: ${path}`);
57
+ return Skill.Info.make({ id: Skill.ID.make(meta.name), name: Skill.Name.make(meta.name),
58
+ description: meta.description, path: Skill.Info.fields.path.make(path), content: text.slice(frontmatter[0].length) });
59
+ }));
60
+ await ctx.skill.transform(editor => { for (const skill of registered) editor.add(skill); });
61
+ }
62
+ await ctx.tool.hook("execute.before", input => {
63
+ if (!input.tool.startsWith("browser_")) return;
64
+ if (!input.sessionID) throw new Error("Browser tool call has no OpenCode session ID");
65
+ if (!input.input || typeof input.input !== "object" || Array.isArray(input.input)) throw new Error("Browser tool call has invalid arguments");
66
+ input.input = { ...input.input, __opencode_session_id: input.sessionID };
67
+ });
68
+ const controller = new AbortController();
69
+ let timer: ReturnType<typeof setTimeout> | undefined;
70
+ let recovering: Promise<void> | undefined;
71
+ let failures = 0;
72
+ // Runners that never list the server cannot be fixed by reloading;
73
+ // stay quiet until it has been seen at least once.
74
+ let seen = false;
75
+ const schedule = () => {
76
+ if (controller.signal.aborted) return;
77
+ timer = setTimeout(() => void recover(), failures ? Math.min(30_000, 1_000 * 2 ** Math.min(failures - 1, 5)) : 5_000);
78
+ timer.unref();
79
+ };
80
+ const recover = (): Promise<void> => {
81
+ if (controller.signal.aborted) return Promise.resolve();
82
+ if (recovering) return recovering;
83
+ if (timer) clearTimeout(timer);
84
+ recovering = (async () => {
85
+ try {
86
+ const server = (await ctx.mcp.list()).data.find(server => server.name === "browser");
87
+ if (!server) throw new Error("Browser MCP status is missing");
88
+ seen = true;
89
+ // A disabled connection is an explicit user choice; only recover failures.
90
+ if (server.status.status === "failed" && !controller.signal.aborted) {
91
+ console.warn("Browser MCP adapter failed; reloading its registration");
92
+ reconnectGeneration++;
93
+ await ctx.mcp.reload();
94
+ const restored = (await ctx.mcp.list()).data.find(server => server.name === "browser");
95
+ if (restored?.status.status !== "connected") throw new Error(`Browser MCP recovery failed: ${JSON.stringify(restored?.status)}`);
96
+ }
97
+ failures = 0;
98
+ } catch (error) {
99
+ if (!controller.signal.aborted) { failures++; if (seen) console.error("Browser MCP recovery failed; will retry", error); }
100
+ } finally { recovering = undefined; schedule(); }
101
+ })();
102
+ return recovering;
103
+ };
104
+ // Recovery must never stall a prompt: a wedged adapter keeps retrying in
105
+ // the background while chat continues within a short deadline.
106
+ const recoverSoon = async () => {
107
+ let deadline: ReturnType<typeof setTimeout> | undefined;
108
+ try {
109
+ await Promise.race([
110
+ recover(),
111
+ new Promise<void>(resolve => { deadline = setTimeout(resolve, 5_000); deadline.unref(); }),
112
+ ]);
113
+ } finally {
114
+ if (deadline) clearTimeout(deadline);
115
+ }
116
+ };
117
+ // Catalog reads wait for plugin bootstrap. Do not await them inside setup.
118
+ const checkPolicy = async () => {
119
+ if (!compactTools || controller.signal.aborted) return;
120
+ const next = !partialPolicy((await ctx.agent.list()).data);
121
+ if (controller.signal.aborted || next === compact) return;
122
+ compact = next;
123
+ if (!compact) console.warn("Browser MCP uses direct tools to preserve per-action permissions");
124
+ await ctx.mcp.reload();
125
+ };
126
+ const policyReady = Promise.resolve().then(checkPolicy);
127
+ void policyReady.catch(error => console.error("Browser MCP permission initialization failed", error));
128
+ await ctx.session.hook("prompt", async () => { await policyReady; await checkPolicy(); await recoverSoon(); });
129
+ const events = async () => {
130
+ for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
131
+ if (controller.signal.aborted) break;
132
+ if (event.type === "agent.updated") void checkPolicy().catch(error => console.error("Browser MCP permission update failed", error));
133
+ if ((event.type === "mcp.status.changed") && event.data.server === "browser") void recover();
134
+ if (event.type !== "session.deleted") continue;
135
+ try { await execute(binary, ["release-session", event.data.sessionID], { signal: controller.signal }); }
136
+ catch (error) { if (!controller.signal.aborted) console.error(`Failed to release browser session ${event.data.sessionID}`, error); }
137
+ }
138
+ };
139
+ void events().catch(error => { if (!controller.signal.aborted) console.error("Browser MCP event subscription failed", error); });
140
+ schedule();
141
+ return () => { controller.abort(); if (timer) clearTimeout(timer); };
142
+ },
143
+ });
Binary file