@ricsam/browser-mcp 0.3.19 → 0.3.20

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.19 uses one cross-platform Node package with matching server/chart 0.3.19, native protocol 3 and no database schema change. Upload and secret-export results carry their capability in ordinary tool text, transfer grants beyond a session's four outstanding ones are refused before anything is prepared, and unknown resource IDs passed to `browser_transfer_status`, `browser_cancel_transfer` or `browser_upload_files` are reported as not found. As since 0.3.18, every download in the dedicated browser stays in its private download folder and is listed by `browser_list_downloads`; background screenshots and capture-only download retry remain. 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.
6
+ Release 0.3.20 uses one cross-platform Node package with matching server/chart 0.3.20, native protocol 3 and no database schema change. Screenshots are returned as soon as Chrome captures them, with nothing running in the page after the capture, and screenshots, page reads, `browser_run_js`, waits and inspections carry `pageState` timing (`capturedAt`, document state, pending requests and the tab's last action). Upload and secret-export capabilities in tool text with up-front transfer grant limits (0.3.19), private download routing (0.3.18), background screenshots and capture-only download retry remain. 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.19
9
+ npm install -g @ricsam/browser-mcp@0.3.20
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.19";
57
+ var version = "0.3.20";
58
58
 
59
59
  // cli/src/browser/chrome-diagnostics.ts
60
60
  import { constants } from "node:fs";
@@ -408,7 +408,7 @@ class ChromeLifecycle {
408
408
  const observation = this.failure ?? (nativeExit ? this.exit : this.disconnect) ?? this.observation();
409
409
  const reason = this.failure?.reason ?? (outcome === "disconnected" ? "transport-or-context-closed-without-child-exit" : outcome === "startup-failure" ? "child-exited-before-ready" : outcome);
410
410
  const failed = outcome !== "requested-shutdown" && outcome !== "normal-exit";
411
- let location2 = "";
411
+ let location = "";
412
412
  if (failed) {
413
413
  if (this.identity.root) {
414
414
  try {
@@ -431,15 +431,15 @@ class ChromeLifecycle {
431
431
  exitDuringCleanup: this.exit?.cleanup ?? false,
432
432
  diagnostics: this.diagnostics.snapshot()
433
433
  });
434
- location2 = ` Diagnostics: ${JSON.stringify(file)}.`;
434
+ location = ` Diagnostics: ${JSON.stringify(file)}.`;
435
435
  } catch {
436
- location2 = " Diagnostics could not be saved (private storage unavailable); original failure retained.";
436
+ location = " Diagnostics could not be saved (private storage unavailable); original failure retained.";
437
437
  }
438
438
  } else
439
- location2 = " Diagnostics storage was not configured.";
439
+ location = " Diagnostics storage was not configured.";
440
440
  }
441
441
  const label = outcome === "abnormal-exit" ? "Chrome terminated abnormally" : outcome === "startup-failure" ? "Chrome startup failed" : outcome === "disconnected" ? "Chrome transport/context disconnected (not proof of a Chrome crash)" : outcome === "normal-exit" ? "Chrome exited normally" : "Chrome shutdown requested";
442
- const summary = `${observation.timestamp} ${label}; profile=${this.identity.profile} instance=${this.identity.instanceId} PID=${this.pid ?? "unavailable"} exitCode=${this.exit?.code ?? "none"} signal=${this.exit?.signal ?? "none"} shutdownRequested=${!!this.shutdown}${this.shutdown ? ` (${this.shutdown})` : ""} stage=${observation.stage} reason=${reason}.${this.exit?.cleanup ? " Child exit observed during cleanup." : ""}${location2}`;
442
+ const summary = `${observation.timestamp} ${label}; profile=${this.identity.profile} instance=${this.identity.instanceId} PID=${this.pid ?? "unavailable"} exitCode=${this.exit?.code ?? "none"} signal=${this.exit?.signal ?? "none"} shutdownRequested=${!!this.shutdown}${this.shutdown ? ` (${this.shutdown})` : ""} stage=${observation.stage} reason=${reason}.${this.exit?.cleanup ? " Child exit observed during cleanup." : ""}${location}`;
443
443
  return { outcome, failed, summary };
444
444
  }
445
445
  }
@@ -2869,6 +2869,7 @@ function observeNavigation(page, input) {
2869
2869
  // cli/src/browser/browser-events.ts
2870
2870
  var CAPACITY = 200;
2871
2871
  var RETENTION_MS = 10 * 60000;
2872
+ var MAX_INFLIGHT = 500;
2872
2873
  function diagnosticUrl(raw) {
2873
2874
  try {
2874
2875
  const u = new URL(raw);
@@ -2895,12 +2896,16 @@ class BrowserPageEvents {
2895
2896
  listeners = new Set;
2896
2897
  changes = new Set;
2897
2898
  requests = new WeakMap;
2899
+ inflight = new Map;
2900
+ lastNetworkActivity;
2898
2901
  choosers = new Map;
2899
2902
  downloads = new Map;
2900
2903
  assets = new Map;
2901
2904
  dialog;
2902
2905
  dialogOrigin;
2903
2906
  cdp;
2907
+ crashListeners = new Set;
2908
+ crashed = false;
2904
2909
  ready;
2905
2910
  pending;
2906
2911
  currentAction;
@@ -2910,11 +2915,21 @@ class BrowserPageEvents {
2910
2915
  this.page = page;
2911
2916
  this.ready = page.context().newCDPSession(page).then((cdp) => {
2912
2917
  this.cdp = cdp;
2918
+ cdp.on("close", () => {
2919
+ if (this.cdp === cdp)
2920
+ this.cdp = undefined;
2921
+ });
2922
+ cdp.on("Inspector.targetCrashed", () => this.setCrashed(true));
2923
+ cdp.on("Inspector.targetReloadedAfterCrash", () => this.setCrashed(false));
2913
2924
  cdp.on("Page.javascriptDialogOpening", ({ url }) => {
2914
2925
  this.dialogOrigin = this.origin(url);
2915
2926
  if (this.dialog)
2916
2927
  this.dialog.event.origin = this.dialogOrigin;
2917
2928
  });
2929
+ cdp.on("Page.frameNavigated", ({ frame }) => {
2930
+ if (!frame.parentId)
2931
+ this.dropPreviousDocumentRequests();
2932
+ });
2918
2933
  cdp.on("Page.javascriptDialogClosed", (event) => {
2919
2934
  this.dialogOrigin = undefined;
2920
2935
  const current = this.dialog;
@@ -2935,15 +2950,26 @@ class BrowserPageEvents {
2935
2950
  }).catch(() => {
2936
2951
  return;
2937
2952
  });
2953
+ page.on("crash", () => this.setCrashed(true));
2938
2954
  page.on("console", (m) => this.record("console", {
2939
2955
  level: m.type(),
2940
2956
  text: diagnosticText(m.text()),
2941
2957
  location: { url: diagnosticUrl(m.location().url), line: m.location().lineNumber }
2942
2958
  }));
2943
2959
  page.on("pageerror", (e) => this.record("page_error", { level: "error", text: diagnosticText(e.message), category: "page" }));
2944
- page.on("request", (r) => this.requests.set(r, { started: Date.now(), url: diagnosticUrl(r.url()), actionId: this.actionId() }));
2945
- page.on("requestfailed", (r) => this.requestFinished(r, { failed: true, error: diagnosticText(r.failure()?.errorText ?? "request_failed") }));
2960
+ page.on("request", (r) => {
2961
+ this.requests.set(r, { started: Date.now(), url: diagnosticUrl(r.url()), actionId: this.actionId() });
2962
+ this.inflight.set(r, this.isMainFrameNavigation(r));
2963
+ if (this.inflight.size > MAX_INFLIGHT)
2964
+ this.inflight.delete(this.inflight.keys().next().value);
2965
+ this.lastNetworkActivity = Date.now();
2966
+ });
2967
+ page.on("requestfailed", (r) => {
2968
+ this.settleRequest(r);
2969
+ this.requestFinished(r, { failed: true, error: diagnosticText(r.failure()?.errorText ?? "request_failed") });
2970
+ });
2946
2971
  page.on("requestfinished", (r) => {
2972
+ this.settleRequest(r);
2947
2973
  r.response().then((response) => {
2948
2974
  this.requestFinished(r, { status: response?.status(), failed: (response?.status() ?? 0) >= 400 });
2949
2975
  }).catch(() => {
@@ -2981,6 +3007,7 @@ class BrowserPageEvents {
2981
3007
  this.choosers.delete(id);
2982
3008
  }
2983
3009
  });
3010
+ page.on("framedetached", () => this.dropDetachedFrameRequests());
2984
3011
  page.on("framenavigated", (frame) => {
2985
3012
  if (frame !== page.mainFrame())
2986
3013
  return;
@@ -2993,9 +3020,70 @@ class BrowserPageEvents {
2993
3020
  this.clearChoosers();
2994
3021
  this.assets.clear();
2995
3022
  this.downloads.clear();
3023
+ this.inflight.clear();
2996
3024
  this.dialog = undefined;
2997
3025
  });
2998
3026
  }
3027
+ isMainFrameNavigation(request) {
3028
+ try {
3029
+ return request.isNavigationRequest() && request.frame() === this.page.mainFrame();
3030
+ } catch {
3031
+ return false;
3032
+ }
3033
+ }
3034
+ settleRequest(request) {
3035
+ if (this.inflight.delete(request))
3036
+ this.lastNetworkActivity = Date.now();
3037
+ }
3038
+ dropPreviousDocumentRequests() {
3039
+ let dropped = false;
3040
+ for (const [request, navigation] of this.inflight)
3041
+ if (!navigation) {
3042
+ this.inflight.delete(request);
3043
+ dropped = true;
3044
+ }
3045
+ if (dropped)
3046
+ this.lastNetworkActivity = Date.now();
3047
+ }
3048
+ dropDetachedFrameRequests() {
3049
+ let dropped = false;
3050
+ for (const request of this.inflight.keys()) {
3051
+ let detached = false;
3052
+ try {
3053
+ detached = request.frame().isDetached();
3054
+ } catch {}
3055
+ if (detached) {
3056
+ this.inflight.delete(request);
3057
+ dropped = true;
3058
+ }
3059
+ }
3060
+ if (dropped)
3061
+ this.lastNetworkActivity = Date.now();
3062
+ }
3063
+ session() {
3064
+ return this.cdp;
3065
+ }
3066
+ setCrashed(crashed) {
3067
+ this.crashed = crashed;
3068
+ if (crashed)
3069
+ for (const listener of [...this.crashListeners])
3070
+ listener();
3071
+ }
3072
+ onCrash(listener) {
3073
+ this.crashListeners.add(listener);
3074
+ return () => this.crashListeners.delete(listener);
3075
+ }
3076
+ networkState(at = Date.now()) {
3077
+ let navigationPending = false;
3078
+ for (const navigation of this.inflight.values())
3079
+ if (navigation)
3080
+ navigationPending = true;
3081
+ return {
3082
+ navigationPending,
3083
+ pendingRequests: this.inflight.size,
3084
+ networkIdleMs: this.lastNetworkActivity === undefined ? null : Math.max(0, at - this.lastNetworkActivity)
3085
+ };
3086
+ }
2999
3087
  origin(url) {
3000
3088
  try {
3001
3089
  return new URL(url).origin;
@@ -3681,6 +3769,144 @@ class BrowserTabState {
3681
3769
  }
3682
3770
  }
3683
3771
 
3772
+ // cli/src/browser/page-state.ts
3773
+ var READY_STATES = new Set(["loading", "interactive", "complete"]);
3774
+ var VISIBILITY_STATES = new Set(["visible", "hidden", "prerender"]);
3775
+ function pageState(capturedAt, network, lastAction, document2) {
3776
+ return {
3777
+ capturedAt: new Date(capturedAt).toISOString(),
3778
+ ...typeof document2?.readyState === "string" && READY_STATES.has(document2.readyState) ? { readyState: document2.readyState } : {},
3779
+ ...typeof document2?.visibilityState === "string" && VISIBILITY_STATES.has(document2.visibilityState) ? { visibilityState: document2.visibilityState } : {},
3780
+ ...network,
3781
+ lastAction: lastAction ? { operation: lastAction.operation, endedAt: new Date(lastAction.endedAt).toISOString(), msBeforeCapture: Math.max(0, capturedAt - lastAction.endedAt) } : null
3782
+ };
3783
+ }
3784
+ var PAGE_EFFECT_OPERATIONS = new Set([
3785
+ "open_tab",
3786
+ "navigate",
3787
+ "history",
3788
+ "set_viewport",
3789
+ "present",
3790
+ "mouse_click",
3791
+ "move_mouse",
3792
+ "hover",
3793
+ "drag",
3794
+ "scroll",
3795
+ "form_input",
3796
+ "keyboard",
3797
+ "keyboard_type",
3798
+ "select_text",
3799
+ "edit_text",
3800
+ "run_js",
3801
+ "upload_attach",
3802
+ "handle_dialog",
3803
+ "webmcp_call"
3804
+ ]);
3805
+
3806
+ // cli/src/browser/screenshot-capture.ts
3807
+ var MAX_CAPTURE_SIDE = 16384;
3808
+ var MAX_CAPTURE_AREA = 8192 * 8192;
3809
+ var SCROLLBAR_SLACK = 128;
3810
+ var ABANDONED_CAPTURE_DETACH_MS = 120000;
3811
+
3812
+ class ObservationError extends Error {
3813
+ }
3814
+ var OBSERVATION_WORLD = "r5d-observation";
3815
+ async function evaluateIsolated(cdp, expression, awaitPromise = false) {
3816
+ const { frameTree } = await cdp.send("Page.getFrameTree");
3817
+ const { executionContextId } = await cdp.send("Page.createIsolatedWorld", { frameId: frameTree.frame.id, worldName: OBSERVATION_WORLD });
3818
+ const { result, exceptionDetails } = await cdp.send("Runtime.evaluate", {
3819
+ expression,
3820
+ contextId: executionContextId,
3821
+ returnByValue: true,
3822
+ awaitPromise,
3823
+ silent: true
3824
+ });
3825
+ if (exceptionDetails)
3826
+ throw new ObservationError("Isolated observation read failed.");
3827
+ return result.value;
3828
+ }
3829
+ var fontsReadyExpression = (waitMs) => `document.fonts && document.fonts.status === "loading" ? Promise.race([document.fonts.ready, new Promise((resolve) => setTimeout(resolve, ${waitMs}))]).then(() => undefined) : undefined`;
3830
+ var DOCUMENT_STATE_EXPRESSION = `({ readyState: document.readyState, visibilityState: document.visibilityState })`;
3831
+ var VIEWPORT_EXPRESSION = `({ url: location.href, scrollX, scrollY, width: innerWidth, height: innerHeight, dpr: devicePixelRatio, readyState: document.readyState, visibilityState: document.visibilityState })`;
3832
+ var DOCUMENT_SIZE_EXPRESSION = `({
3833
+ docWidth: Math.max(document.documentElement.scrollWidth, document.documentElement.offsetWidth, document.documentElement.clientWidth,
3834
+ document.body ? document.body.scrollWidth : 0, document.body ? document.body.offsetWidth : 0, document.body ? document.body.clientWidth : 0),
3835
+ docHeight: Math.max(document.documentElement.scrollHeight, document.documentElement.offsetHeight, document.documentElement.clientHeight,
3836
+ document.body ? document.body.scrollHeight : 0, document.body ? document.body.offsetHeight : 0, document.body ? document.body.clientHeight : 0),
3837
+ })`;
3838
+ var finite = (value) => typeof value === "number" && Number.isFinite(value);
3839
+ async function readViewportGeometry(cdp) {
3840
+ const v = await evaluateIsolated(cdp, VIEWPORT_EXPRESSION);
3841
+ if (!v || typeof v.url !== "string" || ![v.scrollX, v.scrollY, v.width, v.height, v.dpr].every(finite) || !(v.width > 0 && v.height > 0 && v.dpr > 0))
3842
+ throw new ObservationError("Viewport geometry is unavailable.");
3843
+ const state = { url: v.url, scrollX: v.scrollX, scrollY: v.scrollY, width: v.width, height: v.height, dpr: v.dpr };
3844
+ return { state, document: { readyState: v.readyState, visibilityState: v.visibilityState } };
3845
+ }
3846
+ async function readDocumentSize(cdp) {
3847
+ const v = await evaluateIsolated(cdp, DOCUMENT_SIZE_EXPRESSION);
3848
+ if (!v || !finite(v.docWidth) || !finite(v.docHeight) || v.docWidth <= 0 || v.docHeight <= 0)
3849
+ throw new ObservationError("Document size is unavailable.");
3850
+ return { docWidth: v.docWidth, docHeight: v.docHeight };
3851
+ }
3852
+ function checkRegion(region, layout) {
3853
+ const { x, y, width, height } = region;
3854
+ if (![x, y, width, height].every(Number.isFinite) || x < 0 || y < 0 || width <= 0 || height <= 0)
3855
+ throw new ObservationError("Invalid screenshot region.");
3856
+ if (width > MAX_CAPTURE_SIDE || height > MAX_CAPTURE_SIDE || width * height > MAX_CAPTURE_AREA)
3857
+ throw new ObservationError("The screenshot region is too large to capture.");
3858
+ if (region.kind === "viewport" && (x + width > layout.clientWidth + SCROLLBAR_SLACK || y + height > layout.clientHeight + SCROLLBAR_SLACK))
3859
+ throw new ObservationError("The screenshot region exceeds the current viewport. Take a new screenshot.");
3860
+ }
3861
+ async function captureCssScreenshot(context, page, region, timeoutMs, guard = (work) => work()) {
3862
+ const session = context.newCDPSession(page);
3863
+ const work = session.then(async (cdp) => {
3864
+ const { visualViewport, cssLayoutViewport, contentSize, cssContentSize } = await cdp.send("Page.getLayoutMetrics");
3865
+ checkRegion(region, cssLayoutViewport);
3866
+ const ratio = contentSize.width / cssContentSize.width;
3867
+ const deviceScaleFactor = Number.isFinite(ratio) && ratio > 0 ? ratio : 1;
3868
+ const clip = region.kind === "document" ? { x: region.x, y: region.y, width: region.width, height: region.height, scale: 1 / deviceScaleFactor } : {
3869
+ x: visualViewport.pageX + region.x,
3870
+ y: visualViewport.pageY + region.y,
3871
+ width: Math.floor(region.width / visualViewport.scale + 0.001),
3872
+ height: Math.floor(region.height / visualViewport.scale + 0.001),
3873
+ scale: visualViewport.scale / deviceScaleFactor
3874
+ };
3875
+ const { data } = await cdp.send("Page.captureScreenshot", {
3876
+ format: "png",
3877
+ clip,
3878
+ captureBeyondViewport: region.kind === "document" && !region.fitsViewport
3879
+ });
3880
+ return { bytes: Buffer.from(data, "base64"), capturedAt: Date.now() };
3881
+ });
3882
+ const settled = work.then(() => {
3883
+ return;
3884
+ }, () => {
3885
+ return;
3886
+ });
3887
+ let timer2;
3888
+ try {
3889
+ return await guard(() => Promise.race([
3890
+ work,
3891
+ new Promise((_, reject) => {
3892
+ timer2 = setTimeout(() => reject(new ObservationError(`Timeout ${timeoutMs}ms exceeded while capturing the screenshot.`)), timeoutMs);
3893
+ })
3894
+ ]));
3895
+ } finally {
3896
+ clearTimeout(timer2);
3897
+ let bound;
3898
+ Promise.race([settled, new Promise((resolve2) => {
3899
+ bound = setTimeout(resolve2, ABANDONED_CAPTURE_DETACH_MS);
3900
+ bound.unref?.();
3901
+ })]).then(() => {
3902
+ clearTimeout(bound);
3903
+ return session;
3904
+ }).then((cdp) => cdp.detach()).catch(() => {
3905
+ return;
3906
+ });
3907
+ }
3908
+ }
3909
+
3684
3910
  // cli/src/runtime/failures.ts
3685
3911
  import { randomUUID as randomUUID4 } from "node:crypto";
3686
3912
 
@@ -3726,7 +3952,7 @@ function failureFor(error, op, operationId, stage, timing) {
3726
3952
  code2 = "transfer_failed";
3727
3953
  const observation = OBSERVATION_OPERATIONS.has(op);
3728
3954
  const outcome = error instanceof RuntimeFault && error.beforeDispatch ? "not_dispatched" : observation ? "failed" : "unknown";
3729
- 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.";
3955
+ 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 (including a bounded web-font wait), capture (Chrome 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.";
3730
3956
  const diagnosticId = randomUUID4();
3731
3957
  console.error(JSON.stringify({ event: "runtime_failure", diagnosticId, operationId, operation: op, stage, code: code2, outcome, ...timing }));
3732
3958
  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 } };
@@ -3741,6 +3967,7 @@ var REF_ACTION_TIMEOUT_MS = 5000;
3741
3967
  var NAVIGATION_TIMEOUT_MS = 20000;
3742
3968
  var READ_PAGE_TIMEOUT_MS = 1e4;
3743
3969
  var SCREENSHOT_TIMEOUT_MS = 15000;
3970
+ var SCREENSHOT_FONT_WAIT_MS = 1000;
3744
3971
  var MAX_FULL_PAGE_HEIGHT = 4000;
3745
3972
  var MAX_FULL_PAGE_WIDTH = 4096;
3746
3973
  var MAX_TYPED_KEYS_CHARS = 500;
@@ -3788,6 +4015,7 @@ class BrowserRuntime {
3788
4015
  initialization = new Map;
3789
4016
  tabState;
3790
4017
  observations = new Map;
4018
+ lastActions = new Map;
3791
4019
  tabPresentation = new WeakMap;
3792
4020
  savingDownloads = new Set;
3793
4021
  constructor(context, downloadsPath, uploadsPath = `${downloadsPath}.uploads`, downloadHandler, guardPage) {
@@ -3850,6 +4078,7 @@ class BrowserRuntime {
3850
4078
  this.pages.delete(currentId);
3851
4079
  this.cursor.delete(currentId);
3852
4080
  this.observations.delete(currentId);
4081
+ this.lastActions.delete(currentId);
3853
4082
  this.initialization.delete(page);
3854
4083
  this.viewportSessions.delete(currentId);
3855
4084
  this.tabState.closed(page).catch(() => {
@@ -4066,6 +4295,67 @@ class BrowserRuntime {
4066
4295
  hasPendingInteraction() {
4067
4296
  return [...this.pages.values()].some((page) => !!this.events.get(page)?.activeDialog() || !!this.events.get(page)?.pendingAction());
4068
4297
  }
4298
+ noteAction(tabId, operation) {
4299
+ const page = this.pages.get(tabId);
4300
+ if (page && !page.isClosed())
4301
+ this.lastActions.set(tabId, { operation, endedAt: Date.now() });
4302
+ }
4303
+ observedAt(page, tabId, capturedAt = Date.now()) {
4304
+ const network = this.events.get(page).networkState(capturedAt), lastAction = this.lastActions.get(tabId);
4305
+ return (document2) => pageState(capturedAt, network, lastAction, document2);
4306
+ }
4307
+ async observationSession(page, read) {
4308
+ const events = this.events.get(page);
4309
+ return await this.guardRaw(page, "all", async () => {
4310
+ await events.ready;
4311
+ const held = events.session();
4312
+ if (held)
4313
+ return await read(held);
4314
+ const cdp = await this.context.newCDPSession(page);
4315
+ try {
4316
+ return await read(cdp);
4317
+ } finally {
4318
+ await cdp.detach().catch(() => {
4319
+ return;
4320
+ });
4321
+ }
4322
+ });
4323
+ }
4324
+ async guardRaw(page, rewrite, work) {
4325
+ const events = this.events.get(page);
4326
+ const ended = () => page.isClosed() ? new Error("Target page, context or browser has been closed") : events.crashed ? new Error("Target crashed") : undefined;
4327
+ const early = ended();
4328
+ if (early)
4329
+ throw early;
4330
+ let stop = () => {};
4331
+ const interrupted = new Promise((_, reject) => {
4332
+ const onEnd = () => reject(ended() ?? new Error("Target page, context or browser has been closed"));
4333
+ const offCrash = events.onCrash(onEnd);
4334
+ page.once("close", onEnd);
4335
+ stop = () => {
4336
+ offCrash();
4337
+ page.off("close", onEnd);
4338
+ };
4339
+ });
4340
+ interrupted.catch(() => {
4341
+ return;
4342
+ });
4343
+ try {
4344
+ return await Promise.race([work(), interrupted]);
4345
+ } catch (error) {
4346
+ const end = ended();
4347
+ if (end)
4348
+ throw end;
4349
+ if (error instanceof ObservationError || this.context.browser()?.isConnected() === false)
4350
+ throw error;
4351
+ const message = error instanceof Error ? error.message : "";
4352
+ if (rewrite === "closed" && !/Target closed|Session closed|detached|has been closed/i.test(message))
4353
+ throw error;
4354
+ throw new Error(`Execution context was destroyed (${rewrite === "all" ? "isolated observation read" : "screenshot capture"})`, { cause: error });
4355
+ } finally {
4356
+ stop();
4357
+ }
4358
+ }
4069
4359
  closeUploads() {
4070
4360
  this.tabState.suspend();
4071
4361
  this.uploads.close();
@@ -4090,14 +4380,39 @@ class BrowserRuntime {
4090
4380
  const observation = parseObservation(input.observe);
4091
4381
  const previous = this.observations.get(String(input.tabId));
4092
4382
  const previousTabs = new Set(this.pages.keys());
4093
- const invoke = () => this.dispatch(action, input, execution);
4383
+ let admitted = false;
4384
+ const dispatchExecution = {
4385
+ ...execution,
4386
+ beforeDispatch: () => {
4387
+ execution.beforeDispatch?.();
4388
+ admitted = true;
4389
+ }
4390
+ };
4391
+ const invoke = () => this.dispatch(action, input, dispatchExecution);
4094
4392
  const guarded = events && (observedActions.has(action) || ["run_js", "upload_attach", "close_tab", "clipboard", "present"].includes(action)) && action !== "handle_dialog";
4095
- const result = await (guarded ? events.run(execution.operationId ?? crypto.randomUUID(), invoke) : invoke());
4393
+ const recordAction = () => {
4394
+ if (admitted && typeof input.tabId === "string" && PAGE_EFFECT_OPERATIONS.has(action))
4395
+ this.noteAction(input.tabId, action);
4396
+ };
4397
+ let result;
4398
+ try {
4399
+ result = await (guarded ? events.run(execution.operationId ?? crypto.randomUUID(), invoke) : invoke());
4400
+ } catch (error) {
4401
+ recordAction();
4402
+ throw error;
4403
+ }
4404
+ const notDispatched = result.invoked === false || result.dispatched === false || result.selected === false || result.handled === false;
4405
+ if (!notDispatched && result.dispatch?.status !== "not_dispatched")
4406
+ recordAction();
4407
+ if (action === "open_tab") {
4408
+ const opened = result.tab?.tabId;
4409
+ if (typeof opened === "string")
4410
+ this.noteAction(opened, action);
4411
+ }
4096
4412
  if (page && !page.isClosed())
4097
4413
  await this.guardPage?.(page);
4098
4414
  if (!observation || !page || page.isClosed())
4099
4415
  return result;
4100
- const notDispatched = result.invoked === false || result.dispatched === false || result.selected === false || result.handled === false;
4101
4416
  const uncertain = result.status === "unknown";
4102
4417
  const dispatch = result.dispatch ?? { status: uncertain ? "unknown" : notDispatched ? "not_dispatched" : "completed" };
4103
4418
  const succeeded = !notDispatched && !uncertain && result.status !== "Error" && result.status !== "Canceled";
@@ -4235,7 +4550,7 @@ class BrowserRuntime {
4235
4550
  const transform = this.screenshots.get(tabId);
4236
4551
  if (!transform || transform.id !== request.id)
4237
4552
  throw new Error("Screenshot is stale or belongs to another tab. Take a new screenshot.");
4238
- const current = await page.evaluate(() => ({ url: location.href, scrollX, scrollY, width: innerWidth, height: innerHeight, dpr: devicePixelRatio }));
4553
+ const current = (await this.observationSession(page, readViewportGeometry)).state;
4239
4554
  const map = (point) => screenshotPoint(transform, current, request, point);
4240
4555
  input = { ...input, ...input.from ? { from: map(input.from), to: map(input.to) } : map({ x: Number(input.x), y: Number(input.y) }) };
4241
4556
  delete input.screenshot;
@@ -4302,7 +4617,7 @@ class BrowserRuntime {
4302
4617
  case "cancel_transfer":
4303
4618
  return { tabId, ...await this.events.get(page).cancelTransfer(String(input.eventId)) };
4304
4619
  case "inspect":
4305
- return { tabId, ...await inspectElement(page, input) };
4620
+ return { tabId, ...await inspectElement(page, input), pageState: this.observedAt(page, tabId)() };
4306
4621
  case "hover":
4307
4622
  this.cursor.delete(tabId);
4308
4623
  await this.refLocator(page, requireRef(input.ref)).hover({ timeout: REF_ACTION_TIMEOUT_MS, modifiers: input.modifiers });
@@ -4466,11 +4781,15 @@ class BrowserRuntime {
4466
4781
  error: /unavailable|synchronous/i.test(message) ? "Password-safe snapshot APIs are unavailable. Update r5d-browser before retrying." : "Cannot capture this target. Check scope/query selectors and ensure each frames selector identifies exactly one loaded iframe; refresh the page observation if it changed."
4467
4782
  };
4468
4783
  }
4784
+ const observed = this.observedAt(page, tabId);
4469
4785
  const result = {
4470
4786
  tabId,
4471
4787
  url: page.url(),
4472
4788
  title: await page.title().catch(() => ""),
4473
- ...renderSnapshot(snapshot, request)
4789
+ ...renderSnapshot(snapshot, request),
4790
+ pageState: observed(await this.observationSession(page, (cdp) => evaluateIsolated(cdp, DOCUMENT_STATE_EXPRESSION)).catch(() => {
4791
+ return;
4792
+ }))
4474
4793
  };
4475
4794
  this.observations.set(tabId, { text: result.text.slice(0, 30000), url: result.url });
4476
4795
  if (this.observations.size > 64)
@@ -4479,12 +4798,23 @@ class BrowserRuntime {
4479
4798
  }
4480
4799
  case "screenshot": {
4481
4800
  execution.screenshotStage?.("screenshot_geometry");
4482
- const state = await page.evaluate(() => ({ url: location.href, scrollX, scrollY, width: innerWidth, height: innerHeight, dpr: devicePixelRatio }));
4483
- const capture = async (options = {}) => {
4801
+ let fontTimer;
4802
+ await Promise.race([
4803
+ this.observationSession(page, (cdp) => evaluateIsolated(cdp, fontsReadyExpression(SCREENSHOT_FONT_WAIT_MS), true)).catch(() => {
4804
+ return;
4805
+ }),
4806
+ new Promise((resolve2) => {
4807
+ fontTimer = setTimeout(resolve2, SCREENSHOT_FONT_WAIT_MS);
4808
+ })
4809
+ ]);
4810
+ clearTimeout(fontTimer);
4811
+ const { state, document: documentState } = await this.observationSession(page, readViewportGeometry);
4812
+ const capture = async (region) => {
4484
4813
  execution.screenshotStage?.("screenshot_capture");
4485
- const bytes2 = await page.screenshot({ ...options, type: "png", scale: "css", timeout: SCREENSHOT_TIMEOUT_MS });
4814
+ const { bytes: bytes2, capturedAt } = await captureCssScreenshot(this.context, page, region, SCREENSHOT_TIMEOUT_MS, (work) => this.guardRaw(page, "closed", work));
4815
+ const observed = this.observedAt(page, tabId, capturedAt);
4486
4816
  execution.screenshotStage?.("screenshot_encode");
4487
- return bytes2;
4817
+ return { bytes: bytes2, pageState: observed(documentState) };
4488
4818
  };
4489
4819
  const record = (width, height, originX, originY) => {
4490
4820
  const transform = { id: crypto.randomUUID(), state, width, height, originX, originY };
@@ -4495,22 +4825,19 @@ class BrowserRuntime {
4495
4825
  const crop = input.crop;
4496
4826
  if (crop.x + crop.width > state.width || crop.y + crop.height > state.height)
4497
4827
  throw new Error("Crop must fit the current viewport in CSS pixels");
4498
- const bytes2 = await capture({ clip: crop });
4499
- 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) };
4828
+ const { bytes: bytes2, pageState: pageState3 } = await capture({ kind: "viewport", x: crop.x, y: crop.y, width: crop.width, height: crop.height });
4829
+ 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), pageState: pageState3 };
4500
4830
  }
4501
4831
  if (input.fullPage === true) {
4502
4832
  execution.screenshotStage?.("screenshot_metrics");
4503
- const metrics = await page.evaluate(() => ({
4504
- docWidth: Math.max(document.documentElement.scrollWidth, document.documentElement.offsetWidth, document.documentElement.clientWidth, document.body?.scrollWidth ?? 0, document.body?.offsetWidth ?? 0, document.body?.clientWidth ?? 0),
4505
- docHeight: Math.max(document.documentElement.scrollHeight, document.documentElement.offsetHeight, document.documentElement.clientHeight, document.body?.scrollHeight ?? 0, document.body?.offsetHeight ?? 0, document.body?.clientHeight ?? 0)
4506
- }));
4833
+ const metrics = await this.observationSession(page, readDocumentSize);
4507
4834
  const width = Math.min(metrics.docWidth, MAX_FULL_PAGE_WIDTH);
4508
4835
  const height = Math.min(metrics.docHeight, MAX_FULL_PAGE_HEIGHT);
4509
4836
  const truncated = metrics.docHeight > MAX_FULL_PAGE_HEIGHT || metrics.docWidth > MAX_FULL_PAGE_WIDTH;
4510
- const bytes2 = await capture({ fullPage: true, ...truncated ? { clip: { x: 0, y: 0, width, height } } : {} });
4511
- return { base64: bytes2.toString("base64"), width, height, fullPage: true, pageHeight: metrics.docHeight, truncated, ...record(bytes2.readUInt32BE(16), bytes2.readUInt32BE(20), 0, 0) };
4837
+ const { bytes: bytes2, pageState: pageState3 } = await capture({ kind: "document", x: 0, y: 0, width, height, fitsViewport: metrics.docWidth <= state.width && metrics.docHeight <= state.height });
4838
+ return { base64: bytes2.toString("base64"), width, height, fullPage: true, pageHeight: metrics.docHeight, truncated, ...record(bytes2.readUInt32BE(16), bytes2.readUInt32BE(20), 0, 0), pageState: pageState3 };
4512
4839
  }
4513
- const bytes = await capture();
4840
+ const { bytes, pageState: pageState2 } = await capture({ kind: "viewport", x: 0, y: 0, width: state.width, height: state.height });
4514
4841
  const cursor = this.cursor.get(tabId);
4515
4842
  return {
4516
4843
  base64: bytes.toString("base64"),
@@ -4519,7 +4846,8 @@ class BrowserRuntime {
4519
4846
  ...record(bytes.readUInt32BE(16), bytes.readUInt32BE(20), state.scrollX, state.scrollY),
4520
4847
  cursorX: cursor?.x,
4521
4848
  cursorY: cursor?.y,
4522
- cursorKnown: cursor !== undefined
4849
+ cursorKnown: cursor !== undefined,
4850
+ pageState: pageState2
4523
4851
  };
4524
4852
  }
4525
4853
  case "move_mouse": {
@@ -4608,7 +4936,7 @@ class BrowserRuntime {
4608
4936
  return { tabId, direction, amount, ...pointer };
4609
4937
  }
4610
4938
  case "wait_for": {
4611
- return { tabId, ...await waitForBrowserCondition(page, parseWaitInput(input)) };
4939
+ return { tabId, ...await waitForBrowserCondition(page, parseWaitInput(input)), pageState: this.observedAt(page, tabId)() };
4612
4940
  }
4613
4941
  case "upload_begin": {
4614
4942
  const target2 = parseUploadTarget(input);
@@ -4795,13 +5123,25 @@ class BrowserRuntime {
4795
5123
  }
4796
5124
  return filename;
4797
5125
  };
5126
+ const documentState = () => {
5127
+ try {
5128
+ const { readyState, visibilityState } = document;
5129
+ return {
5130
+ readyState: typeof readyState === "string" ? readyState.slice(0, 16) : undefined,
5131
+ visibilityState: typeof visibilityState === "string" ? visibilityState.slice(0, 16) : undefined
5132
+ };
5133
+ } catch {
5134
+ return;
5135
+ }
5136
+ };
4798
5137
  try {
4799
5138
  const invoke = new Function("r5dCreateArtifact", `"use strict"; return (async () => {
4800
5139
  ${code2}
4801
5140
  })()`);
4802
- return { result: await invoke(r5dCreateArtifact), artifacts };
5141
+ const result = await invoke(r5dCreateArtifact);
5142
+ return { result, artifacts, document: documentState() };
4803
5143
  } catch (error) {
4804
- return { artifacts, failure: "script_exception" };
5144
+ return { artifacts, failure: "script_exception", document: documentState() };
4805
5145
  }
4806
5146
  }, { code: input.code, maxBytes: MAX_RUN_JS_ARTIFACT_BYTES, maxCount: MAX_RUN_JS_ARTIFACT_COUNT });
4807
5147
  } catch (error) {
@@ -4811,6 +5151,7 @@ ${code2}
4811
5151
  }
4812
5152
  throw new Error(stripCallLog(message));
4813
5153
  }
5154
+ const observed = this.observedAt(page, tabId);
4814
5155
  if (evaluated.failure && !evaluated.artifacts.length)
4815
5156
  throw new RuntimeFault("script_exception", "Review the submitted script locally. Effects before the exception may have occurred; do not replay automatically.");
4816
5157
  const serialized = JSON.stringify(evaluated.result);
@@ -4828,7 +5169,8 @@ ${code2}
4828
5169
  intent: input.intent,
4829
5170
  reason: input.reason,
4830
5171
  untrusted: true,
4831
- outcomeVerified: false
5172
+ outcomeVerified: false,
5173
+ pageState: observed(evaluated.document)
4832
5174
  };
4833
5175
  }
4834
5176
  default:
@@ -5296,16 +5638,16 @@ import WebSocket from "ws";
5296
5638
  // backend/live-wire.ts
5297
5639
  var isRuntimeTabId = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
5298
5640
  var MAX_LIVE_FRAME_BYTES = 1500000;
5299
- var finite = (value, min, max) => Number.isFinite(value) && value >= min && value <= max;
5641
+ var finite2 = (value, min, max) => Number.isFinite(value) && value >= min && value <= max;
5300
5642
  var uint32 = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 4294967295;
5301
- var coordinate = (value) => typeof value === "number" && finite(value, -1e5, 1e5);
5302
- var delta = (value) => typeof value === "number" && finite(value, -1e6, 1e6);
5643
+ var coordinate = (value) => typeof value === "number" && finite2(value, -1e5, 1e5);
5644
+ var delta = (value) => typeof value === "number" && finite2(value, -1e6, 1e6);
5303
5645
  var TOOL = /^[a-z][a-z0-9_]{0,63}$/;
5304
5646
  function sanitizeLiveEvent(value) {
5305
5647
  if (!value || typeof value !== "object" || Array.isArray(value))
5306
5648
  return null;
5307
5649
  const e = value;
5308
- if (!isRuntimeTabId(e.runtimeTabId) || !uint32(e.navSeq) || typeof e.at !== "number" || !finite(e.at, 0, 100000000000000))
5650
+ if (!isRuntimeTabId(e.runtimeTabId) || !uint32(e.navSeq) || typeof e.at !== "number" || !finite2(e.at, 0, 100000000000000))
5309
5651
  return null;
5310
5652
  const base = { runtimeTabId: e.runtimeTabId, navSeq: e.navSeq, at: e.at };
5311
5653
  switch (e.type) {
@@ -5859,7 +6201,7 @@ class Relay {
5859
6201
  if (this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
5860
6202
  return;
5861
6203
  this.state = "authenticating";
5862
- socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.19", 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 } } }));
6204
+ socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.20", 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 } } }));
5863
6205
  });
5864
6206
  socket.on("message", (bytes, binary) => {
5865
6207
  if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
@@ -7355,7 +7697,7 @@ async function startProfile(root, server, profile, options, groupSignal) {
7355
7697
  return;
7356
7698
  } else if (cmd !== "status")
7357
7699
  throw new Error("Invalid command");
7358
- socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.19", protocol: 3 }) + `
7700
+ socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.20", protocol: 3 }) + `
7359
7701
  `);
7360
7702
  })().catch(() => socket.destroy());
7361
7703
  });
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.19
11
+ console.log(`@ricsam/browser-mcp 0.3.20
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.19");
21
+ console.log("0.3.20");
22
22
  return;
23
23
  }
24
24
  if (command === "browser")
25
- return (await import("./chunk-8d06b7q4.js")).runBrowser(args);
25
+ return (await import("./chunk-99qqnbnf.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.19",
3
+ "version": "0.3.20",
4
4
  "description": "Dedicated native Chrome companion for Browser MCP",
5
5
  "type": "module",
6
6
  "bin": { "browser-mcp": "dist/main.js" },