@ricsam/browser-mcp 0.3.24 → 0.3.26

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.
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  CLI_VERSION
3
- } from "./chunk-4cgmscyh.js";
3
+ } from "./chunk-42sbfmcv.js";
4
4
  import {
5
5
  LIMITS,
6
6
  sameScope,
@@ -1689,6 +1689,7 @@ var CAPABILITIES = {
1689
1689
  liveView: "live-view.v1",
1690
1690
  liveControl: "live-control.v1",
1691
1691
  liveNavigate: "live-navigate.v1",
1692
+ liveFit: "live-fit.v1",
1692
1693
  secrets: "secrets.v1",
1693
1694
  forwarding: "forwarding.v1",
1694
1695
  runtimeQueue: "runtime-queue.v1",
@@ -1698,7 +1699,8 @@ var CAPABILITIES = {
1698
1699
  runJsRead: "run-js-read.v1",
1699
1700
  actionTargets: "action-targets.v1",
1700
1701
  screenshotDelivery: "screenshot-delivery.v1",
1701
- waitConditions: "wait-conditions.v1"
1702
+ waitConditions: "wait-conditions.v1",
1703
+ httpAuth: "http-auth-dialogs.v1"
1702
1704
  };
1703
1705
 
1704
1706
  // cli/src/runtime/failures.ts
@@ -1765,6 +1767,8 @@ var messages = {
1765
1767
  target_not_actionable: "A pointer could not reach the ref's element where a person would: result.reason says why (covered, hidden, disabled, outside_viewport, no_pointer_input or unstable), and result.cover and result.layer name what covers it (untrusted page data).",
1766
1768
  not_a_form_field: "The ref is not a form field whose value can be set: it takes typed text, as a code editor's input does, or no text at all (result.kind). Nothing was changed.",
1767
1769
  check_state_unchanged: "A click where the checkbox or radio button's widget is drawn did not change its state.",
1770
+ page_busy: "The click's input reached the page, which had not finished handling it within five seconds: a script of the page was still running. Whether the click took effect is unknown.",
1771
+ navigation_loading: "The tab is loading another page that has not arrived yet (result.pendingNavigation, untrusted). Until it does, Chrome answers no read of the page the tab still shows, nor actions on its elements. Nothing was dispatched.",
1768
1772
  option_not_found: "No option of the select matches the request; result.options lists its first options (untrusted page data). Nothing was changed.",
1769
1773
  invalid_browser_input: "The request does not fit this operation or its target element. Nothing was changed.",
1770
1774
  pointer_unknown: "This tab has no known pointer position to click at. Nothing was clicked.",
@@ -1785,7 +1789,15 @@ var messages = {
1785
1789
  target_not_found: "No visible element of the main document matched the target within five seconds, so nothing was dispatched. result.candidates lists similar visible elements with their refs, if any (untrusted page data).",
1786
1790
  target_ambiguous: "The target matched more than one visible element, so nothing was dispatched. result.candidates lists them with their refs (untrusted page data).",
1787
1791
  target_invalid: "The target cannot be resolved in this page: its selector does not parse, or it reaches into an iframe. Nothing was dispatched.",
1788
- target_unresolved: "The page did not answer while the target was being resolved, so nothing was dispatched."
1792
+ target_unresolved: "The page did not answer while the target was being resolved, so nothing was dispatched.",
1793
+ http_auth_credentials_required: "This HTTP sign-in needs a username and password: accept it with vaultId, names and expectedOrigin, dismiss it, or let the user sign in in live view. Nothing was sent to the site.",
1794
+ http_auth_origin_mismatch: "The HTTP sign-in is for another origin than expectedOrigin (result.httpAuth.origin, result.expectedOrigin). Nothing was sent to the site.",
1795
+ http_auth_frame_refused: "An iframe of another origin than the page asks for these credentials (result.httpAuth.origin, result.pageOrigin): vault values answer only sign-ins of the page's own origin. Nothing was sent to the site.",
1796
+ http_auth_logging_enabled: "The runtime runs with Playwright's protocol logging enabled (the DEBUG environment variable), which would print the password. Nothing was sent to the site.",
1797
+ http_auth_secret_unavailable: "The vault values for this sign-in are not available to this session: the vaultId or a name is unknown, or the vault expired or ended with its source document. Nothing was sent to the site.",
1798
+ http_auth_closed: "The HTTP sign-in closed while its vault values were read. Nothing was sent to the site.",
1799
+ http_auth_username_unsupported: "The username contains a colon, which HTTP Basic authentication cannot send. Nothing was sent to the site.",
1800
+ http_auth_answer_pending: "This HTTP sign-in is being answered already. Nothing more was sent to the site."
1789
1801
  };
1790
1802
  var faultMessage = (code2) => messages[code2] ?? "Runtime operation rejected.";
1791
1803
  var READ_SCRIPT_RECOVERY = "Review the submitted script and the exception details (untrusted page data). The script was declared intent read, so its failure is reported like an observation's: correct it and run it again. If it did change the page after all, observe the page before repeating it.";
@@ -2162,6 +2174,51 @@ function parseNavigationExpectation(value) {
2162
2174
  };
2163
2175
  }
2164
2176
 
2177
+ // shared/http-auth.ts
2178
+ var HTTP_AUTH_DIALOG = "http_auth";
2179
+ var MAX_HTTP_AUTH_REALM = 200;
2180
+ var MAX_HTTP_AUTH_USERNAME = 256;
2181
+ var MAX_HTTP_AUTH_PASSWORD = 512;
2182
+ var HTTP_AUTH_ARGUMENTS = ["vaultId", "names", "expectedOrigin"];
2183
+ var VAULT_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
2184
+ function signsInWithVault(input) {
2185
+ return !!input && HTTP_AUTH_ARGUMENTS.some((key2) => input[key2] !== undefined && input[key2] !== null);
2186
+ }
2187
+ function exactOrigin(value) {
2188
+ if (typeof value !== "string" || value.length > 255)
2189
+ return;
2190
+ try {
2191
+ const url = new URL(value);
2192
+ return (url.protocol === "https:" || url.protocol === "http:") && url.origin === value ? value : undefined;
2193
+ } catch {
2194
+ return;
2195
+ }
2196
+ }
2197
+ function httpAuthInputProblem(input) {
2198
+ if (!signsInWithVault(input))
2199
+ return;
2200
+ const missing = HTTP_AUTH_ARGUMENTS.filter((key2) => input[key2] === undefined || input[key2] === null);
2201
+ if (missing.length)
2202
+ return `An HTTP sign-in takes vaultId, names and expectedOrigin together: ${missing.join(" and ")} ${missing.length === 1 ? "is" : "are"} missing.`;
2203
+ if (input.decision !== "accept")
2204
+ return 'vaultId, names and expectedOrigin sign in with decision "accept". To cancel an HTTP sign-in, use decision "dismiss" without them.';
2205
+ if (input.promptText !== undefined)
2206
+ return "promptText answers a JavaScript prompt. An HTTP sign-in takes vaultId, names and expectedOrigin instead.";
2207
+ if (typeof input.vaultId !== "string" || !input.vaultId.trim() || input.vaultId.length > 128)
2208
+ return "vaultId must be the vaultId of a local secret vault, from browser_capture_secrets or browser_list_secrets.";
2209
+ const names = input.names;
2210
+ if (!names || typeof names !== "object" || Array.isArray(names) || Object.keys(names).some((key2) => key2 !== "username" && key2 !== "password"))
2211
+ return 'names must be {"username": NAME, "password": NAME}: the names of the vault values that hold the username and the password, never the values.';
2212
+ for (const key2 of ["username", "password"]) {
2213
+ const name = names[key2];
2214
+ if (typeof name !== "string" || !VAULT_NAME.test(name))
2215
+ return `names.${key2} must be the name of a value in the vault, such as ${key2 === "username" ? "SITE_USERNAME" : "SITE_PASSWORD"}, never the value itself.`;
2216
+ }
2217
+ if (!exactOrigin(input.expectedOrigin))
2218
+ return "expectedOrigin must be the exact origin the user authorized these credentials for, such as https://example.com: scheme, host and port only.";
2219
+ return;
2220
+ }
2221
+
2165
2222
  // cli/src/browser/browser-control-input.ts
2166
2223
  var observedActions = new Set([
2167
2224
  "navigate",
@@ -2287,6 +2344,9 @@ function validateControlInput(action, input) {
2287
2344
  choice("decision", ["accept", "dismiss"]);
2288
2345
  if (input.promptText !== undefined && (typeof input.promptText !== "string" || input.promptText.length > 1e4))
2289
2346
  throw new Error("Invalid promptText.");
2347
+ const problem = httpAuthInputProblem(input);
2348
+ if (problem)
2349
+ throw new Error(problem);
2290
2350
  }
2291
2351
  if (action === "events" || action === "diagnostics") {
2292
2352
  integer("timeoutMs", 500, 25000);
@@ -2374,7 +2434,7 @@ var browserInputFields = {
2374
2434
  select_text: { required: ["tabId"], optional: ["ref", "target", "start", "end", "text", "occurrence"] },
2375
2435
  edit_text: { required: ["tabId", "mode", "text"], optional: ["ref", "target"] },
2376
2436
  events: { required: ["tabId"], optional: ["kind", "after", "limit", "timeoutMs"] },
2377
- handle_dialog: { required: ["tabId", "dialogId", "decision"], optional: ["promptText"] },
2437
+ handle_dialog: { required: ["tabId", "dialogId", "decision"], optional: ["promptText", "vaultId", "names", "expectedOrigin"] },
2378
2438
  diagnostics: { required: ["tabId"], optional: ["kind", "after", "limit", "level", "since", "failedOnly"] },
2379
2439
  history: { required: ["tabId", "direction"], optional: [] },
2380
2440
  present: { required: ["tabId", "mode"], optional: [] },
@@ -2989,6 +3049,19 @@ function snapshotLine(line) {
2989
3049
  const { key: key2, ref, role } = snapshotLineParts(line);
2990
3050
  return { key: key2, ref, role };
2991
3051
  }
3052
+ var BOX = / \[box=(-?\d+),(-?\d+),(-?\d+),(-?\d+)\]$/;
3053
+ function moveLineBox(line, origin) {
3054
+ const indent = line.length - line.trimStart().length;
3055
+ if (!line.startsWith("- ", indent))
3056
+ return line;
3057
+ const { key: key2 } = snapshotLineParts(line);
3058
+ const box = BOX.exec(key2);
3059
+ if (!box)
3060
+ return line;
3061
+ const start = indent + 2 + box.index;
3062
+ const moved = origin ? ` [box=${Math.round(Number(box[1]) + origin.x)},${Math.round(Number(box[2]) + origin.y)},${box[3]},${box[4]}]` : "";
3063
+ return line.slice(0, start) + moved + line.slice(indent + 2 + key2.length);
3064
+ }
2992
3065
 
2993
3066
  // cli/src/browser/password-safe-snapshot.ts
2994
3067
  var requirePlaywright2 = createRequire2(import.meta.url);
@@ -2996,6 +3069,48 @@ var SUPPORTED_PLAYWRIGHT_VERSION2 = "1.63.0";
2996
3069
  var DEFAULT_TIMEOUT_MS = 1e4;
2997
3070
  var UNAVAILABLE = "Password-safe browser snapshots are unavailable with this Playwright runtime. Update r5d-browser before retrying.";
2998
3071
  var MAX_MATCH_DETAILS = 1000;
3072
+ var PAGE = { x: 0, y: 0 };
3073
+ var SCALE_TOLERANCE = 1.5;
3074
+ var FRAME_ELEMENT_PROGRESS = { race: (promise) => Promise.race(Array.isArray(promise) ? promise : [promise]) };
3075
+ var finite = (value, keys) => !!value && typeof value === "object" && keys.every((key2) => Number.isFinite(value[key2]));
3076
+ var isGeometry = (value) => finite(value, ["x", "y", "width", "height"]) && finite(value.parentViewport, ["width", "height"]);
3077
+ var drawnAtScale = (size, viewport) => size.width === undefined || size.height === undefined || Math.abs(viewport.width - size.width) <= SCALE_TOLERANCE && Math.abs(viewport.height - size.height) <= SCALE_TOLERANCE;
3078
+ function iframeGeometryInUtilityWorld(context) {
3079
+ const iframe = Array.isArray(context) ? context[1] : context?.elements?.[0];
3080
+ const view = iframe?.ownerDocument?.defaultView;
3081
+ if (!iframe || !iframe.isConnected || !view)
3082
+ return "detached";
3083
+ const zoom = iframe.currentCSSZoom;
3084
+ if (typeof zoom === "number" && zoom !== 1)
3085
+ return "transformed";
3086
+ const translation = (transform) => {
3087
+ if (transform === "none")
3088
+ return true;
3089
+ try {
3090
+ const matrix = new view.DOMMatrixReadOnly(transform);
3091
+ return matrix.is2D && matrix.a === 1 && matrix.b === 0 && matrix.c === 0 && matrix.d === 1;
3092
+ } catch {
3093
+ return false;
3094
+ }
3095
+ };
3096
+ for (let node = iframe;node; node = node.assignedSlot ?? node.parentElement ?? (node.parentNode?.host ?? null)) {
3097
+ const style2 = view.getComputedStyle(node);
3098
+ if (!translation(style2.transform) || style2.scale !== "none" || style2.rotate !== "none" || style2.translate.trim().split(/\s+/).length > 2 || (style2.offsetPath || "none") !== "none")
3099
+ return "transformed";
3100
+ }
3101
+ const box = iframe.getBoundingClientRect();
3102
+ const style = view.getComputedStyle(iframe);
3103
+ const px = (value) => Number.parseFloat(value) || 0;
3104
+ const left = px(style.borderLeftWidth) + px(style.paddingLeft);
3105
+ const top = px(style.borderTopWidth) + px(style.paddingTop);
3106
+ return {
3107
+ x: box.left + left,
3108
+ y: box.top + top,
3109
+ width: box.width - left - px(style.borderRightWidth) - px(style.paddingRight),
3110
+ height: box.height - top - px(style.borderBottomWidth) - px(style.paddingBottom),
3111
+ parentViewport: { width: view.innerWidth, height: view.innerHeight }
3112
+ };
3113
+ }
2999
3114
  function isServerFrame(value) {
3000
3115
  return !!value && typeof value.selectors?.callOnSelector === "function";
3001
3116
  }
@@ -3306,7 +3421,8 @@ function captureInUtilityWorld({ elements, injected }, options) {
3306
3421
  matches,
3307
3422
  matchCount: visible.length,
3308
3423
  ...eligible.length > visible.length ? { hiddenMatchCount: eligible.length - visible.length } : {},
3309
- ...options.scope && !options.matchesOnly ? { scopeMatchCount: 1 } : {}
3424
+ ...options.scope && !options.matchesOnly ? { scopeMatchCount: 1 } : {},
3425
+ ...options.boxes || options.query ? { viewport: { width: window.innerWidth, height: window.innerHeight } } : {}
3310
3426
  };
3311
3427
  } finally {
3312
3428
  Object.defineProperty(Element.prototype, "getAttribute", attributeDescriptor);
@@ -3316,7 +3432,7 @@ function captureInUtilityWorld({ elements, injected }, options) {
3316
3432
  function validateSnapshot(value) {
3317
3433
  const snapshot = value;
3318
3434
  const box = (item) => !!item && [item.x, item.y, item.width, item.height].every((n) => typeof n === "number" && Number.isFinite(n));
3319
- if (!snapshot || typeof snapshot.text !== "string" || !Array.isArray(snapshot.iframeRefs) || !snapshot.iframeDepths || typeof snapshot.iframeDepths !== "object" || snapshot.iframeRefs.some((ref) => typeof ref !== "string" || !/^(f\d+)?e\d+$/.test(ref)) || Object.entries(snapshot.iframeDepths).some(([ref, depth]) => !/^(f\d+)?e\d+$/.test(ref) || !Number.isInteger(depth) || depth < 0) || snapshot.matches !== undefined && (!Array.isArray(snapshot.matches) || snapshot.matches.some((match) => !match || typeof match.ref !== "string" || !REF_PATTERN.test(match.ref) || typeof match.role !== "string" || typeof match.name !== "string" || !match.states || typeof match.states !== "object" || !box(match.box) || match.ancestors !== undefined && (!Array.isArray(match.ancestors) || match.ancestors.some((ref) => typeof ref !== "string"))))) {
3435
+ if (!snapshot || typeof snapshot.text !== "string" || !Array.isArray(snapshot.iframeRefs) || !snapshot.iframeDepths || typeof snapshot.iframeDepths !== "object" || snapshot.iframeRefs.some((ref) => typeof ref !== "string" || !/^(f\d+)?e\d+$/.test(ref)) || Object.entries(snapshot.iframeDepths).some(([ref, depth]) => !/^(f\d+)?e\d+$/.test(ref) || !Number.isInteger(depth) || depth < 0) || snapshot.matches !== undefined && (!Array.isArray(snapshot.matches) || snapshot.matches.some((match) => !match || typeof match.ref !== "string" || !REF_PATTERN.test(match.ref) || typeof match.role !== "string" || typeof match.name !== "string" || !match.states || typeof match.states !== "object" || !box(match.box) || match.ancestors !== undefined && (!Array.isArray(match.ancestors) || match.ancestors.some((ref) => typeof ref !== "string")))) || snapshot.viewport !== undefined && (!Number.isFinite(snapshot.viewport?.width) || !Number.isFinite(snapshot.viewport?.height))) {
3320
3436
  throw new Error(UNAVAILABLE);
3321
3437
  }
3322
3438
  }
@@ -3373,7 +3489,73 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
3373
3489
  clearTimeout(timer2);
3374
3490
  }
3375
3491
  };
3376
- const captureFrame = async (currentFrame, selector, frameOptions, isMainFrame = false, framePath = []) => {
3492
+ const prefix = (options.frames ?? []).map((selector) => `${selector} >> internal:control=enter-frame >> `).join("");
3493
+ const refScope = options.scope?.startsWith("aria-ref=") ? options.scope : undefined;
3494
+ const geometry = !!(options.boxes || options.query);
3495
+ document2.framesWithoutBoxes = [];
3496
+ const withoutBoxes = (framePath, reason) => {
3497
+ document2.framesWithoutBoxes.push({ framePath, reason });
3498
+ return null;
3499
+ };
3500
+ const iframePlacement = async (parentFrame, selector, parent, framePath) => {
3501
+ if (!parent)
3502
+ return null;
3503
+ let measured;
3504
+ try {
3505
+ measured = (await bounded2(parentFrame.selectors.callOnSelector(selector, { strict: true }, iframeGeometryInUtilityWorld, null)))?.result;
3506
+ } catch {
3507
+ measured = undefined;
3508
+ }
3509
+ if (measured === "transformed")
3510
+ return withoutBoxes(framePath, "transformed");
3511
+ if (!isGeometry(measured))
3512
+ return withoutBoxes(framePath, "unknown");
3513
+ if (!drawnAtScale(parent, measured.parentViewport))
3514
+ return withoutBoxes(framePath, "transformed");
3515
+ return { x: parent.x + measured.x, y: parent.y + measured.y, width: measured.width, height: measured.height };
3516
+ };
3517
+ const selectedPlacement = async () => {
3518
+ const frames = options.frames;
3519
+ let placement = PAGE;
3520
+ for (let index = 0;placement && index < frames.length; index++) {
3521
+ const into = frames.slice(0, index).map((selector) => `${selector} >> internal:control=enter-frame >> `).join("");
3522
+ placement = await iframePlacement(frame, `${into}${frames[index]}`, placement, []);
3523
+ }
3524
+ return placement;
3525
+ };
3526
+ const scopePlacement = async (scopeFrame) => {
3527
+ let x = 0, y = 0, size, inner;
3528
+ try {
3529
+ for (let current = scopeFrame;current !== frame; ) {
3530
+ const parent = current.parentFrame?.();
3531
+ if (!parent || typeof current.frameElement !== "function")
3532
+ return withoutBoxes([], "unknown");
3533
+ const element = await bounded2(current.frameElement(FRAME_ELEMENT_PROGRESS));
3534
+ let measured;
3535
+ try {
3536
+ if (typeof element?.evaluateInUtility === "function")
3537
+ measured = await bounded2(element.evaluateInUtility(iframeGeometryInUtilityWorld, null));
3538
+ } finally {
3539
+ element?.dispose?.();
3540
+ }
3541
+ if (measured === "transformed")
3542
+ return withoutBoxes([], "transformed");
3543
+ if (!isGeometry(measured))
3544
+ return withoutBoxes([], "unknown");
3545
+ if (inner && !drawnAtScale(measured, inner))
3546
+ return withoutBoxes([], "transformed");
3547
+ inner = measured.parentViewport;
3548
+ x += measured.x;
3549
+ y += measured.y;
3550
+ size ??= { width: measured.width, height: measured.height };
3551
+ current = parent;
3552
+ }
3553
+ } catch {
3554
+ return withoutBoxes([], "unknown");
3555
+ }
3556
+ return size ? { x, y, ...size } : PAGE;
3557
+ };
3558
+ const captureFrame = async (currentFrame, selector, frameOptions, isMainFrame = false, framePath = [], placing) => {
3377
3559
  if (!isServerFrame(currentFrame))
3378
3560
  throw new Error(UNAVAILABLE);
3379
3561
  if (Date.now() >= deadline)
@@ -3386,9 +3568,11 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
3386
3568
  throw error;
3387
3569
  captured = null;
3388
3570
  }
3571
+ let placement = await placing;
3389
3572
  if (!captured) {
3390
3573
  if (!isMainFrame) {
3391
3574
  document2.unavailableFrames.push(framePath.at(-1));
3575
+ document2.framesWithoutBoxes = document2.framesWithoutBoxes.filter((item) => item.framePath.join(" ") !== framePath.join(" "));
3392
3576
  return [];
3393
3577
  }
3394
3578
  if (options.scope?.startsWith("aria-ref=")) {
@@ -3398,15 +3582,22 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
3398
3582
  if (options.frames?.length)
3399
3583
  throw new Error("Snapshot frame selection failed. Each frames selector must match exactly one iframe with a loaded document.");
3400
3584
  await bounded2(new Promise((resolve2) => setTimeout(resolve2, 50)));
3401
- return captureFrame(currentFrame, selector, frameOptions, true);
3585
+ return captureFrame(currentFrame, selector, frameOptions, true, framePath, placement);
3402
3586
  }
3403
3587
  if (captured.info?.world !== "utility" || !isServerFrame(captured.frame))
3404
3588
  throw new Error(UNAVAILABLE);
3405
3589
  validateSnapshot(captured.result);
3406
3590
  const snapshot = captured.result;
3591
+ if (placement === PAGE && isMainFrame && refScope && captured.frame !== frame)
3592
+ placement = await scopePlacement(captured.frame);
3593
+ if (placement && snapshot.viewport && !drawnAtScale(placement, snapshot.viewport))
3594
+ placement = withoutBoxes(framePath, "transformed");
3595
+ const unchanged = placement === undefined || placement === PAGE;
3407
3596
  document2.priorityRefs.push(...snapshot.priorityRefs ?? []);
3408
- for (const match of snapshot.matches ?? [])
3409
- document2.matches.push({ ...match, framePath });
3597
+ for (const { box, ...match } of snapshot.matches ?? []) {
3598
+ const page2 = unchanged ? box : placement ? { ...box, x: Math.round(box.x + placement.x), y: Math.round(box.y + placement.y) } : undefined;
3599
+ document2.matches.push({ ...match, ...page2 ? { box: page2 } : {}, framePath });
3600
+ }
3410
3601
  document2.matchCount += snapshot.matchCount ?? 0;
3411
3602
  if (snapshot.scopeMatchCount !== undefined)
3412
3603
  document2.scopeMatchCount = snapshot.scopeMatchCount;
@@ -3420,11 +3611,12 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
3420
3611
  scope: undefined,
3421
3612
  scopeName: undefined,
3422
3613
  rootIsScope: false
3423
- }, false, childPath));
3614
+ }, false, childPath, placement === undefined ? undefined : iframePlacement(captured.frame, `aria-ref=${ref}`, placement, childPath)));
3424
3615
  }));
3425
3616
  const lines = [];
3426
- for (const line of snapshot.text.split(`
3617
+ for (const rendered of snapshot.text.split(`
3427
3618
  `)) {
3619
+ const line = frameOptions.boxes && !unchanged ? moveLineBox(rendered, placement ?? null) : rendered;
3428
3620
  const { role, ref } = snapshotLine(line);
3429
3621
  const child = role === "iframe" && ref ? children.get(ref) : undefined;
3430
3622
  lines.push(child?.length ? `${line}:` : line);
@@ -3435,9 +3627,7 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
3435
3627
  }
3436
3628
  return lines;
3437
3629
  };
3438
- const prefix = (options.frames ?? []).map((selector) => `${selector} >> internal:control=enter-frame >> `).join("");
3439
- const refScope = options.scope?.startsWith("aria-ref=") ? options.scope : undefined;
3440
- document2.text = (await captureFrame(frame, refScope ?? `${prefix}body,frameset`, refScope ? { ...renderOptions, scope: undefined, rootIsScope: true } : renderOptions, true)).join(`
3630
+ document2.text = (await captureFrame(frame, refScope ?? `${prefix}body,frameset`, refScope ? { ...renderOptions, scope: undefined, rootIsScope: true } : renderOptions, true, [], !geometry ? undefined : options.frames?.length ? await selectedPlacement() : PAGE)).join(`
3441
3631
  `);
3442
3632
  return document2;
3443
3633
  }
@@ -3601,7 +3791,7 @@ function matchKey(match, boxes) {
3601
3791
  for (const state of MATCH_STATES)
3602
3792
  if (match.states[state] !== undefined)
3603
3793
  key2 += ` [${state}=${JSON.stringify(match.states[state])}]`;
3604
- return `${key2} [ref=${match.ref}]${boxes ? ` [box=${[match.box.x, match.box.y, match.box.width, match.box.height].join(",")}]` : ""}`;
3794
+ return `${key2} [ref=${match.ref}]${boxes && match.box ? ` [box=${[match.box.x, match.box.y, match.box.width, match.box.height].join(",")}]` : ""}`;
3605
3795
  }
3606
3796
  var publicMatch = (match, inOutline, framePath) => ({
3607
3797
  ref: match.ref,
@@ -3610,7 +3800,7 @@ var publicMatch = (match, inOutline, framePath) => ({
3610
3800
  ...match.value !== undefined ? { value: match.value } : {},
3611
3801
  ...match.text ? { text: match.text } : {},
3612
3802
  states: match.states,
3613
- box: match.box,
3803
+ ...match.box ? { box: match.box } : {},
3614
3804
  inOutline,
3615
3805
  ...framePath.length ? { framePath } : {}
3616
3806
  });
@@ -3738,6 +3928,10 @@ function renderSnapshot(document2, input) {
3738
3928
  notes.push(document2.restoredFromCache ? "This page was restored from the back/forward cache, and some of its frames cannot be read until it loads again: browser_history reload loads it afresh, without the state it kept." : "Some frames disappeared or were unavailable during capture; refresh before treating the observation as complete.");
3739
3929
  if (unrepresentedMatches)
3740
3930
  notes.push(`${unrepresentedMatches} visible matching elements have no ref: one frame had more than ${MAX_MATCH_DETAILS} matches. Narrow the query or scope it.`);
3931
+ const boxless = document2.framesWithoutBoxes ?? [];
3932
+ const framesWithoutBoxes = input.boxes ? boxless : input.query ? boxless.filter((frame) => document2.matches.some((match) => !match.box && frame.framePath.every((ref, index) => match.framePath[index] === ref))) : [];
3933
+ if (framesWithoutBoxes.length)
3934
+ notes.push("Elements of frames that the page transforms, scales or zooms, or whose iframe could not be measured, have no boxes (completeness.framesWithoutBoxes; an empty framePath is the frame this read started in): their place in the page's viewport is unknown. Click them by ref.");
3741
3935
  if (returned.some((match) => !match.inOutline))
3742
3936
  notes.push("Matches with inOutline false are not shown in the outline (such as a text span inside a table cell), but their refs work with every ref-taking tool. A DOM-backed ref (d12, f1d3) becomes stale once its element leaves the page or its frame navigates.");
3743
3937
  if (nextOffset !== null)
@@ -3755,7 +3949,8 @@ function renderSnapshot(document2, input) {
3755
3949
  depthOmittedLines: depthOmitted,
3756
3950
  characterLimited,
3757
3951
  unavailableFrames: document2.unavailableFrames,
3758
- ...input.query ? { unrepresentedMatches } : {}
3952
+ ...input.query ? { unrepresentedMatches } : {},
3953
+ ...framesWithoutBoxes.length ? { framesWithoutBoxes } : {}
3759
3954
  },
3760
3955
  ...input.query ? { matchCount: document2.matchCount, returnedMatches, offset: input.offset, nextOffset, matches: returned } : {},
3761
3956
  ...notes.length ? { note: notes.join(" ") } : {}
@@ -3763,18 +3958,38 @@ function renderSnapshot(document2, input) {
3763
3958
  }
3764
3959
 
3765
3960
  // cli/src/browser/back-forward-cache.ts
3961
+ var OTHER_DOCUMENT = new Set(["differentDocument", "historyDifferentDocument", "reload", "reloadBypassingCache", "restore", "restoreWithPost"]);
3766
3962
  var REMEMBERED_DOCUMENTS = 32;
3767
3963
  var COMMIT_HEARD_MS = 1000;
3768
3964
 
3769
3965
  class MainFrameDocuments {
3966
+ cdp;
3770
3967
  commits = 0;
3968
+ pending;
3771
3969
  current;
3970
+ mainFrameId;
3772
3971
  reached = new Map;
3773
3972
  listeners = new Set;
3774
3973
  constructor(cdp) {
3974
+ this.cdp = cdp;
3975
+ cdp.send("Target.getTargetInfo").then(({ targetInfo }) => {
3976
+ this.mainFrameId ??= targetInfo.targetId;
3977
+ }).catch(() => {
3978
+ return;
3979
+ });
3980
+ cdp.on("Page.frameStartedNavigating", ({ frameId, url, navigationType }) => {
3981
+ if (frameId === this.mainFrameId && OTHER_DOCUMENT.has(navigationType))
3982
+ this.pending = { url, since: Date.now() };
3983
+ });
3984
+ cdp.on("Page.frameStoppedLoading", ({ frameId }) => {
3985
+ if (frameId === this.mainFrameId)
3986
+ this.pending = undefined;
3987
+ });
3775
3988
  cdp.on("Page.frameNavigated", ({ frame, type }) => {
3776
3989
  if (frame.parentId)
3777
3990
  return;
3991
+ this.mainFrameId = frame.id;
3992
+ this.pending = undefined;
3778
3993
  const restored = type === "BackForwardCacheRestore";
3779
3994
  this.current = { frameId: frame.id, loaderId: frame.loaderId, url: frame.url + (frame.urlFragment ?? ""), restored, committedAt: ++this.commits };
3780
3995
  const known = this.reached.get(frame.loaderId);
@@ -3844,6 +4059,14 @@ class MainFrameDocuments {
3844
4059
  const document2 = this.restoredShown(page, since);
3845
4060
  return !!document2 && document2.committedAt > since;
3846
4061
  }
4062
+ async shown() {
4063
+ const { frameTree } = await this.cdp.send("Page.getFrameTree");
4064
+ const loaderId = frameTree?.frame?.loaderId;
4065
+ const document2 = this.current;
4066
+ if (typeof loaderId !== "string" || document2 && document2.loaderId !== loaderId)
4067
+ return;
4068
+ return `${document2?.committedAt ?? 0}:${loaderId}`;
4069
+ }
3847
4070
  }
3848
4071
  var followed2 = new WeakMap;
3849
4072
  function followDocuments(page, cdp) {
@@ -3857,6 +4080,9 @@ function followDocuments(page, cdp) {
3857
4080
  function commitsHeard(page) {
3858
4081
  return followed2.get(page)?.commits;
3859
4082
  }
4083
+ function pendingNavigation(page) {
4084
+ return followed2.get(page)?.pending;
4085
+ }
3860
4086
  function restoredFromCache(page, since) {
3861
4087
  const documents = followed2.get(page);
3862
4088
  return documents && since !== undefined ? documents.restoredSince(page, since) : undefined;
@@ -3864,6 +4090,9 @@ function restoredFromCache(page, since) {
3864
4090
  function showsRestoredDocument(page) {
3865
4091
  return followed2.get(page)?.showsRestored(page) ?? false;
3866
4092
  }
4093
+ async function shownDocument(page) {
4094
+ return await followed2.get(page)?.shown();
4095
+ }
3867
4096
  async function waitForLoadState(page, state, timeoutMs, since) {
3868
4097
  const documents = followed2.get(page);
3869
4098
  if (!documents || state === "networkidle")
@@ -4110,152 +4339,6 @@ async function waitForBrowserCondition(page, input, network) {
4110
4339
  return timedOut(counts2);
4111
4340
  }
4112
4341
 
4113
- // cli/src/browser/navigation-observer.ts
4114
- function navigationUrlMatches(pattern, url) {
4115
- if (!pattern)
4116
- return true;
4117
- const source = pattern.split(/(\*\*|\*)/).map((part) => part === "**" ? ".*" : part === "*" ? "[^/]*" : part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("");
4118
- return new RegExp(`^${source}$`).test(url);
4119
- }
4120
- function observeNavigation(page, input) {
4121
- const started = Date.now(), deadline = started + input.timeoutMs;
4122
- const since = commitsHeard(page);
4123
- let settled = false;
4124
- let resolve2;
4125
- const result = new Promise((done) => {
4126
- resolve2 = done;
4127
- });
4128
- const finish = (matched, code2, error) => {
4129
- if (settled)
4130
- return;
4131
- settled = true;
4132
- clearTimeout(timer2);
4133
- page.off("framenavigated", onNavigation);
4134
- page.off("close", onClose);
4135
- page.off("crash", onClose);
4136
- resolve2({ matched, url: page.url(), elapsedMs: Date.now() - started, waitUntil: input.waitUntil, ...code2 ? { code: code2, error } : {} });
4137
- };
4138
- const onClose = () => finish(false, "navigation_tab_closed", "The tab closed before navigation was observed. Inspect tabs before another action.");
4139
- const onNavigation = (frame) => {
4140
- if (frame !== page.mainFrame() || !navigationUrlMatches(input.url, frame.url()))
4141
- return;
4142
- if (input.waitUntil === "commit") {
4143
- finish(true);
4144
- return;
4145
- }
4146
- waitForLoadState(page, input.waitUntil, Math.max(1, deadline - Date.now()), since).then(() => {
4147
- if (navigationUrlMatches(input.url, page.url()))
4148
- finish(true);
4149
- }, () => {
4150
- return;
4151
- });
4152
- };
4153
- const timer2 = setTimeout(() => finish(false, "navigation_timeout", "Input was dispatched, but the expected navigation was not observed before the deadline. Inspect the page; do not repeat the action solely because this wait timed out."), input.timeoutMs);
4154
- page.on("framenavigated", onNavigation);
4155
- page.on("close", onClose);
4156
- page.on("crash", onClose);
4157
- return { result, dispose: () => finish(false, "navigation_observation_cancelled", "Navigation observation ended.") };
4158
- }
4159
-
4160
- // cli/src/browser/frame-history.ts
4161
- var POLL_MS = 50;
4162
- var UNSEEN_COMMIT_MS = 300;
4163
- var FRAME_LOADED_MS = 5000;
4164
- async function traverseToEntry(page, cdp, entryId, timeoutMs) {
4165
- const deadline = Date.now() + timeoutMs;
4166
- const mainId = await cdp.send("Page.getFrameTree").then(({ frameTree }) => frameTree.frame.id, () => {
4167
- return;
4168
- });
4169
- let mainSeen = false;
4170
- let childSeen = false;
4171
- let sameDocument = false;
4172
- let childFrame;
4173
- let response = null;
4174
- let reachedAt;
4175
- let settle;
4176
- const committed = new Promise((resolve2, reject) => {
4177
- let settled = false;
4178
- settle = (value) => {
4179
- if (settled)
4180
- return;
4181
- settled = true;
4182
- stop();
4183
- if (value instanceof Error)
4184
- reject(value);
4185
- else
4186
- resolve2(value);
4187
- };
4188
- });
4189
- const decide = () => {
4190
- if (mainSeen)
4191
- settle("main");
4192
- else if (reachedAt !== undefined && (childSeen || Date.now() - reachedAt >= UNSEEN_COMMIT_MS))
4193
- settle("child");
4194
- };
4195
- const readEntry = () => void cdp.send("Page.getNavigationHistory").then(({ currentIndex, entries }) => {
4196
- if (entries[currentIndex]?.id === entryId)
4197
- reachedAt ??= Date.now();
4198
- decide();
4199
- }, () => {
4200
- return;
4201
- });
4202
- const seen = (main) => {
4203
- if (main)
4204
- mainSeen = true;
4205
- else
4206
- childSeen = true;
4207
- if (mainSeen)
4208
- decide();
4209
- else
4210
- readEntry();
4211
- };
4212
- const onFrameNavigated = (frame) => {
4213
- if (frame !== page.mainFrame())
4214
- childFrame = frame;
4215
- seen(frame === page.mainFrame());
4216
- };
4217
- const onResponse = (candidate) => {
4218
- if (candidate.frame() === page.mainFrame() && candidate.request().isNavigationRequest())
4219
- response = candidate;
4220
- };
4221
- const onClose = () => settle(new Error("Target page, context or browser has been closed"));
4222
- const onCrash = () => settle(new Error("Target crashed"));
4223
- const onCommit = ({ frame }) => seen(!frame.parentId);
4224
- const onWithinDocument = ({ frameId }) => {
4225
- if (mainId === undefined)
4226
- return;
4227
- if (frameId !== mainId)
4228
- sameDocument = true;
4229
- seen(frameId === mainId);
4230
- };
4231
- page.on("framenavigated", onFrameNavigated);
4232
- page.on("response", onResponse);
4233
- page.on("close", onClose);
4234
- page.on("crash", onCrash);
4235
- cdp.on("Page.frameNavigated", onCommit);
4236
- cdp.on("Page.navigatedWithinDocument", onWithinDocument);
4237
- const poll = setInterval(readEntry, POLL_MS);
4238
- const timer2 = setTimeout(() => settle(new Error(`Timeout ${timeoutMs}ms exceeded waiting for the history entry to commit.`)), Math.max(1, deadline - Date.now()));
4239
- function stop() {
4240
- clearInterval(poll);
4241
- clearTimeout(timer2);
4242
- page.off("framenavigated", onFrameNavigated);
4243
- page.off("response", onResponse);
4244
- page.off("close", onClose);
4245
- page.off("crash", onCrash);
4246
- cdp.off("Page.frameNavigated", onCommit);
4247
- cdp.off("Page.navigatedWithinDocument", onWithinDocument);
4248
- }
4249
- await cdp.send("Page.navigateToHistoryEntry", { entryId }).catch((error) => settle(error instanceof Error ? error : new Error(String(error))));
4250
- if (await committed === "main")
4251
- return { frame: "main", response };
4252
- if (childFrame && !sameDocument && !childFrame.isDetached())
4253
- await childFrame.waitForLoadState("domcontentloaded", { timeout: Math.max(1, Math.min(FRAME_LOADED_MS, deadline - Date.now())) }).catch(() => {
4254
- return;
4255
- });
4256
- return { frame: "child" };
4257
- }
4258
-
4259
4342
  // cli/src/browser/passkey-guard.ts
4260
4343
  var MAX_PASSKEY_REQUESTS = 16;
4261
4344
  function passkeyGuardSource(binding, cancelEvent) {
@@ -4330,63 +4413,447 @@ function parsePasskeyReport(payload) {
4330
4413
  }
4331
4414
  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.`;
4332
4415
 
4333
- // cli/src/browser/browser-events.ts
4334
- var PASSKEY_ANNOUNCE_MS = 300;
4335
- var PASSKEY_CANCEL_MS = 2000;
4336
- var PASSKEY_FLUSH_MS = 250;
4337
- var PASSKEY_WORLD = "__browser_mcp_passkey__";
4338
- var CAPACITY = 200;
4339
- var RETENTION_MS = 10 * 60000;
4340
- var MAX_INFLIGHT = 500;
4341
- var MAX_ACTIVITY = 1000;
4342
- function diagnosticUrl(raw) {
4343
- try {
4344
- const u = new URL(raw);
4345
- if (!["http:", "https:"].includes(u.protocol))
4346
- return `${u.protocol}[redacted]`;
4347
- u.username = "";
4348
- u.password = "";
4349
- u.hash = "";
4350
- for (const key2 of [...u.searchParams.keys()])
4351
- u.searchParams.set(key2, "[redacted]");
4352
- return u.href;
4353
- } catch {
4354
- return "[unavailable]";
4355
- }
4356
- }
4357
- function diagnosticText(text) {
4358
- return text.slice(0, 4000).replace(/https?:\/\/[^\s"'<>]+/g, diagnosticUrl).replace(/\b(bearer\s+)[\w.+/=-]+/gi, "$1[redacted]").replace(/\b(password|passwd|secret|token|authorization|cookie|api[-_]?key)\s*[:=]\s*[^\s,;]+/gi, "$1=[redacted]").slice(0, 2000);
4359
- }
4360
- function requestUrl(request) {
4416
+ // cli/src/browser/http-auth.ts
4417
+ var ENABLE_MS = 1500;
4418
+ var OUTCOME_MS = 5000;
4419
+ var MAX_TRACKED = 200;
4420
+ var HTTP_AUTH_RECOVERY = `A site asks for a username and password (an HTTP sign-in, in httpAuth). Answer it with browser_handle_dialog and its dialogId: decision "dismiss" cancels it and the tab shows the site's 401 page; "accept" signs in with vaultId and names (the names of the local vault values from browser_capture_secrets that hold the username and the password, never the values) and expectedOrigin, the exact origin the user authorized them for. Without such values, hand the tab to the user with browser_takeover: live view asks them to sign in. Other actions on this tab are refused until the sign-in is answered.`;
4421
+ var REJECTED_RECOVERY = "The site rejected these credentials and asks again (httpAuth, a new dialogId): check that the vault values are this site's username and password, or ask the user. Answer the new sign-in or dismiss it; do not send the same values again.";
4422
+ var GONE_RECOVERY = "Chrome no longer has this sign-in's request: the page navigated elsewhere, or its navigation was stopped. Nothing was sent. Read browser_events and the page.";
4423
+ var refusal = (code2, recovery, details) => new RuntimeFault(code2, recovery, true, details, true);
4424
+ var protocolLogging = () => /\*|pw:protocol/.test(process.env.DEBUG ?? "");
4425
+ var originOf = (url) => {
4361
4426
  try {
4362
- return request.url();
4427
+ return new URL(url).origin;
4363
4428
  } catch {
4364
- return "";
4429
+ return "null";
4365
4430
  }
4431
+ };
4432
+ async function bounded2(work, ms) {
4433
+ let timer2;
4434
+ await Promise.race([work.catch(() => {
4435
+ return;
4436
+ }), new Promise((resolve2) => timer2 = setTimeout(resolve2, ms))]);
4437
+ clearTimeout(timer2);
4366
4438
  }
4367
4439
 
4368
- class BrowserPageEvents {
4369
- page;
4370
- passkeyDetection;
4371
- sequence = 0;
4372
- entries = [];
4373
- listeners = new Set;
4374
- changes = new Set;
4375
- dialogListeners = new Set;
4376
- requests = new WeakMap;
4377
- inflight = new Map;
4378
- lastNetworkActivity;
4379
- activity = [];
4380
- activityDroppedAt = 0;
4381
- choosers = new Map;
4382
- downloads = new Map;
4383
- assets = new Map;
4384
- dialog;
4385
- dialogOrigin;
4386
- passkey;
4387
- contextFrames = new Map;
4388
- passkeyBinding = `__bmcpPasskey${crypto.randomUUID().replaceAll("-", "")}`;
4389
- passkeyCancel = `bmcp-passkey-cancel-${crypto.randomUUID()}`;
4440
+ class HttpAuthPrompts {
4441
+ host;
4442
+ held = new Map;
4443
+ attempts = new Map;
4444
+ chrome = new Set;
4445
+ waits = new Map;
4446
+ cdp;
4447
+ mainFrameId;
4448
+ constructor(host) {
4449
+ this.host = host;
4450
+ }
4451
+ async watch(cdp) {
4452
+ this.cdp = cdp;
4453
+ cdp.on("Fetch.requestPaused", ({ requestId }) => this.quietly(() => cdp.send("Fetch.continueRequest", { requestId })));
4454
+ cdp.on("Fetch.authRequired", (event) => this.required(cdp, event));
4455
+ cdp.on("Page.frameNavigated", ({ frame }) => this.closeFrame(frame.id, "navigated"));
4456
+ cdp.on("Page.frameDetached", ({ frameId }) => this.closeFrame(frameId, "frame_removed"));
4457
+ cdp.on("close", () => this.release("gone"));
4458
+ await Promise.all([
4459
+ bounded2(cdp.send("Target.getTargetInfo").then(({ targetInfo }) => {
4460
+ this.mainFrameId = targetInfo.targetId;
4461
+ }), ENABLE_MS),
4462
+ bounded2(cdp.send("Fetch.enable", { handleAuthRequests: true, patterns: [{ urlPattern: "*", resourceType: "Document", requestStage: "Request" }] }), ENABLE_MS)
4463
+ ]);
4464
+ }
4465
+ required(cdp, { requestId, request, frameId, resourceType, authChallenge }) {
4466
+ const scheme = String(authChallenge?.scheme ?? "").toLowerCase();
4467
+ const attempt = (this.attempts.get(requestId) ?? 0) + 1;
4468
+ this.attempts.set(requestId, attempt);
4469
+ if (this.attempts.size > MAX_TRACKED)
4470
+ this.attempts.delete(this.attempts.keys().next().value);
4471
+ const eligible = authChallenge?.source === "Server" && (scheme === "basic" || scheme === "digest") && resourceType === "Document";
4472
+ if (!eligible || this.chrome.has(requestId) || attempt === 1 && !this.host.holds()) {
4473
+ this.chrome.add(requestId);
4474
+ if (this.chrome.size > MAX_TRACKED)
4475
+ this.chrome.delete(this.chrome.values().next().value);
4476
+ this.waits.get(requestId)?.resolve({ kind: "pending" });
4477
+ this.quietly(() => cdp.send("Fetch.continueWithAuth", { requestId, authChallengeResponse: { response: "Default" } }));
4478
+ return;
4479
+ }
4480
+ let origin = originOf(request.url);
4481
+ try {
4482
+ origin = new URL(authChallenge.origin).origin;
4483
+ } catch {}
4484
+ const realm = String(authChallenge.realm ?? "").replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim().slice(0, MAX_HTTP_AUTH_REALM);
4485
+ const main = frameId === this.mainFrameId;
4486
+ for (const other of [...this.held.values()])
4487
+ if (other.frameId === frameId && other.requestId !== requestId)
4488
+ this.close(other, "closed", "replaced");
4489
+ const event = this.host.record("dialog", { type: HTTP_AUTH_DIALOG, origin, realm, scheme, url: this.host.redact(request.url), frame: main ? "main" : "iframe", attempt, state: "open" });
4490
+ const state = { event, requestId, frameId, main, url: request.url, origin, realm, scheme, attempt, answering: false };
4491
+ this.held.set(requestId, state);
4492
+ this.waits.get(requestId)?.resolve({ kind: "rejected", next: state });
4493
+ this.host.changed(true);
4494
+ }
4495
+ quietly(call) {
4496
+ try {
4497
+ call().catch(() => {
4498
+ return;
4499
+ });
4500
+ } catch {}
4501
+ }
4502
+ close(state, outcome, reason, handledBy) {
4503
+ if (this.held.get(state.requestId) !== state)
4504
+ return;
4505
+ this.held.delete(state.requestId);
4506
+ state.event.state = outcome;
4507
+ if (handledBy)
4508
+ state.event.handledBy = handledBy;
4509
+ const closing = this.host.record("dialog", { dialogId: state.event.eventId, type: HTTP_AUTH_DIALOG, state: outcome, reason, ...handledBy ? { handledBy } : {} });
4510
+ this.host.changed(false);
4511
+ return closing;
4512
+ }
4513
+ closeFrame(frameId, reason) {
4514
+ for (const state of [...this.held.values()])
4515
+ if (state.frameId === frameId)
4516
+ this.close(state, "closed", reason);
4517
+ }
4518
+ requestEnded(request, status) {
4519
+ if (!this.held.size && !this.waits.size)
4520
+ return;
4521
+ let url;
4522
+ try {
4523
+ if (!request.isNavigationRequest())
4524
+ return;
4525
+ url = request.url();
4526
+ } catch {
4527
+ return;
4528
+ }
4529
+ for (const wait of this.waits.values())
4530
+ if (wait.url === url) {
4531
+ wait.resolve(status === null ? { kind: "failed" } : { kind: "answered", status });
4532
+ return;
4533
+ }
4534
+ if (status === null) {
4535
+ for (const state of [...this.held.values()])
4536
+ if (state.url === url)
4537
+ this.close(state, "closed", "aborted");
4538
+ }
4539
+ }
4540
+ pageClosed() {
4541
+ this.held.clear();
4542
+ for (const wait of [...this.waits.values()])
4543
+ wait.resolve({ kind: "failed" });
4544
+ }
4545
+ release(reason) {
4546
+ if (this.cdp && this.held.size)
4547
+ for (const state of [...this.held.values()])
4548
+ this.close(state, "closed", reason);
4549
+ this.cdp = undefined;
4550
+ for (const wait of [...this.waits.values()])
4551
+ wait.resolve({ kind: "pending" });
4552
+ }
4553
+ handToChrome(reason) {
4554
+ const cdp = this.cdp;
4555
+ for (const state of [...this.held.values()]) {
4556
+ this.close(state, "closed", reason);
4557
+ if (cdp) {
4558
+ this.chrome.add(state.requestId);
4559
+ this.quietly(() => cdp.send("Fetch.continueWithAuth", { requestId: state.requestId, authChallengeResponse: { response: "Default" } }));
4560
+ }
4561
+ }
4562
+ }
4563
+ first() {
4564
+ return this.held.values().next().value;
4565
+ }
4566
+ isOpen() {
4567
+ return this.held.size > 0;
4568
+ }
4569
+ holdsMainFrame() {
4570
+ for (const state of this.held.values())
4571
+ if (state.main)
4572
+ return true;
4573
+ return false;
4574
+ }
4575
+ isOpenDialog(dialogId) {
4576
+ for (const state of this.held.values())
4577
+ if (state.event.eventId === dialogId)
4578
+ return true;
4579
+ return false;
4580
+ }
4581
+ event() {
4582
+ return this.first()?.event;
4583
+ }
4584
+ promptOf(state) {
4585
+ return {
4586
+ dialogId: state.event.eventId,
4587
+ type: HTTP_AUTH_DIALOG,
4588
+ origin: state.origin,
4589
+ realm: state.realm,
4590
+ scheme: state.scheme,
4591
+ url: String(state.event.url),
4592
+ frame: state.main ? "main" : "iframe",
4593
+ attempt: state.attempt,
4594
+ state: "open",
4595
+ openedAt: state.event.timestamp,
4596
+ untrusted: true
4597
+ };
4598
+ }
4599
+ prompt() {
4600
+ const state = this.first();
4601
+ return state ? this.promptOf(state) : null;
4602
+ }
4603
+ details() {
4604
+ const state = this.first();
4605
+ return state ? { type: HTTP_AUTH_DIALOG, message: "", origin: state.origin, realm: state.realm, scheme: state.scheme, frame: state.main ? "main" : "iframe", attempt: state.attempt } : null;
4606
+ }
4607
+ requiredResult(actionId) {
4608
+ const state = this.first();
4609
+ if (!state)
4610
+ return;
4611
+ return {
4612
+ code: "http_auth_required",
4613
+ dispatch: { status: "blocked", actionId, code: "http_auth_required" },
4614
+ httpAuth: this.promptOf(state),
4615
+ recovery: HTTP_AUTH_RECOVERY
4616
+ };
4617
+ }
4618
+ async answer(dialogId, input, answer) {
4619
+ let state;
4620
+ for (const held of this.held.values())
4621
+ if (held.event.eventId === dialogId)
4622
+ state = held;
4623
+ if (!state)
4624
+ return;
4625
+ const cdp = this.cdp;
4626
+ const prompt = this.promptOf(state);
4627
+ const details = { httpAuth: prompt };
4628
+ if (!cdp)
4629
+ return { handled: false, code: "stale_dialog", httpAuth: prompt, recovery: GONE_RECOVERY };
4630
+ if (state.answering)
4631
+ throw refusal("http_auth_answer_pending", "Read browser_events: the sign-in may have closed meanwhile. Answer it again only if it is still open.", details);
4632
+ if (input.promptText !== undefined)
4633
+ return { handled: false, code: "prompt_text_requires_accept_prompt", httpAuth: prompt };
4634
+ const accept = input.decision === "accept";
4635
+ let credentials;
4636
+ if (accept && answer.by === "viewer") {
4637
+ if (!answer.typed || protocolLogging())
4638
+ return { handled: false, code: answer.typed ? "http_auth_logging_enabled" : "http_auth_credentials_required" };
4639
+ credentials = answer.typed;
4640
+ } else if (accept && answer.by === "agent") {
4641
+ if (!answer.names || !answer.reveal)
4642
+ throw refusal("http_auth_credentials_required", HTTP_AUTH_RECOVERY, details);
4643
+ if (answer.expectedOrigin !== state.origin)
4644
+ throw refusal("http_auth_origin_mismatch", "Values are sent only to the exact origin the user authorized. Check httpAuth.origin: if the user authorized it, pass it as expectedOrigin; if the site redirected there, ask the user first. Nothing was sent.", { ...details, expectedOrigin: answer.expectedOrigin });
4645
+ const pageOrigin = originOf(this.host.page.url());
4646
+ if (!state.main && pageOrigin !== state.origin)
4647
+ throw refusal("http_auth_frame_refused", "Dismiss it, or open httpAuth.origin in a tab of its own if the user authorized signing in there. Nothing was sent.", { ...details, pageOrigin });
4648
+ if (protocolLogging())
4649
+ throw refusal("http_auth_logging_enabled", "Ask the user to restart the Browser MCP CLI without DEBUG set, or to sign in themselves in live view (browser_takeover). Nothing was sent.", details);
4650
+ state.answering = true;
4651
+ try {
4652
+ credentials = await answer.reveal();
4653
+ } catch {
4654
+ throw refusal("http_auth_secret_unavailable", "Check the vault with browser_list_secrets: a vault lasts five minutes and ends when the page, or the frame, it was captured from navigates, or when its tab closes. Capture the values again with browser_capture_secrets if the user authorized that, or hand the tab to the user with browser_takeover. Nothing was sent.", { ...details, vaultId: answer.vaultId });
4655
+ } finally {
4656
+ state.answering = false;
4657
+ }
4658
+ if (this.held.get(state.requestId) !== state) {
4659
+ credentials = undefined;
4660
+ throw refusal("http_auth_closed", "Read browser_events and the page: the page navigated, or the user answered it. Nothing was sent.", details);
4661
+ }
4662
+ }
4663
+ if (credentials && state.scheme === "basic" && credentials.username.includes(":")) {
4664
+ credentials = undefined;
4665
+ if (answer.by === "viewer")
4666
+ return { handled: false, code: "http_auth_username_unsupported" };
4667
+ throw refusal("http_auth_username_unsupported", "Check the vault value that holds the username. Nothing was sent.", details);
4668
+ }
4669
+ let outcome;
4670
+ if (accept) {
4671
+ const { requestId, url } = state;
4672
+ outcome = new Promise((resolve2) => {
4673
+ const finish = (value) => {
4674
+ clearTimeout(timer2);
4675
+ if (this.waits.get(requestId) === wait)
4676
+ this.waits.delete(requestId);
4677
+ resolve2(value);
4678
+ };
4679
+ const wait = { url, resolve: finish };
4680
+ const timer2 = setTimeout(() => finish({ kind: "pending" }), OUTCOME_MS);
4681
+ this.waits.set(requestId, wait);
4682
+ });
4683
+ }
4684
+ const closing = this.close(state, accept ? "accepted" : "dismissed", accept ? "credentials" : "cancelled", answer.by);
4685
+ let sent = true;
4686
+ try {
4687
+ await cdp.send("Fetch.continueWithAuth", credentials ? { requestId: state.requestId, authChallengeResponse: { response: "ProvideCredentials", username: credentials.username, password: credentials.password } } : { requestId: state.requestId, authChallengeResponse: { response: "CancelAuth" } });
4688
+ } catch {
4689
+ sent = false;
4690
+ }
4691
+ credentials = undefined;
4692
+ if (!sent) {
4693
+ this.waits.get(state.requestId)?.resolve({ kind: "pending" });
4694
+ for (const event of [state.event, closing])
4695
+ if (event) {
4696
+ event.state = "closed";
4697
+ delete event.handledBy;
4698
+ }
4699
+ if (closing)
4700
+ closing.reason = "gone";
4701
+ return { handled: false, code: "stale_dialog", httpAuth: prompt, recovery: GONE_RECOVERY };
4702
+ }
4703
+ const result = {
4704
+ handled: true,
4705
+ dialogId: prompt.dialogId,
4706
+ decision: accept ? "accept" : "dismiss",
4707
+ type: HTTP_AUTH_DIALOG,
4708
+ origin: state.origin,
4709
+ ...answer.by === "agent" && answer.names ? { vaultId: answer.vaultId, names: { ...answer.names } } : {}
4710
+ };
4711
+ if (outcome) {
4712
+ const settled = await outcome;
4713
+ if (settled.kind === "rejected")
4714
+ Object.assign(result, { signIn: "rejected", httpAuth: this.promptOf(settled.next), recovery: REJECTED_RECOVERY });
4715
+ else if (settled.kind === "answered")
4716
+ Object.assign(result, {
4717
+ signIn: "answered",
4718
+ responseStatus: settled.status,
4719
+ note: "Chrome sends these credentials to this site's realm by itself until this browser session's Chrome quits."
4720
+ });
4721
+ else if (settled.kind === "failed")
4722
+ Object.assign(result, { signIn: "failed", note: "The navigation failed after the credentials were sent: read the page and browser_diagnostics." });
4723
+ else
4724
+ Object.assign(result, { signIn: "sent", note: "The credentials were sent; the site's answer has not arrived yet. Read the page before going on." });
4725
+ }
4726
+ return result;
4727
+ }
4728
+ }
4729
+
4730
+ // cli/src/browser/browser-events.ts
4731
+ var PASSKEY_ANNOUNCE_MS = 300;
4732
+ var PASSKEY_CANCEL_MS = 2000;
4733
+ var PASSKEY_FLUSH_MS = 250;
4734
+ var LOADING_PROBE_MS = 300;
4735
+ var PASSKEY_WORLD = "__browser_mcp_passkey__";
4736
+ var CAPACITY = 200;
4737
+ var RETENTION_MS = 10 * 60000;
4738
+ var MAX_INFLIGHT = 500;
4739
+ var MAX_ACTIVITY = 1000;
4740
+ var MAX_FRAME_DOCUMENTS = 100;
4741
+ var FRAME_DOCUMENT_SETTLE_MS = 50;
4742
+ function httpOrigin(raw) {
4743
+ try {
4744
+ const url = new URL(raw);
4745
+ return url.protocol === "http:" || url.protocol === "https:" ? url.origin : undefined;
4746
+ } catch {
4747
+ return;
4748
+ }
4749
+ }
4750
+ function diagnosticUrl(raw) {
4751
+ try {
4752
+ const u = new URL(raw);
4753
+ if (!["http:", "https:"].includes(u.protocol))
4754
+ return `${u.protocol}[redacted]`;
4755
+ u.username = "";
4756
+ u.password = "";
4757
+ u.hash = "";
4758
+ for (const key2 of [...u.searchParams.keys()])
4759
+ u.searchParams.set(key2, "[redacted]");
4760
+ return u.href;
4761
+ } catch {
4762
+ return "[unavailable]";
4763
+ }
4764
+ }
4765
+ function diagnosticText(text) {
4766
+ return text.slice(0, 4000).replace(/https?:\/\/[^\s"'<>]+/g, diagnosticUrl).replace(/\b(bearer\s+)[\w.+/=-]+/gi, "$1[redacted]").replace(/\b(password|passwd|secret|token|authorization|cookie|api[-_]?key)\s*[:=]\s*[^\s,;]+/gi, "$1=[redacted]").slice(0, 2000);
4767
+ }
4768
+ function requestUrl(request) {
4769
+ try {
4770
+ return request.url();
4771
+ } catch {
4772
+ return "";
4773
+ }
4774
+ }
4775
+ var DIALOG_WAIT_MS = 10 * 60000;
4776
+
4777
+ class NavigationDeadline {
4778
+ ms;
4779
+ done;
4780
+ expired;
4781
+ fail;
4782
+ left;
4783
+ since;
4784
+ timer;
4785
+ stopped = false;
4786
+ heldOnce = false;
4787
+ constructor(ms, held, done) {
4788
+ this.ms = ms;
4789
+ this.done = done;
4790
+ this.left = ms;
4791
+ this.expired = new Promise((_resolve, reject) => this.fail = reject);
4792
+ this.expired.catch(() => {
4793
+ return;
4794
+ });
4795
+ this.update(held);
4796
+ }
4797
+ update(held) {
4798
+ if (this.stopped)
4799
+ return;
4800
+ if (held) {
4801
+ this.heldOnce = true;
4802
+ if (this.since === undefined)
4803
+ return;
4804
+ this.left -= Date.now() - this.since;
4805
+ this.since = undefined;
4806
+ clearTimeout(this.timer);
4807
+ } else if (this.since === undefined) {
4808
+ this.since = Date.now();
4809
+ this.timer = setTimeout(() => {
4810
+ this.stop();
4811
+ this.fail(new Error(`Timeout ${this.ms}ms exceeded.`));
4812
+ }, Math.max(0, this.left));
4813
+ }
4814
+ }
4815
+ held() {
4816
+ return !this.stopped && this.since === undefined;
4817
+ }
4818
+ wasHeld() {
4819
+ return this.heldOnce;
4820
+ }
4821
+ stop() {
4822
+ if (this.stopped)
4823
+ return;
4824
+ this.stopped = true;
4825
+ clearTimeout(this.timer);
4826
+ this.done();
4827
+ }
4828
+ }
4829
+
4830
+ class BrowserPageEvents {
4831
+ page;
4832
+ passkeyDetection;
4833
+ holdHttpAuth;
4834
+ sequence = 0;
4835
+ entries = [];
4836
+ listeners = new Set;
4837
+ changes = new Set;
4838
+ dialogListeners = new Set;
4839
+ requests = new WeakMap;
4840
+ inflight = new Map;
4841
+ frameDocuments = new Map;
4842
+ frameDocumentLoads = new WeakMap;
4843
+ frameDocumentSequence = 0;
4844
+ frameDocumentChecks = new Set;
4845
+ lastNetworkActivity;
4846
+ activity = [];
4847
+ activityDroppedAt = 0;
4848
+ choosers = new Map;
4849
+ downloads = new Map;
4850
+ assets = new Map;
4851
+ dialog;
4852
+ dialogOrigin;
4853
+ passkey;
4854
+ contextFrames = new Map;
4855
+ passkeyBinding = `__bmcpPasskey${crypto.randomUUID().replaceAll("-", "")}`;
4856
+ passkeyCancel = `bmcp-passkey-cancel-${crypto.randomUUID()}`;
4390
4857
  cdp;
4391
4858
  crashListeners = new Set;
4392
4859
  crashed = false;
@@ -4396,11 +4863,26 @@ class BrowserPageEvents {
4396
4863
  pending;
4397
4864
  currentAction;
4398
4865
  recentAction;
4866
+ httpAuth;
4867
+ deadlines = new Set;
4399
4868
  document = 0;
4400
- constructor(page, passkeyDetection = true) {
4869
+ constructor(page, passkeyDetection = true, holdHttpAuth) {
4401
4870
  this.page = page;
4402
4871
  this.passkeyDetection = passkeyDetection;
4403
- this.ready = page.context().newCDPSession(page).then((cdp) => {
4872
+ this.holdHttpAuth = holdHttpAuth;
4873
+ this.httpAuth = new HttpAuthPrompts({
4874
+ page,
4875
+ record: (kind, data) => this.record(kind, data),
4876
+ redact: diagnosticUrl,
4877
+ holds: () => !!this.holdHttpAuth?.(this.actionId() !== undefined),
4878
+ changed: (opened) => {
4879
+ if (opened)
4880
+ for (const listener of this.listeners)
4881
+ listener();
4882
+ this.dialogChanged();
4883
+ }
4884
+ });
4885
+ this.ready = page.context().newCDPSession(page).then(async (cdp) => {
4404
4886
  this.cdp = cdp;
4405
4887
  cdp.on("close", () => {
4406
4888
  if (this.cdp === cdp)
@@ -4440,6 +4922,7 @@ class BrowserPageEvents {
4440
4922
  });
4441
4923
  if (this.passkeyDetection)
4442
4924
  this.watchPasskeys(cdp);
4925
+ await this.httpAuth.watch(cdp);
4443
4926
  }).catch(() => {
4444
4927
  return;
4445
4928
  });
@@ -4459,15 +4942,20 @@ class BrowserPageEvents {
4459
4942
  this.inflight.set(r, this.isMainFrameNavigation(r));
4460
4943
  if (this.inflight.size > MAX_INFLIGHT)
4461
4944
  this.inflight.delete(this.inflight.keys().next().value);
4945
+ if (this.isFrameNavigation(r))
4946
+ this.frameDocumentStarted(r);
4462
4947
  this.lastNetworkActivity = Date.now();
4463
4948
  this.noteActivity(r, this.lastNetworkActivity);
4464
4949
  });
4465
4950
  page.on("requestfailed", (r) => {
4466
4951
  this.settleRequest(r);
4952
+ this.frameDocumentEnded(r);
4953
+ this.httpAuth.requestEnded(r, null);
4467
4954
  this.requestFinished(r, { failed: true, error: diagnosticText(r.failure()?.errorText ?? "request_failed") });
4468
4955
  });
4469
4956
  page.on("requestfinished", (r) => {
4470
4957
  this.settleRequest(r);
4958
+ this.frameDocumentEnded(r);
4471
4959
  r.response().then((response) => {
4472
4960
  this.requestFinished(r, { status: response?.status(), failed: (response?.status() ?? 0) >= 400 });
4473
4961
  }).catch(() => {
@@ -4475,6 +4963,8 @@ class BrowserPageEvents {
4475
4963
  });
4476
4964
  });
4477
4965
  page.on("response", (response) => {
4966
+ this.frameDocumentEnded(response.request());
4967
+ this.httpAuth.requestEnded(response.request(), response.status());
4478
4968
  const headers = response.headers(), size = Number(headers["content-length"]), mimeType = headers["content-type"] ?? "";
4479
4969
  if (!response.ok() || headers["content-encoding"] && headers["content-encoding"] !== "identity" || !/^(image\/|font\/|text\/css)/i.test(mimeType) || !Number.isSafeInteger(size) || size < 0 || size > 8 * 1024 * 1024)
4480
4970
  return;
@@ -4506,7 +4996,10 @@ class BrowserPageEvents {
4506
4996
  this.choosers.delete(id);
4507
4997
  }
4508
4998
  });
4509
- page.on("framedetached", () => this.dropDetachedFrameRequests());
4999
+ page.on("framedetached", () => {
5000
+ this.dropDetachedFrameRequests();
5001
+ this.dropDetachedFrameDocuments();
5002
+ });
4510
5003
  page.on("framenavigated", (frame) => {
4511
5004
  if (frame !== page.mainFrame())
4512
5005
  return;
@@ -4520,9 +5013,13 @@ class BrowserPageEvents {
4520
5013
  this.assets.clear();
4521
5014
  this.downloads.clear();
4522
5015
  this.inflight.clear();
5016
+ this.frameDocuments.clear();
5017
+ for (const check of [...this.frameDocumentChecks])
5018
+ check();
4523
5019
  this.activity = [];
4524
5020
  this.dialog = undefined;
4525
5021
  this.closePasskey("closed");
5022
+ this.httpAuth.pageClosed();
4526
5023
  this.contextFrames.clear();
4527
5024
  this.dialogListeners.clear();
4528
5025
  });
@@ -4629,7 +5126,7 @@ class BrowserPageEvents {
4629
5126
  }
4630
5127
  async flushPasskeyReports() {
4631
5128
  const cdp = this.cdp;
4632
- if (!cdp || !this.passkeyDetection || this.dialog || this.crashed)
5129
+ if (!cdp || !this.passkeyDetection || this.dialog || this.crashed || this.httpAuth.holdsMainFrame() || this.navigationLoading())
4633
5130
  return;
4634
5131
  let timer2;
4635
5132
  await Promise.race([
@@ -4701,10 +5198,15 @@ class BrowserPageEvents {
4701
5198
  const value = this.dialog?.value;
4702
5199
  if (value)
4703
5200
  return { type: value.type(), message: value.message(), defaultValue: value.defaultValue() };
5201
+ const auth = this.httpAuth.details();
5202
+ if (auth)
5203
+ return auth;
4704
5204
  const passkey = this.passkey;
4705
5205
  return passkey?.announced ? { type: "passkey", message: "", defaultValue: "", request: passkey.request, origin: passkey.origin } : null;
4706
5206
  }
4707
5207
  dialogChanged() {
5208
+ for (const deadline of this.deadlines)
5209
+ deadline.update(this.holdsNavigation());
4708
5210
  const details = this.dialogDetails();
4709
5211
  for (const listener of [...this.dialogListeners]) {
4710
5212
  try {
@@ -4719,6 +5221,67 @@ class BrowserPageEvents {
4719
5221
  return false;
4720
5222
  }
4721
5223
  }
5224
+ isFrameNavigation(request) {
5225
+ try {
5226
+ return request.isNavigationRequest() && request.frame() !== this.page.mainFrame();
5227
+ } catch {
5228
+ return false;
5229
+ }
5230
+ }
5231
+ frameDocumentStarted(request) {
5232
+ const from = request.redirectedFrom();
5233
+ const load = from && this.frameDocumentLoads.get(from) || ++this.frameDocumentSequence;
5234
+ this.frameDocumentLoads.set(request, load);
5235
+ this.frameDocuments.set(request, load);
5236
+ if (this.frameDocuments.size > MAX_FRAME_DOCUMENTS)
5237
+ this.frameDocuments.delete(this.frameDocuments.keys().next().value);
5238
+ }
5239
+ frameDocumentEnded(request) {
5240
+ if (!this.frameDocuments.delete(request))
5241
+ return;
5242
+ for (const check of [...this.frameDocumentChecks])
5243
+ check();
5244
+ }
5245
+ dropDetachedFrameDocuments() {
5246
+ for (const request of [...this.frameDocuments.keys()]) {
5247
+ let detached = true;
5248
+ try {
5249
+ detached = request.frame().isDetached();
5250
+ } catch {}
5251
+ if (detached)
5252
+ this.frameDocumentEnded(request);
5253
+ }
5254
+ }
5255
+ frameDocumentMark() {
5256
+ return this.frameDocumentSequence;
5257
+ }
5258
+ framesSettled(mark, pageUrl, ms) {
5259
+ const origin = httpOrigin(pageUrl);
5260
+ if (!origin)
5261
+ return Promise.resolve();
5262
+ const begun = this.frameDocumentSequence;
5263
+ const waiting = () => {
5264
+ for (const [request, load] of this.frameDocuments)
5265
+ if (load > mark && load <= begun && httpOrigin(requestUrl(request)) === origin)
5266
+ return true;
5267
+ return false;
5268
+ };
5269
+ if (!waiting())
5270
+ return Promise.resolve();
5271
+ return new Promise((resolve2) => {
5272
+ const done = () => {
5273
+ clearTimeout(timer2);
5274
+ this.frameDocumentChecks.delete(check);
5275
+ resolve2();
5276
+ };
5277
+ const check = () => {
5278
+ if (!waiting())
5279
+ done();
5280
+ };
5281
+ const timer2 = setTimeout(done, ms);
5282
+ this.frameDocumentChecks.add(check);
5283
+ });
5284
+ }
4722
5285
  settleRequest(request) {
4723
5286
  if (this.inflight.delete(request)) {
4724
5287
  this.lastNetworkActivity = Date.now();
@@ -4804,6 +5367,22 @@ class BrowserPageEvents {
4804
5367
  session() {
4805
5368
  return this.cdp;
4806
5369
  }
5370
+ navigationLoading() {
5371
+ return !!pendingNavigation(this.page);
5372
+ }
5373
+ async loadingPage() {
5374
+ const pending = pendingNavigation(this.page);
5375
+ const cdp = this.cdp;
5376
+ if (!pending || !cdp)
5377
+ return;
5378
+ let timer2;
5379
+ const answered = await Promise.race([
5380
+ cdp.send("Runtime.evaluate", { expression: "0", silent: true }).then(() => true, () => true),
5381
+ new Promise((resolve2) => timer2 = setTimeout(() => resolve2(false), LOADING_PROBE_MS))
5382
+ ]);
5383
+ clearTimeout(timer2);
5384
+ return answered ? undefined : { url: diagnosticUrl(pending.url), pendingMs: Math.max(0, Date.now() - pending.since) };
5385
+ }
4807
5386
  setCrashed(crashed) {
4808
5387
  this.crashed = crashed;
4809
5388
  if (!crashed)
@@ -4901,196 +5480,784 @@ class BrowserPageEvents {
4901
5480
  category: "page"
4902
5481
  };
4903
5482
  }
4904
- async waitQuery(input) {
4905
- const first = this.query(input, false);
4906
- if (first.entries.length || !input.timeoutMs)
4907
- return first;
4908
- let timer2, changed;
5483
+ async waitQuery(input) {
5484
+ const first = this.query(input, false);
5485
+ if (first.entries.length || !input.timeoutMs)
5486
+ return first;
5487
+ let timer2, changed;
5488
+ try {
5489
+ return await new Promise((resolve2) => {
5490
+ changed = () => {
5491
+ const result = this.query(input, false);
5492
+ if (result.entries.length)
5493
+ resolve2(result);
5494
+ };
5495
+ this.changes.add(changed);
5496
+ timer2 = setTimeout(() => resolve2(this.query(input, false)), Number(input.timeoutMs));
5497
+ changed();
5498
+ });
5499
+ } finally {
5500
+ clearTimeout(timer2);
5501
+ this.changes.delete(changed);
5502
+ }
5503
+ }
5504
+ activeDialog() {
5505
+ if (this.dialog)
5506
+ return { ...this.dialog.event, dialogId: this.dialog.event.eventId };
5507
+ const auth = this.httpAuth.event();
5508
+ return auth ? { ...auth, dialogId: auth.eventId } : null;
5509
+ }
5510
+ javascriptDialogOpen() {
5511
+ return !!this.dialog;
5512
+ }
5513
+ httpAuthPrompt() {
5514
+ return this.httpAuth.prompt();
5515
+ }
5516
+ handHttpAuthToChrome(reason) {
5517
+ this.httpAuth.handToChrome(reason);
5518
+ }
5519
+ pendingAction() {
5520
+ return this.pending ? { actionId: this.pending.actionId, status: "pending" } : null;
5521
+ }
5522
+ markUnanswered() {
5523
+ if (this.pending)
5524
+ this.pending.unanswered = true;
5525
+ }
5526
+ holdsNavigation() {
5527
+ return !!this.dialog || this.httpAuth.isOpen();
5528
+ }
5529
+ navigationDeadline(ms) {
5530
+ const deadline = new NavigationDeadline(ms, this.holdsNavigation(), () => this.deadlines.delete(deadline));
5531
+ this.deadlines.add(deadline);
5532
+ return deadline;
5533
+ }
5534
+ async handleDialog(input, handledBy = "agent", options = {}) {
5535
+ const held = this.pending;
5536
+ const auth = await this.httpAuth.answer(input.dialogId, input, handledBy === "viewer" ? { by: "viewer", typed: options.typed } : {
5537
+ by: "agent",
5538
+ vaultId: typeof input.vaultId === "string" ? input.vaultId : undefined,
5539
+ names: input.names,
5540
+ expectedOrigin: typeof input.expectedOrigin === "string" ? input.expectedOrigin : undefined,
5541
+ reveal: options.reveal
5542
+ });
5543
+ if (auth) {
5544
+ const pending2 = held ?? this.pending;
5545
+ const outcome2 = auth.handled === true && auth.signIn !== "rejected" && pending2 ? await this.racePending(pending2, 1000) : undefined;
5546
+ return { ...auth, ...auth.handled === true ? { originalAction: outcome2 ?? this.pendingAction() } : {}, dialog: this.activeDialog() };
5547
+ }
5548
+ if (signsInWithVault(input))
5549
+ return {
5550
+ handled: false,
5551
+ code: this.dialog?.event.eventId === input.dialogId || this.passkey?.event.eventId === input.dialogId ? "not_http_auth" : "stale_dialog",
5552
+ dialog: this.activeDialog(),
5553
+ recovery: "vaultId, names and expectedOrigin answer only an HTTP sign-in (a dialog of type http_auth) that is still open. Read browser_events for the open dialog."
5554
+ };
5555
+ const passkey = this.passkey;
5556
+ if (passkey && input.dialogId === passkey.event.eventId) {
5557
+ if (input.decision !== "dismiss" || input.promptText !== undefined)
5558
+ return { handled: false, code: "passkey_requires_user", passkeyPrompt: this.passkeyPrompt(), recovery: PASSKEY_PROMPT_RECOVERY };
5559
+ if (this.dialog)
5560
+ return {
5561
+ handled: false,
5562
+ code: "dialog_blocking",
5563
+ dialog: this.activeDialog(),
5564
+ passkeyPrompt: this.passkeyPrompt(),
5565
+ recovery: "The page also shows a JavaScript dialog. Handle that dialog first, then cancel the passkey prompt."
5566
+ };
5567
+ if (await this.cancelPasskey(handledBy))
5568
+ return { handled: true, dialogId: input.dialogId, decision: "dismiss", type: "passkey" };
5569
+ return {
5570
+ handled: false,
5571
+ code: "passkey_cancel_unconfirmed",
5572
+ passkeyPrompt: this.passkeyPrompt(),
5573
+ 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.'
5574
+ };
5575
+ }
5576
+ const current = this.dialog;
5577
+ if (!current || current.event.eventId !== input.dialogId)
5578
+ return { handled: false, code: "stale_dialog", dialog: this.activeDialog() };
5579
+ if (input.promptText !== undefined && (current.value.type() !== "prompt" || input.decision !== "accept"))
5580
+ return { handled: false, code: "prompt_text_requires_accept_prompt" };
5581
+ current.event.handledBy = handledBy;
5582
+ const accept = input.decision === "accept";
5583
+ if (this.rendererCrashed && this.cdp)
5584
+ await this.cdp.send("Page.handleJavaScriptDialog", { accept, ...input.promptText !== undefined ? { promptText: String(input.promptText) } : {} });
5585
+ else
5586
+ await (accept ? current.value.accept(input.promptText) : current.value.dismiss());
5587
+ current.event.state = input.decision === "accept" ? "accepted" : "dismissed";
5588
+ if (this.dialog === current) {
5589
+ this.dialog = undefined;
5590
+ this.dialogChanged();
5591
+ }
5592
+ const pending = held ?? this.pending;
5593
+ const outcome = pending ? await this.racePending(pending, 1000) : undefined;
5594
+ return {
5595
+ handled: true,
5596
+ dialogId: input.dialogId,
5597
+ decision: input.decision,
5598
+ originalAction: outcome ?? this.pendingAction(),
5599
+ dialog: this.activeDialog()
5600
+ };
5601
+ }
5602
+ async racePending(pending, ms) {
5603
+ let timer2;
5604
+ try {
5605
+ return await Promise.race([
5606
+ pending.result,
5607
+ new Promise((resolve2) => {
5608
+ timer2 = setTimeout(() => resolve2(undefined), ms);
5609
+ })
5610
+ ]);
5611
+ } finally {
5612
+ clearTimeout(timer2);
5613
+ }
5614
+ }
5615
+ async run(actionId, dispatch) {
5616
+ const holding = !!this.dialog || this.httpAuth.isOpen();
5617
+ if (holding || this.pending) {
5618
+ const httpAuth = this.dialog ? null : this.httpAuth.prompt();
5619
+ return {
5620
+ dispatch: { status: "not_dispatched", code: holding ? "dialog_blocking" : "previous_action_pending" },
5621
+ dialog: this.activeDialog(),
5622
+ ...httpAuth ? { httpAuth, recovery: HTTP_AUTH_RECOVERY } : {},
5623
+ pendingAction: this.pendingAction()
5624
+ };
5625
+ }
5626
+ this.currentAction = actionId;
5627
+ let interruptedByDialog = false;
5628
+ let wake;
5629
+ const interrupted = new Promise((resolve2) => {
5630
+ wake = () => {
5631
+ interruptedByDialog = true;
5632
+ const auth = this.dialog ? undefined : this.httpAuth.requiredResult(actionId);
5633
+ resolve2(auth ?? { dispatch: { status: "blocked", actionId, code: "dialog_open" }, dialog: this.activeDialog() });
5634
+ };
5635
+ this.listeners.add(wake);
5636
+ });
5637
+ const pending = { actionId, settled: false, result: Promise.resolve({}) };
5638
+ const work = Promise.resolve().then(dispatch);
5639
+ pending.result = work.then((result) => {
5640
+ if (interruptedByDialog)
5641
+ this.record("action", { actionId, status: "completed", outcomeVerified: false });
5642
+ return { actionId, status: "completed", result };
5643
+ }, () => {
5644
+ const code2 = pending.unanswered ? "dialog_unanswered" : "executor_uncertain";
5645
+ if (interruptedByDialog)
5646
+ this.record("action", { actionId, status: "unknown", code: code2, retrySafe: false });
5647
+ return { actionId, status: "unknown", code: code2, retrySafe: false };
5648
+ }).finally(() => {
5649
+ pending.settled = true;
5650
+ if (this.pending === pending)
5651
+ this.pending = undefined;
5652
+ this.recentAction = { id: actionId, at: Date.now() };
5653
+ this.currentAction = undefined;
5654
+ this.listeners.delete(wake);
5655
+ });
5656
+ this.pending = pending;
5657
+ return await Promise.race([work, interrupted]);
5658
+ }
5659
+ startDownload(download, downloadId) {
5660
+ const event = this.record("download", {
5661
+ state: "started",
5662
+ downloadId,
5663
+ resourceId: downloadId,
5664
+ readiness: "pending",
5665
+ filename: download.suggestedFilename().slice(0, 255),
5666
+ url: diagnosticUrl(download.url())
5667
+ });
5668
+ this.downloads.set(event.eventId, download);
5669
+ return (data) => {
5670
+ this.record("download", { ...data, downloadId, resourceId: downloadId, transferId: event.eventId, actionId: event.actionId, filename: event.filename });
5671
+ this.downloads.delete(event.eventId);
5672
+ };
5673
+ }
5674
+ chooser(id) {
5675
+ const value = this.choosers.get(id);
5676
+ if (!value || value.document !== this.document || value.event.state !== "open")
5677
+ throw uploadRefusal.chooserExpired();
5678
+ value.event.state = "claimed";
5679
+ this.choosers.delete(id);
5680
+ return value.element;
5681
+ }
5682
+ clearChoosers() {
5683
+ for (const c of this.choosers.values()) {
5684
+ c.event.state = "expired";
5685
+ c.element.dispose().catch(() => {
5686
+ return;
5687
+ });
5688
+ }
5689
+ this.choosers.clear();
5690
+ }
5691
+ async cancelTransfer(id) {
5692
+ const download = this.downloads.get(id), chooser = this.choosers.get(id);
5693
+ if (download) {
5694
+ await download.cancel();
5695
+ return { cancelled: true, eventId: id };
5696
+ }
5697
+ if (chooser) {
5698
+ chooser.event.state = "cancelled";
5699
+ this.choosers.delete(id);
5700
+ await chooser.element.dispose();
5701
+ return { cancelled: true, eventId: id };
5702
+ }
5703
+ return { cancelled: false, code: "transfer_not_active" };
5704
+ }
5705
+ listAssets() {
5706
+ return [...this.assets].map(([assetId, a]) => ({ assetId, url: a.url, size: a.size, mimeType: a.mimeType }));
5707
+ }
5708
+ async assetBytes(id) {
5709
+ const asset = this.assets.get(id);
5710
+ if (!asset || asset.document !== this.document)
5711
+ throw new Error("Asset is no longer in the current document's observed responses.");
5712
+ const body = await asset.response.body();
5713
+ if (body.length > 8 * 1024 * 1024 || body.length > asset.size)
5714
+ throw new Error("Asset exceeds declared size or 8 MiB.");
5715
+ return { bytes: body, mimeType: asset.mimeType };
5716
+ }
5717
+ }
5718
+
5719
+ // cli/src/browser/navigation-observer.ts
5720
+ function navigationUrlMatches(pattern, url) {
5721
+ if (!pattern)
5722
+ return true;
5723
+ const source = pattern.split(/(\*\*|\*)/).map((part) => part === "**" ? ".*" : part === "*" ? "[^/]*" : part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("");
5724
+ return new RegExp(`^${source}$`).test(url);
5725
+ }
5726
+ function observeNavigation(page, input, events) {
5727
+ const started = Date.now();
5728
+ const deadline = events?.navigationDeadline(input.timeoutMs);
5729
+ const bound = started + input.timeoutMs + (deadline ? DIALOG_WAIT_MS : 0);
5730
+ const since = commitsHeard(page);
5731
+ let settled = false;
5732
+ let resolve2;
5733
+ const result = new Promise((done) => {
5734
+ resolve2 = done;
5735
+ });
5736
+ const finish = (matched, code2, error) => {
5737
+ if (settled)
5738
+ return;
5739
+ settled = true;
5740
+ clearTimeout(timer2);
5741
+ deadline?.stop();
5742
+ page.off("framenavigated", onNavigation);
5743
+ page.off("close", onClose);
5744
+ page.off("crash", onClose);
5745
+ resolve2({ matched, url: page.url(), elapsedMs: Date.now() - started, waitUntil: input.waitUntil, ...code2 ? { code: code2, error } : {} });
5746
+ };
5747
+ const onClose = () => finish(false, "navigation_tab_closed", "The tab closed before navigation was observed. Inspect tabs before another action.");
5748
+ const onNavigation = (frame) => {
5749
+ if (frame !== page.mainFrame() || !navigationUrlMatches(input.url, frame.url()))
5750
+ return;
5751
+ if (input.waitUntil === "commit") {
5752
+ finish(true);
5753
+ return;
5754
+ }
5755
+ waitForLoadState(page, input.waitUntil, Math.max(1, bound - Date.now()), since).then(() => {
5756
+ if (navigationUrlMatches(input.url, page.url()))
5757
+ finish(true);
5758
+ }, () => {
5759
+ return;
5760
+ });
5761
+ };
5762
+ const timedOut = () => finish(false, "navigation_timeout", "Input was dispatched, but the expected navigation was not observed before the deadline. Inspect the page; do not repeat the action solely because this wait timed out.");
5763
+ deadline?.expired.catch(timedOut);
5764
+ const timer2 = setTimeout(() => deadline?.held() ? finish(false, "dialog_unanswered", "Input was dispatched, but a dialog that nobody answered still holds the expected navigation. Read browser_events for the dialog and answer or dismiss it; do not repeat the action.") : timedOut(), bound - started);
5765
+ page.on("framenavigated", onNavigation);
5766
+ page.on("close", onClose);
5767
+ page.on("crash", onClose);
5768
+ return { result, dispose: () => finish(false, "navigation_observation_cancelled", "Navigation observation ended.") };
5769
+ }
5770
+
5771
+ // cli/src/browser/frame-history.ts
5772
+ var POLL_MS = 50;
5773
+ var UNSEEN_COMMIT_MS = 300;
5774
+ var FRAME_LOADED_MS = 5000;
5775
+ async function traverseToEntry(page, cdp, entryId, timeoutMs, expired) {
5776
+ const deadline = Date.now() + timeoutMs;
5777
+ const mainId = await cdp.send("Page.getFrameTree").then(({ frameTree }) => frameTree.frame.id, () => {
5778
+ return;
5779
+ });
5780
+ let mainSeen = false;
5781
+ let childSeen = false;
5782
+ let sameDocument = false;
5783
+ let childFrame;
5784
+ let response = null;
5785
+ let reachedAt;
5786
+ let settle;
5787
+ const committed = new Promise((resolve2, reject) => {
5788
+ let settled = false;
5789
+ settle = (value) => {
5790
+ if (settled)
5791
+ return;
5792
+ settled = true;
5793
+ stop();
5794
+ if (value instanceof Error)
5795
+ reject(value);
5796
+ else
5797
+ resolve2(value);
5798
+ };
5799
+ });
5800
+ const decide = () => {
5801
+ if (mainSeen)
5802
+ settle("main");
5803
+ else if (reachedAt !== undefined && (childSeen || Date.now() - reachedAt >= UNSEEN_COMMIT_MS))
5804
+ settle("child");
5805
+ };
5806
+ const readEntry = () => void cdp.send("Page.getNavigationHistory").then(({ currentIndex, entries }) => {
5807
+ if (entries[currentIndex]?.id === entryId)
5808
+ reachedAt ??= Date.now();
5809
+ decide();
5810
+ }, () => {
5811
+ return;
5812
+ });
5813
+ const seen = (main) => {
5814
+ if (main)
5815
+ mainSeen = true;
5816
+ else
5817
+ childSeen = true;
5818
+ if (mainSeen)
5819
+ decide();
5820
+ else
5821
+ readEntry();
5822
+ };
5823
+ const onFrameNavigated = (frame) => {
5824
+ if (frame !== page.mainFrame())
5825
+ childFrame = frame;
5826
+ seen(frame === page.mainFrame());
5827
+ };
5828
+ const onResponse = (candidate) => {
5829
+ if (candidate.frame() === page.mainFrame() && candidate.request().isNavigationRequest())
5830
+ response = candidate;
5831
+ };
5832
+ const onClose = () => settle(new Error("Target page, context or browser has been closed"));
5833
+ const onCrash = () => settle(new Error("Target crashed"));
5834
+ const onCommit = ({ frame }) => seen(!frame.parentId);
5835
+ const onWithinDocument = ({ frameId }) => {
5836
+ if (mainId === undefined)
5837
+ return;
5838
+ if (frameId !== mainId)
5839
+ sameDocument = true;
5840
+ seen(frameId === mainId);
5841
+ };
5842
+ page.on("framenavigated", onFrameNavigated);
5843
+ page.on("response", onResponse);
5844
+ page.on("close", onClose);
5845
+ page.on("crash", onCrash);
5846
+ cdp.on("Page.frameNavigated", onCommit);
5847
+ cdp.on("Page.navigatedWithinDocument", onWithinDocument);
5848
+ const poll = setInterval(readEntry, POLL_MS);
5849
+ const timer2 = setTimeout(() => settle(new Error(`Timeout ${timeoutMs}ms exceeded waiting for the history entry to commit.`)), Math.max(1, deadline - Date.now()));
5850
+ expired?.catch((error) => settle(error instanceof Error ? error : new Error(String(error))));
5851
+ function stop() {
5852
+ clearInterval(poll);
5853
+ clearTimeout(timer2);
5854
+ page.off("framenavigated", onFrameNavigated);
5855
+ page.off("response", onResponse);
5856
+ page.off("close", onClose);
5857
+ page.off("crash", onCrash);
5858
+ cdp.off("Page.frameNavigated", onCommit);
5859
+ cdp.off("Page.navigatedWithinDocument", onWithinDocument);
5860
+ }
5861
+ await cdp.send("Page.navigateToHistoryEntry", { entryId }).catch((error) => settle(error instanceof Error ? error : new Error(String(error))));
5862
+ if (await committed === "main")
5863
+ return { frame: "main", response };
5864
+ if (childFrame && !sameDocument && !childFrame.isDetached())
5865
+ await childFrame.waitForLoadState("domcontentloaded", { timeout: Math.max(1, Math.min(FRAME_LOADED_MS, deadline - Date.now())) }).catch(() => {
5866
+ return;
5867
+ });
5868
+ return { frame: "child" };
5869
+ }
5870
+
5871
+ // cli/src/browser/frame-position.ts
5872
+ import { createRequire as createRequire3 } from "node:module";
5873
+ var requirePlaywright3 = createRequire3(import.meta.url);
5874
+ var SUPPORTED_PLAYWRIGHT_VERSION3 = "1.63.0";
5875
+ var WRAPPED = Symbol.for("browser-mcp.cross-site-frame-position");
5876
+ function contentOffset(model) {
5877
+ const border = model?.border, content = model?.content;
5878
+ const quad = (value) => Array.isArray(value) && value.length === 8 && value.every((n) => typeof n === "number" && Number.isFinite(n));
5879
+ if (!quad(border) || !quad(content))
5880
+ return;
5881
+ const upright = (q) => q[0] === q[6] && q[2] === q[4] && q[1] === q[3] && q[5] === q[7];
5882
+ if (!upright(border) || !upright(content))
5883
+ return;
5884
+ const x = content[0] - border[0], y = content[1] - border[1];
5885
+ return x >= 0 && y >= 0 ? { x, y } : undefined;
5886
+ }
5887
+ async function contentBoxPosition(session, position) {
5888
+ if (!position)
5889
+ return position;
5890
+ try {
5891
+ const frame = session._page.frameManager.frame(session._targetId);
5892
+ const parent = frame?.parentFrame();
5893
+ if (!frame || !parent)
5894
+ return position;
5895
+ const { _client: client } = session._crPage._sessionForFrame(parent);
5896
+ const { backendNodeId } = await client.send("DOM.getFrameOwner", { frameId: frame._id });
5897
+ const { model } = await client.send("DOM.getBoxModel", { backendNodeId });
5898
+ const offset = contentOffset(model);
5899
+ return offset ? { ...position, x: position.x + offset.x, y: position.y + offset.y } : position;
5900
+ } catch {
5901
+ return position;
5902
+ }
5903
+ }
5904
+ function correctCrossSiteFramePositions(page) {
5905
+ try {
5906
+ if (requirePlaywright3("playwright-core/package.json").version !== SUPPORTED_PLAYWRIGHT_VERSION3)
5907
+ return;
5908
+ const connection = page._connection;
5909
+ const server = typeof connection?.toImpl === "function" ? connection.toImpl(page) : undefined;
5910
+ const session = server?.delegate?._mainFrameSession;
5911
+ if (!session || typeof session._targetId !== "string" || typeof session._crPage?._sessionForFrame !== "function" || typeof session._page?.frameManager?.frame !== "function")
5912
+ return;
5913
+ const prototype = Object.getPrototypeOf(session);
5914
+ const original = prototype._framePosition;
5915
+ if (prototype[WRAPPED] || typeof original !== "function" || original.length !== 0)
5916
+ return;
5917
+ prototype._framePosition = async function() {
5918
+ return await contentBoxPosition(this, await original.call(this));
5919
+ };
5920
+ prototype[WRAPPED] = true;
5921
+ } catch {}
5922
+ }
5923
+
5924
+ // cli/src/browser/frame-input.ts
5925
+ var MODIFIER_BITS = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
5926
+ var BUTTON_BITS = { left: 1, right: 2, middle: 4 };
5927
+ var DRAG_HANDOVER_MS = 150;
5928
+ function modifierBits(modifiers) {
5929
+ let bits = 0;
5930
+ for (const modifier of modifiers)
5931
+ bits |= MODIFIER_BITS[modifier === "ControlOrMeta" ? process.platform === "darwin" ? "Meta" : "Control" : modifier];
5932
+ return bits;
5933
+ }
5934
+ function buttonBits(buttons) {
5935
+ let bits = 0;
5936
+ for (const button of buttons)
5937
+ bits |= BUTTON_BITS[button];
5938
+ return bits;
5939
+ }
5940
+ function frameOrigin(iframe) {
5941
+ const view = iframe.ownerDocument?.defaultView;
5942
+ if (!iframe.isConnected || !view)
5943
+ return "detached";
5944
+ const zoom = iframe.currentCSSZoom;
5945
+ if (zoom !== undefined && zoom !== 1)
5946
+ return "transformed";
5947
+ for (let node = iframe;node; node = node.parentElement ?? (node.getRootNode().host || null)) {
5948
+ const style2 = view.getComputedStyle(node);
5949
+ if (style2.transform !== "none" || style2.scale !== "none" || style2.rotate !== "none" || style2.translate !== "none")
5950
+ return "transformed";
5951
+ }
5952
+ const box = iframe.getBoundingClientRect();
5953
+ const style = view.getComputedStyle(iframe);
5954
+ return { x: box.left + iframe.clientLeft + Number.parseFloat(style.paddingLeft), y: box.top + iframe.clientTop + Number.parseFloat(style.paddingTop) };
5955
+ }
5956
+ function parentHit(iframe, options) {
5957
+ const root = iframe.getRootNode();
5958
+ const view = iframe.ownerDocument.defaultView;
5959
+ const { point } = options;
5960
+ if (point.x < 0 || point.y < 0 || point.x >= view.innerWidth || point.y >= view.innerHeight)
5961
+ return "outside";
5962
+ const hit = root.elementFromPoint(point.x, point.y);
5963
+ if (!hit)
5964
+ return "outside";
5965
+ if (hit === iframe)
5966
+ return null;
5967
+ const parentOf = (node) => node.parentElement ?? (node.getRootNode().host || null);
5968
+ const summarize = (node) => {
5969
+ const role = node.getAttribute("role") ?? undefined;
5970
+ const field = node.tagName === "INPUT" || node.tagName === "TEXTAREA" || node.tagName === "SELECT";
5971
+ const password = node.tagName === "INPUT" && node.type === "password";
5972
+ const raw = node.getAttribute("aria-label") ?? node.getAttribute("title") ?? (field ? [...node.labels ?? []][0]?.textContent || (password ? "" : node.getAttribute("placeholder") ?? "") : node.textContent ?? "");
5973
+ const name = raw.replace(/\s+/g, " ").trim().slice(0, options.nameChars);
5974
+ return { tag: node.tagName.toLowerCase(), ...role ? { role } : {}, ...name ? { name } : {} };
5975
+ };
5976
+ let layer;
5977
+ const doc = iframe.ownerDocument;
5978
+ for (let node = hit;node && node !== doc.body && node !== doc.documentElement; node = parentOf(node)) {
5979
+ const s = view.getComputedStyle(node);
5980
+ if (node.matches('dialog, [role="dialog"], [role="alertdialog"], [aria-modal="true"], [role="menu"], [role="listbox"], [role="tooltip"], [role="alert"], [role="banner"], [role="region"], header, nav, aside, footer') || s.position === "fixed" || s.position === "sticky") {
5981
+ layer = node;
5982
+ break;
5983
+ }
5984
+ }
5985
+ return {
5986
+ cover: summarize(hit),
5987
+ ...layer && layer !== hit ? { layer: summarize(layer) } : {},
5988
+ ...view.getComputedStyle(iframe).pointerEvents === "none" ? { passThrough: true } : {}
5989
+ };
5990
+ }
5991
+ function iframeAt(point) {
5992
+ let hit = document.elementFromPoint(point.x, point.y);
5993
+ while (hit?.shadowRoot) {
5994
+ const inner = hit.shadowRoot.elementFromPoint(point.x, point.y);
5995
+ if (!inner || inner === hit)
5996
+ break;
5997
+ hit = inner;
5998
+ }
5999
+ if (!hit || hit.tagName !== "IFRAME" && hit.tagName !== "FRAME")
6000
+ return null;
6001
+ const box = hit.getBoundingClientRect();
6002
+ const style = getComputedStyle(hit);
6003
+ const left = box.left + hit.clientLeft + Number.parseFloat(style.paddingLeft);
6004
+ const top = box.top + hit.clientTop + Number.parseFloat(style.paddingTop);
6005
+ const width = hit.clientWidth - Number.parseFloat(style.paddingLeft) - Number.parseFloat(style.paddingRight);
6006
+ const height = hit.clientHeight - Number.parseFloat(style.paddingTop) - Number.parseFloat(style.paddingBottom);
6007
+ return point.x >= left && point.y >= top && point.x < left + width && point.y < top + height ? hit : null;
6008
+ }
6009
+ async function frameChain(handle) {
6010
+ const chain = [];
6011
+ const frame = await handle.ownerFrame().catch(() => null);
6012
+ for (let node = frame;node?.parentFrame(); node = node.parentFrame())
6013
+ chain.push(node);
6014
+ return chain;
6015
+ }
6016
+ async function framePath(chain, point, nameChars, inRoot = 1) {
6017
+ let current = point;
6018
+ let root = point;
6019
+ for (let index = 0;index < chain.length; index++) {
6020
+ if (index === inRoot - 1)
6021
+ root = current;
6022
+ const iframe = await chain[index].frameElement().catch(() => {
6023
+ return;
6024
+ });
6025
+ if (!iframe)
6026
+ return;
6027
+ try {
6028
+ const origin = await iframe.evaluate(frameOrigin);
6029
+ if (origin === "transformed" || origin === "detached")
6030
+ return;
6031
+ current = { x: current.x + origin.x, y: current.y + origin.y };
6032
+ const hit = await iframe.evaluate(parentHit, { point: current, nameChars });
6033
+ if (hit === "outside")
6034
+ return { kind: "outside_viewport" };
6035
+ if (hit)
6036
+ return { kind: "covered", ...hit };
6037
+ } catch {
6038
+ return;
6039
+ } finally {
6040
+ iframe.dispose().catch(() => {
6041
+ return;
6042
+ });
6043
+ }
6044
+ }
6045
+ return { kind: "reached", root, page: current };
6046
+ }
6047
+ async function revealFrames(chain, timeout2) {
6048
+ for (const frame of chain.toReversed()) {
6049
+ const iframe = await frame.frameElement().catch(() => {
6050
+ return;
6051
+ });
6052
+ if (!iframe)
6053
+ return;
4909
6054
  try {
4910
- return await new Promise((resolve2) => {
4911
- changed = () => {
4912
- const result = this.query(input, false);
4913
- if (result.entries.length)
4914
- resolve2(result);
4915
- };
4916
- this.changes.add(changed);
4917
- timer2 = setTimeout(() => resolve2(this.query(input, false)), Number(input.timeoutMs));
4918
- changed();
6055
+ await iframe.scrollIntoViewIfNeeded({ timeout: timeout2 });
6056
+ } catch {} finally {
6057
+ iframe.dispose().catch(() => {
6058
+ return;
4919
6059
  });
4920
- } finally {
4921
- clearTimeout(timer2);
4922
- this.changes.delete(changed);
4923
6060
  }
4924
6061
  }
4925
- activeDialog() {
4926
- return this.dialog ? { ...this.dialog.event, dialogId: this.dialog.event.eventId } : null;
6062
+ }
6063
+
6064
+ class FrameTarget {
6065
+ page;
6066
+ frame;
6067
+ session;
6068
+ constructor(page, frame, session) {
6069
+ this.page = page;
6070
+ this.frame = frame;
6071
+ this.session = session;
4927
6072
  }
4928
- pendingAction() {
4929
- return this.pending ? { actionId: this.pending.actionId, status: "pending" } : null;
6073
+ static async open(page, frame) {
6074
+ const session = await page.context().newCDPSession(frame).catch(() => {
6075
+ return;
6076
+ });
6077
+ return session && new FrameTarget(page, frame, session);
4930
6078
  }
4931
- async handleDialog(input, handledBy = "agent") {
4932
- const passkey = this.passkey;
4933
- if (passkey && input.dialogId === passkey.event.eventId) {
4934
- if (input.decision !== "dismiss" || input.promptText !== undefined)
4935
- return { handled: false, code: "passkey_requires_user", passkeyPrompt: this.passkeyPrompt(), recovery: PASSKEY_PROMPT_RECOVERY };
4936
- if (this.dialog)
4937
- return {
4938
- handled: false,
4939
- code: "dialog_blocking",
4940
- dialog: this.activeDialog(),
4941
- passkeyPrompt: this.passkeyPrompt(),
4942
- recovery: "The page also shows a JavaScript dialog. Handle that dialog first, then cancel the passkey prompt."
4943
- };
4944
- if (await this.cancelPasskey(handledBy))
4945
- return { handled: true, dialogId: input.dialogId, decision: "dismiss", type: "passkey" };
4946
- return {
4947
- handled: false,
4948
- code: "passkey_cancel_unconfirmed",
4949
- passkeyPrompt: this.passkeyPrompt(),
4950
- 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.'
4951
- };
6079
+ static async forElement(page, chain) {
6080
+ if (!showsRestoredDocument(page) || !chain.length)
6081
+ return;
6082
+ for (let index = 0;index < chain.length; index++) {
6083
+ const target2 = await FrameTarget.open(page, chain[index]);
6084
+ if (target2)
6085
+ return { target: target2, inRoot: index + 1 };
4952
6086
  }
4953
- const current = this.dialog;
4954
- if (!current || current.event.eventId !== input.dialogId)
4955
- return { handled: false, code: "stale_dialog", dialog: this.activeDialog() };
4956
- if (input.promptText !== undefined && (current.value.type() !== "prompt" || input.decision !== "accept"))
4957
- return { handled: false, code: "prompt_text_requires_accept_prompt" };
4958
- current.event.handledBy = handledBy;
4959
- const accept = input.decision === "accept";
4960
- if (this.rendererCrashed && this.cdp)
4961
- await this.cdp.send("Page.handleJavaScriptDialog", { accept, ...input.promptText !== undefined ? { promptText: String(input.promptText) } : {} });
4962
- else
4963
- await (accept ? current.value.accept(input.promptText) : current.value.dismiss());
4964
- current.event.state = input.decision === "accept" ? "accepted" : "dismissed";
4965
- if (this.dialog === current) {
4966
- this.dialog = undefined;
4967
- this.dialogChanged();
6087
+ return;
6088
+ }
6089
+ static async at(page, point, reuse) {
6090
+ if (!showsRestoredDocument(page))
6091
+ return;
6092
+ const path9 = [];
6093
+ let frame = page.mainFrame();
6094
+ let local = point;
6095
+ for (let depth = 0;depth < 8; depth++) {
6096
+ const found = await frame.evaluateHandle(iframeAt, local).catch(() => {
6097
+ return;
6098
+ });
6099
+ const iframe = found?.asElement();
6100
+ if (!iframe) {
6101
+ found?.dispose().catch(() => {
6102
+ return;
6103
+ });
6104
+ break;
6105
+ }
6106
+ try {
6107
+ const origin = await iframe.evaluate(frameOrigin).catch(() => "detached");
6108
+ if (origin === "transformed")
6109
+ return;
6110
+ const child = origin === "detached" ? null : await iframe.contentFrame().catch(() => null);
6111
+ if (!child || origin === "detached")
6112
+ break;
6113
+ local = { x: local.x - origin.x, y: local.y - origin.y };
6114
+ frame = child;
6115
+ path9.push({ frame, local });
6116
+ } finally {
6117
+ iframe.dispose().catch(() => {
6118
+ return;
6119
+ });
6120
+ }
4968
6121
  }
4969
- const pending = this.pending;
4970
- const outcome = pending ? await this.racePending(pending, 1000) : undefined;
4971
- return {
4972
- handled: true,
4973
- dialogId: input.dialogId,
4974
- decision: input.decision,
4975
- originalAction: outcome ?? this.pendingAction(),
4976
- dialog: this.activeDialog()
4977
- };
6122
+ for (const step of path9.toReversed()) {
6123
+ const offset = { x: point.x - step.local.x, y: point.y - step.local.y };
6124
+ if (reuse && reuse.frame === step.frame)
6125
+ return { target: reuse, local: step.local, offset };
6126
+ const target2 = await FrameTarget.open(page, step.frame);
6127
+ if (target2)
6128
+ return { target: target2, local: step.local, offset };
6129
+ }
6130
+ return;
4978
6131
  }
4979
- async racePending(pending, ms) {
4980
- let timer2;
6132
+ mouse(type, point, extra) {
6133
+ return this.session.send("Input.dispatchMouseEvent", { type, x: point.x, y: point.y, ...extra });
6134
+ }
6135
+ move(point, buttons = 0, modifiers = 0) {
6136
+ const button = buttons & BUTTON_BITS.left ? "left" : buttons & BUTTON_BITS.right ? "right" : buttons & BUTTON_BITS.middle ? "middle" : "none";
6137
+ return this.mouse("mouseMoved", point, { button, buttons, modifiers });
6138
+ }
6139
+ press(point, button, clickCount, buttons, modifiers = 0) {
6140
+ return this.mouse("mousePressed", point, { button, buttons, clickCount, modifiers });
6141
+ }
6142
+ release(point, button, clickCount, buttons, modifiers = 0) {
6143
+ return this.mouse("mouseReleased", point, { button, buttons, clickCount, modifiers });
6144
+ }
6145
+ wheel(point, deltaX, deltaY, modifiers = 0) {
6146
+ return this.mouse("mouseWheel", point, { deltaX, deltaY, modifiers });
6147
+ }
6148
+ async click(point, button, clickCount) {
6149
+ await this.move(point);
6150
+ for (let count = 1;count <= clickCount; count++) {
6151
+ await this.press(point, button, count, BUTTON_BITS[button]);
6152
+ await this.release(point, button, count, 0);
6153
+ }
6154
+ }
6155
+ async hover(point, modifiers) {
6156
+ for (const modifier of modifiers)
6157
+ await this.page.keyboard.down(modifier);
4981
6158
  try {
4982
- return await Promise.race([
4983
- pending.result,
4984
- new Promise((resolve2) => {
4985
- timer2 = setTimeout(() => resolve2(undefined), ms);
4986
- })
4987
- ]);
6159
+ await this.move(point, 0, modifierBits(modifiers));
4988
6160
  } finally {
4989
- clearTimeout(timer2);
6161
+ for (const modifier of modifiers.toReversed())
6162
+ await this.page.keyboard.up(modifier);
4990
6163
  }
4991
6164
  }
4992
- async run(actionId, dispatch) {
4993
- if (this.dialog || this.pending)
4994
- return {
4995
- dispatch: { status: "not_dispatched", code: this.dialog ? "dialog_blocking" : "previous_action_pending" },
4996
- dialog: this.activeDialog(),
4997
- pendingAction: this.pendingAction()
4998
- };
4999
- this.currentAction = actionId;
5000
- let interruptedByDialog = false;
5001
- let wake;
5002
- const interrupted = new Promise((resolve2) => {
5003
- wake = () => {
5004
- interruptedByDialog = true;
5005
- resolve2({ dispatch: { status: "blocked", actionId, code: "dialog_open" }, dialog: this.activeDialog() });
5006
- };
5007
- this.listeners.add(wake);
5008
- });
5009
- const pending = { actionId, settled: false, result: Promise.resolve({}) };
5010
- const work = Promise.resolve().then(dispatch);
5011
- pending.result = work.then((result) => {
5012
- if (interruptedByDialog)
5013
- this.record("action", { actionId, status: "completed", outcomeVerified: false });
5014
- return { actionId, status: "completed", result };
5015
- }, () => {
5016
- if (interruptedByDialog)
5017
- this.record("action", { actionId, status: "unknown", code: "executor_uncertain", retrySafe: false });
5018
- return { actionId, status: "unknown", code: "executor_uncertain", retrySafe: false };
5019
- }).finally(() => {
5020
- pending.settled = true;
5021
- if (this.pending === pending)
5022
- this.pending = undefined;
5023
- this.recentAction = { id: actionId, at: Date.now() };
5024
- this.currentAction = undefined;
5025
- this.listeners.delete(wake);
5026
- });
5027
- this.pending = pending;
5028
- return await Promise.race([work, interrupted]);
6165
+ drag(type, point, data, modifiers = 0) {
6166
+ return this.session.send("Input.dispatchDragEvent", { type, x: point.x, y: point.y, data, modifiers });
5029
6167
  }
5030
- startDownload(download, downloadId) {
5031
- const event = this.record("download", {
5032
- state: "started",
5033
- downloadId,
5034
- resourceId: downloadId,
5035
- readiness: "pending",
5036
- filename: download.suggestedFilename().slice(0, 255),
5037
- url: diagnosticUrl(download.url())
6168
+ dispose() {
6169
+ this.session.detach().catch(() => {
6170
+ return;
5038
6171
  });
5039
- this.downloads.set(event.eventId, download);
5040
- return (data) => {
5041
- this.record("download", { ...data, downloadId, resourceId: downloadId, transferId: event.eventId, actionId: event.actionId, filename: event.filename });
5042
- this.downloads.delete(event.eventId);
5043
- };
5044
6172
  }
5045
- chooser(id) {
5046
- const value = this.choosers.get(id);
5047
- if (!value || value.document !== this.document || value.event.state !== "open")
5048
- throw uploadRefusal.chooserExpired();
5049
- value.event.state = "claimed";
5050
- this.choosers.delete(id);
5051
- return value.element;
6173
+ }
6174
+
6175
+ class DragInterception {
6176
+ session;
6177
+ caught;
6178
+ heard;
6179
+ constructor(session) {
6180
+ this.session = session;
5052
6181
  }
5053
- clearChoosers() {
5054
- for (const c of this.choosers.values()) {
5055
- c.event.state = "expired";
5056
- c.element.dispose().catch(() => {
6182
+ static async start(page) {
6183
+ const session = await page.context().newCDPSession(page).catch(() => {
6184
+ return;
6185
+ });
6186
+ if (!session)
6187
+ return;
6188
+ const interception = new DragInterception(session);
6189
+ session.on("Input.dragIntercepted", (event) => {
6190
+ interception.caught = event.data;
6191
+ interception.heard?.();
6192
+ });
6193
+ try {
6194
+ await session.send("Input.setInterceptDrags", { enabled: true });
6195
+ return interception;
6196
+ } catch {
6197
+ session.detach().catch(() => {
5057
6198
  return;
5058
6199
  });
6200
+ return;
5059
6201
  }
5060
- this.choosers.clear();
5061
6202
  }
5062
- async cancelTransfer(id) {
5063
- const download = this.downloads.get(id), chooser = this.choosers.get(id);
5064
- if (download) {
5065
- await download.cancel();
5066
- return { cancelled: true, eventId: id };
5067
- }
5068
- if (chooser) {
5069
- chooser.event.state = "cancelled";
5070
- this.choosers.delete(id);
5071
- await chooser.element.dispose();
5072
- return { cancelled: true, eventId: id };
5073
- }
5074
- return { cancelled: false, code: "transfer_not_active" };
6203
+ get data() {
6204
+ return this.caught;
5075
6205
  }
5076
- listAssets() {
5077
- return [...this.assets].map(([assetId, a]) => ({ assetId, url: a.url, size: a.size, mimeType: a.mimeType }));
6206
+ async wait(ms) {
6207
+ if (this.caught)
6208
+ return this.caught;
6209
+ let timer2;
6210
+ await new Promise((resolve2) => {
6211
+ this.heard = resolve2;
6212
+ timer2 = setTimeout(resolve2, ms);
6213
+ });
6214
+ clearTimeout(timer2);
6215
+ this.heard = undefined;
6216
+ return this.caught;
5078
6217
  }
5079
- async assetBytes(id) {
5080
- const asset = this.assets.get(id);
5081
- if (!asset || asset.document !== this.document)
5082
- throw new Error("Asset is no longer in the current document's observed responses.");
5083
- const body = await asset.response.body();
5084
- if (body.length > 8 * 1024 * 1024 || body.length > asset.size)
5085
- throw new Error("Asset exceeds declared size or 8 MiB.");
5086
- return { bytes: body, mimeType: asset.mimeType };
6218
+ async stop() {
6219
+ await this.session.send("Input.setInterceptDrags", { enabled: false }).catch(() => {
6220
+ return;
6221
+ });
6222
+ this.session.detach().catch(() => {
6223
+ return;
6224
+ });
6225
+ }
6226
+ }
6227
+ async function dragOnTarget(target2, from, to, steps, modifiers = 0) {
6228
+ const interception = await DragInterception.start(target2.page);
6229
+ let entered = false;
6230
+ try {
6231
+ await target2.move(from, 0, modifiers);
6232
+ await target2.press(from, "left", 1, BUTTON_BITS.left, modifiers);
6233
+ const count = Math.max(1, Math.round(steps));
6234
+ for (let step = 1;step <= count; step++) {
6235
+ const point = { x: from.x + (to.x - from.x) * step / count, y: from.y + (to.y - from.y) * step / count };
6236
+ const data2 = interception?.data;
6237
+ if (data2) {
6238
+ await target2.drag(entered ? "dragOver" : "dragEnter", point, data2, modifiers);
6239
+ entered = true;
6240
+ } else
6241
+ await target2.move(point, BUTTON_BITS.left, modifiers);
6242
+ }
6243
+ const data = await interception?.wait(DRAG_HANDOVER_MS);
6244
+ if (data) {
6245
+ if (!entered)
6246
+ await target2.drag("dragEnter", to, data, modifiers);
6247
+ await target2.drag("drop", to, data, modifiers);
6248
+ }
6249
+ } finally {
6250
+ await target2.release(to, "left", 1, 0, modifiers).catch(() => {
6251
+ return;
6252
+ });
6253
+ await interception?.stop();
5087
6254
  }
5088
6255
  }
5089
6256
 
5090
6257
  // cli/src/browser/browser-webmcp.ts
5091
6258
  var NAME_REGISTRATION_WAIT_MS = 1000;
5092
6259
  var FRAMES_LOADED_BEFORE_WATCHING = 'Frames of this document loaded before the runtime began watching the tab, and Chrome does not report the WebMCP tools they registered before that: such tools are missing here. Reloading the tab (browser_history {direction: "reload"}) lists them.';
5093
- var refusal = (code2, recovery, details) => new RuntimeFault(code2, recovery, true, details, true);
6260
+ var refusal2 = (code2, recovery, details) => new RuntimeFault(code2, recovery, true, details, true);
5094
6261
  var STALE_RECOVERY2 = "Call the tool by its name, which is resolved in the tab's current document, or take a current toolId from browser_webmcp_list. Nothing was invoked.";
5095
6262
 
5096
6263
  class BrowserWebMCP {
@@ -5263,7 +6430,7 @@ class BrowserWebMCP {
5263
6430
  if (typeof input.toolId === "string") {
5264
6431
  const entry = this.tools.get(input.toolId);
5265
6432
  if (!entry)
5266
- throw refusal("stale_webmcp_tool", STALE_RECOVERY2);
6433
+ throw refusal2("stale_webmcp_tool", STALE_RECOVERY2);
5267
6434
  return entry;
5268
6435
  }
5269
6436
  const name = String(input.name);
@@ -5273,9 +6440,9 @@ class BrowserWebMCP {
5273
6440
  return matches[0];
5274
6441
  if (!matches.length) {
5275
6442
  const registeredNames = [...new Set([...this.tools.values()].map((entry) => entry.tool.name.slice(0, 100)))].slice(0, 20);
5276
- throw refusal("webmcp_tool_not_found", 'Check the name against registeredNames (up to 20 names the page registered, page data) or browser_webmcp_list. A page registers its tools with its own scripts, which may need a moment after loading. With frameToolsMayBeMissing, a frame of this document may have registered it before the runtime began watching the tab, which Chrome does not report: reloading the tab (browser_history {direction: "reload"}) lists such tools. Nothing was invoked.', { registeredNames, ...this.unwatched.size ? { frameToolsMayBeMissing: true } : {} });
6443
+ throw refusal2("webmcp_tool_not_found", 'Check the name against registeredNames (up to 20 names the page registered, page data) or browser_webmcp_list. A page registers its tools with its own scripts, which may need a moment after loading. With frameToolsMayBeMissing, a frame of this document may have registered it before the runtime began watching the tab, which Chrome does not report: reloading the tab (browser_history {direction: "reload"}) lists such tools. Nothing was invoked.', { registeredNames, ...this.unwatched.size ? { frameToolsMayBeMissing: true } : {} });
5277
6444
  }
5278
- throw refusal("webmcp_tool_ambiguous", "Several frames of the page register this name: call the one you mean by its toolId from candidates (toolId, frameId and the frame's origin, page data). Nothing was invoked.", { candidates: matches.slice(0, 20).map((entry) => ({ toolId: entry.id, frameId: entry.tool.frameId, origin: entry.origin })) });
6445
+ throw refusal2("webmcp_tool_ambiguous", "Several frames of the page register this name: call the one you mean by its toolId from candidates (toolId, frameId and the frame's origin, page data). Nothing was invoked.", { candidates: matches.slice(0, 20).map((entry) => ({ toolId: entry.id, frameId: entry.tool.frameId, origin: entry.origin })) });
5279
6446
  }
5280
6447
  annotatedReadOnly(invocationId) {
5281
6448
  const key2 = String(invocationId);
@@ -5292,7 +6459,7 @@ class BrowserWebMCP {
5292
6459
  const tree = await this.cdp.send("Page.getFrameTree");
5293
6460
  const find = (node) => node.frame.id === entry.tool.frameId ? node.frame : node.childFrames?.map(find).find(Boolean);
5294
6461
  if (find(tree.frameTree)?.loaderId !== entry.loaderId || this.tools.get(entry.id) !== entry)
5295
- throw refusal("stale_webmcp_tool", STALE_RECOVERY2);
6462
+ throw refusal2("stale_webmcp_tool", STALE_RECOVERY2);
5296
6463
  let timer2;
5297
6464
  const { invocationId } = await this.cdp.send("WebMCP.invokeTool", {
5298
6465
  frameId: entry.tool.frameId,
@@ -5972,13 +7139,13 @@ async function exportDocument(page, format) {
5972
7139
  }
5973
7140
  }
5974
7141
  const text = await page.evaluate((format2) => {
5975
- const bounded2 = (text2) => {
7142
+ const bounded3 = (text2) => {
5976
7143
  if (text2.length > 20 * 1024 * 1024 || new TextEncoder().encode(text2).length > 20 * 1024 * 1024)
5977
7144
  throw new Error("Document export exceeds 20 MiB.");
5978
7145
  return text2;
5979
7146
  };
5980
7147
  if (format2 === "text")
5981
- return bounded2(document.body.innerText);
7148
+ return bounded3(document.body.innerText);
5982
7149
  const clone = document.documentElement.cloneNode(true);
5983
7150
  for (const el of clone.querySelectorAll('input[type="password"]'))
5984
7151
  el.setAttribute("value", "[password]");
@@ -5988,7 +7155,7 @@ async function exportDocument(page, format) {
5988
7155
  for (const attr of [...el.attributes])
5989
7156
  if (/^on/i.test(attr.name) || attr.name === "srcdoc" || /^[\s\u0000-\u0020]*(javascript|vbscript):/i.test(attr.value))
5990
7157
  el.removeAttribute(attr.name);
5991
- return bounded2(`<!doctype html>
7158
+ return bounded3(`<!doctype html>
5992
7159
  ` + clone.outerHTML);
5993
7160
  }, format);
5994
7161
  return {
@@ -6193,17 +7360,17 @@ var DOCUMENT_SIZE_EXPRESSION = `({
6193
7360
  docHeight: Math.max(document.documentElement.scrollHeight, document.documentElement.offsetHeight, document.documentElement.clientHeight,
6194
7361
  document.body ? document.body.scrollHeight : 0, document.body ? document.body.offsetHeight : 0, document.body ? document.body.clientHeight : 0),
6195
7362
  })`;
6196
- var finite = (value) => typeof value === "number" && Number.isFinite(value);
7363
+ var finite2 = (value) => typeof value === "number" && Number.isFinite(value);
6197
7364
  async function readViewportGeometry(cdp) {
6198
7365
  const v = await evaluateIsolated(cdp, VIEWPORT_EXPRESSION);
6199
- 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))
7366
+ if (!v || typeof v.url !== "string" || ![v.scrollX, v.scrollY, v.width, v.height, v.dpr].every(finite2) || !(v.width > 0 && v.height > 0 && v.dpr > 0))
6200
7367
  throw new ObservationError("Viewport geometry is unavailable.");
6201
7368
  const state = { url: v.url, scrollX: v.scrollX, scrollY: v.scrollY, width: v.width, height: v.height, dpr: v.dpr };
6202
7369
  return { state, document: { readyState: v.readyState, visibilityState: v.visibilityState } };
6203
7370
  }
6204
7371
  async function readDocumentSize(cdp) {
6205
7372
  const v = await evaluateIsolated(cdp, DOCUMENT_SIZE_EXPRESSION);
6206
- if (!v || !finite(v.docWidth) || !finite(v.docHeight) || v.docWidth <= 0 || v.docHeight <= 0)
7373
+ if (!v || !finite2(v.docWidth) || !finite2(v.docHeight) || v.docWidth <= 0 || v.docHeight <= 0)
6207
7374
  throw new ObservationError("Document size is unavailable.");
6208
7375
  return { docWidth: v.docWidth, docHeight: v.docHeight };
6209
7376
  }
@@ -6334,6 +7501,10 @@ var MAX_RUN_JS_RESULT_BYTES = 1024 * 1024;
6334
7501
  var MAX_RUN_JS_ARTIFACT_BYTES = 20 * 1024 * 1024;
6335
7502
  var MAX_RUN_JS_ARTIFACT_COUNT = 32;
6336
7503
  var REF_ACTION_TIMEOUT_MS = 5000;
7504
+ var NAVIGATION_LOADING = {
7505
+ navigationLoading: true,
7506
+ note: "The click was made, and the page it opens was still loading when the click's five-second wait for it ended. Wait for that page with browser_wait_for, then read it with browser_read_page; do not repeat the click."
7507
+ };
6337
7508
  var TARGET_WAIT_MS = 5000;
6338
7509
  var MAX_TARGET_CANDIDATES = 10;
6339
7510
  var NAVIGATION_TIMEOUT_MS = 20000;
@@ -6368,6 +7539,7 @@ var MAX_TYPED_KEYS_CHARS = 500;
6368
7539
  var MAX_TYPED_KEYS_TOTAL_MS = 20000;
6369
7540
  var TAB_PRESENTATION_TIMEOUT_MS = 2000;
6370
7541
  var OBSERVATION_BASELINE_CHARS = 30000;
7542
+ var DOCUMENT_READ_TIMEOUT_MS = 2000;
6371
7543
  var WEBMCP_WATCH_WAIT_MS = 1000;
6372
7544
  function joinLines(lines, maxChars, cutLongFirst = true) {
6373
7545
  const limit = Math.max(0, maxChars);
@@ -6407,6 +7579,49 @@ function refActionError(error, ref, verb) {
6407
7579
  Ref ${ref} comes from the most recent browser_read_page snapshot of this tab. ` + `The ${verb} outcome may be uncertain. ` + BROWSER_RECOVERY, { cause: error });
6408
7580
  }
6409
7581
  var playwrightTimeout = (error) => error instanceof Error && error.name === "TimeoutError";
7582
+ function clickProgress(error) {
7583
+ const lines = (error instanceof Error ? error.message : String(error)).replace(/\u001b\[[\d;]*m/g, "").split(`
7584
+ `).map((line) => line.trim().replace(/^-\s*/, "").replace(/^\d+\s*×\s*/, ""));
7585
+ const attempt = lines.slice(Math.max(lines.lastIndexOf("attempting click action"), lines.lastIndexOf("retrying click action")) + 1);
7586
+ if (attempt.includes("click action done"))
7587
+ return "done";
7588
+ const sent = attempt.lastIndexOf("performing click action");
7589
+ if (sent < 0 || attempt.slice(sent).some((line) => line.endsWith(" intercepts pointer events")))
7590
+ return;
7591
+ return "sent";
7592
+ }
7593
+ var PAGE_BUSY_RECOVERY = "The click may have taken effect. Wait for its result with browser_wait_for (for example the text you expect), then read the page with browser_read_page, before repeating the click.";
7594
+ var pageBusy = (ref) => new RuntimeFault("page_busy", PAGE_BUSY_RECOVERY, false, { ref });
7595
+ var NAVIGATION_LOADING_RECOVERY = "Wait for that page with browser_wait_for (its text, url or a loadState), then read it again. To go elsewhere instead, use browser_navigate, which replaces that navigation. Nothing was dispatched.";
7596
+ function readsDocument(action, input, pointerKnown) {
7597
+ switch (action) {
7598
+ case "read_page":
7599
+ case "inspect":
7600
+ case "screenshot":
7601
+ case "run_js":
7602
+ case "export_page":
7603
+ case "form_input":
7604
+ case "hover":
7605
+ case "select_text":
7606
+ case "edit_text":
7607
+ case "upload_attach":
7608
+ case "clipboard":
7609
+ case "capabilities":
7610
+ case "webmcp_list":
7611
+ case "webmcp_call":
7612
+ return true;
7613
+ case "scroll":
7614
+ if (input.ref === undefined && input.target === undefined && input.x === undefined && !pointerKnown)
7615
+ return true;
7616
+ case "mouse_click":
7617
+ return input.ref !== undefined || input.target !== undefined || input.screenshot !== undefined;
7618
+ case "drag":
7619
+ case "move_mouse":
7620
+ return input.sourceRef !== undefined || input.screenshot !== undefined;
7621
+ default:
7622
+ return false;
7623
+ }
7624
+ }
6410
7625
  function withTimeout(work, ms) {
6411
7626
  let timer2;
6412
7627
  return Promise.race([
@@ -6416,9 +7631,20 @@ function withTimeout(work, ms) {
6416
7631
  })
6417
7632
  ]).finally(() => clearTimeout(timer2));
6418
7633
  }
6419
- var refusal2 = (code2, recovery, details) => new RuntimeFault(code2, recovery, true, details, true);
6420
- var staleRef = (ref) => refusal2("ref_stale", "Read the page again with browser_read_page and use a current ref. Nothing was dispatched.", { ref });
6421
- var invalidInput = (problem) => refusal2("invalid_browser_input", "Correct the arguments as result.problem says, then send the request again. If the server accepted them, this browser runtime and the server are different versions: ask the user to update the CLI. Nothing was dispatched.", { problem: problem.slice(0, 300) });
7634
+ var refusal3 = (code2, recovery, details) => new RuntimeFault(code2, recovery, true, details, true);
7635
+ function coveredProbe(probe, path10) {
7636
+ return {
7637
+ kind: "covered",
7638
+ point: probe.point,
7639
+ box: probe.box,
7640
+ ...probe.standIn ? { standIn: probe.standIn } : {},
7641
+ cover: path10.cover,
7642
+ ...path10.layer ? { layer: path10.layer } : {},
7643
+ ...path10.passThrough ? { passThrough: true } : {}
7644
+ };
7645
+ }
7646
+ var staleRef = (ref) => refusal3("ref_stale", "Read the page again with browser_read_page and use a current ref. Nothing was dispatched.", { ref });
7647
+ var invalidInput = (problem) => refusal3("invalid_browser_input", "Correct the arguments as result.problem says, then send the request again. If the server accepted them, this browser runtime and the server are different versions: ask the user to update the CLI. Nothing was dispatched.", { problem: problem.slice(0, 300) });
6422
7648
  var problemOf = (error) => error instanceof Error ? error.message : "Invalid arguments.";
6423
7649
  var SESSION_STOPPED_RECOVERY = "Use browser_list_tabs to choose an open tab. Opening a tab in that browser session (browser_open_tab with its session) starts its Chrome again, still signed in; the terminal that runs browser-mcp says why it stopped.";
6424
7650
  var TARGET_NOT_FOUND = "Correct the locator (exact: false matches case-insensitive substrings), wait for the element with browser_wait_for, or find it with a browser_read_page query and pass its ref. Hidden elements are not candidates, and an element in an iframe needs its ref. Nothing was dispatched.";
@@ -6453,7 +7679,7 @@ var EDITOR_TYPING_RULES = "A code editor applies its own typing rules to typed t
6453
7679
  function notAFormField(ref, info, standIn = false) {
6454
7680
  const kind = standIn ? "stand_in" : info.kind;
6455
7681
  const recovery = kind === "other" ? "This element is not a form field: form_input and edit_text replace set inputs, textareas, selects, checkboxes, radios and contenteditable elements. To enter text in a custom widget, click it with browser_mouse_click and type with browser_keyboard_type; for a custom menu or list, click the option. Nothing was changed." : `${kind === "stand_in" ? "This text field is drawn over by its widget, as a code editor's text input is: setting its value would not set the text the widget shows." : "This element takes typed text and holds no value to set, as a code editor's input (an EditContext or a custom textbox) does."} ${TYPE_LIKE_A_PERSON} ${EDITOR_TYPING_RULES} Nothing was changed.`;
6456
- return refusal2("not_a_form_field", recovery, { ref, kind, tag: info.tag });
7682
+ return refusal3("not_a_form_field", recovery, { ref, kind, tag: info.tag });
6457
7683
  }
6458
7684
  function typingNote(focused) {
6459
7685
  if (focused === undefined)
@@ -6478,6 +7704,21 @@ function tabStateView(state) {
6478
7704
  ...state.viewport ? { viewport: { width: state.viewport.width, height: state.viewport.height } } : {}
6479
7705
  };
6480
7706
  }
7707
+ function compareOutlines(baseline, current) {
7708
+ const lines = current.text.split(`
7709
+ `).filter(Boolean);
7710
+ const kept = baseline.text.split(`
7711
+ `).filter(Boolean);
7712
+ const before = new Set(kept);
7713
+ const after = new Set(lines);
7714
+ const edge = (index, length) => index < 0 ? length - 1 : index;
7715
+ const lastShared = baseline.clipped ? edge(lines.findLastIndex((line) => before.has(line)), lines.length) : lines.length - 1;
7716
+ const lastKept = current.clipped ? edge(kept.findLastIndex((line) => after.has(line)), kept.length) : kept.length - 1;
7717
+ return {
7718
+ changed: lines.filter((line, index) => index <= lastShared && !before.has(line)),
7719
+ removed: [...new Set(kept.filter((line, index) => index <= lastKept && !after.has(line)))]
7720
+ };
7721
+ }
6481
7722
 
6482
7723
  class BrowserRuntime {
6483
7724
  context;
@@ -6491,15 +7732,19 @@ class BrowserRuntime {
6491
7732
  pages = new Map;
6492
7733
  cursor = new Map;
6493
7734
  viewportSessions = new Map;
7735
+ takeoverViewports = new Map;
7736
+ viewportChanges = new Map;
6494
7737
  uploads;
6495
7738
  events = new WeakMap;
6496
7739
  webmcp = new WeakMap;
6497
7740
  initialization = new Map;
6498
7741
  contexts = new Map;
6499
7742
  observations = new Map;
7743
+ outlines = new WeakMap;
6500
7744
  lastActions = new Map;
6501
7745
  tabPresentation = new WeakMap;
6502
7746
  savingDownloads = new Set;
7747
+ httpAuthPolicy;
6503
7748
  constructor(context, downloadsPath, uploadsPath = `${downloadsPath}.uploads`, downloadHandler, guardPage, passkeyDetection = true, screenshotMaxEdge = MAX_IMAGE_DIMENSION) {
6504
7749
  this.context = context;
6505
7750
  this.downloadsPath = downloadsPath;
@@ -6564,6 +7809,7 @@ class BrowserRuntime {
6564
7809
  this.lastActions.delete(currentId);
6565
7810
  this.initialization.delete(page);
6566
7811
  this.viewportSessions.delete(currentId);
7812
+ this.takeoverViewports.delete(currentId);
6567
7813
  }
6568
7814
  track(page) {
6569
7815
  const existing = this.ids.get(page);
@@ -6573,8 +7819,9 @@ class BrowserRuntime {
6573
7819
  const id = crypto.randomUUID();
6574
7820
  this.ids.set(page, id);
6575
7821
  this.pages.set(id, page);
6576
- this.events.set(page, new BrowserPageEvents(page, this.passkeyDetection));
7822
+ this.events.set(page, new BrowserPageEvents(page, this.passkeyDetection, (acting) => this.answersHttpAuth(page, acting)));
6577
7823
  followRestoredFrames(page);
7824
+ correctCrossSiteFramePositions(page);
6578
7825
  page.on("framenavigated", () => {
6579
7826
  const tabId = this.ids.get(page);
6580
7827
  if (tabId)
@@ -6754,7 +8001,7 @@ class BrowserRuntime {
6754
8001
  async openTabIn(context, newWindow) {
6755
8002
  const entry = this.contexts.get(context);
6756
8003
  if (!entry)
6757
- throw refusal2("browser_session_stopped", "Open the tab again: the browser session's Chrome starts again, still signed in. The terminal that runs browser-mcp says why it stopped. No tab was opened.");
8004
+ throw refusal3("browser_session_stopped", "Open the tab again: the browser session's Chrome starts again, still signed in. The terminal that runs browser-mcp says why it stopped. No tab was opened.");
6758
8005
  const startup = entry.startupPage;
6759
8006
  entry.startupPage = undefined;
6760
8007
  if (startup && !startup.isClosed() && startup.url() === "about:blank" && this.ids.has(startup))
@@ -6793,7 +8040,7 @@ class BrowserRuntime {
6793
8040
  selector = snapshotSelector(page, target2);
6794
8041
  } catch (error) {
6795
8042
  if (/frames/.test(error instanceof Error ? error.message : ""))
6796
- throw refusal2("target_invalid", TARGET_INVALID, echo);
8043
+ throw refusal3("target_invalid", TARGET_INVALID, echo);
6797
8044
  throw error;
6798
8045
  }
6799
8046
  const look = async (query, maxMatches) => {
@@ -6802,7 +8049,7 @@ class BrowserRuntime {
6802
8049
  } catch (error) {
6803
8050
  if (page.isClosed() || error instanceof RuntimeFault || /unavailable/i.test(error instanceof Error ? error.message : ""))
6804
8051
  throw error;
6805
- throw refusal2("target_unresolved", TARGET_UNRESOLVED, echo);
8052
+ throw refusal3("target_unresolved", TARGET_UNRESOLVED, echo);
6806
8053
  }
6807
8054
  };
6808
8055
  const deadline = Date.now() + TARGET_WAIT_MS;
@@ -6815,11 +8062,11 @@ class BrowserRuntime {
6815
8062
  throw error;
6816
8063
  }
6817
8064
  if (found?.invalidQuery)
6818
- throw refusal2("target_invalid", TARGET_INVALID, echo);
8065
+ throw refusal3("target_invalid", TARGET_INVALID, echo);
6819
8066
  if (found && found.matchCount === 1 && found.matches[0])
6820
8067
  return { ref: found.matches[0].ref, match: found.matches[0] };
6821
8068
  if (found && found.matchCount > 1)
6822
- throw refusal2("target_ambiguous", TARGET_AMBIGUOUS, { ...echo, matchCount: found.matchCount, candidates: found.matches.slice(0, MAX_TARGET_CANDIDATES) });
8069
+ throw refusal3("target_ambiguous", TARGET_AMBIGUOUS, { ...echo, matchCount: found.matchCount, candidates: found.matches.slice(0, MAX_TARGET_CANDIDATES) });
6823
8070
  if (Date.now() >= deadline) {
6824
8071
  const near = [];
6825
8072
  if (target2.exact !== false && (target2.name || target2.text || target2.label || target2.placeholder))
@@ -6832,7 +8079,7 @@ class BrowserRuntime {
6832
8079
  if (candidates.length)
6833
8080
  break;
6834
8081
  }
6835
- throw refusal2("target_not_found", TARGET_NOT_FOUND, {
8082
+ throw refusal3("target_not_found", TARGET_NOT_FOUND, {
6836
8083
  ...echo,
6837
8084
  matchCount: 0,
6838
8085
  ...found?.hiddenMatchCount ? { hiddenMatchCount: found.hiddenMatchCount } : {},
@@ -6854,13 +8101,13 @@ class BrowserRuntime {
6854
8101
  count = await locator.count();
6855
8102
  } catch (error) {
6856
8103
  if (invalidSelector(error))
6857
- throw refusal2("screenshot_target_invalid", SCREENSHOT_INVALID_SELECTOR_RECOVERY);
8104
+ throw refusal3("screenshot_target_invalid", SCREENSHOT_INVALID_SELECTOR_RECOVERY);
6858
8105
  throw error;
6859
8106
  }
6860
8107
  if (count !== 1)
6861
- throw refusal2(count ? "screenshot_target_ambiguous" : "screenshot_target_missing", SCREENSHOT_SELECTOR_RECOVERY, { matchCount: count });
8108
+ throw refusal3(count ? "screenshot_target_ambiguous" : "screenshot_target_missing", SCREENSHOT_SELECTOR_RECOVERY, { matchCount: count });
6862
8109
  }
6863
- const gone = () => ref !== undefined ? staleRef(ref) : refusal2("screenshot_target_missing", SCREENSHOT_SELECTOR_RECOVERY, { matchCount: 0 });
8110
+ const gone = () => ref !== undefined ? staleRef(ref) : refusal3("screenshot_target_missing", SCREENSHOT_SELECTOR_RECOVERY, { matchCount: 0 });
6864
8111
  let handle;
6865
8112
  try {
6866
8113
  handle = await locator.elementHandle({ timeout: REF_ACTION_TIMEOUT_MS });
@@ -6871,7 +8118,7 @@ class BrowserRuntime {
6871
8118
  }
6872
8119
  try {
6873
8120
  if (!await handle.isVisible())
6874
- throw refusal2("screenshot_target_not_visible", SCREENSHOT_NOT_VISIBLE_RECOVERY);
8121
+ throw refusal3("screenshot_target_not_visible", SCREENSHOT_NOT_VISIBLE_RECOVERY);
6875
8122
  const before = await handle.boundingBox();
6876
8123
  try {
6877
8124
  await handle.scrollIntoViewIfNeeded({ timeout: REF_ACTION_TIMEOUT_MS });
@@ -6909,6 +8156,7 @@ class BrowserRuntime {
6909
8156
  const button = input.button === "middle" || input.button === "right" ? input.button : "left";
6910
8157
  const clickCount = input.clickCount === 2 ? 2 : 1;
6911
8158
  const modifiers = Array.isArray(input.modifiers) ? input.modifiers : [];
8159
+ const steady = (before, now) => (before?.kind === "element" || before?.kind === "stand_in") && before.kind === now.kind && Math.abs(before.point.x - now.point.x) < 1 && Math.abs(before.point.y - now.point.y) < 1;
6912
8160
  let handle;
6913
8161
  try {
6914
8162
  handle = await locator.elementHandle({ timeout: REF_ACTION_TIMEOUT_MS });
@@ -6917,8 +8165,12 @@ class BrowserRuntime {
6917
8165
  throw staleRef(ref);
6918
8166
  throw error;
6919
8167
  }
8168
+ let direct;
6920
8169
  try {
8170
+ const chain = await frameChain(handle);
8171
+ direct = await FrameTarget.forElement(page, chain);
6921
8172
  let scrolled = false;
8173
+ let revealed = false;
6922
8174
  let previous;
6923
8175
  for (;; ) {
6924
8176
  const probe = await probePointer(handle);
@@ -6926,14 +8178,57 @@ class BrowserRuntime {
6926
8178
  throw staleRef(ref);
6927
8179
  const standIn = "standIn" in probe ? probe.standIn : undefined;
6928
8180
  if (probe.kind === "outside_viewport" && !scrolled) {
8181
+ if (direct && !revealed) {
8182
+ revealed = true;
8183
+ await revealFrames(chain, Math.min(remaining(), 2000));
8184
+ continue;
8185
+ }
6929
8186
  scrolled = true;
6930
8187
  await handle.scrollIntoViewIfNeeded({ timeout: Math.min(remaining(), 2000) }).catch(() => {
6931
8188
  return;
6932
8189
  });
6933
8190
  continue;
6934
8191
  }
6935
- if (probe.kind === "stand_in") {
6936
- if (previous?.kind === "stand_in" && Math.abs(previous.point.x - probe.point.x) < 1 && Math.abs(previous.point.y - probe.point.y) < 1) {
8192
+ const reachable = probe.kind === "element" || probe.kind === "stand_in" ? probe : undefined;
8193
+ const path10 = reachable && chain.length ? await framePath(chain, reachable.point, NAME_CHARS, direct?.inRoot) : undefined;
8194
+ let blocked = reachable && path10?.kind === "covered" ? coveredProbe(reachable, path10) : probe;
8195
+ if (path10?.kind === "covered") {} else if (direct && reachable) {
8196
+ if (!path10) {
8197
+ direct.target.dispose();
8198
+ direct = undefined;
8199
+ continue;
8200
+ }
8201
+ if (steady(previous, reachable)) {
8202
+ if (path10.kind === "reached") {
8203
+ this.cursor.delete(tabId);
8204
+ try {
8205
+ if (action === "click")
8206
+ await direct.target.click(path10.root, button, clickCount);
8207
+ else
8208
+ await direct.target.hover(path10.root, modifiers);
8209
+ } catch (error) {
8210
+ throw refActionError(error, ref, action);
8211
+ }
8212
+ if (reachable.kind === "element")
8213
+ return { cursorKnown: false };
8214
+ return await this.standInResult(page, handle, reachable, action, undefined);
8215
+ }
8216
+ if (path10.kind === "outside_viewport" && (!revealed || !scrolled)) {
8217
+ if (!revealed) {
8218
+ revealed = true;
8219
+ await revealFrames(chain, Math.min(remaining(), 2000));
8220
+ } else {
8221
+ scrolled = true;
8222
+ await handle.scrollIntoViewIfNeeded({ timeout: Math.min(remaining(), 2000) }).catch(() => {
8223
+ return;
8224
+ });
8225
+ }
8226
+ continue;
8227
+ }
8228
+ blocked = { kind: "outside_viewport" };
8229
+ }
8230
+ } else if (probe.kind === "stand_in") {
8231
+ if (steady(previous, probe)) {
6937
8232
  const point = roundPoint(await this.pagePoint(handle, probe));
6938
8233
  this.cursor.delete(tabId);
6939
8234
  if (action === "click")
@@ -6949,46 +8244,57 @@ class BrowserRuntime {
6949
8244
  }
6950
8245
  }
6951
8246
  this.cursor.set(tabId, point);
6952
- const focused = action === "click" ? await withTimeout(focusWithin(handle), 1000).catch(() => {
6953
- return;
6954
- }) : undefined;
6955
- const elsewhere = focused === false ? await withTimeout(page.evaluate(focusedElementInPage, NAME_CHARS), 1000).catch(() => {
6956
- return;
6957
- }) : undefined;
6958
- return {
6959
- ...point,
6960
- cursorKnown: true,
6961
- standIn: { reason: probe.standIn, widget: probe.widget },
6962
- ...focused === undefined ? {} : { focused },
6963
- ...elsewhere ? { focusedElement: focusedView(elsewhere) } : {},
6964
- note: `This ref is ${STAND_IN_NOTE[probe.standIn]}, so the ${action} went to its widget (standIn.widget) at x/y, where a person would ${action}.` + (focused ? " Focus is now in this ref." : elsewhere ? ` Focus is now in the element named in focusedElement${elsewhere.takesText ? ", which takes typing" : ""}.` : "")
6965
- };
8247
+ return await this.standInResult(page, handle, probe, action, point);
6966
8248
  }
6967
- } else if (!standIn || probe.kind === "element") {
8249
+ } else if (!direct && (!standIn || probe.kind === "element")) {
6968
8250
  this.cursor.delete(tabId);
8251
+ const deadline2 = action === "click" ? this.events.get(page)?.navigationDeadline(remaining()) : undefined;
6969
8252
  try {
6970
8253
  if (action === "click")
6971
8254
  await locator.click({ button, clickCount, timeout: remaining() });
6972
8255
  else
6973
8256
  await locator.hover({ timeout: remaining(), modifiers });
6974
8257
  } catch (error) {
8258
+ const made = action === "click" ? await this.madeClick(page, error, deadline2) : undefined;
8259
+ if (made === "busy")
8260
+ throw pageBusy(ref);
8261
+ if (made)
8262
+ return { cursorKnown: false, ...made === "loading" ? NAVIGATION_LOADING : {} };
6975
8263
  throw await this.pointerFailure(error, handle, ref, action);
8264
+ } finally {
8265
+ deadline2?.stop();
6976
8266
  }
6977
8267
  return { cursorKnown: false };
6978
8268
  }
6979
8269
  if (Date.now() >= deadline) {
6980
- const { reason, problem, next } = pointerProblem(probe);
6981
- throw refusal2("target_not_actionable", `The ref was not ${action === "click" ? "clicked" : "hovered"}: ${standIn ? `${standInState(standIn)}, and ` : ""}${problem}. Nothing was dispatched. ${next}`, { ref, reason, ...probe.kind === "covered" ? { cover: probe.cover, ...probe.layer ? { layer: probe.layer } : {} } : {} });
8270
+ const { reason, problem, next } = pointerProblem(blocked);
8271
+ throw refusal3("target_not_actionable", `The ref was not ${action === "click" ? "clicked" : "hovered"}: ${standIn ? `${standInState(standIn)}, and ` : ""}${problem}. Nothing was dispatched. ${next}`, { ref, reason, ...blocked.kind === "covered" ? { cover: blocked.cover, ...blocked.layer ? { layer: blocked.layer } : {} } : {} });
6982
8272
  }
6983
8273
  previous = probe;
6984
- await new Promise((resolve2) => setTimeout(resolve2, probe.kind === "stand_in" ? 50 : 150));
8274
+ await new Promise((resolve2) => setTimeout(resolve2, probe.kind === "stand_in" || direct || path10?.kind === "covered" ? 50 : 150));
6985
8275
  }
6986
8276
  } finally {
6987
8277
  handle.dispose().catch(() => {
6988
8278
  return;
6989
8279
  });
8280
+ direct?.target.dispose();
6990
8281
  }
6991
8282
  }
8283
+ async standInResult(page, handle, probe, action, point) {
8284
+ const focused = action === "click" ? await withTimeout(focusWithin(handle), 1000).catch(() => {
8285
+ return;
8286
+ }) : undefined;
8287
+ const elsewhere = focused === false ? await withTimeout(page.evaluate(focusedElementInPage, NAME_CHARS), 1000).catch(() => {
8288
+ return;
8289
+ }) : undefined;
8290
+ return {
8291
+ ...point ? { ...point, cursorKnown: true } : { cursorKnown: false },
8292
+ standIn: { reason: probe.standIn, widget: probe.widget },
8293
+ ...focused === undefined ? {} : { focused },
8294
+ ...elsewhere ? { focusedElement: focusedView(elsewhere) } : {},
8295
+ note: `This ref is ${STAND_IN_NOTE[probe.standIn]}, so the ${action} went to its widget (standIn.widget)${point ? " at x/y" : ""}, where a person would ${action}.` + (focused ? " Focus is now in this ref." : elsewhere ? ` Focus is now in the element named in focusedElement${elsewhere.takesText ? ", which takes typing" : ""}.` : "")
8296
+ };
8297
+ }
6992
8298
  async pagePoint(handle, probe) {
6993
8299
  const frame = await handle.ownerFrame();
6994
8300
  if (!frame?.parentFrame())
@@ -7005,39 +8311,178 @@ class BrowserRuntime {
7005
8311
  async pointerFailure(error, target2, ref, action) {
7006
8312
  if (!playwrightTimeout(error))
7007
8313
  return refActionError(error, ref, action);
7008
- const probe = await withTimeout(probePointer(target2, 2000), 2000).catch(() => ({ kind: "detached" }));
8314
+ let probe = await withTimeout(probePointer(target2, 2000), 2000).catch(() => ({ kind: "detached" }));
8315
+ if (probe.kind === "element" || probe.kind === "stand_in")
8316
+ probe = await withTimeout(this.ancestorCover(target2, probe), 2000).catch(() => {
8317
+ return;
8318
+ }) ?? probe;
7009
8319
  const { reason, problem, next } = pointerProblem(probe);
7010
8320
  return new RuntimeFault("target_not_actionable", `The ${action} on this ref waited ${REF_ACTION_TIMEOUT_MS / 1000} seconds: ${problem}. It probably did not happen, but check the page before repeating it. ${next}`, false, { ref, reason, ...probe.kind === "covered" ? { cover: probe.cover, ...probe.layer ? { layer: probe.layer } : {} } : {} });
7011
8321
  }
8322
+ async madeClick(page, error, deadline) {
8323
+ if (!playwrightTimeout(error))
8324
+ return;
8325
+ const progress = clickProgress(error);
8326
+ if (!progress)
8327
+ return;
8328
+ const loading = () => progress === "done" || !!this.events.get(page)?.navigationLoading();
8329
+ if (deadline?.wasHeld())
8330
+ return await this.heldClickNavigation(page, deadline) === "expired" && loading() ? "loading" : "done";
8331
+ return loading() ? "loading" : "busy";
8332
+ }
8333
+ async heldClickNavigation(page, deadline) {
8334
+ let committed;
8335
+ const commit = new Promise((resolve2) => committed = () => resolve2("commit"));
8336
+ const onCommit = (frame) => {
8337
+ if (frame === page.mainFrame())
8338
+ committed();
8339
+ };
8340
+ let timer2;
8341
+ page.on("framenavigated", onCommit);
8342
+ page.on("close", committed);
8343
+ try {
8344
+ const outcome = await Promise.race([
8345
+ commit,
8346
+ deadline.expired.then(() => "expired", () => "expired"),
8347
+ new Promise((resolve2) => timer2 = setTimeout(() => resolve2("bound"), DIALOG_WAIT_MS))
8348
+ ]);
8349
+ if (outcome === "bound" && deadline.held()) {
8350
+ this.events.get(page)?.markUnanswered();
8351
+ throw new Error(`Timeout ${DIALOG_WAIT_MS}ms exceeded while a dialog held the navigation the click started.`);
8352
+ }
8353
+ return outcome === "commit" ? "commit" : "expired";
8354
+ } finally {
8355
+ clearTimeout(timer2);
8356
+ page.off("framenavigated", onCommit);
8357
+ page.off("close", committed);
8358
+ }
8359
+ }
8360
+ async ancestorCover(target2, probe) {
8361
+ const handle = "count" in target2 ? await target2.elementHandle({ timeout: 1000 }).catch(() => {
8362
+ return;
8363
+ }) : target2;
8364
+ if (!handle)
8365
+ return;
8366
+ try {
8367
+ const chain = await frameChain(handle);
8368
+ const path10 = chain.length ? await framePath(chain, probe.point, NAME_CHARS) : undefined;
8369
+ return path10?.kind === "covered" ? coveredProbe(probe, path10) : undefined;
8370
+ } finally {
8371
+ if (handle !== target2)
8372
+ handle.dispose().catch(() => {
8373
+ return;
8374
+ });
8375
+ }
8376
+ }
7012
8377
  async coveredStandIn(target2) {
7013
8378
  const probe = await probePointer(target2, REF_ACTION_TIMEOUT_MS);
7014
8379
  return "standIn" in probe && !!probe.standIn && probe.kind !== "element";
7015
8380
  }
8381
+ async atPoint(page, point, onTarget, onPage) {
8382
+ const routed = await FrameTarget.at(page, point);
8383
+ if (!routed)
8384
+ return await onPage();
8385
+ try {
8386
+ return await onTarget(routed.target, routed.local);
8387
+ } finally {
8388
+ routed.target.dispose();
8389
+ }
8390
+ }
8391
+ async dragInFrame(page, input) {
8392
+ if (!showsRestoredDocument(page))
8393
+ return;
8394
+ const [from, to] = input.sourceRef ? await Promise.all([input.sourceRef, input.targetRef].map((ref) => this.refPagePoint(page, String(ref)))) : [input.from, input.to];
8395
+ if (!from || !to)
8396
+ return;
8397
+ const start = await FrameTarget.at(page, from);
8398
+ if (!start)
8399
+ return;
8400
+ const end = await FrameTarget.at(page, to, start.target);
8401
+ try {
8402
+ if (end?.target !== start.target)
8403
+ return;
8404
+ const modifiers = input.modifiers ?? [];
8405
+ for (const modifier of modifiers)
8406
+ await page.keyboard.down(modifier);
8407
+ try {
8408
+ await dragOnTarget(start.target, start.local, end.local, Number(input.steps ?? 10), modifierBits(modifiers));
8409
+ } finally {
8410
+ for (const modifier of modifiers.toReversed())
8411
+ await page.keyboard.up(modifier);
8412
+ }
8413
+ return { dispatched: true, outcomeVerified: false };
8414
+ } finally {
8415
+ start.target.dispose();
8416
+ if (end && end.target !== start.target)
8417
+ end.target.dispose();
8418
+ }
8419
+ }
8420
+ async refPagePoint(page, ref) {
8421
+ const handle = await this.refLocator(page, ref).elementHandle({ timeout: REF_ACTION_TIMEOUT_MS }).catch(() => {
8422
+ return;
8423
+ });
8424
+ if (!handle)
8425
+ return;
8426
+ try {
8427
+ const probe = await probePointer(handle);
8428
+ if (probe.kind !== "element" && probe.kind !== "stand_in")
8429
+ return;
8430
+ const path10 = await framePath(await frameChain(handle), probe.point, NAME_CHARS);
8431
+ return path10?.kind === "reached" ? path10.page : undefined;
8432
+ } finally {
8433
+ handle.dispose().catch(() => {
8434
+ return;
8435
+ });
8436
+ }
8437
+ }
8438
+ async inChildFrame(target2) {
8439
+ const handle = await target2.elementHandle({ timeout: REF_ACTION_TIMEOUT_MS }).catch(() => {
8440
+ return;
8441
+ });
8442
+ if (!handle)
8443
+ return false;
8444
+ try {
8445
+ return (await frameChain(handle)).length > 0;
8446
+ } finally {
8447
+ handle.dispose().catch(() => {
8448
+ return;
8449
+ });
8450
+ }
8451
+ }
7016
8452
  async setCheckedAtRef(page, tabId, locator, ref, checked) {
7017
8453
  const state = () => locator.evaluate((element) => ({ checked: element.checked, radio: element.type === "radio" }), undefined, {
7018
8454
  timeout: REF_ACTION_TIMEOUT_MS
7019
8455
  });
7020
8456
  const before = await state();
7021
8457
  if (before.checked === checked)
7022
- return;
8458
+ return {};
7023
8459
  if (before.radio && !checked)
7024
- throw refusal2("invalid_browser_input", "A radio button is unchecked by checking another radio button of its group. Nothing was changed.", { ref });
7025
- if (await this.coveredStandIn(locator)) {
7026
- await this.pointAtRef(page, tabId, ref, "click", {});
8460
+ throw refusal3("invalid_browser_input", "A radio button is unchecked by checking another radio button of its group. Nothing was changed.", { ref });
8461
+ if (await this.inChildFrame(locator) || await this.coveredStandIn(locator)) {
8462
+ const clicked = await this.pointAtRef(page, tabId, ref, "click", {});
8463
+ if (clicked.navigationLoading)
8464
+ return NAVIGATION_LOADING;
7027
8465
  if ((await state()).checked !== checked)
7028
8466
  throw new RuntimeFault("check_state_unchanged", `Take a screenshot to see the state of its widget before trying again; the click may have had another effect.`, false, { ref });
7029
- return;
8467
+ return {};
7030
8468
  }
7031
8469
  this.cursor.delete(tabId);
7032
8470
  try {
7033
8471
  await locator.setChecked(checked, { timeout: REF_ACTION_TIMEOUT_MS });
7034
8472
  } catch (error) {
8473
+ const progress = playwrightTimeout(error) ? clickProgress(error) : undefined;
8474
+ if (progress && this.events.get(page)?.navigationLoading())
8475
+ return NAVIGATION_LOADING;
8476
+ if (progress)
8477
+ throw pageBusy(ref);
7035
8478
  throw await this.pointerFailure(error, locator, ref, "form_input");
7036
8479
  }
8480
+ return {};
7037
8481
  }
7038
8482
  async gotoSettled(page, url) {
8483
+ const mark = this.events.get(page)?.frameDocumentMark();
7039
8484
  try {
7040
- await page.goto(url, { waitUntil: "domcontentloaded", timeout: NAVIGATION_TIMEOUT_MS });
8485
+ await this.navigating(page, (timeout2) => page.goto(url, { waitUntil: "domcontentloaded", timeout: timeout2 }));
7041
8486
  } catch (error) {
7042
8487
  const message = error instanceof Error ? error.message : String(error);
7043
8488
  if (/Download is starting/i.test(message))
@@ -7048,8 +8493,32 @@ class BrowserRuntime {
7048
8493
  return;
7049
8494
  });
7050
8495
  }
8496
+ await this.framesSettled(page, mark);
7051
8497
  return {};
7052
8498
  }
8499
+ async navigating(page, navigate) {
8500
+ const events = this.events.get(page);
8501
+ const deadline = events?.navigationDeadline(NAVIGATION_TIMEOUT_MS);
8502
+ if (!events || !deadline)
8503
+ return await navigate(NAVIGATION_TIMEOUT_MS);
8504
+ const work = navigate(NAVIGATION_TIMEOUT_MS + DIALOG_WAIT_MS, deadline.expired);
8505
+ try {
8506
+ return await Promise.race([work, deadline.expired]);
8507
+ } catch (error) {
8508
+ if (deadline.held() && /Timeout \d+ms exceeded/i.test(error instanceof Error ? error.message : String(error)))
8509
+ events.markUnanswered();
8510
+ throw error;
8511
+ } finally {
8512
+ deadline.stop();
8513
+ work.catch(() => {
8514
+ return;
8515
+ });
8516
+ }
8517
+ }
8518
+ async framesSettled(page, mark) {
8519
+ if (mark !== undefined)
8520
+ await this.events.get(page)?.framesSettled(mark, page.url(), FRAME_DOCUMENT_SETTLE_MS);
8521
+ }
7053
8522
  async tabInfo(page, presented) {
7054
8523
  this.track(page);
7055
8524
  await this.initialization.get(page);
@@ -7118,6 +8587,17 @@ class BrowserRuntime {
7118
8587
  await Promise.all(this.savingDownloads);
7119
8588
  }
7120
8589
  async setViewport(page, tabId, viewport) {
8590
+ const fitted = this.takeoverViewports.has(tabId);
8591
+ if (!fitted)
8592
+ await this.inOrder(tabId, () => this.overrideViewport(page, tabId, viewport));
8593
+ if (viewport && !fitted) {
8594
+ const ready = await page.waitForFunction(({ width, height }) => window.innerWidth === width && window.innerHeight === height, viewport, { timeout: 5000 });
8595
+ await ready.dispose();
8596
+ }
8597
+ const actual = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
8598
+ return { tabId, ...actual, reset: viewport === null };
8599
+ }
8600
+ async overrideViewport(page, tabId, viewport) {
7121
8601
  const existing = this.viewportSessions.get(tabId);
7122
8602
  if (viewport) {
7123
8603
  const cdp = existing ?? await page.context().newCDPSession(page);
@@ -7139,16 +8619,51 @@ class BrowserRuntime {
7139
8619
  });
7140
8620
  }
7141
8621
  this.cursor.delete(tabId);
7142
- if (viewport) {
7143
- const ready = await page.waitForFunction(({ width, height }) => window.innerWidth === width && window.innerHeight === height, viewport, { timeout: 5000 });
7144
- await ready.dispose();
8622
+ this.screenshots.delete(tabId);
8623
+ }
8624
+ inOrder(tabId, change) {
8625
+ const result = (this.viewportChanges.get(tabId) ?? Promise.resolve()).then(change);
8626
+ const settled = result.catch(() => {
8627
+ return;
8628
+ });
8629
+ this.viewportChanges.set(tabId, settled);
8630
+ settled.then(() => {
8631
+ if (this.viewportChanges.get(tabId) === settled)
8632
+ this.viewportChanges.delete(tabId);
8633
+ });
8634
+ return result;
8635
+ }
8636
+ async takeoverViewport(tabId, viewport) {
8637
+ const page = this.pages.get(tabId);
8638
+ if (!page || page.isClosed()) {
8639
+ this.takeoverViewports.delete(tabId);
8640
+ return;
7145
8641
  }
7146
- const actual = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
7147
- return { tabId, ...actual, reset: viewport === null };
8642
+ if (viewport)
8643
+ this.takeoverViewports.set(tabId, { width: viewport.width, height: viewport.height });
8644
+ else if (!this.takeoverViewports.delete(tabId))
8645
+ return;
8646
+ await this.inOrder(tabId, async () => {
8647
+ if (page.isClosed())
8648
+ return;
8649
+ const own = (await this.entryOf(page).tabState.resolve(page)).state.viewport ?? null;
8650
+ await this.overrideViewport(page, tabId, this.takeoverViewports.get(tabId) ?? own);
8651
+ });
7148
8652
  }
7149
8653
  hasPendingInteraction() {
7150
8654
  return [...this.pages.values()].some((page) => !!this.events.get(page)?.activeDialog() || !!this.events.get(page)?.pendingAction());
7151
8655
  }
8656
+ answersHttpAuth(page, acting) {
8657
+ const tabId = this.ids.get(page);
8658
+ if (!tabId || page.isClosed())
8659
+ return false;
8660
+ return this.httpAuthPolicy ? this.httpAuthPolicy(tabId, acting) : acting;
8661
+ }
8662
+ handHttpAuthToChrome(reason, tabId) {
8663
+ for (const [id, page] of this.pages)
8664
+ if (tabId === undefined || id === tabId)
8665
+ this.events.get(page)?.handHttpAuthToChrome(reason);
8666
+ }
7152
8667
  assertCrashAllows(page, action, input) {
7153
8668
  const events = this.events.get(page);
7154
8669
  const crash = events?.crash();
@@ -7183,6 +8698,11 @@ class BrowserRuntime {
7183
8698
  }
7184
8699
  });
7185
8700
  }
8701
+ async documentShown(page) {
8702
+ return await withTimeout(this.guardRaw(page, "all", () => shownDocument(page)), DOCUMENT_READ_TIMEOUT_MS).catch(() => {
8703
+ return;
8704
+ });
8705
+ }
7186
8706
  async reloadCrashed(page) {
7187
8707
  const events = this.events.get(page);
7188
8708
  const held = events.session();
@@ -7234,8 +8754,8 @@ class BrowserRuntime {
7234
8754
  outcomeVerified: false
7235
8755
  };
7236
8756
  }
7237
- async traverseHistory(page, delta) {
7238
- const deadline = Date.now() + NAVIGATION_TIMEOUT_MS;
8757
+ async traverseHistory(page, delta, timeout2 = NAVIGATION_TIMEOUT_MS, expired) {
8758
+ const deadline = Date.now() + timeout2;
7239
8759
  const session = this.events.get(page).session();
7240
8760
  const history = await session?.send("Page.getNavigationHistory").catch(() => {
7241
8761
  return;
@@ -7245,13 +8765,13 @@ class BrowserRuntime {
7245
8765
  return;
7246
8766
  const since = commitsHeard(page);
7247
8767
  if (session && history && entry && entry.url === history.entries[history.currentIndex]?.url) {
7248
- const traversed = await traverseToEntry(page, session, entry.id, NAVIGATION_TIMEOUT_MS);
8768
+ const traversed = await traverseToEntry(page, session, entry.id, timeout2, expired);
7249
8769
  if (traversed.frame === "child")
7250
8770
  return { response: null, restoredFromCache: false, frame: traversed.frame };
7251
8771
  await waitForLoadState(page, "domcontentloaded", Math.max(1, deadline - Date.now()), since);
7252
8772
  return { response: traversed.response, restoredFromCache: restoredFromCache(page, since), frame: traversed.frame };
7253
8773
  }
7254
- const options = { timeout: NAVIGATION_TIMEOUT_MS, waitUntil: "commit" };
8774
+ const options = { timeout: timeout2, waitUntil: "commit" };
7255
8775
  const response = await (delta < 0 ? page.goBack(options) : page.goForward(options));
7256
8776
  await waitForLoadState(page, "domcontentloaded", Math.max(1, deadline - Date.now()), since);
7257
8777
  return { response, restoredFromCache: restoredFromCache(page, since), frame: "main" };
@@ -7320,13 +8840,15 @@ class BrowserRuntime {
7320
8840
  const { page, events } = await this.addressedTab(action, input);
7321
8841
  if (page)
7322
8842
  this.assertCrashAllows(page, action, input);
7323
- if (events?.activeDialog() && !["events", "diagnostics", "handle_dialog", "cancel_transfer"].includes(action))
8843
+ if (events?.activeDialog() && !["events", "diagnostics", "handle_dialog", "cancel_transfer"].includes(action)) {
8844
+ const httpAuth = events.javascriptDialogOpen() ? null : events.httpAuthPrompt();
7324
8845
  return {
7325
8846
  tabId: input.tabId,
7326
8847
  dispatch: { status: "not_dispatched", code: "dialog_blocking" },
7327
8848
  dialog: events.activeDialog(),
7328
- recovery: "Handle this dialog explicitly within the user's authorized task."
8849
+ ...httpAuth ? { httpAuth, recovery: HTTP_AUTH_RECOVERY } : { recovery: "Handle this dialog explicitly within the user's authorized task." }
7329
8850
  };
8851
+ }
7330
8852
  const passkeyPrompt = events?.passkeyPrompt();
7331
8853
  if (passkeyPrompt && PASSKEY_BLOCKED_OPERATIONS.has(action))
7332
8854
  return {
@@ -7335,6 +8857,11 @@ class BrowserRuntime {
7335
8857
  passkeyPrompt,
7336
8858
  recovery: PASSKEY_PROMPT_RECOVERY
7337
8859
  };
8860
+ if (page && events && readsDocument(action, input, this.cursor.has(String(input.tabId)))) {
8861
+ const loading = await events.loadingPage();
8862
+ if (loading)
8863
+ throw refusal3("navigation_loading", NAVIGATION_LOADING_RECOVERY, { pendingNavigation: loading });
8864
+ }
7338
8865
  const crash = events?.crash();
7339
8866
  if (page && action !== "close_tab" && !events?.activeDialog() && (!crash || crash === "frame"))
7340
8867
  await this.webmcp.get(page)?.watch(WEBMCP_WATCH_WAIT_MS);
@@ -7400,24 +8927,23 @@ class BrowserRuntime {
7400
8927
  expected = { matched: false, code: "observation_unavailable" };
7401
8928
  }
7402
8929
  }
8930
+ if (await events?.loadingPage())
8931
+ return {
8932
+ ...result,
8933
+ dispatch,
8934
+ expected,
8935
+ outcomeVerified: succeeded && expected?.matched === true,
8936
+ observation: { available: false, navigationLoading: true }
8937
+ };
7403
8938
  try {
7404
- const summary = observation.mode === "summary" && !!previous;
7405
- const snapshot = await this.dispatch("read_page", { tabId: input.tabId, maxChars: summary ? OBSERVATION_BASELINE_CHARS : observation.maxChars }, execution);
8939
+ const snapshot = await this.dispatch("read_page", { tabId: input.tabId, maxChars: observation.maxChars }, execution);
7406
8940
  await Promise.all(this.initialization.values());
7407
8941
  const newTabIds = [...this.pages.keys()].filter((id) => !previousTabs.has(id));
7408
- if (summary && !snapshot.code) {
7409
- const lines2 = String(snapshot.text ?? "").split(`
7410
- `).filter(Boolean);
7411
- const baseline = previous.text.split(`
7412
- `).filter(Boolean);
7413
- const before2 = new Set(baseline);
7414
- const after2 = new Set(lines2);
7415
- const compared = snapshot.completeness?.characterLimited === true;
7416
- const edge = (index, length) => index < 0 ? length - 1 : index;
7417
- const lastShared = previous.clipped ? edge(lines2.findLastIndex((line) => before2.has(line)), lines2.length) : lines2.length - 1;
7418
- const lastKept = compared ? edge(baseline.findLastIndex((line) => after2.has(line)), baseline.length) : baseline.length - 1;
7419
- const changedLines = lines2.filter((line, index) => index <= lastShared && !before2.has(line));
7420
- const removedLines = [...new Set(baseline.filter((line, index) => index <= lastKept && !after2.has(line)))];
8942
+ const current = this.outlines.get(snapshot);
8943
+ const baseline = previous && current && previous.document === current.document ? previous : undefined;
8944
+ if (observation.mode === "summary" && baseline && current) {
8945
+ const { changed: changedLines, removed: removedLines } = compareOutlines(baseline, current);
8946
+ const compared = current.clipped;
7421
8947
  const text2 = joinLines(changedLines, observation.maxChars);
7422
8948
  const removed = joinLines(removedLines, observation.maxChars - text2.text.length, false);
7423
8949
  const notes = [
@@ -7449,10 +8975,6 @@ class BrowserRuntime {
7449
8975
  }
7450
8976
  };
7451
8977
  }
7452
- const lines = String(snapshot.text ?? "").split(`
7453
- `), before = new Set(previous?.text.split(`
7454
- `) ?? []);
7455
- const after = new Set(lines);
7456
8978
  const text = String(snapshot.text ?? "");
7457
8979
  return {
7458
8980
  ...result,
@@ -7464,9 +8986,8 @@ class BrowserRuntime {
7464
8986
  available: !snapshot.code,
7465
8987
  text,
7466
8988
  mode: observation.mode,
7467
- baselineAvailable: !!previous,
7468
- removed: snapshot.code ? "" : [...before].filter((line) => !after.has(line)).join(`
7469
- `).slice(0, Math.max(0, observation.maxChars - text.length)),
8989
+ baselineAvailable: !!baseline,
8990
+ removed: baseline && current ? joinLines(compareOutlines(baseline, current).removed, observation.maxChars - text.length, false).text : "",
7470
8991
  newTabIds,
7471
8992
  untrusted: true
7472
8993
  }
@@ -7610,10 +9131,19 @@ class BrowserRuntime {
7610
9131
  const expectation = parseNavigationExpectation(input.expectNavigation);
7611
9132
  if (expectation) {
7612
9133
  const { expectNavigation: _expectation, ...dispatchInput } = input;
7613
- const observation = observeNavigation(page, expectation);
9134
+ const events = this.events.get(page);
9135
+ const observation = observeNavigation(page, expectation, events);
7614
9136
  try {
7615
9137
  const dispatched = await this.dispatch(action, dispatchInput, execution);
7616
- return { ...dispatched, navigation: await observation.result };
9138
+ const navigation = await observation.result;
9139
+ if (navigation.code === "dialog_unanswered") {
9140
+ events?.markUnanswered();
9141
+ throw new Error(`Timeout ${expectation.timeoutMs + DIALOG_WAIT_MS}ms exceeded while a dialog held the expected navigation.`);
9142
+ }
9143
+ const { navigationLoading, note: _note, ...made } = dispatched;
9144
+ if (navigationLoading !== true)
9145
+ return { ...dispatched, navigation };
9146
+ return { ...made, ...!navigation.matched && events?.navigationLoading() ? { navigationLoading } : {}, navigation };
7617
9147
  } finally {
7618
9148
  observation.dispose();
7619
9149
  }
@@ -7657,12 +9187,13 @@ class BrowserRuntime {
7657
9187
  ...await this.events.get(page).waitQuery(input),
7658
9188
  dialog: this.events.get(page).activeDialog(),
7659
9189
  passkeyPrompt: this.events.get(page).passkeyPrompt(),
9190
+ httpAuth: this.events.get(page).httpAuthPrompt(),
7660
9191
  pendingAction: this.events.get(page).pendingAction()
7661
9192
  };
7662
9193
  case "diagnostics":
7663
9194
  return { tabId, ...this.events.get(page).query(input, true) };
7664
9195
  case "handle_dialog":
7665
- return { tabId, ...await this.events.get(page).handleDialog(input) };
9196
+ return { tabId, ...await this.events.get(page).handleDialog(input, "agent", { reveal: execution.revealHttpAuth }) };
7666
9197
  case "cancel_transfer":
7667
9198
  return { tabId, ...await this.events.get(page).cancelTransfer(String(input.eventId)) };
7668
9199
  case "inspect":
@@ -7676,7 +9207,7 @@ class BrowserRuntime {
7676
9207
  for (const ref of [input.sourceRef, input.targetRef])
7677
9208
  await this.liveRef(page, requireRef(ref));
7678
9209
  this.cursor.delete(tabId);
7679
- return { tabId, ...await withFramesDrawn(page, () => drag(page, input)) };
9210
+ return { tabId, ...await withFramesDrawn(page, async () => await this.dragInFrame(page, input) ?? await drag(page, input)) };
7680
9211
  case "select_text": {
7681
9212
  const { ref, match } = await this.actionRef(page, input);
7682
9213
  return { tabId, ...input.target !== undefined ? { ref, ...match ? { match } : {} } : {}, ...await selectText(await this.liveRef(page, ref), input) };
@@ -7731,7 +9262,10 @@ class BrowserRuntime {
7731
9262
  return await this.reloadCrashed(page);
7732
9263
  }
7733
9264
  const before = page.url();
7734
- const traversed = input.direction === "reload" ? { response: await page.reload({ timeout: NAVIGATION_TIMEOUT_MS, waitUntil: "domcontentloaded" }), restoredFromCache: undefined } : await this.traverseHistory(page, input.direction === "back" ? -1 : 1);
9265
+ const mark = this.events.get(page).frameDocumentMark();
9266
+ const traversed = input.direction === "reload" ? { response: await this.navigating(page, (timeout2) => page.reload({ timeout: timeout2, waitUntil: "domcontentloaded" })), restoredFromCache: undefined } : await this.navigating(page, (timeout2, expired) => this.traverseHistory(page, input.direction === "back" ? -1 : 1, timeout2, expired));
9267
+ if (traversed && !traversed.restoredFromCache && !(("frame" in traversed) && traversed.frame === "child"))
9268
+ await this.framesSettled(page, mark);
7735
9269
  if (!traversed)
7736
9270
  return {
7737
9271
  tab: await this.tabInfo(page),
@@ -7846,6 +9380,8 @@ class BrowserRuntime {
7846
9380
  }
7847
9381
  case "read_page": {
7848
9382
  const request = parseSnapshotInput(input);
9383
+ const keepsBaseline = !request.query && !request.scope && !request.frames.length && !request.interactive && !request.boxes;
9384
+ const documentBefore = keepsBaseline ? await this.documentShown(page) : undefined;
7849
9385
  const capture = () => passwordSafeAriaSnapshot(page, {
7850
9386
  mode: "ai",
7851
9387
  boxes: request.boxes,
@@ -7888,6 +9424,7 @@ class BrowserRuntime {
7888
9424
  };
7889
9425
  }
7890
9426
  const observed = this.observedAt(page, tabId);
9427
+ const documentAfter = keepsBaseline ? await this.documentShown(page) : undefined;
7891
9428
  const result = {
7892
9429
  tabId,
7893
9430
  url: page.url(),
@@ -7897,13 +9434,18 @@ class BrowserRuntime {
7897
9434
  return;
7898
9435
  }))
7899
9436
  };
7900
- if (!request.query && !request.scope && !request.frames.length && !request.interactive && !request.boxes && !("code" in result)) {
7901
- const reuse = request.depth === undefined && request.maxChars === OBSERVATION_BASELINE_CHARS;
7902
- const outline2 = reuse ? result : renderSnapshot(snapshot, { ...parseSnapshotInput({}), maxChars: OBSERVATION_BASELINE_CHARS });
7903
- const clipped = "completeness" in outline2 && outline2.completeness.characterLimited;
7904
- this.observations.set(tabId, { text: outline2.text, url: result.url, clipped });
7905
- if (this.observations.size > 64)
7906
- this.observations.delete(this.observations.keys().next().value);
9437
+ if (keepsBaseline && !("code" in result)) {
9438
+ this.observations.delete(tabId);
9439
+ if (documentBefore !== undefined && documentBefore === documentAfter) {
9440
+ const reuse = request.depth === undefined && request.maxChars === OBSERVATION_BASELINE_CHARS;
9441
+ const outline2 = reuse ? result : renderSnapshot(snapshot, { ...parseSnapshotInput({}), maxChars: OBSERVATION_BASELINE_CHARS });
9442
+ const clipped = "completeness" in outline2 && outline2.completeness.characterLimited;
9443
+ const kept = { text: outline2.text, url: result.url, clipped, document: documentBefore };
9444
+ this.observations.set(tabId, kept);
9445
+ if (this.observations.size > 64)
9446
+ this.observations.delete(this.observations.keys().next().value);
9447
+ this.outlines.set(result, kept);
9448
+ }
7907
9449
  }
7908
9450
  return result;
7909
9451
  }
@@ -7933,7 +9475,7 @@ class BrowserRuntime {
7933
9475
  } else if (input.crop) {
7934
9476
  const crop = input.crop;
7935
9477
  if (crop.x + crop.width > state.width || crop.y + crop.height > state.height)
7936
- throw refusal2("screenshot_crop_outside_viewport", "Pass a crop inside the viewport in its CSS pixels (x + width at most result.viewport.width, y + height at most result.viewport.height), or scroll first. Nothing was captured.", { viewport: { width: state.width, height: state.height } });
9478
+ throw refusal3("screenshot_crop_outside_viewport", "Pass a crop inside the viewport in its CSS pixels (x + width at most result.viewport.width, y + height at most result.viewport.height), or scroll first. Nothing was captured.", { viewport: { width: state.width, height: state.height } });
7937
9479
  [region, format, kind, extra] = [{ kind: "viewport", x: crop.x, y: crop.y, width: crop.width, height: crop.height }, SCREENSHOT_PNG, "crop", {}];
7938
9480
  } else if (input.fullPage === true) {
7939
9481
  execution.screenshotStage?.("screenshot_metrics");
@@ -8018,7 +9560,9 @@ class BrowserRuntime {
8018
9560
  if (!Number.isFinite(x) || !Number.isFinite(y))
8019
9561
  throw invalidInput("move_mouse requires numeric x and y coordinates.");
8020
9562
  this.cursor.delete(tabId);
8021
- await withFramesDrawn(page, () => page.mouse.move(x, y));
9563
+ await withFramesDrawn(page, () => this.atPoint(page, { x, y }, async (target2, local) => {
9564
+ await target2.move(local);
9565
+ }, () => page.mouse.move(x, y)));
8022
9566
  this.cursor.set(tabId, { x, y });
8023
9567
  return { tabId, x, y };
8024
9568
  }
@@ -8041,17 +9585,20 @@ class BrowserRuntime {
8041
9585
  if (!Number.isFinite(x) || !Number.isFinite(y))
8042
9586
  throw new Error("mouse_click by coordinates requires numeric x and y.");
8043
9587
  this.cursor.delete(tabId);
8044
- await withFramesDrawn(page, async () => {
9588
+ await withFramesDrawn(page, () => this.atPoint(page, { x, y }, async (target2, local) => {
9589
+ await target2.click(local, button, clickCount);
9590
+ this.cursor.set(tabId, { x, y });
9591
+ }, async () => {
8045
9592
  await page.mouse.move(x, y);
8046
9593
  this.cursor.set(tabId, { x, y });
8047
9594
  await page.mouse.click(x, y, { button, clickCount });
8048
- });
9595
+ }));
8049
9596
  return { tabId, x, y, button, clickCount };
8050
9597
  }
8051
9598
  const cursor = this.cursor.get(tabId);
8052
9599
  if (!cursor)
8053
- throw refusal2("pointer_unknown", "Pass a ref or a target, or x/y: the center of a box from browser_read_page with boxes: true, or a point in a screenshot with its screenshotId. Nothing was clicked.");
8054
- await withFramesDrawn(page, () => page.mouse.click(cursor.x, cursor.y, { button, clickCount }));
9600
+ throw refusal3("pointer_unknown", "Pass a ref or a target, or x/y: the center of a box from browser_read_page with boxes: true, or a point in a screenshot with its screenshotId. Nothing was clicked.");
9601
+ await withFramesDrawn(page, () => this.atPoint(page, cursor, (target2, local) => target2.click(local, button, clickCount), () => page.mouse.click(cursor.x, cursor.y, { button, clickCount })));
8055
9602
  return { tabId, ...cursor, button };
8056
9603
  }
8057
9604
  case "scroll": {
@@ -8095,11 +9642,15 @@ class BrowserRuntime {
8095
9642
  this.cursor.delete(tabId);
8096
9643
  const deltaX = direction === "left" ? -amount : direction === "right" ? amount : 0;
8097
9644
  const deltaY = direction === "up" ? -amount : direction === "down" ? amount : 0;
8098
- await withFramesDrawn(page, async () => {
9645
+ await withFramesDrawn(page, () => this.atPoint(page, pointer, async (target2, local) => {
9646
+ await target2.move(local);
9647
+ this.cursor.set(tabId, pointer);
9648
+ await target2.wheel(local, deltaX, deltaY);
9649
+ }, async () => {
8099
9650
  await page.mouse.move(pointer.x, pointer.y);
8100
9651
  this.cursor.set(tabId, pointer);
8101
9652
  await page.mouse.wheel(deltaX, deltaY);
8102
- });
9653
+ }));
8103
9654
  return { tabId, direction, amount, ...pointer };
8104
9655
  }
8105
9656
  case "wait_for": {
@@ -8159,14 +9710,15 @@ class BrowserRuntime {
8159
9710
  throw await this.pointerFailure(error, locator, ref, "form_input");
8160
9711
  }
8161
9712
  const kind = info.kind === "select" && info.multiple ? "multiselect" : info.kind;
9713
+ let clicked = {};
8162
9714
  const expectField = (field) => {
8163
9715
  if (provided[0] !== field)
8164
- throw refusal2("invalid_browser_input", `This element (kind ${kind}) takes ${field}, not ${provided[0]}: pass ${field} instead. Nothing was changed.`, { ref, kind, tag: info.tag });
9716
+ throw refusal3("invalid_browser_input", `This element (kind ${kind}) takes ${field}, not ${provided[0]}: pass ${field} instead. Nothing was changed.`, { ref, kind, tag: info.tag });
8165
9717
  };
8166
9718
  const matchOption = (options, entry) => {
8167
9719
  const match2 = options.find((option) => option.value === entry) ?? options.find((option) => option.label === entry.trim());
8168
9720
  if (!match2)
8169
- throw refusal2("option_not_found", "Pass the value or the label of one of the options in options (the first 20 of the select, page data). Nothing was changed.", { ref, options: options.slice(0, 20) });
9721
+ throw refusal3("option_not_found", "Pass the value or the label of one of the options in options (the first 20 of the select, page data). Nothing was changed.", { ref, options: options.slice(0, 20) });
8170
9722
  return match2.value;
8171
9723
  };
8172
9724
  try {
@@ -8188,7 +9740,7 @@ class BrowserRuntime {
8188
9740
  }
8189
9741
  case "checkable":
8190
9742
  expectField("checked");
8191
- await withFramesDrawn(page, () => this.setCheckedAtRef(page, tabId, locator, ref, input.checked === true));
9743
+ clicked = await withFramesDrawn(page, () => this.setCheckedAtRef(page, tabId, locator, ref, input.checked === true));
8192
9744
  break;
8193
9745
  case "text":
8194
9746
  case "contenteditable":
@@ -8205,7 +9757,7 @@ class BrowserRuntime {
8205
9757
  throw error;
8206
9758
  throw await this.pointerFailure(error, locator, ref, "form_input");
8207
9759
  }
8208
- return { tabId, ref, ...match ? { match } : {}, kind };
9760
+ return { tabId, ref, ...match ? { match } : {}, kind, ...clicked };
8209
9761
  }
8210
9762
  case "keyboard": {
8211
9763
  const keys = Array.isArray(input.keys) ? input.keys : [];
@@ -8371,11 +9923,11 @@ ${code2}
8371
9923
 
8372
9924
  // cli/src/runtime/cancellation.ts
8373
9925
  import { AsyncLocalStorage } from "node:async_hooks";
8374
- import { createRequire as createRequire3 } from "node:module";
9926
+ import { createRequire as createRequire4 } from "node:module";
8375
9927
  var current = new AsyncLocalStorage;
8376
9928
  var installed = new WeakSet;
8377
9929
  function installCancellation(context) {
8378
- const require2 = createRequire3(import.meta.url);
9930
+ const require2 = createRequire4(import.meta.url);
8379
9931
  if (require2("playwright-core/package.json").version !== "1.63.0")
8380
9932
  throw new Error("Cancellation adapter unavailable");
8381
9933
  const connection = context._connection;
@@ -8400,9 +9952,38 @@ function outsideCancellation(work) {
8400
9952
  return current.exit(work);
8401
9953
  }
8402
9954
 
9955
+ // cli/src/runtime/frame-documents.ts
9956
+ import { createRequire as createRequire5 } from "node:module";
9957
+ var requirePlaywright4 = createRequire5(import.meta.url);
9958
+ var SUPPORTED_PLAYWRIGHT_VERSION4 = "1.63.0";
9959
+ var supported;
9960
+ function playwrightSupported() {
9961
+ if (supported === undefined) {
9962
+ try {
9963
+ supported = requirePlaywright4("playwright-core/package.json").version === SUPPORTED_PLAYWRIGHT_VERSION4;
9964
+ } catch {
9965
+ supported = false;
9966
+ }
9967
+ }
9968
+ return supported;
9969
+ }
9970
+ function followNewDocuments(frame, onNewDocument) {
9971
+ if (!playwrightSupported())
9972
+ return false;
9973
+ const events = frame._eventEmitter;
9974
+ if (typeof events?.on !== "function")
9975
+ return false;
9976
+ events.on("navigated", (event) => {
9977
+ if (event && !event.error && event.newDocument)
9978
+ onNewDocument();
9979
+ });
9980
+ return true;
9981
+ }
9982
+
8403
9983
  // cli/src/runtime/native.ts
8404
9984
  var BROWSER_OPERATIONS = ["list_tabs", "open_tab", "close_tab", "navigate", "history", "present", "set_viewport", "read_page", "screenshot", "inspect", "capabilities", "mouse_click", "move_mouse", "hover", "drag", "scroll", "form_input", "keyboard", "keyboard_type", "select_text", "edit_text", "batch", "wait_for", "events", "handle_dialog", "diagnostics", "run_js", "export_page", "clipboard", "webmcp_list", "webmcp_call", "tab_lifecycle", "create_session", "list_sessions", "end_session"];
8405
9985
  var scopeKey = (s) => JSON.stringify([s.browserId, s.tokenId, s.sessionKey, s.instanceId]);
9986
+ var FRAME_KEY = /^(\d+)([.:])\d+$/;
8406
9987
  var SESSIONS_UNAVAILABLE = "Browser sessions are unavailable in this browser right now; the terminal that runs browser-mcp says why. Tell the user. Tabs of the default session keep working.";
8407
9988
 
8408
9989
  class NativeRuntime {
@@ -8413,7 +9994,12 @@ class NativeRuntime {
8413
9994
  plugins = [];
8414
9995
  owners = new Map;
8415
9996
  closedOwners = new Map;
8416
- generations = new Map;
9997
+ documents = new Map;
9998
+ frameSerials = new WeakMap;
9999
+ frameNavigations = new WeakMap;
10000
+ frameDocuments = new WeakMap;
10001
+ followedFrames = new WeakSet;
10002
+ nextFrameSerial = 0;
8417
10003
  tracking = new WeakMap;
8418
10004
  ended = new Set;
8419
10005
  epochs = new Map;
@@ -8434,6 +10020,7 @@ class NativeRuntime {
8434
10020
  this.serverOrigin = serverOrigin;
8435
10021
  installCancellation(context);
8436
10022
  this.engine = new BrowserRuntime(context, directory, `${directory}.uploads`, (download, page, downloadId) => this.download(download, page, downloadId), async (page) => this.assertPageAvailable(page), passkeyDetection, screenshotMaxEdge);
10023
+ this.engine.httpAuthPolicy = (tabId, acting) => !this.disconnected && (acting || this.owners.has(tabId) || this.userControlledTabs.has(tabId));
8437
10024
  context.on("page", (page) => {
8438
10025
  this.track(page);
8439
10026
  });
@@ -8485,7 +10072,7 @@ class NativeRuntime {
8485
10072
  }
8486
10073
  async trackPage(page) {
8487
10074
  const id = await this.engine.idFor(page);
8488
- this.generations.set(id, 0);
10075
+ this.documents.set(id, 0);
8489
10076
  const opener = await page.opener();
8490
10077
  if (opener) {
8491
10078
  await this.track(opener);
@@ -8493,21 +10080,26 @@ class NativeRuntime {
8493
10080
  if (owner)
8494
10081
  this.owners.set(id, { ...owner });
8495
10082
  }
8496
- page.on("framenavigated", () => {
8497
- const gen = (this.generations.get(id) ?? 0) + 1;
8498
- this.generations.set(id, gen);
8499
- this.enqueue(async () => {
8500
- for (const plugin of this.plugins)
8501
- await plugin.onNavigation?.(id, gen);
8502
- });
10083
+ const documentEnded = () => this.enqueue(async () => {
10084
+ for (const plugin of this.plugins)
10085
+ await plugin.onNavigation?.(id);
10086
+ });
10087
+ page.on("framenavigated", (frame) => {
10088
+ this.frameNavigations.set(frame, (this.frameNavigations.get(frame) ?? 0) + 1);
10089
+ if (!this.followedFrames.has(frame))
10090
+ this.frameDocuments.set(frame, (this.frameDocuments.get(frame) ?? 0) + 1);
10091
+ if (!frame.parentFrame())
10092
+ this.documents.set(id, (this.documents.get(id) ?? 0) + 1);
10093
+ documentEnded();
8503
10094
  });
10095
+ page.on("framedetached", documentEnded);
8504
10096
  page.on("close", () => {
8505
10097
  const owner = this.owners.get(id);
8506
10098
  if (owner) {
8507
10099
  this.closedOwners.set(page, owner);
8508
10100
  setTimeout(() => this.closedOwners.delete(page), 60000).unref?.();
8509
10101
  }
8510
- this.generations.delete(id);
10102
+ this.documents.delete(id);
8511
10103
  this.owners.delete(id);
8512
10104
  this.enqueue(async () => {
8513
10105
  for (const plugin of this.plugins)
@@ -8515,6 +10107,37 @@ class NativeRuntime {
8515
10107
  });
8516
10108
  });
8517
10109
  }
10110
+ serialOf(frame) {
10111
+ let serial = this.frameSerials.get(frame);
10112
+ if (serial === undefined) {
10113
+ serial = ++this.nextFrameSerial;
10114
+ this.frameSerials.set(frame, serial);
10115
+ if (followNewDocuments(frame, () => this.frameDocuments.set(frame, (this.frameDocuments.get(frame) ?? 0) + 1)))
10116
+ this.followedFrames.add(frame);
10117
+ }
10118
+ return serial;
10119
+ }
10120
+ keyOf(frame, kind) {
10121
+ const serial = this.serialOf(frame);
10122
+ return kind === "navigation" ? `${serial}.${this.frameNavigations.get(frame) ?? 0}` : `${serial}:${this.frameDocuments.get(frame) ?? 0}`;
10123
+ }
10124
+ frameShowing(page, key2) {
10125
+ const match = FRAME_KEY.exec(key2);
10126
+ if (!match)
10127
+ return;
10128
+ const serial = Number(match[1]), kind = match[2] === ":" ? "document" : "navigation";
10129
+ const frame = page.frames().find((candidate) => this.frameSerials.get(candidate) === serial);
10130
+ return frame && !frame.isDetached() && this.keyOf(frame, kind) === key2 ? { frame, kind } : undefined;
10131
+ }
10132
+ documentCurrent(tabId, document2) {
10133
+ let page;
10134
+ try {
10135
+ page = this.engine.page(tabId);
10136
+ } catch {
10137
+ return false;
10138
+ }
10139
+ return !page.isClosed() && !!this.frameShowing(page, document2);
10140
+ }
8518
10141
  revokeOwnership(tabId) {
8519
10142
  this.owners.delete(tabId);
8520
10143
  let page;
@@ -8553,7 +10176,7 @@ class NativeRuntime {
8553
10176
  await this.discardDownload(download, spool);
8554
10177
  return { state: "canceled", readiness: "unavailable", code: "capture_unavailable" };
8555
10178
  }
8556
- return handler.onDownload(download, id, owner, this.generations.get(id) ?? 0, downloadId, spool);
10179
+ return handler.onDownload(download, id, owner, downloadId, spool);
8557
10180
  }
8558
10181
  async discardDownload(download, spool) {
8559
10182
  const plugin = this.plugins.find((p) => p.discardDownload);
@@ -8575,10 +10198,16 @@ class NativeRuntime {
8575
10198
  throw new RuntimeFault("tab_closed", "Use browser_list_tabs to choose an open tab.", true);
8576
10199
  }
8577
10200
  async resolveTarget(tabId, scope, frames = []) {
10201
+ return await this.locate(tabId, scope, frames, "navigation");
10202
+ }
10203
+ async locate(tabId, scope, frames, kind) {
8578
10204
  this.validateScope(scope);
8579
10205
  const page = await this.claimPage(tabId, scope);
8580
10206
  await this.track(page);
8581
10207
  this.assertPageAvailable(page);
10208
+ const loading = await this.engine.pageEvents(page)?.loadingPage();
10209
+ if (loading)
10210
+ throw new RuntimeFault("navigation_loading", NAVIGATION_LOADING_RECOVERY, true, { pendingNavigation: loading }, true);
8582
10211
  let frame = page.mainFrame();
8583
10212
  for (const selector of frames) {
8584
10213
  const locator = frame.locator(selector);
@@ -8591,18 +10220,31 @@ class NativeRuntime {
8591
10220
  throw new RuntimeFault("frame_not_found", "Pass frames selectors, outermost first, that each match exactly one loaded iframe; browser_read_page shows the frames. Nothing was dispatched.", true, undefined, true);
8592
10221
  frame = next;
8593
10222
  }
8594
- const generation = this.generations.get(tabId) ?? 0;
8595
- const scopeEpoch = this.epochs.get(scopeKey(scope)) ?? 0;
10223
+ return this.bound(page, frame, tabId, scope, kind);
10224
+ }
10225
+ async resolveDocument(tabId, scope, document2) {
10226
+ this.validateScope(scope);
10227
+ const page = await this.claimPage(tabId, scope);
10228
+ await this.track(page);
10229
+ this.assertPageAvailable(page);
10230
+ const shown = this.frameShowing(page, document2);
10231
+ if (!shown)
10232
+ throw new Error("Stale document or scope");
10233
+ return this.bound(page, shown.frame, tabId, scope, shown.kind, document2);
10234
+ }
10235
+ bound(page, frame, tabId, scope, kind, document2 = this.keyOf(frame, kind)) {
10236
+ const scopeEpoch = this.epochs.get(scopeKey(scope)) ?? 0, pageEpoch = this.pageEpochs.get(page) ?? 0;
8596
10237
  const assertCurrent = () => {
8597
10238
  this.validateScope(scope);
8598
10239
  this.assertPageAvailable(page);
8599
- if ((this.epochs.get(scopeKey(scope)) ?? 0) !== scopeEpoch || frame.isDetached() || this.generations.get(tabId) !== generation || scopeKey(this.owners.get(tabId)) !== scopeKey(scope))
10240
+ const owner = this.owners.get(tabId);
10241
+ if ((this.epochs.get(scopeKey(scope)) ?? 0) !== scopeEpoch || (this.pageEpochs.get(page) ?? 0) !== pageEpoch || frame.isDetached() || this.keyOf(frame, kind) !== document2 || !owner || scopeKey(owner) !== scopeKey(scope))
8600
10242
  throw new Error("Stale document or scope");
8601
10243
  };
8602
- return { page, frame, tabId, generation, assertCurrent };
10244
+ return { page, frame, tabId, document: document2, generation: this.frameNavigations.get(frame) ?? 0, assertCurrent };
8603
10245
  }
8604
10246
  async resolveUploadTarget(tabId, args, scope) {
8605
- const target2 = await this.resolveTarget(tabId, scope, Array.isArray(args.frames) ? args.frames : []);
10247
+ const target2 = await this.locate(tabId, scope, Array.isArray(args.frames) ? args.frames : [], "document");
8606
10248
  let parsed;
8607
10249
  try {
8608
10250
  parsed = parseUploadTarget(args);
@@ -8614,9 +10256,14 @@ class NativeRuntime {
8614
10256
  const frame = await element.ownerFrame();
8615
10257
  if (!frame || frame.isDetached())
8616
10258
  throw uploadRefusal.changed();
10259
+ const input = this.bound(target2.page, frame, tabId, scope, "document");
10260
+ const assertCurrent = () => {
10261
+ target2.assertCurrent();
10262
+ input.assertCurrent();
10263
+ };
8617
10264
  const info = await element.evaluate((el) => ({ file: el instanceof HTMLInputElement && el.type === "file" && !el.webkitdirectory && el.isConnected, multiple: el instanceof HTMLInputElement && el.multiple }));
8618
10265
  try {
8619
- target2.assertCurrent();
10266
+ assertCurrent();
8620
10267
  } catch {
8621
10268
  throw uploadRefusal.changed();
8622
10269
  }
@@ -8625,7 +10272,7 @@ class NativeRuntime {
8625
10272
  const files = Array.isArray(args.fileIds) ? args.fileIds.length : 1;
8626
10273
  if (files > 1 && !info.multiple)
8627
10274
  throw uploadRefusal.single(files);
8628
- return { ...target2, frame, element, release: () => element.dispose() };
10275
+ return { ...input, assertCurrent, element, release: () => element.dispose() };
8629
10276
  } catch (e) {
8630
10277
  await element.dispose();
8631
10278
  throw notDispatchedFault(e);
@@ -8746,7 +10393,7 @@ class NativeRuntime {
8746
10393
  if (tabId)
8747
10394
  this.sessions?.assertTabAvailable(tabId);
8748
10395
  const page = tabId ? this.engine.page(tabId) : undefined;
8749
- const generation = tabId ? this.generations.get(tabId) : undefined;
10396
+ const admittedDocument = tabId ? this.documents.get(tabId) : undefined;
8750
10397
  return (checkDocument = true) => {
8751
10398
  if (this.scopeEpoch(scope) !== epoch || this.connectionEpoch !== connectionEpoch)
8752
10399
  throw new RuntimeFault("scope_rejected", "Scope or connection changed while waiting; submit a fresh authorized request.", true);
@@ -8759,7 +10406,7 @@ class NativeRuntime {
8759
10406
  } catch {
8760
10407
  throw new RuntimeFault("tab_closed", "Select an open tab before submitting a new request.", true);
8761
10408
  }
8762
- if (current2 !== page || checkDocument && this.generations.get(tabId) !== generation)
10409
+ if (current2 !== page || checkDocument && this.documents.get(tabId) !== admittedDocument)
8763
10410
  throw new RuntimeFault("stale_queued_target", "The target document changed while waiting. Observe it again before submitting a new request.", true);
8764
10411
  const owner = this.owners.get(tabId);
8765
10412
  if (owner && scopeKey(owner) !== scopeKey(scope))
@@ -8819,7 +10466,8 @@ class NativeRuntime {
8819
10466
  begin();
8820
10467
  this.revocationEpoch++;
8821
10468
  this.revokeOwnership(tabId);
8822
- this.generations.set(tabId, (this.generations.get(tabId) ?? 0) + 1);
10469
+ this.documents.set(tabId, (this.documents.get(tabId) ?? 0) + 1);
10470
+ this.engine.handHttpAuthToChrome("handed_off", tabId);
8823
10471
  for (const p of this.plugins)
8824
10472
  await p.onHandoff?.(tabId, scope);
8825
10473
  return { released: true, tabId };
@@ -8862,7 +10510,9 @@ class NativeRuntime {
8862
10510
  this.owners.set(tabId, { ...scope });
8863
10511
  };
8864
10512
  const { session: _session, ...tabArgs } = args;
8865
- const result = await this.engine.execute(op, op === "open_tab" ? tabArgs : args, { sessionId: scopeKey(scope), operationId, beforeDispatch: begin, screenshotStage, onTabOpened, openIn: session?.context });
10513
+ const vault = op === "handle_dialog" && typeof args.vaultId === "string" ? this.plugins.find((p) => p.revealHttpAuth) : undefined;
10514
+ const revealHttpAuth = vault ? () => vault.revealHttpAuth(scope, String(args.vaultId), args.names) : undefined;
10515
+ const result = await this.engine.execute(op, op === "open_tab" ? tabArgs : args, { sessionId: scopeKey(scope), operationId, beforeDispatch: begin, screenshotStage, onTabOpened, openIn: session?.context, revealHttpAuth });
8866
10516
  if (this.disconnected || (this.epochs.get(scopeKey(scope)) ?? 0) !== operationEpoch)
8867
10517
  throw new Error("Scope ended during execution; outcome uncertain");
8868
10518
  const target3 = op === "capabilities" && typeof args.tabId === "string" ? await this.targetCapabilities(args.tabId, scope) : undefined;
@@ -8887,8 +10537,10 @@ class NativeRuntime {
8887
10537
  controller.abort(new Error("Runtime scope revoked"));
8888
10538
  this.revocationEpoch++;
8889
10539
  for (const [id, owner] of this.owners)
8890
- if (scopeKey(owner) === key2)
10540
+ if (scopeKey(owner) === key2) {
8891
10541
  this.revokeOwnership(id);
10542
+ this.engine.handHttpAuthToChrome("session_ended", id);
10543
+ }
8892
10544
  for (const [page, owner] of this.closedOwners)
8893
10545
  if (scopeKey(owner) === key2)
8894
10546
  this.closedOwners.delete(page);
@@ -8898,7 +10550,7 @@ class NativeRuntime {
8898
10550
  }
8899
10551
  async shutdown() {
8900
10552
  await this.disconnect();
8901
- for (const tabId of this.generations.keys())
10553
+ for (const tabId of this.documents.keys())
8902
10554
  for (const p of this.plugins)
8903
10555
  await p.onTabClose?.(tabId);
8904
10556
  await this.hooks;
@@ -8907,6 +10559,7 @@ class NativeRuntime {
8907
10559
  async disconnect() {
8908
10560
  this.disconnected = true;
8909
10561
  this.connectionEpoch++;
10562
+ this.engine.handHttpAuthToChrome("runtime_disconnected");
8910
10563
  for (const controllers of this.controllers.values())
8911
10564
  for (const controller of controllers)
8912
10565
  controller.abort(new Error("Runtime disconnected"));
@@ -8931,19 +10584,171 @@ import path10 from "node:path";
8931
10584
  // cli/src/live/producer.ts
8932
10585
  import WebSocket from "ws";
8933
10586
 
10587
+ // shared/browser-tools.ts
10588
+ var TAKEOVER_TOOL = "browser_takeover";
10589
+ var TAKEOVER_STATUS_TOOL = "browser_takeover_status";
10590
+ var TAKEOVER_RECLAIM_TOOL = "browser_takeover_reclaim";
10591
+ var TAKEOVER_TOOLS = new Set([TAKEOVER_TOOL, TAKEOVER_STATUS_TOOL, TAKEOVER_RECLAIM_TOOL]);
10592
+ var MAX_VIEWPORT_DIMENSION2 = 4096;
10593
+ var observedActions2 = new Set([
10594
+ "navigate",
10595
+ "history",
10596
+ "mouse_click",
10597
+ "hover",
10598
+ "drag",
10599
+ "scroll",
10600
+ "form_input",
10601
+ "keyboard",
10602
+ "keyboard_type",
10603
+ "edit_text",
10604
+ "select_text",
10605
+ "handle_dialog",
10606
+ "webmcp_call"
10607
+ ]);
10608
+ var batchActions2 = new Set([
10609
+ "read_page",
10610
+ "inspect",
10611
+ "wait_for",
10612
+ "mouse_click",
10613
+ "hover",
10614
+ "scroll",
10615
+ "form_input",
10616
+ "keyboard",
10617
+ "keyboard_type",
10618
+ "select_text",
10619
+ "edit_text",
10620
+ "sleep"
10621
+ ]);
10622
+ var screenshotActions = new Set(["mouse_click", "move_mouse", "scroll", "drag"]);
10623
+ var compactForms = new WeakMap;
10624
+ function advertisedAs(canonical, compact) {
10625
+ compactForms.set(canonical, compact);
10626
+ return canonical;
10627
+ }
10628
+ var locatorFields = ["ref", "selector", "role", "name", "text", "label", "placeholder", "testId"];
10629
+ var locatorStrategies = (allowName) => locatorFields.filter((field) => allowName || field !== "name").map((field) => ({
10630
+ type: "object",
10631
+ required: [field],
10632
+ properties: Object.fromEntries(locatorFields.map((key2) => [
10633
+ key2,
10634
+ key2 === field ? { type: "string" } : field === "role" && key2 === "name" ? { type: ["string", "null"] } : { type: "null" }
10635
+ ]))
10636
+ }));
10637
+ var snapshotTarget = {
10638
+ type: "object",
10639
+ additionalProperties: false,
10640
+ description: "One locator: ref, selector, role (with optional name), name, text, label, placeholder or testId, and exact (default true; false matches case-insensitive substrings). Open shadow roots included; a ref already names its frame, so omit frames with one.",
10641
+ anyOf: locatorStrategies(true),
10642
+ properties: Object.fromEntries([
10643
+ ...locatorFields.map((name) => [name, { type: ["string", "null"], minLength: 1, maxLength: 2000, pattern: "\\S" }]),
10644
+ ["exact", { type: ["boolean", "null"] }]
10645
+ ])
10646
+ };
10647
+ var waitTarget = {
10648
+ ...snapshotTarget,
10649
+ anyOf: locatorStrategies(false),
10650
+ description: "One locator: ref, selector, role (with optional name), text, label, placeholder or testId; exact defaults to true, false matches case-insensitive substrings. Hidden candidates and open shadow roots count; a ref names its frame, otherwise frames selects one."
10651
+ };
10652
+ var actionTargetDescription = "Instead of ref: one locator, as browser_wait_for's target ({role, name}, {text}, {label}, {placeholder}, {testId} or {selector}; exact), for a visible element of the main document, found when the action runs (up to 5 s). No match or several are refused before any input, with candidates.";
10653
+ var actionTarget = advertisedAs({
10654
+ ...waitTarget,
10655
+ description: actionTargetDescription
10656
+ }, { type: "object", description: actionTargetDescription });
10657
+ var waitText = { type: "string", minLength: 1, maxLength: 2000, pattern: "\\S" };
10658
+ var networkQuietBounds = { type: "integer", minimum: MIN_NETWORK_QUIET_MS, maximum: MAX_NETWORK_QUIET_MS };
10659
+ var ignoreUrlList = { type: "array", minItems: 1, maxItems: MAX_IGNORE_URLS, items: { type: "string", minLength: 1, maxLength: 2000 } };
10660
+ var navigationDescription = "Wait for the main frame to navigate (reloads and same-document navigations too), armed before the input; the result reports navigation.matched.";
10661
+ var navigationExpectation = advertisedAs({
10662
+ type: "object",
10663
+ additionalProperties: false,
10664
+ description: navigationDescription,
10665
+ properties: {
10666
+ url: { type: ["string", "null"], minLength: 1, maxLength: 4000, description: "Expected URL glob (* within a path segment, ** across)." },
10667
+ waitUntil: { type: ["string", "null"], enum: ["commit", "domcontentloaded", "load", null], description: "Default domcontentloaded." },
10668
+ timeoutMs: { type: ["integer", "null"], minimum: 500, maximum: 25000, description: "Default 10000." }
10669
+ }
10670
+ }, {
10671
+ type: "object",
10672
+ description: navigationDescription,
10673
+ properties: {
10674
+ url: { type: "string", description: "Expected URL glob (* within a path segment, ** across)." },
10675
+ waitUntil: { type: "string", enum: ["commit", "domcontentloaded", "load"], description: "Default domcontentloaded." },
10676
+ timeoutMs: { type: "integer", minimum: 500, maximum: 25000, description: "Default 10000." }
10677
+ }
10678
+ });
10679
+ var observeDescription = 'Read the page after the action: {} or {mode: "summary"} for the changed lines, {mode: "full"} for all of it.';
10680
+ var observe = advertisedAs({
10681
+ anyOf: [
10682
+ { type: "boolean", enum: [false] },
10683
+ { type: "object", additionalProperties: false, properties: { mode: { type: ["string", "null"], enum: ["summary", "full", null] }, maxChars: { type: ["integer", "null"], minimum: 1000, maximum: 30000 } } }
10684
+ ],
10685
+ description: observeDescription
10686
+ }, {
10687
+ anyOf: [
10688
+ { type: "boolean", enum: [false] },
10689
+ { type: "object", properties: { mode: { type: "string", enum: ["summary", "full"] }, maxChars: { type: "integer", minimum: 1000, maximum: 30000 } } }
10690
+ ],
10691
+ description: observeDescription
10692
+ });
10693
+ var expectDescription = `Needs observe (an object such as {}). Then waits for one condition, as browser_wait_for: text, textGone, target (in state, default visible), url or networkQuietMs, at most ${MAX_WAIT_MS / 1000} s; reports expected.matched.`;
10694
+ var waitStates = ["visible", "hidden", "attached", "detached", "enabled", "disabled"];
10695
+ var expect = advertisedAs({
10696
+ type: "object",
10697
+ additionalProperties: false,
10698
+ properties: {
10699
+ text: { ...waitText, type: ["string", "null"] },
10700
+ textGone: { ...waitText, type: ["string", "null"] },
10701
+ exact: { type: ["boolean", "null"] },
10702
+ target: waitTarget,
10703
+ url: { type: ["string", "null"] },
10704
+ networkQuietMs: { ...networkQuietBounds, type: ["integer", "null"] },
10705
+ ignoreUrls: { ...ignoreUrlList, type: ["array", "null"] },
10706
+ state: { type: ["string", "null"], enum: [...waitStates, null] },
10707
+ timeoutMs: { type: ["integer", "null"], minimum: MIN_WAIT_MS }
10708
+ },
10709
+ description: expectDescription
10710
+ }, {
10711
+ type: "object",
10712
+ properties: {
10713
+ text: { type: "string" },
10714
+ textGone: { type: "string" },
10715
+ exact: { type: "boolean" },
10716
+ target: { type: "object", description: "One locator, as browser_wait_for's target." },
10717
+ url: { type: "string" },
10718
+ networkQuietMs: { type: "integer", minimum: MIN_NETWORK_QUIET_MS, maximum: MAX_NETWORK_QUIET_MS },
10719
+ ignoreUrls: { type: "array", items: { type: "string" } },
10720
+ state: { type: "string", enum: waitStates },
10721
+ timeoutMs: { type: "integer", minimum: MIN_WAIT_MS }
10722
+ },
10723
+ description: expectDescription
10724
+ });
10725
+ var vaultName = { type: "string", pattern: "^[A-Za-z_][A-Za-z0-9_]*$", maxLength: 128 };
10726
+ var httpAuthNamesDescription = "HTTP sign-in: {username, password}, the vault names holding them, never the values.";
10727
+ var httpAuthNames = advertisedAs({
10728
+ type: "object",
10729
+ additionalProperties: false,
10730
+ required: ["username", "password"],
10731
+ properties: { username: vaultName, password: vaultName },
10732
+ description: httpAuthNamesDescription
10733
+ }, { type: "object", properties: { username: { type: "string" }, password: { type: "string" } }, description: httpAuthNamesDescription });
10734
+ var advertisedLocatorFields = Object.fromEntries([
10735
+ ...locatorFields.map((key2) => [key2, { type: ["string", "null"] }]),
10736
+ ["exact", { type: ["boolean", "null"] }]
10737
+ ]);
10738
+
8934
10739
  // backend/live-wire.ts
8935
10740
  var isRuntimeTabId = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
8936
10741
  var MAX_LIVE_FRAME_BYTES = 1500000;
8937
- var finite2 = (value, min, max) => Number.isFinite(value) && value >= min && value <= max;
10742
+ var finite3 = (value, min, max) => Number.isFinite(value) && value >= min && value <= max;
8938
10743
  var uint32 = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 4294967295;
8939
- var coordinate = (value) => typeof value === "number" && finite2(value, -1e5, 1e5);
8940
- var delta = (value) => typeof value === "number" && finite2(value, -1e6, 1e6);
10744
+ var coordinate = (value) => typeof value === "number" && finite3(value, -1e5, 1e5);
10745
+ var delta = (value) => typeof value === "number" && finite3(value, -1e6, 1e6);
8941
10746
  var TOOL = /^[a-z][a-z0-9_]{0,63}$/;
8942
10747
  function sanitizeLiveEvent(value) {
8943
10748
  if (!value || typeof value !== "object" || Array.isArray(value))
8944
10749
  return null;
8945
10750
  const e = value;
8946
- if (!isRuntimeTabId(e.runtimeTabId) || !uint32(e.navSeq) || typeof e.at !== "number" || !finite2(e.at, 0, 100000000000000))
10751
+ if (!isRuntimeTabId(e.runtimeTabId) || !uint32(e.navSeq) || typeof e.at !== "number" || !finite3(e.at, 0, 100000000000000))
8947
10752
  return null;
8948
10753
  const base = { runtimeTabId: e.runtimeTabId, navSeq: e.navSeq, at: e.at };
8949
10754
  switch (e.type) {
@@ -8977,6 +10782,8 @@ var KEY_CODE = /^[A-Za-z0-9]{0,32}$/;
8977
10782
  var CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/;
8978
10783
  var LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
8979
10784
  var cleanText = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max && !CONTROL.test(value) && !LONE_SURROGATE.test(value);
10785
+ var ANY_CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
10786
+ var credential2 = (value, max, allowEmpty) => typeof value === "string" && (allowEmpty || value.length > 0) && value.length <= max && !ANY_CONTROL.test(value) && !LONE_SURROGATE.test(value);
8980
10787
  var keyValue = (value) => typeof value === "string" && (NAMED_KEY.test(value) || value.length <= 4 && cleanText(value, 4) && !/[\t\n\r]/.test(value));
8981
10788
  var button = (value) => value === "left" || value === "middle" || value === "right";
8982
10789
  function sanitizeLiveInput(value) {
@@ -9004,6 +10811,11 @@ function sanitizeLiveInput(value) {
9004
10811
  case "dialog":
9005
10812
  if (typeof e.accept !== "boolean")
9006
10813
  return null;
10814
+ if (e.username !== undefined || e.password !== undefined) {
10815
+ if (!e.accept || e.text !== undefined || !credential2(e.username, MAX_HTTP_AUTH_USERNAME, false) || !credential2(e.password, MAX_HTTP_AUTH_PASSWORD, true))
10816
+ return null;
10817
+ return { kind: "dialog", accept: true, username: e.username, password: e.password };
10818
+ }
9007
10819
  if (e.text === undefined)
9008
10820
  return { kind: "dialog", accept: e.accept };
9009
10821
  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;
@@ -9015,8 +10827,17 @@ function sanitizeLiveInput(value) {
9015
10827
  return null;
9016
10828
  }
9017
10829
  }
9018
- var DIALOG_TYPES = new Set(["alert", "confirm", "prompt", "beforeunload", "passkey"]);
10830
+ var DIALOG_TYPES = new Set(["alert", "confirm", "prompt", "beforeunload", "passkey", "http_auth"]);
9019
10831
  var MAX_LIVE_DIALOG_MESSAGE = 500;
10832
+ function sanitizeTakeoverViewport(value) {
10833
+ if (value === null)
10834
+ return null;
10835
+ if (!value || typeof value !== "object" || Array.isArray(value))
10836
+ return;
10837
+ const { width, height } = value;
10838
+ const dimension = (n) => typeof n === "number" && Number.isInteger(n) && n >= 1 && n <= MAX_VIEWPORT_DIMENSION2;
10839
+ return dimension(width) && dimension(height) ? { width, height } : undefined;
10840
+ }
9020
10841
 
9021
10842
  // cli/src/live/wire.ts
9022
10843
  function mediaURL(server) {
@@ -9079,7 +10900,7 @@ class CaptureTimeout extends Error {
9079
10900
  this.stage = stage;
9080
10901
  }
9081
10902
  }
9082
- async function bounded2(stage, operation) {
10903
+ async function bounded3(stage, operation) {
9083
10904
  let timer2;
9084
10905
  try {
9085
10906
  return await Promise.race([operation, new Promise((_, reject) => {
@@ -9214,8 +11035,8 @@ class NativeLiveProducer {
9214
11035
  const cdp = this.cdp;
9215
11036
  this.cdp = undefined;
9216
11037
  if (cdp) {
9217
- await bounded2("stop_screencast", cdp.send("Page.stopScreencast")).catch(() => {});
9218
- await bounded2("detach", cdp.detach()).catch(() => {});
11038
+ await bounded3("stop_screencast", cdp.send("Page.stopScreencast")).catch(() => {});
11039
+ await bounded3("detach", cdp.detach()).catch(() => {});
9219
11040
  }
9220
11041
  }
9221
11042
  async reconcile(generation) {
@@ -9244,7 +11065,7 @@ class NativeLiveProducer {
9244
11065
  const initialNav = this.navSeq;
9245
11066
  let authorized = false;
9246
11067
  try {
9247
- authorized = await bounded2("authorize", this.options.authorizePage(page));
11068
+ authorized = await bounded3("authorize", this.options.authorizePage(page));
9248
11069
  } catch (error) {
9249
11070
  await this.teardown();
9250
11071
  if (generation === this.generation)
@@ -9312,12 +11133,12 @@ class NativeLiveProducer {
9312
11133
  let abandoned = false;
9313
11134
  const attaching = page.context().newCDPSession(page).then((session) => {
9314
11135
  if (abandoned)
9315
- bounded2("detach", session.detach()).catch(() => {});
11136
+ bounded3("detach", session.detach()).catch(() => {});
9316
11137
  return session;
9317
11138
  });
9318
11139
  let cdp;
9319
11140
  try {
9320
- cdp = await bounded2("attach", attaching);
11141
+ cdp = await bounded3("attach", attaching);
9321
11142
  } catch (error) {
9322
11143
  abandoned = true;
9323
11144
  throw error;
@@ -9347,7 +11168,7 @@ class NativeLiveProducer {
9347
11168
  checkingFrame = true;
9348
11169
  (async () => {
9349
11170
  try {
9350
- const allowed = await bounded2("frame_authorize", this.options.authorizePage(page));
11171
+ const allowed = await bounded3("frame_authorize", this.options.authorizePage(page));
9351
11172
  if (generation !== this.generation || nav !== this.navSeq || this.closed || !this.enabled || !this.active || this.socket !== ws || ws.readyState !== WebSocket.OPEN)
9352
11173
  return;
9353
11174
  if (!allowed || this.options.getPage(tab) !== page) {
@@ -9380,7 +11201,7 @@ class NativeLiveProducer {
9380
11201
  forward(event, this.navSeq);
9381
11202
  });
9382
11203
  const startNav = this.navSeq;
9383
- const stillAllowed = await bounded2("authorize", this.options.authorizePage(page));
11204
+ const stillAllowed = await bounded3("authorize", this.options.authorizePage(page));
9384
11205
  if (generation !== this.generation) {
9385
11206
  await this.teardown();
9386
11207
  return;
@@ -9395,7 +11216,7 @@ class NativeLiveProducer {
9395
11216
  this.state("blocked", "page_unavailable");
9396
11217
  return;
9397
11218
  }
9398
- await bounded2("start_screencast", cdp.send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: 1600, maxHeight: 1000, everyNthFrame: 1 }));
11219
+ await bounded3("start_screencast", cdp.send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: 1600, maxHeight: 1000, everyNthFrame: 1 }));
9399
11220
  if (generation !== this.generation) {
9400
11221
  await this.teardown();
9401
11222
  return;
@@ -9424,9 +11245,9 @@ class NativeLiveProducer {
9424
11245
  var MAX_QUEUE = 128;
9425
11246
  var STEP_TIMEOUT_MS = 3000;
9426
11247
  var SHOW_INTERVAL_MS = 1000;
9427
- var DIALOG_TYPES2 = new Set(["alert", "confirm", "prompt", "beforeunload", "passkey"]);
11248
+ var DIALOG_TYPES2 = new Set(["alert", "confirm", "prompt", "beforeunload", "passkey", "http_auth"]);
9428
11249
  var MODIFIERS = Object.entries(LIVE_MODIFIERS);
9429
- async function bounded3(work, ms) {
11250
+ async function bounded4(work, ms) {
9430
11251
  let timer2;
9431
11252
  await Promise.race([work.catch(() => {}), new Promise((resolve2) => {
9432
11253
  timer2 = setTimeout(resolve2, ms);
@@ -9440,13 +11261,14 @@ class TakeoverInput {
9440
11261
  queue = [];
9441
11262
  pumping;
9442
11263
  releases = new Map;
11264
+ layouts = new Map;
9443
11265
  constructor(options) {
9444
11266
  this.options = options;
9445
11267
  }
9446
11268
  get currentTab() {
9447
11269
  return this.group?.session?.tabId;
9448
11270
  }
9449
- activate(root) {
11271
+ activate(root, viewport) {
9450
11272
  if (!isRuntimeTabId(root) || this.group?.root === root)
9451
11273
  return;
9452
11274
  this.deactivate();
@@ -9455,16 +11277,26 @@ class TakeoverInput {
9455
11277
  this.lost(root);
9456
11278
  return;
9457
11279
  }
9458
- const group = { root, tabs: [root], ended: false, cleanup: [] };
11280
+ const group = { root, tabs: [root], ended: false, cleanup: [], fitted: new Set, ...viewport ? { viewport: { ...viewport } } : {} };
9459
11281
  this.group = group;
9460
11282
  this.join(group, root, page);
9461
11283
  this.focus(group, root, page);
11284
+ if (group.viewport)
11285
+ this.layout(group, root);
9462
11286
  }
9463
11287
  deactivate() {
9464
11288
  const group = this.group;
9465
11289
  if (group)
9466
11290
  this.end(group);
9467
11291
  }
11292
+ fit(viewport) {
11293
+ const group = this.group;
11294
+ if (!group || group.ended || viewport?.width === group.viewport?.width && viewport?.height === group.viewport?.height)
11295
+ return;
11296
+ group.viewport = viewport && { ...viewport };
11297
+ for (const tabId of viewport ? group.tabs : [...group.fitted])
11298
+ this.layout(group, tabId);
11299
+ }
9468
11300
  input(frame) {
9469
11301
  const session = this.group?.session;
9470
11302
  if (!session || frame.runtimeTabId !== session.tabId)
@@ -9487,15 +11319,13 @@ class TakeoverInput {
9487
11319
  this.push({ session, event });
9488
11320
  }
9489
11321
  async settled(tabId) {
9490
- const release = this.releases.get(tabId);
9491
- if (release)
9492
- await bounded3(release, STEP_TIMEOUT_MS);
11322
+ const release = this.releases.get(tabId), layout = this.layouts.get(tabId);
11323
+ await Promise.all([release && bounded4(release, STEP_TIMEOUT_MS), layout && bounded4(layout, STEP_TIMEOUT_MS)]);
9493
11324
  }
9494
11325
  async stop() {
9495
11326
  this.deactivate();
9496
11327
  const pumping = this.pumping;
9497
- if (pumping)
9498
- await bounded3(pumping, STEP_TIMEOUT_MS);
11328
+ await Promise.all([pumping && bounded4(pumping, STEP_TIMEOUT_MS), ...[...this.layouts.values()].map((layout) => bounded4(layout, STEP_TIMEOUT_MS))]);
9499
11329
  }
9500
11330
  join(group, tabId, page) {
9501
11331
  const onClose = () => this.left(group, tabId);
@@ -9521,10 +11351,13 @@ class TakeoverInput {
9521
11351
  group.tabs.push(id);
9522
11352
  this.join(group, id, popup);
9523
11353
  this.focus(group, id, popup);
11354
+ if (group.viewport)
11355
+ this.layout(group, id);
9524
11356
  }
9525
11357
  left(group, tabId) {
9526
11358
  if (group.ended || this.group !== group)
9527
11359
  return;
11360
+ group.fitted.delete(tabId);
9528
11361
  if (tabId === group.root) {
9529
11362
  this.end(group);
9530
11363
  this.lost(tabId);
@@ -9602,6 +11435,26 @@ class TakeoverInput {
9602
11435
  }
9603
11436
  if (group.session && !group.session.ended)
9604
11437
  this.close(group.session);
11438
+ for (const tabId of [...group.fitted])
11439
+ this.layout(group, tabId);
11440
+ }
11441
+ layout(group, tabId) {
11442
+ const setViewport = this.options.setViewport;
11443
+ if (!setViewport)
11444
+ return;
11445
+ const viewport = group.ended ? undefined : group.viewport;
11446
+ if (viewport)
11447
+ group.fitted.add(tabId);
11448
+ else if (!group.fitted.delete(tabId))
11449
+ return;
11450
+ const size = viewport ? { ...viewport } : null;
11451
+ const before = [this.layouts.get(tabId), this.options.agentActivity(tabId)];
11452
+ const done = Promise.all(before).then(() => setViewport(tabId, size)).catch(() => {});
11453
+ this.layouts.set(tabId, done);
11454
+ done.then(() => {
11455
+ if (this.layouts.get(tabId) === done)
11456
+ this.layouts.delete(tabId);
11457
+ });
9605
11458
  }
9606
11459
  report(group) {
9607
11460
  const session = group.session;
@@ -9618,8 +11471,10 @@ class TakeoverInput {
9618
11471
  let shown = null;
9619
11472
  if (dialog && type === "passkey")
9620
11473
  shown = { type, message: "", request: dialog.request === "create" ? "create" : "get", ...dialog.origin ? { origin: dialog.origin } : {} };
11474
+ else if (dialog && type === "http_auth")
11475
+ shown = { type, message: "", origin: dialog.origin, realm: dialog.realm ?? "", scheme: dialog.scheme === "digest" ? "digest" : "basic", frame: dialog.frame === "iframe" ? "iframe" : "main", attempt: dialog.attempt ?? 1 };
9621
11476
  else if (dialog && type && DIALOG_TYPES2.has(type))
9622
- shown = { type, message: dialog.message.slice(0, MAX_LIVE_DIALOG_MESSAGE), ...type === "prompt" ? { defaultValue: dialog.defaultValue.slice(0, MAX_LIVE_DIALOG_TEXT) } : {} };
11477
+ shown = { type, message: dialog.message.slice(0, MAX_LIVE_DIALOG_MESSAGE), ...type === "prompt" ? { defaultValue: (dialog.defaultValue ?? "").slice(0, MAX_LIVE_DIALOG_TEXT) } : {} };
9623
11478
  this.options.sendEvent({ type: "event", event: "live_dialog", runtimeTabId: tabId, dialog: shown });
9624
11479
  }
9625
11480
  push(item) {
@@ -9639,7 +11494,7 @@ class TakeoverInput {
9639
11494
  if (session.ended)
9640
11495
  continue;
9641
11496
  }
9642
- await bounded3(this.dispatch(session, event), STEP_TIMEOUT_MS);
11497
+ await bounded4(this.dispatch(session, event), STEP_TIMEOUT_MS);
9643
11498
  } finally {
9644
11499
  item2.done?.();
9645
11500
  }
@@ -9672,7 +11527,7 @@ class TakeoverInput {
9672
11527
  await this.answerDialog(events, event);
9673
11528
  return;
9674
11529
  }
9675
- if (events?.activeDialog())
11530
+ if (events?.activeDialog() && (events.javascriptDialogOpen() || event.kind !== "navigate"))
9676
11531
  return;
9677
11532
  if (event.kind === "show") {
9678
11533
  if (events?.passkeyPrompt())
@@ -9688,6 +11543,8 @@ class TakeoverInput {
9688
11543
  switch (event.kind) {
9689
11544
  case "mouse": {
9690
11545
  await this.syncModifiers(session, this.modifierMask(event.modifiers, event.mac));
11546
+ if (await this.routedMouse(session, event))
11547
+ return;
9691
11548
  if (event.type === "move" || session.pointer.x !== event.x || session.pointer.y !== event.y) {
9692
11549
  session.pointer = { x: event.x, y: event.y };
9693
11550
  await page.mouse.move(event.x, event.y);
@@ -9702,6 +11559,8 @@ class TakeoverInput {
9702
11559
  }
9703
11560
  case "wheel":
9704
11561
  await this.syncModifiers(session, this.modifierMask(event.modifiers, event.mac));
11562
+ if (await this.routedWheel(session, event))
11563
+ return;
9705
11564
  if (session.pointer.x !== event.x || session.pointer.y !== event.y) {
9706
11565
  session.pointer = { x: event.x, y: event.y };
9707
11566
  await page.mouse.move(event.x, event.y);
@@ -9734,6 +11593,88 @@ class TakeoverInput {
9734
11593
  return;
9735
11594
  }
9736
11595
  }
11596
+ async routeAt(session, x, y) {
11597
+ const route = session.route;
11598
+ if (route?.buttons.size)
11599
+ return route;
11600
+ if (session.buttons.size)
11601
+ return;
11602
+ const found = await FrameTarget.at(session.page, { x, y }, route?.target);
11603
+ if (found?.target === route?.target && route) {
11604
+ route.offset = found.offset;
11605
+ return route;
11606
+ }
11607
+ if (route)
11608
+ this.unroute(session);
11609
+ if (!found)
11610
+ return;
11611
+ session.route = { target: found.target, offset: found.offset, buttons: new Set };
11612
+ return session.route;
11613
+ }
11614
+ unroute(session) {
11615
+ const route = session.route;
11616
+ if (!route)
11617
+ return;
11618
+ session.route = undefined;
11619
+ route.target.dispose();
11620
+ route.drag?.stop();
11621
+ session.pointer = { x: Number.NaN, y: Number.NaN };
11622
+ }
11623
+ async routedMouse(session, event) {
11624
+ const route = await this.routeAt(session, event.x, event.y);
11625
+ if (!route)
11626
+ return false;
11627
+ const modifiers = this.modifierMask(event.modifiers, event.mac);
11628
+ const local = { x: event.x - route.offset.x, y: event.y - route.offset.y };
11629
+ const moved = event.type === "move" || session.pointer.x !== event.x || session.pointer.y !== event.y;
11630
+ session.pointer = { x: event.x, y: event.y };
11631
+ const data = route.buttons.size ? route.drag?.data : undefined;
11632
+ if (moved) {
11633
+ if (data) {
11634
+ await route.target.drag(route.entered ? "dragOver" : "dragEnter", local, data, modifiers);
11635
+ route.entered = true;
11636
+ } else
11637
+ await route.target.move(local, buttonBits(route.buttons), modifiers);
11638
+ if (route.buttons.size)
11639
+ route.moved = true;
11640
+ }
11641
+ if (event.type === "down") {
11642
+ if (!route.buttons.size) {
11643
+ route.drag = await DragInterception.start(session.page);
11644
+ route.moved = false;
11645
+ }
11646
+ route.buttons.add(event.button);
11647
+ await route.target.press(local, event.button, event.clickCount, buttonBits(route.buttons), modifiers);
11648
+ } else if (event.type === "up" && route.buttons.has(event.button)) {
11649
+ const dragged = route.buttons.size === 1 ? data ?? (route.moved ? await route.drag?.wait(DRAG_HANDOVER_MS) : undefined) : undefined;
11650
+ route.buttons.delete(event.button);
11651
+ if (dragged) {
11652
+ if (!route.entered)
11653
+ await route.target.drag("dragEnter", local, dragged, modifiers);
11654
+ await route.target.drag("drop", local, dragged, modifiers);
11655
+ }
11656
+ await route.target.release(local, event.button, event.clickCount, buttonBits(route.buttons), modifiers);
11657
+ if (!route.buttons.size) {
11658
+ await route.drag?.stop();
11659
+ route.drag = undefined;
11660
+ route.entered = false;
11661
+ }
11662
+ }
11663
+ return true;
11664
+ }
11665
+ async routedWheel(session, event) {
11666
+ const route = await this.routeAt(session, event.x, event.y);
11667
+ if (!route)
11668
+ return false;
11669
+ const modifiers = this.modifierMask(event.modifiers, event.mac);
11670
+ const local = { x: event.x - route.offset.x, y: event.y - route.offset.y };
11671
+ if (session.pointer.x !== event.x || session.pointer.y !== event.y) {
11672
+ session.pointer = { x: event.x, y: event.y };
11673
+ await route.target.move(local, buttonBits(route.buttons), modifiers);
11674
+ }
11675
+ await route.target.wheel(local, event.deltaX, event.deltaY, modifiers);
11676
+ return true;
11677
+ }
9737
11678
  async syncModifiers(session, mask) {
9738
11679
  for (const [name, bit] of MODIFIERS) {
9739
11680
  const held = [...session.keys].filter(([, key2]) => key2 === name);
@@ -9780,6 +11721,18 @@ class TakeoverInput {
9780
11721
  const buttons = [...session.buttons], keys = new Set(session.keys.values());
9781
11722
  session.buttons.clear();
9782
11723
  session.keys.clear();
11724
+ const route = session.route;
11725
+ if (route) {
11726
+ const local = { x: session.pointer.x - route.offset.x, y: session.pointer.y - route.offset.y };
11727
+ const at = Number.isFinite(local.x) && Number.isFinite(local.y) ? local : { x: 0, y: 0 };
11728
+ if (route.drag?.data && route.buttons.size)
11729
+ await route.target.drag("dragCancel", at, route.drag.data).catch(() => {});
11730
+ for (const button2 of [...route.buttons]) {
11731
+ route.buttons.delete(button2);
11732
+ await route.target.release(at, button2, 1, buttonBits(route.buttons)).catch(() => {});
11733
+ }
11734
+ this.unroute(session);
11735
+ }
9783
11736
  for (const button2 of buttons)
9784
11737
  await session.page.mouse.up({ button: button2 }).catch(() => {});
9785
11738
  for (const key2 of keys)
@@ -9789,6 +11742,11 @@ class TakeoverInput {
9789
11742
  if (!events)
9790
11743
  return;
9791
11744
  const dialog = events.activeDialog(), details = events.dialogDetails();
11745
+ if (dialog && details?.type === "http_auth") {
11746
+ const typed = event.accept && event.username !== undefined && event.password !== undefined ? { username: event.username, password: event.password } : undefined;
11747
+ await events.handleDialog({ dialogId: dialog.dialogId, decision: event.accept ? "accept" : "dismiss" }, "viewer", { typed });
11748
+ return;
11749
+ }
9792
11750
  if (dialog && details) {
9793
11751
  const prompt = details.type === "prompt" && event.accept && event.text !== undefined;
9794
11752
  await events.handleDialog({ dialogId: dialog.dialogId, decision: event.accept ? "accept" : "dismiss", ...prompt ? { promptText: event.text } : {} }, "viewer");
@@ -9994,18 +11952,23 @@ class Relay {
9994
11952
  if (socket?.readyState === WebSocket2.OPEN)
9995
11953
  socket.send(JSON.stringify(event));
9996
11954
  },
9997
- hostMac: process.platform === "darwin"
11955
+ hostMac: process.platform === "darwin",
11956
+ setViewport: (id, viewport) => this.runtime.engine.takeoverViewport(id, viewport)
9998
11957
  });
9999
11958
  }
10000
- setControl(tab) {
11959
+ setControl(tab, viewport) {
10001
11960
  if (tab !== undefined && (!this.liveEnabled || !isRuntimeTabId(tab)))
10002
11961
  tab = undefined;
10003
- if (tab === this.control)
11962
+ const fit = tab ? sanitizeTakeoverViewport(viewport) ?? undefined : undefined;
11963
+ if (tab === this.control) {
11964
+ if (tab)
11965
+ this.takeover.fit(fit);
10004
11966
  return;
11967
+ }
10005
11968
  this.control = tab;
10006
11969
  if (tab) {
10007
11970
  this.controlled([tab], tab);
10008
- this.takeover.activate(tab);
11971
+ this.takeover.activate(tab, fit);
10009
11972
  } else {
10010
11973
  this.takeover.deactivate();
10011
11974
  this.controlled([], undefined);
@@ -10057,7 +12020,7 @@ class Relay {
10057
12020
  if (this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
10058
12021
  return;
10059
12022
  this.state = "authenticating";
10060
- socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: CLI_VERSION, 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", BROWSER_SESSIONS_CAPABILITY, "outline-views.v1", CAPABILITIES.webmcpCallByName, CAPABILITIES.runJsRead, CAPABILITIES.actionTargets, CAPABILITIES.screenshotDelivery, CAPABILITIES.waitConditions], liveView: { enabled: this.liveEnabled } } }));
12023
+ socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: CLI_VERSION, 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", CAPABILITIES.liveFit, BROWSER_SESSIONS_CAPABILITY, "outline-views.v1", CAPABILITIES.webmcpCallByName, CAPABILITIES.runJsRead, CAPABILITIES.actionTargets, CAPABILITIES.screenshotDelivery, CAPABILITIES.waitConditions, CAPABILITIES.httpAuth], liveView: { enabled: this.liveEnabled } } }));
10061
12024
  });
10062
12025
  socket.on("message", (bytes, binary) => {
10063
12026
  if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
@@ -10115,7 +12078,7 @@ class Relay {
10115
12078
  }
10116
12079
  } else if (message.type === "control") {
10117
12080
  if (socket === this.socket)
10118
- this.setControl(message.active === true ? message.runtimeTabId : undefined);
12081
+ this.setControl(message.active === true ? message.runtimeTabId : undefined, message.active === true ? message.viewport : undefined);
10119
12082
  } else if (message.type === "input") {
10120
12083
  if (socket === this.socket && this.control)
10121
12084
  this.takeover.input(message);
@@ -10466,7 +12429,7 @@ class SecretVault {
10466
12429
  this.entries.delete(id);
10467
12430
  }
10468
12431
  metadata(e) {
10469
- return { vaultId: e.id, names: Object.keys(e.values), count: Object.keys(e.values).length, expiresAt: e.expiresAt, tabId: e.tabId, generation: e.generation };
12432
+ return { vaultId: e.id, names: Object.keys(e.values), count: Object.keys(e.values).length, expiresAt: e.expiresAt, runtimeTabId: e.tabId, generation: e.generation };
10470
12433
  }
10471
12434
  async capture(scope, tabId, code2, frames) {
10472
12435
  if (code2.length > 65536)
@@ -10519,7 +12482,7 @@ class SecretVault {
10519
12482
  }
10520
12483
  if (!Object.keys(clean).length || Object.keys(clean).length > LIMITS.count || total + 1024 > LIMITS.secret)
10521
12484
  throw new Error("Vault quota exceeded");
10522
- const entry = { id: randomUUID6(), scope: { ...scope }, tabId, generation: target2.generation, origin: new URL(target2.frame.url()).origin, expiresAt: Date.now() + LIMITS.ttl, values: clean };
12485
+ const entry = { id: randomUUID6(), scope: { ...scope }, tabId, document: target2.document, generation: target2.generation, origin: new URL(target2.frame.url()).origin, expiresAt: Date.now() + LIMITS.ttl, values: clean };
10523
12486
  this.entries.set(entry.id, entry);
10524
12487
  return this.metadata(entry);
10525
12488
  } catch {
@@ -10544,11 +12507,11 @@ class SecretVault {
10544
12507
  const e = this.entries.get(id);
10545
12508
  if (!e || !sameScope(e.scope, scope) || !names.length || new Set(names).size !== names.length)
10546
12509
  throw new Error("Unknown secret selection");
10547
- const target2 = await this.access.resolveTarget(e.tabId, scope);
12510
+ const target2 = await this.access.resolveDocument(e.tabId, scope, e.document);
10548
12511
  target2.assertCurrent();
10549
12512
  if (epoch !== this.epoch || this.entries.get(id) !== e || e.expiresAt <= Date.now())
10550
12513
  throw new Error("Secret export invalidated");
10551
- if (target2.generation !== e.generation || new URL(target2.frame.url()).origin !== e.origin)
12514
+ if (new URL(target2.frame.url()).origin !== e.origin)
10552
12515
  throw new Error("Stale secret document");
10553
12516
  const selected = Object.create(null);
10554
12517
  for (const name of names) {
@@ -10556,14 +12519,29 @@ class SecretVault {
10556
12519
  throw new Error("Unknown secret selection");
10557
12520
  selected[name] = e.values[name];
10558
12521
  }
10559
- return { bytes: Buffer.from(serializeSecrets(selected, format)), tabId: e.tabId, generation: e.generation, assertCurrent: () => {
12522
+ return { bytes: Buffer.from(serializeSecrets(selected, format)), tabId: e.tabId, document: e.document, assertCurrent: () => {
10560
12523
  target2.assertCurrent();
10561
12524
  if (epoch !== this.epoch || this.entries.get(id) !== e || e.expiresAt <= Date.now())
10562
12525
  throw new Error("Secret export invalidated");
10563
12526
  } };
10564
12527
  }
10565
- revoke(predicate) {
10566
- this.epoch++;
12528
+ async reveal(scope, id, names) {
12529
+ this.sweep();
12530
+ const epoch = this.epoch;
12531
+ const e = this.entries.get(id);
12532
+ if (!e || !sameScope(e.scope, scope) || !Object.hasOwn(e.values, names.username) || !Object.hasOwn(e.values, names.password))
12533
+ throw new Error("Unknown secret selection");
12534
+ const target2 = await this.access.resolveDocument(e.tabId, scope, e.document);
12535
+ target2.assertCurrent();
12536
+ if (epoch !== this.epoch || this.entries.get(id) !== e || e.expiresAt <= Date.now())
12537
+ throw new Error("Secret selection invalidated");
12538
+ if (new URL(target2.frame.url()).origin !== e.origin)
12539
+ throw new Error("Stale secret document");
12540
+ return { username: e.values[names.username], password: e.values[names.password] };
12541
+ }
12542
+ revoke(predicate, invalidate = true) {
12543
+ if (invalidate)
12544
+ this.epoch++;
10567
12545
  for (const [id, e] of this.entries)
10568
12546
  if (predicate(e))
10569
12547
  this.entries.delete(id);
@@ -10932,8 +12910,8 @@ async function createDataPlugin(access, options) {
10932
12910
  r.removal = undefined;
10933
12911
  }
10934
12912
  }
10935
- async function revoke(predicate) {
10936
- vault.revoke(predicate);
12913
+ async function revoke(predicate, invalidate = true) {
12914
+ vault.revoke(predicate, invalidate);
10937
12915
  await Promise.all([...resources.values()].filter(predicate).map(remove));
10938
12916
  }
10939
12917
  async function transfer(r, g) {
@@ -11018,7 +12996,7 @@ async function createDataPlugin(access, options) {
11018
12996
  return true;
11019
12997
  }
11020
12998
  return false;
11021
- });
12999
+ }, false);
11022
13000
  for (const [id, t] of terminal)
11023
13001
  if (t.until < Date.now())
11024
13002
  terminal.delete(id);
@@ -11103,7 +13081,7 @@ async function createDataPlugin(access, options) {
11103
13081
  return {};
11104
13082
  return { claim: (guid) => spool.claim(guid, download), release: () => spool.release(download), settlement: (guid) => spool.settlement(guid), isSpoolPath: (path11, guid) => spool.isSpoolPath(path11, guid) };
11105
13083
  }
11106
- async function admit(download, name, scope, tabId, generation, downloadId, hooks, directory = downloadDirectory) {
13084
+ async function admit(download, name, scope, tabId, downloadId, hooks, directory = downloadDirectory) {
11107
13085
  const shared = !scope, owner = scope ?? USER_SCOPE;
11108
13086
  let r;
11109
13087
  try {
@@ -11113,7 +13091,6 @@ async function createDataPlugin(access, options) {
11113
13091
  resources.set(r.id, r);
11114
13092
  r.expiresAt = Date.now() + DOWNLOAD_DEADLINE_MS;
11115
13093
  r.tabId = tabId;
11116
- r.generation = generation;
11117
13094
  const resource = r;
11118
13095
  r.source = { download, directory, hooks: { ...hooks, reserve: (size) => reserveSource(resource, size) } };
11119
13096
  await startCapture(r);
@@ -11157,7 +13134,7 @@ async function createDataPlugin(access, options) {
11157
13134
  await unlink3(file).catch(() => {});
11158
13135
  }
11159
13136
  };
11160
- await admit(handle, entry.suggestedFilename, undefined, undefined, 0, randomUUID8(), {
13137
+ await admit(handle, entry.suggestedFilename, undefined, undefined, randomUUID8(), {
11161
13138
  claim: () => true,
11162
13139
  settlement: (guid) => spool.settlement(guid),
11163
13140
  isSpoolPath: (path11, guid) => spool.isSpoolPath(path11, guid)
@@ -11247,7 +13224,7 @@ async function createDataPlugin(access, options) {
11247
13224
  for (const r of files) {
11248
13225
  r.state = "attached";
11249
13226
  r.tabId = target2.tabId;
11250
- r.generation = target2.generation;
13227
+ r.document = target2.document;
11251
13228
  }
11252
13229
  try {
11253
13230
  await target2.element.setInputFiles(files.map((r) => r.path));
@@ -11286,17 +13263,22 @@ async function createDataPlugin(access, options) {
11286
13263
  r.bytes = snapshot.bytes;
11287
13264
  r.vaultId = String(args.vaultId);
11288
13265
  r.tabId = snapshot.tabId;
11289
- r.generation = snapshot.generation;
13266
+ r.document = snapshot.document;
11290
13267
  return meta(r);
11291
13268
  }
11292
13269
  throw new Error("Unsupported data operation");
11293
13270
  },
11294
- async onDownload(download, tabId, owner, generation, downloadId = randomUUID8(), spool) {
11295
- return admit(download, download.suggestedFilename(), owner.kind === "session" ? owner.scope : undefined, tabId, generation, downloadId, spoolHooks(download, spool ?? guard), spool?.directory ?? downloadDirectory);
13271
+ async onDownload(download, tabId, owner, downloadId = randomUUID8(), spool) {
13272
+ return admit(download, download.suggestedFilename(), owner.kind === "session" ? owner.scope : undefined, tabId, downloadId, spoolHooks(download, spool ?? guard), spool?.directory ?? downloadDirectory);
11296
13273
  },
11297
13274
  observeDownload(download, spool) {
11298
13275
  (spool ?? guard)?.observe(download);
11299
13276
  },
13277
+ async revealHttpAuth(scope, vaultId, names) {
13278
+ if (stopped)
13279
+ throw new Error("Data runtime disconnected");
13280
+ return vault.reveal(scope, vaultId, names);
13281
+ },
11300
13282
  async discardDownload(download, spool) {
11301
13283
  download.cancel().catch(() => {});
11302
13284
  await cleanupDownload({ download, directory: spool?.directory ?? downloadDirectory, hooks: spoolHooks(download, spool ?? guard) });
@@ -11304,8 +13286,8 @@ async function createDataPlugin(access, options) {
11304
13286
  onDownloadSpool(spool) {
11305
13287
  return follow(spool);
11306
13288
  },
11307
- async onNavigation(tabId, generation) {
11308
- await revoke((r) => r.purpose !== "download" && r.tabId === tabId && r.generation !== generation);
13289
+ async onNavigation(tabId) {
13290
+ await revoke((r) => r.purpose !== "download" && r.tabId === tabId && (r.document === undefined || !access.documentCurrent(tabId, r.document)), false);
11309
13291
  },
11310
13292
  async onTabClose(tabId) {
11311
13293
  await revoke((r) => r.purpose !== "download" && r.tabId === tabId);