@ricsam/browser-mcp 0.3.16 → 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.16 uses one cross-platform Node package with matching server/chart 0.3.16, native protocol 3 and no database schema change. It fixes local resume status and unscoped CSS queries for body/html roots. Resume immediately acknowledges reconnecting/unpaused without claiming readiness; already-unpaused resume preserves the current state. Visible DOM matches without ARIA refs are counted and explicitly reported as incomplete, not missing. 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.16
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.16";
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",
@@ -3450,21 +3450,31 @@ var messages = {
3450
3450
  runtime_disconnected: "The runtime or browser connection ended.",
3451
3451
  context_destroyed: "The document execution context changed during the operation.",
3452
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.",
3453
3455
  script_exception: "The script threw an exception. Page exception text and stack are suppressed.",
3454
3456
  transfer_failed: "The file transfer failed or its completion could not be confirmed.",
3455
3457
  resource_unavailable: "The requested resource is unavailable. No download link was created.",
3456
3458
  scope_rejected: "Runtime scope or tab ownership was rejected.",
3457
3459
  runtime_operation_failed: "The browser operation failed; page-derived details are suppressed."
3458
3460
  };
3459
- function failureFor(error, op, operationId, stage) {
3461
+ function failureFor(error, op, operationId, stage, timing) {
3460
3462
  const text = error instanceof Error ? error.message : "";
3461
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";
3462
3472
  const observation = OBSERVATION_OPERATIONS.has(op);
3463
3473
  const outcome = error instanceof RuntimeFault && error.beforeDispatch ? "not_dispatched" : observation ? "failed" : "unknown";
3464
- 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.";
3465
3475
  const diagnosticId = randomUUID4();
3466
- console.error(JSON.stringify({ event: "runtime_failure", diagnosticId, operationId, operation: op, stage, code: code2, outcome }));
3467
- 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 } };
3468
3478
  }
3469
3479
 
3470
3480
  // cli/src/browser/browser-runtime.ts
@@ -3475,6 +3485,7 @@ var MAX_RUN_JS_ARTIFACT_COUNT = 32;
3475
3485
  var REF_ACTION_TIMEOUT_MS = 5000;
3476
3486
  var NAVIGATION_TIMEOUT_MS = 20000;
3477
3487
  var READ_PAGE_TIMEOUT_MS = 1e4;
3488
+ var SCREENSHOT_TIMEOUT_MS = 15000;
3478
3489
  var MAX_FULL_PAGE_HEIGHT = 4000;
3479
3490
  var MAX_FULL_PAGE_WIDTH = 4096;
3480
3491
  var MAX_TYPED_KEYS_CHARS = 500;
@@ -4207,7 +4218,14 @@ class BrowserRuntime {
4207
4218
  return result;
4208
4219
  }
4209
4220
  case "screenshot": {
4221
+ execution.screenshotStage?.("screenshot_geometry");
4210
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
+ };
4211
4229
  const record = (width, height, originX, originY) => {
4212
4230
  const transform = { id: crypto.randomUUID(), state, width, height, originX, originY };
4213
4231
  this.screenshots.set(tabId, transform);
@@ -4217,10 +4235,11 @@ class BrowserRuntime {
4217
4235
  const crop = input.crop;
4218
4236
  if (crop.x + crop.width > state.width || crop.y + crop.height > state.height)
4219
4237
  throw new Error("Crop must fit the current viewport in CSS pixels");
4220
- const bytes2 = await page.screenshot({ type: "png", scale: "css", clip: crop });
4238
+ const bytes2 = await capture({ clip: crop });
4221
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) };
4222
4240
  }
4223
4241
  if (input.fullPage === true) {
4242
+ execution.screenshotStage?.("screenshot_metrics");
4224
4243
  const metrics = await page.evaluate(() => ({
4225
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),
4226
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)
@@ -4228,16 +4247,15 @@ class BrowserRuntime {
4228
4247
  const width = Math.min(metrics.docWidth, MAX_FULL_PAGE_WIDTH);
4229
4248
  const height = Math.min(metrics.docHeight, MAX_FULL_PAGE_HEIGHT);
4230
4249
  const truncated = metrics.docHeight > MAX_FULL_PAGE_HEIGHT || metrics.docWidth > MAX_FULL_PAGE_WIDTH;
4231
- 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 } } : {} });
4232
4251
  return { base64: bytes2.toString("base64"), width, height, fullPage: true, pageHeight: metrics.docHeight, truncated, ...record(bytes2.readUInt32BE(16), bytes2.readUInt32BE(20), 0, 0) };
4233
4252
  }
4234
- const bytes = await page.screenshot({ type: "png", scale: "css" });
4235
- const viewport = page.viewportSize();
4253
+ const bytes = await capture();
4236
4254
  const cursor = this.cursor.get(tabId);
4237
4255
  return {
4238
4256
  base64: bytes.toString("base64"),
4239
- width: viewport?.width ?? Number(await page.evaluate(() => window.innerWidth)),
4240
- height: viewport?.height ?? Number(await page.evaluate(() => window.innerHeight)),
4257
+ width: bytes.readUInt32BE(16),
4258
+ height: bytes.readUInt32BE(20),
4241
4259
  ...record(bytes.readUInt32BE(16), bytes.readUInt32BE(20), state.scrollX, state.scrollY),
4242
4260
  cursorX: cursor?.x,
4243
4261
  cursorY: cursor?.y,
@@ -4843,7 +4861,7 @@ class NativeRuntime {
4843
4861
  cancelOperation(operationId) {
4844
4862
  this.operations.get(operationId)?.abort(new Error("Runtime operation interrupted; page effects remain uncertain"));
4845
4863
  }
4846
- async execute(op, args, scope, operationId, beforeDispatch) {
4864
+ async execute(op, args, scope, operationId, beforeDispatch, screenshotStage) {
4847
4865
  if (op === "session_end") {
4848
4866
  await this.endSession(scope);
4849
4867
  return { ended: true };
@@ -4857,7 +4875,7 @@ class NativeRuntime {
4857
4875
  set.add(controller);
4858
4876
  this.operations.set(operationId, controller);
4859
4877
  try {
4860
- 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));
4861
4879
  } finally {
4862
4880
  this.operations.delete(operationId);
4863
4881
  set.delete(controller);
@@ -4865,7 +4883,7 @@ class NativeRuntime {
4865
4883
  this.controllers.delete(key);
4866
4884
  }
4867
4885
  }
4868
- async executeInner(op, args, scope, operationId, beforeDispatch) {
4886
+ async executeInner(op, args, scope, operationId, beforeDispatch, screenshotStage) {
4869
4887
  let dispatched = false;
4870
4888
  const begin = () => {
4871
4889
  this.validateScope(scope);
@@ -4911,7 +4929,7 @@ class NativeRuntime {
4911
4929
  return { tabs: tabs.filter((t) => !this.owners.has(t.tabId) || scopeKey(this.owners.get(t.tabId)) === scopeKey(scope)) };
4912
4930
  }
4913
4931
  try {
4914
- 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 });
4915
4933
  if (this.disconnected || (this.epochs.get(scopeKey(scope)) ?? 0) !== operationEpoch)
4916
4934
  throw new Error("Scope ended during execution; outcome uncertain");
4917
4935
  const target2 = op === "capabilities" && typeof args.tabId === "string" ? await this.targetCapabilities(args.tabId, scope) : undefined;
@@ -5401,7 +5419,7 @@ class Relay {
5401
5419
  const state = { quarantined, executionState: active.settled ? active.interrupted ? "settled_after_interruption" : "settled_late" : quarantined ? "unresolved" : "in_progress" };
5402
5420
  if (scope && !sameScope3(active.scope, scope))
5403
5421
  return { ...state, ownedByAnotherScope: true };
5404
- 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 };
5405
5423
  }
5406
5424
  health(scope) {
5407
5425
  const active = this.active;
@@ -5541,7 +5559,7 @@ class Relay {
5541
5559
  if (this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
5542
5560
  return;
5543
5561
  this.state = "authenticating";
5544
- socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.16", 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 } } }));
5545
5563
  });
5546
5564
  socket.on("message", (bytes, binary) => {
5547
5565
  if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
@@ -5703,7 +5721,15 @@ class Relay {
5703
5721
  finish = resolve2;
5704
5722
  }), interrupt: () => interrupt(), expire: () => expire() };
5705
5723
  this.active = active;
5706
- 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;
5707
5733
  const expired = new Promise((resolve2) => {
5708
5734
  const terminal = (cancelled) => {
5709
5735
  if (active.interrupted || active.settled)
@@ -5720,7 +5746,10 @@ class Relay {
5720
5746
  else
5721
5747
  active.timedOut = true;
5722
5748
  clearTimeout(timer);
5723
- 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." } });
5724
5753
  this.flushWaiting("blocked_by_prior_operation", "A prior operation timed out or was interrupted. This waiting request was never dispatched.");
5725
5754
  if (cancelled)
5726
5755
  this.runtime.cancelOperation(active.id);
@@ -5739,7 +5768,7 @@ class Relay {
5739
5768
  entry.guard(!active.dispatched);
5740
5769
  active.dispatched = true;
5741
5770
  };
5742
- 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);
5743
5772
  if (active.timedOut || active.interrupted || this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
5744
5773
  return;
5745
5774
  this.runtime.validateScope(message.scope);
@@ -5750,9 +5779,15 @@ class Relay {
5750
5779
  stage = "transfer";
5751
5780
  const blobs = [];
5752
5781
  if (result?.base64 && message.op === "screenshot") {
5782
+ screenshotStage?.("screenshot_encode");
5753
5783
  const bytes = Buffer.from(result.base64, "base64");
5754
5784
  delete result.base64;
5755
- 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");
5756
5791
  }
5757
5792
  if (message.op === "export_page" && Array.isArray(result?.exports))
5758
5793
  for (const item of result.exports) {
@@ -5776,19 +5811,25 @@ class Relay {
5776
5811
  throw new Error("Result budget exceeded");
5777
5812
  response = { type: "result", id: message.id, ok: true, result: wireResult(message.op, result), blobs, outcome: result?.status === "unknown" ? "unknown" : "completed" };
5778
5813
  } catch (error) {
5779
- const failure = failureFor(error, message.op, message.id, stage);
5780
- if (failure.error.code === "context_destroyed" && active.tabId) {
5781
- for (const waiting of [...this.waiting])
5782
- if (waiting.message.args.tabId === active.tabId)
5783
- 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 };
5784
5826
  }
5785
- response = { type: "result", id: message.id, ok: false, ...failure };
5786
5827
  } finally {
5787
5828
  clearTimeout(timer);
5788
5829
  active.settled = true;
5789
5830
  finish();
5790
5831
  if (active.timedOut || active.interrupted)
5791
- 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 });
5792
5833
  if (this.active === active && (!active.interrupted || !active.dispatched) && !active.recovering)
5793
5834
  this.active = undefined;
5794
5835
  }
@@ -5829,11 +5870,11 @@ class Relay {
5829
5870
  clearTimeout(timer);
5830
5871
  }
5831
5872
  }
5832
- async upload(bytes, role, name, mimeType) {
5873
+ async upload(bytes, role, name, mimeType, signal = AbortSignal.timeout(30000)) {
5833
5874
  if (bytes.length > 20 * 1024 * 1024)
5834
5875
  throw new Error("Preview exceeds 20 MiB");
5835
5876
  const blobId = randomUUID5(), sha256 = createHash5("sha256").update(bytes).digest("hex");
5836
- 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 });
5837
5878
  if (!response.ok)
5838
5879
  throw new Error("Preview upload failed");
5839
5880
  return { blobId, role, name, mimeType, size: bytes.length, sha256 };
@@ -5862,9 +5903,9 @@ class Relay {
5862
5903
  }
5863
5904
 
5864
5905
  // cli/src/data/index.ts
5865
- 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";
5866
5907
  import { createReadStream, createWriteStream as createWriteStream2 } from "node:fs";
5867
- import { randomUUID as randomUUID7, createHash as createHash7 } from "node:crypto";
5908
+ import { randomUUID as randomUUID8, createHash as createHash7 } from "node:crypto";
5868
5909
  import { join as join2, basename } from "node:path";
5869
5910
  import { Readable, Transform as Transform2 } from "node:stream";
5870
5911
  import { pipeline as pipeline2 } from "node:stream/promises";
@@ -5990,21 +6031,50 @@ class SecretVault {
5990
6031
 
5991
6032
  // cli/src/data/download-capture.ts
5992
6033
  import { constants as constants3, createWriteStream } from "node:fs";
5993
- import { open as open2 } from "node:fs/promises";
5994
- 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";
5995
6037
  import { Transform } from "node:stream";
5996
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
+
5997
6065
  class CaptureError extends Error {
5998
6066
  code;
5999
- constructor(code2) {
6067
+ reason;
6068
+ constructor(code2, reason = "unknown") {
6000
6069
  super(code2);
6001
6070
  this.code = code2;
6071
+ this.reason = reason;
6002
6072
  }
6003
6073
  }
6004
6074
  async function duringCapture(work, signal) {
6005
6075
  let abort;
6006
6076
  const cancelled = new Promise((_, reject) => {
6007
- abort = () => reject(new CaptureError("download_capture_cancelled"));
6077
+ abort = () => reject(new CaptureError("download_capture_cancelled", "cancelled"));
6008
6078
  signal.addEventListener("abort", abort, { once: true });
6009
6079
  if (signal.aborted)
6010
6080
  abort();
@@ -6030,32 +6100,45 @@ function contentValidation(name, size) {
6030
6100
  warning: "The completed browser file is empty. This may be intentional; no document validity is implied."
6031
6101
  };
6032
6102
  }
6033
- async function captureDownload(download, destination, signal, evidence) {
6034
- const failure = await duringCapture(download.failure(), signal);
6035
- evidence.browserCompletion = failure === null ? "completed" : "failed";
6036
- if (failure !== null)
6037
- throw new CaptureError("download_capture_browser_failed");
6038
- const path10 = await duringCapture(download.path(), signal);
6039
- signal.throwIfAborted();
6040
- evidence.stage = "browser-file";
6103
+ async function captureDownload(browserSource, destination, signal, evidence) {
6104
+ const { download } = browserSource;
6105
+ let operation = "completion";
6041
6106
  let source;
6042
6107
  let retained2;
6043
6108
  try {
6044
- 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";
6045
6123
  const before = await source.stat();
6046
6124
  if (!before.isFile())
6047
- 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";
6048
6130
  evidence.browser = { size: before.size };
6049
6131
  if (before.size > LIMITS.file)
6050
- throw new CaptureError("download_quota_exceeded");
6132
+ throw new CaptureError("download_quota_exceeded", "quota-exceeded");
6051
6133
  signal.throwIfAborted();
6052
6134
  evidence.stage = "copy";
6135
+ operation = "copy";
6053
6136
  let size = 0;
6054
6137
  const hash = createHash6("sha256");
6055
6138
  const bound = new Transform({ transform(chunk, _encoding, callback) {
6056
6139
  size += chunk.length;
6057
6140
  if (size > LIMITS.file)
6058
- return callback(new CaptureError("download_quota_exceeded"));
6141
+ return callback(new CaptureError("download_quota_exceeded", "quota-exceeded"));
6059
6142
  hash.update(chunk);
6060
6143
  callback(null, chunk);
6061
6144
  } });
@@ -6063,6 +6146,7 @@ async function captureDownload(download, destination, signal, evidence) {
6063
6146
  const sourceHash = hash.digest("hex");
6064
6147
  evidence.browser.sha256 = sourceHash;
6065
6148
  evidence.stage = "verification";
6149
+ operation = "verification";
6066
6150
  retained2 = await open2(destination, constants3.O_RDONLY | constants3.O_NOFOLLOW);
6067
6151
  const disk = await retained2.stat();
6068
6152
  if (!disk.isFile() || disk.size > LIMITS.file)
@@ -6072,7 +6156,7 @@ async function captureDownload(download, destination, signal, evidence) {
6072
6156
  for await (const chunk of retained2.createReadStream({ start: 0, autoClose: false, signal })) {
6073
6157
  diskSize += chunk.length;
6074
6158
  if (diskSize > LIMITS.file)
6075
- throw new CaptureError("download_quota_exceeded");
6159
+ throw new CaptureError("download_quota_exceeded", "quota-exceeded");
6076
6160
  diskHash.update(chunk);
6077
6161
  }
6078
6162
  evidence.retained = { size: diskSize, sha256: diskHash.digest("hex") };
@@ -6080,32 +6164,53 @@ async function captureDownload(download, destination, signal, evidence) {
6080
6164
  const diskAfter = await retained2.stat();
6081
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) {
6082
6166
  evidence.comparison = "mismatched";
6083
- throw new CaptureError("download_capture_mismatch");
6167
+ throw new CaptureError("download_capture_mismatch", "source-changed");
6084
6168
  }
6085
6169
  signal.throwIfAborted();
6086
6170
  evidence.comparison = "matched";
6087
6171
  evidence.stage = "verified";
6088
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);
6089
6178
  } finally {
6090
- try {
6091
- await retained2?.close();
6092
- } finally {
6093
- await source?.close();
6094
- }
6179
+ await retained2?.close().catch(() => {});
6180
+ await source?.close().catch(() => {});
6095
6181
  }
6096
6182
  }
6097
- async function cleanupDownload(download, evidence) {
6183
+ async function cleanupDownload(source, evidence) {
6098
6184
  let timer;
6099
6185
  try {
6100
6186
  const deleted = await Promise.race([
6101
- download.delete().then(() => true, () => false),
6102
- new Promise((resolve2) => {
6103
- 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);
6104
6208
  timer.unref?.();
6105
6209
  })
6106
6210
  ]);
6107
6211
  if (evidence)
6108
6212
  evidence.cleanup = deleted ? "deleted" : "browser-context";
6213
+ return deleted;
6109
6214
  } finally {
6110
6215
  clearTimeout(timer);
6111
6216
  }
@@ -6130,6 +6235,10 @@ async function createDataPlugin(access, options) {
6130
6235
  while (terminal.size > 128)
6131
6236
  terminal.delete(terminal.keys().next().value);
6132
6237
  }
6238
+ function failClosed() {
6239
+ stopped = true;
6240
+ options.onSourceCleanupFailure();
6241
+ }
6133
6242
  function status(scope, id) {
6134
6243
  const t = terminal.get(String(id));
6135
6244
  if (t && t.until >= Date.now() && sameScope(t.scope, scope))
@@ -6137,7 +6246,17 @@ async function createDataPlugin(access, options) {
6137
6246
  return meta(get(scope, id));
6138
6247
  }
6139
6248
  function meta(r) {
6140
- 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
+ } : {} };
6141
6260
  }
6142
6261
  function get(scope, id) {
6143
6262
  const r = resources.get(String(id));
@@ -6145,35 +6264,64 @@ async function createDataPlugin(access, options) {
6145
6264
  throw new Error("Unknown resource");
6146
6265
  return r;
6147
6266
  }
6148
- function reserve(scope, size) {
6149
- const all = [...resources.values()].filter((r) => !["failed", "cancelled"].includes(r.state));
6150
- 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)
6151
6272
  throw new Error("Local data quota exceeded");
6152
6273
  }
6153
6274
  function create(scope, purpose, size, name) {
6154
- reserve(scope, size);
6155
- 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 };
6156
6277
  resources.set(r.id, r);
6157
6278
  return r;
6158
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
+ }
6159
6290
  async function remove(r) {
6291
+ if (r.removal)
6292
+ return r.removal;
6160
6293
  r.terminalCode ??= "download_revoked";
6161
6294
  r.abort.abort();
6162
6295
  r.state = "cancelled";
6163
- await r.task?.catch(() => {});
6164
- remember(r);
6165
- r.bytes?.fill(0);
6166
- r.bytes = undefined;
6167
- if (r.path && owned.has(r.path)) {
6168
- await unlink2(r.path).catch(() => {});
6169
- owned.delete(r.path);
6170
- }
6171
- const dir = join2(options.directory, r.id);
6172
- if (ownedDirs.has(dir)) {
6173
- await rmdir2(dir).catch(() => {});
6174
- 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;
6175
6324
  }
6176
- resources.delete(r.id);
6177
6325
  }
6178
6326
  async function revoke(predicate) {
6179
6327
  vault.revoke(predicate);
@@ -6222,7 +6370,7 @@ async function createDataPlugin(access, options) {
6222
6370
  } else {
6223
6371
  if (!r.path)
6224
6372
  throw new Error("Missing file");
6225
- const stat = await lstat2(r.path);
6373
+ const stat = await lstat3(r.path);
6226
6374
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== r.size)
6227
6375
  throw new Error("Changed file");
6228
6376
  body = Readable.toWeb(createReadStream(r.path));
@@ -6236,7 +6384,7 @@ async function createDataPlugin(access, options) {
6236
6384
  if (r.state !== "cancelled")
6237
6385
  r.state = "failed";
6238
6386
  if (r.path && owned.has(r.path) && r.purpose === "upload") {
6239
- await unlink2(r.path).catch(() => {});
6387
+ await unlink3(r.path).catch(() => {});
6240
6388
  owned.delete(r.path);
6241
6389
  }
6242
6390
  } finally {
@@ -6254,6 +6402,8 @@ async function createDataPlugin(access, options) {
6254
6402
  }
6255
6403
  async function sweepExpired() {
6256
6404
  await revoke((r) => {
6405
+ if (r.state === "cancelled")
6406
+ return true;
6257
6407
  if (r.expiresAt < Date.now() && r.state !== "attached") {
6258
6408
  r.terminalCode = "download_expired";
6259
6409
  return true;
@@ -6264,12 +6414,73 @@ async function createDataPlugin(access, options) {
6264
6414
  if (t.until < Date.now())
6265
6415
  terminal.delete(id);
6266
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
+ }
6267
6478
  let sweep = setInterval(() => {
6268
6479
  sweepExpired();
6269
6480
  }, 1e4);
6270
6481
  sweep.unref?.();
6271
6482
  return {
6272
- 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"],
6273
6484
  async execute(op, args, scope) {
6274
6485
  if (stopped)
6275
6486
  throw new Error("Data runtime disconnected");
@@ -6290,6 +6501,13 @@ async function createDataPlugin(access, options) {
6290
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);
6291
6502
  return meta(r);
6292
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
+ }
6293
6511
  if (op === "transfer_status") {
6294
6512
  await sweepExpired();
6295
6513
  return status(scope, args.resourceId ?? args.transferId);
@@ -6314,7 +6532,7 @@ async function createDataPlugin(access, options) {
6314
6532
  }
6315
6533
  if (op === "list_downloads") {
6316
6534
  await sweepExpired();
6317
- 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) };
6318
6536
  }
6319
6537
  if (op === "upload_files") {
6320
6538
  const ids = args.fileIds;
@@ -6369,10 +6587,8 @@ async function createDataPlugin(access, options) {
6369
6587
  }
6370
6588
  throw new Error("Unsupported data operation");
6371
6589
  },
6372
- async onDownload(download, tabId, scope, generation, downloadId = randomUUID7()) {
6590
+ async onDownload(download, tabId, scope, generation, downloadId = randomUUID8()) {
6373
6591
  let r;
6374
- let timeout2;
6375
- let cancel;
6376
6592
  try {
6377
6593
  r = create(scope, "download", LIMITS.file, download.suggestedFilename());
6378
6594
  resources.delete(r.id);
@@ -6380,39 +6596,13 @@ async function createDataPlugin(access, options) {
6380
6596
  resources.set(r.id, r);
6381
6597
  r.tabId = tabId;
6382
6598
  r.generation = generation;
6383
- r.capture = { method: "completed-browser-file", stage: "completion", browserCompletion: "pending", comparison: "pending" };
6384
- cancel = () => {
6385
- download.cancel().catch(() => {});
6386
- };
6387
- r.abort.signal.addEventListener("abort", cancel, { once: true });
6388
- timeout2 = setTimeout(() => {
6389
- r.terminalCode ??= "download_capture_timeout";
6390
- r.abort.abort();
6391
- }, LIMITS.duration);
6392
- timeout2.unref?.();
6393
- const captured = r;
6394
- r.task = (async () => {
6395
- const path10 = join2(options.directory, captured.id);
6396
- captured.path = path10;
6397
- owned.add(path10);
6398
- try {
6399
- const verified = await captureDownload(download, path10, captured.abort.signal, captured.capture);
6400
- if (captured.abort.signal.aborted || stopped || resources.get(captured.id) !== captured)
6401
- throw new Error("Download revoked");
6402
- captured.size = verified.size;
6403
- captured.hash = verified.sha256;
6404
- captured.contentValidation = contentValidation(captured.name, verified.size);
6405
- } finally {
6406
- await cleanupDownload(download, captured.capture);
6407
- }
6408
- if (captured.abort.signal.aborted || stopped || resources.get(captured.id) !== captured)
6409
- throw new Error("Download revoked");
6410
- captured.state = "ready";
6411
- })();
6412
- await r.task;
6413
- if (r.abort.signal.aborted || stopped || resources.get(r.id) !== r)
6414
- throw new Error("Download revoked");
6415
- 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);
6416
6606
  } catch (error) {
6417
6607
  download.cancel().catch(() => {});
6418
6608
  if (r) {
@@ -6420,17 +6610,13 @@ async function createDataPlugin(access, options) {
6420
6610
  await remove(r);
6421
6611
  return status(scope, downloadId);
6422
6612
  }
6423
- await cleanupDownload(download);
6613
+ if (!await cleanupDownload({ download, directory: options.downloadDirectory }))
6614
+ failClosed();
6424
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." };
6425
6616
  terminal.set(downloadId, { scope: { ...scope }, meta: failed, until: Date.now() + LIMITS.ttl });
6426
6617
  while (terminal.size > 128)
6427
6618
  terminal.delete(terminal.keys().next().value);
6428
6619
  return failed;
6429
- } finally {
6430
- if (timeout2)
6431
- clearTimeout(timeout2);
6432
- if (r && cancel)
6433
- r.abort.signal.removeEventListener("abort", cancel);
6434
6620
  }
6435
6621
  },
6436
6622
  async onNavigation(tabId, generation) {
@@ -6592,7 +6778,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
6592
6778
  console.log(`Verified stale lock/socket cleanup complete for profile ${profile}; profile data retained.`);
6593
6779
  return;
6594
6780
  }
6595
- await new Promise((resolve2, reject) => {
6781
+ await new Promise((resolve3, reject) => {
6596
6782
  const socket = net3.connect(controlPath);
6597
6783
  socket.setTimeout(5000, () => socket.destroy(new Error("Local control timeout")));
6598
6784
  socket.once("connect", () => socket.write(JSON.stringify({ command }) + `
@@ -6600,7 +6786,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
6600
6786
  socket.once("data", (data) => {
6601
6787
  console.log(data.toString().trim());
6602
6788
  socket.end();
6603
- resolve2();
6789
+ resolve3();
6604
6790
  });
6605
6791
  socket.once("error", (error) => reject(controlFailure("control-connect", error)));
6606
6792
  });
@@ -6703,7 +6889,10 @@ async function startProfile(root, server, profile, options, groupSignal) {
6703
6889
  runtimeStage = "runtime-setup";
6704
6890
  const previews = path10.join(session.runPath, "previews");
6705
6891
  runtime = new NativeRuntime(session.context, session.instanceId, previews, server);
6706
- 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
+ } }));
6707
6896
  abort.signal.throwIfAborted();
6708
6897
  runtime.plugins.push(createForwardPlugin({ serverUrl: server }));
6709
6898
  relay = new Relay(runtime, server, token, previews, !!options.liveView);
@@ -6739,7 +6928,7 @@ async function startProfile(root, server, profile, options, groupSignal) {
6739
6928
  return;
6740
6929
  } else if (cmd !== "status")
6741
6930
  throw new Error("Invalid command");
6742
- socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.16", protocol: 3 }) + `
6931
+ socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.17", protocol: 3 }) + `
6743
6932
  `);
6744
6933
  })().catch(() => socket.destroy());
6745
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.16
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.16");
21
+ console.log("0.3.17");
22
22
  return;
23
23
  }
24
24
  if (command === "browser")
25
- return (await import("./chunk-g9ksk86v.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.16",
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" },