@ricsam/browser-mcp 0.3.20 → 0.3.22

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.20";
57
+ var version = "0.3.22";
58
58
 
59
59
  // cli/src/browser/chrome-diagnostics.ts
60
60
  import { constants } from "node:fs";
@@ -2866,7 +2866,85 @@ function observeNavigation(page, input) {
2866
2866
  return { result, dispose: () => finish(false, "navigation_observation_cancelled", "Navigation observation ended.") };
2867
2867
  }
2868
2868
 
2869
+ // cli/src/browser/passkey-guard.ts
2870
+ var MAX_PASSKEY_REQUESTS = 16;
2871
+ function passkeyGuardSource(binding, cancelEvent) {
2872
+ const name = JSON.stringify(binding), cancel = JSON.stringify(cancelEvent);
2873
+ return `(() => {
2874
+ const report = globalThis[${name}];
2875
+ try { delete globalThis[${name}]; } catch {}
2876
+ const C = globalThis.CredentialsContainer;
2877
+ if (typeof report !== "function" || !C || !C.prototype || typeof AbortController !== "function") return;
2878
+ const send = (message) => { try { report(JSON.stringify(message)); } catch {} };
2879
+ const pending = new Map();
2880
+ let seq = 0;
2881
+ addEventListener(${cancel}, () => {
2882
+ for (const controller of pending.values()) controller.abort(new DOMException("The passkey prompt was cancelled.", "AbortError"));
2883
+ });
2884
+ for (const name of ["get", "create"]) {
2885
+ const descriptor = Object.getOwnPropertyDescriptor(C.prototype, name);
2886
+ const original = descriptor && descriptor.value;
2887
+ if (typeof original !== "function") continue;
2888
+ const wrapped = { [name](options) {
2889
+ if (!options || typeof options !== "object" || !options.publicKey || options.mediation === "conditional") return original.apply(this, arguments);
2890
+ const id = ++seq, controller = new AbortController();
2891
+ let request;
2892
+ try {
2893
+ let signal = controller.signal;
2894
+ const own = options.signal;
2895
+ if (own && typeof AbortSignal.any === "function") signal = AbortSignal.any([own, controller.signal]);
2896
+ else if (own) {
2897
+ if (own.aborted) controller.abort(own.reason);
2898
+ else own.addEventListener("abort", () => controller.abort(own.reason), { once: true });
2899
+ }
2900
+ // The page's own options, with the combined signal in place of theirs: members on their
2901
+ // prototype chain included, and their getters still run on them. A signal property
2902
+ // the page made non-configurable cannot be replaced that way; it is shadowed instead.
2903
+ const fixed = Object.getOwnPropertyDescriptor(options, "signal");
2904
+ request = fixed && !fixed.configurable
2905
+ ? Object.create(options, { signal: { value: signal, enumerable: true } })
2906
+ : new Proxy(options, { get: (target, key) => (key === "signal" ? signal : Reflect.get(target, key, target)) });
2907
+ } catch {
2908
+ // Not an AbortSignal: Chrome rejects the request itself, as without this script.
2909
+ return original.apply(this, arguments);
2910
+ }
2911
+ const result = original.call(this, request);
2912
+ pending.set(id, controller);
2913
+ send({ state: "open", id, request: name });
2914
+ const done = () => { if (pending.delete(id)) send({ state: "closed", id }); };
2915
+ Promise.resolve(result).then(done, done);
2916
+ return result;
2917
+ } }[name];
2918
+ try { Object.defineProperty(wrapped, "length", { value: original.length }); } catch {}
2919
+ Object.defineProperty(C.prototype, name, Object.assign({}, descriptor, { value: wrapped }));
2920
+ }
2921
+ })();`;
2922
+ }
2923
+ function parsePasskeyReport(payload) {
2924
+ let value;
2925
+ try {
2926
+ value = JSON.parse(payload);
2927
+ } catch {
2928
+ return null;
2929
+ }
2930
+ if (!value || typeof value !== "object" || Array.isArray(value))
2931
+ return null;
2932
+ const v = value;
2933
+ if (typeof v.id !== "number" || !Number.isSafeInteger(v.id) || v.id < 1)
2934
+ return null;
2935
+ if (v.state === "closed")
2936
+ return { state: "closed", id: v.id };
2937
+ if (v.state === "open" && (v.request === "get" || v.request === "create"))
2938
+ return { state: "open", id: v.id, request: v.request };
2939
+ return null;
2940
+ }
2941
+ var PASSKEY_PROMPT_RECOVERY = `Chrome is showing a passkey prompt for this tab. Chrome draws it outside the page, so screenshots and live view don't show it, and it ignores mouse, keyboard and scroll input to the tab until the prompt is completed or cancelled. Only the user can complete it, at the computer that runs this browser (Touch ID or Windows Hello, a security key, or a phone that scans its QR code); Chrome shows it there only while this tab is the active tab of its window (browser_present {mode: "focus"} makes it so). Hand the tab to the user with browser_takeover so they can complete or cancel it, or cancel it with browser_handle_dialog {dialogId, decision: "dismiss"} when choosing another sign-in method is within the user's authorized task. Reloading or navigating the tab also cancels it.`;
2942
+
2869
2943
  // cli/src/browser/browser-events.ts
2944
+ var PASSKEY_ANNOUNCE_MS = 300;
2945
+ var PASSKEY_CANCEL_MS = 2000;
2946
+ var PASSKEY_FLUSH_MS = 250;
2947
+ var PASSKEY_WORLD = "__browser_mcp_passkey__";
2870
2948
  var CAPACITY = 200;
2871
2949
  var RETENTION_MS = 10 * 60000;
2872
2950
  var MAX_INFLIGHT = 500;
@@ -2891,10 +2969,12 @@ function diagnosticText(text) {
2891
2969
 
2892
2970
  class BrowserPageEvents {
2893
2971
  page;
2972
+ passkeyDetection;
2894
2973
  sequence = 0;
2895
2974
  entries = [];
2896
2975
  listeners = new Set;
2897
2976
  changes = new Set;
2977
+ dialogListeners = new Set;
2898
2978
  requests = new WeakMap;
2899
2979
  inflight = new Map;
2900
2980
  lastNetworkActivity;
@@ -2903,6 +2983,10 @@ class BrowserPageEvents {
2903
2983
  assets = new Map;
2904
2984
  dialog;
2905
2985
  dialogOrigin;
2986
+ passkey;
2987
+ contextFrames = new Map;
2988
+ passkeyBinding = `__bmcpPasskey${crypto.randomUUID().replaceAll("-", "")}`;
2989
+ passkeyCancel = `bmcp-passkey-cancel-${crypto.randomUUID()}`;
2906
2990
  cdp;
2907
2991
  crashListeners = new Set;
2908
2992
  crashed = false;
@@ -2911,8 +2995,9 @@ class BrowserPageEvents {
2911
2995
  currentAction;
2912
2996
  recentAction;
2913
2997
  document = 0;
2914
- constructor(page) {
2998
+ constructor(page, passkeyDetection = true) {
2915
2999
  this.page = page;
3000
+ this.passkeyDetection = passkeyDetection;
2916
3001
  this.ready = page.context().newCDPSession(page).then((cdp) => {
2917
3002
  this.cdp = cdp;
2918
3003
  cdp.on("close", () => {
@@ -2927,8 +3012,10 @@ class BrowserPageEvents {
2927
3012
  this.dialog.event.origin = this.dialogOrigin;
2928
3013
  });
2929
3014
  cdp.on("Page.frameNavigated", ({ frame }) => {
2930
- if (!frame.parentId)
2931
- this.dropPreviousDocumentRequests();
3015
+ if (frame.parentId)
3016
+ return;
3017
+ this.dropPreviousDocumentRequests();
3018
+ this.closePasskey("navigated");
2932
3019
  });
2933
3020
  cdp.on("Page.javascriptDialogClosed", (event) => {
2934
3021
  this.dialogOrigin = undefined;
@@ -2943,10 +3030,13 @@ class BrowserPageEvents {
2943
3030
  actionId: current.event.actionId
2944
3031
  });
2945
3032
  this.dialog = undefined;
3033
+ this.dialogChanged();
2946
3034
  });
2947
3035
  cdp.send("Page.enable").catch(() => {
2948
3036
  return;
2949
3037
  });
3038
+ if (this.passkeyDetection)
3039
+ this.watchPasskeys(cdp);
2950
3040
  }).catch(() => {
2951
3041
  return;
2952
3042
  });
@@ -2995,6 +3085,7 @@ class BrowserPageEvents {
2995
3085
  this.dialog = { value, event };
2996
3086
  for (const listener of this.listeners)
2997
3087
  listener();
3088
+ this.dialogChanged();
2998
3089
  });
2999
3090
  page.on("filechooser", (chooser) => {
3000
3091
  const event = this.record("chooser", { multiple: chooser.isMultiple(), state: "open", document: this.document });
@@ -3022,8 +3113,196 @@ class BrowserPageEvents {
3022
3113
  this.downloads.clear();
3023
3114
  this.inflight.clear();
3024
3115
  this.dialog = undefined;
3116
+ this.closePasskey("closed");
3117
+ this.contextFrames.clear();
3118
+ this.dialogListeners.clear();
3025
3119
  });
3026
3120
  }
3121
+ watchPasskeys(cdp) {
3122
+ cdp.on("Runtime.executionContextCreated", ({ context }) => {
3123
+ const aux = context.auxData;
3124
+ if (aux?.isDefault !== true || typeof aux.frameId !== "string")
3125
+ return;
3126
+ this.contextFrames.set(context.id, aux.frameId);
3127
+ if (this.contextFrames.size > 500)
3128
+ this.contextFrames.delete(this.contextFrames.keys().next().value);
3129
+ });
3130
+ cdp.on("Runtime.executionContextDestroyed", ({ executionContextId }) => {
3131
+ this.contextFrames.delete(executionContextId);
3132
+ const current = this.passkey;
3133
+ if (!current)
3134
+ return;
3135
+ for (const key2 of [...current.requests.keys()])
3136
+ if (key2.startsWith(`${executionContextId}:`))
3137
+ current.requests.delete(key2);
3138
+ if (!current.requests.size)
3139
+ this.closePasskey("settled");
3140
+ });
3141
+ cdp.on("Runtime.executionContextsCleared", () => {
3142
+ this.contextFrames.clear();
3143
+ this.closePasskey("navigated");
3144
+ });
3145
+ cdp.on("Runtime.bindingCalled", ({ name, payload, executionContextId }) => {
3146
+ if (name === this.passkeyBinding)
3147
+ this.passkeyReport(executionContextId, payload);
3148
+ });
3149
+ cdp.send("Runtime.enable").catch(() => {
3150
+ return;
3151
+ });
3152
+ cdp.send("Runtime.addBinding", { name: this.passkeyBinding }).catch(() => {
3153
+ return;
3154
+ });
3155
+ cdp.send("Page.addScriptToEvaluateOnNewDocument", { source: passkeyGuardSource(this.passkeyBinding, this.passkeyCancel), runImmediately: true }).catch(() => {
3156
+ return;
3157
+ });
3158
+ }
3159
+ passkeyReport(contextId, payload) {
3160
+ const report = parsePasskeyReport(payload);
3161
+ if (!report)
3162
+ return;
3163
+ const key2 = `${contextId}:${report.id}`;
3164
+ if (report.state === "closed") {
3165
+ const current2 = this.passkey;
3166
+ if (current2?.requests.delete(key2) && !current2.requests.size)
3167
+ this.closePasskey(current2.cancelledBy ? "cancelled" : "settled");
3168
+ return;
3169
+ }
3170
+ let current = this.passkey;
3171
+ if (!current) {
3172
+ const origin = this.origin(this.page.url());
3173
+ const event = this.record("dialog", { type: "passkey", request: report.request, origin, state: "open" });
3174
+ const opened = { event, request: report.request, origin, requests: new Map, announced: false };
3175
+ opened.timer = setTimeout(() => {
3176
+ if (this.passkey !== opened)
3177
+ return;
3178
+ opened.announced = true;
3179
+ this.dialogChanged();
3180
+ }, PASSKEY_ANNOUNCE_MS);
3181
+ current = this.passkey = opened;
3182
+ }
3183
+ if (current.requests.size < MAX_PASSKEY_REQUESTS)
3184
+ current.requests.set(key2, report.request);
3185
+ }
3186
+ closePasskey(reason) {
3187
+ const current = this.passkey;
3188
+ if (!current)
3189
+ return;
3190
+ this.passkey = undefined;
3191
+ clearTimeout(current.timer);
3192
+ current.event.state = reason === "cancelled" ? "dismissed" : "closed";
3193
+ if (current.cancelledBy)
3194
+ current.event.handledBy = current.cancelledBy;
3195
+ if (reason !== "closed")
3196
+ this.record("dialog", {
3197
+ dialogId: current.event.eventId,
3198
+ type: "passkey",
3199
+ state: current.event.state,
3200
+ reason,
3201
+ ...current.cancelledBy ? { handledBy: current.cancelledBy } : {}
3202
+ });
3203
+ if (current.announced)
3204
+ this.dialogChanged();
3205
+ }
3206
+ passkeyPrompt() {
3207
+ const current = this.passkey;
3208
+ return current ? { dialogId: current.event.eventId, type: "passkey", request: current.request, origin: current.origin, state: "open", openedAt: current.event.timestamp } : null;
3209
+ }
3210
+ async settledPasskeyPrompt(afterInput = false) {
3211
+ if (afterInput)
3212
+ await this.flushPasskeyReports();
3213
+ const current = this.passkey;
3214
+ if (current && !current.announced) {
3215
+ const remaining = PASSKEY_ANNOUNCE_MS - (Date.now() - Date.parse(current.event.timestamp));
3216
+ if (remaining > 0)
3217
+ await this.passkeyClosed(current, remaining + 10);
3218
+ }
3219
+ return this.passkeyPrompt();
3220
+ }
3221
+ async flushPasskeyReports() {
3222
+ const cdp = this.cdp;
3223
+ if (!cdp || !this.passkeyDetection || this.dialog || this.crashed)
3224
+ return;
3225
+ let timer2;
3226
+ await Promise.race([
3227
+ cdp.send("Runtime.evaluate", { expression: "0", silent: true }).catch(() => {
3228
+ return;
3229
+ }),
3230
+ new Promise((resolve2) => {
3231
+ timer2 = setTimeout(resolve2, PASSKEY_FLUSH_MS);
3232
+ })
3233
+ ]);
3234
+ clearTimeout(timer2);
3235
+ }
3236
+ async cancelPasskey(handledBy) {
3237
+ const current = this.passkey, cdp = this.cdp;
3238
+ if (!current || !cdp)
3239
+ return !current;
3240
+ if (this.crashed) {
3241
+ this.closePasskey("crashed");
3242
+ return true;
3243
+ }
3244
+ current.cancelledBy = handledBy;
3245
+ const frames = new Set;
3246
+ for (const key2 of current.requests.keys()) {
3247
+ const frameId = this.contextFrames.get(Number(key2.slice(0, key2.indexOf(":"))));
3248
+ if (frameId)
3249
+ frames.add(frameId);
3250
+ }
3251
+ const expression = `dispatchEvent(new Event(${JSON.stringify(this.passkeyCancel)}))`;
3252
+ let timer2;
3253
+ await Promise.race([
3254
+ Promise.all([...frames].map(async (frameId) => {
3255
+ try {
3256
+ const world = await cdp.send("Page.createIsolatedWorld", { frameId, worldName: PASSKEY_WORLD });
3257
+ await cdp.send("Runtime.evaluate", { contextId: world.executionContextId, expression });
3258
+ } catch {}
3259
+ })),
3260
+ new Promise((resolve2) => {
3261
+ timer2 = setTimeout(resolve2, PASSKEY_CANCEL_MS);
3262
+ })
3263
+ ]);
3264
+ clearTimeout(timer2);
3265
+ const closed = await this.passkeyClosed(current, PASSKEY_CANCEL_MS);
3266
+ if (!closed && this.passkey === current)
3267
+ current.cancelledBy = undefined;
3268
+ return closed;
3269
+ }
3270
+ passkeyClosed(current, ms) {
3271
+ if (this.passkey !== current)
3272
+ return Promise.resolve(true);
3273
+ return new Promise((resolve2) => {
3274
+ const finish = () => {
3275
+ clearTimeout(timer2);
3276
+ this.changes.delete(changed);
3277
+ resolve2(this.passkey !== current);
3278
+ };
3279
+ const changed = () => {
3280
+ if (this.passkey !== current)
3281
+ finish();
3282
+ };
3283
+ const timer2 = setTimeout(finish, ms);
3284
+ this.changes.add(changed);
3285
+ });
3286
+ }
3287
+ onDialog(listener) {
3288
+ this.dialogListeners.add(listener);
3289
+ return () => this.dialogListeners.delete(listener);
3290
+ }
3291
+ dialogDetails() {
3292
+ const value = this.dialog?.value;
3293
+ if (value)
3294
+ return { type: value.type(), message: value.message(), defaultValue: value.defaultValue() };
3295
+ const passkey = this.passkey;
3296
+ return passkey?.announced ? { type: "passkey", message: "", defaultValue: "", request: passkey.request, origin: passkey.origin } : null;
3297
+ }
3298
+ dialogChanged() {
3299
+ const details = this.dialogDetails();
3300
+ for (const listener of [...this.dialogListeners]) {
3301
+ try {
3302
+ listener(details);
3303
+ } catch {}
3304
+ }
3305
+ }
3027
3306
  isMainFrameNavigation(request) {
3028
3307
  try {
3029
3308
  return request.isNavigationRequest() && request.frame() === this.page.mainFrame();
@@ -3065,9 +3344,11 @@ class BrowserPageEvents {
3065
3344
  }
3066
3345
  setCrashed(crashed) {
3067
3346
  this.crashed = crashed;
3068
- if (crashed)
3069
- for (const listener of [...this.crashListeners])
3070
- listener();
3347
+ if (!crashed)
3348
+ return;
3349
+ for (const listener of [...this.crashListeners])
3350
+ listener();
3351
+ this.closePasskey("crashed");
3071
3352
  }
3072
3353
  onCrash(listener) {
3073
3354
  this.crashListeners.add(listener);
@@ -3176,17 +3457,40 @@ class BrowserPageEvents {
3176
3457
  pendingAction() {
3177
3458
  return this.pending ? { actionId: this.pending.actionId, status: "pending" } : null;
3178
3459
  }
3179
- async handleDialog(input) {
3460
+ async handleDialog(input, handledBy = "agent") {
3461
+ const passkey = this.passkey;
3462
+ if (passkey && input.dialogId === passkey.event.eventId) {
3463
+ if (input.decision !== "dismiss" || input.promptText !== undefined)
3464
+ return { handled: false, code: "passkey_requires_user", passkeyPrompt: this.passkeyPrompt(), recovery: PASSKEY_PROMPT_RECOVERY };
3465
+ if (this.dialog)
3466
+ return {
3467
+ handled: false,
3468
+ code: "dialog_blocking",
3469
+ dialog: this.activeDialog(),
3470
+ passkeyPrompt: this.passkeyPrompt(),
3471
+ recovery: "The page also shows a JavaScript dialog. Handle that dialog first, then cancel the passkey prompt."
3472
+ };
3473
+ if (await this.cancelPasskey(handledBy))
3474
+ return { handled: true, dialogId: input.dialogId, decision: "dismiss", type: "passkey" };
3475
+ return {
3476
+ handled: false,
3477
+ code: "passkey_cancel_unconfirmed",
3478
+ passkeyPrompt: this.passkeyPrompt(),
3479
+ recovery: 'The passkey prompt did not close. Reload the tab with browser_history {direction: "reload"} to end it, or hand the tab to the user with browser_takeover.'
3480
+ };
3481
+ }
3180
3482
  const current = this.dialog;
3181
3483
  if (!current || current.event.eventId !== input.dialogId)
3182
3484
  return { handled: false, code: "stale_dialog", dialog: this.activeDialog() };
3183
3485
  if (input.promptText !== undefined && (current.value.type() !== "prompt" || input.decision !== "accept"))
3184
3486
  return { handled: false, code: "prompt_text_requires_accept_prompt" };
3185
- current.event.handledBy = "agent";
3487
+ current.event.handledBy = handledBy;
3186
3488
  await (input.decision === "accept" ? current.value.accept(input.promptText) : current.value.dismiss());
3187
3489
  current.event.state = input.decision === "accept" ? "accepted" : "dismissed";
3188
- if (this.dialog === current)
3490
+ if (this.dialog === current) {
3189
3491
  this.dialog = undefined;
3492
+ this.dialogChanged();
3493
+ }
3190
3494
  const pending = this.pending;
3191
3495
  const outcome = pending ? await this.racePending(pending, 1000) : undefined;
3192
3496
  return {
@@ -3772,13 +4076,14 @@ class BrowserTabState {
3772
4076
  // cli/src/browser/page-state.ts
3773
4077
  var READY_STATES = new Set(["loading", "interactive", "complete"]);
3774
4078
  var VISIBILITY_STATES = new Set(["visible", "hidden", "prerender"]);
3775
- function pageState(capturedAt, network, lastAction, document2) {
4079
+ function pageState(capturedAt, network, lastAction, document2, passkeyPrompt) {
3776
4080
  return {
3777
4081
  capturedAt: new Date(capturedAt).toISOString(),
3778
4082
  ...typeof document2?.readyState === "string" && READY_STATES.has(document2.readyState) ? { readyState: document2.readyState } : {},
3779
4083
  ...typeof document2?.visibilityState === "string" && VISIBILITY_STATES.has(document2.visibilityState) ? { visibilityState: document2.visibilityState } : {},
3780
4084
  ...network,
3781
- lastAction: lastAction ? { operation: lastAction.operation, endedAt: new Date(lastAction.endedAt).toISOString(), msBeforeCapture: Math.max(0, capturedAt - lastAction.endedAt) } : null
4085
+ lastAction: lastAction ? { operation: lastAction.operation, endedAt: new Date(lastAction.endedAt).toISOString(), msBeforeCapture: Math.max(0, capturedAt - lastAction.endedAt) } : null,
4086
+ ...passkeyPrompt ? { passkeyPrompt: { dialogId: passkeyPrompt.dialogId, request: passkeyPrompt.request, openedAt: passkeyPrompt.openedAt } } : {}
3782
4087
  };
3783
4088
  }
3784
4089
  var PAGE_EFFECT_OPERATIONS = new Set([
@@ -3922,7 +4227,10 @@ class RuntimeFault extends Error {
3922
4227
  }
3923
4228
  }
3924
4229
  var OBSERVATION_OPERATIONS = new Set(["list_tabs", "list_downloads", "read_page", "screenshot", "wait_for", "capabilities", "inspect", "events", "diagnostics", "export_page", "webmcp_list", "runtime_health"]);
4230
+ 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.";
4231
+ 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.";
3925
4232
  var messages = {
4233
+ user_in_control: USER_IN_CONTROL_MESSAGE,
3926
4234
  unsupported_target: "Chrome does not expose the interface required by this operation on this target.",
3927
4235
  browser_operation_unsupported: "Chrome reported that this operation or protocol method is not supported on this target.",
3928
4236
  tab_closed: "The tab is closed or detached.",
@@ -3966,6 +4274,18 @@ var MAX_RUN_JS_ARTIFACT_COUNT = 32;
3966
4274
  var REF_ACTION_TIMEOUT_MS = 5000;
3967
4275
  var NAVIGATION_TIMEOUT_MS = 20000;
3968
4276
  var READ_PAGE_TIMEOUT_MS = 1e4;
4277
+ var PASSKEY_BLOCKED_OPERATIONS = new Set([
4278
+ "mouse_click",
4279
+ "move_mouse",
4280
+ "hover",
4281
+ "drag",
4282
+ "scroll",
4283
+ "keyboard",
4284
+ "keyboard_type",
4285
+ "form_input",
4286
+ "select_text",
4287
+ "edit_text"
4288
+ ]);
3969
4289
  var SCREENSHOT_TIMEOUT_MS = 15000;
3970
4290
  var SCREENSHOT_FONT_WAIT_MS = 1000;
3971
4291
  var MAX_FULL_PAGE_HEIGHT = 4000;
@@ -3998,12 +4318,19 @@ function refActionError(error, ref, verb) {
3998
4318
  return new Error(`${message}
3999
4319
  Ref ${ref} comes from the most recent browser_read_page snapshot of this tab. ` + `The ${verb} outcome may be uncertain. ` + BROWSER_RECOVERY, { cause: error });
4000
4320
  }
4321
+ function tabStateView(state) {
4322
+ return {
4323
+ retention: state.retention,
4324
+ ...state.viewport ? { viewport: { width: state.viewport.width, height: state.viewport.height } } : {}
4325
+ };
4326
+ }
4001
4327
 
4002
4328
  class BrowserRuntime {
4003
4329
  context;
4004
4330
  downloadsPath;
4005
4331
  downloadHandler;
4006
4332
  guardPage;
4333
+ passkeyDetection;
4007
4334
  screenshots = new Map;
4008
4335
  ids = new WeakMap;
4009
4336
  pages = new Map;
@@ -4018,11 +4345,12 @@ class BrowserRuntime {
4018
4345
  lastActions = new Map;
4019
4346
  tabPresentation = new WeakMap;
4020
4347
  savingDownloads = new Set;
4021
- constructor(context, downloadsPath, uploadsPath = `${downloadsPath}.uploads`, downloadHandler, guardPage) {
4348
+ constructor(context, downloadsPath, uploadsPath = `${downloadsPath}.uploads`, downloadHandler, guardPage, passkeyDetection = true) {
4022
4349
  this.context = context;
4023
4350
  this.downloadsPath = downloadsPath;
4024
4351
  this.downloadHandler = downloadHandler;
4025
4352
  this.guardPage = guardPage;
4353
+ this.passkeyDetection = passkeyDetection;
4026
4354
  this.uploads = new BrowserUploadStore(uploadsPath, (target2) => {
4027
4355
  target2.dispose().catch(() => {
4028
4356
  return;
@@ -4041,7 +4369,7 @@ class BrowserRuntime {
4041
4369
  const id = crypto.randomUUID();
4042
4370
  this.ids.set(page, id);
4043
4371
  this.pages.set(id, page);
4044
- this.events.set(page, new BrowserPageEvents(page));
4372
+ this.events.set(page, new BrowserPageEvents(page, this.passkeyDetection));
4045
4373
  page.on("framenavigated", () => {
4046
4374
  const tabId = this.ids.get(page);
4047
4375
  if (tabId)
@@ -4237,8 +4565,9 @@ class BrowserRuntime {
4237
4565
  await this.initialization.get(page);
4238
4566
  const tabId = this.ids.get(page);
4239
4567
  const state = (await this.tabState.resolve(page)).state;
4568
+ const info = ({ windowId: windowId2, title: title2 }) => ({ tabId, windowId: windowId2, title: title2, url: page.url(), ...tabStateView(state) });
4240
4569
  if (this.events.get(page)?.activeDialog()) {
4241
- return { ...state, tabId, ...this.tabPresentation.get(page) ?? { windowId: "unknown", title: "" }, url: page.url() };
4570
+ return info(this.tabPresentation.get(page) ?? { windowId: "unknown", title: "" });
4242
4571
  }
4243
4572
  let windowId = "unknown";
4244
4573
  let title = "";
@@ -4254,7 +4583,7 @@ class BrowserRuntime {
4254
4583
  });
4255
4584
  }
4256
4585
  this.tabPresentation.set(page, { windowId, title });
4257
- return { ...state, tabId, windowId, title, url: page.url() };
4586
+ return info({ windowId, title });
4258
4587
  }
4259
4588
  async listTabs() {
4260
4589
  await Promise.all(this.initialization.values());
@@ -4301,8 +4630,8 @@ class BrowserRuntime {
4301
4630
  this.lastActions.set(tabId, { operation, endedAt: Date.now() });
4302
4631
  }
4303
4632
  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);
4633
+ const events = this.events.get(page), network = events.networkState(capturedAt), lastAction = this.lastActions.get(tabId), prompt = events.passkeyPrompt();
4634
+ return (document2) => pageState(capturedAt, network, lastAction, document2, prompt);
4306
4635
  }
4307
4636
  async observationSession(page, read) {
4308
4637
  const events = this.events.get(page);
@@ -4377,6 +4706,14 @@ class BrowserRuntime {
4377
4706
  dialog: events.activeDialog(),
4378
4707
  recovery: "Handle this dialog explicitly within the user's authorized task."
4379
4708
  };
4709
+ const passkeyPrompt = events?.passkeyPrompt();
4710
+ if (passkeyPrompt && PASSKEY_BLOCKED_OPERATIONS.has(action))
4711
+ return {
4712
+ tabId: input.tabId,
4713
+ dispatch: { status: "not_dispatched", code: "passkey_prompt_open" },
4714
+ passkeyPrompt,
4715
+ recovery: PASSKEY_PROMPT_RECOVERY
4716
+ };
4380
4717
  const observation = parseObservation(input.observe);
4381
4718
  const previous = this.observations.get(String(input.tabId));
4382
4719
  const previousTabs = new Set(this.pages.keys());
@@ -4401,6 +4738,9 @@ class BrowserRuntime {
4401
4738
  recordAction();
4402
4739
  throw error;
4403
4740
  }
4741
+ const promptAfter = action !== "events" && page && !page.isClosed() ? await events?.settledPasskeyPrompt(PASSKEY_BLOCKED_OPERATIONS.has(action)) : undefined;
4742
+ if (promptAfter && result && typeof result === "object" && !("passkeyPrompt" in result))
4743
+ result = { ...result, passkeyPrompt: promptAfter, passkeyRecovery: PASSKEY_PROMPT_RECOVERY };
4404
4744
  const notDispatched = result.invoked === false || result.dispatched === false || result.selected === false || result.handled === false;
4405
4745
  if (!notDispatched && result.dispatch?.status !== "not_dispatched")
4406
4746
  recordAction();
@@ -4485,6 +4825,19 @@ class BrowserRuntime {
4485
4825
  if (result?.matched === false || result?.expected?.matched === false || result?.dispatch && result.dispatch.status !== "completed" || result?.code || result?.observation?.available === false)
4486
4826
  return { results, stoppedAt: index, remaining: steps.length - index - 1, code: "batch_step_stopped", retrySafe: false };
4487
4827
  } catch (error) {
4828
+ if (error instanceof RuntimeFault && error.beforeDispatch) {
4829
+ if (index === 0)
4830
+ throw error;
4831
+ const refused = failureFor(error, step.action, execution.operationId ?? crypto.randomUUID(), "batch_step");
4832
+ return {
4833
+ results: [...results, { index, action: step.action, status: "not_dispatched", ...refused.result, code: refused.error.code }],
4834
+ stoppedAt: index,
4835
+ remaining: steps.length - index,
4836
+ code: "batch_step_stopped",
4837
+ retrySafe: false,
4838
+ recovery: refused.result.recovery
4839
+ };
4840
+ }
4488
4841
  const failure = failureFor(error, step.action, execution.operationId ?? crypto.randomUUID(), "batch_step");
4489
4842
  return {
4490
4843
  results: [...results, { index, action: step.action, status: "unknown", ...failure.result, code: failure.error.code }],
@@ -4608,6 +4961,7 @@ class BrowserRuntime {
4608
4961
  tabId,
4609
4962
  ...await this.events.get(page).waitQuery(input),
4610
4963
  dialog: this.events.get(page).activeDialog(),
4964
+ passkeyPrompt: this.events.get(page).passkeyPrompt(),
4611
4965
  pendingAction: this.events.get(page).pendingAction()
4612
4966
  };
4613
4967
  case "diagnostics":
@@ -4675,7 +5029,7 @@ class BrowserRuntime {
4675
5029
  retention: input.mode === "handoff" ? "user" : input.mode === "temporary" ? "temporary" : "retained",
4676
5030
  ...input.mode === "handoff" ? { ownerSessionId: undefined, ...input.preserveViewport === true ? {} : { viewport: undefined } } : {}
4677
5031
  });
4678
- return { changed: true, ...next };
5032
+ return { changed: true, tabId, ...tabStateView(next) };
4679
5033
  }
4680
5034
  case "clipboard":
4681
5035
  return { tabId, ...await clipboard(page, input), scope: "system" };
@@ -5231,12 +5585,13 @@ class NativeRuntime {
5231
5585
  operations = new Map;
5232
5586
  hooks = Promise.resolve();
5233
5587
  browserId;
5234
- constructor(context, instanceId, directory, serverOrigin) {
5588
+ userControlledTabs = new Set;
5589
+ constructor(context, instanceId, directory, serverOrigin, passkeyDetection = true) {
5235
5590
  this.context = context;
5236
5591
  this.instanceId = instanceId;
5237
5592
  this.serverOrigin = serverOrigin;
5238
5593
  installCancellation(context);
5239
- this.engine = new BrowserRuntime(context, directory, `${directory}.uploads`, (download, page, downloadId) => this.download(download, page, downloadId), async (page) => this.assertPageAvailable(page));
5594
+ this.engine = new BrowserRuntime(context, directory, `${directory}.uploads`, (download, page, downloadId) => this.download(download, page, downloadId), async (page) => this.assertPageAvailable(page), passkeyDetection);
5240
5595
  context.on("page", (page) => {
5241
5596
  this.track(page);
5242
5597
  });
@@ -5470,7 +5825,11 @@ class NativeRuntime {
5470
5825
  this.operations.get(operationId)?.abort(new Error("Blocked target closed by approved recovery"));
5471
5826
  return { closed: true };
5472
5827
  }
5473
- admissionGuard(args, scope) {
5828
+ assertAgentControl(tabId, op) {
5829
+ if (typeof tabId === "string" && this.userControlledTabs.has(tabId) && op !== "release_tab" && op !== "session_end")
5830
+ throw new RuntimeFault("user_in_control", USER_IN_CONTROL_RECOVERY, true);
5831
+ }
5832
+ admissionGuard(args, scope, op) {
5474
5833
  const epoch = this.scopeEpoch(scope), connectionEpoch = this.connectionEpoch;
5475
5834
  const tabId = typeof args.tabId === "string" ? args.tabId : undefined;
5476
5835
  const page = tabId ? this.engine.page(tabId) : undefined;
@@ -5478,6 +5837,7 @@ class NativeRuntime {
5478
5837
  return (checkDocument = true) => {
5479
5838
  if (this.scopeEpoch(scope) !== epoch || this.connectionEpoch !== connectionEpoch)
5480
5839
  throw new RuntimeFault("scope_rejected", "Scope or connection changed while waiting; submit a fresh authorized request.", true);
5840
+ this.assertAgentControl(tabId, op);
5481
5841
  if (tabId) {
5482
5842
  let current2;
5483
5843
  try {
@@ -5528,6 +5888,7 @@ class NativeRuntime {
5528
5888
  await this.hooks;
5529
5889
  this.validateScope(scope);
5530
5890
  if (typeof args.tabId === "string") {
5891
+ this.assertAgentControl(args.tabId, op);
5531
5892
  const page = await this.claimPage(args.tabId, scope);
5532
5893
  await this.track(page);
5533
5894
  this.assertPageAvailable(page);
@@ -5669,6 +6030,58 @@ function sanitizeLiveEvent(value) {
5669
6030
  return null;
5670
6031
  }
5671
6032
  }
6033
+ var LIVE_MODIFIERS = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
6034
+ var NAVIGATIONS = new Set(["reload", "back", "forward"]);
6035
+ var MAX_LIVE_INPUT_TEXT = 200;
6036
+ var isLiveRelease = (event) => event.kind === "release" || (event.kind === "mouse" || event.kind === "key") && event.type === "up";
6037
+ var MAX_LIVE_DIALOG_TEXT = 500;
6038
+ var MAX_CONTROL_TABS = 8;
6039
+ var modifierMask = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 15;
6040
+ var NAMED_KEY = /^[A-Za-z][A-Za-z0-9]{1,31}$/;
6041
+ var KEY_CODE = /^[A-Za-z0-9]{0,32}$/;
6042
+ var CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/;
6043
+ var LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
6044
+ var cleanText = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max && !CONTROL.test(value) && !LONE_SURROGATE.test(value);
6045
+ var keyValue = (value) => typeof value === "string" && (NAMED_KEY.test(value) || value.length <= 4 && cleanText(value, 4) && !/[\t\n\r]/.test(value));
6046
+ var button = (value) => value === "left" || value === "middle" || value === "right";
6047
+ function sanitizeLiveInput(value) {
6048
+ if (!value || typeof value !== "object" || Array.isArray(value))
6049
+ return null;
6050
+ const e = value;
6051
+ const mac = e.mac === true;
6052
+ switch (e.kind) {
6053
+ case "mouse":
6054
+ 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)
6055
+ return null;
6056
+ 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 };
6057
+ case "wheel":
6058
+ if (!coordinate(e.x) || !coordinate(e.y) || !coordinate(e.deltaX) || !coordinate(e.deltaY) || !modifierMask(e.modifiers))
6059
+ return null;
6060
+ return { kind: "wheel", x: e.x, y: e.y, deltaX: e.deltaX, deltaY: e.deltaY, modifiers: e.modifiers, mac };
6061
+ case "key":
6062
+ if (e.type !== "down" && e.type !== "up" || !keyValue(e.key) || typeof e.code !== "string" || !KEY_CODE.test(e.code) || !modifierMask(e.modifiers))
6063
+ return null;
6064
+ return { kind: "key", type: e.type, key: e.key, code: e.code, modifiers: e.modifiers, repeat: e.repeat === true, mac };
6065
+ case "text":
6066
+ return cleanText(e.text, MAX_LIVE_INPUT_TEXT) ? { kind: "text", text: e.text } : null;
6067
+ case "release":
6068
+ return { kind: "release" };
6069
+ case "dialog":
6070
+ if (typeof e.accept !== "boolean")
6071
+ return null;
6072
+ if (e.text === undefined)
6073
+ return { kind: "dialog", accept: e.accept };
6074
+ 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;
6075
+ case "navigate":
6076
+ return NAVIGATIONS.has(e.action) ? { kind: "navigate", action: e.action } : null;
6077
+ case "show":
6078
+ return { kind: "show" };
6079
+ default:
6080
+ return null;
6081
+ }
6082
+ }
6083
+ var DIALOG_TYPES = new Set(["alert", "confirm", "prompt", "beforeunload", "passkey"]);
6084
+ var MAX_LIVE_DIALOG_MESSAGE = 500;
5672
6085
 
5673
6086
  // cli/src/live/wire.ts
5674
6087
  function mediaURL(server) {
@@ -5722,6 +6135,7 @@ function eventMessage(value, navSeq) {
5722
6135
 
5723
6136
  // cli/src/live/producer.ts
5724
6137
  var STAGE_TIMEOUT_MS = 5000;
6138
+ var MAX_ATTACH_RETRIES = 4;
5725
6139
 
5726
6140
  class CaptureTimeout extends Error {
5727
6141
  stage;
@@ -5747,6 +6161,7 @@ class NativeLiveProducer {
5747
6161
  active = false;
5748
6162
  closed = false;
5749
6163
  tab;
6164
+ controlTab;
5750
6165
  generation = 0;
5751
6166
  serial = Promise.resolve();
5752
6167
  socket;
@@ -5755,8 +6170,9 @@ class NativeLiveProducer {
5755
6170
  unlisten;
5756
6171
  frameSeq = 0;
5757
6172
  navSeq = 0;
5758
- lastFrame = 0;
5759
6173
  eventWindow = { start: 0, count: 0 };
6174
+ retries = 0;
6175
+ retryTab;
5760
6176
  constructor(options) {
5761
6177
  this.options = options;
5762
6178
  const url = new URL(options.mediaUrl);
@@ -5776,17 +6192,27 @@ class NativeLiveProducer {
5776
6192
  if (this.closed)
5777
6193
  return this.serial;
5778
6194
  this.active = frame.active === true;
5779
- if (isRuntimeTabId(frame.followTabId))
6195
+ if (isRuntimeTabId(frame.followTabId) && (!this.controlTab || frame.followTabId === this.controlTab))
5780
6196
  this.tab = frame.followTabId;
5781
6197
  return this.schedule();
5782
6198
  }
5783
6199
  followTab(runtimeTabId) {
5784
- if (this.closed || !isRuntimeTabId(runtimeTabId) || runtimeTabId === this.tab)
6200
+ if (this.closed || !isRuntimeTabId(runtimeTabId) || runtimeTabId === this.tab || this.controlTab && runtimeTabId !== this.controlTab)
5785
6201
  return this.serial;
5786
6202
  this.tab = runtimeTabId;
5787
6203
  this.navSeq++;
5788
6204
  return this.schedule();
5789
6205
  }
6206
+ setControl(runtimeTabId) {
6207
+ if (this.closed)
6208
+ return this.serial;
6209
+ this.controlTab = isRuntimeTabId(runtimeTabId) ? runtimeTabId : undefined;
6210
+ if (!this.controlTab || this.controlTab === this.tab)
6211
+ return this.serial;
6212
+ this.tab = this.controlTab;
6213
+ this.navSeq++;
6214
+ return this.schedule();
6215
+ }
5790
6216
  emitCursor(event) {
5791
6217
  const ws = this.socket;
5792
6218
  if (!this.enabled || !this.active || this.closed || !ws || ws.readyState !== WebSocket.OPEN || ws.bufferedAmount > 512 * 1024)
@@ -5824,6 +6250,23 @@ class NativeLiveProducer {
5824
6250
  });
5825
6251
  return this.serial;
5826
6252
  }
6253
+ retry(generation, detail) {
6254
+ if (generation !== this.generation)
6255
+ return;
6256
+ if (this.retryTab !== this.tab) {
6257
+ this.retryTab = this.tab;
6258
+ this.retries = 0;
6259
+ }
6260
+ if (this.retries >= MAX_ATTACH_RETRIES) {
6261
+ this.state("blocked", detail);
6262
+ return;
6263
+ }
6264
+ const timer2 = setTimeout(() => {
6265
+ if (generation === this.generation)
6266
+ this.schedule();
6267
+ }, 250 * ++this.retries);
6268
+ timer2.unref?.();
6269
+ }
5827
6270
  async teardown() {
5828
6271
  clearInterval(this.heartbeat);
5829
6272
  this.heartbeat = undefined;
@@ -5873,10 +6316,15 @@ class NativeLiveProducer {
5873
6316
  this.state("blocked", error instanceof CaptureTimeout ? `${error.stage}_timeout` : "page_unavailable");
5874
6317
  return;
5875
6318
  }
5876
- if (generation !== this.generation || initialNav !== this.navSeq) {
6319
+ if (generation !== this.generation) {
5877
6320
  await this.teardown();
5878
6321
  return;
5879
6322
  }
6323
+ if (initialNav !== this.navSeq) {
6324
+ await this.teardown();
6325
+ this.retry(generation, "page_unavailable");
6326
+ return;
6327
+ }
5880
6328
  if (!authorized) {
5881
6329
  await this.teardown();
5882
6330
  this.state("blocked", "page_unavailable");
@@ -5915,7 +6363,7 @@ class NativeLiveProducer {
5915
6363
  }
5916
6364
  ws.on("error", () => {});
5917
6365
  ws.once("close", () => {
5918
- if (generation === this.generation && !this.closed) {
6366
+ if (generation === this.generation && !this.closed && this.socket === ws) {
5919
6367
  this.active = false;
5920
6368
  this.schedule();
5921
6369
  }
@@ -5945,33 +6393,29 @@ class NativeLiveProducer {
5945
6393
  return;
5946
6394
  }
5947
6395
  let checkingFrame = false;
5948
- cdp.on("Page.screencastFrame", (event) => {
5949
- cdp.send("Page.screencastFrameAck", { sessionId: event.sessionId }).catch(() => {});
5950
- if (generation !== this.generation || !this.enabled || !this.active || ws.readyState !== WebSocket.OPEN)
6396
+ let lastFrame = 0;
6397
+ let deferred;
6398
+ const forward = (event, nav) => {
6399
+ if (generation !== this.generation || nav !== this.navSeq || !this.enabled || !this.active || ws.readyState !== WebSocket.OPEN)
5951
6400
  return;
5952
- let allowed = false;
5953
- try {
5954
- allowed = this.options.getPage(tab) === page;
5955
- } catch {}
5956
- if (!allowed) {
5957
- this.active = false;
5958
- this.schedule();
6401
+ const wait = Math.max(lastFrame + 100 - Date.now(), checkingFrame || ws.bufferedAmount > 512 * 1024 ? 100 : 0);
6402
+ if (wait > 0) {
6403
+ clearTimeout(deferred);
6404
+ deferred = setTimeout(() => {
6405
+ deferred = undefined;
6406
+ forward(event, nav);
6407
+ }, wait);
6408
+ deferred.unref?.();
5959
6409
  return;
5960
6410
  }
5961
- const now = Date.now();
5962
- if (now - this.lastFrame < 100 || ws.bufferedAmount > 512 * 1024 || event.data.length > Math.ceil(MAX_LIVE_FRAME_BYTES / 3) * 4)
5963
- return;
5964
- if (checkingFrame)
5965
- return;
5966
- this.lastFrame = now;
6411
+ lastFrame = Date.now();
5967
6412
  checkingFrame = true;
5968
- const nav = this.navSeq;
5969
6413
  (async () => {
5970
6414
  try {
5971
- const allowed2 = await bounded2("frame_authorize", this.options.authorizePage(page));
6415
+ const allowed = await bounded2("frame_authorize", this.options.authorizePage(page));
5972
6416
  if (generation !== this.generation || nav !== this.navSeq || this.closed || !this.enabled || !this.active || this.socket !== ws || ws.readyState !== WebSocket.OPEN)
5973
6417
  return;
5974
- if (!allowed2 || this.options.getPage(tab) !== page) {
6418
+ if (!allowed || this.options.getPage(tab) !== page) {
5975
6419
  this.active = false;
5976
6420
  this.schedule();
5977
6421
  return;
@@ -5982,10 +6426,38 @@ class NativeLiveProducer {
5982
6426
  checkingFrame = false;
5983
6427
  }
5984
6428
  })();
6429
+ };
6430
+ cdp.on("Page.screencastFrame", (event) => {
6431
+ cdp.send("Page.screencastFrameAck", { sessionId: event.sessionId }).catch(() => {});
6432
+ if (generation !== this.generation || !this.enabled || !this.active || ws.readyState !== WebSocket.OPEN)
6433
+ return;
6434
+ let allowed = false;
6435
+ try {
6436
+ allowed = this.options.getPage(tab) === page;
6437
+ } catch {}
6438
+ if (!allowed) {
6439
+ this.active = false;
6440
+ this.schedule();
6441
+ return;
6442
+ }
6443
+ if (event.data.length > Math.ceil(MAX_LIVE_FRAME_BYTES / 3) * 4)
6444
+ return;
6445
+ forward(event, this.navSeq);
5985
6446
  });
5986
6447
  const startNav = this.navSeq;
5987
- if (!await bounded2("authorize", this.options.authorizePage(page)) || generation !== this.generation || startNav !== this.navSeq) {
6448
+ const stillAllowed = await bounded2("authorize", this.options.authorizePage(page));
6449
+ if (generation !== this.generation) {
6450
+ await this.teardown();
6451
+ return;
6452
+ }
6453
+ if (startNav !== this.navSeq) {
6454
+ await this.teardown();
6455
+ this.retry(generation, "capture_unavailable");
6456
+ return;
6457
+ }
6458
+ if (!stillAllowed) {
5988
6459
  await this.teardown();
6460
+ this.state("blocked", "page_unavailable");
5989
6461
  return;
5990
6462
  }
5991
6463
  await bounded2("start_screencast", cdp.send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: 1600, maxHeight: 1000, everyNthFrame: 1 }));
@@ -5998,18 +6470,405 @@ class NativeLiveProducer {
5998
6470
  ws.send('{"type":"ping"}');
5999
6471
  }, 20000);
6000
6472
  this.heartbeat.unref?.();
6473
+ this.retries = 0;
6001
6474
  this.state("streaming");
6002
6475
  } catch (error) {
6003
6476
  await this.teardown();
6004
- if (generation === this.generation)
6005
- this.state("blocked", error instanceof CaptureTimeout ? `${error.stage}_timeout` : "capture_unavailable");
6477
+ if (generation !== this.generation)
6478
+ return;
6479
+ const detail = error instanceof CaptureTimeout ? `${error.stage}_timeout` : "capture_unavailable";
6480
+ if (!page.isClosed())
6481
+ this.retry(generation, detail);
6482
+ else
6483
+ this.state("blocked", detail);
6484
+ }
6485
+ }
6486
+ }
6487
+
6488
+ // cli/src/live/takeover.ts
6489
+ var MAX_QUEUE = 128;
6490
+ var STEP_TIMEOUT_MS = 3000;
6491
+ var SHOW_INTERVAL_MS = 1000;
6492
+ var DIALOG_TYPES2 = new Set(["alert", "confirm", "prompt", "beforeunload", "passkey"]);
6493
+ var MODIFIERS = Object.entries(LIVE_MODIFIERS);
6494
+ async function bounded3(work, ms) {
6495
+ let timer2;
6496
+ await Promise.race([work.catch(() => {}), new Promise((resolve2) => {
6497
+ timer2 = setTimeout(resolve2, ms);
6498
+ })]);
6499
+ clearTimeout(timer2);
6500
+ }
6501
+
6502
+ class TakeoverInput {
6503
+ options;
6504
+ group;
6505
+ queue = [];
6506
+ pumping;
6507
+ releases = new Map;
6508
+ constructor(options) {
6509
+ this.options = options;
6510
+ }
6511
+ get currentTab() {
6512
+ return this.group?.session?.tabId;
6513
+ }
6514
+ activate(root) {
6515
+ if (!isRuntimeTabId(root) || this.group?.root === root)
6516
+ return;
6517
+ this.deactivate();
6518
+ const page = this.options.getPage(root);
6519
+ if (!page || page.isClosed()) {
6520
+ this.lost(root);
6521
+ return;
6522
+ }
6523
+ const group = { root, tabs: [root], ended: false, cleanup: [] };
6524
+ this.group = group;
6525
+ this.join(group, root, page);
6526
+ this.focus(group, root, page);
6527
+ }
6528
+ deactivate() {
6529
+ const group = this.group;
6530
+ if (group)
6531
+ this.end(group);
6532
+ }
6533
+ input(frame) {
6534
+ const session = this.group?.session;
6535
+ if (!session || frame.runtimeTabId !== session.tabId)
6536
+ return;
6537
+ const event = sanitizeLiveInput(frame.event);
6538
+ if (!event)
6539
+ return;
6540
+ if (event.kind === "dialog") {
6541
+ this.answerDialog(this.options.events(session.page), event).catch(() => {});
6542
+ return;
6543
+ }
6544
+ const last = this.queue[this.queue.length - 1];
6545
+ if (event.kind === "mouse" && event.type === "move" && last?.session === session && last.event.kind === "mouse" && last.event.type === "move") {
6546
+ last.event = event;
6547
+ return;
6548
+ }
6549
+ const essential = isLiveRelease(event);
6550
+ if (this.queue.length >= (essential ? MAX_QUEUE * 2 : MAX_QUEUE))
6551
+ return;
6552
+ this.push({ session, event });
6553
+ }
6554
+ async settled(tabId) {
6555
+ const release = this.releases.get(tabId);
6556
+ if (release)
6557
+ await bounded3(release, STEP_TIMEOUT_MS);
6558
+ }
6559
+ async stop() {
6560
+ this.deactivate();
6561
+ const pumping = this.pumping;
6562
+ if (pumping)
6563
+ await bounded3(pumping, STEP_TIMEOUT_MS);
6564
+ }
6565
+ join(group, tabId, page) {
6566
+ const onClose = () => this.left(group, tabId);
6567
+ const onPopup = (popup) => {
6568
+ this.opened(group, popup);
6569
+ };
6570
+ page.on("close", onClose);
6571
+ page.on("popup", onPopup);
6572
+ group.cleanup.push(() => {
6573
+ page.off("close", onClose);
6574
+ page.off("popup", onPopup);
6575
+ });
6576
+ }
6577
+ async opened(group, popup) {
6578
+ let id;
6579
+ try {
6580
+ id = await this.options.idFor(popup);
6581
+ } catch {
6582
+ return;
6583
+ }
6584
+ if (group.ended || this.group !== group || !isRuntimeTabId(id) || popup.isClosed() || group.tabs.includes(id) || group.tabs.length >= MAX_CONTROL_TABS)
6585
+ return;
6586
+ group.tabs.push(id);
6587
+ this.join(group, id, popup);
6588
+ this.focus(group, id, popup);
6589
+ }
6590
+ left(group, tabId) {
6591
+ if (group.ended || this.group !== group)
6592
+ return;
6593
+ if (tabId === group.root) {
6594
+ this.end(group);
6595
+ this.lost(tabId);
6596
+ return;
6597
+ }
6598
+ group.tabs = group.tabs.filter((id) => id !== tabId);
6599
+ if (group.session?.tabId !== tabId) {
6600
+ this.report(group);
6601
+ return;
6602
+ }
6603
+ for (const id of [...group.tabs].reverse()) {
6604
+ const page = this.options.getPage(id);
6605
+ if (page && !page.isClosed()) {
6606
+ this.focus(group, id, page);
6607
+ return;
6608
+ }
6609
+ }
6610
+ this.end(group);
6611
+ this.lost(group.root);
6612
+ }
6613
+ focus(group, tabId, page) {
6614
+ if (group.session)
6615
+ this.close(group.session);
6616
+ const session = { tabId, page, keys: new Map, buttons: new Set, pointer: { x: Number.NaN, y: Number.NaN }, ended: false, cleanup: [], shownAt: 0 };
6617
+ group.session = session;
6618
+ const gate = this.options.agentActivity(tabId);
6619
+ if (gate) {
6620
+ session.gate = gate;
6621
+ gate.then(() => {
6622
+ if (session.gate !== gate)
6623
+ return;
6624
+ session.gate = undefined;
6625
+ if (group.session === session && !session.ended)
6626
+ this.report(group);
6627
+ });
6628
+ }
6629
+ const events = this.options.events(page);
6630
+ if (events)
6631
+ session.cleanup.push(events.onDialog((dialog) => {
6632
+ if (group.session === session && !session.ended)
6633
+ this.reportDialog(tabId, dialog);
6634
+ }));
6635
+ this.report(group);
6636
+ const open2 = events?.dialogDetails();
6637
+ if (open2)
6638
+ this.reportDialog(tabId, open2);
6639
+ }
6640
+ close(session) {
6641
+ session.ended = true;
6642
+ for (const done of session.cleanup.splice(0)) {
6643
+ try {
6644
+ done();
6645
+ } catch {}
6646
+ }
6647
+ this.queue = this.queue.filter((item) => item.session !== session);
6648
+ let finish;
6649
+ const released = new Promise((resolve2) => {
6650
+ finish = resolve2;
6651
+ });
6652
+ this.releases.set(session.tabId, released);
6653
+ released.then(() => {
6654
+ if (this.releases.get(session.tabId) === released)
6655
+ this.releases.delete(session.tabId);
6656
+ });
6657
+ this.push({ session, event: { kind: "release_all" }, done: finish });
6658
+ }
6659
+ end(group) {
6660
+ group.ended = true;
6661
+ if (this.group === group)
6662
+ this.group = undefined;
6663
+ for (const done of group.cleanup.splice(0)) {
6664
+ try {
6665
+ done();
6666
+ } catch {}
6667
+ }
6668
+ if (group.session && !group.session.ended)
6669
+ this.close(group.session);
6670
+ }
6671
+ report(group) {
6672
+ const session = group.session;
6673
+ if (group.ended || this.group !== group || !session)
6674
+ return;
6675
+ this.options.onTabs([...group.tabs], session.tabId);
6676
+ this.options.sendEvent({ type: "event", event: "live_control_state", runtimeTabId: group.root, tabs: [...group.tabs], current: session.tabId, busy: !!session.gate });
6677
+ }
6678
+ lost(tabId) {
6679
+ this.options.sendEvent({ type: "event", event: "live_control_lost", runtimeTabId: tabId, reason: "tab_closed" });
6680
+ }
6681
+ reportDialog(tabId, dialog) {
6682
+ const type = dialog?.type;
6683
+ let shown = null;
6684
+ if (dialog && type === "passkey")
6685
+ shown = { type, message: "", request: dialog.request === "create" ? "create" : "get", ...dialog.origin ? { origin: dialog.origin } : {} };
6686
+ else if (dialog && type && DIALOG_TYPES2.has(type))
6687
+ shown = { type, message: dialog.message.slice(0, MAX_LIVE_DIALOG_MESSAGE), ...type === "prompt" ? { defaultValue: dialog.defaultValue.slice(0, MAX_LIVE_DIALOG_TEXT) } : {} };
6688
+ this.options.sendEvent({ type: "event", event: "live_dialog", runtimeTabId: tabId, dialog: shown });
6689
+ }
6690
+ push(item) {
6691
+ this.queue.push(item);
6692
+ if (this.pumping)
6693
+ return;
6694
+ this.pumping = (async () => {
6695
+ while (this.queue.length) {
6696
+ const item2 = this.queue.shift();
6697
+ const { session, event } = item2;
6698
+ try {
6699
+ if (event.kind !== "release_all") {
6700
+ if (session.ended)
6701
+ continue;
6702
+ if (session.gate)
6703
+ await session.gate;
6704
+ if (session.ended)
6705
+ continue;
6706
+ }
6707
+ await bounded3(this.dispatch(session, event), STEP_TIMEOUT_MS);
6708
+ } finally {
6709
+ item2.done?.();
6710
+ }
6711
+ }
6712
+ })().finally(() => {
6713
+ this.pumping = undefined;
6714
+ });
6715
+ }
6716
+ keyName(key2, mac) {
6717
+ if (mac === this.options.hostMac)
6718
+ return key2;
6719
+ return key2 === "Meta" ? "Control" : key2 === "Control" ? "Meta" : key2;
6720
+ }
6721
+ modifierMask(mask, mac) {
6722
+ if (mac === this.options.hostMac)
6723
+ return mask;
6724
+ const { Control, Meta } = LIVE_MODIFIERS;
6725
+ return mask & ~(Control | Meta) | (mask & Control ? Meta : 0) | (mask & Meta ? Control : 0);
6726
+ }
6727
+ async dispatch(session, event) {
6728
+ const { page } = session;
6729
+ if (page.isClosed())
6730
+ return;
6731
+ if (event.kind === "release_all" || event.kind === "release") {
6732
+ await this.releaseAll(session);
6733
+ return;
6734
+ }
6735
+ const events = this.options.events(page);
6736
+ if (event.kind === "dialog") {
6737
+ await this.answerDialog(events, event);
6738
+ return;
6739
+ }
6740
+ if (events?.activeDialog())
6741
+ return;
6742
+ if (event.kind === "show") {
6743
+ if (events?.passkeyPrompt())
6744
+ await this.show(session, events);
6745
+ return;
6746
+ }
6747
+ if (event.kind === "navigate") {
6748
+ await this.navigate(page, event.action);
6749
+ return;
6750
+ }
6751
+ if (events?.passkeyPrompt())
6752
+ return;
6753
+ switch (event.kind) {
6754
+ case "mouse": {
6755
+ await this.syncModifiers(session, this.modifierMask(event.modifiers, event.mac));
6756
+ if (event.type === "move" || session.pointer.x !== event.x || session.pointer.y !== event.y) {
6757
+ session.pointer = { x: event.x, y: event.y };
6758
+ await page.mouse.move(event.x, event.y);
6759
+ }
6760
+ if (event.type === "down") {
6761
+ session.buttons.add(event.button);
6762
+ await page.mouse.down({ button: event.button, clickCount: event.clickCount });
6763
+ } else if (event.type === "up" && session.buttons.delete(event.button)) {
6764
+ await page.mouse.up({ button: event.button, clickCount: event.clickCount });
6765
+ }
6766
+ return;
6767
+ }
6768
+ case "wheel":
6769
+ await this.syncModifiers(session, this.modifierMask(event.modifiers, event.mac));
6770
+ if (session.pointer.x !== event.x || session.pointer.y !== event.y) {
6771
+ session.pointer = { x: event.x, y: event.y };
6772
+ await page.mouse.move(event.x, event.y);
6773
+ }
6774
+ await page.mouse.wheel(event.deltaX, event.deltaY);
6775
+ return;
6776
+ case "key": {
6777
+ const key2 = this.keyName(event.key, event.mac);
6778
+ const id = event.code || key2;
6779
+ if (event.type === "up") {
6780
+ const pressed = session.keys.get(id);
6781
+ if (pressed === undefined)
6782
+ return;
6783
+ session.keys.delete(id);
6784
+ await page.keyboard.up(pressed);
6785
+ return;
6786
+ }
6787
+ session.keys.set(id, key2);
6788
+ try {
6789
+ await page.keyboard.down(key2);
6790
+ } catch (error) {
6791
+ session.keys.delete(id);
6792
+ if (error instanceof Error && /Unknown key/.test(error.message) && [...key2].length === 1)
6793
+ await page.keyboard.insertText(key2);
6794
+ }
6795
+ return;
6796
+ }
6797
+ case "text":
6798
+ await page.keyboard.insertText(event.text);
6799
+ return;
6800
+ }
6801
+ }
6802
+ async syncModifiers(session, mask) {
6803
+ for (const [name, bit] of MODIFIERS) {
6804
+ const held = [...session.keys].filter(([, key2]) => key2 === name);
6805
+ if (mask & bit) {
6806
+ if (held.length)
6807
+ continue;
6808
+ session.keys.set(`modifier:${name}`, name);
6809
+ await session.page.keyboard.down(name);
6810
+ } else if (held.length) {
6811
+ for (const [id] of held)
6812
+ session.keys.delete(id);
6813
+ await session.page.keyboard.up(name);
6814
+ }
6006
6815
  }
6007
6816
  }
6817
+ async navigate(page, action) {
6818
+ const options = { waitUntil: "commit", timeout: STEP_TIMEOUT_MS };
6819
+ await (action === "back" ? page.goBack(options) : action === "forward" ? page.goForward(options) : page.reload(options)).catch(() => {});
6820
+ }
6821
+ async show(session, events) {
6822
+ const now = Date.now();
6823
+ if (now - session.shownAt < SHOW_INTERVAL_MS)
6824
+ return;
6825
+ session.shownAt = now;
6826
+ const { page } = session;
6827
+ const shared = events.session();
6828
+ const cdp = shared ?? await page.context().newCDPSession(page).catch(() => {
6829
+ return;
6830
+ });
6831
+ try {
6832
+ if (cdp) {
6833
+ const { windowId } = await cdp.send("Browser.getWindowForTarget");
6834
+ const { bounds } = await cdp.send("Browser.getWindowBounds", { windowId });
6835
+ if (bounds.windowState === "minimized")
6836
+ await cdp.send("Browser.setWindowBounds", { windowId, bounds: { windowState: "normal" } });
6837
+ }
6838
+ } catch {} finally {
6839
+ if (cdp && cdp !== shared)
6840
+ await cdp.detach().catch(() => {});
6841
+ }
6842
+ await page.bringToFront().catch(() => {});
6843
+ }
6844
+ async releaseAll(session) {
6845
+ const buttons = [...session.buttons], keys = new Set(session.keys.values());
6846
+ session.buttons.clear();
6847
+ session.keys.clear();
6848
+ for (const button2 of buttons)
6849
+ await session.page.mouse.up({ button: button2 }).catch(() => {});
6850
+ for (const key2 of keys)
6851
+ await session.page.keyboard.up(key2).catch(() => {});
6852
+ }
6853
+ async answerDialog(events, event) {
6854
+ if (!events)
6855
+ return;
6856
+ const dialog = events.activeDialog(), details = events.dialogDetails();
6857
+ if (dialog && details) {
6858
+ const prompt = details.type === "prompt" && event.accept && event.text !== undefined;
6859
+ await events.handleDialog({ dialogId: dialog.dialogId, decision: event.accept ? "accept" : "dismiss", ...prompt ? { promptText: event.text } : {} }, "viewer");
6860
+ return;
6861
+ }
6862
+ const passkey = events.passkeyPrompt();
6863
+ if (passkey && !event.accept)
6864
+ await events.handleDialog({ dialogId: passkey.dialogId, decision: "dismiss" }, "viewer");
6865
+ }
6008
6866
  }
6009
6867
 
6010
6868
  // cli/src/runtime/relay.ts
6011
6869
  var sameScope3 = (a, b) => a.browserId === b.browserId && a.tokenId === b.tokenId && a.sessionKey === b.sessionKey && a.instanceId === b.instanceId;
6012
6870
  var QUEUE_LIMITS = Object.freeze({ maxWaiting: 16, maxWaitingPerScope: 8, maxWaitMs: 5000 });
6871
+ var INPUT_OPERATIONS = new Set(["mouse_click", "move_mouse", "hover", "drag", "scroll", "keyboard", "keyboard_type", "form_input", "select_text", "edit_text", "batch"]);
6013
6872
  var LIMIT = 2 * 1024 * 1024;
6014
6873
  function wireResult(op, value) {
6015
6874
  if (!value || typeof value !== "object")
@@ -6072,13 +6931,13 @@ class Relay {
6072
6931
  this.active?.interrupt();
6073
6932
  this.flushWaiting(code2, "The runtime was interrupted. Waiting work was never dispatched; reconnect and re-observe before submitting a fresh request.");
6074
6933
  }
6075
- rejectWaiting(entry, code2, message) {
6934
+ rejectWaiting(entry, code2, message, recovery) {
6076
6935
  const index = this.waiting.indexOf(entry);
6077
6936
  if (index < 0)
6078
6937
  return;
6079
6938
  this.waiting.splice(index, 1);
6080
6939
  clearTimeout(entry.timer);
6081
- 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." };
6940
+ 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." };
6082
6941
  entry.send({ type: "result", id: entry.message.id, ok: false, outcome: "not_dispatched", error: { code: code2, message }, result });
6083
6942
  this.recent.push({ scope: entry.message.scope, result });
6084
6943
  if (this.recent.length > 32)
@@ -6135,8 +6994,11 @@ class Relay {
6135
6994
  }
6136
6995
  try {
6137
6996
  entry.guard();
6138
- } catch {
6139
- this.rejectWaiting(entry, "stale_queued_request", "Scope, target identity or document changed while waiting. No action was dispatched.");
6997
+ } catch (error) {
6998
+ if (error instanceof RuntimeFault && error.code === "user_in_control")
6999
+ this.rejectWaiting(entry, "user_in_control", USER_IN_CONTROL_MESSAGE, error.recovery);
7000
+ else
7001
+ this.rejectWaiting(entry, "stale_queued_request", "Scope, target identity or document changed while waiting. No action was dispatched.");
6140
7002
  this.drain();
6141
7003
  return;
6142
7004
  }
@@ -6158,12 +7020,67 @@ class Relay {
6158
7020
  }
6159
7021
  state = "disconnected";
6160
7022
  paused = false;
7023
+ control;
7024
+ watch;
7025
+ takeover;
6161
7026
  constructor(runtime, server, token, previewDirectory, liveEnabled = false) {
6162
7027
  this.runtime = runtime;
6163
7028
  this.server = server;
6164
7029
  this.token = token;
6165
7030
  this.previewDirectory = previewDirectory;
6166
7031
  this.liveEnabled = liveEnabled;
7032
+ this.takeover = new TakeoverInput({
7033
+ getPage: (id) => {
7034
+ try {
7035
+ return this.runtime.engine.page(id);
7036
+ } catch {
7037
+ return;
7038
+ }
7039
+ },
7040
+ idFor: (page) => this.runtime.engine.idFor(page),
7041
+ events: (page) => this.runtime.engine.pageEvents(page),
7042
+ agentActivity: (tab) => {
7043
+ const active = this.active;
7044
+ if (!active || active.settled || active.tabId !== tab || !INPUT_OPERATIONS.has(active.op))
7045
+ return;
7046
+ let timer2;
7047
+ return Promise.race([active.done, new Promise((resolve2) => {
7048
+ timer2 = setTimeout(resolve2, Math.max(0, active.deadlineAt - Date.now()));
7049
+ })]).finally(() => clearTimeout(timer2));
7050
+ },
7051
+ onTabs: (tabs, current2) => {
7052
+ if (this.control)
7053
+ this.controlled(tabs, current2);
7054
+ },
7055
+ sendEvent: (event) => {
7056
+ const socket = this.socket;
7057
+ if (socket?.readyState === WebSocket2.OPEN)
7058
+ socket.send(JSON.stringify(event));
7059
+ },
7060
+ hostMac: process.platform === "darwin"
7061
+ });
7062
+ }
7063
+ setControl(tab) {
7064
+ if (tab !== undefined && (!this.liveEnabled || !isRuntimeTabId(tab)))
7065
+ tab = undefined;
7066
+ if (tab === this.control)
7067
+ return;
7068
+ this.control = tab;
7069
+ if (tab) {
7070
+ this.controlled([tab], tab);
7071
+ this.takeover.activate(tab);
7072
+ } else {
7073
+ this.takeover.deactivate();
7074
+ this.controlled([], undefined);
7075
+ }
7076
+ this.drain();
7077
+ }
7078
+ controlled(tabs, current2) {
7079
+ this.runtime.userControlledTabs = new Set(tabs);
7080
+ for (const entry of [...this.waiting])
7081
+ if (typeof entry.message.args?.tabId === "string" && this.runtime.userControlledTabs.has(entry.message.args.tabId) && entry.message.op !== "release_tab")
7082
+ this.rejectWaiting(entry, "user_in_control", USER_IN_CONTROL_MESSAGE, USER_IN_CONTROL_RECOVERY);
7083
+ this.live?.setControl(current2).catch(() => {});
6167
7084
  }
6168
7085
  async start() {
6169
7086
  while (!this.stopping) {
@@ -6172,6 +7089,8 @@ class Relay {
6172
7089
  continue;
6173
7090
  }
6174
7091
  await this.connect().catch(() => {});
7092
+ this.setControl(undefined);
7093
+ this.watch = undefined;
6175
7094
  await this.live?.stop();
6176
7095
  this.live = undefined;
6177
7096
  await this.runtime.disconnect();
@@ -6201,7 +7120,7 @@ class Relay {
6201
7120
  if (this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
6202
7121
  return;
6203
7122
  this.state = "authenticating";
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 } } }));
7123
+ socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.22", 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", "live-navigate.v1"], liveView: { enabled: this.liveEnabled } } }));
6205
7124
  });
6206
7125
  socket.on("message", (bytes, binary) => {
6207
7126
  if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
@@ -6245,11 +7164,24 @@ class Relay {
6245
7164
  if (socket.readyState === WebSocket2.OPEN)
6246
7165
  socket.send(JSON.stringify(event));
6247
7166
  } });
7167
+ if (this.control)
7168
+ this.live.setControl(this.takeover.currentTab ?? this.control).catch(() => {});
7169
+ if (this.watch)
7170
+ this.live.onWatch(this.watch).catch(() => {});
6248
7171
  this.live.setEnabled(this.liveEnabled);
6249
7172
  console.error("Browser MCP connected (dedicated Chrome; local pause available)");
6250
7173
  })().catch(() => socket.close(1011));
6251
7174
  } else if (message.type === "watch") {
6252
- this.live?.onWatch(message).catch(() => {});
7175
+ if (socket === this.socket) {
7176
+ this.watch = message;
7177
+ this.live?.onWatch(message).catch(() => {});
7178
+ }
7179
+ } else if (message.type === "control") {
7180
+ if (socket === this.socket)
7181
+ this.setControl(message.active === true ? message.runtimeTabId : undefined);
7182
+ } else if (message.type === "input") {
7183
+ if (socket === this.socket && this.control)
7184
+ this.takeover.input(message);
6253
7185
  } else if (message.type === "ping")
6254
7186
  socket.send(JSON.stringify({ type: "pong" }));
6255
7187
  else if (message.type === "cancel" && typeof message.id === "string")
@@ -6339,9 +7271,13 @@ class Relay {
6339
7271
  }
6340
7272
  let guard;
6341
7273
  try {
6342
- guard = this.runtime.admissionGuard(message.args, message.scope);
7274
+ guard = this.runtime.admissionGuard(message.args, message.scope, message.op);
6343
7275
  guard();
6344
- } catch {
7276
+ } catch (error) {
7277
+ if (error instanceof RuntimeFault && error.code === "user_in_control") {
7278
+ reject("user_in_control", USER_IN_CONTROL_MESSAGE, { recovery: error.recovery });
7279
+ return;
7280
+ }
6345
7281
  reject("stale_queued_request", "Scope or target is unavailable. No action was dispatched.");
6346
7282
  return;
6347
7283
  }
@@ -6404,6 +7340,8 @@ class Relay {
6404
7340
  const task = (async () => {
6405
7341
  let response;
6406
7342
  try {
7343
+ if (typeof message.args.tabId === "string")
7344
+ await this.takeover.settled(message.args.tabId);
6407
7345
  const beforeDispatch = () => {
6408
7346
  if (active.timedOut || active.interrupted || this.stopping || this.paused || socket !== this.socket || socket.readyState !== WebSocket2.OPEN || Date.now() >= active.deadlineAt)
6409
7347
  throw new RuntimeFault("queue_wait_expired", "Request expired or was interrupted before browser dispatch.", true);
@@ -6526,7 +7464,9 @@ class Relay {
6526
7464
  this.interrupt("queue_paused");
6527
7465
  this.state = "paused";
6528
7466
  this.socket?.close();
7467
+ this.setControl(undefined);
6529
7468
  await this.live?.stop();
7469
+ await this.takeover.stop();
6530
7470
  await this.runtime.disconnect();
6531
7471
  }
6532
7472
  resume() {
@@ -6539,7 +7479,9 @@ class Relay {
6539
7479
  this.stopping = true;
6540
7480
  this.interrupt("queue_shutdown");
6541
7481
  this.socket?.close();
7482
+ this.setControl(undefined);
6542
7483
  await this.live?.stop();
7484
+ await this.takeover.stop();
6543
7485
  await this.runtime.disconnect();
6544
7486
  }
6545
7487
  }
@@ -7499,6 +8441,8 @@ function parse2(args) {
7499
8441
  options.ephemeral = true;
7500
8442
  else if (key2 === "--live-view")
7501
8443
  options.liveView = true;
8444
+ else if (key2 === "--no-passkey-detection")
8445
+ options.passkeyDetection = false;
7502
8446
  else if (key2 === "--profile" || key2 === "--server" || key2 === "--chrome-path") {
7503
8447
  if (!args[i + 1] || args[i + 1].startsWith("--"))
7504
8448
  throw new Error(`Missing ${key2} value`);
@@ -7515,10 +8459,10 @@ function parse2(args) {
7515
8459
  async function runBrowser(args) {
7516
8460
  const command = args.shift() ?? "help";
7517
8461
  if (command === "help" || command === "--help" || args.includes("--help")) {
7518
- console.log(`browser-mcp browser start [--server https://browser-mcp.click] [--profile work] [--profile personal ...] [--ephemeral] [--chrome-path /path/to/chrome] [--live-view]
8462
+ console.log(`browser-mcp browser start [--server https://browser-mcp.click] [--profile work] [--profile personal ...] [--ephemeral] [--chrome-path /path/to/chrome] [--live-view] [--no-passkey-detection]
7519
8463
  browser-mcp browser status|pause|resume|stop|recover [--profile work]
7520
8464
  Repeat --profile to launch multiple isolated browsers. Without --profile, uses default. Approve each new profile separately. Local controls target one profile; Ctrl-C closes all browsers started by this command. A launch/runtime failure stops the group.
7521
- Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI closes Chrome; no detach/reattach. recover removes only verified stale lock/socket artifacts, never profile data. Live view requires local --live-view opt-in (screenshots may expose secrets). Windows browser host is not yet supported.`);
8465
+ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI closes Chrome; no detach/reattach. recover removes only verified stale lock/socket artifacts, never profile data. Live view requires local --live-view opt-in (screenshots may expose secrets). --no-passkey-detection keeps the passkey prompt script out of pages. Windows browser host is not yet supported.`);
7522
8466
  return;
7523
8467
  }
7524
8468
  if (!["start", "status", "pause", "resume", "stop", "recover"].includes(command))
@@ -7657,7 +8601,7 @@ async function startProfile(root, server, profile, options, groupSignal) {
7657
8601
  abort.signal.throwIfAborted();
7658
8602
  runtimeStage = "runtime-setup";
7659
8603
  const previews = path11.join(session.runPath, "previews");
7660
- runtime = new NativeRuntime(session.context, session.instanceId, previews, server);
8604
+ runtime = new NativeRuntime(session.context, session.instanceId, previews, server, options.passkeyDetection !== false);
7661
8605
  runtime.plugins.push(await createDataPlugin(runtime, { directory: path11.join(session.runPath, "data"), downloads: session.downloads, serverOrigin: server, allowInsecureLoopback: new URL(server).protocol === "http:", onSourceCleanupFailure: () => {
7662
8606
  console.error("Download cleanup could not be verified; closing the owned browser to bound private spool retention. No website action was replayed.");
7663
8607
  requestStop("owner-close");
@@ -7697,7 +8641,7 @@ async function startProfile(root, server, profile, options, groupSignal) {
7697
8641
  return;
7698
8642
  } else if (cmd !== "status")
7699
8643
  throw new Error("Invalid command");
7700
- socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.20", protocol: 3 }) + `
8644
+ socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.22", protocol: 3 }) + `
7701
8645
  `);
7702
8646
  })().catch(() => socket.destroy());
7703
8647
  });