@ricsam/browser-mcp 0.3.11 → 0.3.13

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.
package/README.md CHANGED
@@ -3,8 +3,10 @@
3
3
  Native Chrome companion. Requires Node >=22.14.0 and an installed
4
4
  Google Chrome. No browser download or startup occurs during npm installation.
5
5
 
6
+ Release 0.3.13 uses one cross-platform Node package with matching server/chart 0.3.13, native protocol 3 and no database schema change. It adds independent health and deadline quarantine, explicitly approved blocked-tab recovery, sanitized failure diagnostics, and verified binary download/export/script transfers. Older runtimes require an update for new capabilities. Stop the old CLI before upgrading, then restart the same named profile to preserve sign-ins and pairing; never replay uncertain actions automatically.
7
+
6
8
  ```sh
7
- npm install -g @ricsam/browser-mcp@0.3.11
9
+ npm install -g @ricsam/browser-mcp@0.3.13
8
10
  browser-mcp browser start --server https://browser-mcp.click --profile work
9
11
  browser-mcp browser status --profile work
10
12
  browser-mcp browser pause --profile work
@@ -28,6 +30,15 @@ Chrome launch (up to 30 seconds) before closing acquired resources. Repeated
28
30
  signals wait for that same cleanup. Pairing waits are cancelled too. A cleanup
29
31
  error is reported after the other safe cleanup stages have been attempted.
30
32
 
33
+ Every Chrome launch enables WebMCP by default, equivalent to setting
34
+ `chrome://flags/#enable-webmcp-testing` to **Enabled**. The launcher passes
35
+ `--enable-features=WebMCP,WebMCPTesting,DevToolsWebMCPSupport` to support current
36
+ and earlier Chrome feature names, including the older DevTools protocol gate.
37
+ This applies to persistent, ephemeral and multi-profile browsers. Restart the
38
+ CLI/browser after updating to pick it up; no manual flag or profile edit is
39
+ needed. WebMCP still requires a supporting Chrome version and a site that
40
+ registers tools; it does not automatically invoke tools or grant permissions.
41
+
31
42
  Chrome runs headed, without `--enable-automation`, `--headless`,
32
43
  `--remote-debugging-pipe` or `--remote-debugging-port=0`, so its native
33
44
  `navigator.webdriver` stays false (no getter override or stealth script).
@@ -2,12 +2,13 @@ import {
2
2
  capabilityFetch,
3
3
  exclusiveOutput,
4
4
  readCapability
5
- } from "./chunk-2hzkme2s.js";
5
+ } from "./chunk-k9cpr8vk.js";
6
6
  import"./chunk-1sjcwr28.js";
7
7
 
8
8
  // cli/src/agent/files.ts
9
9
  import { open, constants, unlink } from "node:fs/promises";
10
10
  import { Readable, Transform } from "node:stream";
11
+ import { createHash } from "node:crypto";
11
12
  import { pipeline } from "node:stream/promises";
12
13
  async function uploadFile(capabilityPath, inputPath) {
13
14
  const cap = await readCapability(capabilityPath);
@@ -26,8 +27,8 @@ async function uploadFile(capabilityPath, inputPath) {
26
27
  }
27
28
  async function downloadFile(capabilityPath, outputPath) {
28
29
  const cap = await readCapability(capabilityPath);
29
- if (cap.method !== "GET")
30
- throw new Error("Download capability required");
30
+ if (cap.method !== "GET" || cap.size === undefined || cap.sha256 === undefined)
31
+ throw new Error("Download capability with exact size and SHA-256 required");
31
32
  const file = await exclusiveOutput(outputPath);
32
33
  let success = false;
33
34
  try {
@@ -35,16 +36,21 @@ async function downloadFile(capabilityPath, outputPath) {
35
36
  if (!response.body)
36
37
  throw new Error("Missing transfer body");
37
38
  let bytes = 0;
39
+ const hash = createHash("sha256");
38
40
  const limiter = new Transform({ transform(chunk, _encoding, callback) {
39
41
  bytes += chunk.length;
40
42
  if (bytes > cap.limits.maxBytes)
41
43
  return callback(new Error("Size exceeded"));
44
+ hash.update(chunk);
42
45
  callback(null, chunk);
43
46
  } });
44
47
  await pipeline(Readable.fromWeb(response.body), limiter, file.createWriteStream({ autoClose: false }));
48
+ const sha256 = hash.digest("hex");
49
+ if (bytes !== cap.size || sha256 !== cap.sha256)
50
+ throw new Error("Download integrity verification failed; request a new capability, never retry this one");
45
51
  await file.sync();
46
52
  success = true;
47
- return { downloaded: true, bytes };
53
+ return { downloaded: true, bytes, sha256 };
48
54
  } finally {
49
55
  await file.close();
50
56
  if (!success)
@@ -6,7 +6,7 @@ import {
6
6
  capabilityFetch,
7
7
  exclusiveOutput,
8
8
  readCapability
9
- } from "./chunk-2hzkme2s.js";
9
+ } from "./chunk-k9cpr8vk.js";
10
10
  import"./chunk-1sjcwr28.js";
11
11
 
12
12
  // cli/src/agent/secrets.ts
@@ -22,7 +22,7 @@ async function readCapability(path) {
22
22
  }
23
23
  const cap = JSON.parse(text);
24
24
  const u = new URL(cap.url);
25
- if (u.protocol !== "https:" || u.username || u.password || u.search || u.hash || !/^\/api\/native-data\/[a-zA-Z0-9-]+$/.test(u.pathname) || !["GET", "PUT"].includes(cap.method) || !/^Bearer [A-Za-z0-9_-]{43}$/.test(cap.headers.Authorization) || cap.expiresAt <= Date.now() || !Number.isSafeInteger(cap.limits.maxBytes) || cap.limits.maxBytes < 0 || cap.limits.maxBytes > 256 * 1024 * 1024)
25
+ if (u.protocol !== "https:" || u.username || u.password || u.search || u.hash || !/^\/api\/native-data\/[a-zA-Z0-9-]+$/.test(u.pathname) || !["GET", "PUT"].includes(cap.method) || !/^Bearer [A-Za-z0-9_-]{43}$/.test(cap.headers.Authorization) || !Number.isFinite(cap.expiresAt) || cap.expiresAt <= Date.now() || cap.limits.maxAttempts !== 1 || cap.limits.resumable !== false || cap.size !== undefined && (!Number.isSafeInteger(cap.size) || cap.size !== cap.limits.maxBytes) || cap.sha256 !== undefined && !/^[a-f0-9]{64}$/.test(cap.sha256) || !Number.isSafeInteger(cap.limits.maxBytes) || cap.limits.maxBytes < 0 || cap.limits.maxBytes > 256 * 1024 * 1024)
26
26
  throw new Error("Invalid capability");
27
27
  return cap;
28
28
  }
@@ -54,7 +54,7 @@ function onceAsync(action) {
54
54
  // cli/src/browser/owned-chrome.ts
55
55
  import { randomUUID as randomUUID2 } from "node:crypto";
56
56
  // cli/package.json
57
- var version = "0.3.11";
57
+ var version = "0.3.13";
58
58
 
59
59
  // cli/src/browser/chrome-diagnostics.ts
60
60
  import { constants } from "node:fs";
@@ -482,6 +482,7 @@ function ownedChromeArgs(profile, port) {
482
482
  `--remote-debugging-port=${port}`,
483
483
  "--no-first-run",
484
484
  "--no-default-browser-check",
485
+ "--enable-features=WebMCP,WebMCPTesting,DevToolsWebMCPSupport",
485
486
  "--disable-extensions",
486
487
  "--disable-component-extensions-with-background-pages",
487
488
  "--disable-sync",
@@ -3373,10 +3374,47 @@ class BrowserTabState {
3373
3374
  }
3374
3375
  }
3375
3376
 
3377
+ // cli/src/runtime/failures.ts
3378
+ import { randomUUID as randomUUID4 } from "node:crypto";
3379
+
3380
+ class RuntimeFault extends Error {
3381
+ code;
3382
+ recovery;
3383
+ beforeDispatch;
3384
+ constructor(code2, recovery, beforeDispatch = false) {
3385
+ super(code2);
3386
+ this.code = code2;
3387
+ this.recovery = recovery;
3388
+ this.beforeDispatch = beforeDispatch;
3389
+ }
3390
+ }
3391
+ var OBSERVATION_OPERATIONS = new Set(["list_tabs", "list_downloads", "read_page", "screenshot", "wait_for", "capabilities", "inspect", "events", "diagnostics", "export_page", "webmcp_list", "runtime_health"]);
3392
+ var messages = {
3393
+ unsupported_target: "This target contains a privileged/internal document that browser page tools cannot inspect.",
3394
+ tab_closed: "The tab is closed or detached.",
3395
+ runtime_disconnected: "The runtime or browser connection ended.",
3396
+ context_destroyed: "The document execution context changed during the operation.",
3397
+ execution_timeout: "The browser operation exceeded its internal wait budget.",
3398
+ script_exception: "The script threw an exception. Page exception text and stack are suppressed.",
3399
+ transfer_failed: "The file transfer failed or its completion could not be confirmed.",
3400
+ scope_rejected: "Runtime scope or tab ownership was rejected.",
3401
+ runtime_operation_failed: "The browser operation failed; page-derived details are suppressed."
3402
+ };
3403
+ function failureFor(error, op, operationId, stage) {
3404
+ const text = error instanceof Error ? error.message : "";
3405
+ let code2 = error instanceof RuntimeFault ? error.code : /no longer open|Target page, context or browser has been closed|Target closed|Frame was detached/i.test(text) ? "tab_closed" : /Runtime disconnected|Browser closed|browser has been closed|Connection closed/i.test(text) ? "runtime_disconnected" : /Execution context was destroyed|destroying its JavaScript context|Cannot find context with specified id/i.test(text) ? "context_destroyed" : /Timeout|timed out|time out/i.test(text) ? "execution_timeout" : stage === "transfer" ? "transfer_failed" : op === "run_js" ? "script_exception" : /download|upload|transfer|resource|grant/i.test(op) ? "transfer_failed" : "runtime_operation_failed";
3406
+ const observation = OBSERVATION_OPERATIONS.has(op);
3407
+ const outcome = error instanceof RuntimeFault && error.beforeDispatch ? "not_dispatched" : observation ? "failed" : "unknown";
3408
+ const recovery = error instanceof RuntimeFault ? error.recovery : code2 === "runtime_disconnected" ? "Reconnect the runtime, then call browser_runtime_health. Do not repeat an uncertain mutation." : code2 === "tab_closed" ? "Use browser_list_tabs to select an existing tab. Do not replay the prior mutation." : code2 === "execution_timeout" ? "Call browser_runtime_health to distinguish a settled wait from quarantined execution. A timeout does not cancel page effects." : code2 === "transfer_failed" ? "Inspect browser_transfer_status and browser_list_downloads. Reissue a grant only for retained bytes; do not repeat a website action." : code2 === "script_exception" ? "Review the submitted script locally. Effects before the exception may have occurred; do not replay automatically." : "Call browser_runtime_health, then browser_capabilities for a supported target. Do not repeat an uncertain mutation.";
3409
+ const diagnosticId = randomUUID4();
3410
+ console.error(JSON.stringify({ event: "runtime_failure", diagnosticId, operationId, operation: op, stage, code: code2, outcome }));
3411
+ return { error: { code: code2, message: messages[code2] ?? "Runtime operation rejected." }, outcome, result: { diagnosticId, operationId, category: code2, stage, recovery, retrySafe: outcome !== "unknown", executionState: "settled", cancellationConfirmed: false } };
3412
+ }
3413
+
3376
3414
  // cli/src/browser/browser-runtime.ts
3377
3415
  var MAX_DOWNLOAD_CHUNK_BYTES = 1024 * 1024;
3378
3416
  var MAX_RUN_JS_RESULT_BYTES = 1024 * 1024;
3379
- var MAX_RUN_JS_ARTIFACT_BYTES = 4 * 1024 * 1024;
3417
+ var MAX_RUN_JS_ARTIFACT_BYTES = 20 * 1024 * 1024;
3380
3418
  var MAX_RUN_JS_ARTIFACT_COUNT = 32;
3381
3419
  var REF_ACTION_TIMEOUT_MS = 5000;
3382
3420
  var NAVIGATION_TIMEOUT_MS = 20000;
@@ -3713,7 +3751,7 @@ class BrowserRuntime {
3713
3751
  if (action === "batch")
3714
3752
  return await this.batch(input, execution);
3715
3753
  const page = typeof input.tabId === "string" ? this.page(input.tabId) : undefined;
3716
- if (page)
3754
+ if (page && action !== "close_tab")
3717
3755
  await this.guardPage?.(page);
3718
3756
  const events = page ? this.events.get(page) : undefined;
3719
3757
  await events?.ready;
@@ -3806,20 +3844,23 @@ class BrowserRuntime {
3806
3844
  results.push({ index, action: step.action, result });
3807
3845
  if (result?.matched === false || result?.expected?.matched === false || result?.dispatch && result.dispatch.status !== "completed" || result?.code || result?.observation?.available === false)
3808
3846
  return { results, stoppedAt: index, remaining: steps.length - index - 1, code: "batch_step_stopped", retrySafe: false };
3809
- } catch {
3847
+ } catch (error) {
3848
+ const failure = failureFor(error, step.action, execution.operationId ?? crypto.randomUUID(), "batch_step");
3810
3849
  return {
3811
- results: [...results, { index, action: step.action, status: "unknown", retrySafe: false }],
3850
+ results: [...results, { index, action: step.action, status: "unknown", ...failure.result, code: failure.error.code }],
3812
3851
  stoppedAt: index,
3813
3852
  remaining: steps.length - index - 1,
3853
+ status: "unknown",
3854
+ retrySafe: false,
3814
3855
  code: "batch_outcome_uncertain",
3815
- recovery: BROWSER_RECOVERY
3856
+ recovery: failure.result.recovery
3816
3857
  };
3817
3858
  }
3818
3859
  }
3819
3860
  return { results, completed: true, outcomeVerified: false };
3820
3861
  }
3821
3862
  async dispatch(action, input, execution) {
3822
- if (typeof input.tabId === "string")
3863
+ if (typeof input.tabId === "string" && action !== "close_tab")
3823
3864
  await this.guardPage?.(this.page(input.tabId));
3824
3865
  if (action === "upload_abort") {
3825
3866
  this.uploads.abort(input.uploadId, input.tabId);
@@ -4378,32 +4419,43 @@ class BrowserRuntime {
4378
4419
  evaluated = await page.evaluate(async ({ code: code2, maxBytes, maxCount }) => {
4379
4420
  const artifacts = [];
4380
4421
  let totalBytes = 0;
4381
- const r5dCreateArtifact = (filename, content) => {
4422
+ const r5dCreateArtifact = (filename, content, mimeType) => {
4382
4423
  if (typeof filename !== "string" || !filename.trim()) {
4383
4424
  throw new TypeError("r5dCreateArtifact(filename, content): filename must be a non-empty string.");
4384
4425
  }
4385
- if (typeof content !== "string") {
4386
- throw new TypeError(`r5dCreateArtifact(${JSON.stringify(filename)}, content): content must be a string. Use JSON.stringify(value) for objects.`);
4387
- }
4426
+ if (filename.length > 255 || /[\\/\\\\\x00-\x1f]/.test(filename))
4427
+ throw new TypeError("Artifact filename must be a simple filename of at most 255 characters.");
4428
+ const text = typeof content === "string";
4429
+ const bytes = text ? new TextEncoder().encode(content) : content instanceof ArrayBuffer ? new Uint8Array(content) : content instanceof Uint8Array ? content : undefined;
4430
+ if (!bytes)
4431
+ throw new TypeError("Artifact content must be a string, Uint8Array or ArrayBuffer; use await response.arrayBuffer() for binary documents.");
4432
+ const mime = mimeType === undefined ? text ? "text/plain" : "application/octet-stream" : mimeType;
4433
+ if (typeof mime !== "string" || !/^[a-zA-Z0-9!#$&^_.+-]+\/[a-zA-Z0-9!#$&^_.+-]+$/.test(mime) || mime.length > 200)
4434
+ throw new TypeError("Artifact MIME must be a type/subtype without parameters.");
4388
4435
  if (artifacts.length >= maxCount) {
4389
4436
  throw new RangeError(`r5dCreateArtifact: at most ${maxCount} artifacts can be created in one browser_run_js call.`);
4390
4437
  }
4391
- totalBytes += new TextEncoder().encode(content).length;
4438
+ totalBytes += bytes.byteLength;
4392
4439
  if (totalBytes > maxBytes) {
4393
4440
  throw new RangeError(`r5dCreateArtifact: artifact content exceeded the ${maxBytes} byte budget for one browser_run_js call.`);
4394
4441
  }
4395
- artifacts.push({ filename, content });
4442
+ if (text)
4443
+ artifacts.push({ filename, content, mimeType: mime });
4444
+ else {
4445
+ let encoded = "";
4446
+ for (let offset = 0;offset < bytes.length; offset += 24576)
4447
+ encoded += btoa(String.fromCharCode(...bytes.subarray(offset, offset + 24576)));
4448
+ artifacts.push({ filename, base64: encoded, mimeType: mime });
4449
+ }
4396
4450
  return filename;
4397
4451
  };
4398
- const invoke = new Function("r5dCreateArtifact", `"use strict"; return (async () => {
4452
+ try {
4453
+ const invoke = new Function("r5dCreateArtifact", `"use strict"; return (async () => {
4399
4454
  ${code2}
4400
4455
  })()`);
4401
- try {
4402
4456
  return { result: await invoke(r5dCreateArtifact), artifacts };
4403
4457
  } catch (error) {
4404
- if (artifacts.length === 0)
4405
- throw error;
4406
- return { artifacts, failure: error instanceof Error ? error.message : String(error) };
4458
+ return { artifacts, failure: "script_exception" };
4407
4459
  }
4408
4460
  }, { code: input.code, maxBytes: MAX_RUN_JS_ARTIFACT_BYTES, maxCount: MAX_RUN_JS_ARTIFACT_COUNT });
4409
4461
  } catch (error) {
@@ -4413,15 +4465,19 @@ ${code2}
4413
4465
  }
4414
4466
  throw new Error(stripCallLog(message));
4415
4467
  }
4468
+ if (evaluated.failure && !evaluated.artifacts.length)
4469
+ throw new RuntimeFault("script_exception", "Review the submitted script locally. Effects before the exception may have occurred; do not replay automatically.");
4416
4470
  const serialized = JSON.stringify(evaluated.result);
4417
4471
  if (serialized && Buffer.byteLength(serialized) > MAX_RUN_JS_RESULT_BYTES) {
4418
4472
  throw new Error("Browser JavaScript result exceeded the 1 MiB limit.");
4419
4473
  }
4474
+ const partialFailure = evaluated.failure ? failureFor(new Error("Script exception"), "run_js", execution.operationId ?? crypto.randomUUID(), "execute") : undefined;
4420
4475
  return {
4421
4476
  tabId,
4422
4477
  result: evaluated.result,
4423
4478
  artifacts: evaluated.artifacts,
4424
4479
  failure: evaluated.failure,
4480
+ ...partialFailure ? { ...partialFailure.result, status: "unknown", retrySafe: false, recovery: "The script failed after producing these artifacts. Prior effects may have occurred; do not replay automatically." } : {},
4425
4481
  execution: "javascript_escape_hatch",
4426
4482
  intent: input.intent,
4427
4483
  reason: input.reason,
@@ -4480,6 +4536,7 @@ class NativeRuntime {
4480
4536
  epochs = new Map;
4481
4537
  controllers = new Map;
4482
4538
  disconnected = false;
4539
+ operations = new Map;
4483
4540
  hooks = Promise.resolve();
4484
4541
  browserId;
4485
4542
  constructor(context, instanceId, directory, serverOrigin) {
@@ -4561,8 +4618,10 @@ class NativeRuntime {
4561
4618
  }
4562
4619
  }
4563
4620
  assertPage(page) {
4564
- if (page.isClosed() || page.frames().some((f) => !this.allowURL(f.url())))
4565
- throw new Error("Privileged or unsupported browser origin");
4621
+ if (page.isClosed())
4622
+ throw new RuntimeFault("tab_closed", "Use browser_list_tabs to choose an open tab.", true);
4623
+ if (page.frames().some((f) => !this.allowURL(f.url())))
4624
+ throw new RuntimeFault("unsupported_target", "Call browser_capabilities. For documents use the website download, browser_list_downloads, then browser_create_download; do not screenshot or evaluate an internal viewer.", true);
4566
4625
  }
4567
4626
  async assertPageDeep(page) {
4568
4627
  this.assertPage(page);
@@ -4579,7 +4638,7 @@ class NativeRuntime {
4579
4638
  const check = (tree) => {
4580
4639
  const origin = tree.frame.securityOrigin;
4581
4640
  if (origin && origin !== "null" && origin !== "://" && !this.allowURL(origin))
4582
- throw new Error("Privileged inherited origin");
4641
+ throw new RuntimeFault("unsupported_target", "Use browser_capabilities and transfer the document to local document tools instead of inspecting this internal target.", true);
4583
4642
  for (const child of tree.childFrames ?? [])
4584
4643
  check(child);
4585
4644
  };
@@ -4590,13 +4649,9 @@ class NativeRuntime {
4590
4649
  }
4591
4650
  async resolveTarget(tabId, scope, frames = []) {
4592
4651
  this.validateScope(scope);
4593
- const page = this.engine.page(tabId);
4652
+ const page = this.claimPage(tabId, scope);
4594
4653
  await this.track(page);
4595
4654
  await this.assertPageDeep(page);
4596
- const owner = this.owners.get(tabId);
4597
- if (owner && scopeKey(owner) !== scopeKey(scope))
4598
- throw new Error("Tab belongs to another runtime scope");
4599
- this.owners.set(tabId, { ...scope });
4600
4655
  let frame = page.mainFrame();
4601
4656
  for (const selector of frames) {
4602
4657
  const locator = frame.locator(selector);
@@ -4649,9 +4704,43 @@ class NativeRuntime {
4649
4704
  events.diagnosticsSuppressed = false;
4650
4705
  }
4651
4706
  }
4707
+ claimPage(tabId, scope) {
4708
+ this.validateScope(scope);
4709
+ let page;
4710
+ try {
4711
+ page = this.engine.page(tabId);
4712
+ } catch {
4713
+ throw new RuntimeFault("tab_closed", "Use browser_list_tabs to choose an open tab.", true);
4714
+ }
4715
+ const owner = this.owners.get(tabId);
4716
+ if (owner && scopeKey(owner) !== scopeKey(scope))
4717
+ throw new RuntimeFault("scope_rejected", "Use a tab owned by this session.", true);
4718
+ this.owners.set(tabId, { ...scope });
4719
+ return page;
4720
+ }
4721
+ targetCapabilities(tabId, scope) {
4722
+ const page = this.claimPage(tabId, scope);
4723
+ const internal = page.frames().some((f) => !this.allowURL(f.url()));
4724
+ const pdf = page.frames().some((f) => f.url().startsWith("chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai")) || /\.pdf(?:[?#]|$)/i.test(page.url());
4725
+ return { targetKind: internal ? pdf ? "pdf_viewer" : "internal" : pdf ? "possible_pdf" : "web", pageToolsSupported: !internal, pdfDetected: pdf, requiresDocumentTools: internal || pdf, retrieval: { tool: "browser_create_download", source: "browser_list_downloads" }, recovery: internal || pdf ? "Download the original document using the website UI, then browser_list_downloads and browser_create_download. Alternatively fetch an authorized document from a supported same-origin web page into r5dCreateArtifact; do not forward cookies or decode PDF in page scripts." : null };
4726
+ }
4727
+ async closeBlockedTab(tabId, scope, operationId) {
4728
+ this.validateScope(scope);
4729
+ const owner = this.owners.get(tabId);
4730
+ if (!owner || scopeKey(owner) !== scopeKey(scope))
4731
+ throw new RuntimeFault("scope_rejected", "Recovery is limited to the blocked operation owner.", true);
4732
+ const page = this.engine.page(tabId);
4733
+ await page.close({ runBeforeUnload: false });
4734
+ if (!page.isClosed())
4735
+ throw new Error("Tab closure unconfirmed");
4736
+ this.operations.get(operationId)?.abort(new Error("Blocked target closed by approved recovery"));
4737
+ return { closed: true };
4738
+ }
4652
4739
  async execute(op, args, scope, operationId) {
4653
- if (op === "session_end")
4654
- return this.executeInner(op, args, scope, operationId);
4740
+ if (op === "session_end") {
4741
+ await this.endSession(scope);
4742
+ return { ended: true };
4743
+ }
4655
4744
  const controller = new AbortController, key = scopeKey(scope);
4656
4745
  let set = this.controllers.get(key);
4657
4746
  if (!set) {
@@ -4659,9 +4748,11 @@ class NativeRuntime {
4659
4748
  this.controllers.set(key, set);
4660
4749
  }
4661
4750
  set.add(controller);
4751
+ this.operations.set(operationId, controller);
4662
4752
  try {
4663
4753
  return await withCancellation(controller.signal, () => this.executeInner(op, args, scope, operationId));
4664
4754
  } finally {
4755
+ this.operations.delete(operationId);
4665
4756
  set.delete(controller);
4666
4757
  if (!set.size)
4667
4758
  this.controllers.delete(key);
@@ -4671,9 +4762,18 @@ class NativeRuntime {
4671
4762
  await this.hooks;
4672
4763
  this.validateScope(scope);
4673
4764
  if (args.url !== undefined && !this.allowURL(String(args.url)))
4674
- throw new Error("Unsupported navigation origin");
4675
- if (typeof args.tabId === "string")
4676
- await this.resolveTarget(args.tabId, scope);
4765
+ throw new RuntimeFault("unsupported_target", "Navigate only to authorized HTTP(S) pages or about:blank.", true);
4766
+ if (op === "capabilities" && typeof args.tabId === "string") {
4767
+ const target2 = this.targetCapabilities(args.tabId, scope);
4768
+ if (!target2.pageToolsSupported || target2.pdfDetected)
4769
+ return { tabId: args.tabId, ...target2, observation: target2.pageToolsSupported ? null : false, screenshot: { supported: target2.pageToolsSupported ? null : false }, runJs: { supported: target2.pageToolsSupported ? null : false }, export: { supported: target2.pageToolsSupported ? null : false }, capabilityProbe: "metadata_only" };
4770
+ }
4771
+ if (typeof args.tabId === "string") {
4772
+ if (op === "close_tab")
4773
+ this.claimPage(args.tabId, scope);
4774
+ else
4775
+ await this.resolveTarget(args.tabId, scope);
4776
+ }
4677
4777
  if (op === "batch" && Array.isArray(args.steps))
4678
4778
  for (const step of args.steps) {
4679
4779
  if (step.input?.url !== undefined && !this.allowURL(String(step.input.url)))
@@ -4704,14 +4804,22 @@ class NativeRuntime {
4704
4804
  const tabs = await this.engine.listTabs();
4705
4805
  return { tabs: tabs.filter((t) => this.allowURL(t.url) && (!this.owners.has(t.tabId) || scopeKey(this.owners.get(t.tabId)) === scopeKey(scope))) };
4706
4806
  }
4707
- const result = await this.engine.execute(op, args, { sessionId: scopeKey(scope), operationId });
4708
- if (this.disconnected || (this.epochs.get(scopeKey(scope)) ?? 0) !== operationEpoch)
4709
- throw new Error("Scope ended during execution; outcome uncertain");
4710
- if (typeof args.tabId === "string" && op !== "close_tab")
4711
- await this.assertPageDeep(this.engine.page(args.tabId));
4712
- if (op === "open_tab" && typeof result?.tab?.tabId === "string")
4713
- this.owners.set(result.tab.tabId, { ...scope });
4714
- return result;
4807
+ try {
4808
+ const result = await this.engine.execute(op, args, { sessionId: scopeKey(scope), operationId });
4809
+ if (this.disconnected || (this.epochs.get(scopeKey(scope)) ?? 0) !== operationEpoch)
4810
+ throw new Error("Scope ended during execution; outcome uncertain");
4811
+ if (typeof args.tabId === "string" && op !== "close_tab")
4812
+ await this.assertPageDeep(this.engine.page(args.tabId));
4813
+ if (op === "open_tab" && typeof result?.tab?.tabId === "string")
4814
+ this.owners.set(result.tab.tabId, { ...scope });
4815
+ if (op === "capabilities" && typeof args.tabId === "string")
4816
+ return { ...result, ...this.targetCapabilities(args.tabId, scope) };
4817
+ return result;
4818
+ } catch (error) {
4819
+ if (error instanceof RuntimeFault)
4820
+ throw new RuntimeFault(error.code, error.recovery, false);
4821
+ throw error;
4822
+ }
4715
4823
  }
4716
4824
  async endSession(scope) {
4717
4825
  const key = scopeKey(scope);
@@ -4728,9 +4836,9 @@ class NativeRuntime {
4728
4836
  }
4729
4837
  async shutdown() {
4730
4838
  await this.disconnect();
4731
- for (const tab of await this.engine.listTabs())
4839
+ for (const tabId of this.generations.keys())
4732
4840
  for (const p of this.plugins)
4733
- await p.onTabClose?.(tab.tabId);
4841
+ await p.onTabClose?.(tabId);
4734
4842
  await this.hooks;
4735
4843
  this.engine.closeUploads();
4736
4844
  }
@@ -4753,7 +4861,7 @@ class NativeRuntime {
4753
4861
 
4754
4862
  // cli/src/runtime/relay.ts
4755
4863
  import WebSocket2 from "ws";
4756
- import { createHash as createHash5, randomUUID as randomUUID4 } from "node:crypto";
4864
+ import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
4757
4865
  import fs9 from "node:fs/promises";
4758
4866
  import path8 from "node:path";
4759
4867
 
@@ -5133,6 +5241,7 @@ class NativeLiveProducer {
5133
5241
  }
5134
5242
 
5135
5243
  // cli/src/runtime/relay.ts
5244
+ var sameScope3 = (a, b) => a.browserId === b.browserId && a.tokenId === b.tokenId && a.sessionKey === b.sessionKey && a.instanceId === b.instanceId;
5136
5245
  var LIMIT = 2 * 1024 * 1024;
5137
5246
  function wireResult(op, value) {
5138
5247
  if (!value || typeof value !== "object")
@@ -5176,7 +5285,21 @@ class Relay {
5176
5285
  stopping = false;
5177
5286
  live;
5178
5287
  seen = new Set;
5179
- queue = Promise.resolve();
5288
+ active;
5289
+ recent = [];
5290
+ health(scope) {
5291
+ const active = this.active, own = active && (!scope || sameScope3(active.scope, scope));
5292
+ return { state: this.state, paused: this.paused, queueDepth: 0, admission: active ? "blocked" : "ready", quarantined: !!active && (active.timedOut || active.interrupted), operation: own ? { operationId: active.id, operation: active.op, startedAt: active.startedAt, deadlineAt: active.deadlineAt, callerDeadline: active.timedOut ? "expired" : "pending", executionState: active.settled ? "settled_after_interruption" : "unresolved", cancellationConfirmed: false, recoveryAvailable: !!active.tabId && !active.recovering } : active ? { ownedByAnotherScope: true } : null, recent: this.recent.filter((r) => !scope || sameScope3(r.scope, scope)).map((r) => r.result) };
5293
+ }
5294
+ interrupt() {
5295
+ if (this.active)
5296
+ this.active.interrupted = true;
5297
+ }
5298
+ remember(active, result) {
5299
+ this.recent.push({ scope: active.scope, result: { operationId: active.id, ...result } });
5300
+ if (this.recent.length > 32)
5301
+ this.recent.shift();
5302
+ }
5180
5303
  state = "disconnected";
5181
5304
  paused = false;
5182
5305
  constructor(runtime, server, token, previewDirectory, liveEnabled = false) {
@@ -5209,6 +5332,7 @@ class Relay {
5209
5332
  await new Promise((resolve2, reject) => {
5210
5333
  socket.once("error", reject);
5211
5334
  socket.once("close", () => {
5335
+ this.interrupt();
5212
5336
  clearInterval(heartbeat);
5213
5337
  resolve2();
5214
5338
  });
@@ -5219,7 +5343,7 @@ class Relay {
5219
5343
  heartbeat.unref();
5220
5344
  socket.once("open", () => {
5221
5345
  this.state = "authenticating";
5222
- socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.11", instanceId: this.runtime.instanceId, operations: [...BROWSER_OPERATIONS, ...this.runtime.plugins.flatMap((p) => p.operations), "session_end", "release_tab"], capabilities: ["browser-controls.v1", "screenshot-ids.v1", "webmcp.page-context.v1", "clipboard.native.v1", "native-transfers.v1", "secrets.v1", "forwarding.v1", "live-view.v1"], liveView: { enabled: this.liveEnabled } } }));
5346
+ socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.13", instanceId: this.runtime.instanceId, operations: [...BROWSER_OPERATIONS, ...this.runtime.plugins.flatMap((p) => p.operations), "session_end", "release_tab", "runtime_health", "runtime_recover"], capabilities: ["runtime-quarantine.v1", "binary-artifacts.v1", "browser-controls.v1", "screenshot-ids.v1", "webmcp.page-context.v1", "clipboard.native.v1", "native-transfers.v1", "secrets.v1", "forwarding.v1", "live-view.v1"], liveView: { enabled: this.liveEnabled } } }));
5223
5347
  });
5224
5348
  socket.on("message", (bytes, binary) => {
5225
5349
  if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
@@ -5239,7 +5363,7 @@ class Relay {
5239
5363
  return;
5240
5364
  }
5241
5365
  this.state = "initializing";
5242
- this.queue = this.queue.then(async () => {
5366
+ (async () => {
5243
5367
  await this.runtime.reconnect(message.browserId);
5244
5368
  this.state = "connected";
5245
5369
  this.live = new NativeLiveProducer({ mediaUrl: mediaURL(this.server), token: this.token, instanceId: this.runtime.instanceId, credentialEpoch: message.credentialEpoch, context: this.runtime.context, authorizePage: async (page) => {
@@ -5262,14 +5386,16 @@ class Relay {
5262
5386
  } });
5263
5387
  this.live.setEnabled(this.liveEnabled);
5264
5388
  console.error("Browser MCP connected (dedicated Chrome; local pause available)");
5265
- }).catch(() => socket.close(1011));
5389
+ })().catch(() => socket.close(1011));
5266
5390
  } else if (message.type === "watch") {
5267
5391
  this.live?.onWatch(message).catch(() => {});
5268
5392
  } else if (message.type === "ping")
5269
5393
  socket.send(JSON.stringify({ type: "pong" }));
5270
5394
  else if (message.type === "command") {
5271
- if (!["connected", "initializing"].includes(this.state) || this.paused)
5395
+ if (this.state !== "connected" || this.paused) {
5396
+ socket.send(JSON.stringify({ type: "result", id: message.id, ok: false, outcome: "not_dispatched", error: { code: this.paused ? "runtime_paused" : "runtime_initializing", message: "Runtime is paused or initializing; no action was dispatched." }, result: { executionState: "not_started", retrySafe: true, recovery: "Use local browser-mcp browser status for independent health. Resume locally if paused; retry health after the runtime connects." } }));
5272
5397
  return;
5398
+ }
5273
5399
  let admittedEpoch;
5274
5400
  try {
5275
5401
  admittedEpoch = this.runtime.scopeEpoch(message.scope);
@@ -5277,11 +5403,7 @@ class Relay {
5277
5403
  socket.send(JSON.stringify({ type: "result", id: message.id, ok: false, outcome: "not_dispatched", error: { code: "invalid_scope", message: "Scope rejected at admission" } }));
5278
5404
  return;
5279
5405
  }
5280
- if (message.op === "session_end") {
5281
- this.command(message, socket, admittedEpoch);
5282
- return;
5283
- }
5284
- this.queue = this.queue.then(() => this.command(message, socket, admittedEpoch)).catch(() => {});
5406
+ this.command(message, socket, admittedEpoch).catch(() => socket.close(1011));
5285
5407
  }
5286
5408
  });
5287
5409
  });
@@ -5314,65 +5436,135 @@ class Relay {
5314
5436
  return;
5315
5437
  }
5316
5438
  this.seen.add(message.id);
5317
- let timeout2, timedOut = false;
5318
- const task = this.runtime.execute(message.op, message.args, message.scope, message.id);
5319
- timeout2 = setTimeout(() => {
5320
- timedOut = true;
5321
- send({ type: "result", id: message.id, ok: false, outcome: "unknown", error: { code: "runtime_timeout", message: "Execution budget expired. Effects may have occurred; do not replay." } });
5322
- }, Math.max(500, Math.min(120000, Number(message.timeoutMs) || 30000)));
5323
- try {
5324
- const result = await task;
5325
- if (timedOut || this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
5326
- return;
5327
- this.runtime.validateScope(message.scope);
5328
- if (typeof message.args.tabId === "string") {
5329
- this.live?.followTab(message.args.tabId);
5330
- this.live?.emitCursor({ type: "action", phase: "end", ok: true, at: Date.now(), runtimeTabId: message.args.tabId, tool: message.op });
5331
- }
5332
- const blobs = [];
5333
- if (result?.base64 && message.op === "screenshot") {
5334
- const bytes = Buffer.from(result.base64, "base64");
5335
- delete result.base64;
5336
- blobs.push(await this.upload(bytes, "screenshot", "screenshot.png", "image/png"));
5337
- }
5338
- if (message.op === "export_page" && Array.isArray(result?.exports))
5339
- for (const item of result.exports) {
5340
- const filename = Buffer.from(item.downloadId, "base64url").toString("utf8");
5341
- if (path8.basename(filename) !== filename)
5342
- throw new Error("Invalid export file");
5343
- const filenamePath = path8.join(this.previewDirectory, filename);
5344
- const stat = await fs9.lstat(filenamePath);
5345
- if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 20 * 1024 * 1024)
5346
- throw new Error("Invalid export file");
5347
- blobs.push(await this.upload(await fs9.readFile(filenamePath), "export", item.filename, item.mimeType));
5348
- await fs9.unlink(filenamePath);
5349
- delete item.downloadId;
5439
+ if (message.op === "runtime_health") {
5440
+ send({ type: "result", id: message.id, ok: true, result: this.health(message.scope), outcome: "completed" });
5441
+ return;
5442
+ }
5443
+ if (message.op === "runtime_recover") {
5444
+ await this.recover(message, send);
5445
+ return;
5446
+ }
5447
+ if (message.op === "session_end") {
5448
+ if (this.active && sameScope3(this.active.scope, message.scope))
5449
+ this.interrupt();
5450
+ await this.runtime.endSession(message.scope);
5451
+ send({ type: "result", id: message.id, ok: true, result: { ended: true }, outcome: "completed" });
5452
+ return;
5453
+ }
5454
+ if (this.active) {
5455
+ send({ type: "result", id: message.id, ok: false, outcome: "not_dispatched", error: { code: "blocked_by_prior_operation", message: "A prior operation is unresolved or quarantined. No action was queued or dispatched." }, result: { operationId: message.id, blockingOperationId: sameScope3(this.active.scope, message.scope) ? this.active.id : undefined, retrySafe: true, executionState: "not_started", recovery: "Call browser_runtime_health. Wait for confirmed settlement or request explicit user-approved recovery; never replay the prior mutation." } });
5456
+ return;
5457
+ }
5458
+ let finish;
5459
+ const active = { id: message.id, scope: { ...message.scope }, tabId: typeof message.args.tabId === "string" ? message.args.tabId : undefined, op: message.op, startedAt: Date.now(), deadlineAt: Date.now() + Math.max(500, Math.min(120000, Number(message.timeoutMs) || 30000)), timedOut: false, interrupted: false, settled: false, recovering: false, done: new Promise((resolve2) => {
5460
+ finish = resolve2;
5461
+ }) };
5462
+ this.active = active;
5463
+ let stage = "execute", timer;
5464
+ const expired = new Promise((resolve2) => {
5465
+ timer = setTimeout(() => {
5466
+ active.timedOut = true;
5467
+ send({ type: "result", id: message.id, ok: false, outcome: OBSERVATION_OPERATIONS.has(message.op) ? "failed" : "unknown", error: { code: "runtime_timeout", message: "Caller deadline expired. Execution is not confirmed cancelled; do not replay a mutation." }, result: { operationId: active.id, diagnosticId: active.id, category: "execution_timeout", stage, callerDeadline: "expired", executionState: "unresolved", quarantined: true, cancellationConfirmed: false, retrySafe: false, recovery: "Use browser_runtime_health independently. Wait for late settlement or, with explicit user approval, browser_runtime_recover to close this blocked tab." } });
5468
+ console.error(JSON.stringify({ event: "runtime_deadline", diagnosticId: active.id, operation: active.op, stage, executionState: "unresolved" }));
5469
+ resolve2();
5470
+ }, Math.max(1, active.deadlineAt - Date.now()));
5471
+ });
5472
+ const task = (async () => {
5473
+ try {
5474
+ const result = await this.runtime.execute(message.op, message.args, message.scope, message.id);
5475
+ if (active.timedOut || active.interrupted || this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
5476
+ return;
5477
+ this.runtime.validateScope(message.scope);
5478
+ if (typeof message.args.tabId === "string") {
5479
+ this.live?.followTab(message.args.tabId);
5480
+ this.live?.emitCursor({ type: "action", phase: "end", ok: true, at: Date.now(), runtimeTabId: message.args.tabId, tool: message.op });
5481
+ }
5482
+ stage = "transfer";
5483
+ const blobs = [];
5484
+ if (result?.base64 && message.op === "screenshot") {
5485
+ const bytes = Buffer.from(result.base64, "base64");
5486
+ delete result.base64;
5487
+ blobs.push(await this.upload(bytes, "screenshot", "screenshot.png", "image/png"));
5350
5488
  }
5351
- if (message.op === "run_js" && Array.isArray(result?.artifacts)) {
5352
- for (const artifact2 of result.artifacts)
5353
- blobs.push(await this.upload(Buffer.from(artifact2.content), "artifact", path8.basename(artifact2.filename), "text/plain"));
5354
- result.artifacts = result.artifacts.map((a) => ({ filename: path8.basename(a.filename) }));
5489
+ if (message.op === "export_page" && Array.isArray(result?.exports))
5490
+ for (const item of result.exports) {
5491
+ const filename = Buffer.from(item.downloadId, "base64url").toString("utf8");
5492
+ if (path8.basename(filename) !== filename)
5493
+ throw new Error("Invalid export file");
5494
+ const filenamePath = path8.join(this.previewDirectory, filename);
5495
+ const stat = await fs9.lstat(filenamePath);
5496
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 20 * 1024 * 1024)
5497
+ throw new Error("Invalid export file");
5498
+ blobs.push(await this.upload(await fs9.readFile(filenamePath), "export", item.filename, item.mimeType));
5499
+ await fs9.unlink(filenamePath);
5500
+ delete item.downloadId;
5501
+ }
5502
+ if (message.op === "run_js" && Array.isArray(result?.artifacts)) {
5503
+ for (const artifact2 of result.artifacts)
5504
+ blobs.push(await this.upload(artifact2.base64 !== undefined ? Buffer.from(artifact2.base64, "base64") : Buffer.from(artifact2.content), "artifact", path8.basename(artifact2.filename), artifact2.mimeType ?? "text/plain"));
5505
+ result.artifacts = result.artifacts.map((a) => ({ filename: path8.basename(a.filename) }));
5506
+ }
5507
+ if (Buffer.byteLength(JSON.stringify(result)) > 1800000)
5508
+ throw new Error("Result budget exceeded");
5509
+ if (!active.timedOut && !active.interrupted)
5510
+ send({ type: "result", id: message.id, ok: true, result: wireResult(message.op, result), blobs, outcome: result?.status === "unknown" ? "unknown" : "completed" });
5511
+ } catch (error) {
5512
+ const failure = failureFor(error, message.op, message.id, stage);
5513
+ if (!active.timedOut && !active.interrupted)
5514
+ send({ type: "result", id: message.id, ok: false, ...failure });
5515
+ } finally {
5516
+ clearTimeout(timer);
5517
+ active.settled = true;
5518
+ finish();
5519
+ if (active.timedOut || active.interrupted)
5520
+ this.remember(active, { callerDeadline: active.timedOut ? "expired" : "interrupted", executionState: active.interrupted ? "settled_after_interruption" : "settled_late", outcome: "unknown", retrySafe: false, cancellationConfirmed: false });
5521
+ if (this.active === active && !active.interrupted && !active.recovering)
5522
+ this.active = undefined;
5355
5523
  }
5356
- if (Buffer.byteLength(JSON.stringify(result)) > 1800000)
5357
- throw new Error("Result budget exceeded");
5358
- send({ type: "result", id: message.id, ok: true, result: wireResult(message.op, result), blobs, outcome: result?.status === "unknown" ? "unknown" : "completed" });
5524
+ })();
5525
+ await Promise.race([task, expired]);
5526
+ }
5527
+ async recover(message, send) {
5528
+ const active = this.active;
5529
+ const reject = (code2, messageText) => send({ type: "result", id: message.id, ok: false, outcome: "not_dispatched", error: { code: code2, message: messageText } });
5530
+ if (!active || active.id !== message.args.operationId || !sameScope3(active.scope, message.scope))
5531
+ return reject("recovery_unavailable", "No matching blocked operation belongs to this session.");
5532
+ if (!(active.timedOut || active.interrupted) || !active.tabId || active.recovering)
5533
+ return reject("recovery_unavailable", "Recovery requires a quarantined tab operation, with no recovery already running.");
5534
+ if (message.args.method !== "close_tab" || typeof message.args.approval !== "string" || !message.args.approval.trim())
5535
+ return reject("approval_required", "Explicit user approval to close the blocked tab is required. This may discard unsaved page state; profile data is retained.");
5536
+ active.recovering = true;
5537
+ const work = (async () => {
5538
+ await this.runtime.closeBlockedTab(active.tabId, message.scope, active.id);
5539
+ await active.done;
5540
+ this.remember(active, { executionState: "target_closed", terminationConfirmed: true, outcome: "unknown", retrySafe: false, replayed: false });
5541
+ if (this.active === active)
5542
+ this.active = undefined;
5543
+ return { recovered: true, operationId: active.id, executionState: "target_closed", terminationConfirmed: true, originalOutcome: "unknown", retrySafe: false, replayed: false, profilePreserved: true };
5544
+ })();
5545
+ let timer;
5546
+ try {
5547
+ const result = await Promise.race([work, new Promise((_, reject2) => {
5548
+ timer = setTimeout(() => reject2(new Error("Recovery timeout")), 5000);
5549
+ })]);
5550
+ send({ type: "result", id: message.id, ok: true, result, outcome: "completed" });
5359
5551
  } catch {
5360
- if (!timedOut)
5361
- send({ type: "result", id: message.id, ok: false, outcome: "unknown", error: { code: "runtime_operation_failed", message: "Operation failed or became uncertain. Observe the page before retrying. Page exception details are suppressed." } });
5552
+ send({ type: "result", id: message.id, ok: false, outcome: "unknown", error: { code: "recovery_uncertain", message: "Recovery completion is unconfirmed. Do not repeat it; query browser_runtime_health or ask the user to stop and restart this dedicated runtime." }, result: { operationId: active.id, retrySafe: false, cancellationConfirmed: false } });
5362
5553
  } finally {
5363
- clearTimeout(timeout2);
5554
+ clearTimeout(timer);
5364
5555
  }
5365
5556
  }
5366
5557
  async upload(bytes, role, name, mimeType) {
5367
5558
  if (bytes.length > 20 * 1024 * 1024)
5368
5559
  throw new Error("Preview exceeds 20 MiB");
5369
- const blobId = randomUUID4(), sha256 = createHash5("sha256").update(bytes).digest("hex");
5560
+ const blobId = randomUUID5(), sha256 = createHash5("sha256").update(bytes).digest("hex");
5370
5561
  const response = await fetch(new URL(`/api/runtime/blobs/${blobId}`, this.server), { method: "PUT", headers: { Authorization: `Bearer ${this.token}`, "Content-Type": "application/octet-stream", "X-Runtime-Instance": this.runtime.instanceId, "X-Content-SHA256": sha256 }, body: bytes, redirect: "error", signal: AbortSignal.timeout(30000) });
5371
5562
  if (!response.ok)
5372
5563
  throw new Error("Preview upload failed");
5373
5564
  return { blobId, role, name, mimeType, size: bytes.length, sha256 };
5374
5565
  }
5375
5566
  async pause() {
5567
+ this.interrupt();
5376
5568
  this.paused = true;
5377
5569
  this.state = "paused";
5378
5570
  this.socket?.close();
@@ -5383,6 +5575,7 @@ class Relay {
5383
5575
  this.paused = false;
5384
5576
  }
5385
5577
  async stop() {
5578
+ this.interrupt();
5386
5579
  this.stopping = true;
5387
5580
  this.socket?.close();
5388
5581
  await this.live?.stop();
@@ -5393,13 +5586,13 @@ class Relay {
5393
5586
  // cli/src/data/index.ts
5394
5587
  import { mkdir as mkdir2, open as open2, rename, unlink as unlink2, rmdir as rmdir2, chmod, lstat as lstat2 } from "node:fs/promises";
5395
5588
  import { createReadStream, createWriteStream } from "node:fs";
5396
- import { randomUUID as randomUUID6, createHash as createHash6 } from "node:crypto";
5589
+ import { randomUUID as randomUUID7, createHash as createHash6 } from "node:crypto";
5397
5590
  import { join as join2, basename } from "node:path";
5398
5591
  import { Readable, Transform } from "node:stream";
5399
5592
  import { pipeline } from "node:stream/promises";
5400
5593
 
5401
5594
  // cli/src/data/vault.ts
5402
- import { randomUUID as randomUUID5 } from "node:crypto";
5595
+ import { randomUUID as randomUUID6 } from "node:crypto";
5403
5596
  class SecretVault {
5404
5597
  access;
5405
5598
  entries = new Map;
@@ -5466,7 +5659,7 @@ class SecretVault {
5466
5659
  }
5467
5660
  if (!Object.keys(clean).length || Object.keys(clean).length > LIMITS.count || total + 1024 > LIMITS.secret)
5468
5661
  throw new Error("Vault quota exceeded");
5469
- const entry = { id: randomUUID5(), scope: { ...scope }, tabId, generation: target2.generation, origin: new URL(target2.frame.url()).origin, expiresAt: Date.now() + LIMITS.ttl, values: clean };
5662
+ const entry = { id: randomUUID6(), scope: { ...scope }, tabId, generation: target2.generation, origin: new URL(target2.frame.url()).origin, expiresAt: Date.now() + LIMITS.ttl, values: clean };
5470
5663
  this.entries.set(entry.id, entry);
5471
5664
  return this.metadata(entry);
5472
5665
  } catch {
@@ -5529,7 +5722,7 @@ async function createDataPlugin(access, options) {
5529
5722
  const resources = new Map, owned = new Set, ownedDirs = new Set, vault = new SecretVault(access);
5530
5723
  let stopped = false;
5531
5724
  function meta(r) {
5532
- return { resourceId: r.id, fileId: r.id, maxBytes: r.size, size: r.size, name: r.name, state: r.state, sha256: r.hash, expiresAt: r.expiresAt };
5725
+ return { resourceId: r.id, fileId: r.id, maxBytes: r.size, size: r.size, name: r.name, state: r.state, sha256: r.hash, expiresAt: r.expiresAt, ...r.purpose === "download" ? { downloadId: r.id, mimeType: "application/octet-stream", sourceKind: "download", readiness: r.state === "ready" ? "ready" : "pending", retrieval: { tool: "browser_create_download", arguments: { downloadId: r.id } } } : {} };
5533
5726
  }
5534
5727
  function get(scope, id) {
5535
5728
  const r = resources.get(String(id));
@@ -5544,7 +5737,7 @@ async function createDataPlugin(access, options) {
5544
5737
  }
5545
5738
  function create(scope, purpose, size, name) {
5546
5739
  reserve(scope, size);
5547
- const r = { id: randomUUID6(), scope: { ...scope }, purpose, size, name: safeName(name), state: "prepared", abort: new AbortController, expiresAt: Date.now() + LIMITS.ttl };
5740
+ const r = { id: randomUUID7(), scope: { ...scope }, purpose, size, name: safeName(name), state: "prepared", abort: new AbortController, expiresAt: Date.now() + LIMITS.ttl };
5548
5741
  resources.set(r.id, r);
5549
5742
  return r;
5550
5743
  }
@@ -5623,7 +5816,8 @@ async function createDataPlugin(access, options) {
5623
5816
  r.state = "ready";
5624
5817
  }
5625
5818
  } catch {
5626
- r.state = "failed";
5819
+ if (r.state !== "cancelled")
5820
+ r.state = "failed";
5627
5821
  if (r.path && owned.has(r.path) && r.purpose === "upload") {
5628
5822
  await unlink2(r.path).catch(() => {});
5629
5823
  owned.delete(r.path);
@@ -5634,6 +5828,11 @@ async function createDataPlugin(access, options) {
5634
5828
  r.bytes?.fill(0);
5635
5829
  r.bytes = undefined;
5636
5830
  }
5831
+ if (r.purpose === "download" && r.state !== "cancelled" && !stopped && resources.get(r.id) === r) {
5832
+ r.authorized = false;
5833
+ r.abort = new AbortController;
5834
+ r.state = "ready";
5835
+ }
5637
5836
  }
5638
5837
  }
5639
5838
  let sweep = setInterval(() => {
@@ -5657,7 +5856,7 @@ async function createDataPlugin(access, options) {
5657
5856
  return meta(r);
5658
5857
  }
5659
5858
  if (op === "create_download") {
5660
- const r = get(scope, args.fileId ?? args.resourceId);
5859
+ const r = get(scope, args.downloadId ?? args.fileId ?? args.resourceId);
5661
5860
  if (r.purpose !== "download" || r.state !== "ready")
5662
5861
  throw new Error("Download unavailable");
5663
5862
  return meta(r);
@@ -6083,7 +6282,7 @@ async function startProfile(root, server, profile, options, groupSignal) {
6083
6282
  return;
6084
6283
  } else if (cmd !== "status")
6085
6284
  throw new Error("Invalid command");
6086
- socket.end(JSON.stringify({ state: relay.state, paused: relay.paused, instanceId: session.instanceId, profile, version: "0.3.11", protocol: 3 }) + `
6285
+ socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.13", protocol: 3 }) + `
6087
6286
  `);
6088
6287
  })().catch(() => socket.destroy());
6089
6288
  });
package/dist/main.js CHANGED
@@ -8,7 +8,7 @@ var args = process.argv.slice(2);
8
8
  var command = args.shift();
9
9
  async function main() {
10
10
  if (!command || command === "--help" || command === "help") {
11
- console.log(`@ricsam/browser-mcp 0.3.11
11
+ console.log(`@ricsam/browser-mcp 0.3.13
12
12
  Usage: browser-mcp browser start|status|pause|resume|stop|recover [options]
13
13
  browser-mcp files upload|download [options]
14
14
  browser-mcp secrets export|exec [options]
@@ -18,15 +18,15 @@ Browser dependencies load only for browser commands. No automatic Chrome downloa
18
18
  return;
19
19
  }
20
20
  if (command === "--version") {
21
- console.log("0.3.11");
21
+ console.log("0.3.13");
22
22
  return;
23
23
  }
24
24
  if (command === "browser")
25
- return (await import("./chunk-hqk1x668.js")).runBrowser(args);
25
+ return (await import("./chunk-vw3wanmm.js")).runBrowser(args);
26
26
  if (command === "files")
27
- return (await import("./chunk-xgk37h9a.js")).runFilesCommand(args);
27
+ return (await import("./chunk-6dypb4ga.js")).runFilesCommand(args);
28
28
  if (command === "secrets")
29
- return (await import("./chunk-847prxk6.js")).runSecretsCommand(args);
29
+ return (await import("./chunk-6kc5yfp5.js")).runSecretsCommand(args);
30
30
  if (command === "forward")
31
31
  return (await import("./chunk-swy0qtx0.js")).runForward(args);
32
32
  throw new Error("Unknown command. Use --help.");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ricsam/browser-mcp",
3
- "version": "0.3.11",
3
+ "version": "0.3.13",
4
4
  "description": "Dedicated native Chrome companion for Browser MCP",
5
5
  "type": "module",
6
6
  "bin": { "browser-mcp": "dist/main.js" },