@ricsam/browser-mcp 0.3.24 → 0.3.25

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-mktre13d.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
@@ -1785,7 +1787,15 @@ var messages = {
1785
1787
  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
1788
  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
1789
  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."
1790
+ target_unresolved: "The page did not answer while the target was being resolved, so nothing was dispatched.",
1791
+ 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.",
1792
+ 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.",
1793
+ 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.",
1794
+ 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.",
1795
+ 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.",
1796
+ http_auth_closed: "The HTTP sign-in closed while its vault values were read. Nothing was sent to the site.",
1797
+ http_auth_username_unsupported: "The username contains a colon, which HTTP Basic authentication cannot send. Nothing was sent to the site.",
1798
+ http_auth_answer_pending: "This HTTP sign-in is being answered already. Nothing more was sent to the site."
1789
1799
  };
1790
1800
  var faultMessage = (code2) => messages[code2] ?? "Runtime operation rejected.";
1791
1801
  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 +2172,51 @@ function parseNavigationExpectation(value) {
2162
2172
  };
2163
2173
  }
2164
2174
 
2175
+ // shared/http-auth.ts
2176
+ var HTTP_AUTH_DIALOG = "http_auth";
2177
+ var MAX_HTTP_AUTH_REALM = 200;
2178
+ var MAX_HTTP_AUTH_USERNAME = 256;
2179
+ var MAX_HTTP_AUTH_PASSWORD = 512;
2180
+ var HTTP_AUTH_ARGUMENTS = ["vaultId", "names", "expectedOrigin"];
2181
+ var VAULT_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
2182
+ function signsInWithVault(input) {
2183
+ return !!input && HTTP_AUTH_ARGUMENTS.some((key2) => input[key2] !== undefined && input[key2] !== null);
2184
+ }
2185
+ function exactOrigin(value) {
2186
+ if (typeof value !== "string" || value.length > 255)
2187
+ return;
2188
+ try {
2189
+ const url = new URL(value);
2190
+ return (url.protocol === "https:" || url.protocol === "http:") && url.origin === value ? value : undefined;
2191
+ } catch {
2192
+ return;
2193
+ }
2194
+ }
2195
+ function httpAuthInputProblem(input) {
2196
+ if (!signsInWithVault(input))
2197
+ return;
2198
+ const missing = HTTP_AUTH_ARGUMENTS.filter((key2) => input[key2] === undefined || input[key2] === null);
2199
+ if (missing.length)
2200
+ return `An HTTP sign-in takes vaultId, names and expectedOrigin together: ${missing.join(" and ")} ${missing.length === 1 ? "is" : "are"} missing.`;
2201
+ if (input.decision !== "accept")
2202
+ return 'vaultId, names and expectedOrigin sign in with decision "accept". To cancel an HTTP sign-in, use decision "dismiss" without them.';
2203
+ if (input.promptText !== undefined)
2204
+ return "promptText answers a JavaScript prompt. An HTTP sign-in takes vaultId, names and expectedOrigin instead.";
2205
+ if (typeof input.vaultId !== "string" || !input.vaultId.trim() || input.vaultId.length > 128)
2206
+ return "vaultId must be the vaultId of a local secret vault, from browser_capture_secrets or browser_list_secrets.";
2207
+ const names = input.names;
2208
+ if (!names || typeof names !== "object" || Array.isArray(names) || Object.keys(names).some((key2) => key2 !== "username" && key2 !== "password"))
2209
+ return 'names must be {"username": NAME, "password": NAME}: the names of the vault values that hold the username and the password, never the values.';
2210
+ for (const key2 of ["username", "password"]) {
2211
+ const name = names[key2];
2212
+ if (typeof name !== "string" || !VAULT_NAME.test(name))
2213
+ 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.`;
2214
+ }
2215
+ if (!exactOrigin(input.expectedOrigin))
2216
+ return "expectedOrigin must be the exact origin the user authorized these credentials for, such as https://example.com: scheme, host and port only.";
2217
+ return;
2218
+ }
2219
+
2165
2220
  // cli/src/browser/browser-control-input.ts
2166
2221
  var observedActions = new Set([
2167
2222
  "navigate",
@@ -2287,6 +2342,9 @@ function validateControlInput(action, input) {
2287
2342
  choice("decision", ["accept", "dismiss"]);
2288
2343
  if (input.promptText !== undefined && (typeof input.promptText !== "string" || input.promptText.length > 1e4))
2289
2344
  throw new Error("Invalid promptText.");
2345
+ const problem = httpAuthInputProblem(input);
2346
+ if (problem)
2347
+ throw new Error(problem);
2290
2348
  }
2291
2349
  if (action === "events" || action === "diagnostics") {
2292
2350
  integer("timeoutMs", 500, 25000);
@@ -2374,7 +2432,7 @@ var browserInputFields = {
2374
2432
  select_text: { required: ["tabId"], optional: ["ref", "target", "start", "end", "text", "occurrence"] },
2375
2433
  edit_text: { required: ["tabId", "mode", "text"], optional: ["ref", "target"] },
2376
2434
  events: { required: ["tabId"], optional: ["kind", "after", "limit", "timeoutMs"] },
2377
- handle_dialog: { required: ["tabId", "dialogId", "decision"], optional: ["promptText"] },
2435
+ handle_dialog: { required: ["tabId", "dialogId", "decision"], optional: ["promptText", "vaultId", "names", "expectedOrigin"] },
2378
2436
  diagnostics: { required: ["tabId"], optional: ["kind", "after", "limit", "level", "since", "failedOnly"] },
2379
2437
  history: { required: ["tabId", "direction"], optional: [] },
2380
2438
  present: { required: ["tabId", "mode"], optional: [] },
@@ -3767,11 +3825,13 @@ var REMEMBERED_DOCUMENTS = 32;
3767
3825
  var COMMIT_HEARD_MS = 1000;
3768
3826
 
3769
3827
  class MainFrameDocuments {
3828
+ cdp;
3770
3829
  commits = 0;
3771
3830
  current;
3772
3831
  reached = new Map;
3773
3832
  listeners = new Set;
3774
3833
  constructor(cdp) {
3834
+ this.cdp = cdp;
3775
3835
  cdp.on("Page.frameNavigated", ({ frame, type }) => {
3776
3836
  if (frame.parentId)
3777
3837
  return;
@@ -3844,6 +3904,14 @@ class MainFrameDocuments {
3844
3904
  const document2 = this.restoredShown(page, since);
3845
3905
  return !!document2 && document2.committedAt > since;
3846
3906
  }
3907
+ async shown() {
3908
+ const { frameTree } = await this.cdp.send("Page.getFrameTree");
3909
+ const loaderId = frameTree?.frame?.loaderId;
3910
+ const document2 = this.current;
3911
+ if (typeof loaderId !== "string" || document2 && document2.loaderId !== loaderId)
3912
+ return;
3913
+ return `${document2?.committedAt ?? 0}:${loaderId}`;
3914
+ }
3847
3915
  }
3848
3916
  var followed2 = new WeakMap;
3849
3917
  function followDocuments(page, cdp) {
@@ -3864,6 +3932,9 @@ function restoredFromCache(page, since) {
3864
3932
  function showsRestoredDocument(page) {
3865
3933
  return followed2.get(page)?.showsRestored(page) ?? false;
3866
3934
  }
3935
+ async function shownDocument(page) {
3936
+ return await followed2.get(page)?.shown();
3937
+ }
3867
3938
  async function waitForLoadState(page, state, timeoutMs, since) {
3868
3939
  const documents = followed2.get(page);
3869
3940
  if (!documents || state === "networkidle")
@@ -4256,6 +4327,152 @@ async function traverseToEntry(page, cdp, entryId, timeoutMs) {
4256
4327
  return { frame: "child" };
4257
4328
  }
4258
4329
 
4330
+ // cli/src/browser/frame-input.ts
4331
+ var MODIFIER_BITS = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
4332
+ var BUTTON_BITS = { left: 1, right: 2, middle: 4 };
4333
+ function frameOrigin(iframe) {
4334
+ const view = iframe.ownerDocument?.defaultView;
4335
+ if (!iframe.isConnected || !view)
4336
+ return "detached";
4337
+ const zoom = iframe.currentCSSZoom;
4338
+ if (zoom !== undefined && zoom !== 1)
4339
+ return "transformed";
4340
+ for (let node = iframe;node; node = node.parentElement ?? (node.getRootNode().host || null)) {
4341
+ const style2 = view.getComputedStyle(node);
4342
+ if (style2.transform !== "none" || style2.scale !== "none" || style2.rotate !== "none" || style2.translate !== "none")
4343
+ return "transformed";
4344
+ }
4345
+ const box = iframe.getBoundingClientRect();
4346
+ const style = view.getComputedStyle(iframe);
4347
+ return { x: box.left + iframe.clientLeft + Number.parseFloat(style.paddingLeft), y: box.top + iframe.clientTop + Number.parseFloat(style.paddingTop) };
4348
+ }
4349
+ function parentHit(iframe, options) {
4350
+ const root = iframe.getRootNode();
4351
+ const view = iframe.ownerDocument.defaultView;
4352
+ if (options.point.x < 0 || options.point.y < 0 || options.point.x >= view.innerWidth || options.point.y >= view.innerHeight)
4353
+ return "outside";
4354
+ const hit = root.elementFromPoint(options.point.x, options.point.y);
4355
+ if (!hit)
4356
+ return "outside";
4357
+ if (hit === iframe)
4358
+ return null;
4359
+ const role = hit.getAttribute("role") ?? undefined;
4360
+ const field = hit.tagName === "INPUT" || hit.tagName === "TEXTAREA" || hit.tagName === "SELECT";
4361
+ const password = hit.tagName === "INPUT" && hit.type === "password";
4362
+ const raw = hit.getAttribute("aria-label") ?? hit.getAttribute("title") ?? (field ? [...hit.labels ?? []][0]?.textContent || (password ? "" : hit.getAttribute("placeholder") ?? "") : hit.textContent ?? "");
4363
+ const name = raw.replace(/\s+/g, " ").trim().slice(0, options.nameChars);
4364
+ return { tag: hit.tagName.toLowerCase(), ...role ? { role } : {}, ...name ? { name } : {} };
4365
+ }
4366
+
4367
+ class FrameInput {
4368
+ page;
4369
+ chain;
4370
+ inRoot;
4371
+ session;
4372
+ constructor(page, chain, inRoot, session) {
4373
+ this.page = page;
4374
+ this.chain = chain;
4375
+ this.inRoot = inRoot;
4376
+ this.session = session;
4377
+ }
4378
+ static async of(page, handle) {
4379
+ if (!showsRestoredDocument(page))
4380
+ return;
4381
+ const frame = await handle.ownerFrame().catch(() => null);
4382
+ if (!frame?.parentFrame())
4383
+ return;
4384
+ const chain = [];
4385
+ for (let node = frame;node?.parentFrame(); node = node.parentFrame())
4386
+ chain.push(node);
4387
+ for (let index = 0;index < chain.length; index++) {
4388
+ const session = await page.context().newCDPSession(chain[index]).catch(() => {
4389
+ return;
4390
+ });
4391
+ if (session)
4392
+ return new FrameInput(page, chain, index + 1, session);
4393
+ }
4394
+ return;
4395
+ }
4396
+ async path(point, nameChars) {
4397
+ let current = point;
4398
+ let root = point;
4399
+ for (let index = 0;index < this.chain.length; index++) {
4400
+ if (index === this.inRoot - 1)
4401
+ root = current;
4402
+ const iframe = await this.chain[index].frameElement().catch(() => {
4403
+ return;
4404
+ });
4405
+ if (!iframe)
4406
+ return;
4407
+ try {
4408
+ const origin = await iframe.evaluate(frameOrigin);
4409
+ if (origin === "transformed" || origin === "detached")
4410
+ return;
4411
+ current = { x: current.x + origin.x, y: current.y + origin.y };
4412
+ const hit = await iframe.evaluate(parentHit, { point: current, nameChars });
4413
+ if (hit === "outside")
4414
+ return { kind: "outside_viewport" };
4415
+ if (hit)
4416
+ return { kind: "covered", cover: hit };
4417
+ } catch {
4418
+ return;
4419
+ } finally {
4420
+ iframe.dispose().catch(() => {
4421
+ return;
4422
+ });
4423
+ }
4424
+ }
4425
+ return { kind: "reached", root };
4426
+ }
4427
+ async reveal(timeout2) {
4428
+ for (const frame of this.chain.toReversed()) {
4429
+ const iframe = await frame.frameElement().catch(() => {
4430
+ return;
4431
+ });
4432
+ if (!iframe)
4433
+ return;
4434
+ try {
4435
+ await iframe.scrollIntoViewIfNeeded({ timeout: timeout2 });
4436
+ } catch {} finally {
4437
+ iframe.dispose().catch(() => {
4438
+ return;
4439
+ });
4440
+ }
4441
+ }
4442
+ }
4443
+ send(type, point, extra) {
4444
+ return this.session.send("Input.dispatchMouseEvent", { type, x: point.x, y: point.y, ...extra });
4445
+ }
4446
+ bits(modifiers) {
4447
+ let bits = 0;
4448
+ for (const modifier of modifiers)
4449
+ bits |= MODIFIER_BITS[modifier === "ControlOrMeta" ? process.platform === "darwin" ? "Meta" : "Control" : modifier];
4450
+ return bits;
4451
+ }
4452
+ async click(point, button, clickCount) {
4453
+ await this.send("mouseMoved", point, {});
4454
+ for (let count = 1;count <= clickCount; count++) {
4455
+ await this.send("mousePressed", point, { button, buttons: BUTTON_BITS[button], clickCount: count });
4456
+ await this.send("mouseReleased", point, { button, buttons: 0, clickCount: count });
4457
+ }
4458
+ }
4459
+ async hover(point, modifiers) {
4460
+ for (const modifier of modifiers)
4461
+ await this.page.keyboard.down(modifier);
4462
+ try {
4463
+ await this.send("mouseMoved", point, { modifiers: this.bits(modifiers) });
4464
+ } finally {
4465
+ for (const modifier of modifiers.toReversed())
4466
+ await this.page.keyboard.up(modifier);
4467
+ }
4468
+ }
4469
+ dispose() {
4470
+ this.session.detach().catch(() => {
4471
+ return;
4472
+ });
4473
+ }
4474
+ }
4475
+
4259
4476
  // cli/src/browser/passkey-guard.ts
4260
4477
  var MAX_PASSKEY_REQUESTS = 16;
4261
4478
  function passkeyGuardSource(binding, cancelEvent) {
@@ -4330,6 +4547,320 @@ function parsePasskeyReport(payload) {
4330
4547
  }
4331
4548
  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
4549
 
4550
+ // cli/src/browser/http-auth.ts
4551
+ var ENABLE_MS = 1500;
4552
+ var OUTCOME_MS = 5000;
4553
+ var MAX_TRACKED = 200;
4554
+ 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.`;
4555
+ 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.";
4556
+ 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.";
4557
+ var refusal = (code2, recovery, details) => new RuntimeFault(code2, recovery, true, details, true);
4558
+ var protocolLogging = () => /\*|pw:protocol/.test(process.env.DEBUG ?? "");
4559
+ var originOf = (url) => {
4560
+ try {
4561
+ return new URL(url).origin;
4562
+ } catch {
4563
+ return "null";
4564
+ }
4565
+ };
4566
+ async function bounded2(work, ms) {
4567
+ let timer2;
4568
+ await Promise.race([work.catch(() => {
4569
+ return;
4570
+ }), new Promise((resolve2) => timer2 = setTimeout(resolve2, ms))]);
4571
+ clearTimeout(timer2);
4572
+ }
4573
+
4574
+ class HttpAuthPrompts {
4575
+ host;
4576
+ held = new Map;
4577
+ attempts = new Map;
4578
+ chrome = new Set;
4579
+ waits = new Map;
4580
+ cdp;
4581
+ mainFrameId;
4582
+ constructor(host) {
4583
+ this.host = host;
4584
+ }
4585
+ async watch(cdp) {
4586
+ this.cdp = cdp;
4587
+ cdp.on("Fetch.requestPaused", ({ requestId }) => this.quietly(() => cdp.send("Fetch.continueRequest", { requestId })));
4588
+ cdp.on("Fetch.authRequired", (event) => this.required(cdp, event));
4589
+ cdp.on("Page.frameNavigated", ({ frame }) => this.closeFrame(frame.id, "navigated"));
4590
+ cdp.on("Page.frameDetached", ({ frameId }) => this.closeFrame(frameId, "frame_removed"));
4591
+ cdp.on("close", () => this.release("gone"));
4592
+ await Promise.all([
4593
+ bounded2(cdp.send("Target.getTargetInfo").then(({ targetInfo }) => {
4594
+ this.mainFrameId = targetInfo.targetId;
4595
+ }), ENABLE_MS),
4596
+ bounded2(cdp.send("Fetch.enable", { handleAuthRequests: true, patterns: [{ urlPattern: "*", resourceType: "Document", requestStage: "Request" }] }), ENABLE_MS)
4597
+ ]);
4598
+ }
4599
+ required(cdp, { requestId, request, frameId, resourceType, authChallenge }) {
4600
+ const scheme = String(authChallenge?.scheme ?? "").toLowerCase();
4601
+ const attempt = (this.attempts.get(requestId) ?? 0) + 1;
4602
+ this.attempts.set(requestId, attempt);
4603
+ if (this.attempts.size > MAX_TRACKED)
4604
+ this.attempts.delete(this.attempts.keys().next().value);
4605
+ const eligible = authChallenge?.source === "Server" && (scheme === "basic" || scheme === "digest") && resourceType === "Document";
4606
+ if (!eligible || this.chrome.has(requestId) || attempt === 1 && !this.host.holds()) {
4607
+ this.chrome.add(requestId);
4608
+ if (this.chrome.size > MAX_TRACKED)
4609
+ this.chrome.delete(this.chrome.values().next().value);
4610
+ this.waits.get(requestId)?.resolve({ kind: "pending" });
4611
+ this.quietly(() => cdp.send("Fetch.continueWithAuth", { requestId, authChallengeResponse: { response: "Default" } }));
4612
+ return;
4613
+ }
4614
+ let origin = originOf(request.url);
4615
+ try {
4616
+ origin = new URL(authChallenge.origin).origin;
4617
+ } catch {}
4618
+ const realm = String(authChallenge.realm ?? "").replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim().slice(0, MAX_HTTP_AUTH_REALM);
4619
+ const main = frameId === this.mainFrameId;
4620
+ for (const other of [...this.held.values()])
4621
+ if (other.frameId === frameId && other.requestId !== requestId)
4622
+ this.close(other, "closed", "replaced");
4623
+ 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" });
4624
+ const state = { event, requestId, frameId, main, url: request.url, origin, realm, scheme, attempt, answering: false };
4625
+ this.held.set(requestId, state);
4626
+ this.waits.get(requestId)?.resolve({ kind: "rejected", next: state });
4627
+ this.host.changed(true);
4628
+ }
4629
+ quietly(call) {
4630
+ try {
4631
+ call().catch(() => {
4632
+ return;
4633
+ });
4634
+ } catch {}
4635
+ }
4636
+ close(state, outcome, reason, handledBy) {
4637
+ if (this.held.get(state.requestId) !== state)
4638
+ return;
4639
+ this.held.delete(state.requestId);
4640
+ state.event.state = outcome;
4641
+ if (handledBy)
4642
+ state.event.handledBy = handledBy;
4643
+ const closing = this.host.record("dialog", { dialogId: state.event.eventId, type: HTTP_AUTH_DIALOG, state: outcome, reason, ...handledBy ? { handledBy } : {} });
4644
+ this.host.changed(false);
4645
+ return closing;
4646
+ }
4647
+ closeFrame(frameId, reason) {
4648
+ for (const state of [...this.held.values()])
4649
+ if (state.frameId === frameId)
4650
+ this.close(state, "closed", reason);
4651
+ }
4652
+ requestEnded(request, status) {
4653
+ if (!this.held.size && !this.waits.size)
4654
+ return;
4655
+ let url;
4656
+ try {
4657
+ if (!request.isNavigationRequest())
4658
+ return;
4659
+ url = request.url();
4660
+ } catch {
4661
+ return;
4662
+ }
4663
+ for (const wait of this.waits.values())
4664
+ if (wait.url === url) {
4665
+ wait.resolve(status === null ? { kind: "failed" } : { kind: "answered", status });
4666
+ return;
4667
+ }
4668
+ if (status === null) {
4669
+ for (const state of [...this.held.values()])
4670
+ if (state.url === url)
4671
+ this.close(state, "closed", "aborted");
4672
+ }
4673
+ }
4674
+ pageClosed() {
4675
+ this.held.clear();
4676
+ for (const wait of [...this.waits.values()])
4677
+ wait.resolve({ kind: "failed" });
4678
+ }
4679
+ release(reason) {
4680
+ if (this.cdp && this.held.size)
4681
+ for (const state of [...this.held.values()])
4682
+ this.close(state, "closed", reason);
4683
+ this.cdp = undefined;
4684
+ for (const wait of [...this.waits.values()])
4685
+ wait.resolve({ kind: "pending" });
4686
+ }
4687
+ handToChrome(reason) {
4688
+ const cdp = this.cdp;
4689
+ for (const state of [...this.held.values()]) {
4690
+ this.close(state, "closed", reason);
4691
+ if (cdp) {
4692
+ this.chrome.add(state.requestId);
4693
+ this.quietly(() => cdp.send("Fetch.continueWithAuth", { requestId: state.requestId, authChallengeResponse: { response: "Default" } }));
4694
+ }
4695
+ }
4696
+ }
4697
+ first() {
4698
+ return this.held.values().next().value;
4699
+ }
4700
+ isOpen() {
4701
+ return this.held.size > 0;
4702
+ }
4703
+ holdsMainFrame() {
4704
+ for (const state of this.held.values())
4705
+ if (state.main)
4706
+ return true;
4707
+ return false;
4708
+ }
4709
+ isOpenDialog(dialogId) {
4710
+ for (const state of this.held.values())
4711
+ if (state.event.eventId === dialogId)
4712
+ return true;
4713
+ return false;
4714
+ }
4715
+ event() {
4716
+ return this.first()?.event;
4717
+ }
4718
+ promptOf(state) {
4719
+ return {
4720
+ dialogId: state.event.eventId,
4721
+ type: HTTP_AUTH_DIALOG,
4722
+ origin: state.origin,
4723
+ realm: state.realm,
4724
+ scheme: state.scheme,
4725
+ url: String(state.event.url),
4726
+ frame: state.main ? "main" : "iframe",
4727
+ attempt: state.attempt,
4728
+ state: "open",
4729
+ openedAt: state.event.timestamp,
4730
+ untrusted: true
4731
+ };
4732
+ }
4733
+ prompt() {
4734
+ const state = this.first();
4735
+ return state ? this.promptOf(state) : null;
4736
+ }
4737
+ details() {
4738
+ const state = this.first();
4739
+ 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;
4740
+ }
4741
+ requiredResult(actionId) {
4742
+ const state = this.first();
4743
+ if (!state)
4744
+ return;
4745
+ return {
4746
+ code: "http_auth_required",
4747
+ dispatch: { status: "blocked", actionId, code: "http_auth_required" },
4748
+ httpAuth: this.promptOf(state),
4749
+ recovery: HTTP_AUTH_RECOVERY
4750
+ };
4751
+ }
4752
+ async answer(dialogId, input, answer) {
4753
+ let state;
4754
+ for (const held of this.held.values())
4755
+ if (held.event.eventId === dialogId)
4756
+ state = held;
4757
+ if (!state)
4758
+ return;
4759
+ const cdp = this.cdp;
4760
+ const prompt = this.promptOf(state);
4761
+ const details = { httpAuth: prompt };
4762
+ if (!cdp)
4763
+ return { handled: false, code: "stale_dialog", httpAuth: prompt, recovery: GONE_RECOVERY };
4764
+ if (state.answering)
4765
+ 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);
4766
+ if (input.promptText !== undefined)
4767
+ return { handled: false, code: "prompt_text_requires_accept_prompt", httpAuth: prompt };
4768
+ const accept = input.decision === "accept";
4769
+ let credentials;
4770
+ if (accept && answer.by === "viewer") {
4771
+ if (!answer.typed || protocolLogging())
4772
+ return { handled: false, code: answer.typed ? "http_auth_logging_enabled" : "http_auth_credentials_required" };
4773
+ credentials = answer.typed;
4774
+ } else if (accept && answer.by === "agent") {
4775
+ if (!answer.names || !answer.reveal)
4776
+ throw refusal("http_auth_credentials_required", HTTP_AUTH_RECOVERY, details);
4777
+ if (answer.expectedOrigin !== state.origin)
4778
+ 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 });
4779
+ const pageOrigin = originOf(this.host.page.url());
4780
+ if (!state.main && pageOrigin !== state.origin)
4781
+ 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 });
4782
+ if (protocolLogging())
4783
+ 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);
4784
+ state.answering = true;
4785
+ try {
4786
+ credentials = await answer.reveal();
4787
+ } catch {
4788
+ 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 });
4789
+ } finally {
4790
+ state.answering = false;
4791
+ }
4792
+ if (this.held.get(state.requestId) !== state) {
4793
+ credentials = undefined;
4794
+ throw refusal("http_auth_closed", "Read browser_events and the page: the page navigated, or the user answered it. Nothing was sent.", details);
4795
+ }
4796
+ }
4797
+ if (credentials && state.scheme === "basic" && credentials.username.includes(":")) {
4798
+ credentials = undefined;
4799
+ if (answer.by === "viewer")
4800
+ return { handled: false, code: "http_auth_username_unsupported" };
4801
+ throw refusal("http_auth_username_unsupported", "Check the vault value that holds the username. Nothing was sent.", details);
4802
+ }
4803
+ let outcome;
4804
+ if (accept) {
4805
+ const { requestId, url } = state;
4806
+ outcome = new Promise((resolve2) => {
4807
+ const finish = (value) => {
4808
+ clearTimeout(timer2);
4809
+ if (this.waits.get(requestId) === wait)
4810
+ this.waits.delete(requestId);
4811
+ resolve2(value);
4812
+ };
4813
+ const wait = { url, resolve: finish };
4814
+ const timer2 = setTimeout(() => finish({ kind: "pending" }), OUTCOME_MS);
4815
+ this.waits.set(requestId, wait);
4816
+ });
4817
+ }
4818
+ const closing = this.close(state, accept ? "accepted" : "dismissed", accept ? "credentials" : "cancelled", answer.by);
4819
+ let sent = true;
4820
+ try {
4821
+ await cdp.send("Fetch.continueWithAuth", credentials ? { requestId: state.requestId, authChallengeResponse: { response: "ProvideCredentials", username: credentials.username, password: credentials.password } } : { requestId: state.requestId, authChallengeResponse: { response: "CancelAuth" } });
4822
+ } catch {
4823
+ sent = false;
4824
+ }
4825
+ credentials = undefined;
4826
+ if (!sent) {
4827
+ this.waits.get(state.requestId)?.resolve({ kind: "pending" });
4828
+ for (const event of [state.event, closing])
4829
+ if (event) {
4830
+ event.state = "closed";
4831
+ delete event.handledBy;
4832
+ }
4833
+ if (closing)
4834
+ closing.reason = "gone";
4835
+ return { handled: false, code: "stale_dialog", httpAuth: prompt, recovery: GONE_RECOVERY };
4836
+ }
4837
+ const result = {
4838
+ handled: true,
4839
+ dialogId: prompt.dialogId,
4840
+ decision: accept ? "accept" : "dismiss",
4841
+ type: HTTP_AUTH_DIALOG,
4842
+ origin: state.origin,
4843
+ ...answer.by === "agent" && answer.names ? { vaultId: answer.vaultId, names: { ...answer.names } } : {}
4844
+ };
4845
+ if (outcome) {
4846
+ const settled = await outcome;
4847
+ if (settled.kind === "rejected")
4848
+ Object.assign(result, { signIn: "rejected", httpAuth: this.promptOf(settled.next), recovery: REJECTED_RECOVERY });
4849
+ else if (settled.kind === "answered")
4850
+ Object.assign(result, {
4851
+ signIn: "answered",
4852
+ responseStatus: settled.status,
4853
+ note: "Chrome sends these credentials to this site's realm by itself until this browser session's Chrome quits."
4854
+ });
4855
+ else if (settled.kind === "failed")
4856
+ Object.assign(result, { signIn: "failed", note: "The navigation failed after the credentials were sent: read the page and browser_diagnostics." });
4857
+ else
4858
+ Object.assign(result, { signIn: "sent", note: "The credentials were sent; the site's answer has not arrived yet. Read the page before going on." });
4859
+ }
4860
+ return result;
4861
+ }
4862
+ }
4863
+
4333
4864
  // cli/src/browser/browser-events.ts
4334
4865
  var PASSKEY_ANNOUNCE_MS = 300;
4335
4866
  var PASSKEY_CANCEL_MS = 2000;
@@ -4339,6 +4870,16 @@ var CAPACITY = 200;
4339
4870
  var RETENTION_MS = 10 * 60000;
4340
4871
  var MAX_INFLIGHT = 500;
4341
4872
  var MAX_ACTIVITY = 1000;
4873
+ var MAX_FRAME_DOCUMENTS = 100;
4874
+ var FRAME_DOCUMENT_SETTLE_MS = 50;
4875
+ function httpOrigin(raw) {
4876
+ try {
4877
+ const url = new URL(raw);
4878
+ return url.protocol === "http:" || url.protocol === "https:" ? url.origin : undefined;
4879
+ } catch {
4880
+ return;
4881
+ }
4882
+ }
4342
4883
  function diagnosticUrl(raw) {
4343
4884
  try {
4344
4885
  const u = new URL(raw);
@@ -4368,6 +4909,7 @@ function requestUrl(request) {
4368
4909
  class BrowserPageEvents {
4369
4910
  page;
4370
4911
  passkeyDetection;
4912
+ holdHttpAuth;
4371
4913
  sequence = 0;
4372
4914
  entries = [];
4373
4915
  listeners = new Set;
@@ -4375,6 +4917,10 @@ class BrowserPageEvents {
4375
4917
  dialogListeners = new Set;
4376
4918
  requests = new WeakMap;
4377
4919
  inflight = new Map;
4920
+ frameDocuments = new Map;
4921
+ frameDocumentLoads = new WeakMap;
4922
+ frameDocumentSequence = 0;
4923
+ frameDocumentChecks = new Set;
4378
4924
  lastNetworkActivity;
4379
4925
  activity = [];
4380
4926
  activityDroppedAt = 0;
@@ -4396,11 +4942,25 @@ class BrowserPageEvents {
4396
4942
  pending;
4397
4943
  currentAction;
4398
4944
  recentAction;
4945
+ httpAuth;
4399
4946
  document = 0;
4400
- constructor(page, passkeyDetection = true) {
4947
+ constructor(page, passkeyDetection = true, holdHttpAuth) {
4401
4948
  this.page = page;
4402
4949
  this.passkeyDetection = passkeyDetection;
4403
- this.ready = page.context().newCDPSession(page).then((cdp) => {
4950
+ this.holdHttpAuth = holdHttpAuth;
4951
+ this.httpAuth = new HttpAuthPrompts({
4952
+ page,
4953
+ record: (kind, data) => this.record(kind, data),
4954
+ redact: diagnosticUrl,
4955
+ holds: () => !!this.holdHttpAuth?.(this.actionId() !== undefined),
4956
+ changed: (opened) => {
4957
+ if (opened)
4958
+ for (const listener of this.listeners)
4959
+ listener();
4960
+ this.dialogChanged();
4961
+ }
4962
+ });
4963
+ this.ready = page.context().newCDPSession(page).then(async (cdp) => {
4404
4964
  this.cdp = cdp;
4405
4965
  cdp.on("close", () => {
4406
4966
  if (this.cdp === cdp)
@@ -4440,6 +5000,7 @@ class BrowserPageEvents {
4440
5000
  });
4441
5001
  if (this.passkeyDetection)
4442
5002
  this.watchPasskeys(cdp);
5003
+ await this.httpAuth.watch(cdp);
4443
5004
  }).catch(() => {
4444
5005
  return;
4445
5006
  });
@@ -4459,15 +5020,20 @@ class BrowserPageEvents {
4459
5020
  this.inflight.set(r, this.isMainFrameNavigation(r));
4460
5021
  if (this.inflight.size > MAX_INFLIGHT)
4461
5022
  this.inflight.delete(this.inflight.keys().next().value);
5023
+ if (this.isFrameNavigation(r))
5024
+ this.frameDocumentStarted(r);
4462
5025
  this.lastNetworkActivity = Date.now();
4463
5026
  this.noteActivity(r, this.lastNetworkActivity);
4464
5027
  });
4465
5028
  page.on("requestfailed", (r) => {
4466
5029
  this.settleRequest(r);
5030
+ this.frameDocumentEnded(r);
5031
+ this.httpAuth.requestEnded(r, null);
4467
5032
  this.requestFinished(r, { failed: true, error: diagnosticText(r.failure()?.errorText ?? "request_failed") });
4468
5033
  });
4469
5034
  page.on("requestfinished", (r) => {
4470
5035
  this.settleRequest(r);
5036
+ this.frameDocumentEnded(r);
4471
5037
  r.response().then((response) => {
4472
5038
  this.requestFinished(r, { status: response?.status(), failed: (response?.status() ?? 0) >= 400 });
4473
5039
  }).catch(() => {
@@ -4475,6 +5041,8 @@ class BrowserPageEvents {
4475
5041
  });
4476
5042
  });
4477
5043
  page.on("response", (response) => {
5044
+ this.frameDocumentEnded(response.request());
5045
+ this.httpAuth.requestEnded(response.request(), response.status());
4478
5046
  const headers = response.headers(), size = Number(headers["content-length"]), mimeType = headers["content-type"] ?? "";
4479
5047
  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
5048
  return;
@@ -4506,7 +5074,10 @@ class BrowserPageEvents {
4506
5074
  this.choosers.delete(id);
4507
5075
  }
4508
5076
  });
4509
- page.on("framedetached", () => this.dropDetachedFrameRequests());
5077
+ page.on("framedetached", () => {
5078
+ this.dropDetachedFrameRequests();
5079
+ this.dropDetachedFrameDocuments();
5080
+ });
4510
5081
  page.on("framenavigated", (frame) => {
4511
5082
  if (frame !== page.mainFrame())
4512
5083
  return;
@@ -4520,9 +5091,13 @@ class BrowserPageEvents {
4520
5091
  this.assets.clear();
4521
5092
  this.downloads.clear();
4522
5093
  this.inflight.clear();
5094
+ this.frameDocuments.clear();
5095
+ for (const check of [...this.frameDocumentChecks])
5096
+ check();
4523
5097
  this.activity = [];
4524
5098
  this.dialog = undefined;
4525
5099
  this.closePasskey("closed");
5100
+ this.httpAuth.pageClosed();
4526
5101
  this.contextFrames.clear();
4527
5102
  this.dialogListeners.clear();
4528
5103
  });
@@ -4629,7 +5204,7 @@ class BrowserPageEvents {
4629
5204
  }
4630
5205
  async flushPasskeyReports() {
4631
5206
  const cdp = this.cdp;
4632
- if (!cdp || !this.passkeyDetection || this.dialog || this.crashed)
5207
+ if (!cdp || !this.passkeyDetection || this.dialog || this.crashed || this.httpAuth.holdsMainFrame())
4633
5208
  return;
4634
5209
  let timer2;
4635
5210
  await Promise.race([
@@ -4701,6 +5276,9 @@ class BrowserPageEvents {
4701
5276
  const value = this.dialog?.value;
4702
5277
  if (value)
4703
5278
  return { type: value.type(), message: value.message(), defaultValue: value.defaultValue() };
5279
+ const auth = this.httpAuth.details();
5280
+ if (auth)
5281
+ return auth;
4704
5282
  const passkey = this.passkey;
4705
5283
  return passkey?.announced ? { type: "passkey", message: "", defaultValue: "", request: passkey.request, origin: passkey.origin } : null;
4706
5284
  }
@@ -4719,6 +5297,67 @@ class BrowserPageEvents {
4719
5297
  return false;
4720
5298
  }
4721
5299
  }
5300
+ isFrameNavigation(request) {
5301
+ try {
5302
+ return request.isNavigationRequest() && request.frame() !== this.page.mainFrame();
5303
+ } catch {
5304
+ return false;
5305
+ }
5306
+ }
5307
+ frameDocumentStarted(request) {
5308
+ const from = request.redirectedFrom();
5309
+ const load = from && this.frameDocumentLoads.get(from) || ++this.frameDocumentSequence;
5310
+ this.frameDocumentLoads.set(request, load);
5311
+ this.frameDocuments.set(request, load);
5312
+ if (this.frameDocuments.size > MAX_FRAME_DOCUMENTS)
5313
+ this.frameDocuments.delete(this.frameDocuments.keys().next().value);
5314
+ }
5315
+ frameDocumentEnded(request) {
5316
+ if (!this.frameDocuments.delete(request))
5317
+ return;
5318
+ for (const check of [...this.frameDocumentChecks])
5319
+ check();
5320
+ }
5321
+ dropDetachedFrameDocuments() {
5322
+ for (const request of [...this.frameDocuments.keys()]) {
5323
+ let detached = true;
5324
+ try {
5325
+ detached = request.frame().isDetached();
5326
+ } catch {}
5327
+ if (detached)
5328
+ this.frameDocumentEnded(request);
5329
+ }
5330
+ }
5331
+ frameDocumentMark() {
5332
+ return this.frameDocumentSequence;
5333
+ }
5334
+ framesSettled(mark, pageUrl, ms) {
5335
+ const origin = httpOrigin(pageUrl);
5336
+ if (!origin)
5337
+ return Promise.resolve();
5338
+ const begun = this.frameDocumentSequence;
5339
+ const waiting = () => {
5340
+ for (const [request, load] of this.frameDocuments)
5341
+ if (load > mark && load <= begun && httpOrigin(requestUrl(request)) === origin)
5342
+ return true;
5343
+ return false;
5344
+ };
5345
+ if (!waiting())
5346
+ return Promise.resolve();
5347
+ return new Promise((resolve2) => {
5348
+ const done = () => {
5349
+ clearTimeout(timer2);
5350
+ this.frameDocumentChecks.delete(check);
5351
+ resolve2();
5352
+ };
5353
+ const check = () => {
5354
+ if (!waiting())
5355
+ done();
5356
+ };
5357
+ const timer2 = setTimeout(done, ms);
5358
+ this.frameDocumentChecks.add(check);
5359
+ });
5360
+ }
4722
5361
  settleRequest(request) {
4723
5362
  if (this.inflight.delete(request)) {
4724
5363
  this.lastNetworkActivity = Date.now();
@@ -4923,12 +5562,43 @@ class BrowserPageEvents {
4923
5562
  }
4924
5563
  }
4925
5564
  activeDialog() {
4926
- return this.dialog ? { ...this.dialog.event, dialogId: this.dialog.event.eventId } : null;
5565
+ if (this.dialog)
5566
+ return { ...this.dialog.event, dialogId: this.dialog.event.eventId };
5567
+ const auth = this.httpAuth.event();
5568
+ return auth ? { ...auth, dialogId: auth.eventId } : null;
5569
+ }
5570
+ javascriptDialogOpen() {
5571
+ return !!this.dialog;
5572
+ }
5573
+ httpAuthPrompt() {
5574
+ return this.httpAuth.prompt();
5575
+ }
5576
+ handHttpAuthToChrome(reason) {
5577
+ this.httpAuth.handToChrome(reason);
4927
5578
  }
4928
5579
  pendingAction() {
4929
5580
  return this.pending ? { actionId: this.pending.actionId, status: "pending" } : null;
4930
5581
  }
4931
- async handleDialog(input, handledBy = "agent") {
5582
+ async handleDialog(input, handledBy = "agent", options = {}) {
5583
+ const auth = await this.httpAuth.answer(input.dialogId, input, handledBy === "viewer" ? { by: "viewer", typed: options.typed } : {
5584
+ by: "agent",
5585
+ vaultId: typeof input.vaultId === "string" ? input.vaultId : undefined,
5586
+ names: input.names,
5587
+ expectedOrigin: typeof input.expectedOrigin === "string" ? input.expectedOrigin : undefined,
5588
+ reveal: options.reveal
5589
+ });
5590
+ if (auth) {
5591
+ const pending2 = this.pending;
5592
+ const outcome2 = auth.handled === true && auth.signIn !== "rejected" && pending2 ? await this.racePending(pending2, 1000) : undefined;
5593
+ return { ...auth, ...auth.handled === true ? { originalAction: outcome2 ?? this.pendingAction() } : {}, dialog: this.activeDialog() };
5594
+ }
5595
+ if (signsInWithVault(input))
5596
+ return {
5597
+ handled: false,
5598
+ code: this.dialog?.event.eventId === input.dialogId || this.passkey?.event.eventId === input.dialogId ? "not_http_auth" : "stale_dialog",
5599
+ dialog: this.activeDialog(),
5600
+ 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."
5601
+ };
4932
5602
  const passkey = this.passkey;
4933
5603
  if (passkey && input.dialogId === passkey.event.eventId) {
4934
5604
  if (input.decision !== "dismiss" || input.promptText !== undefined)
@@ -4990,19 +5660,24 @@ class BrowserPageEvents {
4990
5660
  }
4991
5661
  }
4992
5662
  async run(actionId, dispatch) {
4993
- if (this.dialog || this.pending)
5663
+ const holding = !!this.dialog || this.httpAuth.isOpen();
5664
+ if (holding || this.pending) {
5665
+ const httpAuth = this.dialog ? null : this.httpAuth.prompt();
4994
5666
  return {
4995
- dispatch: { status: "not_dispatched", code: this.dialog ? "dialog_blocking" : "previous_action_pending" },
5667
+ dispatch: { status: "not_dispatched", code: holding ? "dialog_blocking" : "previous_action_pending" },
4996
5668
  dialog: this.activeDialog(),
5669
+ ...httpAuth ? { httpAuth, recovery: HTTP_AUTH_RECOVERY } : {},
4997
5670
  pendingAction: this.pendingAction()
4998
5671
  };
5672
+ }
4999
5673
  this.currentAction = actionId;
5000
5674
  let interruptedByDialog = false;
5001
5675
  let wake;
5002
5676
  const interrupted = new Promise((resolve2) => {
5003
5677
  wake = () => {
5004
5678
  interruptedByDialog = true;
5005
- resolve2({ dispatch: { status: "blocked", actionId, code: "dialog_open" }, dialog: this.activeDialog() });
5679
+ const auth = this.dialog ? undefined : this.httpAuth.requiredResult(actionId);
5680
+ resolve2(auth ?? { dispatch: { status: "blocked", actionId, code: "dialog_open" }, dialog: this.activeDialog() });
5006
5681
  };
5007
5682
  this.listeners.add(wake);
5008
5683
  });
@@ -5090,7 +5765,7 @@ class BrowserPageEvents {
5090
5765
  // cli/src/browser/browser-webmcp.ts
5091
5766
  var NAME_REGISTRATION_WAIT_MS = 1000;
5092
5767
  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);
5768
+ var refusal2 = (code2, recovery, details) => new RuntimeFault(code2, recovery, true, details, true);
5094
5769
  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
5770
 
5096
5771
  class BrowserWebMCP {
@@ -5263,7 +5938,7 @@ class BrowserWebMCP {
5263
5938
  if (typeof input.toolId === "string") {
5264
5939
  const entry = this.tools.get(input.toolId);
5265
5940
  if (!entry)
5266
- throw refusal("stale_webmcp_tool", STALE_RECOVERY2);
5941
+ throw refusal2("stale_webmcp_tool", STALE_RECOVERY2);
5267
5942
  return entry;
5268
5943
  }
5269
5944
  const name = String(input.name);
@@ -5273,9 +5948,9 @@ class BrowserWebMCP {
5273
5948
  return matches[0];
5274
5949
  if (!matches.length) {
5275
5950
  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 } : {} });
5951
+ 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
5952
  }
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 })) });
5953
+ 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
5954
  }
5280
5955
  annotatedReadOnly(invocationId) {
5281
5956
  const key2 = String(invocationId);
@@ -5292,7 +5967,7 @@ class BrowserWebMCP {
5292
5967
  const tree = await this.cdp.send("Page.getFrameTree");
5293
5968
  const find = (node) => node.frame.id === entry.tool.frameId ? node.frame : node.childFrames?.map(find).find(Boolean);
5294
5969
  if (find(tree.frameTree)?.loaderId !== entry.loaderId || this.tools.get(entry.id) !== entry)
5295
- throw refusal("stale_webmcp_tool", STALE_RECOVERY2);
5970
+ throw refusal2("stale_webmcp_tool", STALE_RECOVERY2);
5296
5971
  let timer2;
5297
5972
  const { invocationId } = await this.cdp.send("WebMCP.invokeTool", {
5298
5973
  frameId: entry.tool.frameId,
@@ -5972,13 +6647,13 @@ async function exportDocument(page, format) {
5972
6647
  }
5973
6648
  }
5974
6649
  const text = await page.evaluate((format2) => {
5975
- const bounded2 = (text2) => {
6650
+ const bounded3 = (text2) => {
5976
6651
  if (text2.length > 20 * 1024 * 1024 || new TextEncoder().encode(text2).length > 20 * 1024 * 1024)
5977
6652
  throw new Error("Document export exceeds 20 MiB.");
5978
6653
  return text2;
5979
6654
  };
5980
6655
  if (format2 === "text")
5981
- return bounded2(document.body.innerText);
6656
+ return bounded3(document.body.innerText);
5982
6657
  const clone = document.documentElement.cloneNode(true);
5983
6658
  for (const el of clone.querySelectorAll('input[type="password"]'))
5984
6659
  el.setAttribute("value", "[password]");
@@ -5988,7 +6663,7 @@ async function exportDocument(page, format) {
5988
6663
  for (const attr of [...el.attributes])
5989
6664
  if (/^on/i.test(attr.name) || attr.name === "srcdoc" || /^[\s\u0000-\u0020]*(javascript|vbscript):/i.test(attr.value))
5990
6665
  el.removeAttribute(attr.name);
5991
- return bounded2(`<!doctype html>
6666
+ return bounded3(`<!doctype html>
5992
6667
  ` + clone.outerHTML);
5993
6668
  }, format);
5994
6669
  return {
@@ -6368,6 +7043,7 @@ var MAX_TYPED_KEYS_CHARS = 500;
6368
7043
  var MAX_TYPED_KEYS_TOTAL_MS = 20000;
6369
7044
  var TAB_PRESENTATION_TIMEOUT_MS = 2000;
6370
7045
  var OBSERVATION_BASELINE_CHARS = 30000;
7046
+ var DOCUMENT_READ_TIMEOUT_MS = 2000;
6371
7047
  var WEBMCP_WATCH_WAIT_MS = 1000;
6372
7048
  function joinLines(lines, maxChars, cutLongFirst = true) {
6373
7049
  const limit = Math.max(0, maxChars);
@@ -6416,9 +7092,9 @@ function withTimeout(work, ms) {
6416
7092
  })
6417
7093
  ]).finally(() => clearTimeout(timer2));
6418
7094
  }
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) });
7095
+ var refusal3 = (code2, recovery, details) => new RuntimeFault(code2, recovery, true, details, true);
7096
+ var staleRef = (ref) => refusal3("ref_stale", "Read the page again with browser_read_page and use a current ref. Nothing was dispatched.", { ref });
7097
+ 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
7098
  var problemOf = (error) => error instanceof Error ? error.message : "Invalid arguments.";
6423
7099
  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
7100
  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 +7129,7 @@ var EDITOR_TYPING_RULES = "A code editor applies its own typing rules to typed t
6453
7129
  function notAFormField(ref, info, standIn = false) {
6454
7130
  const kind = standIn ? "stand_in" : info.kind;
6455
7131
  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 });
7132
+ return refusal3("not_a_form_field", recovery, { ref, kind, tag: info.tag });
6457
7133
  }
6458
7134
  function typingNote(focused) {
6459
7135
  if (focused === undefined)
@@ -6478,6 +7154,21 @@ function tabStateView(state) {
6478
7154
  ...state.viewport ? { viewport: { width: state.viewport.width, height: state.viewport.height } } : {}
6479
7155
  };
6480
7156
  }
7157
+ function compareOutlines(baseline, current) {
7158
+ const lines = current.text.split(`
7159
+ `).filter(Boolean);
7160
+ const kept = baseline.text.split(`
7161
+ `).filter(Boolean);
7162
+ const before = new Set(kept);
7163
+ const after = new Set(lines);
7164
+ const edge = (index, length) => index < 0 ? length - 1 : index;
7165
+ const lastShared = baseline.clipped ? edge(lines.findLastIndex((line) => before.has(line)), lines.length) : lines.length - 1;
7166
+ const lastKept = current.clipped ? edge(kept.findLastIndex((line) => after.has(line)), kept.length) : kept.length - 1;
7167
+ return {
7168
+ changed: lines.filter((line, index) => index <= lastShared && !before.has(line)),
7169
+ removed: [...new Set(kept.filter((line, index) => index <= lastKept && !after.has(line)))]
7170
+ };
7171
+ }
6481
7172
 
6482
7173
  class BrowserRuntime {
6483
7174
  context;
@@ -6491,15 +7182,19 @@ class BrowserRuntime {
6491
7182
  pages = new Map;
6492
7183
  cursor = new Map;
6493
7184
  viewportSessions = new Map;
7185
+ takeoverViewports = new Map;
7186
+ viewportChanges = new Map;
6494
7187
  uploads;
6495
7188
  events = new WeakMap;
6496
7189
  webmcp = new WeakMap;
6497
7190
  initialization = new Map;
6498
7191
  contexts = new Map;
6499
7192
  observations = new Map;
7193
+ outlines = new WeakMap;
6500
7194
  lastActions = new Map;
6501
7195
  tabPresentation = new WeakMap;
6502
7196
  savingDownloads = new Set;
7197
+ httpAuthPolicy;
6503
7198
  constructor(context, downloadsPath, uploadsPath = `${downloadsPath}.uploads`, downloadHandler, guardPage, passkeyDetection = true, screenshotMaxEdge = MAX_IMAGE_DIMENSION) {
6504
7199
  this.context = context;
6505
7200
  this.downloadsPath = downloadsPath;
@@ -6564,6 +7259,7 @@ class BrowserRuntime {
6564
7259
  this.lastActions.delete(currentId);
6565
7260
  this.initialization.delete(page);
6566
7261
  this.viewportSessions.delete(currentId);
7262
+ this.takeoverViewports.delete(currentId);
6567
7263
  }
6568
7264
  track(page) {
6569
7265
  const existing = this.ids.get(page);
@@ -6573,7 +7269,7 @@ class BrowserRuntime {
6573
7269
  const id = crypto.randomUUID();
6574
7270
  this.ids.set(page, id);
6575
7271
  this.pages.set(id, page);
6576
- this.events.set(page, new BrowserPageEvents(page, this.passkeyDetection));
7272
+ this.events.set(page, new BrowserPageEvents(page, this.passkeyDetection, (acting) => this.answersHttpAuth(page, acting)));
6577
7273
  followRestoredFrames(page);
6578
7274
  page.on("framenavigated", () => {
6579
7275
  const tabId = this.ids.get(page);
@@ -6754,7 +7450,7 @@ class BrowserRuntime {
6754
7450
  async openTabIn(context, newWindow) {
6755
7451
  const entry = this.contexts.get(context);
6756
7452
  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.");
7453
+ 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
7454
  const startup = entry.startupPage;
6759
7455
  entry.startupPage = undefined;
6760
7456
  if (startup && !startup.isClosed() && startup.url() === "about:blank" && this.ids.has(startup))
@@ -6793,7 +7489,7 @@ class BrowserRuntime {
6793
7489
  selector = snapshotSelector(page, target2);
6794
7490
  } catch (error) {
6795
7491
  if (/frames/.test(error instanceof Error ? error.message : ""))
6796
- throw refusal2("target_invalid", TARGET_INVALID, echo);
7492
+ throw refusal3("target_invalid", TARGET_INVALID, echo);
6797
7493
  throw error;
6798
7494
  }
6799
7495
  const look = async (query, maxMatches) => {
@@ -6802,7 +7498,7 @@ class BrowserRuntime {
6802
7498
  } catch (error) {
6803
7499
  if (page.isClosed() || error instanceof RuntimeFault || /unavailable/i.test(error instanceof Error ? error.message : ""))
6804
7500
  throw error;
6805
- throw refusal2("target_unresolved", TARGET_UNRESOLVED, echo);
7501
+ throw refusal3("target_unresolved", TARGET_UNRESOLVED, echo);
6806
7502
  }
6807
7503
  };
6808
7504
  const deadline = Date.now() + TARGET_WAIT_MS;
@@ -6815,11 +7511,11 @@ class BrowserRuntime {
6815
7511
  throw error;
6816
7512
  }
6817
7513
  if (found?.invalidQuery)
6818
- throw refusal2("target_invalid", TARGET_INVALID, echo);
7514
+ throw refusal3("target_invalid", TARGET_INVALID, echo);
6819
7515
  if (found && found.matchCount === 1 && found.matches[0])
6820
7516
  return { ref: found.matches[0].ref, match: found.matches[0] };
6821
7517
  if (found && found.matchCount > 1)
6822
- throw refusal2("target_ambiguous", TARGET_AMBIGUOUS, { ...echo, matchCount: found.matchCount, candidates: found.matches.slice(0, MAX_TARGET_CANDIDATES) });
7518
+ throw refusal3("target_ambiguous", TARGET_AMBIGUOUS, { ...echo, matchCount: found.matchCount, candidates: found.matches.slice(0, MAX_TARGET_CANDIDATES) });
6823
7519
  if (Date.now() >= deadline) {
6824
7520
  const near = [];
6825
7521
  if (target2.exact !== false && (target2.name || target2.text || target2.label || target2.placeholder))
@@ -6832,7 +7528,7 @@ class BrowserRuntime {
6832
7528
  if (candidates.length)
6833
7529
  break;
6834
7530
  }
6835
- throw refusal2("target_not_found", TARGET_NOT_FOUND, {
7531
+ throw refusal3("target_not_found", TARGET_NOT_FOUND, {
6836
7532
  ...echo,
6837
7533
  matchCount: 0,
6838
7534
  ...found?.hiddenMatchCount ? { hiddenMatchCount: found.hiddenMatchCount } : {},
@@ -6854,13 +7550,13 @@ class BrowserRuntime {
6854
7550
  count = await locator.count();
6855
7551
  } catch (error) {
6856
7552
  if (invalidSelector(error))
6857
- throw refusal2("screenshot_target_invalid", SCREENSHOT_INVALID_SELECTOR_RECOVERY);
7553
+ throw refusal3("screenshot_target_invalid", SCREENSHOT_INVALID_SELECTOR_RECOVERY);
6858
7554
  throw error;
6859
7555
  }
6860
7556
  if (count !== 1)
6861
- throw refusal2(count ? "screenshot_target_ambiguous" : "screenshot_target_missing", SCREENSHOT_SELECTOR_RECOVERY, { matchCount: count });
7557
+ throw refusal3(count ? "screenshot_target_ambiguous" : "screenshot_target_missing", SCREENSHOT_SELECTOR_RECOVERY, { matchCount: count });
6862
7558
  }
6863
- const gone = () => ref !== undefined ? staleRef(ref) : refusal2("screenshot_target_missing", SCREENSHOT_SELECTOR_RECOVERY, { matchCount: 0 });
7559
+ const gone = () => ref !== undefined ? staleRef(ref) : refusal3("screenshot_target_missing", SCREENSHOT_SELECTOR_RECOVERY, { matchCount: 0 });
6864
7560
  let handle;
6865
7561
  try {
6866
7562
  handle = await locator.elementHandle({ timeout: REF_ACTION_TIMEOUT_MS });
@@ -6871,7 +7567,7 @@ class BrowserRuntime {
6871
7567
  }
6872
7568
  try {
6873
7569
  if (!await handle.isVisible())
6874
- throw refusal2("screenshot_target_not_visible", SCREENSHOT_NOT_VISIBLE_RECOVERY);
7570
+ throw refusal3("screenshot_target_not_visible", SCREENSHOT_NOT_VISIBLE_RECOVERY);
6875
7571
  const before = await handle.boundingBox();
6876
7572
  try {
6877
7573
  await handle.scrollIntoViewIfNeeded({ timeout: REF_ACTION_TIMEOUT_MS });
@@ -6917,8 +7613,11 @@ class BrowserRuntime {
6917
7613
  throw staleRef(ref);
6918
7614
  throw error;
6919
7615
  }
7616
+ let direct;
6920
7617
  try {
7618
+ direct = await FrameInput.of(page, handle);
6921
7619
  let scrolled = false;
7620
+ let revealed = false;
6922
7621
  let previous;
6923
7622
  for (;; ) {
6924
7623
  const probe = await probePointer(handle);
@@ -6926,13 +7625,55 @@ class BrowserRuntime {
6926
7625
  throw staleRef(ref);
6927
7626
  const standIn = "standIn" in probe ? probe.standIn : undefined;
6928
7627
  if (probe.kind === "outside_viewport" && !scrolled) {
7628
+ if (direct && !revealed) {
7629
+ revealed = true;
7630
+ await direct.reveal(Math.min(remaining(), 2000));
7631
+ continue;
7632
+ }
6929
7633
  scrolled = true;
6930
7634
  await handle.scrollIntoViewIfNeeded({ timeout: Math.min(remaining(), 2000) }).catch(() => {
6931
7635
  return;
6932
7636
  });
6933
7637
  continue;
6934
7638
  }
6935
- if (probe.kind === "stand_in") {
7639
+ let blocked = probe;
7640
+ if (direct && (probe.kind === "element" || probe.kind === "stand_in")) {
7641
+ if (previous?.kind === probe.kind && Math.abs(previous.point.x - probe.point.x) < 1 && Math.abs(previous.point.y - probe.point.y) < 1) {
7642
+ const path10 = await direct.path(probe.point, NAME_CHARS);
7643
+ if (!path10) {
7644
+ direct.dispose();
7645
+ direct = undefined;
7646
+ continue;
7647
+ }
7648
+ if (path10.kind === "reached") {
7649
+ this.cursor.delete(tabId);
7650
+ try {
7651
+ if (action === "click")
7652
+ await direct.click(path10.root, button, clickCount);
7653
+ else
7654
+ await direct.hover(path10.root, modifiers);
7655
+ } catch (error) {
7656
+ throw refActionError(error, ref, action);
7657
+ }
7658
+ if (probe.kind === "element")
7659
+ return { cursorKnown: false };
7660
+ return await this.standInResult(page, handle, probe, action, undefined);
7661
+ }
7662
+ if (path10.kind === "outside_viewport" && (!revealed || !scrolled)) {
7663
+ if (!revealed) {
7664
+ revealed = true;
7665
+ await direct.reveal(Math.min(remaining(), 2000));
7666
+ } else {
7667
+ scrolled = true;
7668
+ await handle.scrollIntoViewIfNeeded({ timeout: Math.min(remaining(), 2000) }).catch(() => {
7669
+ return;
7670
+ });
7671
+ }
7672
+ continue;
7673
+ }
7674
+ blocked = path10.kind === "covered" ? { kind: "covered", point: probe.point, box: probe.box, cover: path10.cover } : { kind: "outside_viewport" };
7675
+ }
7676
+ } else if (probe.kind === "stand_in") {
6936
7677
  if (previous?.kind === "stand_in" && Math.abs(previous.point.x - probe.point.x) < 1 && Math.abs(previous.point.y - probe.point.y) < 1) {
6937
7678
  const point = roundPoint(await this.pagePoint(handle, probe));
6938
7679
  this.cursor.delete(tabId);
@@ -6949,22 +7690,9 @@ class BrowserRuntime {
6949
7690
  }
6950
7691
  }
6951
7692
  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
- };
7693
+ return await this.standInResult(page, handle, probe, action, point);
6966
7694
  }
6967
- } else if (!standIn || probe.kind === "element") {
7695
+ } else if (!direct && (!standIn || probe.kind === "element")) {
6968
7696
  this.cursor.delete(tabId);
6969
7697
  try {
6970
7698
  if (action === "click")
@@ -6977,18 +7705,34 @@ class BrowserRuntime {
6977
7705
  return { cursorKnown: false };
6978
7706
  }
6979
7707
  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 } : {} } : {} });
7708
+ const { reason, problem, next } = pointerProblem(blocked);
7709
+ 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
7710
  }
6983
7711
  previous = probe;
6984
- await new Promise((resolve2) => setTimeout(resolve2, probe.kind === "stand_in" ? 50 : 150));
7712
+ await new Promise((resolve2) => setTimeout(resolve2, probe.kind === "stand_in" || direct ? 50 : 150));
6985
7713
  }
6986
7714
  } finally {
6987
7715
  handle.dispose().catch(() => {
6988
7716
  return;
6989
7717
  });
7718
+ direct?.dispose();
6990
7719
  }
6991
7720
  }
7721
+ async standInResult(page, handle, probe, action, point) {
7722
+ const focused = action === "click" ? await withTimeout(focusWithin(handle), 1000).catch(() => {
7723
+ return;
7724
+ }) : undefined;
7725
+ const elsewhere = focused === false ? await withTimeout(page.evaluate(focusedElementInPage, NAME_CHARS), 1000).catch(() => {
7726
+ return;
7727
+ }) : undefined;
7728
+ return {
7729
+ ...point ? { ...point, cursorKnown: true } : { cursorKnown: false },
7730
+ standIn: { reason: probe.standIn, widget: probe.widget },
7731
+ ...focused === undefined ? {} : { focused },
7732
+ ...elsewhere ? { focusedElement: focusedView(elsewhere) } : {},
7733
+ 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" : ""}.` : "")
7734
+ };
7735
+ }
6992
7736
  async pagePoint(handle, probe) {
6993
7737
  const frame = await handle.ownerFrame();
6994
7738
  if (!frame?.parentFrame())
@@ -7013,6 +7757,24 @@ class BrowserRuntime {
7013
7757
  const probe = await probePointer(target2, REF_ACTION_TIMEOUT_MS);
7014
7758
  return "standIn" in probe && !!probe.standIn && probe.kind !== "element";
7015
7759
  }
7760
+ async takesDirectInput(page, target2) {
7761
+ if (!showsRestoredDocument(page))
7762
+ return false;
7763
+ const handle = await target2.elementHandle({ timeout: REF_ACTION_TIMEOUT_MS }).catch(() => {
7764
+ return;
7765
+ });
7766
+ if (!handle)
7767
+ return false;
7768
+ try {
7769
+ const input = await FrameInput.of(page, handle);
7770
+ input?.dispose();
7771
+ return !!input;
7772
+ } finally {
7773
+ handle.dispose().catch(() => {
7774
+ return;
7775
+ });
7776
+ }
7777
+ }
7016
7778
  async setCheckedAtRef(page, tabId, locator, ref, checked) {
7017
7779
  const state = () => locator.evaluate((element) => ({ checked: element.checked, radio: element.type === "radio" }), undefined, {
7018
7780
  timeout: REF_ACTION_TIMEOUT_MS
@@ -7021,8 +7783,8 @@ class BrowserRuntime {
7021
7783
  if (before.checked === checked)
7022
7784
  return;
7023
7785
  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)) {
7786
+ throw refusal3("invalid_browser_input", "A radio button is unchecked by checking another radio button of its group. Nothing was changed.", { ref });
7787
+ if (await this.takesDirectInput(page, locator) || await this.coveredStandIn(locator)) {
7026
7788
  await this.pointAtRef(page, tabId, ref, "click", {});
7027
7789
  if ((await state()).checked !== checked)
7028
7790
  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 });
@@ -7036,6 +7798,7 @@ class BrowserRuntime {
7036
7798
  }
7037
7799
  }
7038
7800
  async gotoSettled(page, url) {
7801
+ const mark = this.events.get(page)?.frameDocumentMark();
7039
7802
  try {
7040
7803
  await page.goto(url, { waitUntil: "domcontentloaded", timeout: NAVIGATION_TIMEOUT_MS });
7041
7804
  } catch (error) {
@@ -7048,8 +7811,13 @@ class BrowserRuntime {
7048
7811
  return;
7049
7812
  });
7050
7813
  }
7814
+ await this.framesSettled(page, mark);
7051
7815
  return {};
7052
7816
  }
7817
+ async framesSettled(page, mark) {
7818
+ if (mark !== undefined)
7819
+ await this.events.get(page)?.framesSettled(mark, page.url(), FRAME_DOCUMENT_SETTLE_MS);
7820
+ }
7053
7821
  async tabInfo(page, presented) {
7054
7822
  this.track(page);
7055
7823
  await this.initialization.get(page);
@@ -7118,6 +7886,17 @@ class BrowserRuntime {
7118
7886
  await Promise.all(this.savingDownloads);
7119
7887
  }
7120
7888
  async setViewport(page, tabId, viewport) {
7889
+ const fitted = this.takeoverViewports.has(tabId);
7890
+ if (!fitted)
7891
+ await this.inOrder(tabId, () => this.overrideViewport(page, tabId, viewport));
7892
+ if (viewport && !fitted) {
7893
+ const ready = await page.waitForFunction(({ width, height }) => window.innerWidth === width && window.innerHeight === height, viewport, { timeout: 5000 });
7894
+ await ready.dispose();
7895
+ }
7896
+ const actual = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
7897
+ return { tabId, ...actual, reset: viewport === null };
7898
+ }
7899
+ async overrideViewport(page, tabId, viewport) {
7121
7900
  const existing = this.viewportSessions.get(tabId);
7122
7901
  if (viewport) {
7123
7902
  const cdp = existing ?? await page.context().newCDPSession(page);
@@ -7139,16 +7918,51 @@ class BrowserRuntime {
7139
7918
  });
7140
7919
  }
7141
7920
  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();
7921
+ this.screenshots.delete(tabId);
7922
+ }
7923
+ inOrder(tabId, change) {
7924
+ const result = (this.viewportChanges.get(tabId) ?? Promise.resolve()).then(change);
7925
+ const settled = result.catch(() => {
7926
+ return;
7927
+ });
7928
+ this.viewportChanges.set(tabId, settled);
7929
+ settled.then(() => {
7930
+ if (this.viewportChanges.get(tabId) === settled)
7931
+ this.viewportChanges.delete(tabId);
7932
+ });
7933
+ return result;
7934
+ }
7935
+ async takeoverViewport(tabId, viewport) {
7936
+ const page = this.pages.get(tabId);
7937
+ if (!page || page.isClosed()) {
7938
+ this.takeoverViewports.delete(tabId);
7939
+ return;
7145
7940
  }
7146
- const actual = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
7147
- return { tabId, ...actual, reset: viewport === null };
7941
+ if (viewport)
7942
+ this.takeoverViewports.set(tabId, { width: viewport.width, height: viewport.height });
7943
+ else if (!this.takeoverViewports.delete(tabId))
7944
+ return;
7945
+ await this.inOrder(tabId, async () => {
7946
+ if (page.isClosed())
7947
+ return;
7948
+ const own = (await this.entryOf(page).tabState.resolve(page)).state.viewport ?? null;
7949
+ await this.overrideViewport(page, tabId, this.takeoverViewports.get(tabId) ?? own);
7950
+ });
7148
7951
  }
7149
7952
  hasPendingInteraction() {
7150
7953
  return [...this.pages.values()].some((page) => !!this.events.get(page)?.activeDialog() || !!this.events.get(page)?.pendingAction());
7151
7954
  }
7955
+ answersHttpAuth(page, acting) {
7956
+ const tabId = this.ids.get(page);
7957
+ if (!tabId || page.isClosed())
7958
+ return false;
7959
+ return this.httpAuthPolicy ? this.httpAuthPolicy(tabId, acting) : acting;
7960
+ }
7961
+ handHttpAuthToChrome(reason, tabId) {
7962
+ for (const [id, page] of this.pages)
7963
+ if (tabId === undefined || id === tabId)
7964
+ this.events.get(page)?.handHttpAuthToChrome(reason);
7965
+ }
7152
7966
  assertCrashAllows(page, action, input) {
7153
7967
  const events = this.events.get(page);
7154
7968
  const crash = events?.crash();
@@ -7183,6 +7997,11 @@ class BrowserRuntime {
7183
7997
  }
7184
7998
  });
7185
7999
  }
8000
+ async documentShown(page) {
8001
+ return await withTimeout(this.guardRaw(page, "all", () => shownDocument(page)), DOCUMENT_READ_TIMEOUT_MS).catch(() => {
8002
+ return;
8003
+ });
8004
+ }
7186
8005
  async reloadCrashed(page) {
7187
8006
  const events = this.events.get(page);
7188
8007
  const held = events.session();
@@ -7320,13 +8139,15 @@ class BrowserRuntime {
7320
8139
  const { page, events } = await this.addressedTab(action, input);
7321
8140
  if (page)
7322
8141
  this.assertCrashAllows(page, action, input);
7323
- if (events?.activeDialog() && !["events", "diagnostics", "handle_dialog", "cancel_transfer"].includes(action))
8142
+ if (events?.activeDialog() && !["events", "diagnostics", "handle_dialog", "cancel_transfer"].includes(action)) {
8143
+ const httpAuth = events.javascriptDialogOpen() ? null : events.httpAuthPrompt();
7324
8144
  return {
7325
8145
  tabId: input.tabId,
7326
8146
  dispatch: { status: "not_dispatched", code: "dialog_blocking" },
7327
8147
  dialog: events.activeDialog(),
7328
- recovery: "Handle this dialog explicitly within the user's authorized task."
8148
+ ...httpAuth ? { httpAuth, recovery: HTTP_AUTH_RECOVERY } : { recovery: "Handle this dialog explicitly within the user's authorized task." }
7329
8149
  };
8150
+ }
7330
8151
  const passkeyPrompt = events?.passkeyPrompt();
7331
8152
  if (passkeyPrompt && PASSKEY_BLOCKED_OPERATIONS.has(action))
7332
8153
  return {
@@ -7401,23 +8222,14 @@ class BrowserRuntime {
7401
8222
  }
7402
8223
  }
7403
8224
  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);
8225
+ const snapshot = await this.dispatch("read_page", { tabId: input.tabId, maxChars: observation.maxChars }, execution);
7406
8226
  await Promise.all(this.initialization.values());
7407
8227
  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)))];
8228
+ const current = this.outlines.get(snapshot);
8229
+ const baseline = previous && current && previous.document === current.document ? previous : undefined;
8230
+ if (observation.mode === "summary" && baseline && current) {
8231
+ const { changed: changedLines, removed: removedLines } = compareOutlines(baseline, current);
8232
+ const compared = current.clipped;
7421
8233
  const text2 = joinLines(changedLines, observation.maxChars);
7422
8234
  const removed = joinLines(removedLines, observation.maxChars - text2.text.length, false);
7423
8235
  const notes = [
@@ -7449,10 +8261,6 @@ class BrowserRuntime {
7449
8261
  }
7450
8262
  };
7451
8263
  }
7452
- const lines = String(snapshot.text ?? "").split(`
7453
- `), before = new Set(previous?.text.split(`
7454
- `) ?? []);
7455
- const after = new Set(lines);
7456
8264
  const text = String(snapshot.text ?? "");
7457
8265
  return {
7458
8266
  ...result,
@@ -7464,9 +8272,8 @@ class BrowserRuntime {
7464
8272
  available: !snapshot.code,
7465
8273
  text,
7466
8274
  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)),
8275
+ baselineAvailable: !!baseline,
8276
+ removed: baseline && current ? joinLines(compareOutlines(baseline, current).removed, observation.maxChars - text.length, false).text : "",
7470
8277
  newTabIds,
7471
8278
  untrusted: true
7472
8279
  }
@@ -7657,12 +8464,13 @@ class BrowserRuntime {
7657
8464
  ...await this.events.get(page).waitQuery(input),
7658
8465
  dialog: this.events.get(page).activeDialog(),
7659
8466
  passkeyPrompt: this.events.get(page).passkeyPrompt(),
8467
+ httpAuth: this.events.get(page).httpAuthPrompt(),
7660
8468
  pendingAction: this.events.get(page).pendingAction()
7661
8469
  };
7662
8470
  case "diagnostics":
7663
8471
  return { tabId, ...this.events.get(page).query(input, true) };
7664
8472
  case "handle_dialog":
7665
- return { tabId, ...await this.events.get(page).handleDialog(input) };
8473
+ return { tabId, ...await this.events.get(page).handleDialog(input, "agent", { reveal: execution.revealHttpAuth }) };
7666
8474
  case "cancel_transfer":
7667
8475
  return { tabId, ...await this.events.get(page).cancelTransfer(String(input.eventId)) };
7668
8476
  case "inspect":
@@ -7731,7 +8539,10 @@ class BrowserRuntime {
7731
8539
  return await this.reloadCrashed(page);
7732
8540
  }
7733
8541
  const before = page.url();
8542
+ const mark = this.events.get(page).frameDocumentMark();
7734
8543
  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);
8544
+ if (traversed && !traversed.restoredFromCache && !(("frame" in traversed) && traversed.frame === "child"))
8545
+ await this.framesSettled(page, mark);
7735
8546
  if (!traversed)
7736
8547
  return {
7737
8548
  tab: await this.tabInfo(page),
@@ -7846,6 +8657,8 @@ class BrowserRuntime {
7846
8657
  }
7847
8658
  case "read_page": {
7848
8659
  const request = parseSnapshotInput(input);
8660
+ const keepsBaseline = !request.query && !request.scope && !request.frames.length && !request.interactive && !request.boxes;
8661
+ const documentBefore = keepsBaseline ? await this.documentShown(page) : undefined;
7849
8662
  const capture = () => passwordSafeAriaSnapshot(page, {
7850
8663
  mode: "ai",
7851
8664
  boxes: request.boxes,
@@ -7888,6 +8701,7 @@ class BrowserRuntime {
7888
8701
  };
7889
8702
  }
7890
8703
  const observed = this.observedAt(page, tabId);
8704
+ const documentAfter = keepsBaseline ? await this.documentShown(page) : undefined;
7891
8705
  const result = {
7892
8706
  tabId,
7893
8707
  url: page.url(),
@@ -7897,13 +8711,18 @@ class BrowserRuntime {
7897
8711
  return;
7898
8712
  }))
7899
8713
  };
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);
8714
+ if (keepsBaseline && !("code" in result)) {
8715
+ this.observations.delete(tabId);
8716
+ if (documentBefore !== undefined && documentBefore === documentAfter) {
8717
+ const reuse = request.depth === undefined && request.maxChars === OBSERVATION_BASELINE_CHARS;
8718
+ const outline2 = reuse ? result : renderSnapshot(snapshot, { ...parseSnapshotInput({}), maxChars: OBSERVATION_BASELINE_CHARS });
8719
+ const clipped = "completeness" in outline2 && outline2.completeness.characterLimited;
8720
+ const kept = { text: outline2.text, url: result.url, clipped, document: documentBefore };
8721
+ this.observations.set(tabId, kept);
8722
+ if (this.observations.size > 64)
8723
+ this.observations.delete(this.observations.keys().next().value);
8724
+ this.outlines.set(result, kept);
8725
+ }
7907
8726
  }
7908
8727
  return result;
7909
8728
  }
@@ -7933,7 +8752,7 @@ class BrowserRuntime {
7933
8752
  } else if (input.crop) {
7934
8753
  const crop = input.crop;
7935
8754
  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 } });
8755
+ 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
8756
  [region, format, kind, extra] = [{ kind: "viewport", x: crop.x, y: crop.y, width: crop.width, height: crop.height }, SCREENSHOT_PNG, "crop", {}];
7938
8757
  } else if (input.fullPage === true) {
7939
8758
  execution.screenshotStage?.("screenshot_metrics");
@@ -8050,7 +8869,7 @@ class BrowserRuntime {
8050
8869
  }
8051
8870
  const cursor = this.cursor.get(tabId);
8052
8871
  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.");
8872
+ 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.");
8054
8873
  await withFramesDrawn(page, () => page.mouse.click(cursor.x, cursor.y, { button, clickCount }));
8055
8874
  return { tabId, ...cursor, button };
8056
8875
  }
@@ -8161,12 +8980,12 @@ class BrowserRuntime {
8161
8980
  const kind = info.kind === "select" && info.multiple ? "multiselect" : info.kind;
8162
8981
  const expectField = (field) => {
8163
8982
  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 });
8983
+ 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
8984
  };
8166
8985
  const matchOption = (options, entry) => {
8167
8986
  const match2 = options.find((option) => option.value === entry) ?? options.find((option) => option.label === entry.trim());
8168
8987
  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) });
8988
+ 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
8989
  return match2.value;
8171
8990
  };
8172
8991
  try {
@@ -8400,9 +9219,38 @@ function outsideCancellation(work) {
8400
9219
  return current.exit(work);
8401
9220
  }
8402
9221
 
9222
+ // cli/src/runtime/frame-documents.ts
9223
+ import { createRequire as createRequire4 } from "node:module";
9224
+ var requirePlaywright3 = createRequire4(import.meta.url);
9225
+ var SUPPORTED_PLAYWRIGHT_VERSION3 = "1.63.0";
9226
+ var supported;
9227
+ function playwrightSupported() {
9228
+ if (supported === undefined) {
9229
+ try {
9230
+ supported = requirePlaywright3("playwright-core/package.json").version === SUPPORTED_PLAYWRIGHT_VERSION3;
9231
+ } catch {
9232
+ supported = false;
9233
+ }
9234
+ }
9235
+ return supported;
9236
+ }
9237
+ function followNewDocuments(frame, onNewDocument) {
9238
+ if (!playwrightSupported())
9239
+ return false;
9240
+ const events = frame._eventEmitter;
9241
+ if (typeof events?.on !== "function")
9242
+ return false;
9243
+ events.on("navigated", (event) => {
9244
+ if (event && !event.error && event.newDocument)
9245
+ onNewDocument();
9246
+ });
9247
+ return true;
9248
+ }
9249
+
8403
9250
  // cli/src/runtime/native.ts
8404
9251
  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
9252
  var scopeKey = (s) => JSON.stringify([s.browserId, s.tokenId, s.sessionKey, s.instanceId]);
9253
+ var FRAME_KEY = /^(\d+)([.:])\d+$/;
8406
9254
  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
9255
 
8408
9256
  class NativeRuntime {
@@ -8413,7 +9261,12 @@ class NativeRuntime {
8413
9261
  plugins = [];
8414
9262
  owners = new Map;
8415
9263
  closedOwners = new Map;
8416
- generations = new Map;
9264
+ documents = new Map;
9265
+ frameSerials = new WeakMap;
9266
+ frameNavigations = new WeakMap;
9267
+ frameDocuments = new WeakMap;
9268
+ followedFrames = new WeakSet;
9269
+ nextFrameSerial = 0;
8417
9270
  tracking = new WeakMap;
8418
9271
  ended = new Set;
8419
9272
  epochs = new Map;
@@ -8434,6 +9287,7 @@ class NativeRuntime {
8434
9287
  this.serverOrigin = serverOrigin;
8435
9288
  installCancellation(context);
8436
9289
  this.engine = new BrowserRuntime(context, directory, `${directory}.uploads`, (download, page, downloadId) => this.download(download, page, downloadId), async (page) => this.assertPageAvailable(page), passkeyDetection, screenshotMaxEdge);
9290
+ this.engine.httpAuthPolicy = (tabId, acting) => !this.disconnected && (acting || this.owners.has(tabId) || this.userControlledTabs.has(tabId));
8437
9291
  context.on("page", (page) => {
8438
9292
  this.track(page);
8439
9293
  });
@@ -8485,7 +9339,7 @@ class NativeRuntime {
8485
9339
  }
8486
9340
  async trackPage(page) {
8487
9341
  const id = await this.engine.idFor(page);
8488
- this.generations.set(id, 0);
9342
+ this.documents.set(id, 0);
8489
9343
  const opener = await page.opener();
8490
9344
  if (opener) {
8491
9345
  await this.track(opener);
@@ -8493,21 +9347,26 @@ class NativeRuntime {
8493
9347
  if (owner)
8494
9348
  this.owners.set(id, { ...owner });
8495
9349
  }
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
- });
9350
+ const documentEnded = () => this.enqueue(async () => {
9351
+ for (const plugin of this.plugins)
9352
+ await plugin.onNavigation?.(id);
9353
+ });
9354
+ page.on("framenavigated", (frame) => {
9355
+ this.frameNavigations.set(frame, (this.frameNavigations.get(frame) ?? 0) + 1);
9356
+ if (!this.followedFrames.has(frame))
9357
+ this.frameDocuments.set(frame, (this.frameDocuments.get(frame) ?? 0) + 1);
9358
+ if (!frame.parentFrame())
9359
+ this.documents.set(id, (this.documents.get(id) ?? 0) + 1);
9360
+ documentEnded();
8503
9361
  });
9362
+ page.on("framedetached", documentEnded);
8504
9363
  page.on("close", () => {
8505
9364
  const owner = this.owners.get(id);
8506
9365
  if (owner) {
8507
9366
  this.closedOwners.set(page, owner);
8508
9367
  setTimeout(() => this.closedOwners.delete(page), 60000).unref?.();
8509
9368
  }
8510
- this.generations.delete(id);
9369
+ this.documents.delete(id);
8511
9370
  this.owners.delete(id);
8512
9371
  this.enqueue(async () => {
8513
9372
  for (const plugin of this.plugins)
@@ -8515,6 +9374,37 @@ class NativeRuntime {
8515
9374
  });
8516
9375
  });
8517
9376
  }
9377
+ serialOf(frame) {
9378
+ let serial = this.frameSerials.get(frame);
9379
+ if (serial === undefined) {
9380
+ serial = ++this.nextFrameSerial;
9381
+ this.frameSerials.set(frame, serial);
9382
+ if (followNewDocuments(frame, () => this.frameDocuments.set(frame, (this.frameDocuments.get(frame) ?? 0) + 1)))
9383
+ this.followedFrames.add(frame);
9384
+ }
9385
+ return serial;
9386
+ }
9387
+ keyOf(frame, kind) {
9388
+ const serial = this.serialOf(frame);
9389
+ return kind === "navigation" ? `${serial}.${this.frameNavigations.get(frame) ?? 0}` : `${serial}:${this.frameDocuments.get(frame) ?? 0}`;
9390
+ }
9391
+ frameShowing(page, key2) {
9392
+ const match = FRAME_KEY.exec(key2);
9393
+ if (!match)
9394
+ return;
9395
+ const serial = Number(match[1]), kind = match[2] === ":" ? "document" : "navigation";
9396
+ const frame = page.frames().find((candidate) => this.frameSerials.get(candidate) === serial);
9397
+ return frame && !frame.isDetached() && this.keyOf(frame, kind) === key2 ? { frame, kind } : undefined;
9398
+ }
9399
+ documentCurrent(tabId, document2) {
9400
+ let page;
9401
+ try {
9402
+ page = this.engine.page(tabId);
9403
+ } catch {
9404
+ return false;
9405
+ }
9406
+ return !page.isClosed() && !!this.frameShowing(page, document2);
9407
+ }
8518
9408
  revokeOwnership(tabId) {
8519
9409
  this.owners.delete(tabId);
8520
9410
  let page;
@@ -8553,7 +9443,7 @@ class NativeRuntime {
8553
9443
  await this.discardDownload(download, spool);
8554
9444
  return { state: "canceled", readiness: "unavailable", code: "capture_unavailable" };
8555
9445
  }
8556
- return handler.onDownload(download, id, owner, this.generations.get(id) ?? 0, downloadId, spool);
9446
+ return handler.onDownload(download, id, owner, downloadId, spool);
8557
9447
  }
8558
9448
  async discardDownload(download, spool) {
8559
9449
  const plugin = this.plugins.find((p) => p.discardDownload);
@@ -8575,6 +9465,9 @@ class NativeRuntime {
8575
9465
  throw new RuntimeFault("tab_closed", "Use browser_list_tabs to choose an open tab.", true);
8576
9466
  }
8577
9467
  async resolveTarget(tabId, scope, frames = []) {
9468
+ return await this.locate(tabId, scope, frames, "navigation");
9469
+ }
9470
+ async locate(tabId, scope, frames, kind) {
8578
9471
  this.validateScope(scope);
8579
9472
  const page = await this.claimPage(tabId, scope);
8580
9473
  await this.track(page);
@@ -8591,18 +9484,31 @@ class NativeRuntime {
8591
9484
  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
9485
  frame = next;
8593
9486
  }
8594
- const generation = this.generations.get(tabId) ?? 0;
8595
- const scopeEpoch = this.epochs.get(scopeKey(scope)) ?? 0;
9487
+ return this.bound(page, frame, tabId, scope, kind);
9488
+ }
9489
+ async resolveDocument(tabId, scope, document2) {
9490
+ this.validateScope(scope);
9491
+ const page = await this.claimPage(tabId, scope);
9492
+ await this.track(page);
9493
+ this.assertPageAvailable(page);
9494
+ const shown = this.frameShowing(page, document2);
9495
+ if (!shown)
9496
+ throw new Error("Stale document or scope");
9497
+ return this.bound(page, shown.frame, tabId, scope, shown.kind, document2);
9498
+ }
9499
+ bound(page, frame, tabId, scope, kind, document2 = this.keyOf(frame, kind)) {
9500
+ const scopeEpoch = this.epochs.get(scopeKey(scope)) ?? 0, pageEpoch = this.pageEpochs.get(page) ?? 0;
8596
9501
  const assertCurrent = () => {
8597
9502
  this.validateScope(scope);
8598
9503
  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))
9504
+ const owner = this.owners.get(tabId);
9505
+ 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
9506
  throw new Error("Stale document or scope");
8601
9507
  };
8602
- return { page, frame, tabId, generation, assertCurrent };
9508
+ return { page, frame, tabId, document: document2, generation: this.frameNavigations.get(frame) ?? 0, assertCurrent };
8603
9509
  }
8604
9510
  async resolveUploadTarget(tabId, args, scope) {
8605
- const target2 = await this.resolveTarget(tabId, scope, Array.isArray(args.frames) ? args.frames : []);
9511
+ const target2 = await this.locate(tabId, scope, Array.isArray(args.frames) ? args.frames : [], "document");
8606
9512
  let parsed;
8607
9513
  try {
8608
9514
  parsed = parseUploadTarget(args);
@@ -8614,9 +9520,14 @@ class NativeRuntime {
8614
9520
  const frame = await element.ownerFrame();
8615
9521
  if (!frame || frame.isDetached())
8616
9522
  throw uploadRefusal.changed();
9523
+ const input = this.bound(target2.page, frame, tabId, scope, "document");
9524
+ const assertCurrent = () => {
9525
+ target2.assertCurrent();
9526
+ input.assertCurrent();
9527
+ };
8617
9528
  const info = await element.evaluate((el) => ({ file: el instanceof HTMLInputElement && el.type === "file" && !el.webkitdirectory && el.isConnected, multiple: el instanceof HTMLInputElement && el.multiple }));
8618
9529
  try {
8619
- target2.assertCurrent();
9530
+ assertCurrent();
8620
9531
  } catch {
8621
9532
  throw uploadRefusal.changed();
8622
9533
  }
@@ -8625,7 +9536,7 @@ class NativeRuntime {
8625
9536
  const files = Array.isArray(args.fileIds) ? args.fileIds.length : 1;
8626
9537
  if (files > 1 && !info.multiple)
8627
9538
  throw uploadRefusal.single(files);
8628
- return { ...target2, frame, element, release: () => element.dispose() };
9539
+ return { ...input, assertCurrent, element, release: () => element.dispose() };
8629
9540
  } catch (e) {
8630
9541
  await element.dispose();
8631
9542
  throw notDispatchedFault(e);
@@ -8746,7 +9657,7 @@ class NativeRuntime {
8746
9657
  if (tabId)
8747
9658
  this.sessions?.assertTabAvailable(tabId);
8748
9659
  const page = tabId ? this.engine.page(tabId) : undefined;
8749
- const generation = tabId ? this.generations.get(tabId) : undefined;
9660
+ const admittedDocument = tabId ? this.documents.get(tabId) : undefined;
8750
9661
  return (checkDocument = true) => {
8751
9662
  if (this.scopeEpoch(scope) !== epoch || this.connectionEpoch !== connectionEpoch)
8752
9663
  throw new RuntimeFault("scope_rejected", "Scope or connection changed while waiting; submit a fresh authorized request.", true);
@@ -8759,7 +9670,7 @@ class NativeRuntime {
8759
9670
  } catch {
8760
9671
  throw new RuntimeFault("tab_closed", "Select an open tab before submitting a new request.", true);
8761
9672
  }
8762
- if (current2 !== page || checkDocument && this.generations.get(tabId) !== generation)
9673
+ if (current2 !== page || checkDocument && this.documents.get(tabId) !== admittedDocument)
8763
9674
  throw new RuntimeFault("stale_queued_target", "The target document changed while waiting. Observe it again before submitting a new request.", true);
8764
9675
  const owner = this.owners.get(tabId);
8765
9676
  if (owner && scopeKey(owner) !== scopeKey(scope))
@@ -8819,7 +9730,8 @@ class NativeRuntime {
8819
9730
  begin();
8820
9731
  this.revocationEpoch++;
8821
9732
  this.revokeOwnership(tabId);
8822
- this.generations.set(tabId, (this.generations.get(tabId) ?? 0) + 1);
9733
+ this.documents.set(tabId, (this.documents.get(tabId) ?? 0) + 1);
9734
+ this.engine.handHttpAuthToChrome("handed_off", tabId);
8823
9735
  for (const p of this.plugins)
8824
9736
  await p.onHandoff?.(tabId, scope);
8825
9737
  return { released: true, tabId };
@@ -8862,7 +9774,9 @@ class NativeRuntime {
8862
9774
  this.owners.set(tabId, { ...scope });
8863
9775
  };
8864
9776
  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 });
9777
+ const vault = op === "handle_dialog" && typeof args.vaultId === "string" ? this.plugins.find((p) => p.revealHttpAuth) : undefined;
9778
+ const revealHttpAuth = vault ? () => vault.revealHttpAuth(scope, String(args.vaultId), args.names) : undefined;
9779
+ 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
9780
  if (this.disconnected || (this.epochs.get(scopeKey(scope)) ?? 0) !== operationEpoch)
8867
9781
  throw new Error("Scope ended during execution; outcome uncertain");
8868
9782
  const target3 = op === "capabilities" && typeof args.tabId === "string" ? await this.targetCapabilities(args.tabId, scope) : undefined;
@@ -8887,8 +9801,10 @@ class NativeRuntime {
8887
9801
  controller.abort(new Error("Runtime scope revoked"));
8888
9802
  this.revocationEpoch++;
8889
9803
  for (const [id, owner] of this.owners)
8890
- if (scopeKey(owner) === key2)
9804
+ if (scopeKey(owner) === key2) {
8891
9805
  this.revokeOwnership(id);
9806
+ this.engine.handHttpAuthToChrome("session_ended", id);
9807
+ }
8892
9808
  for (const [page, owner] of this.closedOwners)
8893
9809
  if (scopeKey(owner) === key2)
8894
9810
  this.closedOwners.delete(page);
@@ -8898,7 +9814,7 @@ class NativeRuntime {
8898
9814
  }
8899
9815
  async shutdown() {
8900
9816
  await this.disconnect();
8901
- for (const tabId of this.generations.keys())
9817
+ for (const tabId of this.documents.keys())
8902
9818
  for (const p of this.plugins)
8903
9819
  await p.onTabClose?.(tabId);
8904
9820
  await this.hooks;
@@ -8907,6 +9823,7 @@ class NativeRuntime {
8907
9823
  async disconnect() {
8908
9824
  this.disconnected = true;
8909
9825
  this.connectionEpoch++;
9826
+ this.engine.handHttpAuthToChrome("runtime_disconnected");
8910
9827
  for (const controllers of this.controllers.values())
8911
9828
  for (const controller of controllers)
8912
9829
  controller.abort(new Error("Runtime disconnected"));
@@ -8931,6 +9848,158 @@ import path10 from "node:path";
8931
9848
  // cli/src/live/producer.ts
8932
9849
  import WebSocket from "ws";
8933
9850
 
9851
+ // shared/browser-tools.ts
9852
+ var TAKEOVER_TOOL = "browser_takeover";
9853
+ var TAKEOVER_STATUS_TOOL = "browser_takeover_status";
9854
+ var TAKEOVER_RECLAIM_TOOL = "browser_takeover_reclaim";
9855
+ var TAKEOVER_TOOLS = new Set([TAKEOVER_TOOL, TAKEOVER_STATUS_TOOL, TAKEOVER_RECLAIM_TOOL]);
9856
+ var MAX_VIEWPORT_DIMENSION2 = 4096;
9857
+ var observedActions2 = new Set([
9858
+ "navigate",
9859
+ "history",
9860
+ "mouse_click",
9861
+ "hover",
9862
+ "drag",
9863
+ "scroll",
9864
+ "form_input",
9865
+ "keyboard",
9866
+ "keyboard_type",
9867
+ "edit_text",
9868
+ "select_text",
9869
+ "handle_dialog",
9870
+ "webmcp_call"
9871
+ ]);
9872
+ var batchActions2 = new Set([
9873
+ "read_page",
9874
+ "inspect",
9875
+ "wait_for",
9876
+ "mouse_click",
9877
+ "hover",
9878
+ "scroll",
9879
+ "form_input",
9880
+ "keyboard",
9881
+ "keyboard_type",
9882
+ "select_text",
9883
+ "edit_text",
9884
+ "sleep"
9885
+ ]);
9886
+ var screenshotActions = new Set(["mouse_click", "move_mouse", "scroll", "drag"]);
9887
+ var compactForms = new WeakMap;
9888
+ function advertisedAs(canonical, compact) {
9889
+ compactForms.set(canonical, compact);
9890
+ return canonical;
9891
+ }
9892
+ var locatorFields = ["ref", "selector", "role", "name", "text", "label", "placeholder", "testId"];
9893
+ var locatorStrategies = (allowName) => locatorFields.filter((field) => allowName || field !== "name").map((field) => ({
9894
+ type: "object",
9895
+ required: [field],
9896
+ properties: Object.fromEntries(locatorFields.map((key2) => [
9897
+ key2,
9898
+ key2 === field ? { type: "string" } : field === "role" && key2 === "name" ? { type: ["string", "null"] } : { type: "null" }
9899
+ ]))
9900
+ }));
9901
+ var snapshotTarget = {
9902
+ type: "object",
9903
+ additionalProperties: false,
9904
+ 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.",
9905
+ anyOf: locatorStrategies(true),
9906
+ properties: Object.fromEntries([
9907
+ ...locatorFields.map((name) => [name, { type: ["string", "null"], minLength: 1, maxLength: 2000, pattern: "\\S" }]),
9908
+ ["exact", { type: ["boolean", "null"] }]
9909
+ ])
9910
+ };
9911
+ var waitTarget = {
9912
+ ...snapshotTarget,
9913
+ anyOf: locatorStrategies(false),
9914
+ 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."
9915
+ };
9916
+ 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.";
9917
+ var actionTarget = advertisedAs({
9918
+ ...waitTarget,
9919
+ description: actionTargetDescription
9920
+ }, { type: "object", description: actionTargetDescription });
9921
+ var waitText = { type: "string", minLength: 1, maxLength: 2000, pattern: "\\S" };
9922
+ var networkQuietBounds = { type: "integer", minimum: MIN_NETWORK_QUIET_MS, maximum: MAX_NETWORK_QUIET_MS };
9923
+ var ignoreUrlList = { type: "array", minItems: 1, maxItems: MAX_IGNORE_URLS, items: { type: "string", minLength: 1, maxLength: 2000 } };
9924
+ var navigationDescription = "Wait for the main frame to navigate (reloads and same-document navigations too), armed before the input; the result reports navigation.matched.";
9925
+ var navigationExpectation = advertisedAs({
9926
+ type: "object",
9927
+ additionalProperties: false,
9928
+ description: navigationDescription,
9929
+ properties: {
9930
+ url: { type: ["string", "null"], minLength: 1, maxLength: 4000, description: "Expected URL glob (* within a path segment, ** across)." },
9931
+ waitUntil: { type: ["string", "null"], enum: ["commit", "domcontentloaded", "load", null], description: "Default domcontentloaded." },
9932
+ timeoutMs: { type: ["integer", "null"], minimum: 500, maximum: 25000, description: "Default 10000." }
9933
+ }
9934
+ }, {
9935
+ type: "object",
9936
+ description: navigationDescription,
9937
+ properties: {
9938
+ url: { type: "string", description: "Expected URL glob (* within a path segment, ** across)." },
9939
+ waitUntil: { type: "string", enum: ["commit", "domcontentloaded", "load"], description: "Default domcontentloaded." },
9940
+ timeoutMs: { type: "integer", minimum: 500, maximum: 25000, description: "Default 10000." }
9941
+ }
9942
+ });
9943
+ var observeDescription = 'Read the page after the action: {} or {mode: "summary"} for the changed lines, {mode: "full"} for all of it.';
9944
+ var observe = advertisedAs({
9945
+ anyOf: [
9946
+ { type: "boolean", enum: [false] },
9947
+ { type: "object", additionalProperties: false, properties: { mode: { type: ["string", "null"], enum: ["summary", "full", null] }, maxChars: { type: ["integer", "null"], minimum: 1000, maximum: 30000 } } }
9948
+ ],
9949
+ description: observeDescription
9950
+ }, {
9951
+ anyOf: [
9952
+ { type: "boolean", enum: [false] },
9953
+ { type: "object", properties: { mode: { type: "string", enum: ["summary", "full"] }, maxChars: { type: "integer", minimum: 1000, maximum: 30000 } } }
9954
+ ],
9955
+ description: observeDescription
9956
+ });
9957
+ 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.`;
9958
+ var waitStates = ["visible", "hidden", "attached", "detached", "enabled", "disabled"];
9959
+ var expect = advertisedAs({
9960
+ type: "object",
9961
+ additionalProperties: false,
9962
+ properties: {
9963
+ text: { ...waitText, type: ["string", "null"] },
9964
+ textGone: { ...waitText, type: ["string", "null"] },
9965
+ exact: { type: ["boolean", "null"] },
9966
+ target: waitTarget,
9967
+ url: { type: ["string", "null"] },
9968
+ networkQuietMs: { ...networkQuietBounds, type: ["integer", "null"] },
9969
+ ignoreUrls: { ...ignoreUrlList, type: ["array", "null"] },
9970
+ state: { type: ["string", "null"], enum: [...waitStates, null] },
9971
+ timeoutMs: { type: ["integer", "null"], minimum: MIN_WAIT_MS }
9972
+ },
9973
+ description: expectDescription
9974
+ }, {
9975
+ type: "object",
9976
+ properties: {
9977
+ text: { type: "string" },
9978
+ textGone: { type: "string" },
9979
+ exact: { type: "boolean" },
9980
+ target: { type: "object", description: "One locator, as browser_wait_for's target." },
9981
+ url: { type: "string" },
9982
+ networkQuietMs: { type: "integer", minimum: MIN_NETWORK_QUIET_MS, maximum: MAX_NETWORK_QUIET_MS },
9983
+ ignoreUrls: { type: "array", items: { type: "string" } },
9984
+ state: { type: "string", enum: waitStates },
9985
+ timeoutMs: { type: "integer", minimum: MIN_WAIT_MS }
9986
+ },
9987
+ description: expectDescription
9988
+ });
9989
+ var vaultName = { type: "string", pattern: "^[A-Za-z_][A-Za-z0-9_]*$", maxLength: 128 };
9990
+ var httpAuthNamesDescription = "HTTP sign-in: {username, password}, the vault names holding them, never the values.";
9991
+ var httpAuthNames = advertisedAs({
9992
+ type: "object",
9993
+ additionalProperties: false,
9994
+ required: ["username", "password"],
9995
+ properties: { username: vaultName, password: vaultName },
9996
+ description: httpAuthNamesDescription
9997
+ }, { type: "object", properties: { username: { type: "string" }, password: { type: "string" } }, description: httpAuthNamesDescription });
9998
+ var advertisedLocatorFields = Object.fromEntries([
9999
+ ...locatorFields.map((key2) => [key2, { type: ["string", "null"] }]),
10000
+ ["exact", { type: ["boolean", "null"] }]
10001
+ ]);
10002
+
8934
10003
  // backend/live-wire.ts
8935
10004
  var isRuntimeTabId = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
8936
10005
  var MAX_LIVE_FRAME_BYTES = 1500000;
@@ -8977,6 +10046,8 @@ var KEY_CODE = /^[A-Za-z0-9]{0,32}$/;
8977
10046
  var CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/;
8978
10047
  var LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
8979
10048
  var cleanText = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max && !CONTROL.test(value) && !LONE_SURROGATE.test(value);
10049
+ var ANY_CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
10050
+ var credential2 = (value, max, allowEmpty) => typeof value === "string" && (allowEmpty || value.length > 0) && value.length <= max && !ANY_CONTROL.test(value) && !LONE_SURROGATE.test(value);
8980
10051
  var keyValue = (value) => typeof value === "string" && (NAMED_KEY.test(value) || value.length <= 4 && cleanText(value, 4) && !/[\t\n\r]/.test(value));
8981
10052
  var button = (value) => value === "left" || value === "middle" || value === "right";
8982
10053
  function sanitizeLiveInput(value) {
@@ -9004,6 +10075,11 @@ function sanitizeLiveInput(value) {
9004
10075
  case "dialog":
9005
10076
  if (typeof e.accept !== "boolean")
9006
10077
  return null;
10078
+ if (e.username !== undefined || e.password !== undefined) {
10079
+ if (!e.accept || e.text !== undefined || !credential2(e.username, MAX_HTTP_AUTH_USERNAME, false) || !credential2(e.password, MAX_HTTP_AUTH_PASSWORD, true))
10080
+ return null;
10081
+ return { kind: "dialog", accept: true, username: e.username, password: e.password };
10082
+ }
9007
10083
  if (e.text === undefined)
9008
10084
  return { kind: "dialog", accept: e.accept };
9009
10085
  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 +10091,17 @@ function sanitizeLiveInput(value) {
9015
10091
  return null;
9016
10092
  }
9017
10093
  }
9018
- var DIALOG_TYPES = new Set(["alert", "confirm", "prompt", "beforeunload", "passkey"]);
10094
+ var DIALOG_TYPES = new Set(["alert", "confirm", "prompt", "beforeunload", "passkey", "http_auth"]);
9019
10095
  var MAX_LIVE_DIALOG_MESSAGE = 500;
10096
+ function sanitizeTakeoverViewport(value) {
10097
+ if (value === null)
10098
+ return null;
10099
+ if (!value || typeof value !== "object" || Array.isArray(value))
10100
+ return;
10101
+ const { width, height } = value;
10102
+ const dimension = (n) => typeof n === "number" && Number.isInteger(n) && n >= 1 && n <= MAX_VIEWPORT_DIMENSION2;
10103
+ return dimension(width) && dimension(height) ? { width, height } : undefined;
10104
+ }
9020
10105
 
9021
10106
  // cli/src/live/wire.ts
9022
10107
  function mediaURL(server) {
@@ -9079,7 +10164,7 @@ class CaptureTimeout extends Error {
9079
10164
  this.stage = stage;
9080
10165
  }
9081
10166
  }
9082
- async function bounded2(stage, operation) {
10167
+ async function bounded3(stage, operation) {
9083
10168
  let timer2;
9084
10169
  try {
9085
10170
  return await Promise.race([operation, new Promise((_, reject) => {
@@ -9214,8 +10299,8 @@ class NativeLiveProducer {
9214
10299
  const cdp = this.cdp;
9215
10300
  this.cdp = undefined;
9216
10301
  if (cdp) {
9217
- await bounded2("stop_screencast", cdp.send("Page.stopScreencast")).catch(() => {});
9218
- await bounded2("detach", cdp.detach()).catch(() => {});
10302
+ await bounded3("stop_screencast", cdp.send("Page.stopScreencast")).catch(() => {});
10303
+ await bounded3("detach", cdp.detach()).catch(() => {});
9219
10304
  }
9220
10305
  }
9221
10306
  async reconcile(generation) {
@@ -9244,7 +10329,7 @@ class NativeLiveProducer {
9244
10329
  const initialNav = this.navSeq;
9245
10330
  let authorized = false;
9246
10331
  try {
9247
- authorized = await bounded2("authorize", this.options.authorizePage(page));
10332
+ authorized = await bounded3("authorize", this.options.authorizePage(page));
9248
10333
  } catch (error) {
9249
10334
  await this.teardown();
9250
10335
  if (generation === this.generation)
@@ -9312,12 +10397,12 @@ class NativeLiveProducer {
9312
10397
  let abandoned = false;
9313
10398
  const attaching = page.context().newCDPSession(page).then((session) => {
9314
10399
  if (abandoned)
9315
- bounded2("detach", session.detach()).catch(() => {});
10400
+ bounded3("detach", session.detach()).catch(() => {});
9316
10401
  return session;
9317
10402
  });
9318
10403
  let cdp;
9319
10404
  try {
9320
- cdp = await bounded2("attach", attaching);
10405
+ cdp = await bounded3("attach", attaching);
9321
10406
  } catch (error) {
9322
10407
  abandoned = true;
9323
10408
  throw error;
@@ -9347,7 +10432,7 @@ class NativeLiveProducer {
9347
10432
  checkingFrame = true;
9348
10433
  (async () => {
9349
10434
  try {
9350
- const allowed = await bounded2("frame_authorize", this.options.authorizePage(page));
10435
+ const allowed = await bounded3("frame_authorize", this.options.authorizePage(page));
9351
10436
  if (generation !== this.generation || nav !== this.navSeq || this.closed || !this.enabled || !this.active || this.socket !== ws || ws.readyState !== WebSocket.OPEN)
9352
10437
  return;
9353
10438
  if (!allowed || this.options.getPage(tab) !== page) {
@@ -9380,7 +10465,7 @@ class NativeLiveProducer {
9380
10465
  forward(event, this.navSeq);
9381
10466
  });
9382
10467
  const startNav = this.navSeq;
9383
- const stillAllowed = await bounded2("authorize", this.options.authorizePage(page));
10468
+ const stillAllowed = await bounded3("authorize", this.options.authorizePage(page));
9384
10469
  if (generation !== this.generation) {
9385
10470
  await this.teardown();
9386
10471
  return;
@@ -9395,7 +10480,7 @@ class NativeLiveProducer {
9395
10480
  this.state("blocked", "page_unavailable");
9396
10481
  return;
9397
10482
  }
9398
- await bounded2("start_screencast", cdp.send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: 1600, maxHeight: 1000, everyNthFrame: 1 }));
10483
+ await bounded3("start_screencast", cdp.send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: 1600, maxHeight: 1000, everyNthFrame: 1 }));
9399
10484
  if (generation !== this.generation) {
9400
10485
  await this.teardown();
9401
10486
  return;
@@ -9424,9 +10509,9 @@ class NativeLiveProducer {
9424
10509
  var MAX_QUEUE = 128;
9425
10510
  var STEP_TIMEOUT_MS = 3000;
9426
10511
  var SHOW_INTERVAL_MS = 1000;
9427
- var DIALOG_TYPES2 = new Set(["alert", "confirm", "prompt", "beforeunload", "passkey"]);
10512
+ var DIALOG_TYPES2 = new Set(["alert", "confirm", "prompt", "beforeunload", "passkey", "http_auth"]);
9428
10513
  var MODIFIERS = Object.entries(LIVE_MODIFIERS);
9429
- async function bounded3(work, ms) {
10514
+ async function bounded4(work, ms) {
9430
10515
  let timer2;
9431
10516
  await Promise.race([work.catch(() => {}), new Promise((resolve2) => {
9432
10517
  timer2 = setTimeout(resolve2, ms);
@@ -9440,13 +10525,14 @@ class TakeoverInput {
9440
10525
  queue = [];
9441
10526
  pumping;
9442
10527
  releases = new Map;
10528
+ layouts = new Map;
9443
10529
  constructor(options) {
9444
10530
  this.options = options;
9445
10531
  }
9446
10532
  get currentTab() {
9447
10533
  return this.group?.session?.tabId;
9448
10534
  }
9449
- activate(root) {
10535
+ activate(root, viewport) {
9450
10536
  if (!isRuntimeTabId(root) || this.group?.root === root)
9451
10537
  return;
9452
10538
  this.deactivate();
@@ -9455,16 +10541,26 @@ class TakeoverInput {
9455
10541
  this.lost(root);
9456
10542
  return;
9457
10543
  }
9458
- const group = { root, tabs: [root], ended: false, cleanup: [] };
10544
+ const group = { root, tabs: [root], ended: false, cleanup: [], fitted: new Set, ...viewport ? { viewport: { ...viewport } } : {} };
9459
10545
  this.group = group;
9460
10546
  this.join(group, root, page);
9461
10547
  this.focus(group, root, page);
10548
+ if (group.viewport)
10549
+ this.layout(group, root);
9462
10550
  }
9463
10551
  deactivate() {
9464
10552
  const group = this.group;
9465
10553
  if (group)
9466
10554
  this.end(group);
9467
10555
  }
10556
+ fit(viewport) {
10557
+ const group = this.group;
10558
+ if (!group || group.ended || viewport?.width === group.viewport?.width && viewport?.height === group.viewport?.height)
10559
+ return;
10560
+ group.viewport = viewport && { ...viewport };
10561
+ for (const tabId of viewport ? group.tabs : [...group.fitted])
10562
+ this.layout(group, tabId);
10563
+ }
9468
10564
  input(frame) {
9469
10565
  const session = this.group?.session;
9470
10566
  if (!session || frame.runtimeTabId !== session.tabId)
@@ -9487,15 +10583,13 @@ class TakeoverInput {
9487
10583
  this.push({ session, event });
9488
10584
  }
9489
10585
  async settled(tabId) {
9490
- const release = this.releases.get(tabId);
9491
- if (release)
9492
- await bounded3(release, STEP_TIMEOUT_MS);
10586
+ const release = this.releases.get(tabId), layout = this.layouts.get(tabId);
10587
+ await Promise.all([release && bounded4(release, STEP_TIMEOUT_MS), layout && bounded4(layout, STEP_TIMEOUT_MS)]);
9493
10588
  }
9494
10589
  async stop() {
9495
10590
  this.deactivate();
9496
10591
  const pumping = this.pumping;
9497
- if (pumping)
9498
- await bounded3(pumping, STEP_TIMEOUT_MS);
10592
+ await Promise.all([pumping && bounded4(pumping, STEP_TIMEOUT_MS), ...[...this.layouts.values()].map((layout) => bounded4(layout, STEP_TIMEOUT_MS))]);
9499
10593
  }
9500
10594
  join(group, tabId, page) {
9501
10595
  const onClose = () => this.left(group, tabId);
@@ -9521,10 +10615,13 @@ class TakeoverInput {
9521
10615
  group.tabs.push(id);
9522
10616
  this.join(group, id, popup);
9523
10617
  this.focus(group, id, popup);
10618
+ if (group.viewport)
10619
+ this.layout(group, id);
9524
10620
  }
9525
10621
  left(group, tabId) {
9526
10622
  if (group.ended || this.group !== group)
9527
10623
  return;
10624
+ group.fitted.delete(tabId);
9528
10625
  if (tabId === group.root) {
9529
10626
  this.end(group);
9530
10627
  this.lost(tabId);
@@ -9602,6 +10699,26 @@ class TakeoverInput {
9602
10699
  }
9603
10700
  if (group.session && !group.session.ended)
9604
10701
  this.close(group.session);
10702
+ for (const tabId of [...group.fitted])
10703
+ this.layout(group, tabId);
10704
+ }
10705
+ layout(group, tabId) {
10706
+ const setViewport = this.options.setViewport;
10707
+ if (!setViewport)
10708
+ return;
10709
+ const viewport = group.ended ? undefined : group.viewport;
10710
+ if (viewport)
10711
+ group.fitted.add(tabId);
10712
+ else if (!group.fitted.delete(tabId))
10713
+ return;
10714
+ const size = viewport ? { ...viewport } : null;
10715
+ const before = [this.layouts.get(tabId), this.options.agentActivity(tabId)];
10716
+ const done = Promise.all(before).then(() => setViewport(tabId, size)).catch(() => {});
10717
+ this.layouts.set(tabId, done);
10718
+ done.then(() => {
10719
+ if (this.layouts.get(tabId) === done)
10720
+ this.layouts.delete(tabId);
10721
+ });
9605
10722
  }
9606
10723
  report(group) {
9607
10724
  const session = group.session;
@@ -9618,8 +10735,10 @@ class TakeoverInput {
9618
10735
  let shown = null;
9619
10736
  if (dialog && type === "passkey")
9620
10737
  shown = { type, message: "", request: dialog.request === "create" ? "create" : "get", ...dialog.origin ? { origin: dialog.origin } : {} };
10738
+ else if (dialog && type === "http_auth")
10739
+ 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
10740
  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) } : {} };
10741
+ shown = { type, message: dialog.message.slice(0, MAX_LIVE_DIALOG_MESSAGE), ...type === "prompt" ? { defaultValue: (dialog.defaultValue ?? "").slice(0, MAX_LIVE_DIALOG_TEXT) } : {} };
9623
10742
  this.options.sendEvent({ type: "event", event: "live_dialog", runtimeTabId: tabId, dialog: shown });
9624
10743
  }
9625
10744
  push(item) {
@@ -9639,7 +10758,7 @@ class TakeoverInput {
9639
10758
  if (session.ended)
9640
10759
  continue;
9641
10760
  }
9642
- await bounded3(this.dispatch(session, event), STEP_TIMEOUT_MS);
10761
+ await bounded4(this.dispatch(session, event), STEP_TIMEOUT_MS);
9643
10762
  } finally {
9644
10763
  item2.done?.();
9645
10764
  }
@@ -9672,7 +10791,7 @@ class TakeoverInput {
9672
10791
  await this.answerDialog(events, event);
9673
10792
  return;
9674
10793
  }
9675
- if (events?.activeDialog())
10794
+ if (events?.activeDialog() && (events.javascriptDialogOpen() || event.kind !== "navigate"))
9676
10795
  return;
9677
10796
  if (event.kind === "show") {
9678
10797
  if (events?.passkeyPrompt())
@@ -9789,6 +10908,11 @@ class TakeoverInput {
9789
10908
  if (!events)
9790
10909
  return;
9791
10910
  const dialog = events.activeDialog(), details = events.dialogDetails();
10911
+ if (dialog && details?.type === "http_auth") {
10912
+ const typed = event.accept && event.username !== undefined && event.password !== undefined ? { username: event.username, password: event.password } : undefined;
10913
+ await events.handleDialog({ dialogId: dialog.dialogId, decision: event.accept ? "accept" : "dismiss" }, "viewer", { typed });
10914
+ return;
10915
+ }
9792
10916
  if (dialog && details) {
9793
10917
  const prompt = details.type === "prompt" && event.accept && event.text !== undefined;
9794
10918
  await events.handleDialog({ dialogId: dialog.dialogId, decision: event.accept ? "accept" : "dismiss", ...prompt ? { promptText: event.text } : {} }, "viewer");
@@ -9994,18 +11118,23 @@ class Relay {
9994
11118
  if (socket?.readyState === WebSocket2.OPEN)
9995
11119
  socket.send(JSON.stringify(event));
9996
11120
  },
9997
- hostMac: process.platform === "darwin"
11121
+ hostMac: process.platform === "darwin",
11122
+ setViewport: (id, viewport) => this.runtime.engine.takeoverViewport(id, viewport)
9998
11123
  });
9999
11124
  }
10000
- setControl(tab) {
11125
+ setControl(tab, viewport) {
10001
11126
  if (tab !== undefined && (!this.liveEnabled || !isRuntimeTabId(tab)))
10002
11127
  tab = undefined;
10003
- if (tab === this.control)
11128
+ const fit = tab ? sanitizeTakeoverViewport(viewport) ?? undefined : undefined;
11129
+ if (tab === this.control) {
11130
+ if (tab)
11131
+ this.takeover.fit(fit);
10004
11132
  return;
11133
+ }
10005
11134
  this.control = tab;
10006
11135
  if (tab) {
10007
11136
  this.controlled([tab], tab);
10008
- this.takeover.activate(tab);
11137
+ this.takeover.activate(tab, fit);
10009
11138
  } else {
10010
11139
  this.takeover.deactivate();
10011
11140
  this.controlled([], undefined);
@@ -10057,7 +11186,7 @@ class Relay {
10057
11186
  if (this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
10058
11187
  return;
10059
11188
  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 } } }));
11189
+ 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
11190
  });
10062
11191
  socket.on("message", (bytes, binary) => {
10063
11192
  if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
@@ -10115,7 +11244,7 @@ class Relay {
10115
11244
  }
10116
11245
  } else if (message.type === "control") {
10117
11246
  if (socket === this.socket)
10118
- this.setControl(message.active === true ? message.runtimeTabId : undefined);
11247
+ this.setControl(message.active === true ? message.runtimeTabId : undefined, message.active === true ? message.viewport : undefined);
10119
11248
  } else if (message.type === "input") {
10120
11249
  if (socket === this.socket && this.control)
10121
11250
  this.takeover.input(message);
@@ -10519,7 +11648,7 @@ class SecretVault {
10519
11648
  }
10520
11649
  if (!Object.keys(clean).length || Object.keys(clean).length > LIMITS.count || total + 1024 > LIMITS.secret)
10521
11650
  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 };
11651
+ 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
11652
  this.entries.set(entry.id, entry);
10524
11653
  return this.metadata(entry);
10525
11654
  } catch {
@@ -10544,11 +11673,11 @@ class SecretVault {
10544
11673
  const e = this.entries.get(id);
10545
11674
  if (!e || !sameScope(e.scope, scope) || !names.length || new Set(names).size !== names.length)
10546
11675
  throw new Error("Unknown secret selection");
10547
- const target2 = await this.access.resolveTarget(e.tabId, scope);
11676
+ const target2 = await this.access.resolveDocument(e.tabId, scope, e.document);
10548
11677
  target2.assertCurrent();
10549
11678
  if (epoch !== this.epoch || this.entries.get(id) !== e || e.expiresAt <= Date.now())
10550
11679
  throw new Error("Secret export invalidated");
10551
- if (target2.generation !== e.generation || new URL(target2.frame.url()).origin !== e.origin)
11680
+ if (new URL(target2.frame.url()).origin !== e.origin)
10552
11681
  throw new Error("Stale secret document");
10553
11682
  const selected = Object.create(null);
10554
11683
  for (const name of names) {
@@ -10556,14 +11685,29 @@ class SecretVault {
10556
11685
  throw new Error("Unknown secret selection");
10557
11686
  selected[name] = e.values[name];
10558
11687
  }
10559
- return { bytes: Buffer.from(serializeSecrets(selected, format)), tabId: e.tabId, generation: e.generation, assertCurrent: () => {
11688
+ return { bytes: Buffer.from(serializeSecrets(selected, format)), tabId: e.tabId, document: e.document, assertCurrent: () => {
10560
11689
  target2.assertCurrent();
10561
11690
  if (epoch !== this.epoch || this.entries.get(id) !== e || e.expiresAt <= Date.now())
10562
11691
  throw new Error("Secret export invalidated");
10563
11692
  } };
10564
11693
  }
10565
- revoke(predicate) {
10566
- this.epoch++;
11694
+ async reveal(scope, id, names) {
11695
+ this.sweep();
11696
+ const epoch = this.epoch;
11697
+ const e = this.entries.get(id);
11698
+ if (!e || !sameScope(e.scope, scope) || !Object.hasOwn(e.values, names.username) || !Object.hasOwn(e.values, names.password))
11699
+ throw new Error("Unknown secret selection");
11700
+ const target2 = await this.access.resolveDocument(e.tabId, scope, e.document);
11701
+ target2.assertCurrent();
11702
+ if (epoch !== this.epoch || this.entries.get(id) !== e || e.expiresAt <= Date.now())
11703
+ throw new Error("Secret selection invalidated");
11704
+ if (new URL(target2.frame.url()).origin !== e.origin)
11705
+ throw new Error("Stale secret document");
11706
+ return { username: e.values[names.username], password: e.values[names.password] };
11707
+ }
11708
+ revoke(predicate, invalidate = true) {
11709
+ if (invalidate)
11710
+ this.epoch++;
10567
11711
  for (const [id, e] of this.entries)
10568
11712
  if (predicate(e))
10569
11713
  this.entries.delete(id);
@@ -10932,8 +12076,8 @@ async function createDataPlugin(access, options) {
10932
12076
  r.removal = undefined;
10933
12077
  }
10934
12078
  }
10935
- async function revoke(predicate) {
10936
- vault.revoke(predicate);
12079
+ async function revoke(predicate, invalidate = true) {
12080
+ vault.revoke(predicate, invalidate);
10937
12081
  await Promise.all([...resources.values()].filter(predicate).map(remove));
10938
12082
  }
10939
12083
  async function transfer(r, g) {
@@ -11018,7 +12162,7 @@ async function createDataPlugin(access, options) {
11018
12162
  return true;
11019
12163
  }
11020
12164
  return false;
11021
- });
12165
+ }, false);
11022
12166
  for (const [id, t] of terminal)
11023
12167
  if (t.until < Date.now())
11024
12168
  terminal.delete(id);
@@ -11103,7 +12247,7 @@ async function createDataPlugin(access, options) {
11103
12247
  return {};
11104
12248
  return { claim: (guid) => spool.claim(guid, download), release: () => spool.release(download), settlement: (guid) => spool.settlement(guid), isSpoolPath: (path11, guid) => spool.isSpoolPath(path11, guid) };
11105
12249
  }
11106
- async function admit(download, name, scope, tabId, generation, downloadId, hooks, directory = downloadDirectory) {
12250
+ async function admit(download, name, scope, tabId, downloadId, hooks, directory = downloadDirectory) {
11107
12251
  const shared = !scope, owner = scope ?? USER_SCOPE;
11108
12252
  let r;
11109
12253
  try {
@@ -11113,7 +12257,6 @@ async function createDataPlugin(access, options) {
11113
12257
  resources.set(r.id, r);
11114
12258
  r.expiresAt = Date.now() + DOWNLOAD_DEADLINE_MS;
11115
12259
  r.tabId = tabId;
11116
- r.generation = generation;
11117
12260
  const resource = r;
11118
12261
  r.source = { download, directory, hooks: { ...hooks, reserve: (size) => reserveSource(resource, size) } };
11119
12262
  await startCapture(r);
@@ -11157,7 +12300,7 @@ async function createDataPlugin(access, options) {
11157
12300
  await unlink3(file).catch(() => {});
11158
12301
  }
11159
12302
  };
11160
- await admit(handle, entry.suggestedFilename, undefined, undefined, 0, randomUUID8(), {
12303
+ await admit(handle, entry.suggestedFilename, undefined, undefined, randomUUID8(), {
11161
12304
  claim: () => true,
11162
12305
  settlement: (guid) => spool.settlement(guid),
11163
12306
  isSpoolPath: (path11, guid) => spool.isSpoolPath(path11, guid)
@@ -11247,7 +12390,7 @@ async function createDataPlugin(access, options) {
11247
12390
  for (const r of files) {
11248
12391
  r.state = "attached";
11249
12392
  r.tabId = target2.tabId;
11250
- r.generation = target2.generation;
12393
+ r.document = target2.document;
11251
12394
  }
11252
12395
  try {
11253
12396
  await target2.element.setInputFiles(files.map((r) => r.path));
@@ -11286,17 +12429,22 @@ async function createDataPlugin(access, options) {
11286
12429
  r.bytes = snapshot.bytes;
11287
12430
  r.vaultId = String(args.vaultId);
11288
12431
  r.tabId = snapshot.tabId;
11289
- r.generation = snapshot.generation;
12432
+ r.document = snapshot.document;
11290
12433
  return meta(r);
11291
12434
  }
11292
12435
  throw new Error("Unsupported data operation");
11293
12436
  },
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);
12437
+ async onDownload(download, tabId, owner, downloadId = randomUUID8(), spool) {
12438
+ return admit(download, download.suggestedFilename(), owner.kind === "session" ? owner.scope : undefined, tabId, downloadId, spoolHooks(download, spool ?? guard), spool?.directory ?? downloadDirectory);
11296
12439
  },
11297
12440
  observeDownload(download, spool) {
11298
12441
  (spool ?? guard)?.observe(download);
11299
12442
  },
12443
+ async revealHttpAuth(scope, vaultId, names) {
12444
+ if (stopped)
12445
+ throw new Error("Data runtime disconnected");
12446
+ return vault.reveal(scope, vaultId, names);
12447
+ },
11300
12448
  async discardDownload(download, spool) {
11301
12449
  download.cancel().catch(() => {});
11302
12450
  await cleanupDownload({ download, directory: spool?.directory ?? downloadDirectory, hooks: spoolHooks(download, spool ?? guard) });
@@ -11304,8 +12452,8 @@ async function createDataPlugin(access, options) {
11304
12452
  onDownloadSpool(spool) {
11305
12453
  return follow(spool);
11306
12454
  },
11307
- async onNavigation(tabId, generation) {
11308
- await revoke((r) => r.purpose !== "download" && r.tabId === tabId && r.generation !== generation);
12455
+ async onNavigation(tabId) {
12456
+ await revoke((r) => r.purpose !== "download" && r.tabId === tabId && (r.document === undefined || !access.documentCurrent(tabId, r.document)), false);
11309
12457
  },
11310
12458
  async onTabClose(tabId) {
11311
12459
  await revoke((r) => r.purpose !== "download" && r.tabId === tabId);