@ricsam/browser-mcp 0.3.15 → 0.3.17

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,10 +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.15 uses one cross-platform Node package with matching server/chart 0.3.15, native protocol 3 and no database schema change. It adds bounded FIFO operation queuing, broader document access, verified native-download capture, restored snapshot text, known unavailable-download refusals, and early socket-path validation. Keep administrative sign-ins outside automated profiles unless deliberately delegated: internal pages, local files and the Browser MCP dashboard are no longer blanket-blocked, subject to Chrome's interface limits. 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.
6
+ Release 0.3.17 uses one cross-platform Node package with matching server/chart 0.3.17, native protocol 3 and no database schema change. Background screenshots use Chrome's new capture surface without stealing focus; capture and delivery have bounded, sanitized diagnostics. Eligible failed downloads retain their original source for explicit capture-only retry, without replaying website actions or extending the original expiry. Verified readiness is still required before retrieving bytes. Keep administrative sign-ins outside automated profiles unless deliberately delegated: internal pages, local files and the Browser MCP dashboard are no longer blanket-blocked, subject to Chrome's interface limits. 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
7
 
8
8
  ```sh
9
- npm install -g @ricsam/browser-mcp@0.3.15
9
+ npm install -g @ricsam/browser-mcp@0.3.17
10
10
  browser-mcp browser start --server https://browser-mcp.click --profile work
11
11
  browser-mcp browser status --profile work
12
12
  browser-mcp browser pause --profile work
@@ -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.15";
57
+ var version = "0.3.17";
58
58
 
59
59
  // cli/src/browser/chrome-diagnostics.ts
60
60
  import { constants } from "node:fs";
@@ -482,7 +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
+ "--enable-features=WebMCP,WebMCPTesting,DevToolsWebMCPSupport,CDPScreenshotNewSurface",
486
486
  "--disable-extensions",
487
487
  "--disable-component-extensions-with-background-pages",
488
488
  "--disable-sync",
@@ -2015,7 +2015,8 @@ function captureInUtilityWorld({ elements, injected }, options) {
2015
2015
  if (inActiveBranch(item.element))
2016
2016
  priorityRefs.push(ref);
2017
2017
  }
2018
- const matches = options.query ? injected.querySelectorAll(injected.parseSelector(options.query), selectedRoot).filter((element) => (!options.query.startsWith("aria-ref=") || index.refs.has(element)) && injected.elementState(element, "visible").matches && named(element, options.queryName, options.exact)) : [];
2018
+ const queryRoot = options.scope || options.rootIsScope ? selectedRoot : selectedRoot.ownerDocument;
2019
+ const matches = options.query ? injected.querySelectorAll(injected.parseSelector(options.query), queryRoot).filter((element) => (!options.query.startsWith("aria-ref=") || index.refs.has(element)) && injected.elementState(element, "visible").matches && named(element, options.queryName, options.exact)) : [];
2019
2020
  const matchRefs = matches.flatMap((element) => {
2020
2021
  const ref = index.refs.get(element);
2021
2022
  return ref ? [ref] : [];
@@ -2119,7 +2120,8 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
2119
2120
  children.set(ref, await captureFrame(captured.frame, `aria-ref=${ref} >> internal:control=enter-frame >> body,frameset`, {
2120
2121
  ...frameOptions,
2121
2122
  scope: undefined,
2122
- scopeName: undefined
2123
+ scopeName: undefined,
2124
+ rootIsScope: false
2123
2125
  }, false, childPath));
2124
2126
  }));
2125
2127
  const lines = [];
@@ -2137,7 +2139,7 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
2137
2139
  };
2138
2140
  const prefix = (options.frames ?? []).map((selector) => `${selector} >> internal:control=enter-frame >> `).join("");
2139
2141
  const refScope = options.scope?.startsWith("aria-ref=") ? options.scope : undefined;
2140
- document2.text = (await captureFrame(frame, refScope ?? `${prefix}body,frameset`, refScope ? { ...renderOptions, scope: undefined } : renderOptions, true)).join(`
2142
+ document2.text = (await captureFrame(frame, refScope ?? `${prefix}body,frameset`, refScope ? { ...renderOptions, scope: undefined, rootIsScope: true } : renderOptions, true)).join(`
2141
2143
  `);
2142
2144
  return document2;
2143
2145
  }
@@ -2263,7 +2265,7 @@ function renderSnapshot(document2, input) {
2263
2265
  if (document2.unavailableFrames.length)
2264
2266
  notes.push("Some frames disappeared or were unavailable during capture; refresh before treating the observation as complete.");
2265
2267
  if (unrepresentedMatches)
2266
- notes.push(`${unrepresentedMatches} matching elements have no rendered ref. Narrow the selector and read that unique scope.`);
2268
+ notes.push(`${unrepresentedMatches} visible matching elements are not represented by a ref in the ARIA outline. Use browser_inspect with a unique selector for exact DOM details, or read that unique scope for its represented subtree. Pagination only includes represented matches.`);
2267
2269
  if (nextOffset !== null)
2268
2270
  notes.push(`Continue query with offset ${nextOffset} and this snapshotId. A changed observation requires restarting the search.`);
2269
2271
  return {
@@ -3448,21 +3450,31 @@ var messages = {
3448
3450
  runtime_disconnected: "The runtime or browser connection ended.",
3449
3451
  context_destroyed: "The document execution context changed during the operation.",
3450
3452
  execution_timeout: "The browser operation exceeded its internal wait budget.",
3453
+ screenshot_capture_timeout: "Chrome did not finish screenshot preparation/rendering/PNG capture within 15 seconds.",
3454
+ screenshot_upload_timeout: "The captured screenshot did not finish uploading within its remaining transfer budget.",
3451
3455
  script_exception: "The script threw an exception. Page exception text and stack are suppressed.",
3452
3456
  transfer_failed: "The file transfer failed or its completion could not be confirmed.",
3453
3457
  resource_unavailable: "The requested resource is unavailable. No download link was created.",
3454
3458
  scope_rejected: "Runtime scope or tab ownership was rejected.",
3455
3459
  runtime_operation_failed: "The browser operation failed; page-derived details are suppressed."
3456
3460
  };
3457
- function failureFor(error, op, operationId, stage) {
3461
+ function failureFor(error, op, operationId, stage, timing) {
3458
3462
  const text = error instanceof Error ? error.message : "";
3459
3463
  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" : /Protocol error.*(?:not supported|not allowed|wasn't found|Method not found)|Printing is not available|not available in an isolated browser context/i.test(text) ? "browser_operation_unsupported" : stage === "transfer" ? "transfer_failed" : op === "run_js" ? "script_exception" : /download|upload|transfer|resource|grant/i.test(op) ? "transfer_failed" : "runtime_operation_failed";
3464
+ if (op === "screenshot" && code2 === "execution_timeout") {
3465
+ if (stage === "screenshot_capture")
3466
+ code2 = "screenshot_capture_timeout";
3467
+ if (stage === "screenshot_upload")
3468
+ code2 = "screenshot_upload_timeout";
3469
+ }
3470
+ if (op === "screenshot" && stage === "screenshot_upload" && code2 === "runtime_operation_failed")
3471
+ code2 = "transfer_failed";
3460
3472
  const observation = OBSERVATION_OPERATIONS.has(op);
3461
3473
  const outcome = error instanceof RuntimeFault && error.beforeDispatch ? "not_dispatched" : observation ? "failed" : "unknown";
3462
- 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 === "browser_operation_unsupported" ? "Use browser_capabilities for interface prerequisites. Other operations, including navigation away, may still work. For original document bytes use an available website/viewer download control, browser_list_downloads and browser_create_download. Do not replay an uncertain mutation." : 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.";
3474
+ const recovery = error instanceof RuntimeFault ? error.recovery : op === "screenshot" ? "Call browser_runtime_health. A settled screenshot failure can leave admission ready; health does not probe Chrome capture. The stage identifies geometry, capture (including font/render/PNG work), encoding or upload, not a specific Chrome cause. No screenshot was delivered and no automatic retry occurred. Inspect the target before deciding on a fresh screenshot; never replay a prior mutation or recover without approval." : 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 === "browser_operation_unsupported" ? "Use browser_capabilities for interface prerequisites. Other operations, including navigation away, may still work. For original document bytes use an available website/viewer download control, browser_list_downloads and browser_create_download. Do not replay an uncertain mutation." : 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.";
3463
3475
  const diagnosticId = randomUUID4();
3464
- console.error(JSON.stringify({ event: "runtime_failure", diagnosticId, operationId, operation: op, stage, code: code2, outcome }));
3465
- return { error: { code: code2, message: messages[code2] ?? "Runtime operation rejected." }, outcome, result: { diagnosticId, operationId, category: code2, stage, recovery, retrySafe: outcome !== "unknown", executionState: outcome === "not_dispatched" ? "not_started" : "settled", cancellationConfirmed: false } };
3476
+ console.error(JSON.stringify({ event: "runtime_failure", diagnosticId, operationId, operation: op, stage, code: code2, outcome, ...timing }));
3477
+ return { error: { code: code2, message: messages[code2] ?? "Runtime operation rejected." }, outcome, result: { diagnosticId, operationId, category: code2, stage, ...timing, recovery, retrySafe: outcome !== "unknown", executionState: outcome === "not_dispatched" ? "not_started" : "settled", cancellationConfirmed: false } };
3466
3478
  }
3467
3479
 
3468
3480
  // cli/src/browser/browser-runtime.ts
@@ -3473,6 +3485,7 @@ var MAX_RUN_JS_ARTIFACT_COUNT = 32;
3473
3485
  var REF_ACTION_TIMEOUT_MS = 5000;
3474
3486
  var NAVIGATION_TIMEOUT_MS = 20000;
3475
3487
  var READ_PAGE_TIMEOUT_MS = 1e4;
3488
+ var SCREENSHOT_TIMEOUT_MS = 15000;
3476
3489
  var MAX_FULL_PAGE_HEIGHT = 4000;
3477
3490
  var MAX_FULL_PAGE_WIDTH = 4096;
3478
3491
  var MAX_TYPED_KEYS_CHARS = 500;
@@ -4205,7 +4218,14 @@ class BrowserRuntime {
4205
4218
  return result;
4206
4219
  }
4207
4220
  case "screenshot": {
4221
+ execution.screenshotStage?.("screenshot_geometry");
4208
4222
  const state = await page.evaluate(() => ({ url: location.href, scrollX, scrollY, width: innerWidth, height: innerHeight, dpr: devicePixelRatio }));
4223
+ const capture = async (options = {}) => {
4224
+ execution.screenshotStage?.("screenshot_capture");
4225
+ const bytes2 = await page.screenshot({ ...options, type: "png", scale: "css", timeout: SCREENSHOT_TIMEOUT_MS });
4226
+ execution.screenshotStage?.("screenshot_encode");
4227
+ return bytes2;
4228
+ };
4209
4229
  const record = (width, height, originX, originY) => {
4210
4230
  const transform = { id: crypto.randomUUID(), state, width, height, originX, originY };
4211
4231
  this.screenshots.set(tabId, transform);
@@ -4215,10 +4235,11 @@ class BrowserRuntime {
4215
4235
  const crop = input.crop;
4216
4236
  if (crop.x + crop.width > state.width || crop.y + crop.height > state.height)
4217
4237
  throw new Error("Crop must fit the current viewport in CSS pixels");
4218
- const bytes2 = await page.screenshot({ type: "png", scale: "css", clip: crop });
4238
+ const bytes2 = await capture({ clip: crop });
4219
4239
  return { base64: bytes2.toString("base64"), width: crop.width, height: crop.height, ...record(bytes2.readUInt32BE(16), bytes2.readUInt32BE(20), crop.x + state.scrollX, crop.y + state.scrollY) };
4220
4240
  }
4221
4241
  if (input.fullPage === true) {
4242
+ execution.screenshotStage?.("screenshot_metrics");
4222
4243
  const metrics = await page.evaluate(() => ({
4223
4244
  docWidth: Math.max(document.documentElement.scrollWidth, document.documentElement.offsetWidth, document.documentElement.clientWidth, document.body?.scrollWidth ?? 0, document.body?.offsetWidth ?? 0, document.body?.clientWidth ?? 0),
4224
4245
  docHeight: Math.max(document.documentElement.scrollHeight, document.documentElement.offsetHeight, document.documentElement.clientHeight, document.body?.scrollHeight ?? 0, document.body?.offsetHeight ?? 0, document.body?.clientHeight ?? 0)
@@ -4226,16 +4247,15 @@ class BrowserRuntime {
4226
4247
  const width = Math.min(metrics.docWidth, MAX_FULL_PAGE_WIDTH);
4227
4248
  const height = Math.min(metrics.docHeight, MAX_FULL_PAGE_HEIGHT);
4228
4249
  const truncated = metrics.docHeight > MAX_FULL_PAGE_HEIGHT || metrics.docWidth > MAX_FULL_PAGE_WIDTH;
4229
- const bytes2 = truncated ? await page.screenshot({ type: "png", scale: "css", timeout: 15000, fullPage: true, clip: { x: 0, y: 0, width, height } }) : await page.screenshot({ type: "png", scale: "css", timeout: 15000, fullPage: true });
4250
+ const bytes2 = await capture({ fullPage: true, ...truncated ? { clip: { x: 0, y: 0, width, height } } : {} });
4230
4251
  return { base64: bytes2.toString("base64"), width, height, fullPage: true, pageHeight: metrics.docHeight, truncated, ...record(bytes2.readUInt32BE(16), bytes2.readUInt32BE(20), 0, 0) };
4231
4252
  }
4232
- const bytes = await page.screenshot({ type: "png", scale: "css" });
4233
- const viewport = page.viewportSize();
4253
+ const bytes = await capture();
4234
4254
  const cursor = this.cursor.get(tabId);
4235
4255
  return {
4236
4256
  base64: bytes.toString("base64"),
4237
- width: viewport?.width ?? Number(await page.evaluate(() => window.innerWidth)),
4238
- height: viewport?.height ?? Number(await page.evaluate(() => window.innerHeight)),
4257
+ width: bytes.readUInt32BE(16),
4258
+ height: bytes.readUInt32BE(20),
4239
4259
  ...record(bytes.readUInt32BE(16), bytes.readUInt32BE(20), state.scrollX, state.scrollY),
4240
4260
  cursorX: cursor?.x,
4241
4261
  cursorY: cursor?.y,
@@ -4841,7 +4861,7 @@ class NativeRuntime {
4841
4861
  cancelOperation(operationId) {
4842
4862
  this.operations.get(operationId)?.abort(new Error("Runtime operation interrupted; page effects remain uncertain"));
4843
4863
  }
4844
- async execute(op, args, scope, operationId, beforeDispatch) {
4864
+ async execute(op, args, scope, operationId, beforeDispatch, screenshotStage) {
4845
4865
  if (op === "session_end") {
4846
4866
  await this.endSession(scope);
4847
4867
  return { ended: true };
@@ -4855,7 +4875,7 @@ class NativeRuntime {
4855
4875
  set.add(controller);
4856
4876
  this.operations.set(operationId, controller);
4857
4877
  try {
4858
- return await withCancellation(controller.signal, () => this.executeInner(op, args, scope, operationId, beforeDispatch));
4878
+ return await withCancellation(controller.signal, () => this.executeInner(op, args, scope, operationId, beforeDispatch, screenshotStage));
4859
4879
  } finally {
4860
4880
  this.operations.delete(operationId);
4861
4881
  set.delete(controller);
@@ -4863,7 +4883,7 @@ class NativeRuntime {
4863
4883
  this.controllers.delete(key);
4864
4884
  }
4865
4885
  }
4866
- async executeInner(op, args, scope, operationId, beforeDispatch) {
4886
+ async executeInner(op, args, scope, operationId, beforeDispatch, screenshotStage) {
4867
4887
  let dispatched = false;
4868
4888
  const begin = () => {
4869
4889
  this.validateScope(scope);
@@ -4909,7 +4929,7 @@ class NativeRuntime {
4909
4929
  return { tabs: tabs.filter((t) => !this.owners.has(t.tabId) || scopeKey(this.owners.get(t.tabId)) === scopeKey(scope)) };
4910
4930
  }
4911
4931
  try {
4912
- const result = await this.engine.execute(op, args, { sessionId: scopeKey(scope), operationId, beforeDispatch: begin });
4932
+ const result = await this.engine.execute(op, args, { sessionId: scopeKey(scope), operationId, beforeDispatch: begin, screenshotStage });
4913
4933
  if (this.disconnected || (this.epochs.get(scopeKey(scope)) ?? 0) !== operationEpoch)
4914
4934
  throw new Error("Scope ended during execution; outcome uncertain");
4915
4935
  const target2 = op === "capabilities" && typeof args.tabId === "string" ? await this.targetCapabilities(args.tabId, scope) : undefined;
@@ -5399,7 +5419,7 @@ class Relay {
5399
5419
  const state = { quarantined, executionState: active.settled ? active.interrupted ? "settled_after_interruption" : "settled_late" : quarantined ? "unresolved" : "in_progress" };
5400
5420
  if (scope && !sameScope3(active.scope, scope))
5401
5421
  return { ...state, ownedByAnotherScope: true };
5402
- return { ...state, operationId: active.id, operation: active.op, startedAt: active.startedAt, deadlineAt: active.deadlineAt, callerDeadline: active.timedOut ? "expired" : active.interrupted ? "interrupted" : "pending", cancellationConfirmed: false, recoveryAvailable: quarantined && !!active.tabId && !active.recovering };
5422
+ return { ...state, ...active.screenshotStage ? { stage: active.screenshotStage } : {}, operationId: active.id, operation: active.op, startedAt: active.startedAt, deadlineAt: active.deadlineAt, callerDeadline: active.timedOut ? "expired" : active.interrupted ? "interrupted" : "pending", cancellationConfirmed: false, recoveryAvailable: quarantined && !!active.tabId && !active.recovering };
5403
5423
  }
5404
5424
  health(scope) {
5405
5425
  const active = this.active;
@@ -5536,8 +5556,10 @@ class Relay {
5536
5556
  }, 20000);
5537
5557
  heartbeat.unref();
5538
5558
  socket.once("open", () => {
5559
+ if (this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
5560
+ return;
5539
5561
  this.state = "authenticating";
5540
- socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.15", instanceId: this.runtime.instanceId, operations: [...BROWSER_OPERATIONS, ...this.runtime.plugins.flatMap((p) => p.operations), "session_end", "release_tab", "runtime_health", "runtime_recover"], capabilities: ["runtime-queue.v1", "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 } } }));
5562
+ socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.17", instanceId: this.runtime.instanceId, operations: [...BROWSER_OPERATIONS, ...this.runtime.plugins.flatMap((p) => p.operations), "session_end", "release_tab", "runtime_health", "runtime_recover"], capabilities: ["runtime-queue.v1", "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 } } }));
5541
5563
  });
5542
5564
  socket.on("message", (bytes, binary) => {
5543
5565
  if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
@@ -5552,6 +5574,8 @@ class Relay {
5552
5574
  return;
5553
5575
  }
5554
5576
  if (message.type === "ready") {
5577
+ if (this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
5578
+ return;
5555
5579
  if (message.protocol !== 3 || typeof message.browserId !== "string" || !Number.isSafeInteger(message.credentialEpoch) || message.credentialEpoch < 1 || this.state !== "authenticating") {
5556
5580
  socket.close(1002);
5557
5581
  return;
@@ -5559,6 +5583,8 @@ class Relay {
5559
5583
  this.state = "initializing";
5560
5584
  (async () => {
5561
5585
  await this.runtime.reconnect(message.browserId);
5586
+ if (this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
5587
+ return;
5562
5588
  this.state = "connected";
5563
5589
  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) => {
5564
5590
  try {
@@ -5695,7 +5721,15 @@ class Relay {
5695
5721
  finish = resolve2;
5696
5722
  }), interrupt: () => interrupt(), expire: () => expire() };
5697
5723
  this.active = active;
5698
- let stage = "execute", timer;
5724
+ let stage = message.op === "screenshot" ? "screenshot_prepare" : "execute", stageStartedAt = Date.now(), timer;
5725
+ const screenshotStage = message.op === "screenshot" ? (next) => {
5726
+ stage = next;
5727
+ stageStartedAt = Date.now();
5728
+ active.screenshotStage = next;
5729
+ } : undefined;
5730
+ screenshotStage?.("screenshot_prepare");
5731
+ const timing = () => message.op === "screenshot" ? { elapsedMs: Math.max(0, Date.now() - active.startedAt), stageElapsedMs: Math.max(0, Date.now() - stageStartedAt) } : undefined;
5732
+ const screenshotUpload = new AbortController;
5699
5733
  const expired = new Promise((resolve2) => {
5700
5734
  const terminal = (cancelled) => {
5701
5735
  if (active.interrupted || active.settled)
@@ -5712,7 +5746,10 @@ class Relay {
5712
5746
  else
5713
5747
  active.timedOut = true;
5714
5748
  clearTimeout(timer);
5715
- send({ type: "result", id: message.id, ok: false, outcome: !active.dispatched ? "not_dispatched" : OBSERVATION_OPERATIONS.has(message.op) ? "failed" : "unknown", error: { code: cancelled ? "runtime_interrupted" : "runtime_timeout", message: active.dispatched ? "Execution is not confirmed cancelled; do not replay a mutation." : "Interrupted or expired before browser dispatch; no action was dispatched." }, result: { operationId: active.id, diagnosticId: active.id, category: cancelled ? "execution_interrupted" : "execution_timeout", stage, callerDeadline: cancelled ? "interrupted" : "expired", executionState: active.dispatched ? "unresolved" : "not_started", quarantined: true, cancellationConfirmed: !active.dispatched, retrySafe: !active.dispatched, recovery: "Use browser_runtime_health independently. Never replay uncertain work; request explicit user-approved recovery if needed." } });
5749
+ screenshotUpload.abort();
5750
+ if (message.op === "screenshot")
5751
+ console.error(JSON.stringify({ event: "runtime_failure", diagnosticId: active.id, operationId: active.id, operation: message.op, stage, code: cancelled ? "runtime_interrupted" : "runtime_timeout", outcome: active.dispatched ? "failed" : "not_dispatched", ...timing() }));
5752
+ send({ type: "result", id: message.id, ok: false, outcome: !active.dispatched ? "not_dispatched" : OBSERVATION_OPERATIONS.has(message.op) ? "failed" : "unknown", error: { code: cancelled ? "runtime_interrupted" : "runtime_timeout", message: active.dispatched ? "Execution is not confirmed cancelled; do not replay a mutation." : "Interrupted or expired before browser dispatch; no action was dispatched." }, result: { operationId: active.id, diagnosticId: active.id, category: cancelled ? "execution_interrupted" : "execution_timeout", stage, ...timing(), callerDeadline: cancelled ? "interrupted" : "expired", executionState: active.dispatched ? "unresolved" : "not_started", quarantined: true, cancellationConfirmed: !active.dispatched, retrySafe: !active.dispatched, recovery: "Use browser_runtime_health independently. Never replay uncertain work; request explicit user-approved recovery if needed." } });
5716
5753
  this.flushWaiting("blocked_by_prior_operation", "A prior operation timed out or was interrupted. This waiting request was never dispatched.");
5717
5754
  if (cancelled)
5718
5755
  this.runtime.cancelOperation(active.id);
@@ -5731,7 +5768,7 @@ class Relay {
5731
5768
  entry.guard(!active.dispatched);
5732
5769
  active.dispatched = true;
5733
5770
  };
5734
- const result = await this.runtime.execute(message.op, message.args, message.scope, message.id, beforeDispatch);
5771
+ const result = await this.runtime.execute(message.op, message.args, message.scope, message.id, beforeDispatch, screenshotStage);
5735
5772
  if (active.timedOut || active.interrupted || this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
5736
5773
  return;
5737
5774
  this.runtime.validateScope(message.scope);
@@ -5742,9 +5779,15 @@ class Relay {
5742
5779
  stage = "transfer";
5743
5780
  const blobs = [];
5744
5781
  if (result?.base64 && message.op === "screenshot") {
5782
+ screenshotStage?.("screenshot_encode");
5745
5783
  const bytes = Buffer.from(result.base64, "base64");
5746
5784
  delete result.base64;
5747
- blobs.push(await this.upload(bytes, "screenshot", "screenshot.png", "image/png"));
5785
+ screenshotStage?.("screenshot_upload");
5786
+ const remaining = active.deadlineAt - Date.now() - 1000;
5787
+ if (remaining <= 0)
5788
+ throw new RuntimeFault("screenshot_upload_timeout", "Call browser_runtime_health. Capture completed but there was no remaining upload budget; no image was delivered and no automatic retry occurred.");
5789
+ blobs.push(await this.upload(bytes, "screenshot", "screenshot.png", "image/png", AbortSignal.any([screenshotUpload.signal, AbortSignal.timeout(Math.min(1e4, remaining))])));
5790
+ screenshotStage?.("screenshot_reply");
5748
5791
  }
5749
5792
  if (message.op === "export_page" && Array.isArray(result?.exports))
5750
5793
  for (const item of result.exports) {
@@ -5768,19 +5811,25 @@ class Relay {
5768
5811
  throw new Error("Result budget exceeded");
5769
5812
  response = { type: "result", id: message.id, ok: true, result: wireResult(message.op, result), blobs, outcome: result?.status === "unknown" ? "unknown" : "completed" };
5770
5813
  } catch (error) {
5771
- const failure = failureFor(error, message.op, message.id, stage);
5772
- if (failure.error.code === "context_destroyed" && active.tabId) {
5773
- for (const waiting of [...this.waiting])
5774
- if (waiting.message.args.tabId === active.tabId)
5775
- this.rejectWaiting(waiting, "stale_queued_request", "The target document changed while waiting. No action was dispatched; observe it again before submitting a fresh request.");
5814
+ if (message.op === "screenshot" && (active.timedOut || active.interrupted)) {
5815
+ console.error(JSON.stringify({ event: "screenshot_late_settlement", operationId: active.id, stage, ...timing(), callerDeadline: active.interrupted ? "interrupted" : "expired" }));
5816
+ } else {
5817
+ const failure = failureFor(error, message.op, message.id, stage, timing());
5818
+ if (message.op === "screenshot")
5819
+ this.remember(active, { operation: message.op, ...failure.result, outcome: failure.outcome });
5820
+ if (failure.error.code === "context_destroyed" && active.tabId) {
5821
+ for (const waiting of [...this.waiting])
5822
+ if (waiting.message.args.tabId === active.tabId)
5823
+ this.rejectWaiting(waiting, "stale_queued_request", "The target document changed while waiting. No action was dispatched; observe it again before submitting a fresh request.");
5824
+ }
5825
+ response = { type: "result", id: message.id, ok: false, ...failure };
5776
5826
  }
5777
- response = { type: "result", id: message.id, ok: false, ...failure };
5778
5827
  } finally {
5779
5828
  clearTimeout(timer);
5780
5829
  active.settled = true;
5781
5830
  finish();
5782
5831
  if (active.timedOut || active.interrupted)
5783
- this.remember(active, { callerDeadline: active.timedOut ? "expired" : "interrupted", executionState: active.interrupted ? "settled_after_interruption" : "settled_late", outcome: "unknown", retrySafe: false, cancellationConfirmed: false });
5832
+ this.remember(active, { ...message.op === "screenshot" ? { operation: message.op, stage, ...timing() } : {}, callerDeadline: active.timedOut ? "expired" : "interrupted", executionState: active.interrupted ? "settled_after_interruption" : "settled_late", outcome: "unknown", retrySafe: false, cancellationConfirmed: false });
5784
5833
  if (this.active === active && (!active.interrupted || !active.dispatched) && !active.recovering)
5785
5834
  this.active = undefined;
5786
5835
  }
@@ -5821,11 +5870,11 @@ class Relay {
5821
5870
  clearTimeout(timer);
5822
5871
  }
5823
5872
  }
5824
- async upload(bytes, role, name, mimeType) {
5873
+ async upload(bytes, role, name, mimeType, signal = AbortSignal.timeout(30000)) {
5825
5874
  if (bytes.length > 20 * 1024 * 1024)
5826
5875
  throw new Error("Preview exceeds 20 MiB");
5827
5876
  const blobId = randomUUID5(), sha256 = createHash5("sha256").update(bytes).digest("hex");
5828
- 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) });
5877
+ 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 });
5829
5878
  if (!response.ok)
5830
5879
  throw new Error("Preview upload failed");
5831
5880
  return { blobId, role, name, mimeType, size: bytes.length, sha256 };
@@ -5839,7 +5888,10 @@ class Relay {
5839
5888
  await this.runtime.disconnect();
5840
5889
  }
5841
5890
  resume() {
5891
+ if (!this.paused)
5892
+ return;
5842
5893
  this.paused = false;
5894
+ this.state = "reconnecting";
5843
5895
  }
5844
5896
  async stop() {
5845
5897
  this.stopping = true;
@@ -5851,9 +5903,9 @@ class Relay {
5851
5903
  }
5852
5904
 
5853
5905
  // cli/src/data/index.ts
5854
- import { mkdir as mkdir2, open as open3, rename, unlink as unlink2, rmdir as rmdir2, lstat as lstat2 } from "node:fs/promises";
5906
+ import { mkdir as mkdir2, open as open3, rename, unlink as unlink3, rmdir as rmdir2, lstat as lstat3 } from "node:fs/promises";
5855
5907
  import { createReadStream, createWriteStream as createWriteStream2 } from "node:fs";
5856
- import { randomUUID as randomUUID7, createHash as createHash7 } from "node:crypto";
5908
+ import { randomUUID as randomUUID8, createHash as createHash7 } from "node:crypto";
5857
5909
  import { join as join2, basename } from "node:path";
5858
5910
  import { Readable, Transform as Transform2 } from "node:stream";
5859
5911
  import { pipeline as pipeline2 } from "node:stream/promises";
@@ -5979,21 +6031,50 @@ class SecretVault {
5979
6031
 
5980
6032
  // cli/src/data/download-capture.ts
5981
6033
  import { constants as constants3, createWriteStream } from "node:fs";
5982
- import { open as open2 } from "node:fs/promises";
5983
- import { createHash as createHash6 } from "node:crypto";
6034
+ import { lstat as lstat2, open as open2, unlink as unlink2 } from "node:fs/promises";
6035
+ import { createHash as createHash6, randomUUID as randomUUID7 } from "node:crypto";
6036
+ import { dirname as dirname2, resolve as resolve2 } from "node:path";
5984
6037
  import { Transform } from "node:stream";
5985
6038
  import { pipeline } from "node:stream/promises";
6039
+ var filesystemReasons = new Set(["ENOENT", "EACCES", "EPERM", "ELOOP", "ENOTDIR", "EMFILE", "ENFILE", "EIO", "ENOSPC"]);
6040
+ function captureEvidence() {
6041
+ return { method: "completed-browser-file", stage: "completion", browserCompletion: "pending", comparison: "pending" };
6042
+ }
6043
+ function reasonFor(error) {
6044
+ if (error instanceof CaptureError)
6045
+ return error.reason;
6046
+ const code2 = error?.code;
6047
+ return typeof code2 === "string" && filesystemReasons.has(code2) ? code2 : "unknown";
6048
+ }
6049
+ async function sourceAvailability(source) {
6050
+ if (!source.path)
6051
+ return "unconfirmed";
6052
+ try {
6053
+ const stat = await lstat2(source.path);
6054
+ if (!stat.isFile() || stat.isSymbolicLink())
6055
+ return "unsafe";
6056
+ if (source.identity && (source.identity.dev !== stat.dev || source.identity.ino !== stat.ino))
6057
+ return "unsafe";
6058
+ source.identity ??= { dev: stat.dev, ino: stat.ino };
6059
+ return "present";
6060
+ } catch (error) {
6061
+ return ["ENOENT", "ENOTDIR"].includes(reasonFor(error)) ? "unavailable" : "unconfirmed";
6062
+ }
6063
+ }
6064
+
5986
6065
  class CaptureError extends Error {
5987
6066
  code;
5988
- constructor(code2) {
6067
+ reason;
6068
+ constructor(code2, reason = "unknown") {
5989
6069
  super(code2);
5990
6070
  this.code = code2;
6071
+ this.reason = reason;
5991
6072
  }
5992
6073
  }
5993
6074
  async function duringCapture(work, signal) {
5994
6075
  let abort;
5995
6076
  const cancelled = new Promise((_, reject) => {
5996
- abort = () => reject(new CaptureError("download_capture_cancelled"));
6077
+ abort = () => reject(new CaptureError("download_capture_cancelled", "cancelled"));
5997
6078
  signal.addEventListener("abort", abort, { once: true });
5998
6079
  if (signal.aborted)
5999
6080
  abort();
@@ -6019,32 +6100,45 @@ function contentValidation(name, size) {
6019
6100
  warning: "The completed browser file is empty. This may be intentional; no document validity is implied."
6020
6101
  };
6021
6102
  }
6022
- async function captureDownload(download, destination, signal, evidence) {
6023
- const failure = await duringCapture(download.failure(), signal);
6024
- evidence.browserCompletion = failure === null ? "completed" : "failed";
6025
- if (failure !== null)
6026
- throw new CaptureError("download_capture_browser_failed");
6027
- const path10 = await duringCapture(download.path(), signal);
6028
- signal.throwIfAborted();
6029
- evidence.stage = "browser-file";
6103
+ async function captureDownload(browserSource, destination, signal, evidence) {
6104
+ const { download } = browserSource;
6105
+ let operation = "completion";
6030
6106
  let source;
6031
6107
  let retained2;
6032
6108
  try {
6033
- source = await open2(path10, constants3.O_RDONLY | constants3.O_NOFOLLOW);
6109
+ const failure = await duringCapture(download.failure(), signal);
6110
+ evidence.browserCompletion = failure === null ? "completed" : "failed";
6111
+ if (failure !== null)
6112
+ throw new CaptureError("download_capture_browser_failed", "browser-failed");
6113
+ operation = "path";
6114
+ const path10 = await duringCapture(download.path(), signal);
6115
+ signal.throwIfAborted();
6116
+ evidence.stage = "browser-file";
6117
+ if (dirname2(resolve2(path10)) !== resolve2(browserSource.directory) || browserSource.path && path10 !== browserSource.path)
6118
+ throw new CaptureError("download_capture_source_unavailable", "unsafe-path");
6119
+ browserSource.path = path10;
6120
+ operation = "open";
6121
+ source = await open2(path10, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
6122
+ operation = "stat";
6034
6123
  const before = await source.stat();
6035
6124
  if (!before.isFile())
6036
- throw new CaptureError("download_capture_source_unavailable");
6125
+ throw new CaptureError("download_capture_source_unavailable", "not-regular-file");
6126
+ if (browserSource.identity && (before.dev !== browserSource.identity.dev || before.ino !== browserSource.identity.ino))
6127
+ throw new CaptureError("download_capture_source_unavailable", "source-changed");
6128
+ browserSource.identity = { dev: before.dev, ino: before.ino };
6129
+ evidence.sourceAvailability = "present";
6037
6130
  evidence.browser = { size: before.size };
6038
6131
  if (before.size > LIMITS.file)
6039
- throw new CaptureError("download_quota_exceeded");
6132
+ throw new CaptureError("download_quota_exceeded", "quota-exceeded");
6040
6133
  signal.throwIfAborted();
6041
6134
  evidence.stage = "copy";
6135
+ operation = "copy";
6042
6136
  let size = 0;
6043
6137
  const hash = createHash6("sha256");
6044
6138
  const bound = new Transform({ transform(chunk, _encoding, callback) {
6045
6139
  size += chunk.length;
6046
6140
  if (size > LIMITS.file)
6047
- return callback(new CaptureError("download_quota_exceeded"));
6141
+ return callback(new CaptureError("download_quota_exceeded", "quota-exceeded"));
6048
6142
  hash.update(chunk);
6049
6143
  callback(null, chunk);
6050
6144
  } });
@@ -6052,6 +6146,7 @@ async function captureDownload(download, destination, signal, evidence) {
6052
6146
  const sourceHash = hash.digest("hex");
6053
6147
  evidence.browser.sha256 = sourceHash;
6054
6148
  evidence.stage = "verification";
6149
+ operation = "verification";
6055
6150
  retained2 = await open2(destination, constants3.O_RDONLY | constants3.O_NOFOLLOW);
6056
6151
  const disk = await retained2.stat();
6057
6152
  if (!disk.isFile() || disk.size > LIMITS.file)
@@ -6061,7 +6156,7 @@ async function captureDownload(download, destination, signal, evidence) {
6061
6156
  for await (const chunk of retained2.createReadStream({ start: 0, autoClose: false, signal })) {
6062
6157
  diskSize += chunk.length;
6063
6158
  if (diskSize > LIMITS.file)
6064
- throw new CaptureError("download_quota_exceeded");
6159
+ throw new CaptureError("download_quota_exceeded", "quota-exceeded");
6065
6160
  diskHash.update(chunk);
6066
6161
  }
6067
6162
  evidence.retained = { size: diskSize, sha256: diskHash.digest("hex") };
@@ -6069,32 +6164,53 @@ async function captureDownload(download, destination, signal, evidence) {
6069
6164
  const diskAfter = await retained2.stat();
6070
6165
  if (size !== before.size || disk.size !== size || diskSize !== size || evidence.retained.sha256 !== sourceHash || after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs || diskAfter.size !== disk.size || diskAfter.mtimeMs !== disk.mtimeMs || diskAfter.ctimeMs !== disk.ctimeMs) {
6071
6166
  evidence.comparison = "mismatched";
6072
- throw new CaptureError("download_capture_mismatch");
6167
+ throw new CaptureError("download_capture_mismatch", "source-changed");
6073
6168
  }
6074
6169
  signal.throwIfAborted();
6075
6170
  evidence.comparison = "matched";
6076
6171
  evidence.stage = "verified";
6077
6172
  return { size, sha256: sourceHash };
6173
+ } catch (error) {
6174
+ const reason = signal.aborted ? "cancelled" : reasonFor(error);
6175
+ evidence.diagnostic = { id: randomUUID7(), operation, reason };
6176
+ evidence.sourceAvailability = ["unsafe-path", "source-changed", "not-regular-file", "ELOOP"].includes(reason) ? "unsafe" : await sourceAvailability(browserSource);
6177
+ throw error instanceof CaptureError ? error : new CaptureError(signal.aborted ? "download_capture_cancelled" : ["path", "open", "stat"].includes(operation) ? "download_capture_source_unavailable" : "download_capture_failed", reason);
6078
6178
  } finally {
6079
- try {
6080
- await retained2?.close();
6081
- } finally {
6082
- await source?.close();
6083
- }
6179
+ await retained2?.close().catch(() => {});
6180
+ await source?.close().catch(() => {});
6084
6181
  }
6085
6182
  }
6086
- async function cleanupDownload(download, evidence) {
6183
+ async function cleanupDownload(source, evidence) {
6087
6184
  let timer;
6088
6185
  try {
6089
6186
  const deleted = await Promise.race([
6090
- download.delete().then(() => true, () => false),
6091
- new Promise((resolve2) => {
6092
- timer = setTimeout(() => resolve2(false), 2000);
6187
+ (async () => {
6188
+ if (!source.path) {
6189
+ const path10 = await source.download.path().catch(() => {
6190
+ return;
6191
+ });
6192
+ if (path10 && dirname2(resolve2(path10)) === resolve2(source.directory))
6193
+ source.path = path10;
6194
+ }
6195
+ await source.download.delete().catch(() => {});
6196
+ if (!source.path)
6197
+ return false;
6198
+ await unlink2(source.path).catch(() => {});
6199
+ try {
6200
+ await lstat2(source.path);
6201
+ return false;
6202
+ } catch (error) {
6203
+ return reasonFor(error) === "ENOENT";
6204
+ }
6205
+ })(),
6206
+ new Promise((resolve3) => {
6207
+ timer = setTimeout(() => resolve3(false), 2000);
6093
6208
  timer.unref?.();
6094
6209
  })
6095
6210
  ]);
6096
6211
  if (evidence)
6097
6212
  evidence.cleanup = deleted ? "deleted" : "browser-context";
6213
+ return deleted;
6098
6214
  } finally {
6099
6215
  clearTimeout(timer);
6100
6216
  }
@@ -6119,6 +6235,10 @@ async function createDataPlugin(access, options) {
6119
6235
  while (terminal.size > 128)
6120
6236
  terminal.delete(terminal.keys().next().value);
6121
6237
  }
6238
+ function failClosed() {
6239
+ stopped = true;
6240
+ options.onSourceCleanupFailure();
6241
+ }
6122
6242
  function status(scope, id) {
6123
6243
  const t = terminal.get(String(id));
6124
6244
  if (t && t.until >= Date.now() && sameScope(t.scope, scope))
@@ -6126,7 +6246,17 @@ async function createDataPlugin(access, options) {
6126
6246
  return meta(get(scope, id));
6127
6247
  }
6128
6248
  function meta(r) {
6129
- return { resourceId: r.id, fileId: r.id, maxBytes: r.size, size: r.purpose === "download" && !r.hash ? undefined : 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" ? r.size === 0 ? "ready-with-warning" : "ready" : "pending", capture: r.capture, contentValidation: r.contentValidation, retrieval: { tool: "browser_create_download", arguments: { downloadId: r.id } } } : {} };
6249
+ const failed = r.state === "capture-failed";
6250
+ return { resourceId: r.id, fileId: r.id, maxBytes: r.size, size: r.purpose === "download" && !r.hash ? undefined : r.size, name: r.name, state: r.state, sha256: r.hash, expiresAt: r.expiresAt, ...r.purpose === "download" ? {
6251
+ downloadId: r.id,
6252
+ mimeType: "application/octet-stream",
6253
+ sourceKind: "download",
6254
+ readiness: r.state === "ready" ? r.size === 0 ? "ready-with-warning" : "ready" : failed ? "unavailable" : "pending",
6255
+ capture: r.capture,
6256
+ contentValidation: r.contentValidation,
6257
+ ...r.state === "ready" ? { retrieval: { tool: "browser_create_download", arguments: { downloadId: r.id } } } : {},
6258
+ ...failed ? { code: r.terminalCode, retry: { tool: "browser_retry_download_capture", arguments: { downloadId: r.id } }, recovery: r.capture?.sourceAvailability === "unavailable" ? "The completed browser source is unavailable at its original location. No bytes are ready. Capture-only retry cannot recreate missing bytes; never automatically repeat the website action." : "Only capture failed; any remaining completed browser source is held until expiresAt under the original reservation. Retry capture explicitly with this downloadId; it never repeats the website action. Source availability is not proof of readable bytes." } : {}
6259
+ } : {} };
6130
6260
  }
6131
6261
  function get(scope, id) {
6132
6262
  const r = resources.get(String(id));
@@ -6134,35 +6264,64 @@ async function createDataPlugin(access, options) {
6134
6264
  throw new Error("Unknown resource");
6135
6265
  return r;
6136
6266
  }
6137
- function reserve(scope, size) {
6138
- const all = [...resources.values()].filter((r) => !["failed", "cancelled"].includes(r.state));
6139
- if (stopped || !Number.isSafeInteger(size) || size < 0 || size > LIMITS.file || all.length >= 128 || all.reduce((n, r) => n + r.size, 0) + size > LIMITS.browser || all.filter((r) => sameScope(r.scope, scope)).reduce((n, r) => n + r.size, 0) + size > LIMITS.session)
6267
+ const reserved = (r) => r.source ? 2 * LIMITS.file : r.size;
6268
+ function reserve(scope, size, purpose) {
6269
+ const all = [...resources.values()];
6270
+ const cost = purpose === "download" ? 2 * size : size;
6271
+ if (stopped || !Number.isSafeInteger(size) || size < 0 || size > LIMITS.file || all.length >= 128 || all.reduce((n, r) => n + reserved(r), 0) + cost > LIMITS.browser || all.filter((r) => sameScope(r.scope, scope)).reduce((n, r) => n + r.size, 0) + size > LIMITS.session)
6140
6272
  throw new Error("Local data quota exceeded");
6141
6273
  }
6142
6274
  function create(scope, purpose, size, name) {
6143
- reserve(scope, size);
6144
- const r = { id: randomUUID7(), scope: { ...scope }, purpose, size, name: safeName(name), state: "prepared", abort: new AbortController, expiresAt: Date.now() + LIMITS.ttl };
6275
+ reserve(scope, size, purpose);
6276
+ const r = { id: randomUUID8(), scope: { ...scope }, purpose, size, name: safeName(name), state: "prepared", abort: new AbortController, expiresAt: Date.now() + LIMITS.ttl };
6145
6277
  resources.set(r.id, r);
6146
6278
  return r;
6147
6279
  }
6280
+ async function discardCopy(r) {
6281
+ if (r.path && owned.has(r.path)) {
6282
+ await unlink3(r.path).catch((error) => {
6283
+ if (error.code !== "ENOENT")
6284
+ throw error;
6285
+ });
6286
+ owned.delete(r.path);
6287
+ r.path = undefined;
6288
+ }
6289
+ }
6148
6290
  async function remove(r) {
6291
+ if (r.removal)
6292
+ return r.removal;
6149
6293
  r.terminalCode ??= "download_revoked";
6150
6294
  r.abort.abort();
6151
6295
  r.state = "cancelled";
6152
- await r.task?.catch(() => {});
6153
- remember(r);
6154
- r.bytes?.fill(0);
6155
- r.bytes = undefined;
6156
- if (r.path && owned.has(r.path)) {
6157
- await unlink2(r.path).catch(() => {});
6158
- owned.delete(r.path);
6159
- }
6160
- const dir = join2(options.directory, r.id);
6161
- if (ownedDirs.has(dir)) {
6162
- await rmdir2(dir).catch(() => {});
6163
- ownedDirs.delete(dir);
6296
+ r.removal = (async () => {
6297
+ await r.task?.catch(() => {});
6298
+ const deleted = !r.source || await cleanupDownload(r.source, r.capture);
6299
+ if (deleted)
6300
+ r.source = undefined;
6301
+ else
6302
+ failClosed();
6303
+ remember(r);
6304
+ r.bytes?.fill(0);
6305
+ r.bytes = undefined;
6306
+ try {
6307
+ await discardCopy(r);
6308
+ } catch {
6309
+ failClosed();
6310
+ return;
6311
+ }
6312
+ const dir = join2(options.directory, r.id);
6313
+ if (ownedDirs.has(dir)) {
6314
+ await rmdir2(dir).catch(() => {});
6315
+ ownedDirs.delete(dir);
6316
+ }
6317
+ if (deleted)
6318
+ resources.delete(r.id);
6319
+ })();
6320
+ try {
6321
+ await r.removal;
6322
+ } finally {
6323
+ r.removal = undefined;
6164
6324
  }
6165
- resources.delete(r.id);
6166
6325
  }
6167
6326
  async function revoke(predicate) {
6168
6327
  vault.revoke(predicate);
@@ -6211,7 +6370,7 @@ async function createDataPlugin(access, options) {
6211
6370
  } else {
6212
6371
  if (!r.path)
6213
6372
  throw new Error("Missing file");
6214
- const stat = await lstat2(r.path);
6373
+ const stat = await lstat3(r.path);
6215
6374
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== r.size)
6216
6375
  throw new Error("Changed file");
6217
6376
  body = Readable.toWeb(createReadStream(r.path));
@@ -6225,7 +6384,7 @@ async function createDataPlugin(access, options) {
6225
6384
  if (r.state !== "cancelled")
6226
6385
  r.state = "failed";
6227
6386
  if (r.path && owned.has(r.path) && r.purpose === "upload") {
6228
- await unlink2(r.path).catch(() => {});
6387
+ await unlink3(r.path).catch(() => {});
6229
6388
  owned.delete(r.path);
6230
6389
  }
6231
6390
  } finally {
@@ -6243,6 +6402,8 @@ async function createDataPlugin(access, options) {
6243
6402
  }
6244
6403
  async function sweepExpired() {
6245
6404
  await revoke((r) => {
6405
+ if (r.state === "cancelled")
6406
+ return true;
6246
6407
  if (r.expiresAt < Date.now() && r.state !== "attached") {
6247
6408
  r.terminalCode = "download_expired";
6248
6409
  return true;
@@ -6253,12 +6414,73 @@ async function createDataPlugin(access, options) {
6253
6414
  if (t.until < Date.now())
6254
6415
  terminal.delete(id);
6255
6416
  }
6417
+ function startCapture(r) {
6418
+ r.state = "capturing";
6419
+ r.terminalCode = undefined;
6420
+ r.capture = captureEvidence();
6421
+ r.abort = new AbortController;
6422
+ const source = r.source;
6423
+ const valid = () => !r.abort.signal.aborted && !stopped && resources.get(r.id) === r && r.expiresAt > Date.now();
6424
+ const cancel = () => {
6425
+ if (r.capture?.browserCompletion !== "completed")
6426
+ source.download.cancel().catch(() => {});
6427
+ };
6428
+ r.abort.signal.addEventListener("abort", cancel, { once: true });
6429
+ const timeout2 = setTimeout(() => {
6430
+ r.terminalCode ??= "download_capture_timeout";
6431
+ r.abort.abort();
6432
+ }, Math.max(1, Math.min(LIMITS.duration, r.expiresAt - Date.now())));
6433
+ timeout2.unref?.();
6434
+ const task = (async () => {
6435
+ try {
6436
+ await discardCopy(r);
6437
+ const path10 = join2(options.directory, r.id);
6438
+ r.path = path10;
6439
+ owned.add(path10);
6440
+ const verified = await captureDownload(source, path10, r.abort.signal, r.capture);
6441
+ if (!valid())
6442
+ throw new CaptureError("download_capture_cancelled", "cancelled");
6443
+ r.size = verified.size;
6444
+ r.hash = verified.sha256;
6445
+ r.contentValidation = contentValidation(r.name, verified.size);
6446
+ if (await cleanupDownload(source, r.capture))
6447
+ r.source = undefined;
6448
+ if (!valid())
6449
+ throw new CaptureError("download_capture_cancelled", "cancelled");
6450
+ r.state = "ready";
6451
+ } catch (error) {
6452
+ r.terminalCode ??= error instanceof CaptureError ? error.code : "download_capture_failed";
6453
+ r.hash = undefined;
6454
+ r.contentValidation = undefined;
6455
+ r.size = LIMITS.file;
6456
+ let discarded = true;
6457
+ try {
6458
+ await discardCopy(r);
6459
+ } catch {
6460
+ discarded = false;
6461
+ }
6462
+ if (valid() && discarded && r.capture?.browserCompletion === "completed" && r.capture.sourceAvailability !== "unsafe" && r.terminalCode !== "download_quota_exceeded") {
6463
+ r.capture.cleanup = "retained";
6464
+ r.state = "capture-failed";
6465
+ } else
6466
+ r.state = "cancelled";
6467
+ } finally {
6468
+ clearTimeout(timeout2);
6469
+ r.abort.signal.removeEventListener("abort", cancel);
6470
+ }
6471
+ })();
6472
+ r.task = task;
6473
+ return task.then(async () => {
6474
+ if (r.state === "cancelled")
6475
+ await remove(r);
6476
+ });
6477
+ }
6256
6478
  let sweep = setInterval(() => {
6257
6479
  sweepExpired();
6258
6480
  }, 1e4);
6259
6481
  sweep.unref?.();
6260
6482
  return {
6261
- operations: ["create_upload", "create_download", "transfer_status", "cancel_transfer", "upload_files", "list_downloads", "capture_secrets", "list_secrets", "delete_secrets", "create_secret_export", "authorize_data"],
6483
+ operations: ["create_upload", "create_download", "retry_download_capture", "transfer_status", "cancel_transfer", "upload_files", "list_downloads", "capture_secrets", "list_secrets", "delete_secrets", "create_secret_export", "authorize_data"],
6262
6484
  async execute(op, args, scope) {
6263
6485
  if (stopped)
6264
6486
  throw new Error("Data runtime disconnected");
@@ -6279,6 +6501,13 @@ async function createDataPlugin(access, options) {
6279
6501
  throw new RuntimeFault("resource_unavailable", "Use browser_list_downloads to select an available retained downloadId in this session. If no retained bytes are available, ask before recreating them; never automatically replay the website action, export or script.", true);
6280
6502
  return meta(r);
6281
6503
  }
6504
+ if (op === "retry_download_capture") {
6505
+ const r = resources.get(String(args.downloadId));
6506
+ if (!r || !sameScope(r.scope, scope) || r.expiresAt <= Date.now() || r.purpose !== "download" || r.state !== "capture-failed" || !r.source)
6507
+ throw new RuntimeFault("resource_unavailable", "Use browser_list_downloads in this session to select a capture-failed source before its original expiry. Never replay the website action.", true);
6508
+ startCapture(r).catch(() => {});
6509
+ return meta(r);
6510
+ }
6282
6511
  if (op === "transfer_status") {
6283
6512
  await sweepExpired();
6284
6513
  return status(scope, args.resourceId ?? args.transferId);
@@ -6303,7 +6532,7 @@ async function createDataPlugin(access, options) {
6303
6532
  }
6304
6533
  if (op === "list_downloads") {
6305
6534
  await sweepExpired();
6306
- return { files: [...resources.values()].filter((r) => sameScope(r.scope, scope) && r.purpose === "download").map(meta), terminal: [...terminal.values()].filter((t) => sameScope(t.scope, scope)).map((t) => t.meta) };
6535
+ return { files: [...resources.values()].filter((r) => sameScope(r.scope, scope) && r.purpose === "download" && r.state !== "cancelled").map(meta), terminal: [...terminal.values()].filter((t) => sameScope(t.scope, scope)).map((t) => t.meta) };
6307
6536
  }
6308
6537
  if (op === "upload_files") {
6309
6538
  const ids = args.fileIds;
@@ -6358,10 +6587,8 @@ async function createDataPlugin(access, options) {
6358
6587
  }
6359
6588
  throw new Error("Unsupported data operation");
6360
6589
  },
6361
- async onDownload(download, tabId, scope, generation, downloadId = randomUUID7()) {
6590
+ async onDownload(download, tabId, scope, generation, downloadId = randomUUID8()) {
6362
6591
  let r;
6363
- let timeout2;
6364
- let cancel;
6365
6592
  try {
6366
6593
  r = create(scope, "download", LIMITS.file, download.suggestedFilename());
6367
6594
  resources.delete(r.id);
@@ -6369,39 +6596,13 @@ async function createDataPlugin(access, options) {
6369
6596
  resources.set(r.id, r);
6370
6597
  r.tabId = tabId;
6371
6598
  r.generation = generation;
6372
- r.capture = { method: "completed-browser-file", stage: "completion", browserCompletion: "pending", comparison: "pending" };
6373
- cancel = () => {
6374
- download.cancel().catch(() => {});
6375
- };
6376
- r.abort.signal.addEventListener("abort", cancel, { once: true });
6377
- timeout2 = setTimeout(() => {
6378
- r.terminalCode ??= "download_capture_timeout";
6379
- r.abort.abort();
6380
- }, LIMITS.duration);
6381
- timeout2.unref?.();
6382
- const captured = r;
6383
- r.task = (async () => {
6384
- const path10 = join2(options.directory, captured.id);
6385
- captured.path = path10;
6386
- owned.add(path10);
6387
- try {
6388
- const verified = await captureDownload(download, path10, captured.abort.signal, captured.capture);
6389
- if (captured.abort.signal.aborted || stopped || resources.get(captured.id) !== captured)
6390
- throw new Error("Download revoked");
6391
- captured.size = verified.size;
6392
- captured.hash = verified.sha256;
6393
- captured.contentValidation = contentValidation(captured.name, verified.size);
6394
- } finally {
6395
- await cleanupDownload(download, captured.capture);
6396
- }
6397
- if (captured.abort.signal.aborted || stopped || resources.get(captured.id) !== captured)
6398
- throw new Error("Download revoked");
6399
- captured.state = "ready";
6400
- })();
6401
- await r.task;
6402
- if (r.abort.signal.aborted || stopped || resources.get(r.id) !== r)
6403
- throw new Error("Download revoked");
6404
- return { ...meta(r), state: "completed" };
6599
+ r.source = { download, directory: options.downloadDirectory };
6600
+ await startCapture(r);
6601
+ if (r.state === "ready")
6602
+ return { ...meta(r), state: "completed" };
6603
+ if (r.state === "capture-failed")
6604
+ return { ...meta(r), state: "failed" };
6605
+ return status(scope, downloadId);
6405
6606
  } catch (error) {
6406
6607
  download.cancel().catch(() => {});
6407
6608
  if (r) {
@@ -6409,17 +6610,13 @@ async function createDataPlugin(access, options) {
6409
6610
  await remove(r);
6410
6611
  return status(scope, downloadId);
6411
6612
  }
6412
- await cleanupDownload(download);
6613
+ if (!await cleanupDownload({ download, directory: options.downloadDirectory }))
6614
+ failClosed();
6413
6615
  const failed = { downloadId, resourceId: downloadId, state: "failed", readiness: "unavailable", code: "download_capture_rejected", recovery: "Capture could not be reserved. Do not automatically repeat the website action." };
6414
6616
  terminal.set(downloadId, { scope: { ...scope }, meta: failed, until: Date.now() + LIMITS.ttl });
6415
6617
  while (terminal.size > 128)
6416
6618
  terminal.delete(terminal.keys().next().value);
6417
6619
  return failed;
6418
- } finally {
6419
- if (timeout2)
6420
- clearTimeout(timeout2);
6421
- if (r && cancel)
6422
- r.abort.signal.removeEventListener("abort", cancel);
6423
6620
  }
6424
6621
  },
6425
6622
  async onNavigation(tabId, generation) {
@@ -6581,7 +6778,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
6581
6778
  console.log(`Verified stale lock/socket cleanup complete for profile ${profile}; profile data retained.`);
6582
6779
  return;
6583
6780
  }
6584
- await new Promise((resolve2, reject) => {
6781
+ await new Promise((resolve3, reject) => {
6585
6782
  const socket = net3.connect(controlPath);
6586
6783
  socket.setTimeout(5000, () => socket.destroy(new Error("Local control timeout")));
6587
6784
  socket.once("connect", () => socket.write(JSON.stringify({ command }) + `
@@ -6589,7 +6786,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
6589
6786
  socket.once("data", (data) => {
6590
6787
  console.log(data.toString().trim());
6591
6788
  socket.end();
6592
- resolve2();
6789
+ resolve3();
6593
6790
  });
6594
6791
  socket.once("error", (error) => reject(controlFailure("control-connect", error)));
6595
6792
  });
@@ -6692,7 +6889,10 @@ async function startProfile(root, server, profile, options, groupSignal) {
6692
6889
  runtimeStage = "runtime-setup";
6693
6890
  const previews = path10.join(session.runPath, "previews");
6694
6891
  runtime = new NativeRuntime(session.context, session.instanceId, previews, server);
6695
- runtime.plugins.push(await createDataPlugin(runtime, { directory: path10.join(session.runPath, "data"), serverOrigin: server, allowInsecureLoopback: new URL(server).protocol === "http:" }));
6892
+ runtime.plugins.push(await createDataPlugin(runtime, { directory: path10.join(session.runPath, "data"), downloadDirectory: path10.join(session.runPath, "chrome-downloads"), serverOrigin: server, allowInsecureLoopback: new URL(server).protocol === "http:", onSourceCleanupFailure: () => {
6893
+ console.error("Download cleanup could not be verified; closing the owned browser to bound private spool retention. No website action was replayed.");
6894
+ requestStop("owner-close");
6895
+ } }));
6696
6896
  abort.signal.throwIfAborted();
6697
6897
  runtime.plugins.push(createForwardPlugin({ serverUrl: server }));
6698
6898
  relay = new Relay(runtime, server, token, previews, !!options.liveView);
@@ -6728,7 +6928,7 @@ async function startProfile(root, server, profile, options, groupSignal) {
6728
6928
  return;
6729
6929
  } else if (cmd !== "status")
6730
6930
  throw new Error("Invalid command");
6731
- socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.15", protocol: 3 }) + `
6931
+ socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.17", protocol: 3 }) + `
6732
6932
  `);
6733
6933
  })().catch(() => socket.destroy());
6734
6934
  });
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.15
11
+ console.log(`@ricsam/browser-mcp 0.3.17
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,11 +18,11 @@ 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.15");
21
+ console.log("0.3.17");
22
22
  return;
23
23
  }
24
24
  if (command === "browser")
25
- return (await import("./chunk-ts4nynm9.js")).runBrowser(args);
25
+ return (await import("./chunk-kvvj8z88.js")).runBrowser(args);
26
26
  if (command === "files")
27
27
  return (await import("./chunk-zv1900tw.js")).runFilesCommand(args);
28
28
  if (command === "secrets")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ricsam/browser-mcp",
3
- "version": "0.3.15",
3
+ "version": "0.3.17",
4
4
  "description": "Dedicated native Chrome companion for Browser MCP",
5
5
  "type": "module",
6
6
  "bin": { "browser-mcp": "dist/main.js" },