@ricsam/browser-mcp 0.3.19 → 0.3.21

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.
@@ -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.21";
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);
@@ -2894,13 +2895,18 @@ class BrowserPageEvents {
2894
2895
  entries = [];
2895
2896
  listeners = new Set;
2896
2897
  changes = new Set;
2898
+ dialogListeners = new Set;
2897
2899
  requests = new WeakMap;
2900
+ inflight = new Map;
2901
+ lastNetworkActivity;
2898
2902
  choosers = new Map;
2899
2903
  downloads = new Map;
2900
2904
  assets = new Map;
2901
2905
  dialog;
2902
2906
  dialogOrigin;
2903
2907
  cdp;
2908
+ crashListeners = new Set;
2909
+ crashed = false;
2904
2910
  ready;
2905
2911
  pending;
2906
2912
  currentAction;
@@ -2910,11 +2916,21 @@ class BrowserPageEvents {
2910
2916
  this.page = page;
2911
2917
  this.ready = page.context().newCDPSession(page).then((cdp) => {
2912
2918
  this.cdp = cdp;
2919
+ cdp.on("close", () => {
2920
+ if (this.cdp === cdp)
2921
+ this.cdp = undefined;
2922
+ });
2923
+ cdp.on("Inspector.targetCrashed", () => this.setCrashed(true));
2924
+ cdp.on("Inspector.targetReloadedAfterCrash", () => this.setCrashed(false));
2913
2925
  cdp.on("Page.javascriptDialogOpening", ({ url }) => {
2914
2926
  this.dialogOrigin = this.origin(url);
2915
2927
  if (this.dialog)
2916
2928
  this.dialog.event.origin = this.dialogOrigin;
2917
2929
  });
2930
+ cdp.on("Page.frameNavigated", ({ frame }) => {
2931
+ if (!frame.parentId)
2932
+ this.dropPreviousDocumentRequests();
2933
+ });
2918
2934
  cdp.on("Page.javascriptDialogClosed", (event) => {
2919
2935
  this.dialogOrigin = undefined;
2920
2936
  const current = this.dialog;
@@ -2928,6 +2944,7 @@ class BrowserPageEvents {
2928
2944
  actionId: current.event.actionId
2929
2945
  });
2930
2946
  this.dialog = undefined;
2947
+ this.dialogChanged();
2931
2948
  });
2932
2949
  cdp.send("Page.enable").catch(() => {
2933
2950
  return;
@@ -2935,15 +2952,26 @@ class BrowserPageEvents {
2935
2952
  }).catch(() => {
2936
2953
  return;
2937
2954
  });
2955
+ page.on("crash", () => this.setCrashed(true));
2938
2956
  page.on("console", (m) => this.record("console", {
2939
2957
  level: m.type(),
2940
2958
  text: diagnosticText(m.text()),
2941
2959
  location: { url: diagnosticUrl(m.location().url), line: m.location().lineNumber }
2942
2960
  }));
2943
2961
  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") }));
2962
+ page.on("request", (r) => {
2963
+ this.requests.set(r, { started: Date.now(), url: diagnosticUrl(r.url()), actionId: this.actionId() });
2964
+ this.inflight.set(r, this.isMainFrameNavigation(r));
2965
+ if (this.inflight.size > MAX_INFLIGHT)
2966
+ this.inflight.delete(this.inflight.keys().next().value);
2967
+ this.lastNetworkActivity = Date.now();
2968
+ });
2969
+ page.on("requestfailed", (r) => {
2970
+ this.settleRequest(r);
2971
+ this.requestFinished(r, { failed: true, error: diagnosticText(r.failure()?.errorText ?? "request_failed") });
2972
+ });
2946
2973
  page.on("requestfinished", (r) => {
2974
+ this.settleRequest(r);
2947
2975
  r.response().then((response) => {
2948
2976
  this.requestFinished(r, { status: response?.status(), failed: (response?.status() ?? 0) >= 400 });
2949
2977
  }).catch(() => {
@@ -2969,6 +2997,7 @@ class BrowserPageEvents {
2969
2997
  this.dialog = { value, event };
2970
2998
  for (const listener of this.listeners)
2971
2999
  listener();
3000
+ this.dialogChanged();
2972
3001
  });
2973
3002
  page.on("filechooser", (chooser) => {
2974
3003
  const event = this.record("chooser", { multiple: chooser.isMultiple(), state: "open", document: this.document });
@@ -2981,6 +3010,7 @@ class BrowserPageEvents {
2981
3010
  this.choosers.delete(id);
2982
3011
  }
2983
3012
  });
3013
+ page.on("framedetached", () => this.dropDetachedFrameRequests());
2984
3014
  page.on("framenavigated", (frame) => {
2985
3015
  if (frame !== page.mainFrame())
2986
3016
  return;
@@ -2993,9 +3023,87 @@ class BrowserPageEvents {
2993
3023
  this.clearChoosers();
2994
3024
  this.assets.clear();
2995
3025
  this.downloads.clear();
3026
+ this.inflight.clear();
2996
3027
  this.dialog = undefined;
3028
+ this.dialogListeners.clear();
2997
3029
  });
2998
3030
  }
3031
+ onDialog(listener) {
3032
+ this.dialogListeners.add(listener);
3033
+ return () => this.dialogListeners.delete(listener);
3034
+ }
3035
+ dialogDetails() {
3036
+ const value = this.dialog?.value;
3037
+ return value ? { type: value.type(), message: value.message(), defaultValue: value.defaultValue() } : null;
3038
+ }
3039
+ dialogChanged() {
3040
+ const details = this.dialogDetails();
3041
+ for (const listener of [...this.dialogListeners]) {
3042
+ try {
3043
+ listener(details);
3044
+ } catch {}
3045
+ }
3046
+ }
3047
+ isMainFrameNavigation(request) {
3048
+ try {
3049
+ return request.isNavigationRequest() && request.frame() === this.page.mainFrame();
3050
+ } catch {
3051
+ return false;
3052
+ }
3053
+ }
3054
+ settleRequest(request) {
3055
+ if (this.inflight.delete(request))
3056
+ this.lastNetworkActivity = Date.now();
3057
+ }
3058
+ dropPreviousDocumentRequests() {
3059
+ let dropped = false;
3060
+ for (const [request, navigation] of this.inflight)
3061
+ if (!navigation) {
3062
+ this.inflight.delete(request);
3063
+ dropped = true;
3064
+ }
3065
+ if (dropped)
3066
+ this.lastNetworkActivity = Date.now();
3067
+ }
3068
+ dropDetachedFrameRequests() {
3069
+ let dropped = false;
3070
+ for (const request of this.inflight.keys()) {
3071
+ let detached = false;
3072
+ try {
3073
+ detached = request.frame().isDetached();
3074
+ } catch {}
3075
+ if (detached) {
3076
+ this.inflight.delete(request);
3077
+ dropped = true;
3078
+ }
3079
+ }
3080
+ if (dropped)
3081
+ this.lastNetworkActivity = Date.now();
3082
+ }
3083
+ session() {
3084
+ return this.cdp;
3085
+ }
3086
+ setCrashed(crashed) {
3087
+ this.crashed = crashed;
3088
+ if (crashed)
3089
+ for (const listener of [...this.crashListeners])
3090
+ listener();
3091
+ }
3092
+ onCrash(listener) {
3093
+ this.crashListeners.add(listener);
3094
+ return () => this.crashListeners.delete(listener);
3095
+ }
3096
+ networkState(at = Date.now()) {
3097
+ let navigationPending = false;
3098
+ for (const navigation of this.inflight.values())
3099
+ if (navigation)
3100
+ navigationPending = true;
3101
+ return {
3102
+ navigationPending,
3103
+ pendingRequests: this.inflight.size,
3104
+ networkIdleMs: this.lastNetworkActivity === undefined ? null : Math.max(0, at - this.lastNetworkActivity)
3105
+ };
3106
+ }
2999
3107
  origin(url) {
3000
3108
  try {
3001
3109
  return new URL(url).origin;
@@ -3088,17 +3196,19 @@ class BrowserPageEvents {
3088
3196
  pendingAction() {
3089
3197
  return this.pending ? { actionId: this.pending.actionId, status: "pending" } : null;
3090
3198
  }
3091
- async handleDialog(input) {
3199
+ async handleDialog(input, handledBy = "agent") {
3092
3200
  const current = this.dialog;
3093
3201
  if (!current || current.event.eventId !== input.dialogId)
3094
3202
  return { handled: false, code: "stale_dialog", dialog: this.activeDialog() };
3095
3203
  if (input.promptText !== undefined && (current.value.type() !== "prompt" || input.decision !== "accept"))
3096
3204
  return { handled: false, code: "prompt_text_requires_accept_prompt" };
3097
- current.event.handledBy = "agent";
3205
+ current.event.handledBy = handledBy;
3098
3206
  await (input.decision === "accept" ? current.value.accept(input.promptText) : current.value.dismiss());
3099
3207
  current.event.state = input.decision === "accept" ? "accepted" : "dismissed";
3100
- if (this.dialog === current)
3208
+ if (this.dialog === current) {
3101
3209
  this.dialog = undefined;
3210
+ this.dialogChanged();
3211
+ }
3102
3212
  const pending = this.pending;
3103
3213
  const outcome = pending ? await this.racePending(pending, 1000) : undefined;
3104
3214
  return {
@@ -3681,6 +3791,144 @@ class BrowserTabState {
3681
3791
  }
3682
3792
  }
3683
3793
 
3794
+ // cli/src/browser/page-state.ts
3795
+ var READY_STATES = new Set(["loading", "interactive", "complete"]);
3796
+ var VISIBILITY_STATES = new Set(["visible", "hidden", "prerender"]);
3797
+ function pageState(capturedAt, network, lastAction, document2) {
3798
+ return {
3799
+ capturedAt: new Date(capturedAt).toISOString(),
3800
+ ...typeof document2?.readyState === "string" && READY_STATES.has(document2.readyState) ? { readyState: document2.readyState } : {},
3801
+ ...typeof document2?.visibilityState === "string" && VISIBILITY_STATES.has(document2.visibilityState) ? { visibilityState: document2.visibilityState } : {},
3802
+ ...network,
3803
+ lastAction: lastAction ? { operation: lastAction.operation, endedAt: new Date(lastAction.endedAt).toISOString(), msBeforeCapture: Math.max(0, capturedAt - lastAction.endedAt) } : null
3804
+ };
3805
+ }
3806
+ var PAGE_EFFECT_OPERATIONS = new Set([
3807
+ "open_tab",
3808
+ "navigate",
3809
+ "history",
3810
+ "set_viewport",
3811
+ "present",
3812
+ "mouse_click",
3813
+ "move_mouse",
3814
+ "hover",
3815
+ "drag",
3816
+ "scroll",
3817
+ "form_input",
3818
+ "keyboard",
3819
+ "keyboard_type",
3820
+ "select_text",
3821
+ "edit_text",
3822
+ "run_js",
3823
+ "upload_attach",
3824
+ "handle_dialog",
3825
+ "webmcp_call"
3826
+ ]);
3827
+
3828
+ // cli/src/browser/screenshot-capture.ts
3829
+ var MAX_CAPTURE_SIDE = 16384;
3830
+ var MAX_CAPTURE_AREA = 8192 * 8192;
3831
+ var SCROLLBAR_SLACK = 128;
3832
+ var ABANDONED_CAPTURE_DETACH_MS = 120000;
3833
+
3834
+ class ObservationError extends Error {
3835
+ }
3836
+ var OBSERVATION_WORLD = "r5d-observation";
3837
+ async function evaluateIsolated(cdp, expression, awaitPromise = false) {
3838
+ const { frameTree } = await cdp.send("Page.getFrameTree");
3839
+ const { executionContextId } = await cdp.send("Page.createIsolatedWorld", { frameId: frameTree.frame.id, worldName: OBSERVATION_WORLD });
3840
+ const { result, exceptionDetails } = await cdp.send("Runtime.evaluate", {
3841
+ expression,
3842
+ contextId: executionContextId,
3843
+ returnByValue: true,
3844
+ awaitPromise,
3845
+ silent: true
3846
+ });
3847
+ if (exceptionDetails)
3848
+ throw new ObservationError("Isolated observation read failed.");
3849
+ return result.value;
3850
+ }
3851
+ var fontsReadyExpression = (waitMs) => `document.fonts && document.fonts.status === "loading" ? Promise.race([document.fonts.ready, new Promise((resolve) => setTimeout(resolve, ${waitMs}))]).then(() => undefined) : undefined`;
3852
+ var DOCUMENT_STATE_EXPRESSION = `({ readyState: document.readyState, visibilityState: document.visibilityState })`;
3853
+ var VIEWPORT_EXPRESSION = `({ url: location.href, scrollX, scrollY, width: innerWidth, height: innerHeight, dpr: devicePixelRatio, readyState: document.readyState, visibilityState: document.visibilityState })`;
3854
+ var DOCUMENT_SIZE_EXPRESSION = `({
3855
+ docWidth: Math.max(document.documentElement.scrollWidth, document.documentElement.offsetWidth, document.documentElement.clientWidth,
3856
+ document.body ? document.body.scrollWidth : 0, document.body ? document.body.offsetWidth : 0, document.body ? document.body.clientWidth : 0),
3857
+ docHeight: Math.max(document.documentElement.scrollHeight, document.documentElement.offsetHeight, document.documentElement.clientHeight,
3858
+ document.body ? document.body.scrollHeight : 0, document.body ? document.body.offsetHeight : 0, document.body ? document.body.clientHeight : 0),
3859
+ })`;
3860
+ var finite = (value) => typeof value === "number" && Number.isFinite(value);
3861
+ async function readViewportGeometry(cdp) {
3862
+ const v = await evaluateIsolated(cdp, VIEWPORT_EXPRESSION);
3863
+ 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))
3864
+ throw new ObservationError("Viewport geometry is unavailable.");
3865
+ const state = { url: v.url, scrollX: v.scrollX, scrollY: v.scrollY, width: v.width, height: v.height, dpr: v.dpr };
3866
+ return { state, document: { readyState: v.readyState, visibilityState: v.visibilityState } };
3867
+ }
3868
+ async function readDocumentSize(cdp) {
3869
+ const v = await evaluateIsolated(cdp, DOCUMENT_SIZE_EXPRESSION);
3870
+ if (!v || !finite(v.docWidth) || !finite(v.docHeight) || v.docWidth <= 0 || v.docHeight <= 0)
3871
+ throw new ObservationError("Document size is unavailable.");
3872
+ return { docWidth: v.docWidth, docHeight: v.docHeight };
3873
+ }
3874
+ function checkRegion(region, layout) {
3875
+ const { x, y, width, height } = region;
3876
+ if (![x, y, width, height].every(Number.isFinite) || x < 0 || y < 0 || width <= 0 || height <= 0)
3877
+ throw new ObservationError("Invalid screenshot region.");
3878
+ if (width > MAX_CAPTURE_SIDE || height > MAX_CAPTURE_SIDE || width * height > MAX_CAPTURE_AREA)
3879
+ throw new ObservationError("The screenshot region is too large to capture.");
3880
+ if (region.kind === "viewport" && (x + width > layout.clientWidth + SCROLLBAR_SLACK || y + height > layout.clientHeight + SCROLLBAR_SLACK))
3881
+ throw new ObservationError("The screenshot region exceeds the current viewport. Take a new screenshot.");
3882
+ }
3883
+ async function captureCssScreenshot(context, page, region, timeoutMs, guard = (work) => work()) {
3884
+ const session = context.newCDPSession(page);
3885
+ const work = session.then(async (cdp) => {
3886
+ const { visualViewport, cssLayoutViewport, contentSize, cssContentSize } = await cdp.send("Page.getLayoutMetrics");
3887
+ checkRegion(region, cssLayoutViewport);
3888
+ const ratio = contentSize.width / cssContentSize.width;
3889
+ const deviceScaleFactor = Number.isFinite(ratio) && ratio > 0 ? ratio : 1;
3890
+ const clip = region.kind === "document" ? { x: region.x, y: region.y, width: region.width, height: region.height, scale: 1 / deviceScaleFactor } : {
3891
+ x: visualViewport.pageX + region.x,
3892
+ y: visualViewport.pageY + region.y,
3893
+ width: Math.floor(region.width / visualViewport.scale + 0.001),
3894
+ height: Math.floor(region.height / visualViewport.scale + 0.001),
3895
+ scale: visualViewport.scale / deviceScaleFactor
3896
+ };
3897
+ const { data } = await cdp.send("Page.captureScreenshot", {
3898
+ format: "png",
3899
+ clip,
3900
+ captureBeyondViewport: region.kind === "document" && !region.fitsViewport
3901
+ });
3902
+ return { bytes: Buffer.from(data, "base64"), capturedAt: Date.now() };
3903
+ });
3904
+ const settled = work.then(() => {
3905
+ return;
3906
+ }, () => {
3907
+ return;
3908
+ });
3909
+ let timer2;
3910
+ try {
3911
+ return await guard(() => Promise.race([
3912
+ work,
3913
+ new Promise((_, reject) => {
3914
+ timer2 = setTimeout(() => reject(new ObservationError(`Timeout ${timeoutMs}ms exceeded while capturing the screenshot.`)), timeoutMs);
3915
+ })
3916
+ ]));
3917
+ } finally {
3918
+ clearTimeout(timer2);
3919
+ let bound;
3920
+ Promise.race([settled, new Promise((resolve2) => {
3921
+ bound = setTimeout(resolve2, ABANDONED_CAPTURE_DETACH_MS);
3922
+ bound.unref?.();
3923
+ })]).then(() => {
3924
+ clearTimeout(bound);
3925
+ return session;
3926
+ }).then((cdp) => cdp.detach()).catch(() => {
3927
+ return;
3928
+ });
3929
+ }
3930
+ }
3931
+
3684
3932
  // cli/src/runtime/failures.ts
3685
3933
  import { randomUUID as randomUUID4 } from "node:crypto";
3686
3934
 
@@ -3696,7 +3944,10 @@ class RuntimeFault extends Error {
3696
3944
  }
3697
3945
  }
3698
3946
  var OBSERVATION_OPERATIONS = new Set(["list_tabs", "list_downloads", "read_page", "screenshot", "wait_for", "capabilities", "inspect", "events", "diagnostics", "export_page", "webmcp_list", "runtime_health"]);
3947
+ var USER_IN_CONTROL_MESSAGE = "The user controls this tab in live view (takeover), so the agent cannot use it now. No action was dispatched.";
3948
+ var USER_IN_CONTROL_RECOVERY = "Wait for the user to give control back with browser_takeover_status {tabId, waitMs}, or ask for it with browser_takeover_reclaim and respect a declined request. Other tabs keep working. Once you have control, observe this tab again before acting; retry only with a fresh idempotency key.";
3699
3949
  var messages = {
3950
+ user_in_control: USER_IN_CONTROL_MESSAGE,
3700
3951
  unsupported_target: "Chrome does not expose the interface required by this operation on this target.",
3701
3952
  browser_operation_unsupported: "Chrome reported that this operation or protocol method is not supported on this target.",
3702
3953
  tab_closed: "The tab is closed or detached.",
@@ -3726,7 +3977,7 @@ function failureFor(error, op, operationId, stage, timing) {
3726
3977
  code2 = "transfer_failed";
3727
3978
  const observation = OBSERVATION_OPERATIONS.has(op);
3728
3979
  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.";
3980
+ 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
3981
  const diagnosticId = randomUUID4();
3731
3982
  console.error(JSON.stringify({ event: "runtime_failure", diagnosticId, operationId, operation: op, stage, code: code2, outcome, ...timing }));
3732
3983
  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 +3992,7 @@ var REF_ACTION_TIMEOUT_MS = 5000;
3741
3992
  var NAVIGATION_TIMEOUT_MS = 20000;
3742
3993
  var READ_PAGE_TIMEOUT_MS = 1e4;
3743
3994
  var SCREENSHOT_TIMEOUT_MS = 15000;
3995
+ var SCREENSHOT_FONT_WAIT_MS = 1000;
3744
3996
  var MAX_FULL_PAGE_HEIGHT = 4000;
3745
3997
  var MAX_FULL_PAGE_WIDTH = 4096;
3746
3998
  var MAX_TYPED_KEYS_CHARS = 500;
@@ -3771,6 +4023,12 @@ function refActionError(error, ref, verb) {
3771
4023
  return new Error(`${message}
3772
4024
  Ref ${ref} comes from the most recent browser_read_page snapshot of this tab. ` + `The ${verb} outcome may be uncertain. ` + BROWSER_RECOVERY, { cause: error });
3773
4025
  }
4026
+ function tabStateView(state) {
4027
+ return {
4028
+ retention: state.retention,
4029
+ ...state.viewport ? { viewport: { width: state.viewport.width, height: state.viewport.height } } : {}
4030
+ };
4031
+ }
3774
4032
 
3775
4033
  class BrowserRuntime {
3776
4034
  context;
@@ -3788,6 +4046,7 @@ class BrowserRuntime {
3788
4046
  initialization = new Map;
3789
4047
  tabState;
3790
4048
  observations = new Map;
4049
+ lastActions = new Map;
3791
4050
  tabPresentation = new WeakMap;
3792
4051
  savingDownloads = new Set;
3793
4052
  constructor(context, downloadsPath, uploadsPath = `${downloadsPath}.uploads`, downloadHandler, guardPage) {
@@ -3850,6 +4109,7 @@ class BrowserRuntime {
3850
4109
  this.pages.delete(currentId);
3851
4110
  this.cursor.delete(currentId);
3852
4111
  this.observations.delete(currentId);
4112
+ this.lastActions.delete(currentId);
3853
4113
  this.initialization.delete(page);
3854
4114
  this.viewportSessions.delete(currentId);
3855
4115
  this.tabState.closed(page).catch(() => {
@@ -4008,8 +4268,9 @@ class BrowserRuntime {
4008
4268
  await this.initialization.get(page);
4009
4269
  const tabId = this.ids.get(page);
4010
4270
  const state = (await this.tabState.resolve(page)).state;
4271
+ const info = ({ windowId: windowId2, title: title2 }) => ({ tabId, windowId: windowId2, title: title2, url: page.url(), ...tabStateView(state) });
4011
4272
  if (this.events.get(page)?.activeDialog()) {
4012
- return { ...state, tabId, ...this.tabPresentation.get(page) ?? { windowId: "unknown", title: "" }, url: page.url() };
4273
+ return info(this.tabPresentation.get(page) ?? { windowId: "unknown", title: "" });
4013
4274
  }
4014
4275
  let windowId = "unknown";
4015
4276
  let title = "";
@@ -4025,7 +4286,7 @@ class BrowserRuntime {
4025
4286
  });
4026
4287
  }
4027
4288
  this.tabPresentation.set(page, { windowId, title });
4028
- return { ...state, tabId, windowId, title, url: page.url() };
4289
+ return info({ windowId, title });
4029
4290
  }
4030
4291
  async listTabs() {
4031
4292
  await Promise.all(this.initialization.values());
@@ -4066,6 +4327,67 @@ class BrowserRuntime {
4066
4327
  hasPendingInteraction() {
4067
4328
  return [...this.pages.values()].some((page) => !!this.events.get(page)?.activeDialog() || !!this.events.get(page)?.pendingAction());
4068
4329
  }
4330
+ noteAction(tabId, operation) {
4331
+ const page = this.pages.get(tabId);
4332
+ if (page && !page.isClosed())
4333
+ this.lastActions.set(tabId, { operation, endedAt: Date.now() });
4334
+ }
4335
+ observedAt(page, tabId, capturedAt = Date.now()) {
4336
+ const network = this.events.get(page).networkState(capturedAt), lastAction = this.lastActions.get(tabId);
4337
+ return (document2) => pageState(capturedAt, network, lastAction, document2);
4338
+ }
4339
+ async observationSession(page, read) {
4340
+ const events = this.events.get(page);
4341
+ return await this.guardRaw(page, "all", async () => {
4342
+ await events.ready;
4343
+ const held = events.session();
4344
+ if (held)
4345
+ return await read(held);
4346
+ const cdp = await this.context.newCDPSession(page);
4347
+ try {
4348
+ return await read(cdp);
4349
+ } finally {
4350
+ await cdp.detach().catch(() => {
4351
+ return;
4352
+ });
4353
+ }
4354
+ });
4355
+ }
4356
+ async guardRaw(page, rewrite, work) {
4357
+ const events = this.events.get(page);
4358
+ const ended = () => page.isClosed() ? new Error("Target page, context or browser has been closed") : events.crashed ? new Error("Target crashed") : undefined;
4359
+ const early = ended();
4360
+ if (early)
4361
+ throw early;
4362
+ let stop = () => {};
4363
+ const interrupted = new Promise((_, reject) => {
4364
+ const onEnd = () => reject(ended() ?? new Error("Target page, context or browser has been closed"));
4365
+ const offCrash = events.onCrash(onEnd);
4366
+ page.once("close", onEnd);
4367
+ stop = () => {
4368
+ offCrash();
4369
+ page.off("close", onEnd);
4370
+ };
4371
+ });
4372
+ interrupted.catch(() => {
4373
+ return;
4374
+ });
4375
+ try {
4376
+ return await Promise.race([work(), interrupted]);
4377
+ } catch (error) {
4378
+ const end = ended();
4379
+ if (end)
4380
+ throw end;
4381
+ if (error instanceof ObservationError || this.context.browser()?.isConnected() === false)
4382
+ throw error;
4383
+ const message = error instanceof Error ? error.message : "";
4384
+ if (rewrite === "closed" && !/Target closed|Session closed|detached|has been closed/i.test(message))
4385
+ throw error;
4386
+ throw new Error(`Execution context was destroyed (${rewrite === "all" ? "isolated observation read" : "screenshot capture"})`, { cause: error });
4387
+ } finally {
4388
+ stop();
4389
+ }
4390
+ }
4069
4391
  closeUploads() {
4070
4392
  this.tabState.suspend();
4071
4393
  this.uploads.close();
@@ -4090,14 +4412,39 @@ class BrowserRuntime {
4090
4412
  const observation = parseObservation(input.observe);
4091
4413
  const previous = this.observations.get(String(input.tabId));
4092
4414
  const previousTabs = new Set(this.pages.keys());
4093
- const invoke = () => this.dispatch(action, input, execution);
4415
+ let admitted = false;
4416
+ const dispatchExecution = {
4417
+ ...execution,
4418
+ beforeDispatch: () => {
4419
+ execution.beforeDispatch?.();
4420
+ admitted = true;
4421
+ }
4422
+ };
4423
+ const invoke = () => this.dispatch(action, input, dispatchExecution);
4094
4424
  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());
4425
+ const recordAction = () => {
4426
+ if (admitted && typeof input.tabId === "string" && PAGE_EFFECT_OPERATIONS.has(action))
4427
+ this.noteAction(input.tabId, action);
4428
+ };
4429
+ let result;
4430
+ try {
4431
+ result = await (guarded ? events.run(execution.operationId ?? crypto.randomUUID(), invoke) : invoke());
4432
+ } catch (error) {
4433
+ recordAction();
4434
+ throw error;
4435
+ }
4436
+ const notDispatched = result.invoked === false || result.dispatched === false || result.selected === false || result.handled === false;
4437
+ if (!notDispatched && result.dispatch?.status !== "not_dispatched")
4438
+ recordAction();
4439
+ if (action === "open_tab") {
4440
+ const opened = result.tab?.tabId;
4441
+ if (typeof opened === "string")
4442
+ this.noteAction(opened, action);
4443
+ }
4096
4444
  if (page && !page.isClosed())
4097
4445
  await this.guardPage?.(page);
4098
4446
  if (!observation || !page || page.isClosed())
4099
4447
  return result;
4100
- const notDispatched = result.invoked === false || result.dispatched === false || result.selected === false || result.handled === false;
4101
4448
  const uncertain = result.status === "unknown";
4102
4449
  const dispatch = result.dispatch ?? { status: uncertain ? "unknown" : notDispatched ? "not_dispatched" : "completed" };
4103
4450
  const succeeded = !notDispatched && !uncertain && result.status !== "Error" && result.status !== "Canceled";
@@ -4170,6 +4517,19 @@ class BrowserRuntime {
4170
4517
  if (result?.matched === false || result?.expected?.matched === false || result?.dispatch && result.dispatch.status !== "completed" || result?.code || result?.observation?.available === false)
4171
4518
  return { results, stoppedAt: index, remaining: steps.length - index - 1, code: "batch_step_stopped", retrySafe: false };
4172
4519
  } catch (error) {
4520
+ if (error instanceof RuntimeFault && error.beforeDispatch) {
4521
+ if (index === 0)
4522
+ throw error;
4523
+ const refused = failureFor(error, step.action, execution.operationId ?? crypto.randomUUID(), "batch_step");
4524
+ return {
4525
+ results: [...results, { index, action: step.action, status: "not_dispatched", ...refused.result, code: refused.error.code }],
4526
+ stoppedAt: index,
4527
+ remaining: steps.length - index,
4528
+ code: "batch_step_stopped",
4529
+ retrySafe: false,
4530
+ recovery: refused.result.recovery
4531
+ };
4532
+ }
4173
4533
  const failure = failureFor(error, step.action, execution.operationId ?? crypto.randomUUID(), "batch_step");
4174
4534
  return {
4175
4535
  results: [...results, { index, action: step.action, status: "unknown", ...failure.result, code: failure.error.code }],
@@ -4235,7 +4595,7 @@ class BrowserRuntime {
4235
4595
  const transform = this.screenshots.get(tabId);
4236
4596
  if (!transform || transform.id !== request.id)
4237
4597
  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 }));
4598
+ const current = (await this.observationSession(page, readViewportGeometry)).state;
4239
4599
  const map = (point) => screenshotPoint(transform, current, request, point);
4240
4600
  input = { ...input, ...input.from ? { from: map(input.from), to: map(input.to) } : map({ x: Number(input.x), y: Number(input.y) }) };
4241
4601
  delete input.screenshot;
@@ -4302,7 +4662,7 @@ class BrowserRuntime {
4302
4662
  case "cancel_transfer":
4303
4663
  return { tabId, ...await this.events.get(page).cancelTransfer(String(input.eventId)) };
4304
4664
  case "inspect":
4305
- return { tabId, ...await inspectElement(page, input) };
4665
+ return { tabId, ...await inspectElement(page, input), pageState: this.observedAt(page, tabId)() };
4306
4666
  case "hover":
4307
4667
  this.cursor.delete(tabId);
4308
4668
  await this.refLocator(page, requireRef(input.ref)).hover({ timeout: REF_ACTION_TIMEOUT_MS, modifiers: input.modifiers });
@@ -4360,7 +4720,7 @@ class BrowserRuntime {
4360
4720
  retention: input.mode === "handoff" ? "user" : input.mode === "temporary" ? "temporary" : "retained",
4361
4721
  ...input.mode === "handoff" ? { ownerSessionId: undefined, ...input.preserveViewport === true ? {} : { viewport: undefined } } : {}
4362
4722
  });
4363
- return { changed: true, ...next };
4723
+ return { changed: true, tabId, ...tabStateView(next) };
4364
4724
  }
4365
4725
  case "clipboard":
4366
4726
  return { tabId, ...await clipboard(page, input), scope: "system" };
@@ -4466,11 +4826,15 @@ class BrowserRuntime {
4466
4826
  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
4827
  };
4468
4828
  }
4829
+ const observed = this.observedAt(page, tabId);
4469
4830
  const result = {
4470
4831
  tabId,
4471
4832
  url: page.url(),
4472
4833
  title: await page.title().catch(() => ""),
4473
- ...renderSnapshot(snapshot, request)
4834
+ ...renderSnapshot(snapshot, request),
4835
+ pageState: observed(await this.observationSession(page, (cdp) => evaluateIsolated(cdp, DOCUMENT_STATE_EXPRESSION)).catch(() => {
4836
+ return;
4837
+ }))
4474
4838
  };
4475
4839
  this.observations.set(tabId, { text: result.text.slice(0, 30000), url: result.url });
4476
4840
  if (this.observations.size > 64)
@@ -4479,12 +4843,23 @@ class BrowserRuntime {
4479
4843
  }
4480
4844
  case "screenshot": {
4481
4845
  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 = {}) => {
4846
+ let fontTimer;
4847
+ await Promise.race([
4848
+ this.observationSession(page, (cdp) => evaluateIsolated(cdp, fontsReadyExpression(SCREENSHOT_FONT_WAIT_MS), true)).catch(() => {
4849
+ return;
4850
+ }),
4851
+ new Promise((resolve2) => {
4852
+ fontTimer = setTimeout(resolve2, SCREENSHOT_FONT_WAIT_MS);
4853
+ })
4854
+ ]);
4855
+ clearTimeout(fontTimer);
4856
+ const { state, document: documentState } = await this.observationSession(page, readViewportGeometry);
4857
+ const capture = async (region) => {
4484
4858
  execution.screenshotStage?.("screenshot_capture");
4485
- const bytes2 = await page.screenshot({ ...options, type: "png", scale: "css", timeout: SCREENSHOT_TIMEOUT_MS });
4859
+ const { bytes: bytes2, capturedAt } = await captureCssScreenshot(this.context, page, region, SCREENSHOT_TIMEOUT_MS, (work) => this.guardRaw(page, "closed", work));
4860
+ const observed = this.observedAt(page, tabId, capturedAt);
4486
4861
  execution.screenshotStage?.("screenshot_encode");
4487
- return bytes2;
4862
+ return { bytes: bytes2, pageState: observed(documentState) };
4488
4863
  };
4489
4864
  const record = (width, height, originX, originY) => {
4490
4865
  const transform = { id: crypto.randomUUID(), state, width, height, originX, originY };
@@ -4495,22 +4870,19 @@ class BrowserRuntime {
4495
4870
  const crop = input.crop;
4496
4871
  if (crop.x + crop.width > state.width || crop.y + crop.height > state.height)
4497
4872
  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) };
4873
+ const { bytes: bytes2, pageState: pageState3 } = await capture({ kind: "viewport", x: crop.x, y: crop.y, width: crop.width, height: crop.height });
4874
+ 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
4875
  }
4501
4876
  if (input.fullPage === true) {
4502
4877
  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
- }));
4878
+ const metrics = await this.observationSession(page, readDocumentSize);
4507
4879
  const width = Math.min(metrics.docWidth, MAX_FULL_PAGE_WIDTH);
4508
4880
  const height = Math.min(metrics.docHeight, MAX_FULL_PAGE_HEIGHT);
4509
4881
  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) };
4882
+ const { bytes: bytes2, pageState: pageState3 } = await capture({ kind: "document", x: 0, y: 0, width, height, fitsViewport: metrics.docWidth <= state.width && metrics.docHeight <= state.height });
4883
+ 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
4884
  }
4513
- const bytes = await capture();
4885
+ const { bytes, pageState: pageState2 } = await capture({ kind: "viewport", x: 0, y: 0, width: state.width, height: state.height });
4514
4886
  const cursor = this.cursor.get(tabId);
4515
4887
  return {
4516
4888
  base64: bytes.toString("base64"),
@@ -4519,7 +4891,8 @@ class BrowserRuntime {
4519
4891
  ...record(bytes.readUInt32BE(16), bytes.readUInt32BE(20), state.scrollX, state.scrollY),
4520
4892
  cursorX: cursor?.x,
4521
4893
  cursorY: cursor?.y,
4522
- cursorKnown: cursor !== undefined
4894
+ cursorKnown: cursor !== undefined,
4895
+ pageState: pageState2
4523
4896
  };
4524
4897
  }
4525
4898
  case "move_mouse": {
@@ -4608,7 +4981,7 @@ class BrowserRuntime {
4608
4981
  return { tabId, direction, amount, ...pointer };
4609
4982
  }
4610
4983
  case "wait_for": {
4611
- return { tabId, ...await waitForBrowserCondition(page, parseWaitInput(input)) };
4984
+ return { tabId, ...await waitForBrowserCondition(page, parseWaitInput(input)), pageState: this.observedAt(page, tabId)() };
4612
4985
  }
4613
4986
  case "upload_begin": {
4614
4987
  const target2 = parseUploadTarget(input);
@@ -4795,13 +5168,25 @@ class BrowserRuntime {
4795
5168
  }
4796
5169
  return filename;
4797
5170
  };
5171
+ const documentState = () => {
5172
+ try {
5173
+ const { readyState, visibilityState } = document;
5174
+ return {
5175
+ readyState: typeof readyState === "string" ? readyState.slice(0, 16) : undefined,
5176
+ visibilityState: typeof visibilityState === "string" ? visibilityState.slice(0, 16) : undefined
5177
+ };
5178
+ } catch {
5179
+ return;
5180
+ }
5181
+ };
4798
5182
  try {
4799
5183
  const invoke = new Function("r5dCreateArtifact", `"use strict"; return (async () => {
4800
5184
  ${code2}
4801
5185
  })()`);
4802
- return { result: await invoke(r5dCreateArtifact), artifacts };
5186
+ const result = await invoke(r5dCreateArtifact);
5187
+ return { result, artifacts, document: documentState() };
4803
5188
  } catch (error) {
4804
- return { artifacts, failure: "script_exception" };
5189
+ return { artifacts, failure: "script_exception", document: documentState() };
4805
5190
  }
4806
5191
  }, { code: input.code, maxBytes: MAX_RUN_JS_ARTIFACT_BYTES, maxCount: MAX_RUN_JS_ARTIFACT_COUNT });
4807
5192
  } catch (error) {
@@ -4811,6 +5196,7 @@ ${code2}
4811
5196
  }
4812
5197
  throw new Error(stripCallLog(message));
4813
5198
  }
5199
+ const observed = this.observedAt(page, tabId);
4814
5200
  if (evaluated.failure && !evaluated.artifacts.length)
4815
5201
  throw new RuntimeFault("script_exception", "Review the submitted script locally. Effects before the exception may have occurred; do not replay automatically.");
4816
5202
  const serialized = JSON.stringify(evaluated.result);
@@ -4828,7 +5214,8 @@ ${code2}
4828
5214
  intent: input.intent,
4829
5215
  reason: input.reason,
4830
5216
  untrusted: true,
4831
- outcomeVerified: false
5217
+ outcomeVerified: false,
5218
+ pageState: observed(evaluated.document)
4832
5219
  };
4833
5220
  }
4834
5221
  default:
@@ -4889,6 +5276,7 @@ class NativeRuntime {
4889
5276
  operations = new Map;
4890
5277
  hooks = Promise.resolve();
4891
5278
  browserId;
5279
+ userControlledTabs = new Set;
4892
5280
  constructor(context, instanceId, directory, serverOrigin) {
4893
5281
  this.context = context;
4894
5282
  this.instanceId = instanceId;
@@ -5128,7 +5516,11 @@ class NativeRuntime {
5128
5516
  this.operations.get(operationId)?.abort(new Error("Blocked target closed by approved recovery"));
5129
5517
  return { closed: true };
5130
5518
  }
5131
- admissionGuard(args, scope) {
5519
+ assertAgentControl(tabId, op) {
5520
+ if (typeof tabId === "string" && this.userControlledTabs.has(tabId) && op !== "release_tab" && op !== "session_end")
5521
+ throw new RuntimeFault("user_in_control", USER_IN_CONTROL_RECOVERY, true);
5522
+ }
5523
+ admissionGuard(args, scope, op) {
5132
5524
  const epoch = this.scopeEpoch(scope), connectionEpoch = this.connectionEpoch;
5133
5525
  const tabId = typeof args.tabId === "string" ? args.tabId : undefined;
5134
5526
  const page = tabId ? this.engine.page(tabId) : undefined;
@@ -5136,6 +5528,7 @@ class NativeRuntime {
5136
5528
  return (checkDocument = true) => {
5137
5529
  if (this.scopeEpoch(scope) !== epoch || this.connectionEpoch !== connectionEpoch)
5138
5530
  throw new RuntimeFault("scope_rejected", "Scope or connection changed while waiting; submit a fresh authorized request.", true);
5531
+ this.assertAgentControl(tabId, op);
5139
5532
  if (tabId) {
5140
5533
  let current2;
5141
5534
  try {
@@ -5186,6 +5579,7 @@ class NativeRuntime {
5186
5579
  await this.hooks;
5187
5580
  this.validateScope(scope);
5188
5581
  if (typeof args.tabId === "string") {
5582
+ this.assertAgentControl(args.tabId, op);
5189
5583
  const page = await this.claimPage(args.tabId, scope);
5190
5584
  await this.track(page);
5191
5585
  this.assertPageAvailable(page);
@@ -5296,16 +5690,16 @@ import WebSocket from "ws";
5296
5690
  // backend/live-wire.ts
5297
5691
  var isRuntimeTabId = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
5298
5692
  var MAX_LIVE_FRAME_BYTES = 1500000;
5299
- var finite = (value, min, max) => Number.isFinite(value) && value >= min && value <= max;
5693
+ var finite2 = (value, min, max) => Number.isFinite(value) && value >= min && value <= max;
5300
5694
  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);
5695
+ var coordinate = (value) => typeof value === "number" && finite2(value, -1e5, 1e5);
5696
+ var delta = (value) => typeof value === "number" && finite2(value, -1e6, 1e6);
5303
5697
  var TOOL = /^[a-z][a-z0-9_]{0,63}$/;
5304
5698
  function sanitizeLiveEvent(value) {
5305
5699
  if (!value || typeof value !== "object" || Array.isArray(value))
5306
5700
  return null;
5307
5701
  const e = value;
5308
- if (!isRuntimeTabId(e.runtimeTabId) || !uint32(e.navSeq) || typeof e.at !== "number" || !finite(e.at, 0, 100000000000000))
5702
+ if (!isRuntimeTabId(e.runtimeTabId) || !uint32(e.navSeq) || typeof e.at !== "number" || !finite2(e.at, 0, 100000000000000))
5309
5703
  return null;
5310
5704
  const base = { runtimeTabId: e.runtimeTabId, navSeq: e.navSeq, at: e.at };
5311
5705
  switch (e.type) {
@@ -5327,6 +5721,53 @@ function sanitizeLiveEvent(value) {
5327
5721
  return null;
5328
5722
  }
5329
5723
  }
5724
+ var LIVE_MODIFIERS = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
5725
+ var MAX_LIVE_INPUT_TEXT = 200;
5726
+ var isLiveRelease = (event) => event.kind === "release" || (event.kind === "mouse" || event.kind === "key") && event.type === "up";
5727
+ var MAX_LIVE_DIALOG_TEXT = 500;
5728
+ var MAX_CONTROL_TABS = 8;
5729
+ var modifierMask = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 15;
5730
+ var NAMED_KEY = /^[A-Za-z][A-Za-z0-9]{1,31}$/;
5731
+ var KEY_CODE = /^[A-Za-z0-9]{0,32}$/;
5732
+ var CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/;
5733
+ var LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
5734
+ var cleanText = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max && !CONTROL.test(value) && !LONE_SURROGATE.test(value);
5735
+ var keyValue = (value) => typeof value === "string" && (NAMED_KEY.test(value) || value.length <= 4 && cleanText(value, 4) && !/[\t\n\r]/.test(value));
5736
+ var button = (value) => value === "left" || value === "middle" || value === "right";
5737
+ function sanitizeLiveInput(value) {
5738
+ if (!value || typeof value !== "object" || Array.isArray(value))
5739
+ return null;
5740
+ const e = value;
5741
+ const mac = e.mac === true;
5742
+ switch (e.kind) {
5743
+ case "mouse":
5744
+ if (e.type !== "move" && e.type !== "down" && e.type !== "up" || !coordinate(e.x) || !coordinate(e.y) || !button(e.button) || !modifierMask(e.modifiers) || typeof e.clickCount !== "number" || !Number.isInteger(e.clickCount) || e.clickCount < 0 || e.clickCount > 3)
5745
+ return null;
5746
+ return { kind: "mouse", type: e.type, x: e.x, y: e.y, button: e.button, clickCount: e.type === "move" ? 0 : Math.max(1, e.clickCount), modifiers: e.modifiers, mac };
5747
+ case "wheel":
5748
+ if (!coordinate(e.x) || !coordinate(e.y) || !coordinate(e.deltaX) || !coordinate(e.deltaY) || !modifierMask(e.modifiers))
5749
+ return null;
5750
+ return { kind: "wheel", x: e.x, y: e.y, deltaX: e.deltaX, deltaY: e.deltaY, modifiers: e.modifiers, mac };
5751
+ case "key":
5752
+ if (e.type !== "down" && e.type !== "up" || !keyValue(e.key) || typeof e.code !== "string" || !KEY_CODE.test(e.code) || !modifierMask(e.modifiers))
5753
+ return null;
5754
+ return { kind: "key", type: e.type, key: e.key, code: e.code, modifiers: e.modifiers, repeat: e.repeat === true, mac };
5755
+ case "text":
5756
+ return cleanText(e.text, MAX_LIVE_INPUT_TEXT) ? { kind: "text", text: e.text } : null;
5757
+ case "release":
5758
+ return { kind: "release" };
5759
+ case "dialog":
5760
+ if (typeof e.accept !== "boolean")
5761
+ return null;
5762
+ if (e.text === undefined)
5763
+ return { kind: "dialog", accept: e.accept };
5764
+ return typeof e.text === "string" && e.text.length <= MAX_LIVE_DIALOG_TEXT && !CONTROL.test(e.text) && !LONE_SURROGATE.test(e.text) ? { kind: "dialog", accept: e.accept, text: e.text } : null;
5765
+ default:
5766
+ return null;
5767
+ }
5768
+ }
5769
+ var DIALOG_TYPES = new Set(["alert", "confirm", "prompt", "beforeunload"]);
5770
+ var MAX_LIVE_DIALOG_MESSAGE = 500;
5330
5771
 
5331
5772
  // cli/src/live/wire.ts
5332
5773
  function mediaURL(server) {
@@ -5380,6 +5821,7 @@ function eventMessage(value, navSeq) {
5380
5821
 
5381
5822
  // cli/src/live/producer.ts
5382
5823
  var STAGE_TIMEOUT_MS = 5000;
5824
+ var MAX_ATTACH_RETRIES = 4;
5383
5825
 
5384
5826
  class CaptureTimeout extends Error {
5385
5827
  stage;
@@ -5405,6 +5847,7 @@ class NativeLiveProducer {
5405
5847
  active = false;
5406
5848
  closed = false;
5407
5849
  tab;
5850
+ controlTab;
5408
5851
  generation = 0;
5409
5852
  serial = Promise.resolve();
5410
5853
  socket;
@@ -5413,8 +5856,9 @@ class NativeLiveProducer {
5413
5856
  unlisten;
5414
5857
  frameSeq = 0;
5415
5858
  navSeq = 0;
5416
- lastFrame = 0;
5417
5859
  eventWindow = { start: 0, count: 0 };
5860
+ retries = 0;
5861
+ retryTab;
5418
5862
  constructor(options) {
5419
5863
  this.options = options;
5420
5864
  const url = new URL(options.mediaUrl);
@@ -5434,17 +5878,27 @@ class NativeLiveProducer {
5434
5878
  if (this.closed)
5435
5879
  return this.serial;
5436
5880
  this.active = frame.active === true;
5437
- if (isRuntimeTabId(frame.followTabId))
5881
+ if (isRuntimeTabId(frame.followTabId) && (!this.controlTab || frame.followTabId === this.controlTab))
5438
5882
  this.tab = frame.followTabId;
5439
5883
  return this.schedule();
5440
5884
  }
5441
5885
  followTab(runtimeTabId) {
5442
- if (this.closed || !isRuntimeTabId(runtimeTabId) || runtimeTabId === this.tab)
5886
+ if (this.closed || !isRuntimeTabId(runtimeTabId) || runtimeTabId === this.tab || this.controlTab && runtimeTabId !== this.controlTab)
5443
5887
  return this.serial;
5444
5888
  this.tab = runtimeTabId;
5445
5889
  this.navSeq++;
5446
5890
  return this.schedule();
5447
5891
  }
5892
+ setControl(runtimeTabId) {
5893
+ if (this.closed)
5894
+ return this.serial;
5895
+ this.controlTab = isRuntimeTabId(runtimeTabId) ? runtimeTabId : undefined;
5896
+ if (!this.controlTab || this.controlTab === this.tab)
5897
+ return this.serial;
5898
+ this.tab = this.controlTab;
5899
+ this.navSeq++;
5900
+ return this.schedule();
5901
+ }
5448
5902
  emitCursor(event) {
5449
5903
  const ws = this.socket;
5450
5904
  if (!this.enabled || !this.active || this.closed || !ws || ws.readyState !== WebSocket.OPEN || ws.bufferedAmount > 512 * 1024)
@@ -5482,6 +5936,23 @@ class NativeLiveProducer {
5482
5936
  });
5483
5937
  return this.serial;
5484
5938
  }
5939
+ retry(generation, detail) {
5940
+ if (generation !== this.generation)
5941
+ return;
5942
+ if (this.retryTab !== this.tab) {
5943
+ this.retryTab = this.tab;
5944
+ this.retries = 0;
5945
+ }
5946
+ if (this.retries >= MAX_ATTACH_RETRIES) {
5947
+ this.state("blocked", detail);
5948
+ return;
5949
+ }
5950
+ const timer2 = setTimeout(() => {
5951
+ if (generation === this.generation)
5952
+ this.schedule();
5953
+ }, 250 * ++this.retries);
5954
+ timer2.unref?.();
5955
+ }
5485
5956
  async teardown() {
5486
5957
  clearInterval(this.heartbeat);
5487
5958
  this.heartbeat = undefined;
@@ -5531,10 +6002,15 @@ class NativeLiveProducer {
5531
6002
  this.state("blocked", error instanceof CaptureTimeout ? `${error.stage}_timeout` : "page_unavailable");
5532
6003
  return;
5533
6004
  }
5534
- if (generation !== this.generation || initialNav !== this.navSeq) {
6005
+ if (generation !== this.generation) {
5535
6006
  await this.teardown();
5536
6007
  return;
5537
6008
  }
6009
+ if (initialNav !== this.navSeq) {
6010
+ await this.teardown();
6011
+ this.retry(generation, "page_unavailable");
6012
+ return;
6013
+ }
5538
6014
  if (!authorized) {
5539
6015
  await this.teardown();
5540
6016
  this.state("blocked", "page_unavailable");
@@ -5573,7 +6049,7 @@ class NativeLiveProducer {
5573
6049
  }
5574
6050
  ws.on("error", () => {});
5575
6051
  ws.once("close", () => {
5576
- if (generation === this.generation && !this.closed) {
6052
+ if (generation === this.generation && !this.closed && this.socket === ws) {
5577
6053
  this.active = false;
5578
6054
  this.schedule();
5579
6055
  }
@@ -5603,33 +6079,29 @@ class NativeLiveProducer {
5603
6079
  return;
5604
6080
  }
5605
6081
  let checkingFrame = false;
5606
- cdp.on("Page.screencastFrame", (event) => {
5607
- cdp.send("Page.screencastFrameAck", { sessionId: event.sessionId }).catch(() => {});
5608
- if (generation !== this.generation || !this.enabled || !this.active || ws.readyState !== WebSocket.OPEN)
6082
+ let lastFrame = 0;
6083
+ let deferred;
6084
+ const forward = (event, nav) => {
6085
+ if (generation !== this.generation || nav !== this.navSeq || !this.enabled || !this.active || ws.readyState !== WebSocket.OPEN)
5609
6086
  return;
5610
- let allowed = false;
5611
- try {
5612
- allowed = this.options.getPage(tab) === page;
5613
- } catch {}
5614
- if (!allowed) {
5615
- this.active = false;
5616
- this.schedule();
6087
+ const wait = Math.max(lastFrame + 100 - Date.now(), checkingFrame || ws.bufferedAmount > 512 * 1024 ? 100 : 0);
6088
+ if (wait > 0) {
6089
+ clearTimeout(deferred);
6090
+ deferred = setTimeout(() => {
6091
+ deferred = undefined;
6092
+ forward(event, nav);
6093
+ }, wait);
6094
+ deferred.unref?.();
5617
6095
  return;
5618
6096
  }
5619
- const now = Date.now();
5620
- if (now - this.lastFrame < 100 || ws.bufferedAmount > 512 * 1024 || event.data.length > Math.ceil(MAX_LIVE_FRAME_BYTES / 3) * 4)
5621
- return;
5622
- if (checkingFrame)
5623
- return;
5624
- this.lastFrame = now;
6097
+ lastFrame = Date.now();
5625
6098
  checkingFrame = true;
5626
- const nav = this.navSeq;
5627
6099
  (async () => {
5628
6100
  try {
5629
- const allowed2 = await bounded2("frame_authorize", this.options.authorizePage(page));
6101
+ const allowed = await bounded2("frame_authorize", this.options.authorizePage(page));
5630
6102
  if (generation !== this.generation || nav !== this.navSeq || this.closed || !this.enabled || !this.active || this.socket !== ws || ws.readyState !== WebSocket.OPEN)
5631
6103
  return;
5632
- if (!allowed2 || this.options.getPage(tab) !== page) {
6104
+ if (!allowed || this.options.getPage(tab) !== page) {
5633
6105
  this.active = false;
5634
6106
  this.schedule();
5635
6107
  return;
@@ -5640,12 +6112,40 @@ class NativeLiveProducer {
5640
6112
  checkingFrame = false;
5641
6113
  }
5642
6114
  })();
6115
+ };
6116
+ cdp.on("Page.screencastFrame", (event) => {
6117
+ cdp.send("Page.screencastFrameAck", { sessionId: event.sessionId }).catch(() => {});
6118
+ if (generation !== this.generation || !this.enabled || !this.active || ws.readyState !== WebSocket.OPEN)
6119
+ return;
6120
+ let allowed = false;
6121
+ try {
6122
+ allowed = this.options.getPage(tab) === page;
6123
+ } catch {}
6124
+ if (!allowed) {
6125
+ this.active = false;
6126
+ this.schedule();
6127
+ return;
6128
+ }
6129
+ if (event.data.length > Math.ceil(MAX_LIVE_FRAME_BYTES / 3) * 4)
6130
+ return;
6131
+ forward(event, this.navSeq);
5643
6132
  });
5644
6133
  const startNav = this.navSeq;
5645
- if (!await bounded2("authorize", this.options.authorizePage(page)) || generation !== this.generation || startNav !== this.navSeq) {
6134
+ const stillAllowed = await bounded2("authorize", this.options.authorizePage(page));
6135
+ if (generation !== this.generation) {
5646
6136
  await this.teardown();
5647
6137
  return;
5648
6138
  }
6139
+ if (startNav !== this.navSeq) {
6140
+ await this.teardown();
6141
+ this.retry(generation, "capture_unavailable");
6142
+ return;
6143
+ }
6144
+ if (!stillAllowed) {
6145
+ await this.teardown();
6146
+ this.state("blocked", "page_unavailable");
6147
+ return;
6148
+ }
5649
6149
  await bounded2("start_screencast", cdp.send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: 1600, maxHeight: 1000, everyNthFrame: 1 }));
5650
6150
  if (generation !== this.generation) {
5651
6151
  await this.teardown();
@@ -5656,18 +6156,360 @@ class NativeLiveProducer {
5656
6156
  ws.send('{"type":"ping"}');
5657
6157
  }, 20000);
5658
6158
  this.heartbeat.unref?.();
6159
+ this.retries = 0;
5659
6160
  this.state("streaming");
5660
6161
  } catch (error) {
5661
6162
  await this.teardown();
5662
- if (generation === this.generation)
5663
- this.state("blocked", error instanceof CaptureTimeout ? `${error.stage}_timeout` : "capture_unavailable");
6163
+ if (generation !== this.generation)
6164
+ return;
6165
+ const detail = error instanceof CaptureTimeout ? `${error.stage}_timeout` : "capture_unavailable";
6166
+ if (!page.isClosed())
6167
+ this.retry(generation, detail);
6168
+ else
6169
+ this.state("blocked", detail);
5664
6170
  }
5665
6171
  }
5666
6172
  }
5667
6173
 
6174
+ // cli/src/live/takeover.ts
6175
+ var MAX_QUEUE = 128;
6176
+ var STEP_TIMEOUT_MS = 3000;
6177
+ var DIALOG_TYPES2 = new Set(["alert", "confirm", "prompt", "beforeunload"]);
6178
+ var MODIFIERS = Object.entries(LIVE_MODIFIERS);
6179
+ async function bounded3(work, ms) {
6180
+ let timer2;
6181
+ await Promise.race([work.catch(() => {}), new Promise((resolve2) => {
6182
+ timer2 = setTimeout(resolve2, ms);
6183
+ })]);
6184
+ clearTimeout(timer2);
6185
+ }
6186
+
6187
+ class TakeoverInput {
6188
+ options;
6189
+ group;
6190
+ queue = [];
6191
+ pumping;
6192
+ releases = new Map;
6193
+ constructor(options) {
6194
+ this.options = options;
6195
+ }
6196
+ get currentTab() {
6197
+ return this.group?.session?.tabId;
6198
+ }
6199
+ activate(root) {
6200
+ if (!isRuntimeTabId(root) || this.group?.root === root)
6201
+ return;
6202
+ this.deactivate();
6203
+ const page = this.options.getPage(root);
6204
+ if (!page || page.isClosed()) {
6205
+ this.lost(root);
6206
+ return;
6207
+ }
6208
+ const group = { root, tabs: [root], ended: false, cleanup: [] };
6209
+ this.group = group;
6210
+ this.join(group, root, page);
6211
+ this.focus(group, root, page);
6212
+ }
6213
+ deactivate() {
6214
+ const group = this.group;
6215
+ if (group)
6216
+ this.end(group);
6217
+ }
6218
+ input(frame) {
6219
+ const session = this.group?.session;
6220
+ if (!session || frame.runtimeTabId !== session.tabId)
6221
+ return;
6222
+ const event = sanitizeLiveInput(frame.event);
6223
+ if (!event)
6224
+ return;
6225
+ if (event.kind === "dialog") {
6226
+ this.answerDialog(this.options.events(session.page), event).catch(() => {});
6227
+ return;
6228
+ }
6229
+ const last = this.queue[this.queue.length - 1];
6230
+ if (event.kind === "mouse" && event.type === "move" && last?.session === session && last.event.kind === "mouse" && last.event.type === "move") {
6231
+ last.event = event;
6232
+ return;
6233
+ }
6234
+ const essential = isLiveRelease(event);
6235
+ if (this.queue.length >= (essential ? MAX_QUEUE * 2 : MAX_QUEUE))
6236
+ return;
6237
+ this.push({ session, event });
6238
+ }
6239
+ async settled(tabId) {
6240
+ const release = this.releases.get(tabId);
6241
+ if (release)
6242
+ await bounded3(release, STEP_TIMEOUT_MS);
6243
+ }
6244
+ async stop() {
6245
+ this.deactivate();
6246
+ const pumping = this.pumping;
6247
+ if (pumping)
6248
+ await bounded3(pumping, STEP_TIMEOUT_MS);
6249
+ }
6250
+ join(group, tabId, page) {
6251
+ const onClose = () => this.left(group, tabId);
6252
+ const onPopup = (popup) => {
6253
+ this.opened(group, popup);
6254
+ };
6255
+ page.on("close", onClose);
6256
+ page.on("popup", onPopup);
6257
+ group.cleanup.push(() => {
6258
+ page.off("close", onClose);
6259
+ page.off("popup", onPopup);
6260
+ });
6261
+ }
6262
+ async opened(group, popup) {
6263
+ let id;
6264
+ try {
6265
+ id = await this.options.idFor(popup);
6266
+ } catch {
6267
+ return;
6268
+ }
6269
+ if (group.ended || this.group !== group || !isRuntimeTabId(id) || popup.isClosed() || group.tabs.includes(id) || group.tabs.length >= MAX_CONTROL_TABS)
6270
+ return;
6271
+ group.tabs.push(id);
6272
+ this.join(group, id, popup);
6273
+ this.focus(group, id, popup);
6274
+ }
6275
+ left(group, tabId) {
6276
+ if (group.ended || this.group !== group)
6277
+ return;
6278
+ if (tabId === group.root) {
6279
+ this.end(group);
6280
+ this.lost(tabId);
6281
+ return;
6282
+ }
6283
+ group.tabs = group.tabs.filter((id) => id !== tabId);
6284
+ if (group.session?.tabId !== tabId) {
6285
+ this.report(group);
6286
+ return;
6287
+ }
6288
+ for (const id of [...group.tabs].reverse()) {
6289
+ const page = this.options.getPage(id);
6290
+ if (page && !page.isClosed()) {
6291
+ this.focus(group, id, page);
6292
+ return;
6293
+ }
6294
+ }
6295
+ this.end(group);
6296
+ this.lost(group.root);
6297
+ }
6298
+ focus(group, tabId, page) {
6299
+ if (group.session)
6300
+ this.close(group.session);
6301
+ const session = { tabId, page, keys: new Map, buttons: new Set, pointer: { x: Number.NaN, y: Number.NaN }, ended: false, cleanup: [] };
6302
+ group.session = session;
6303
+ const gate = this.options.agentActivity(tabId);
6304
+ if (gate) {
6305
+ session.gate = gate;
6306
+ gate.then(() => {
6307
+ if (session.gate !== gate)
6308
+ return;
6309
+ session.gate = undefined;
6310
+ if (group.session === session && !session.ended)
6311
+ this.report(group);
6312
+ });
6313
+ }
6314
+ const events = this.options.events(page);
6315
+ if (events)
6316
+ session.cleanup.push(events.onDialog((dialog) => {
6317
+ if (group.session === session && !session.ended)
6318
+ this.reportDialog(tabId, dialog);
6319
+ }));
6320
+ this.report(group);
6321
+ const open2 = events?.dialogDetails();
6322
+ if (open2)
6323
+ this.reportDialog(tabId, open2);
6324
+ }
6325
+ close(session) {
6326
+ session.ended = true;
6327
+ for (const done of session.cleanup.splice(0)) {
6328
+ try {
6329
+ done();
6330
+ } catch {}
6331
+ }
6332
+ this.queue = this.queue.filter((item) => item.session !== session);
6333
+ let finish;
6334
+ const released = new Promise((resolve2) => {
6335
+ finish = resolve2;
6336
+ });
6337
+ this.releases.set(session.tabId, released);
6338
+ released.then(() => {
6339
+ if (this.releases.get(session.tabId) === released)
6340
+ this.releases.delete(session.tabId);
6341
+ });
6342
+ this.push({ session, event: { kind: "release_all" }, done: finish });
6343
+ }
6344
+ end(group) {
6345
+ group.ended = true;
6346
+ if (this.group === group)
6347
+ this.group = undefined;
6348
+ for (const done of group.cleanup.splice(0)) {
6349
+ try {
6350
+ done();
6351
+ } catch {}
6352
+ }
6353
+ if (group.session && !group.session.ended)
6354
+ this.close(group.session);
6355
+ }
6356
+ report(group) {
6357
+ const session = group.session;
6358
+ if (group.ended || this.group !== group || !session)
6359
+ return;
6360
+ this.options.onTabs([...group.tabs], session.tabId);
6361
+ this.options.sendEvent({ type: "event", event: "live_control_state", runtimeTabId: group.root, tabs: [...group.tabs], current: session.tabId, busy: !!session.gate });
6362
+ }
6363
+ lost(tabId) {
6364
+ this.options.sendEvent({ type: "event", event: "live_control_lost", runtimeTabId: tabId, reason: "tab_closed" });
6365
+ }
6366
+ reportDialog(tabId, dialog) {
6367
+ const type = dialog?.type;
6368
+ this.options.sendEvent({
6369
+ type: "event",
6370
+ event: "live_dialog",
6371
+ runtimeTabId: tabId,
6372
+ dialog: dialog && type && DIALOG_TYPES2.has(type) ? { type, message: dialog.message.slice(0, MAX_LIVE_DIALOG_MESSAGE), ...type === "prompt" ? { defaultValue: dialog.defaultValue.slice(0, MAX_LIVE_DIALOG_TEXT) } : {} } : null
6373
+ });
6374
+ }
6375
+ push(item) {
6376
+ this.queue.push(item);
6377
+ if (this.pumping)
6378
+ return;
6379
+ this.pumping = (async () => {
6380
+ while (this.queue.length) {
6381
+ const item2 = this.queue.shift();
6382
+ const { session, event } = item2;
6383
+ try {
6384
+ if (event.kind !== "release_all") {
6385
+ if (session.ended)
6386
+ continue;
6387
+ if (session.gate)
6388
+ await session.gate;
6389
+ if (session.ended)
6390
+ continue;
6391
+ }
6392
+ await bounded3(this.dispatch(session, event), STEP_TIMEOUT_MS);
6393
+ } finally {
6394
+ item2.done?.();
6395
+ }
6396
+ }
6397
+ })().finally(() => {
6398
+ this.pumping = undefined;
6399
+ });
6400
+ }
6401
+ keyName(key2, mac) {
6402
+ if (mac === this.options.hostMac)
6403
+ return key2;
6404
+ return key2 === "Meta" ? "Control" : key2 === "Control" ? "Meta" : key2;
6405
+ }
6406
+ modifierMask(mask, mac) {
6407
+ if (mac === this.options.hostMac)
6408
+ return mask;
6409
+ const { Control, Meta } = LIVE_MODIFIERS;
6410
+ return mask & ~(Control | Meta) | (mask & Control ? Meta : 0) | (mask & Meta ? Control : 0);
6411
+ }
6412
+ async dispatch(session, event) {
6413
+ const { page } = session;
6414
+ if (page.isClosed())
6415
+ return;
6416
+ if (event.kind === "release_all" || event.kind === "release") {
6417
+ await this.releaseAll(session);
6418
+ return;
6419
+ }
6420
+ const events = this.options.events(page);
6421
+ if (event.kind === "dialog") {
6422
+ await this.answerDialog(events, event);
6423
+ return;
6424
+ }
6425
+ if (events?.dialogDetails())
6426
+ return;
6427
+ switch (event.kind) {
6428
+ case "mouse": {
6429
+ await this.syncModifiers(session, this.modifierMask(event.modifiers, event.mac));
6430
+ if (event.type === "move" || session.pointer.x !== event.x || session.pointer.y !== event.y) {
6431
+ session.pointer = { x: event.x, y: event.y };
6432
+ await page.mouse.move(event.x, event.y);
6433
+ }
6434
+ if (event.type === "down") {
6435
+ session.buttons.add(event.button);
6436
+ await page.mouse.down({ button: event.button, clickCount: event.clickCount });
6437
+ } else if (event.type === "up" && session.buttons.delete(event.button)) {
6438
+ await page.mouse.up({ button: event.button, clickCount: event.clickCount });
6439
+ }
6440
+ return;
6441
+ }
6442
+ case "wheel":
6443
+ await this.syncModifiers(session, this.modifierMask(event.modifiers, event.mac));
6444
+ if (session.pointer.x !== event.x || session.pointer.y !== event.y) {
6445
+ session.pointer = { x: event.x, y: event.y };
6446
+ await page.mouse.move(event.x, event.y);
6447
+ }
6448
+ await page.mouse.wheel(event.deltaX, event.deltaY);
6449
+ return;
6450
+ case "key": {
6451
+ const key2 = this.keyName(event.key, event.mac);
6452
+ const id = event.code || key2;
6453
+ if (event.type === "up") {
6454
+ const pressed = session.keys.get(id);
6455
+ if (pressed === undefined)
6456
+ return;
6457
+ session.keys.delete(id);
6458
+ await page.keyboard.up(pressed);
6459
+ return;
6460
+ }
6461
+ session.keys.set(id, key2);
6462
+ try {
6463
+ await page.keyboard.down(key2);
6464
+ } catch (error) {
6465
+ session.keys.delete(id);
6466
+ if (error instanceof Error && /Unknown key/.test(error.message) && [...key2].length === 1)
6467
+ await page.keyboard.insertText(key2);
6468
+ }
6469
+ return;
6470
+ }
6471
+ case "text":
6472
+ await page.keyboard.insertText(event.text);
6473
+ return;
6474
+ }
6475
+ }
6476
+ async syncModifiers(session, mask) {
6477
+ for (const [name, bit] of MODIFIERS) {
6478
+ const held = [...session.keys].filter(([, key2]) => key2 === name);
6479
+ if (mask & bit) {
6480
+ if (held.length)
6481
+ continue;
6482
+ session.keys.set(`modifier:${name}`, name);
6483
+ await session.page.keyboard.down(name);
6484
+ } else if (held.length) {
6485
+ for (const [id] of held)
6486
+ session.keys.delete(id);
6487
+ await session.page.keyboard.up(name);
6488
+ }
6489
+ }
6490
+ }
6491
+ async releaseAll(session) {
6492
+ const buttons = [...session.buttons], keys = new Set(session.keys.values());
6493
+ session.buttons.clear();
6494
+ session.keys.clear();
6495
+ for (const button2 of buttons)
6496
+ await session.page.mouse.up({ button: button2 }).catch(() => {});
6497
+ for (const key2 of keys)
6498
+ await session.page.keyboard.up(key2).catch(() => {});
6499
+ }
6500
+ async answerDialog(events, event) {
6501
+ const dialog = events?.activeDialog(), details = events?.dialogDetails();
6502
+ if (!events || !dialog || !details)
6503
+ return;
6504
+ const prompt = details.type === "prompt" && event.accept && event.text !== undefined;
6505
+ await events.handleDialog({ dialogId: dialog.dialogId, decision: event.accept ? "accept" : "dismiss", ...prompt ? { promptText: event.text } : {} }, "viewer");
6506
+ }
6507
+ }
6508
+
5668
6509
  // cli/src/runtime/relay.ts
5669
6510
  var sameScope3 = (a, b) => a.browserId === b.browserId && a.tokenId === b.tokenId && a.sessionKey === b.sessionKey && a.instanceId === b.instanceId;
5670
6511
  var QUEUE_LIMITS = Object.freeze({ maxWaiting: 16, maxWaitingPerScope: 8, maxWaitMs: 5000 });
6512
+ var INPUT_OPERATIONS = new Set(["mouse_click", "move_mouse", "hover", "drag", "scroll", "keyboard", "keyboard_type", "form_input", "select_text", "edit_text", "batch"]);
5671
6513
  var LIMIT = 2 * 1024 * 1024;
5672
6514
  function wireResult(op, value) {
5673
6515
  if (!value || typeof value !== "object")
@@ -5730,13 +6572,13 @@ class Relay {
5730
6572
  this.active?.interrupt();
5731
6573
  this.flushWaiting(code2, "The runtime was interrupted. Waiting work was never dispatched; reconnect and re-observe before submitting a fresh request.");
5732
6574
  }
5733
- rejectWaiting(entry, code2, message) {
6575
+ rejectWaiting(entry, code2, message, recovery) {
5734
6576
  const index = this.waiting.indexOf(entry);
5735
6577
  if (index < 0)
5736
6578
  return;
5737
6579
  this.waiting.splice(index, 1);
5738
6580
  clearTimeout(entry.timer);
5739
- const result = { operationId: entry.message.id, category: code2, executionState: "not_started", rejectedBeforeAdmission: true, retrySafe: true, cancellationConfirmed: true, quarantined: !!this.active && (this.active.timedOut || this.active.interrupted), recovery: "This request was never dispatched. Check browser_runtime_health and current target/authority before submitting a fresh request ID; never replay the blocking operation." };
6581
+ const result = { operationId: entry.message.id, category: code2, executionState: "not_started", rejectedBeforeAdmission: true, retrySafe: true, cancellationConfirmed: true, quarantined: !!this.active && (this.active.timedOut || this.active.interrupted), recovery: recovery ?? "This request was never dispatched. Check browser_runtime_health and current target/authority before submitting a fresh request ID; never replay the blocking operation." };
5740
6582
  entry.send({ type: "result", id: entry.message.id, ok: false, outcome: "not_dispatched", error: { code: code2, message }, result });
5741
6583
  this.recent.push({ scope: entry.message.scope, result });
5742
6584
  if (this.recent.length > 32)
@@ -5793,8 +6635,11 @@ class Relay {
5793
6635
  }
5794
6636
  try {
5795
6637
  entry.guard();
5796
- } catch {
5797
- this.rejectWaiting(entry, "stale_queued_request", "Scope, target identity or document changed while waiting. No action was dispatched.");
6638
+ } catch (error) {
6639
+ if (error instanceof RuntimeFault && error.code === "user_in_control")
6640
+ this.rejectWaiting(entry, "user_in_control", USER_IN_CONTROL_MESSAGE, error.recovery);
6641
+ else
6642
+ this.rejectWaiting(entry, "stale_queued_request", "Scope, target identity or document changed while waiting. No action was dispatched.");
5798
6643
  this.drain();
5799
6644
  return;
5800
6645
  }
@@ -5816,12 +6661,67 @@ class Relay {
5816
6661
  }
5817
6662
  state = "disconnected";
5818
6663
  paused = false;
6664
+ control;
6665
+ watch;
6666
+ takeover;
5819
6667
  constructor(runtime, server, token, previewDirectory, liveEnabled = false) {
5820
6668
  this.runtime = runtime;
5821
6669
  this.server = server;
5822
6670
  this.token = token;
5823
6671
  this.previewDirectory = previewDirectory;
5824
6672
  this.liveEnabled = liveEnabled;
6673
+ this.takeover = new TakeoverInput({
6674
+ getPage: (id) => {
6675
+ try {
6676
+ return this.runtime.engine.page(id);
6677
+ } catch {
6678
+ return;
6679
+ }
6680
+ },
6681
+ idFor: (page) => this.runtime.engine.idFor(page),
6682
+ events: (page) => this.runtime.engine.pageEvents(page),
6683
+ agentActivity: (tab) => {
6684
+ const active = this.active;
6685
+ if (!active || active.settled || active.tabId !== tab || !INPUT_OPERATIONS.has(active.op))
6686
+ return;
6687
+ let timer2;
6688
+ return Promise.race([active.done, new Promise((resolve2) => {
6689
+ timer2 = setTimeout(resolve2, Math.max(0, active.deadlineAt - Date.now()));
6690
+ })]).finally(() => clearTimeout(timer2));
6691
+ },
6692
+ onTabs: (tabs, current2) => {
6693
+ if (this.control)
6694
+ this.controlled(tabs, current2);
6695
+ },
6696
+ sendEvent: (event) => {
6697
+ const socket = this.socket;
6698
+ if (socket?.readyState === WebSocket2.OPEN)
6699
+ socket.send(JSON.stringify(event));
6700
+ },
6701
+ hostMac: process.platform === "darwin"
6702
+ });
6703
+ }
6704
+ setControl(tab) {
6705
+ if (tab !== undefined && (!this.liveEnabled || !isRuntimeTabId(tab)))
6706
+ tab = undefined;
6707
+ if (tab === this.control)
6708
+ return;
6709
+ this.control = tab;
6710
+ if (tab) {
6711
+ this.controlled([tab], tab);
6712
+ this.takeover.activate(tab);
6713
+ } else {
6714
+ this.takeover.deactivate();
6715
+ this.controlled([], undefined);
6716
+ }
6717
+ this.drain();
6718
+ }
6719
+ controlled(tabs, current2) {
6720
+ this.runtime.userControlledTabs = new Set(tabs);
6721
+ for (const entry of [...this.waiting])
6722
+ if (typeof entry.message.args?.tabId === "string" && this.runtime.userControlledTabs.has(entry.message.args.tabId) && entry.message.op !== "release_tab")
6723
+ this.rejectWaiting(entry, "user_in_control", USER_IN_CONTROL_MESSAGE, USER_IN_CONTROL_RECOVERY);
6724
+ this.live?.setControl(current2).catch(() => {});
5825
6725
  }
5826
6726
  async start() {
5827
6727
  while (!this.stopping) {
@@ -5830,6 +6730,8 @@ class Relay {
5830
6730
  continue;
5831
6731
  }
5832
6732
  await this.connect().catch(() => {});
6733
+ this.setControl(undefined);
6734
+ this.watch = undefined;
5833
6735
  await this.live?.stop();
5834
6736
  this.live = undefined;
5835
6737
  await this.runtime.disconnect();
@@ -5859,7 +6761,7 @@ class Relay {
5859
6761
  if (this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
5860
6762
  return;
5861
6763
  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 } } }));
6764
+ socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.21", 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", "live-control.v1"], liveView: { enabled: this.liveEnabled } } }));
5863
6765
  });
5864
6766
  socket.on("message", (bytes, binary) => {
5865
6767
  if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
@@ -5903,11 +6805,24 @@ class Relay {
5903
6805
  if (socket.readyState === WebSocket2.OPEN)
5904
6806
  socket.send(JSON.stringify(event));
5905
6807
  } });
6808
+ if (this.control)
6809
+ this.live.setControl(this.takeover.currentTab ?? this.control).catch(() => {});
6810
+ if (this.watch)
6811
+ this.live.onWatch(this.watch).catch(() => {});
5906
6812
  this.live.setEnabled(this.liveEnabled);
5907
6813
  console.error("Browser MCP connected (dedicated Chrome; local pause available)");
5908
6814
  })().catch(() => socket.close(1011));
5909
6815
  } else if (message.type === "watch") {
5910
- this.live?.onWatch(message).catch(() => {});
6816
+ if (socket === this.socket) {
6817
+ this.watch = message;
6818
+ this.live?.onWatch(message).catch(() => {});
6819
+ }
6820
+ } else if (message.type === "control") {
6821
+ if (socket === this.socket)
6822
+ this.setControl(message.active === true ? message.runtimeTabId : undefined);
6823
+ } else if (message.type === "input") {
6824
+ if (socket === this.socket && this.control)
6825
+ this.takeover.input(message);
5911
6826
  } else if (message.type === "ping")
5912
6827
  socket.send(JSON.stringify({ type: "pong" }));
5913
6828
  else if (message.type === "cancel" && typeof message.id === "string")
@@ -5997,9 +6912,13 @@ class Relay {
5997
6912
  }
5998
6913
  let guard;
5999
6914
  try {
6000
- guard = this.runtime.admissionGuard(message.args, message.scope);
6915
+ guard = this.runtime.admissionGuard(message.args, message.scope, message.op);
6001
6916
  guard();
6002
- } catch {
6917
+ } catch (error) {
6918
+ if (error instanceof RuntimeFault && error.code === "user_in_control") {
6919
+ reject("user_in_control", USER_IN_CONTROL_MESSAGE, { recovery: error.recovery });
6920
+ return;
6921
+ }
6003
6922
  reject("stale_queued_request", "Scope or target is unavailable. No action was dispatched.");
6004
6923
  return;
6005
6924
  }
@@ -6062,6 +6981,8 @@ class Relay {
6062
6981
  const task = (async () => {
6063
6982
  let response;
6064
6983
  try {
6984
+ if (typeof message.args.tabId === "string")
6985
+ await this.takeover.settled(message.args.tabId);
6065
6986
  const beforeDispatch = () => {
6066
6987
  if (active.timedOut || active.interrupted || this.stopping || this.paused || socket !== this.socket || socket.readyState !== WebSocket2.OPEN || Date.now() >= active.deadlineAt)
6067
6988
  throw new RuntimeFault("queue_wait_expired", "Request expired or was interrupted before browser dispatch.", true);
@@ -6184,7 +7105,9 @@ class Relay {
6184
7105
  this.interrupt("queue_paused");
6185
7106
  this.state = "paused";
6186
7107
  this.socket?.close();
7108
+ this.setControl(undefined);
6187
7109
  await this.live?.stop();
7110
+ await this.takeover.stop();
6188
7111
  await this.runtime.disconnect();
6189
7112
  }
6190
7113
  resume() {
@@ -6197,7 +7120,9 @@ class Relay {
6197
7120
  this.stopping = true;
6198
7121
  this.interrupt("queue_shutdown");
6199
7122
  this.socket?.close();
7123
+ this.setControl(undefined);
6200
7124
  await this.live?.stop();
7125
+ await this.takeover.stop();
6201
7126
  await this.runtime.disconnect();
6202
7127
  }
6203
7128
  }
@@ -7355,7 +8280,7 @@ async function startProfile(root, server, profile, options, groupSignal) {
7355
8280
  return;
7356
8281
  } else if (cmd !== "status")
7357
8282
  throw new Error("Invalid command");
7358
- socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.19", protocol: 3 }) + `
8283
+ socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.21", protocol: 3 }) + `
7359
8284
  `);
7360
8285
  })().catch(() => socket.destroy());
7361
8286
  });