@mind-harness/mh-browser 0.2.6 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -7,9 +7,9 @@ import { assertSupportedJsonSchema, defineTool, validateJsonSchemaValue } from "
7
7
  import { createHash, randomUUID } from "node:crypto";
8
8
  import { parse } from "yaml";
9
9
  import { accessSync, constants, readFileSync, realpathSync, statSync } from "node:fs";
10
- import { lstat, mkdir, open, readFile, readlink, realpath, unlink, writeFile } from "node:fs/promises";
10
+ import { access, lstat, mkdir, open, readFile, readdir, readlink, realpath, rename, unlink, writeFile } from "node:fs/promises";
11
11
  import { z as z$1 } from "zod";
12
- import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
12
+ import { Service } from "@deepseek-ai/cordis";
13
13
  import { chromium } from "playwright";
14
14
  import { execFile } from "node:child_process";
15
15
  import { homedir } from "node:os";
@@ -19,10 +19,11 @@ import { UserQuestionError } from "@deepseek-ai/dsh-user-questions";
19
19
  const browserConfig = z.object({
20
20
  presence: z.object({ maxBytes: z.number().step(1).min(1).required().description("Most bytes of page text one presence reminder may carry.") }).required().description("Pages kept in context across steps."),
21
21
  browser: z.union([
22
+ "auto",
22
23
  "chrome",
23
24
  "msedge",
24
25
  "chromium"
25
- ]).default("chrome").volatile().description("Which browser to drive. chromium is the one Playwright downloads. A new value restarts the browser once it is idle."),
26
+ ]).default("auto").volatile().description("Which browser to drive. auto keeps the one that launched last, or Chrome and then Edge. chromium is the one Playwright downloads. A new value restarts the browser once it is idle."),
26
27
  executablePath: z.string().volatile().description("Absolute path of the browser executable. `~` is expanded. Leave empty to locate one. A new value restarts the browser once it is idle."),
27
28
  profileDir: z.string().description("Browser profile directory, kept between runs. Defaults to mh/profiles/<dsh profile>/browser under the dsh home."),
28
29
  headless: z.boolean().default(false).description("Run the browser without a window.")
@@ -35,16 +36,22 @@ const browserConfig = z.object({
35
36
  function defaultProfileDir(profile, home = resolveDshHome()) {
36
37
  return profile === void 0 ? join(home, "mh", "browser") : join(home, "mh", "profiles", profile.name, "browser");
37
38
  }
39
+ /** One subdirectory of the default profile root per browser, so logins do not cross browsers. */
40
+ function profileDirFor(root, browser) {
41
+ return join(root, browser);
42
+ }
38
43
  //#endregion
39
44
  //#region lib/types/types.js
40
45
  var MhBrowserError = class extends Error {
41
46
  code;
42
47
  page;
43
- constructor(code, message, page) {
48
+ notFound;
49
+ constructor(code, message, page, notFound) {
44
50
  super(message);
45
51
  this.name = "MhBrowserError";
46
52
  this.code = code;
47
53
  if (page !== void 0) this.page = page;
54
+ if (notFound !== void 0) this.notFound = notFound;
48
55
  }
49
56
  };
50
57
  /** Owner of the person's own window. It belongs to no Session. */
@@ -557,13 +564,13 @@ function pageAttrs(view, screenshot) {
557
564
  screenshot === void 0 ? "" : attr$1("screenshot", screenshot)
558
565
  ].join("");
559
566
  }
560
- const BODY_LIMIT = 2e5;
567
+ const BODY_LIMIT$1 = 2e5;
561
568
  function pageBody(view) {
562
569
  const representation = view.representation;
563
570
  if (view.mediaType === void 0 || representation.kind !== "snapshot") return representation.text;
564
571
  if (view.body !== void 0) {
565
- if (view.body.length <= BODY_LIMIT) return view.body;
566
- return `${view.body.slice(0, BODY_LIMIT)}\nCut at ${String(BODY_LIMIT)} characters; use browser_download to save the whole file into the workspace.`;
572
+ if (view.body.length <= BODY_LIMIT$1) return view.body;
573
+ return `${view.body.slice(0, BODY_LIMIT$1)}\nCut at ${String(BODY_LIMIT$1)} characters; use browser_download to save the whole file into the workspace.`;
567
574
  }
568
575
  if (view.status !== void 0) return `The site answered HTTP ${String(view.status)}; the ${view.mediaType} body is not shown.`;
569
576
  return "Not an HTML page; use browser_download to save it into the workspace.";
@@ -2370,6 +2377,302 @@ function plainObject(keys) {
2370
2377
  return z$1.custom((value) => value !== null && typeof value === "object" && keys.every((key) => key in value));
2371
2378
  }
2372
2379
  //#endregion
2380
+ //#region lib/types/routes.js
2381
+ /** Requests larger than this are refused before the service method runs. */
2382
+ const BODY_LIMIT = 65536;
2383
+ const PREFIX = "/mh-browser/api";
2384
+ var RouteFailure = class extends Error {
2385
+ status;
2386
+ body;
2387
+ constructor(status, body) {
2388
+ super(body.message);
2389
+ this.name = "RouteFailure";
2390
+ this.status = status;
2391
+ this.body = body;
2392
+ }
2393
+ };
2394
+ function method(spec) {
2395
+ return {
2396
+ verb: spec.verb,
2397
+ input: spec.input,
2398
+ run: (input, signal) => spec.run(input, signal)
2399
+ };
2400
+ }
2401
+ const locateInput = z$1.object({ browser: z$1.enum([
2402
+ "auto",
2403
+ "chrome",
2404
+ "msedge",
2405
+ "chromium"
2406
+ ]) }).strict();
2407
+ const revealInput = z$1.object({ sessionId: z$1.string() }).strict();
2408
+ /**
2409
+ * Routes for the browser client. A composition without `webServer` never
2410
+ * starts this plugin; the browser tools do not depend on it.
2411
+ */
2412
+ const browserRoutesPlugin = {
2413
+ name: "mh-browser-routes",
2414
+ inject: [
2415
+ "mhBrowser",
2416
+ "webServer",
2417
+ "connection"
2418
+ ],
2419
+ apply(inner) {
2420
+ registerBrowserRoutes(inner);
2421
+ }
2422
+ };
2423
+ function registerBrowserRoutes(ctx) {
2424
+ registerApiRoutes(ctx, {
2425
+ prefix: PREFIX,
2426
+ packageName: "mh-browser",
2427
+ methods: {
2428
+ "locate-for": method({
2429
+ verb: "POST",
2430
+ input: locateInput,
2431
+ run: (input, signal) => ctx.mhBrowser.locateFor(input.browser, signal)
2432
+ }),
2433
+ "reveal-handover": method({
2434
+ verb: "POST",
2435
+ input: revealInput,
2436
+ run: (input, signal) => ctx.mhBrowser.revealHandover(input.sessionId, signal)
2437
+ })
2438
+ },
2439
+ mapError: browserFailure
2440
+ });
2441
+ }
2442
+ function registerApiRoutes(host, routes) {
2443
+ host.effect(() => host.webServer.register({
2444
+ kind: "prefix",
2445
+ path: routes.prefix,
2446
+ handler: (req, res) => handle(req, res, host, routes)
2447
+ }));
2448
+ }
2449
+ async function handle(req, res, host, routes) {
2450
+ const name = routes.packageName;
2451
+ try {
2452
+ const admission = host.connection.admit({ headers: req.headers });
2453
+ if ("rejection" in admission) {
2454
+ const status = admission.rejection;
2455
+ writeJson(res, status, fail(name, status === 401 ? "unadmitted" : "forbidden", status === 401 ? "sign in required" : "forbidden"), name);
2456
+ return;
2457
+ }
2458
+ const found = methodOf(routes, segmentOf(req.url, routes.prefix));
2459
+ if (found === void 0) {
2460
+ writeJson(res, 404, fail(name, "not-found", "no such route"), name);
2461
+ return;
2462
+ }
2463
+ if (req.method !== found.verb) {
2464
+ writeJson(res, 405, fail(name, "method-not-allowed", "method not allowed"), name, { allow: found.verb });
2465
+ return;
2466
+ }
2467
+ const controller = new AbortController();
2468
+ const onClose = () => {
2469
+ if (!res.writableEnded) controller.abort();
2470
+ };
2471
+ res.on("close", onClose);
2472
+ if (req.destroyed || res.destroyed) controller.abort();
2473
+ try {
2474
+ if (signalAborted(controller, res, name)) return;
2475
+ const input = found.verb === "GET" ? queryInput(req.url) : await readJson(req, name);
2476
+ if (signalAborted(controller, res, name)) return;
2477
+ const parsed = found.input.safeParse(input);
2478
+ if (!parsed.success) {
2479
+ writeJson(res, 400, {
2480
+ ok: false,
2481
+ error: {
2482
+ code: `${name}/invalid-input`,
2483
+ message: "invalid input",
2484
+ details: { issues: parsed.error.issues.map((issue) => ({
2485
+ path: issue.path.map((part) => String(part)).join("."),
2486
+ message: issue.message
2487
+ })) }
2488
+ }
2489
+ }, name);
2490
+ return;
2491
+ }
2492
+ const value = await found.run(parsed.data, controller.signal);
2493
+ writeJson(res, 200, {
2494
+ ok: true,
2495
+ value: value === void 0 ? null : value
2496
+ }, name);
2497
+ } finally {
2498
+ res.removeListener("close", onClose);
2499
+ }
2500
+ } catch (error) {
2501
+ const failed = error instanceof RouteFailure ? {
2502
+ status: error.status,
2503
+ error: error.body
2504
+ } : routes.mapError(error);
2505
+ writeJson(res, failed.status, {
2506
+ ok: false,
2507
+ error: failed.error
2508
+ }, name);
2509
+ }
2510
+ }
2511
+ /** Names on `Object.prototype` are not routes. */
2512
+ function methodOf(routes, segment) {
2513
+ if (segment === void 0 || segment === "" || !Object.hasOwn(routes.methods, segment)) return;
2514
+ return routes.methods[segment];
2515
+ }
2516
+ function signalAborted(controller, res, packageName) {
2517
+ if (!controller.signal.aborted) return false;
2518
+ writeJson(res, 400, fail(packageName, "cancelled", "cancelled"), packageName);
2519
+ return true;
2520
+ }
2521
+ function browserFailure(error) {
2522
+ if (error instanceof MhBrowserError) {
2523
+ if (error.code === "INTERRUPTED") return {
2524
+ status: 400,
2525
+ error: {
2526
+ code: "mh-browser/cancelled",
2527
+ message: error.message
2528
+ }
2529
+ };
2530
+ return {
2531
+ status: error.code === "INVALID_ARGS" || error.code === "INVALID_INPUT" ? 400 : 500,
2532
+ error: {
2533
+ code: error.code,
2534
+ message: error.message
2535
+ }
2536
+ };
2537
+ }
2538
+ return {
2539
+ status: 500,
2540
+ error: {
2541
+ code: "mh-browser/failed",
2542
+ message: error instanceof Error ? error.message : "request failed"
2543
+ }
2544
+ };
2545
+ }
2546
+ function fail(packageName, code, message) {
2547
+ return {
2548
+ ok: false,
2549
+ error: {
2550
+ code: `${packageName}/${code}`,
2551
+ message
2552
+ }
2553
+ };
2554
+ }
2555
+ function segmentOf(url, prefix) {
2556
+ let pathname;
2557
+ try {
2558
+ pathname = new URL(url ?? "/", "http://127.0.0.1").pathname;
2559
+ } catch {
2560
+ return;
2561
+ }
2562
+ if (pathname.length > 1 && pathname.endsWith("/")) pathname = pathname.slice(0, -1);
2563
+ if (pathname === prefix) return "";
2564
+ const head = `${prefix}/`;
2565
+ if (!pathname.startsWith(head)) return void 0;
2566
+ const rest = pathname.slice(head.length);
2567
+ if (rest === "" || rest.includes("/")) return void 0;
2568
+ try {
2569
+ return decodeURIComponent(rest);
2570
+ } catch {
2571
+ return;
2572
+ }
2573
+ }
2574
+ function queryInput(url) {
2575
+ const params = new URL(url ?? "/", "http://127.0.0.1").searchParams;
2576
+ const input = {};
2577
+ for (const [key, value] of params) input[key] = value;
2578
+ return input;
2579
+ }
2580
+ async function readJson(req, packageName) {
2581
+ const chunks = await readChunks(req);
2582
+ if (chunks === void 0) throw new RouteFailure(400, {
2583
+ code: `${packageName}/invalid-input`,
2584
+ message: "request is too large"
2585
+ });
2586
+ const text = Buffer.concat(chunks).toString("utf8");
2587
+ if (text.trim() === "") return {};
2588
+ try {
2589
+ return JSON.parse(text);
2590
+ } catch {
2591
+ throw new RouteFailure(400, {
2592
+ code: `${packageName}/invalid-input`,
2593
+ message: "request is not json"
2594
+ });
2595
+ }
2596
+ }
2597
+ /** `undefined` means the body is over the limit. The socket stays open. */
2598
+ function readChunks(req) {
2599
+ const declared = declaredLength(req);
2600
+ if (declared !== void 0 && declared > BODY_LIMIT) {
2601
+ req.on("error", () => void 0);
2602
+ req.resume();
2603
+ return Promise.resolve(void 0);
2604
+ }
2605
+ const chunks = [];
2606
+ let size = 0;
2607
+ return new Promise((resolve, reject) => {
2608
+ const stop = () => {
2609
+ req.off("data", onData);
2610
+ req.off("end", onEnd);
2611
+ req.off("error", onError);
2612
+ };
2613
+ const onData = (chunk) => {
2614
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
2615
+ size += buffer.length;
2616
+ if (size > BODY_LIMIT) {
2617
+ stop();
2618
+ req.on("error", () => void 0);
2619
+ req.pause();
2620
+ req.resume();
2621
+ resolve(void 0);
2622
+ return;
2623
+ }
2624
+ chunks.push(buffer);
2625
+ };
2626
+ const onEnd = () => {
2627
+ stop();
2628
+ resolve(chunks);
2629
+ };
2630
+ const onError = (error) => {
2631
+ stop();
2632
+ reject(error);
2633
+ };
2634
+ req.on("data", onData);
2635
+ req.on("end", onEnd);
2636
+ req.on("error", onError);
2637
+ });
2638
+ }
2639
+ function declaredLength(req) {
2640
+ const raw = req.headers["content-length"];
2641
+ if (typeof raw !== "string" || !/^\d+$/.test(raw)) return void 0;
2642
+ const length = Number(raw);
2643
+ return Number.isSafeInteger(length) ? length : void 0;
2644
+ }
2645
+ function writeJson(res, status, body, packageName, extra) {
2646
+ if (res.writableEnded || res.destroyed) return;
2647
+ let payload;
2648
+ let nextStatus = status;
2649
+ let nextExtra = extra;
2650
+ try {
2651
+ payload = JSON.stringify(body);
2652
+ } catch {
2653
+ payload = JSON.stringify({
2654
+ ok: false,
2655
+ error: {
2656
+ code: `${packageName}/failed`,
2657
+ message: "request failed"
2658
+ }
2659
+ });
2660
+ nextStatus = 500;
2661
+ nextExtra = void 0;
2662
+ }
2663
+ const headers = {
2664
+ "content-type": "application/json; charset=utf-8",
2665
+ "cache-control": "no-store"
2666
+ };
2667
+ if (nextExtra !== void 0) Object.assign(headers, nextExtra);
2668
+ try {
2669
+ res.writeHead(nextStatus, headers);
2670
+ res.end(payload);
2671
+ } catch {
2672
+ res.destroy();
2673
+ }
2674
+ }
2675
+ //#endregion
2373
2676
  //#region lib/types/presence/book.js
2374
2677
  /** In-memory presence set for one process. The log is the source of a set that outlives the process. */
2375
2678
  var PresenceBook = class {
@@ -3166,6 +3469,48 @@ function configuredPathError(path, code) {
3166
3469
  if (code === "not-absolute") return /* @__PURE__ */ new Error(`The configured browser path must be absolute: ${path}`);
3167
3470
  return /* @__PURE__ */ new Error(`The configured browser path cannot be run (${code}): ${path}`);
3168
3471
  }
3472
+ /** Chrome and Edge were both missed. The message asks for Chrome only. */
3473
+ var BrowserNotFoundError = class extends Error {
3474
+ notFound;
3475
+ constructor(misses) {
3476
+ const tried = misses.flatMap((item) => item.missing.map((miss) => ({
3477
+ browser: item.browser,
3478
+ path: miss.path,
3479
+ reason: miss.reason
3480
+ })));
3481
+ const listed = tried.map((item) => `${item.path} (${item.reason})`).join("; ");
3482
+ const detail = listed === "" ? "" : ` Tried: ${listed}.`;
3483
+ super(`Neither Google Chrome nor Microsoft Edge was found.${detail} Ask the person to install Google Chrome, or set the browser's path in the configuration.`);
3484
+ this.name = "BrowserNotFoundError";
3485
+ this.notFound = {
3486
+ browsers: misses.map((item) => item.browser),
3487
+ tried
3488
+ };
3489
+ }
3490
+ };
3491
+ /**
3492
+ * The installed browser to launch when the choice is automatic.
3493
+ * The remembered browser wins while it can still be found; otherwise Chrome, then Edge.
3494
+ */
3495
+ async function resolveAuto(env, remembered, signal) {
3496
+ const order = [];
3497
+ if (remembered === "chrome" || remembered === "msedge") order.push(remembered);
3498
+ for (const name of ["chrome", "msedge"]) if (!order.includes(name)) order.push(name);
3499
+ const misses = [];
3500
+ for (const name of order) {
3501
+ if (signal?.aborted === true) break;
3502
+ const located = await locateInstalled(name, env, signal);
3503
+ if ("found" in located) return {
3504
+ browser: name,
3505
+ path: located.found
3506
+ };
3507
+ misses.push({
3508
+ browser: name,
3509
+ missing: located.missing
3510
+ });
3511
+ }
3512
+ throw new BrowserNotFoundError(misses);
3513
+ }
3169
3514
  /** Failure listing every path that was tried. */
3170
3515
  function browserNotFoundError(browser, missing) {
3171
3516
  const tried = missing.map((item) => `${item.path} (${item.reason})`).join("; ");
@@ -3366,7 +3711,7 @@ async function launchBrowser(options, env = hostLocateEnv()) {
3366
3711
  "--test-type"
3367
3712
  ]
3368
3713
  },
3369
- ...options.browser === "chromium" ? {} : { channel: options.browser },
3714
+ ...options.browser !== "chromium" && options.channel !== false ? { channel: options.browser } : {},
3370
3715
  ...executablePath !== void 0 ? { executablePath } : {}
3371
3716
  });
3372
3717
  }
@@ -3428,6 +3773,126 @@ async function closeOrKill(close, pid, waitMs = 1e3, kill = (target) => {
3428
3773
  return "killed";
3429
3774
  }
3430
3775
  //#endregion
3776
+ //#region lib/types/service/profile.js
3777
+ const LAST_BROWSER = "last-browser.json";
3778
+ /** Subdirectories a split profile root keeps beside the browser that is launching. */
3779
+ const KEPT = /* @__PURE__ */ new Set([
3780
+ "chrome",
3781
+ "msedge",
3782
+ "chromium",
3783
+ "custom",
3784
+ LAST_BROWSER
3785
+ ]);
3786
+ /** The browser recorded after the last successful launch, if the file names one. */
3787
+ async function readLastBrowser(root) {
3788
+ try {
3789
+ const browser = JSON.parse(await readFile(join(root, LAST_BROWSER), "utf8")).browser;
3790
+ if (browser === "chrome" || browser === "msedge" || browser === "chromium") return browser;
3791
+ } catch {
3792
+ return;
3793
+ }
3794
+ }
3795
+ /** Remember which browser actually launched, so automatic selection keeps using it. */
3796
+ async function writeLastBrowser(root, browser) {
3797
+ await mkdir(root, { recursive: true });
3798
+ await writeFile(join(root, LAST_BROWSER), `${JSON.stringify({ browser })}\n`);
3799
+ }
3800
+ /**
3801
+ * Move a profile that older versions kept in the root into `browser`'s subdirectory.
3802
+ * A root without Chrome's `Local State`, or one whose subdirectory already exists, stays as it is.
3803
+ */
3804
+ async function migrateLegacyProfile(root, browser) {
3805
+ if (!KEPT.has(browser) || browser === LAST_BROWSER) return;
3806
+ const target = join(root, browser);
3807
+ try {
3808
+ await access(join(root, "Local State"));
3809
+ } catch {
3810
+ return;
3811
+ }
3812
+ try {
3813
+ await access(target);
3814
+ return;
3815
+ } catch {}
3816
+ await mkdir(target, { recursive: true });
3817
+ const names = await readdir(root);
3818
+ for (const name of names) {
3819
+ if (KEPT.has(name)) continue;
3820
+ await rename(join(root, name), join(target, name));
3821
+ }
3822
+ }
3823
+ //#endregion
3824
+ //#region lib/types/service/launch-plan.js
3825
+ /** Subdirectory for a configured path while automatic selection does not name a browser. */
3826
+ const CUSTOM = "custom";
3827
+ /**
3828
+ * Which browser, path, and profile directory to launch.
3829
+ * A configured path is checked and never replaced. Automatic selection keeps the
3830
+ * remembered browser while it can be found, then Chrome, then Edge.
3831
+ * Playwright's Chromium is used only when it is selected, or when it is the remembered one.
3832
+ */
3833
+ async function planLaunch(input) {
3834
+ const configured = input.configured?.trim() ?? "";
3835
+ if (configured !== "") {
3836
+ const checked = checkConfigured(configured, input.env);
3837
+ if (!checked.ok) throw configuredPathError(checked.path, checked.code);
3838
+ const named = input.choice === "auto" ? void 0 : input.choice;
3839
+ if (named !== void 0) await settle(input, named);
3840
+ return {
3841
+ browser: named ?? "chrome",
3842
+ channel: named !== void 0 && named !== "chromium",
3843
+ profileDir: folder(input, named ?? CUSTOM),
3844
+ executablePath: checked.path,
3845
+ ...named !== void 0 ? { remember: named } : {}
3846
+ };
3847
+ }
3848
+ if (input.choice === "auto" && input.remembered === "chromium" && "found" in input.bundled) {
3849
+ await settle(input, "chromium");
3850
+ return {
3851
+ browser: "chromium",
3852
+ channel: false,
3853
+ profileDir: folder(input, "chromium"),
3854
+ remember: "chromium"
3855
+ };
3856
+ }
3857
+ if (input.choice === "auto") {
3858
+ const remembered = input.remembered === "chromium" ? void 0 : input.remembered;
3859
+ const resolved = await resolveAuto(input.env, remembered, input.signal);
3860
+ await settle(input, resolved.browser);
3861
+ return {
3862
+ browser: resolved.browser,
3863
+ channel: true,
3864
+ profileDir: folder(input, resolved.browser),
3865
+ executablePath: resolved.path,
3866
+ remember: resolved.browser
3867
+ };
3868
+ }
3869
+ if (input.choice === "chromium") {
3870
+ await settle(input, "chromium");
3871
+ return {
3872
+ browser: "chromium",
3873
+ channel: false,
3874
+ profileDir: folder(input, "chromium"),
3875
+ remember: "chromium"
3876
+ };
3877
+ }
3878
+ const located = await locateInstalled(input.choice, input.env, input.signal);
3879
+ if (!("found" in located)) throw browserNotFoundError(input.choice, located.missing);
3880
+ await settle(input, input.choice);
3881
+ return {
3882
+ browser: input.choice,
3883
+ channel: true,
3884
+ profileDir: folder(input, input.choice),
3885
+ executablePath: located.found,
3886
+ remember: input.choice
3887
+ };
3888
+ }
3889
+ function folder(input, name) {
3890
+ return input.split ? profileDirFor(input.root, name) : input.root;
3891
+ }
3892
+ async function settle(input, name) {
3893
+ if (input.split) await migrateLegacyProfile(input.root, name);
3894
+ }
3895
+ //#endregion
3431
3896
  //#region lib/types/service/control.js
3432
3897
  /**
3433
3898
  * Who holds each tab of one session. Person input outside a service dispatch
@@ -4607,16 +5072,18 @@ function extensionDir() {
4607
5072
  var Extension = class Extension {
4608
5073
  context;
4609
5074
  id;
5075
+ browserSession;
4610
5076
  workerPage;
4611
- constructor(context, id, worker) {
5077
+ constructor(context, id, browserSession, worker) {
4612
5078
  this.context = context;
4613
5079
  this.id = id;
5080
+ this.browserSession = browserSession;
4614
5081
  this.workerPage = worker;
4615
5082
  }
4616
5083
  static async load(context, browserSession) {
4617
5084
  const loaded = await browserSession.send("Extensions.loadUnpacked", { path: extensionDir() });
4618
5085
  const worker = await findWorker(context, loaded.id);
4619
- return new Extension(context, loaded.id, worker);
5086
+ return new Extension(context, loaded.id, browserSession, worker);
4620
5087
  }
4621
5088
  /** Address of a page shipped in the extension directory. */
4622
5089
  pageUrl(name) {
@@ -4700,11 +5167,32 @@ var Extension = class Extension {
4700
5167
  async worker(signal) {
4701
5168
  const current = this.workerPage;
4702
5169
  if (current !== void 0 && this.context.serviceWorkers().includes(current)) return current;
4703
- const worker = await untilAborted(findWorker(this.context, this.id), capped(signal, CALL_MS$1));
5170
+ const worker = await restoreWorker(this.context, this.id, async () => {
5171
+ await this.browserSession.send("Extensions.loadUnpacked", { path: extensionDir() });
5172
+ }, signal);
4704
5173
  this.workerPage = worker;
4705
5174
  return worker;
4706
5175
  }
4707
5176
  };
5177
+ /**
5178
+ * The service worker, reloading the extension once when it is gone.
5179
+ * A worker that comes back on its own during the first wait is used as it is.
5180
+ * After a reload that still has no worker, the extension was turned off.
5181
+ */
5182
+ async function restoreWorker(context, id, reload, signal, appearMs = 1e3) {
5183
+ try {
5184
+ return await untilAborted(findWorker(context, id, appearMs), signal);
5185
+ } catch (error) {
5186
+ if (isInterrupted(error)) throw error;
5187
+ }
5188
+ try {
5189
+ await reload();
5190
+ return await untilAborted(findWorker(context, id), signal);
5191
+ } catch (error) {
5192
+ if (isInterrupted(error)) throw error;
5193
+ throw new Error("The agent extension in the browser was turned off.", { cause: error });
5194
+ }
5195
+ }
4708
5196
  /** The extension's service worker. Looks once more after the wait times out. */
4709
5197
  async function findWorker(context, id, timeoutMs = WORKER_MS) {
4710
5198
  const find = () => context.serviceWorkers().find((worker) => worker.url().includes(id));
@@ -5522,46 +6010,6 @@ async function writeCounter(profileDir, next) {
5522
6010
  const testHooks = Symbol("mh-browser test hooks");
5523
6011
  //#endregion
5524
6012
  //#region lib/types/service/service.js
5525
- var __runInitializers = function(thisArg, initializers, value) {
5526
- var useValue = arguments.length > 2;
5527
- for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
5528
- return useValue ? value : void 0;
5529
- };
5530
- var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
5531
- function accept(f) {
5532
- if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
5533
- return f;
5534
- }
5535
- var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
5536
- var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
5537
- var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
5538
- var _, done = false;
5539
- for (var i = decorators.length - 1; i >= 0; i--) {
5540
- var context = {};
5541
- for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
5542
- for (var p in contextIn.access) context.access[p] = contextIn.access[p];
5543
- context.addInitializer = function(f) {
5544
- if (done) throw new TypeError("Cannot add initializers after decoration has completed");
5545
- extraInitializers.push(accept(f || null));
5546
- };
5547
- var result = (0, decorators[i])(kind === "accessor" ? {
5548
- get: descriptor.get,
5549
- set: descriptor.set
5550
- } : descriptor[key], context);
5551
- if (kind === "accessor") {
5552
- if (result === void 0) continue;
5553
- if (result === null || typeof result !== "object") throw new TypeError("Object expected");
5554
- if (_ = accept(result.get)) descriptor.get = _;
5555
- if (_ = accept(result.set)) descriptor.set = _;
5556
- if (_ = accept(result.init)) initializers.unshift(_);
5557
- } else if (_ = accept(result)) {
5558
- if (kind === "field") initializers.unshift(_);
5559
- else descriptor[key] = _;
5560
- }
5561
- }
5562
- if (target) Object.defineProperty(target, contextIn.name, descriptor);
5563
- done = true;
5564
- };
5565
6013
  /** Navigation and back share this limit (§3.7). */
5566
6014
  const NAVIGATION_MS = 1e4;
5567
6015
  /** How long an open that started a download waits for the download event. */
@@ -5589,1581 +6037,1585 @@ const NO_WORKSPACE_REASON = "this session has no working directory";
5589
6037
  * the session's browser. `act` returns a snapshot, including on a page that
5590
6038
  * also has an Agent View.
5591
6039
  */
5592
- let MhBrowserService = (() => {
5593
- let _classSuper = TypertRemoteService;
5594
- let _instanceExtraInitializers = [];
5595
- let _locateFor_decorators;
5596
- let _revealHandover_decorators;
5597
- return class MhBrowserService extends _classSuper {
5598
- static {
5599
- const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
5600
- _locateFor_decorators = [Remote];
5601
- _revealHandover_decorators = [Remote];
5602
- __esDecorate(this, null, _locateFor_decorators, {
5603
- kind: "method",
5604
- name: "locateFor",
5605
- static: false,
5606
- private: false,
5607
- access: {
5608
- has: (obj) => "locateFor" in obj,
5609
- get: (obj) => obj.locateFor
5610
- },
5611
- metadata: _metadata
5612
- }, null, _instanceExtraInitializers);
5613
- __esDecorate(this, null, _revealHandover_decorators, {
5614
- kind: "method",
5615
- name: "revealHandover",
5616
- static: false,
5617
- private: false,
5618
- access: {
5619
- has: (obj) => "revealHandover" in obj,
5620
- get: (obj) => obj.revealHandover
5621
- },
5622
- metadata: _metadata
5623
- }, null, _instanceExtraInitializers);
5624
- if (_metadata) Object.defineProperty(this, Symbol.metadata, {
5625
- enumerable: true,
5626
- configurable: true,
5627
- writable: true,
5628
- value: _metadata
6040
+ var MhBrowserService = class extends Service {
6041
+ windows = new Windows();
6042
+ headless;
6043
+ /** Profile root. The default root gets one subdirectory per browser at launch. */
6044
+ profileRoot;
6045
+ /** A configured profile directory is used as given, without a per-browser subdirectory. */
6046
+ splitProfile;
6047
+ browserName;
6048
+ executablePath;
6049
+ /** Tests replace the machine lookup. Unset uses this machine. */
6050
+ locator;
6051
+ context;
6052
+ pids = /* @__PURE__ */ new WeakMap();
6053
+ ready = Promise.resolve();
6054
+ closing = false;
6055
+ /** A browser restart was requested and has not run yet. */
6056
+ relaunchWanted = false;
6057
+ /** Counts browser and path changes. A start that sampled the latest one clears the restart. */
6058
+ configEpoch = 0;
6059
+ /** The running browser is being closed so the new configuration can start. */
6060
+ replacing = false;
6061
+ /** The browser is not running. The next call that needs a page starts it. */
6062
+ exited = true;
6063
+ exits = [];
6064
+ /** One queue per owner: a slow wait in one Session does not hold up another. */
6065
+ queues = /* @__PURE__ */ new Map();
6066
+ shown = /* @__PURE__ */ new Map();
6067
+ book = new PresenceBook();
6068
+ maxBytes;
6069
+ workspaces = /* @__PURE__ */ new Map();
6070
+ control = new Control();
6071
+ personTouch = /* @__PURE__ */ new Set();
6072
+ /** Origins that have served a readable Agent View. Memory only; a restart clears it. */
6073
+ agentViewOrigins = /* @__PURE__ */ new Set();
6074
+ /** The last Agent View read for a page address, so a later read can send If-None-Match. */
6075
+ documents = /* @__PURE__ */ new Map();
6076
+ constructor(ctx, config) {
6077
+ super(ctx, "mhBrowser");
6078
+ this.maxBytes = config.presence.maxBytes;
6079
+ this.headless = config.headless;
6080
+ const configuredDir = config.profileDir;
6081
+ this.splitProfile = configuredDir === void 0 || configuredDir === "";
6082
+ this.profileRoot = this.splitProfile ? defaultProfileDir(ctx.get("profileContext")) : configuredDir;
6083
+ this.browserName = config.browser;
6084
+ this.executablePath = config.executablePath ?? { get: () => void 0 };
6085
+ Object.getPrototypeOf(ctx).on("loader/volatile-update", (paths) => {
6086
+ if (!paths.some((path) => path.includes("browser") || path.includes("executablePath"))) return;
6087
+ this.configEpoch += 1;
6088
+ this.relaunchWanted = true;
6089
+ this.relaunchIfIdle();
6090
+ });
6091
+ this.windows.setPersonInput((owner, tab) => {
6092
+ const live = tab === void 0 ? void 0 : this.windows.get(owner, tab);
6093
+ this.control.note(owner, tab);
6094
+ if (live !== void 0) this.windows.markMayHaveChanged(live);
6095
+ });
6096
+ this.windows.onTabClosed((tab) => {
6097
+ this.shown.delete(tab.id);
6098
+ });
6099
+ this.up().catch(() => void 0);
6100
+ ctx.on("session/disposed", (session) => {
6101
+ const owner = session.id;
6102
+ if (owner === void 0) return;
6103
+ this.exclusive(owner, () => this.windows.closeOwner(owner, AbortSignal.timeout(DISPOSE_MS)), AbortSignal.timeout(DISPOSE_MS)).catch((error) => {
6104
+ ctx.logger.warn("closing the windows of %s failed: %o", owner, error);
5629
6105
  });
6106
+ this.book.forget(owner);
6107
+ this.control.forget(owner);
6108
+ this.workspaces.delete(owner);
6109
+ });
6110
+ ctx.effect(() => async () => {
6111
+ this.closing = true;
6112
+ await this.stop();
6113
+ });
6114
+ }
6115
+ /** Remember an origin whose pages offer Agent Views. A missing page does not remove it. */
6116
+ declareAgentViewOrigin(origin) {
6117
+ try {
6118
+ const parsed = new URL(origin);
6119
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return;
6120
+ this.agentViewOrigins.add(parsed.origin);
6121
+ } catch {}
6122
+ }
6123
+ async open(owner, items, signal, options) {
6124
+ const reveal = options?.reveal === true;
6125
+ try {
6126
+ return await this.exclusive(owner, async () => {
6127
+ await this.up(owner === PERSON_OWNER);
6128
+ const views = [];
6129
+ for (const item of items) {
6130
+ if (signal?.aborted) {
6131
+ views.push({
6132
+ url: item.url,
6133
+ reason: WAITING_STOPPED
6134
+ });
6135
+ continue;
6136
+ }
6137
+ views.push(await this.openAddress(owner, item, signal, reveal));
6138
+ }
6139
+ await this.enforceCap(owner);
6140
+ return views;
6141
+ }, signal);
6142
+ } catch (error) {
6143
+ if (!isInterrupted(error)) throw error;
6144
+ return items.map((item) => ({
6145
+ url: item.url,
6146
+ reason: WAITING_STOPPED
6147
+ }));
5630
6148
  }
5631
- windows = (__runInitializers(this, _instanceExtraInitializers), new Windows());
5632
- headless;
5633
- profileDir;
5634
- browserName;
5635
- executablePath;
5636
- /** Tests replace the machine lookup. Unset uses this machine. */
5637
- locator;
5638
- context;
5639
- pids = /* @__PURE__ */ new WeakMap();
5640
- ready = Promise.resolve();
5641
- closing = false;
5642
- /** A browser restart was requested and has not run yet. */
5643
- relaunchWanted = false;
5644
- /** Counts browser and path changes. A start that sampled the latest one clears the restart. */
5645
- configEpoch = 0;
5646
- /** The running browser is being closed so the new configuration can start. */
5647
- replacing = false;
5648
- /** The browser is not running. The next call that needs a page starts it. */
5649
- exited = true;
5650
- exits = [];
5651
- /** One queue per owner: a slow wait in one Session does not hold up another. */
5652
- queues = /* @__PURE__ */ new Map();
5653
- shown = /* @__PURE__ */ new Map();
5654
- book = new PresenceBook();
5655
- maxBytes;
5656
- workspaces = /* @__PURE__ */ new Map();
5657
- control = new Control();
5658
- personTouch = /* @__PURE__ */ new Set();
5659
- /** Origins that have served a readable Agent View. Memory only; a restart clears it. */
5660
- agentViewOrigins = /* @__PURE__ */ new Set();
5661
- /** The last Agent View read for a page address, so a later read can send If-None-Match. */
5662
- documents = /* @__PURE__ */ new Map();
5663
- constructor(ctx, config) {
5664
- super(ctx, "mhBrowser");
5665
- this.maxBytes = config.presence.maxBytes;
5666
- this.headless = config.headless;
5667
- this.profileDir = config.profileDir ?? defaultProfileDir(ctx.get("profileContext"));
5668
- this.browserName = config.browser;
5669
- this.executablePath = config.executablePath ?? { get: () => void 0 };
5670
- Object.getPrototypeOf(ctx).on("loader/volatile-update", (paths) => {
5671
- if (!paths.some((path) => path.includes("browser") || path.includes("executablePath"))) return;
5672
- this.configEpoch += 1;
5673
- this.relaunchWanted = true;
5674
- this.relaunchIfIdle();
5675
- });
5676
- this.windows.setPersonInput((owner, tab) => {
5677
- const live = tab === void 0 ? void 0 : this.windows.get(owner, tab);
5678
- this.control.note(owner, tab);
5679
- if (live !== void 0) this.windows.markMayHaveChanged(live);
5680
- });
5681
- this.windows.onTabClosed((tab) => {
5682
- this.shown.delete(tab.id);
5683
- });
5684
- this.up().catch(() => void 0);
5685
- ctx.on("session/disposed", (session) => {
5686
- const owner = session.id;
5687
- if (owner === void 0) return;
5688
- this.exclusive(owner, () => this.windows.closeOwner(owner, AbortSignal.timeout(DISPOSE_MS)), AbortSignal.timeout(DISPOSE_MS)).catch((error) => {
5689
- ctx.logger.warn("closing the windows of %s failed: %o", owner, error);
6149
+ }
6150
+ async view(owner, tab, signal) {
6151
+ return this.exclusive(owner, async () => {
6152
+ await this.ready;
6153
+ const live = this.windows.get(owner, tab);
6154
+ if (live === void 0) return unknownTab();
6155
+ if (signal?.aborted) return {
6156
+ tab,
6157
+ url: live.url,
6158
+ reason: WAITING_STOPPED
6159
+ };
6160
+ return this.refreshView(live, signal);
6161
+ }, signal);
6162
+ }
6163
+ /** Pages whose current representation is already in the model's presence. */
6164
+ rememberPresence(owner, urls) {
6165
+ this.book.remember(owner, urls.map((url) => canonical(url)));
6166
+ }
6167
+ presenceList(owner) {
6168
+ return this.book.entries(owner);
6169
+ }
6170
+ presencePut(owner, urls, source) {
6171
+ return this.book.put(owner, urls.map((url) => canonical(url)), source);
6172
+ }
6173
+ presenceRemove(owner, urls) {
6174
+ return this.book.remove(owner, urls.map((url) => canonical(url)));
6175
+ }
6176
+ /** The set the session log folds to; taken once per process. */
6177
+ presenceLoad(owner, folded) {
6178
+ this.book.load(owner, folded);
6179
+ }
6180
+ presenceTakeResume(owner) {
6181
+ return this.book.takeResume(owner);
6182
+ }
6183
+ /**
6184
+ * Re-read presence pages and build the next reminder.
6185
+ * A tab already on the address is read in place. A check that has to open
6186
+ * one closes it before returning. Removals are included, and they cause
6187
+ * every remaining page to be read so a page kept out by the byte budget
6188
+ * can come back. An empty set has nothing to read and does not wait for the
6189
+ * browser; a browser that is down makes every page absent.
6190
+ */
6191
+ async presenceCheck(owner, which, opts) {
6192
+ if (this.book.entries(owner).length === 0 && this.book.peekRemovals(owner).length === 0) return;
6193
+ return this.exclusive(owner, async () => {
6194
+ const down = await this.up().then(() => void 0, (error) => error instanceof Error ? error.message : String(error));
6195
+ const pages = this.book.entries(owner);
6196
+ const removals = this.book.peekRemovals(owner);
6197
+ const wanted = new Set(which === "all" ? pages.map((page) => page.url) : which.map(canonical));
6198
+ if (removals.length > 0) for (const page of pages) wanted.add(page.url);
6199
+ const observations = [];
6200
+ for (const page of pages) {
6201
+ if (!wanted.has(page.url)) continue;
6202
+ observations.push(down === void 0 ? await this.observePresence(owner, page.url, opts?.signal) : {
6203
+ url: page.url,
6204
+ ok: false,
6205
+ reason: `browser not running: ${down}`,
6206
+ title: "",
6207
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
6208
+ bytes: 0
5690
6209
  });
5691
- this.book.forget(owner);
5692
- this.control.forget(owner);
5693
- this.workspaces.delete(owner);
6210
+ }
6211
+ const planned = planReminder({
6212
+ pages,
6213
+ observations,
6214
+ removals,
6215
+ maxBytes: this.maxBytes,
6216
+ baseline: opts?.baseline === true,
6217
+ replaces: opts?.replaces === true,
6218
+ ...opts?.force === true ? { force: true } : {}
5694
6219
  });
5695
- ctx.effect(() => async () => {
5696
- this.closing = true;
5697
- await this.stop();
6220
+ if (planned === void 0) return void 0;
6221
+ this.book.apply(owner, planned.next);
6222
+ this.book.clearRemovals(owner);
6223
+ return {
6224
+ text: planned.text,
6225
+ record: planned.record
6226
+ };
6227
+ }, opts?.signal);
6228
+ }
6229
+ /**
6230
+ * Where a download the page starts may be written: the session's writable
6231
+ * root, or why it may not write at all.
6232
+ */
6233
+ noteWorkspace(owner, target) {
6234
+ this.workspaces.set(owner, target);
6235
+ }
6236
+ tabs(owner) {
6237
+ return this.windows.list(owner);
6238
+ }
6239
+ takeClosed(owner) {
6240
+ return this.windows.takeClosed(owner);
6241
+ }
6242
+ windowId(owner, tab) {
6243
+ return this.exclusive(owner, async () => {
6244
+ await this.ready;
6245
+ return this.windows.windowId(owner, tab);
6246
+ });
6247
+ }
6248
+ async fetch(url, opts) {
6249
+ try {
6250
+ await this.up();
6251
+ const context = this.context;
6252
+ if (context === void 0) return {
6253
+ kind: "error",
6254
+ reason: "browser is not running"
6255
+ };
6256
+ const headers = {};
6257
+ if (opts?.accept !== void 0) headers.accept = opts.accept;
6258
+ if (opts?.ifNoneMatch !== void 0) headers["if-none-match"] = opts.ifNoneMatch;
6259
+ const response = await context.request.get(url, {
6260
+ headers,
6261
+ failOnStatusCode: false,
6262
+ ...opts?.signal !== void 0 ? { signal: opts.signal } : {}
5698
6263
  });
6264
+ const headerMap = response.headers();
6265
+ const body = {
6266
+ kind: "response",
6267
+ finalUrl: response.url(),
6268
+ status: response.status(),
6269
+ body: new Uint8Array(await untilAborted(response.body(), capped(opts?.signal, READ_MS)))
6270
+ };
6271
+ const mediaType = headerMap["content-type"];
6272
+ const etag = headerMap.etag;
6273
+ const link = headerMap.link;
6274
+ if (mediaType !== void 0) body.mediaType = mediaType;
6275
+ if (etag !== void 0) body.etag = etag;
6276
+ if (link !== void 0) body.link = link;
6277
+ return body;
6278
+ } catch (error) {
6279
+ return {
6280
+ kind: "error",
6281
+ reason: error instanceof Error ? error.message : String(error)
6282
+ };
5699
6283
  }
5700
- /** Remember an origin whose pages offer Agent Views. A missing page does not remove it. */
5701
- declareAgentViewOrigin(origin) {
5702
- try {
5703
- const parsed = new URL(origin);
5704
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return;
5705
- this.agentViewOrigins.add(parsed.origin);
5706
- } catch {}
5707
- }
5708
- async open(owner, items, signal, options) {
5709
- const reveal = options?.reveal === true;
5710
- try {
5711
- return await this.exclusive(owner, async () => {
5712
- await this.up(owner === PERSON_OWNER);
5713
- const views = [];
5714
- for (const item of items) {
5715
- if (signal?.aborted) {
5716
- views.push({
5717
- url: item.url,
5718
- reason: WAITING_STOPPED
5719
- });
5720
- continue;
5721
- }
5722
- views.push(await this.openAddress(owner, item, signal, reveal));
5723
- }
5724
- await this.enforceCap(owner);
5725
- return views;
5726
- }, signal);
5727
- } catch (error) {
5728
- if (!isInterrupted(error)) throw error;
5729
- return items.map((item) => ({
5730
- url: item.url,
5731
- reason: WAITING_STOPPED
5732
- }));
6284
+ }
6285
+ async pushPath(owner, tab, path) {
6286
+ await this.ready;
6287
+ const live = this.windows.get(owner, tab);
6288
+ if (live === void 0) return;
6289
+ await live.page.evaluate((next) => {
6290
+ history.pushState({}, "", next);
6291
+ }, path);
6292
+ }
6293
+ async started() {
6294
+ await this.ready;
6295
+ }
6296
+ /** The person asked for the browser: start it if it exited, past the exit limit. */
6297
+ startForPerson() {
6298
+ return this.up(true);
6299
+ }
6300
+ [testHooks]() {
6301
+ return {
6302
+ crash: async () => {
6303
+ this.windows.suppressPersonInput();
6304
+ await (this.context?.browser())?.close();
6305
+ },
6306
+ page: (owner, tab) => this.windows.get(owner, tab)?.page,
6307
+ running: () => this.context !== void 0,
6308
+ pages: () => this.context?.pages() ?? [],
6309
+ pid: () => this.context === void 0 ? void 0 : this.pids.get(this.context),
6310
+ useLocator: (env) => {
6311
+ this.locator = env;
5733
6312
  }
6313
+ };
6314
+ }
6315
+ /**
6316
+ * Where `browser` would be launched from when no path is configured.
6317
+ * The configured path is not consulted: the answer is what an empty path uses.
6318
+ * `auto` reports the browser automatic selection would launch.
6319
+ */
6320
+ async locateFor(browser, signal) {
6321
+ const stopped = () => signal?.aborted === true;
6322
+ if (stopped()) throw new MhBrowserError(INTERRUPTED, WAITING_STOPPED);
6323
+ if (browser !== "auto" && browser !== "chrome" && browser !== "msedge" && browser !== "chromium") throw new MhBrowserError("INVALID_ARGS", "browser must be auto, chrome, msedge, or chromium");
6324
+ const env = this.locateEnv();
6325
+ if (browser === "auto") return this.locateAuto(env, signal);
6326
+ if (browser === "chromium") return bundledChromiumLocation(env.access);
6327
+ const located = await locateInstalled(browser, env, signal);
6328
+ if (stopped()) throw new MhBrowserError(INTERRUPTED, WAITING_STOPPED);
6329
+ return located;
6330
+ }
6331
+ async locateAuto(env, signal) {
6332
+ const stopped = () => signal?.aborted === true;
6333
+ const remembered = await readLastBrowser(this.profileRoot);
6334
+ if (remembered === "chromium") {
6335
+ const bundled = bundledChromiumLocation(env.access);
6336
+ if ("found" in bundled) return {
6337
+ found: bundled.found,
6338
+ browser: "chromium"
6339
+ };
5734
6340
  }
5735
- async view(owner, tab, signal) {
5736
- return this.exclusive(owner, async () => {
5737
- await this.ready;
5738
- const live = this.windows.get(owner, tab);
5739
- if (live === void 0) return unknownTab();
5740
- if (signal?.aborted) return {
5741
- tab,
5742
- url: live.url,
5743
- reason: WAITING_STOPPED
5744
- };
5745
- return this.refreshView(live, signal);
5746
- }, signal);
6341
+ try {
6342
+ const resolved = await resolveAuto(env, remembered === "chromium" ? void 0 : remembered, signal);
6343
+ if (stopped()) throw new MhBrowserError(INTERRUPTED, WAITING_STOPPED);
6344
+ return {
6345
+ found: resolved.path,
6346
+ browser: resolved.browser
6347
+ };
6348
+ } catch (error) {
6349
+ if (stopped()) throw new MhBrowserError(INTERRUPTED, WAITING_STOPPED);
6350
+ if (error instanceof BrowserNotFoundError) return { missing: error.notFound.tried };
6351
+ throw error;
5747
6352
  }
5748
- /** Pages whose current representation is already in the model's presence. */
5749
- rememberPresence(owner, urls) {
5750
- this.book.remember(owner, urls.map((url) => canonical(url)));
5751
- }
5752
- presenceList(owner) {
5753
- return this.book.entries(owner);
5754
- }
5755
- presencePut(owner, urls, source) {
5756
- return this.book.put(owner, urls.map((url) => canonical(url)), source);
5757
- }
5758
- presenceRemove(owner, urls) {
5759
- return this.book.remove(owner, urls.map((url) => canonical(url)));
5760
- }
5761
- /** The set the session log folds to; taken once per process. */
5762
- presenceLoad(owner, folded) {
5763
- this.book.load(owner, folded);
5764
- }
5765
- presenceTakeResume(owner) {
5766
- return this.book.takeResume(owner);
5767
- }
5768
- /**
5769
- * Re-read presence pages and build the next reminder.
5770
- * A tab already on the address is read in place. A check that has to open
5771
- * one closes it before returning. Removals are included, and they cause
5772
- * every remaining page to be read so a page kept out by the byte budget
5773
- * can come back. An empty set has nothing to read and does not wait for the
5774
- * browser; a browser that is down makes every page absent.
5775
- */
5776
- async presenceCheck(owner, which, opts) {
5777
- if (this.book.entries(owner).length === 0 && this.book.peekRemovals(owner).length === 0) return;
5778
- return this.exclusive(owner, async () => {
5779
- const down = await this.up().then(() => void 0, (error) => error instanceof Error ? error.message : String(error));
5780
- const pages = this.book.entries(owner);
5781
- const removals = this.book.peekRemovals(owner);
5782
- const wanted = new Set(which === "all" ? pages.map((page) => page.url) : which.map(canonical));
5783
- if (removals.length > 0) for (const page of pages) wanted.add(page.url);
5784
- const observations = [];
5785
- for (const page of pages) {
5786
- if (!wanted.has(page.url)) continue;
5787
- observations.push(down === void 0 ? await this.observePresence(owner, page.url, opts?.signal) : {
5788
- url: page.url,
5789
- ok: false,
5790
- reason: `browser not running: ${down}`,
5791
- title: "",
5792
- observedAt: (/* @__PURE__ */ new Date()).toISOString(),
5793
- bytes: 0
5794
- });
6353
+ }
6354
+ async act(owner, tab, op, signal) {
6355
+ return this.exclusive(owner, async () => {
6356
+ await this.ready;
6357
+ this.refuseIfPerson(owner, tab);
6358
+ const live = this.windows.get(owner, tab);
6359
+ if (live === void 0) throw new MhBrowserError(UNKNOWN_TAB, UNKNOWN_TAB_REASON);
6360
+ if (signal?.aborted) throw new MhBrowserError(INTERRUPTED, WAITING_STOPPED);
6361
+ const linked = this.control.link(owner, signal, tab);
6362
+ try {
6363
+ if (live.dialogHeld && op.kind !== "handle_dialog") throw new MhBrowserError("MODAL_STATE", "a dialog is open; use browser_handle_dialog", await this.blockedView(live));
6364
+ if (live.fileChooser !== void 0 && op.kind !== "file_upload") {
6365
+ const blocked = await this.pageFromShown(live, this.shown.get(live.id), { surface: "snapshot" }, signal);
6366
+ blocked.dialog = {
6367
+ type: "filechooser",
6368
+ message: live.fileChooser.isMultiple() ? "choose files (several allowed) with browser_file_upload" : "choose one file with browser_file_upload"
6369
+ };
6370
+ throw new MhBrowserError("MODAL_STATE", "a file chooser is open; use browser_file_upload", blocked);
5795
6371
  }
5796
- const planned = planReminder({
5797
- pages,
5798
- observations,
5799
- removals,
5800
- maxBytes: this.maxBytes,
5801
- baseline: opts?.baseline === true,
5802
- replaces: opts?.replaces === true,
5803
- ...opts?.force === true ? { force: true } : {}
5804
- });
5805
- if (planned === void 0) return void 0;
5806
- this.book.apply(owner, planned.next);
5807
- this.book.clearRemovals(owner);
5808
- return {
5809
- text: planned.text,
5810
- record: planned.record
6372
+ const outcome = await this.perform(live, op, linked.signal);
6373
+ if (op.kind === "fill_form" || op.kind === "select_option" || op.kind === "type" || op.kind === "file_upload") {
6374
+ if (outcome.navigated) this.windows.onNavigated(live);
6375
+ else this.windows.holdInput(live);
6376
+ } else if (outcome.navigated) this.windows.onNavigated(live);
6377
+ this.windows.touch(live);
6378
+ const shown = outcome.navigated ? await this.discover(live, live.page.url(), null, signal) : await this.refreshSnapshot(live, signal);
6379
+ const scoped = op.kind === "snapshot" && (op.target !== void 0 || op.depth !== void 0 || op.boxes === true) ? await this.scopedSnapshot(live, op, signal) : void 0;
6380
+ this.shown.set(live.id, shown);
6381
+ this.windows.noteUrl(live, live.page.url());
6382
+ const view = await this.pageFromShown(live, shown, {
6383
+ surface: "snapshot",
6384
+ ...outcome.dialog !== void 0 ? { dialog: outcome.dialog } : {},
6385
+ ...outcome.incomplete !== void 0 ? { incomplete: outcome.incomplete } : {},
6386
+ ...outcome.waited !== void 0 ? { waited: outcome.waited } : {}
6387
+ }, signal);
6388
+ if (scoped !== void 0 && view.representation.kind === "snapshot") view.representation = {
6389
+ ...view.representation,
6390
+ text: scoped
5811
6391
  };
5812
- }, opts?.signal);
5813
- }
5814
- /**
5815
- * Where a download the page starts may be written: the session's writable
5816
- * root, or why it may not write at all.
5817
- */
5818
- noteWorkspace(owner, target) {
5819
- this.workspaces.set(owner, target);
5820
- }
5821
- tabs(owner) {
5822
- return this.windows.list(owner);
5823
- }
5824
- takeClosed(owner) {
5825
- return this.windows.takeClosed(owner);
5826
- }
5827
- windowId(owner, tab) {
5828
- return this.exclusive(owner, async () => {
5829
- await this.ready;
5830
- return this.windows.windowId(owner, tab);
5831
- });
5832
- }
5833
- async fetch(url, opts) {
5834
- try {
5835
- await this.up();
5836
- const context = this.context;
5837
- if (context === void 0) return {
5838
- kind: "error",
5839
- reason: "browser is not running"
5840
- };
5841
- const headers = {};
5842
- if (opts?.accept !== void 0) headers.accept = opts.accept;
5843
- if (opts?.ifNoneMatch !== void 0) headers["if-none-match"] = opts.ifNoneMatch;
5844
- const response = await context.request.get(url, {
5845
- headers,
5846
- failOnStatusCode: false,
5847
- ...opts?.signal !== void 0 ? { signal: opts.signal } : {}
5848
- });
5849
- const headerMap = response.headers();
5850
- const body = {
5851
- kind: "response",
5852
- finalUrl: response.url(),
5853
- status: response.status(),
5854
- body: new Uint8Array(await untilAborted(response.body(), capped(opts?.signal, READ_MS)))
5855
- };
5856
- const mediaType = headerMap["content-type"];
5857
- const etag = headerMap.etag;
5858
- const link = headerMap.link;
5859
- if (mediaType !== void 0) body.mediaType = mediaType;
5860
- if (etag !== void 0) body.etag = etag;
5861
- if (link !== void 0) body.link = link;
5862
- return body;
6392
+ if (!showsSnapshot(op)) {
6393
+ const summary = outcome.summary ?? summaryOf(op);
6394
+ if (summary !== void 0) view.summary = summary;
6395
+ if (outcome.detail !== void 0 && outcome.detail !== "") view.detail = outcome.detail;
6396
+ }
6397
+ if (op.kind === "take_screenshot") view.summary = "";
6398
+ if (outcome.shot !== void 0) view.shot = outcome.shot;
6399
+ if (outcome.writes !== void 0) view.writes = outcome.writes;
6400
+ return this.attachDownload(live, view, false);
5863
6401
  } catch (error) {
5864
- return {
5865
- kind: "error",
5866
- reason: error instanceof Error ? error.message : String(error)
5867
- };
6402
+ if (error instanceof MhBrowserError && error.code === "TAKEN_OVER") throw error;
6403
+ if (this.control.ofTab(owner, tab) === "person") throw await this.takenOver(live);
6404
+ if (error instanceof MhBrowserError && error.code === "STALE_REF" && error.page === void 0) throw new MhBrowserError(error.code, error.message, await this.pageFromShown(live, this.shown.get(live.id), { surface: "snapshot" }, signal));
6405
+ throw error;
6406
+ } finally {
6407
+ linked.release();
5868
6408
  }
5869
- }
5870
- async pushPath(owner, tab, path) {
5871
- await this.ready;
5872
- const live = this.windows.get(owner, tab);
5873
- if (live === void 0) return;
5874
- await live.page.evaluate((next) => {
5875
- history.pushState({}, "", next);
5876
- }, path);
5877
- }
5878
- async started() {
6409
+ }, signal);
6410
+ }
6411
+ holdHandover(owner, tab) {
6412
+ const live = this.windows.get(owner, tab);
6413
+ if (live === void 0) throw new MhBrowserError(UNKNOWN_TAB, UNKNOWN_TAB_REASON);
6414
+ this.windows.holdHandover(live);
6415
+ }
6416
+ releaseHandover(owner) {
6417
+ this.windows.releaseHandover(owner);
6418
+ this.windows.markWaiting(owner, false);
6419
+ }
6420
+ /** `undefined` when no screenshot can be taken now: a dialog is open, or the page refused. */
6421
+ capture(owner, tab, signal) {
6422
+ return this.exclusive(owner, async () => {
5879
6423
  await this.ready;
5880
- }
5881
- /** The person asked for the browser: start it if it exited, past the exit limit. */
5882
- startForPerson() {
5883
- return this.up(true);
5884
- }
5885
- [testHooks]() {
5886
- return {
5887
- crash: async () => {
5888
- this.windows.suppressPersonInput();
5889
- await (this.context?.browser())?.close();
5890
- },
5891
- page: (owner, tab) => this.windows.get(owner, tab)?.page,
5892
- running: () => this.context !== void 0,
5893
- pages: () => this.context?.pages() ?? [],
5894
- pid: () => this.context === void 0 ? void 0 : this.pids.get(this.context),
5895
- useLocator: (env) => {
5896
- this.locator = env;
5897
- }
5898
- };
5899
- }
5900
- /**
5901
- * Where `browser` would be launched from when no path is configured.
5902
- * The configured path is not consulted: the answer is what an empty path uses.
5903
- */
5904
- async locateFor(browser, signal) {
5905
- const stopped = () => signal?.aborted === true;
5906
- if (stopped()) throw new MhBrowserError(INTERRUPTED, WAITING_STOPPED);
5907
- if (browser !== "chrome" && browser !== "msedge" && browser !== "chromium") throw new MhBrowserError("INVALID_ARGS", "browser must be chrome, msedge, or chromium");
5908
- const env = this.locateEnv();
5909
- if (browser === "chromium") return bundledChromiumLocation(env.access);
5910
- const located = await locateInstalled(browser, env, signal);
5911
- if (stopped()) throw new MhBrowserError(INTERRUPTED, WAITING_STOPPED);
5912
- return located;
5913
- }
5914
- async act(owner, tab, op, signal) {
5915
- return this.exclusive(owner, async () => {
5916
- await this.ready;
5917
- this.refuseIfPerson(owner, tab);
5918
- const live = this.windows.get(owner, tab);
5919
- if (live === void 0) throw new MhBrowserError(UNKNOWN_TAB, UNKNOWN_TAB_REASON);
5920
- if (signal?.aborted) throw new MhBrowserError(INTERRUPTED, WAITING_STOPPED);
5921
- const linked = this.control.link(owner, signal, tab);
5922
- try {
5923
- if (live.dialogHeld && op.kind !== "handle_dialog") throw new MhBrowserError("MODAL_STATE", "a dialog is open; use browser_handle_dialog", await this.blockedView(live));
5924
- if (live.fileChooser !== void 0 && op.kind !== "file_upload") {
5925
- const blocked = await this.pageFromShown(live, this.shown.get(live.id), { surface: "snapshot" }, signal);
5926
- blocked.dialog = {
5927
- type: "filechooser",
5928
- message: live.fileChooser.isMultiple() ? "choose files (several allowed) with browser_file_upload" : "choose one file with browser_file_upload"
5929
- };
5930
- throw new MhBrowserError("MODAL_STATE", "a file chooser is open; use browser_file_upload", blocked);
5931
- }
5932
- const outcome = await this.perform(live, op, linked.signal);
5933
- if (op.kind === "fill_form" || op.kind === "select_option" || op.kind === "type" || op.kind === "file_upload") {
5934
- if (outcome.navigated) this.windows.onNavigated(live);
5935
- else this.windows.holdInput(live);
5936
- } else if (outcome.navigated) this.windows.onNavigated(live);
5937
- this.windows.touch(live);
5938
- const shown = outcome.navigated ? await this.discover(live, live.page.url(), null, signal) : await this.refreshSnapshot(live, signal);
5939
- const scoped = op.kind === "snapshot" && (op.target !== void 0 || op.depth !== void 0 || op.boxes === true) ? await this.scopedSnapshot(live, op, signal) : void 0;
5940
- this.shown.set(live.id, shown);
5941
- this.windows.noteUrl(live, live.page.url());
5942
- const view = await this.pageFromShown(live, shown, {
5943
- surface: "snapshot",
5944
- ...outcome.dialog !== void 0 ? { dialog: outcome.dialog } : {},
5945
- ...outcome.incomplete !== void 0 ? { incomplete: outcome.incomplete } : {},
5946
- ...outcome.waited !== void 0 ? { waited: outcome.waited } : {}
5947
- }, signal);
5948
- if (scoped !== void 0 && view.representation.kind === "snapshot") view.representation = {
5949
- ...view.representation,
5950
- text: scoped
5951
- };
5952
- if (!showsSnapshot(op)) {
5953
- const summary = outcome.summary ?? summaryOf(op);
5954
- if (summary !== void 0) view.summary = summary;
5955
- if (outcome.detail !== void 0 && outcome.detail !== "") view.detail = outcome.detail;
5956
- }
5957
- if (op.kind === "take_screenshot") view.summary = "";
5958
- if (outcome.shot !== void 0) view.shot = outcome.shot;
5959
- if (outcome.writes !== void 0) view.writes = outcome.writes;
5960
- return this.attachDownload(live, view, false);
5961
- } catch (error) {
5962
- if (error instanceof MhBrowserError && error.code === "TAKEN_OVER") throw error;
5963
- if (this.control.ofTab(owner, tab) === "person") throw await this.takenOver(live);
5964
- if (error instanceof MhBrowserError && error.code === "STALE_REF" && error.page === void 0) throw new MhBrowserError(error.code, error.message, await this.pageFromShown(live, this.shown.get(live.id), { surface: "snapshot" }, signal));
5965
- throw error;
5966
- } finally {
5967
- linked.release();
5968
- }
5969
- }, signal);
5970
- }
5971
- holdHandover(owner, tab) {
5972
6424
  const live = this.windows.get(owner, tab);
5973
- if (live === void 0) throw new MhBrowserError(UNKNOWN_TAB, UNKNOWN_TAB_REASON);
5974
- this.windows.holdHandover(live);
5975
- }
5976
- releaseHandover(owner) {
5977
- this.windows.releaseHandover(owner);
5978
- this.windows.markWaiting(owner, false);
5979
- }
5980
- /** `undefined` when no screenshot can be taken now: a dialog is open, or the page refused. */
5981
- capture(owner, tab, signal) {
5982
- return this.exclusive(owner, async () => {
5983
- await this.ready;
5984
- const live = this.windows.get(owner, tab);
5985
- if (live === void 0 || live.dialogHeld) return void 0;
5986
- try {
5987
- const limit = capped(signal, READ_MS);
5988
- const bytes = await untilAborted(live.page.screenshot({
5989
- type: "png",
5990
- signal: limit
5991
- }), limit);
5992
- return new Uint8Array(bytes);
5993
- } catch {
5994
- return;
5995
- }
5996
- }, signal);
5997
- }
5998
- invoke(owner, _page, call, opts) {
5999
- return this.exclusive(owner, async () => {
6000
- await this.up();
6001
- if (opts?.signal?.aborted) throw new MhBrowserError(INTERRUPTED, WAITING_STOPPED);
6002
- const signal = opts?.signal;
6003
- const sent = await runInvoke({
6004
- open: (url) => this.openAddress(owner, { url }, signal),
6005
- refreshIdle: (url, except) => this.refreshIdle(owner, url, except, signal),
6006
- send: (request) => this.sendAction(request, signal),
6007
- readFile: opts?.readFile ?? (async () => {
6008
- throw new MhBrowserError("NO_WORKSPACE", NO_WORKSPACE_REASON);
6009
- })
6010
- }, call);
6011
- await this.enforceCap(owner);
6012
- return sent;
6013
- }, opts?.signal);
6014
- }
6015
- /**
6016
- * Not queued: it opens no tab, and a long body must not hold up the
6017
- * Session's other calls. `root` is the directory the session may write.
6018
- */
6019
- async download(_owner, url, root, signal) {
6425
+ if (live === void 0 || live.dialogHeld) return void 0;
6426
+ try {
6427
+ const limit = capped(signal, READ_MS);
6428
+ const bytes = await untilAborted(live.page.screenshot({
6429
+ type: "png",
6430
+ signal: limit
6431
+ }), limit);
6432
+ return new Uint8Array(bytes);
6433
+ } catch {
6434
+ return;
6435
+ }
6436
+ }, signal);
6437
+ }
6438
+ invoke(owner, _page, call, opts) {
6439
+ return this.exclusive(owner, async () => {
6020
6440
  await this.up();
6021
- return this.saveResponse(url, root, signal);
6022
- }
6023
- controlOf(owner) {
6024
- return this.control.of(owner);
6025
- }
6026
- /** Presence registers this. A hand-back calls it with the touched presence pages. */
6027
- bindPersonTouch(fn) {
6028
- this.personTouch.add(fn);
6029
- return () => {
6030
- this.personTouch.delete(fn);
6031
- };
6032
- }
6033
- /**
6034
- * Give the browser to the person. The named tab stays in use until hand-back.
6035
- * This does not wait; the tool waits on the question card.
6036
- */
6037
- handover(owner, req, signal) {
6038
- return this.exclusive(owner, async () => {
6039
- await this.up();
6040
- if (signal?.aborted === true) throw new MhBrowserError(INTERRUPTED, WAITING_STOPPED);
6041
- if (req.tab !== void 0) {
6042
- const live = this.windows.get(owner, req.tab);
6043
- if (live === void 0) throw new MhBrowserError(UNKNOWN_TAB, UNKNOWN_TAB_REASON);
6044
- this.windows.holdHandover(live);
6045
- await this.windows.activate(live, signal).catch(() => void 0);
6046
- }
6047
- this.control.handover(owner, req.tab);
6048
- this.windows.markWaiting(owner, true);
6049
- }, signal);
6050
- }
6051
- /** Remember the Session title for its tab group. Empty when the host has none. */
6052
- noteSessionTitle(owner, title) {
6053
- this.windows.setTitle(owner, title);
6054
- }
6055
- /** Raise the window of this owner's latest tab. False when it has no tab. */
6056
- async bringToFront(owner) {
6057
- await this.ready;
6058
- const live = this.windows.latest(owner);
6059
- if (live === void 0) return false;
6060
- await untilAborted(live.page.bringToFront(), AbortSignal.timeout(READ_MS));
6061
- return true;
6062
- }
6063
- /** The person asked to see the page this Session handed over. */
6064
- async revealHandover(sessionId, signal) {
6441
+ if (opts?.signal?.aborted) throw new MhBrowserError(INTERRUPTED, WAITING_STOPPED);
6442
+ const signal = opts?.signal;
6443
+ const sent = await runInvoke({
6444
+ open: (url) => this.openAddress(owner, { url }, signal),
6445
+ refreshIdle: (url, except) => this.refreshIdle(owner, url, except, signal),
6446
+ send: (request) => this.sendAction(request, signal),
6447
+ readFile: opts?.readFile ?? (async () => {
6448
+ throw new MhBrowserError("NO_WORKSPACE", NO_WORKSPACE_REASON);
6449
+ })
6450
+ }, call);
6451
+ await this.enforceCap(owner);
6452
+ return sent;
6453
+ }, opts?.signal);
6454
+ }
6455
+ /**
6456
+ * Not queued: it opens no tab, and a long body must not hold up the
6457
+ * Session's other calls. `root` is the directory the session may write.
6458
+ */
6459
+ async download(_owner, url, root, signal) {
6460
+ await this.up();
6461
+ return this.saveResponse(url, root, signal);
6462
+ }
6463
+ controlOf(owner) {
6464
+ return this.control.of(owner);
6465
+ }
6466
+ /** Presence registers this. A hand-back calls it with the touched presence pages. */
6467
+ bindPersonTouch(fn) {
6468
+ this.personTouch.add(fn);
6469
+ return () => {
6470
+ this.personTouch.delete(fn);
6471
+ };
6472
+ }
6473
+ /**
6474
+ * Give the browser to the person. The named tab stays in use until hand-back.
6475
+ * This does not wait; the tool waits on the question card.
6476
+ */
6477
+ handover(owner, req, signal) {
6478
+ return this.exclusive(owner, async () => {
6479
+ await this.up();
6480
+ if (signal?.aborted === true) throw new MhBrowserError(INTERRUPTED, WAITING_STOPPED);
6481
+ if (req.tab !== void 0) {
6482
+ const live = this.windows.get(owner, req.tab);
6483
+ if (live === void 0) throw new MhBrowserError(UNKNOWN_TAB, UNKNOWN_TAB_REASON);
6484
+ this.windows.holdHandover(live);
6485
+ await this.windows.activate(live, signal).catch(() => void 0);
6486
+ }
6487
+ this.control.handover(owner, req.tab);
6488
+ this.windows.markWaiting(owner, true);
6489
+ }, signal);
6490
+ }
6491
+ /** Remember the Session title for its tab group. Empty when the host has none. */
6492
+ noteSessionTitle(owner, title) {
6493
+ this.windows.setTitle(owner, title);
6494
+ }
6495
+ /** Raise the window of this owner's latest tab. False when it has no tab. */
6496
+ async bringToFront(owner) {
6497
+ await this.ready;
6498
+ const live = this.windows.latest(owner);
6499
+ if (live === void 0) return false;
6500
+ await untilAborted(live.page.bringToFront(), AbortSignal.timeout(READ_MS));
6501
+ return true;
6502
+ }
6503
+ /** The person asked to see the page this Session handed over. */
6504
+ async revealHandover(sessionId, signal) {
6505
+ await this.ready;
6506
+ if (signal?.aborted === true) return { status: "not-handing-over" };
6507
+ if (!this.control.holds(sessionId)) return { status: "not-handing-over" };
6508
+ const named = this.control.namedTab(sessionId);
6509
+ const live = (named === void 0 ? void 0 : this.windows.get(sessionId, named)) ?? this.windows.latest(sessionId);
6510
+ if (live === void 0) return { status: "no-tab" };
6511
+ await untilAborted(live.page.bringToFront(), capped(signal, READ_MS));
6512
+ return { status: "revealed" };
6513
+ }
6514
+ /** The person answered. Returns the note, the operation count, and the named tab. */
6515
+ async handBack(owner, note) {
6516
+ const signal = capped(void 0, READ_MS);
6517
+ return this.exclusive(owner, async () => {
6065
6518
  await this.ready;
6066
- if (signal?.aborted === true) return { status: "not-handing-over" };
6067
- if (!this.control.holds(sessionId)) return { status: "not-handing-over" };
6068
- const named = this.control.namedTab(sessionId);
6069
- const live = (named === void 0 ? void 0 : this.windows.get(sessionId, named)) ?? this.windows.latest(sessionId);
6070
- if (live === void 0) return { status: "no-tab" };
6071
- await untilAborted(live.page.bringToFront(), capped(signal, READ_MS));
6072
- return { status: "revealed" };
6073
- }
6074
- /** The person answered. Returns the note, the operation count, and the named tab. */
6075
- async handBack(owner, note) {
6076
- const signal = capped(void 0, READ_MS);
6077
- return this.exclusive(owner, async () => {
6078
- await this.ready;
6079
- const taken = this.control.finish(owner);
6080
- if (taken === void 0) throw new MhBrowserError("INVALID_ARGS", "the browser is not with the person");
6081
- this.windows.releaseHandover(owner);
6082
- this.windows.markWaiting(owner, false);
6083
- const urls = this.presenceUrls(owner, taken.tabs);
6084
- for (const touch of this.personTouch) touch(owner, urls);
6085
- const page = await this.snapshotNamed(owner, taken.tab, signal);
6086
- return {
6087
- ...taken,
6088
- urls,
6089
- ...note !== void 0 && note !== "" ? { note } : {},
6090
- ...page !== void 0 ? { page } : {}
6091
- };
6092
- }, signal);
6093
- }
6094
- /** A stopped handover gives control back. A finished hand-back is left alone. */
6095
- releaseIfHeld(owner) {
6096
- if (!this.control.releaseIfHeld(owner)) return;
6519
+ const taken = this.control.finish(owner);
6520
+ if (taken === void 0) throw new MhBrowserError("INVALID_ARGS", "the browser is not with the person");
6097
6521
  this.windows.releaseHandover(owner);
6098
6522
  this.windows.markWaiting(owner, false);
6099
- this.relaunchIfIdle();
6100
- }
6101
- /**
6102
- * The person took over between turns. The next message they send is the
6103
- * hand-back. A handover that is still waiting on its card is not.
6104
- * The addresses are read before a waiting restart closes the pages.
6105
- */
6106
- takePersonHandback(owner) {
6107
- const taken = this.control.takePerson(owner);
6108
- if (taken === void 0) return void 0;
6109
6523
  const urls = this.presenceUrls(owner, taken.tabs);
6110
- this.windows.releaseHandover(owner);
6111
- this.relaunchIfIdle();
6524
+ for (const touch of this.personTouch) touch(owner, urls);
6525
+ const page = await this.snapshotNamed(owner, taken.tab, signal);
6112
6526
  return {
6113
6527
  ...taken,
6114
- urls
6528
+ urls,
6529
+ ...note !== void 0 && note !== "" ? { note } : {},
6530
+ ...page !== void 0 ? { page } : {}
6115
6531
  };
6116
- }
6117
- /**
6118
- * Read one address. A known origin is tried on the request channel first.
6119
- * A readable Agent View found on a tab this call opened is returned without
6120
- * the tab, and that tab is not listed as closed.
6121
- */
6122
- async openAddress(owner, item, signal, reveal = false) {
6123
- if (!openableAddress(item.url)) return {
6532
+ }, signal);
6533
+ }
6534
+ /** A stopped handover gives control back. A finished hand-back is left alone. */
6535
+ releaseIfHeld(owner) {
6536
+ if (!this.control.releaseIfHeld(owner)) return;
6537
+ this.windows.releaseHandover(owner);
6538
+ this.windows.markWaiting(owner, false);
6539
+ this.relaunchIfIdle();
6540
+ }
6541
+ /**
6542
+ * The person took over between turns. The next message they send is the
6543
+ * hand-back. A handover that is still waiting on its card is not.
6544
+ * The addresses are read before a waiting restart closes the pages.
6545
+ */
6546
+ takePersonHandback(owner) {
6547
+ const taken = this.control.takePerson(owner);
6548
+ if (taken === void 0) return void 0;
6549
+ const urls = this.presenceUrls(owner, taken.tabs);
6550
+ this.windows.releaseHandover(owner);
6551
+ this.relaunchIfIdle();
6552
+ return {
6553
+ ...taken,
6554
+ urls
6555
+ };
6556
+ }
6557
+ /**
6558
+ * Read one address. A known origin is tried on the request channel first.
6559
+ * A readable Agent View found on a tab this call opened is returned without
6560
+ * the tab, and that tab is not listed as closed.
6561
+ */
6562
+ async openAddress(owner, item, signal, reveal = false) {
6563
+ if (!openableAddress(item.url)) return {
6564
+ url: item.url,
6565
+ reason: OPEN_ADDRESS_REASON
6566
+ };
6567
+ const wantsTab = owner === "person" || item.snapshot === true || item.waitFor !== void 0;
6568
+ if (!wantsTab && this.knownOrigin(item.url)) {
6569
+ const via = await this.readKnown(owner, item.url, signal);
6570
+ if (via === STOPPED) return {
6124
6571
  url: item.url,
6125
- reason: OPEN_ADDRESS_REASON
6572
+ reason: WAITING_STOPPED
6126
6573
  };
6127
- const wantsTab = owner === "person" || item.snapshot === true || item.waitFor !== void 0;
6128
- if (!wantsTab && this.knownOrigin(item.url)) {
6129
- const via = await this.readKnown(owner, item.url, signal);
6130
- if (via === STOPPED) return {
6131
- url: item.url,
6132
- reason: WAITING_STOPPED
6133
- };
6134
- if (via !== void 0) return via;
6135
- }
6136
- const opened = await this.openOne(owner, item.url, item.waitFor, signal, item.snapshot === true, reveal);
6137
- this.keepAgentView(opened);
6138
- if (opened.live !== void 0 && !wantsTab && opened.fresh && this.closable(owner, opened.live) && "representation" in opened.view && opened.view.representation.kind === "agent-view") {
6139
- await this.windows.closeTab(opened.live);
6140
- const view = { ...opened.view };
6141
- delete view.tab;
6142
- return view;
6143
- }
6144
- return opened.view;
6574
+ if (via !== void 0) return via;
6575
+ }
6576
+ const opened = await this.openOne(owner, item.url, item.waitFor, signal, item.snapshot === true, reveal);
6577
+ this.keepAgentView(opened);
6578
+ if (opened.live !== void 0 && !wantsTab && opened.fresh && this.closable(owner, opened.live) && "representation" in opened.view && opened.view.representation.kind === "agent-view") {
6579
+ await this.windows.closeTab(opened.live);
6580
+ const view = { ...opened.view };
6581
+ delete view.tab;
6582
+ return view;
6145
6583
  }
6146
- /** A tab this call opened can be closed again unless the person took it or it holds input. */
6147
- closable(owner, live) {
6148
- return this.control.ofTab(owner, live.id) !== "person" && !live.occupied;
6584
+ return opened.view;
6585
+ }
6586
+ /** A tab this call opened can be closed again unless the person took it or it holds input. */
6587
+ closable(owner, live) {
6588
+ return this.control.ofTab(owner, live.id) !== "person" && !live.occupied;
6589
+ }
6590
+ knownOrigin(url) {
6591
+ try {
6592
+ return this.agentViewOrigins.has(new URL(url).origin);
6593
+ } catch {
6594
+ return false;
6149
6595
  }
6150
- knownOrigin(url) {
6151
- try {
6152
- return this.agentViewOrigins.has(new URL(url).origin);
6153
- } catch {
6154
- return false;
6155
- }
6596
+ }
6597
+ rememberOrigin(url) {
6598
+ try {
6599
+ this.agentViewOrigins.add(new URL(url).origin);
6600
+ } catch {}
6601
+ }
6602
+ /** A readable Agent View puts its origin on the list and keeps the document for the next read. */
6603
+ keepAgentView(opened) {
6604
+ if (opened.live === void 0) return;
6605
+ if (!("representation" in opened.view)) return;
6606
+ const representation = opened.view.representation;
6607
+ if (!(representation.kind === "agent-view" || representation.kind === "snapshot" && representation.agentView !== void 0)) return;
6608
+ this.rememberOrigin(opened.view.url);
6609
+ const shown = this.shown.get(opened.live.id);
6610
+ if (shown?.kind === "agent-view") this.rememberDocument(shown.pageUrl, shown);
6611
+ }
6612
+ /**
6613
+ * Read a known origin without a tab. `undefined` means this page has to be
6614
+ * opened in a tab: nothing declared, the declaration could not be read, or
6615
+ * the request failed. The origin stays on the list either way. A stop
6616
+ * ends the read without falling back to a tab.
6617
+ */
6618
+ async readKnown(owner, url, signal) {
6619
+ const key = canonical(url);
6620
+ const previous = this.documents.get(key);
6621
+ const servedAtPage = previous?.kind === "agent-view" && previous.href !== void 0 && canonical(previous.href) === canonical(previous.pageUrl);
6622
+ let response;
6623
+ try {
6624
+ const got = await this.fetchSameOrigin(url, PAGE_ACCEPT, servedAtPage ? previous.etag : void 0, signal);
6625
+ if (signal?.aborted === true) return STOPPED;
6626
+ if (got === void 0) return void 0;
6627
+ response = got;
6628
+ } catch {
6629
+ return signal?.aborted === true ? STOPPED : void 0;
6630
+ }
6631
+ if (response.status === 304 && previous?.kind === "agent-view") return this.pageOfShown(owner, previous);
6632
+ const text = new TextDecoder().decode(response.body);
6633
+ const pageUrl = canonical(response.finalUrl === "" ? url : response.finalUrl);
6634
+ const cached = this.documents.get(pageUrl);
6635
+ const shown = await loadShown({
6636
+ pageUrl,
6637
+ ...optionalFragment(response.finalUrl === "" ? url : response.finalUrl),
6638
+ snapshot: "",
6639
+ main: {
6640
+ status: response.status,
6641
+ ...response.mediaType !== void 0 ? { mediaType: response.mediaType } : {},
6642
+ finalUrl: response.finalUrl === "" ? url : response.finalUrl,
6643
+ ...response.link !== void 0 ? { link: response.link } : {},
6644
+ ...response.etag !== void 0 ? { etag: response.etag } : {},
6645
+ body: text
6646
+ },
6647
+ domLinks: linksInHtml(text, response.finalUrl === "" ? url : response.finalUrl),
6648
+ ...cached !== void 0 ? { previous: cached } : {},
6649
+ relocate: false,
6650
+ fetch: (target, accept, ifNoneMatch) => this.fetchForRead(target, accept, ifNoneMatch, signal)
6651
+ });
6652
+ if (stopped(signal)) return STOPPED;
6653
+ if (shown.kind !== "agent-view") return void 0;
6654
+ this.rememberDocument(pageUrl, shown);
6655
+ this.rememberOrigin(pageUrl);
6656
+ return this.pageOfShown(owner, shown);
6657
+ }
6658
+ /** Keep the newest Agent Views. A dropped one is read in full the next time. */
6659
+ rememberDocument(url, shown) {
6660
+ const key = canonical(url);
6661
+ this.documents.delete(key);
6662
+ this.documents.set(key, shown);
6663
+ while (this.documents.size > DOCUMENT_CAP) {
6664
+ const oldest = this.documents.keys().next().value;
6665
+ if (oldest === void 0) return;
6666
+ this.documents.delete(oldest);
6667
+ }
6668
+ }
6669
+ /** One page from a document, with no tab. */
6670
+ pageOfShown(owner, shown) {
6671
+ const view = {
6672
+ url: shown.pageUrl,
6673
+ title: "",
6674
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
6675
+ representation: shown.kind === "agent-view" ? {
6676
+ kind: "agent-view",
6677
+ text: shown.text,
6678
+ ...shown.version !== void 0 ? { version: shown.version } : {},
6679
+ ...shown.href !== void 0 ? { href: shown.href } : {}
6680
+ } : {
6681
+ kind: "snapshot",
6682
+ text: shown.snapshot,
6683
+ ...shown.agentViewError !== void 0 ? { agentViewError: shown.agentViewError } : {}
6684
+ },
6685
+ inPresence: this.book.isShown(owner, canonical(shown.pageUrl))
6686
+ };
6687
+ if (shown.fragment !== void 0) view.fragment = shown.fragment;
6688
+ if (shown.status !== void 0) view.status = shown.status;
6689
+ if (shown.mediaType !== void 0) view.mediaType = shown.mediaType;
6690
+ if (shown.body !== void 0) view.body = shown.body;
6691
+ return view;
6692
+ }
6693
+ /**
6694
+ * GET that follows same-origin redirects only. `undefined` when it cannot.
6695
+ * A body that is neither text nor an Agent View is not read: the page then
6696
+ * goes to a tab, which loads it anyway.
6697
+ */
6698
+ async fetchSameOrigin(url, accept, ifNoneMatch, signal) {
6699
+ const context = this.context;
6700
+ if (context === void 0) return void 0;
6701
+ let current = url;
6702
+ let origin;
6703
+ try {
6704
+ origin = new URL(url).origin;
6705
+ } catch {
6706
+ return;
6156
6707
  }
6157
- rememberOrigin(url) {
6158
- try {
6159
- this.agentViewOrigins.add(new URL(url).origin);
6160
- } catch {}
6161
- }
6162
- /** A readable Agent View puts its origin on the list and keeps the document for the next read. */
6163
- keepAgentView(opened) {
6164
- if (opened.live === void 0) return;
6165
- if (!("representation" in opened.view)) return;
6166
- const representation = opened.view.representation;
6167
- if (!(representation.kind === "agent-view" || representation.kind === "snapshot" && representation.agentView !== void 0)) return;
6168
- this.rememberOrigin(opened.view.url);
6169
- const shown = this.shown.get(opened.live.id);
6170
- if (shown?.kind === "agent-view") this.rememberDocument(shown.pageUrl, shown);
6171
- }
6172
- /**
6173
- * Read a known origin without a tab. `undefined` means this page has to be
6174
- * opened in a tab: nothing declared, the declaration could not be read, or
6175
- * the request failed. The origin stays on the list either way. A stop
6176
- * ends the read without falling back to a tab.
6177
- */
6178
- async readKnown(owner, url, signal) {
6179
- const key = canonical(url);
6180
- const previous = this.documents.get(key);
6181
- const servedAtPage = previous?.kind === "agent-view" && previous.href !== void 0 && canonical(previous.href) === canonical(previous.pageUrl);
6182
- let response;
6183
- try {
6184
- const got = await this.fetchSameOrigin(url, PAGE_ACCEPT, servedAtPage ? previous.etag : void 0, signal);
6185
- if (signal?.aborted === true) return STOPPED;
6186
- if (got === void 0) return void 0;
6187
- response = got;
6188
- } catch {
6189
- return signal?.aborted === true ? STOPPED : void 0;
6190
- }
6191
- if (response.status === 304 && previous?.kind === "agent-view") return this.pageOfShown(owner, previous);
6192
- const text = new TextDecoder().decode(response.body);
6193
- const pageUrl = canonical(response.finalUrl === "" ? url : response.finalUrl);
6194
- const cached = this.documents.get(pageUrl);
6195
- const shown = await loadShown({
6196
- pageUrl,
6197
- ...optionalFragment(response.finalUrl === "" ? url : response.finalUrl),
6198
- snapshot: "",
6199
- main: {
6200
- status: response.status,
6201
- ...response.mediaType !== void 0 ? { mediaType: response.mediaType } : {},
6202
- finalUrl: response.finalUrl === "" ? url : response.finalUrl,
6203
- ...response.link !== void 0 ? { link: response.link } : {},
6204
- ...response.etag !== void 0 ? { etag: response.etag } : {},
6205
- body: text
6206
- },
6207
- domLinks: linksInHtml(text, response.finalUrl === "" ? url : response.finalUrl),
6208
- ...cached !== void 0 ? { previous: cached } : {},
6209
- relocate: false,
6210
- fetch: (target, accept, ifNoneMatch) => this.fetchForRead(target, accept, ifNoneMatch, signal)
6708
+ for (let hop = 0; hop < 10; hop += 1) {
6709
+ const headers = { accept };
6710
+ if (ifNoneMatch !== void 0 && hop === 0) headers["if-none-match"] = ifNoneMatch;
6711
+ const response = await context.request.get(current, {
6712
+ headers,
6713
+ maxRedirects: 0,
6714
+ failOnStatusCode: false,
6715
+ ...signal !== void 0 ? { signal } : {}
6211
6716
  });
6212
- if (stopped(signal)) return STOPPED;
6213
- if (shown.kind !== "agent-view") return void 0;
6214
- this.rememberDocument(pageUrl, shown);
6215
- this.rememberOrigin(pageUrl);
6216
- return this.pageOfShown(owner, shown);
6217
- }
6218
- /** Keep the newest Agent Views. A dropped one is read in full the next time. */
6219
- rememberDocument(url, shown) {
6220
- const key = canonical(url);
6221
- this.documents.delete(key);
6222
- this.documents.set(key, shown);
6223
- while (this.documents.size > DOCUMENT_CAP) {
6224
- const oldest = this.documents.keys().next().value;
6225
- if (oldest === void 0) return;
6226
- this.documents.delete(oldest);
6227
- }
6228
- }
6229
- /** One page from a document, with no tab. */
6230
- pageOfShown(owner, shown) {
6231
- const view = {
6232
- url: shown.pageUrl,
6233
- title: "",
6234
- observedAt: (/* @__PURE__ */ new Date()).toISOString(),
6235
- representation: shown.kind === "agent-view" ? {
6236
- kind: "agent-view",
6237
- text: shown.text,
6238
- ...shown.version !== void 0 ? { version: shown.version } : {},
6239
- ...shown.href !== void 0 ? { href: shown.href } : {}
6240
- } : {
6241
- kind: "snapshot",
6242
- text: shown.snapshot,
6243
- ...shown.agentViewError !== void 0 ? { agentViewError: shown.agentViewError } : {}
6244
- },
6245
- inPresence: this.book.isShown(owner, canonical(shown.pageUrl))
6246
- };
6247
- if (shown.fragment !== void 0) view.fragment = shown.fragment;
6248
- if (shown.status !== void 0) view.status = shown.status;
6249
- if (shown.mediaType !== void 0) view.mediaType = shown.mediaType;
6250
- if (shown.body !== void 0) view.body = shown.body;
6251
- return view;
6252
- }
6253
- /**
6254
- * GET that follows same-origin redirects only. `undefined` when it cannot.
6255
- * A body that is neither text nor an Agent View is not read: the page then
6256
- * goes to a tab, which loads it anyway.
6257
- */
6258
- async fetchSameOrigin(url, accept, ifNoneMatch, signal) {
6259
- const context = this.context;
6260
- if (context === void 0) return void 0;
6261
- let current = url;
6262
- let origin;
6263
- try {
6264
- origin = new URL(url).origin;
6265
- } catch {
6266
- return;
6267
- }
6268
- for (let hop = 0; hop < 10; hop += 1) {
6269
- const headers = { accept };
6270
- if (ifNoneMatch !== void 0 && hop === 0) headers["if-none-match"] = ifNoneMatch;
6271
- const response = await context.request.get(current, {
6272
- headers,
6273
- maxRedirects: 0,
6274
- failOnStatusCode: false,
6275
- ...signal !== void 0 ? { signal } : {}
6276
- });
6277
- const status = response.status();
6278
- const location = response.headers().location;
6279
- if (status >= 300 && status < 400 && location !== void 0 && location !== "") {
6280
- let next;
6281
- try {
6282
- next = new URL(location, current);
6283
- } catch {
6284
- return;
6285
- }
6286
- if (next.origin !== origin) return void 0;
6287
- current = next.href;
6288
- continue;
6289
- }
6290
- const headerMap = response.headers();
6291
- const mediaType = headerMap["content-type"];
6292
- const body = {
6293
- kind: "response",
6294
- finalUrl: current,
6295
- status,
6296
- body: readsAsText(mediaType) ? new Uint8Array(await untilAborted(response.body(), capped(signal, READ_MS))) : /* @__PURE__ */ new Uint8Array()
6297
- };
6298
- const etag = headerMap.etag;
6299
- const link = headerMap.link;
6300
- if (mediaType !== void 0) body.mediaType = mediaType;
6301
- if (etag !== void 0) body.etag = etag;
6302
- if (link !== void 0) body.link = link;
6303
- return body;
6304
- }
6305
- }
6306
- async openOne(owner, url, waitFor, signal, snapshot = false, reveal = false) {
6307
- assertWaitFor(waitFor);
6308
- const reused = this.idleTabOn(owner, url);
6309
- const fresh = reused === void 0;
6310
- let live;
6311
- try {
6312
- live = reused ?? await this.windows.openBlank(owner, signal);
6313
- } catch (error) {
6314
- if (signal?.aborted === true || isInterrupted(error)) return {
6315
- view: {
6316
- url,
6317
- reason: WAITING_STOPPED
6318
- },
6319
- fresh
6320
- };
6321
- throw error;
6322
- }
6323
- const linked = this.control.link(owner, signal, live.id);
6324
- if (reveal && !linked.signal.aborted) await live.page.bringToFront().catch(() => void 0);
6325
- const nextDialog = this.windows.nextDialog(live);
6326
- try {
6327
- let seenDialog;
6328
- const dialogDuringGoto = nextDialog.dialog.then((dialog) => {
6329
- seenDialog = dialog;
6330
- return dialog;
6331
- });
6332
- let navigationError;
6333
- let response = null;
6334
- const raced = this.goto(live.page, url, linked.signal).then((value) => {
6335
- response = value;
6336
- return "navigated";
6337
- }, (error) => {
6338
- navigationError = error;
6339
- return "failed";
6340
- });
6341
- const winner = await Promise.race([raced, dialogDuringGoto.then((dialog) => ({ dialog }))]);
6342
- nextDialog.cancel();
6343
- if (winner === "failed" && seenDialog === void 0) {
6344
- if (isDownloadStart(navigationError) || live.pendingDownload !== void 0) {
6345
- const view = await this.pageFromShown(live, this.shown.get(live.id), void 0, signal);
6346
- if (view.url === "" || view.url === "about:blank") view.url = canonical(url);
6347
- this.applyDocumentType(live, view);
6348
- return {
6349
- view: await this.attachDownload(live, view, true),
6350
- fresh,
6351
- live
6352
- };
6353
- }
6354
- throw navigationError;
6355
- }
6356
- if (linked.signal.aborted) return {
6357
- view: {
6358
- tab: live.id,
6359
- url,
6360
- reason: WAITING_STOPPED
6361
- },
6362
- fresh,
6363
- live
6364
- };
6365
- const current = live.page.url();
6366
- const address = current === "about:blank" ? url : current;
6367
- this.windows.noteUrl(live, address);
6368
- const held = seenDialog ?? (typeof winner === "object" ? winner.dialog : void 0);
6369
- const dialog = held === void 0 ? void 0 : {
6370
- type: held.type(),
6371
- message: held.message()
6372
- };
6373
- if (held !== void 0) this.windows.holdDialog(live, held);
6374
- else this.windows.onNavigated(live);
6375
- const load = dialog !== void 0 ? {
6376
- load: false,
6377
- pendingRequests: 0,
6378
- dialog
6379
- } : await waitForLoad(live.page, linked.signal);
6380
- if (load.dialog !== void 0) this.windows.holdDialog(live);
6381
- let waited;
6382
- if (waitFor !== void 0 && load.dialog === void 0) {
6383
- const text = await waitForText(live.page, waitFor, linked.signal);
6384
- waited = {
6385
- met: text.met,
6386
- seconds: text.seconds
6387
- };
6388
- if (text.dialog !== void 0) this.windows.holdDialog(live);
6717
+ const status = response.status();
6718
+ const location = response.headers().location;
6719
+ if (status >= 300 && status < 400 && location !== void 0 && location !== "") {
6720
+ let next;
6721
+ try {
6722
+ next = new URL(location, current);
6723
+ } catch {
6724
+ return;
6389
6725
  }
6390
- this.windows.touch(live);
6391
- const shown = load.dialog !== void 0 ? await loadShown({
6392
- pageUrl: canonical(address),
6393
- ...optionalFragment(address),
6394
- snapshot: "",
6395
- relocate: false,
6396
- fetch: (target, accept, ifNoneMatch) => this.fetchForRead(target, accept, ifNoneMatch, signal)
6397
- }) : await this.discover(live, address, response, signal);
6398
- this.shown.set(live.id, shown);
6399
- const view = await this.pageFromShown(live, shown, {
6400
- ...snapshot ? { surface: "snapshot" } : {},
6401
- ...load.load ? {} : { incomplete: {
6402
- load: load.load,
6403
- pendingRequests: load.pendingRequests
6404
- } },
6405
- ...load.dialog !== void 0 ? { dialog: load.dialog } : {},
6406
- ...waited !== void 0 ? { waited } : {}
6407
- }, signal);
6408
- return {
6409
- view: await this.attachDownload(live, view, false),
6410
- fresh,
6411
- live
6412
- };
6413
- } catch (error) {
6414
- nextDialog.cancel();
6415
- if (this.control.ofTab(owner, live.id) === "person") throw await this.takenOver(live);
6416
- if (linked.signal.aborted || error instanceof MhBrowserError && error.code === "INTERRUPTED") return {
6417
- view: {
6418
- tab: live.id,
6419
- url,
6420
- reason: WAITING_STOPPED
6421
- },
6422
- fresh,
6423
- live
6424
- };
6425
- return {
6426
- view: {
6427
- tab: live.id,
6428
- url,
6429
- reason: error instanceof Error ? error.message : String(error)
6430
- },
6431
- fresh,
6432
- live
6433
- };
6434
- } finally {
6435
- linked.release();
6726
+ if (next.origin !== origin) return void 0;
6727
+ current = next.href;
6728
+ continue;
6436
6729
  }
6437
- }
6438
- async perform(live, op, signal) {
6439
- if (op.kind === "snapshot") return { navigated: false };
6440
- if (op.kind === "find") return {
6441
- navigated: false,
6442
- summary: findInSnapshot(await this.aria(live, signal), op)
6730
+ const headerMap = response.headers();
6731
+ const mediaType = headerMap["content-type"];
6732
+ const body = {
6733
+ kind: "response",
6734
+ finalUrl: current,
6735
+ status,
6736
+ body: readsAsText(mediaType) ? new Uint8Array(await untilAborted(response.body(), capped(signal, READ_MS))) : /* @__PURE__ */ new Uint8Array()
6443
6737
  };
6444
- if (op.kind === "evaluate") {
6445
- const snapshot = this.shown.get(live.id)?.snapshot ?? "";
6446
- const target = op.target === void 0 ? void 0 : await locate(live.page, op.target, snapshot);
6447
- return this.evaluateOn(live, op, target, signal);
6448
- }
6449
- if (op.kind === "take_screenshot") return this.shoot(live, op, signal);
6450
- if (op.kind === "file_upload") return this.uploadHeld(live, op, signal);
6451
- if (op.kind === "wait_for") {
6452
- const waitFor = waitFrom(op);
6453
- assertWaitFor(waitFor);
6454
- const text = await waitForText(live.page, waitFor, signal);
6455
- if (text.dialog !== void 0) this.windows.holdDialog(live);
6456
- return {
6457
- navigated: false,
6458
- waited: {
6459
- met: text.met,
6460
- seconds: text.seconds
6461
- },
6462
- ...text.dialog !== void 0 ? { dialog: text.dialog } : {}
6463
- };
6464
- }
6465
- if (op.kind === "handle_dialog") {
6466
- const dialog = live.pendingDialog;
6467
- if (dialog === void 0) throw new MhBrowserError("INVALID_ARGS", "this page has no dialog");
6468
- const before = live.page.url();
6469
- if (op.accept) await (op.promptText !== void 0 ? dialog.accept(op.promptText) : dialog.accept());
6470
- else await dialog.dismiss();
6471
- this.windows.clearDialog(live);
6472
- const navigated = live.page.url() !== before;
6473
- return {
6474
- navigated,
6475
- ...settled(await settleAction(live.page, navigated, void 0, signal))
6476
- };
6477
- }
6478
- const requests = trackActionRequests(live.page);
6479
- const nextDialog = this.windows.nextDialog(live);
6480
- const chooser = watchFileChooser(live.page);
6481
- const snapshot = this.shown.get(live.id)?.snapshot ?? "";
6482
- this.windows.beginDispatch(live.page);
6483
- try {
6484
- const finished = runAction(live.page, op, snapshot, signal).then((navigated) => ({
6485
- kind: "done",
6486
- navigated
6487
- }));
6488
- const appeared = nextDialog.dialog.then((dialog) => ({
6489
- kind: "dialog",
6490
- dialog
6491
- }));
6492
- const chose = chooser.opened.then((opened) => ({
6493
- kind: "chooser",
6494
- opened
6495
- }));
6496
- const winner = await Promise.race([
6497
- finished,
6498
- appeared,
6499
- chose
6500
- ]).finally(() => {
6501
- this.windows.endDispatch(live.page);
6502
- });
6503
- if (winner.kind === "dialog") {
6504
- this.windows.holdDialog(live, winner.dialog);
6505
- finished.catch(() => void 0);
6506
- return {
6507
- navigated: false,
6508
- dialog: {
6509
- type: winner.dialog.type(),
6510
- message: winner.dialog.message()
6511
- }
6512
- };
6513
- }
6514
- if (winner.kind === "chooser") {
6515
- finished.catch(() => void 0);
6516
- return {
6517
- navigated: false,
6518
- dialog: this.chooserHeld(live, winner.opened)
6519
- };
6520
- }
6521
- const settledLoad = await Promise.race([settleAction(live.page, winner.navigated, requests, signal), chooser.opened.then((opened) => ({
6522
- load: true,
6523
- pendingRequests: 0,
6524
- dialog: this.chooserHeld(live, opened)
6525
- }))]);
6526
- return {
6527
- navigated: winner.navigated,
6528
- ...settled(settledLoad)
6529
- };
6530
- } finally {
6531
- requests.stop();
6532
- nextDialog.cancel();
6533
- chooser.stop();
6534
- }
6535
- }
6536
- /**
6537
- * `browser_evaluate`. A dialog the function opens is held like any other; a
6538
- * stop or a takeover ends the wait and still reports the writes already sent.
6539
- */
6540
- async evaluateOn(live, op, target, signal) {
6541
- const nextDialog = this.windows.nextDialog(live);
6542
- let navigated = false;
6543
- const onNav = (frame) => {
6544
- if (frame.parentFrame() === null) navigated = true;
6738
+ const etag = headerMap.etag;
6739
+ const link = headerMap.link;
6740
+ if (mediaType !== void 0) body.mediaType = mediaType;
6741
+ if (etag !== void 0) body.etag = etag;
6742
+ if (link !== void 0) body.link = link;
6743
+ return body;
6744
+ }
6745
+ }
6746
+ async openOne(owner, url, waitFor, signal, snapshot = false, reveal = false) {
6747
+ assertWaitFor(waitFor);
6748
+ const reused = this.idleTabOn(owner, url);
6749
+ const fresh = reused === void 0;
6750
+ let live;
6751
+ try {
6752
+ live = reused ?? await this.windows.openBlank(owner, signal);
6753
+ } catch (error) {
6754
+ if (signal?.aborted === true || isInterrupted(error)) return {
6755
+ view: {
6756
+ url,
6757
+ reason: WAITING_STOPPED
6758
+ },
6759
+ fresh
6545
6760
  };
6546
- live.page.on("framenavigated", onNav);
6547
- try {
6548
- const evaluated = await evaluateMarked(live.page, op.function, target, op.callId, signal, nextDialog.dialog);
6549
- const writes = formatWrites(evaluated.writes);
6550
- const counted = evaluated.writes.length === 0 ? {} : { writes: evaluated.writes };
6551
- if (evaluated.kind === "stopped") {
6552
- const note = writes === "" ? "" : `\n${writes}`;
6553
- if (this.control.ofTab(live.owner, live.id) === "person") throw await this.takenOver(live, note);
6554
- throw new MhBrowserError(INTERRUPTED, `${WAITING_STOPPED}${note}`);
6555
- }
6556
- if (evaluated.kind === "dialog") {
6557
- this.windows.holdDialog(live, evaluated.dialog);
6761
+ throw error;
6762
+ }
6763
+ const linked = this.control.link(owner, signal, live.id);
6764
+ if (reveal && !linked.signal.aborted) await live.page.bringToFront().catch(() => void 0);
6765
+ const nextDialog = this.windows.nextDialog(live);
6766
+ try {
6767
+ let seenDialog;
6768
+ const dialogDuringGoto = nextDialog.dialog.then((dialog) => {
6769
+ seenDialog = dialog;
6770
+ return dialog;
6771
+ });
6772
+ let navigationError;
6773
+ let response = null;
6774
+ const raced = this.goto(live.page, url, linked.signal).then((value) => {
6775
+ response = value;
6776
+ return "navigated";
6777
+ }, (error) => {
6778
+ navigationError = error;
6779
+ return "failed";
6780
+ });
6781
+ const winner = await Promise.race([raced, dialogDuringGoto.then((dialog) => ({ dialog }))]);
6782
+ nextDialog.cancel();
6783
+ if (winner === "failed" && seenDialog === void 0) {
6784
+ if (isDownloadStart(navigationError) || live.pendingDownload !== void 0) {
6785
+ const view = await this.pageFromShown(live, this.shown.get(live.id), void 0, signal);
6786
+ if (view.url === "" || view.url === "about:blank") view.url = canonical(url);
6787
+ this.applyDocumentType(live, view);
6558
6788
  return {
6559
- navigated: false,
6560
- dialog: {
6561
- type: evaluated.dialog.type(),
6562
- message: evaluated.dialog.message()
6563
- },
6564
- summary: "",
6565
- detail: writes,
6566
- ...counted
6789
+ view: await this.attachDownload(live, view, true),
6790
+ fresh,
6791
+ live
6567
6792
  };
6568
6793
  }
6569
- if (evaluated.kind === "navigated") return {
6570
- navigated: true,
6571
- summary: NAVIGATED_DURING_EVALUATE,
6572
- detail: writes,
6573
- ...counted
6574
- };
6575
- return {
6576
- navigated,
6577
- summary: evaluated.value,
6578
- detail: writes,
6579
- ...counted
6580
- };
6581
- } finally {
6582
- live.page.off("framenavigated", onNav);
6583
- nextDialog.cancel();
6794
+ throw navigationError;
6584
6795
  }
6585
- }
6586
- async uploadHeld(live, op, signal) {
6587
- const chooser = live.fileChooser;
6588
- if (chooser === void 0) throw new MhBrowserError("INVALID_ARGS", "No file chooser visible");
6589
- const paths = op.paths;
6590
- if (paths === void 0 || paths.length === 0) {
6591
- live.fileChooser = void 0;
6592
- return { navigated: false };
6593
- }
6594
- const requests = trackActionRequests(live.page);
6595
- let navigated = false;
6596
- const onNav = (frame) => {
6597
- if (frame.parentFrame() === null) navigated = true;
6598
- };
6599
- live.page.on("framenavigated", onNav);
6600
- this.windows.beginDispatch(live.page);
6601
- try {
6602
- await chooser.setFiles(paths, signal === void 0 ? {} : { signal });
6603
- live.fileChooser = void 0;
6604
- await settleAction(live.page, navigated, requests, signal);
6605
- return { navigated };
6606
- } finally {
6607
- live.page.off("framenavigated", onNav);
6608
- this.windows.endDispatch(live.page);
6609
- requests.stop();
6610
- }
6611
- }
6612
- async shoot(live, op, signal) {
6613
- if (op.fullPage === true && op.target !== void 0) throw new MhBrowserError("INVALID_ARGS", "fullPage cannot be used with element screenshots.");
6614
- const type = op.type ?? "png";
6615
- const snapshot = this.shown.get(live.id)?.snapshot ?? "";
6616
- const locator = op.target === void 0 ? void 0 : await locate(live.page, op.target, snapshot);
6617
- const options = {
6618
- type,
6619
- ...type === "jpeg" ? { quality: 90 } : {},
6620
- ...op.scale !== void 0 ? { scale: op.scale } : {},
6621
- ...op.fullPage === true ? { fullPage: true } : {},
6622
- ...signal !== void 0 ? { signal } : {}
6623
- };
6624
- const bytes = locator === void 0 ? await live.page.screenshot(options) : await locator.screenshot(options);
6625
- return {
6626
- navigated: false,
6627
- shot: {
6628
- mediaType: `image/${type}`,
6629
- bytes: new Uint8Array(bytes)
6630
- }
6631
- };
6632
- }
6633
- /** A snapshot limited to a target, a depth, or boxes. Refs still resolve against the full one. */
6634
- async scopedSnapshot(tab, op, signal) {
6635
- const options = {
6636
- mode: "ai",
6637
- ...op.depth !== void 0 ? { depth: op.depth } : {},
6638
- ...op.boxes === true ? { boxes: true } : {}
6639
- };
6640
- const snapshot = this.shown.get(tab.id)?.snapshot ?? "";
6641
- const limit = capped(signal, READ_MS);
6642
- if (op.target !== void 0) return untilAborted((await locate(tab.page, op.target, snapshot)).ariaSnapshot(options), limit);
6643
- return untilAborted(tab.page.ariaSnapshot(options), limit);
6644
- }
6645
- /** A file chooser the action opened. The tab stays in use until it navigates. */
6646
- chooserHeld(live, chooser) {
6647
- live.fileChooser = chooser;
6648
- this.windows.holdInput(live);
6649
- return {
6650
- type: "filechooser",
6651
- message: chooser.isMultiple() ? "choose files (several allowed) with browser_file_upload" : "choose one file with browser_file_upload"
6652
- };
6653
- }
6654
- async refreshSnapshot(tab, signal) {
6655
- const previous = this.shown.get(tab.id);
6656
- const snapshot = tab.dialogHeld ? "" : await this.aria(tab, signal);
6657
- if (previous === void 0) return {
6658
- pageUrl: canonical(tab.page.url()),
6659
- digest: "",
6660
- kind: "snapshot",
6661
- text: snapshot,
6662
- snapshot
6796
+ if (linked.signal.aborted) return {
6797
+ view: {
6798
+ tab: live.id,
6799
+ url,
6800
+ reason: WAITING_STOPPED
6801
+ },
6802
+ fresh,
6803
+ live
6663
6804
  };
6664
- return {
6665
- ...previous,
6666
- snapshot
6805
+ const current = live.page.url();
6806
+ const address = current === "about:blank" ? url : current;
6807
+ this.windows.noteUrl(live, address);
6808
+ const held = seenDialog ?? (typeof winner === "object" ? winner.dialog : void 0);
6809
+ const dialog = held === void 0 ? void 0 : {
6810
+ type: held.type(),
6811
+ message: held.message()
6667
6812
  };
6668
- }
6669
- async blockedView(tab) {
6670
- const dialog = tab.pendingDialog;
6671
- return this.pageFromShown(tab, this.shown.get(tab.id), {
6672
- surface: "snapshot",
6673
- ...dialog !== void 0 ? { dialog: {
6674
- type: dialog.type(),
6675
- message: dialog.message()
6676
- } } : {}
6677
- });
6678
- }
6679
- async goto(page, url, signal) {
6680
- this.windows.beginDispatch(page);
6681
- try {
6682
- return await page.goto(url, {
6683
- waitUntil: "domcontentloaded",
6684
- timeout: NAVIGATION_MS,
6685
- ...signal !== void 0 ? { signal } : {}
6686
- });
6687
- } finally {
6688
- this.windows.endDispatch(page);
6813
+ if (held !== void 0) this.windows.holdDialog(live, held);
6814
+ else this.windows.onNavigated(live);
6815
+ const load = dialog !== void 0 ? {
6816
+ load: false,
6817
+ pendingRequests: 0,
6818
+ dialog
6819
+ } : await waitForLoad(live.page, linked.signal);
6820
+ if (load.dialog !== void 0) this.windows.holdDialog(live);
6821
+ let waited;
6822
+ if (waitFor !== void 0 && load.dialog === void 0) {
6823
+ const text = await waitForText(live.page, waitFor, linked.signal);
6824
+ waited = {
6825
+ met: text.met,
6826
+ seconds: text.seconds
6827
+ };
6828
+ if (text.dialog !== void 0) this.windows.holdDialog(live);
6689
6829
  }
6690
- }
6691
- async discover(tab, address, response, signal) {
6692
- const main = response === null ? void 0 : await mainDocument(response, signal);
6693
- const relocated = main !== void 0 && !samePage(main.finalUrl, address);
6694
- const domLinks = relocated ? [] : await readDomLinks(tab.page, signal);
6695
- const previous = this.shown.get(tab.id);
6696
- return loadShown({
6830
+ this.windows.touch(live);
6831
+ const shown = load.dialog !== void 0 ? await loadShown({
6697
6832
  pageUrl: canonical(address),
6698
6833
  ...optionalFragment(address),
6699
- snapshot: await this.aria(tab, signal),
6700
- ...main !== void 0 && !relocated ? { main } : {},
6701
- ...domLinks.length > 0 ? { domLinks } : {},
6702
- ...previous !== void 0 ? { previous } : {},
6703
- relocate: relocated,
6834
+ snapshot: "",
6835
+ relocate: false,
6704
6836
  fetch: (target, accept, ifNoneMatch) => this.fetchForRead(target, accept, ifNoneMatch, signal)
6705
- });
6706
- }
6707
- fetchForRead(url, accept, ifNoneMatch, signal) {
6708
- return this.fetch(url, {
6709
- accept,
6710
- ...ifNoneMatch !== void 0 ? { ifNoneMatch } : {},
6711
- ...signal !== void 0 ? { signal } : {}
6712
- });
6713
- }
6714
- async aria(tab, signal) {
6715
- return untilAborted(tab.page.ariaSnapshot({ mode: "ai" }).catch((error) => {
6716
- this.ctx.logger.debug("aria snapshot failed: %s", errorText(error));
6717
- return "";
6718
- }), capped(signal, READ_MS));
6719
- }
6720
- async pageFromShown(tab, shown, extra, signal) {
6721
- const current = shown ?? {
6722
- pageUrl: canonical(tab.url),
6723
- digest: "",
6724
- kind: "snapshot",
6725
- text: "",
6726
- snapshot: ""
6837
+ }) : await this.discover(live, address, response, signal);
6838
+ this.shown.set(live.id, shown);
6839
+ const view = await this.pageFromShown(live, shown, {
6840
+ ...snapshot ? { surface: "snapshot" } : {},
6841
+ ...load.load ? {} : { incomplete: {
6842
+ load: load.load,
6843
+ pendingRequests: load.pendingRequests
6844
+ } },
6845
+ ...load.dialog !== void 0 ? { dialog: load.dialog } : {},
6846
+ ...waited !== void 0 ? { waited } : {}
6847
+ }, signal);
6848
+ return {
6849
+ view: await this.attachDownload(live, view, false),
6850
+ fresh,
6851
+ live
6727
6852
  };
6728
- const title = tab.dialogHeld ? "" : await untilAborted(tab.page.title().catch((error) => {
6729
- this.ctx.logger.debug("page title failed: %s", errorText(error));
6730
- return "";
6731
- }), capped(signal, READ_MS));
6732
- this.windows.noteTitle(tab, title);
6733
- const view = {
6734
- tab: tab.id,
6735
- url: current.pageUrl,
6736
- title,
6737
- observedAt: (/* @__PURE__ */ new Date()).toISOString(),
6738
- representation: current.kind === "agent-view" ? {
6739
- kind: "agent-view",
6740
- text: current.text,
6741
- ...current.version !== void 0 ? { version: current.version } : {},
6742
- ...current.href !== void 0 ? { href: current.href } : {}
6743
- } : {
6744
- kind: "snapshot",
6745
- text: current.snapshot,
6746
- ...current.agentViewError !== void 0 ? { agentViewError: current.agentViewError } : {}
6853
+ } catch (error) {
6854
+ nextDialog.cancel();
6855
+ if (this.control.ofTab(owner, live.id) === "person") throw await this.takenOver(live);
6856
+ if (linked.signal.aborted || error instanceof MhBrowserError && error.code === "INTERRUPTED") return {
6857
+ view: {
6858
+ tab: live.id,
6859
+ url,
6860
+ reason: WAITING_STOPPED
6747
6861
  },
6748
- inPresence: this.book.isShown(tab.owner, canonical(current.pageUrl))
6862
+ fresh,
6863
+ live
6749
6864
  };
6750
- tab.inPresence = view.inPresence;
6751
- if (extra?.surface === "snapshot") view.representation = snapshotSurface(current);
6752
- if (current.fragment !== void 0) view.fragment = current.fragment;
6753
- if (current.status !== void 0) view.status = current.status;
6754
- if (current.mediaType !== void 0) view.mediaType = current.mediaType;
6755
- if (current.body !== void 0) view.body = current.body;
6756
- if (extra?.dialog !== void 0) view.dialog = extra.dialog;
6757
- if (extra?.incomplete !== void 0) view.incomplete = extra.incomplete;
6758
- if (extra?.waited !== void 0) view.waited = extra.waited;
6759
- return view;
6760
- }
6761
- /**
6762
- * Read one presence page. A known origin is read on the request channel,
6763
- * with If-None-Match when the document was read before. Anything else uses
6764
- * a tab already on the address, or opens one and closes it again.
6765
- */
6766
- async observePresence(owner, url, signal) {
6767
- if (this.knownOrigin(url)) {
6768
- const via = await this.readKnown(owner, url, signal);
6769
- if (via === STOPPED) return observationOf(url, {
6865
+ return {
6866
+ view: {
6867
+ tab: live.id,
6770
6868
  url,
6771
- reason: WAITING_STOPPED
6772
- });
6773
- if (via !== void 0) return observationOf(url, via);
6774
- }
6775
- const existing = this.tabOn(owner, url);
6776
- if (existing !== void 0) return observationOf(url, await this.refreshView(existing, signal));
6777
- const opened = await this.openOne(owner, url, void 0, signal, false);
6778
- this.keepAgentView(opened);
6779
- const view = opened.view;
6780
- if (opened.fresh && "tab" in view && view.tab !== void 0) {
6781
- const live = this.windows.get(owner, view.tab);
6782
- if (live !== void 0 && this.closable(owner, live)) {
6783
- const agent = "representation" in view && view.representation.kind === "agent-view";
6784
- await this.windows.closeTab(live, agent ? void 0 : `${live.id} (idle)`);
6785
- if (agent) {
6786
- const shown = { ...view };
6787
- delete shown.tab;
6788
- return observationOf(url, shown);
6789
- }
6790
- }
6791
- }
6792
- return observationOf(url, view);
6869
+ reason: error instanceof Error ? error.message : String(error)
6870
+ },
6871
+ fresh,
6872
+ live
6873
+ };
6874
+ } finally {
6875
+ linked.release();
6876
+ }
6877
+ }
6878
+ async perform(live, op, signal) {
6879
+ if (op.kind === "snapshot") return { navigated: false };
6880
+ if (op.kind === "find") return {
6881
+ navigated: false,
6882
+ summary: findInSnapshot(await this.aria(live, signal), op)
6883
+ };
6884
+ if (op.kind === "evaluate") {
6885
+ const snapshot = this.shown.get(live.id)?.snapshot ?? "";
6886
+ const target = op.target === void 0 ? void 0 : await locate(live.page, op.target, snapshot);
6887
+ return this.evaluateOn(live, op, target, signal);
6888
+ }
6889
+ if (op.kind === "take_screenshot") return this.shoot(live, op, signal);
6890
+ if (op.kind === "file_upload") return this.uploadHeld(live, op, signal);
6891
+ if (op.kind === "wait_for") {
6892
+ const waitFor = waitFrom(op);
6893
+ assertWaitFor(waitFor);
6894
+ const text = await waitForText(live.page, waitFor, signal);
6895
+ if (text.dialog !== void 0) this.windows.holdDialog(live);
6896
+ return {
6897
+ navigated: false,
6898
+ waited: {
6899
+ met: text.met,
6900
+ seconds: text.seconds
6901
+ },
6902
+ ...text.dialog !== void 0 ? { dialog: text.dialog } : {}
6903
+ };
6793
6904
  }
6794
- tabOn(owner, url) {
6795
- const pageUrl = canonical(url);
6796
- const tabs = this.windows.list(owner).map((info) => this.windows.get(owner, info.tab)).filter((tab) => tab !== void 0 && canonical(tab.url) === pageUrl);
6797
- tabs.sort((left, right) => right.touchedAt - left.touchedAt);
6798
- return tabs[0];
6905
+ if (op.kind === "handle_dialog") {
6906
+ const dialog = live.pendingDialog;
6907
+ if (dialog === void 0) throw new MhBrowserError("INVALID_ARGS", "this page has no dialog");
6908
+ const before = live.page.url();
6909
+ if (op.accept) await (op.promptText !== void 0 ? dialog.accept(op.promptText) : dialog.accept());
6910
+ else await dialog.dismiss();
6911
+ this.windows.clearDialog(live);
6912
+ const navigated = live.page.url() !== before;
6913
+ return {
6914
+ navigated,
6915
+ ...settled(await settleAction(live.page, navigated, void 0, signal))
6916
+ };
6799
6917
  }
6800
- async refreshView(live, signal) {
6801
- this.windows.touch(live);
6802
- if (live.dialogHeld) return this.pageFromShown(live, this.shown.get(live.id), void 0, signal);
6803
- const address = live.page.url();
6804
- const previous = this.shown.get(live.id);
6805
- const shown = await loadShown({
6806
- pageUrl: canonical(address),
6807
- ...optionalFragment(address),
6808
- snapshot: await this.aria(live, signal),
6809
- ...previous !== void 0 ? { previous } : {},
6810
- relocate: previous !== void 0 && !samePage(previous.pageUrl, address),
6811
- fetch: (url, accept, ifNoneMatch) => this.fetchForRead(url, accept, ifNoneMatch, signal)
6918
+ const requests = trackActionRequests(live.page);
6919
+ const nextDialog = this.windows.nextDialog(live);
6920
+ const chooser = watchFileChooser(live.page);
6921
+ const snapshot = this.shown.get(live.id)?.snapshot ?? "";
6922
+ this.windows.beginDispatch(live.page);
6923
+ try {
6924
+ const finished = runAction(live.page, op, snapshot, signal).then((navigated) => ({
6925
+ kind: "done",
6926
+ navigated
6927
+ }));
6928
+ const appeared = nextDialog.dialog.then((dialog) => ({
6929
+ kind: "dialog",
6930
+ dialog
6931
+ }));
6932
+ const chose = chooser.opened.then((opened) => ({
6933
+ kind: "chooser",
6934
+ opened
6935
+ }));
6936
+ const winner = await Promise.race([
6937
+ finished,
6938
+ appeared,
6939
+ chose
6940
+ ]).finally(() => {
6941
+ this.windows.endDispatch(live.page);
6812
6942
  });
6813
- this.shown.set(live.id, shown);
6814
- this.windows.noteUrl(live, address);
6815
- return this.pageFromShown(live, shown, void 0, signal);
6816
- }
6817
- /** The most recently touched idle tab on this address. A tab the person holds is left alone. */
6818
- idleTabOn(owner, url) {
6819
- const pageUrl = canonical(url);
6820
- const tabs = this.windows.list(owner).map((info) => this.windows.get(owner, info.tab)).filter((tab) => tab !== void 0 && canonical(tab.url) === pageUrl && !tab.occupied && this.control.ofTab(owner, tab.id) !== "person");
6821
- tabs.sort((left, right) => right.touchedAt - left.touchedAt);
6822
- return tabs[0];
6823
- }
6824
- /** Only Session windows are capped; the person's window is theirs to close. */
6825
- async enforceCap(owner) {
6826
- if (owner === "person") return;
6827
- await this.windows.enforceCap(owner);
6828
- }
6829
- /** Other tabs on this address: idle ones reload, occupied or taken ones are marked. */
6830
- async refreshIdle(owner, url, except, signal) {
6831
- const pageUrl = canonical(url);
6832
- const tabs = this.windows.list(owner).map((info) => this.windows.get(owner, info.tab)).filter((item) => item !== void 0 && canonical(item.url) === pageUrl);
6833
- for (const item of tabs) {
6834
- if (item.id === except) continue;
6835
- if (item.occupied || this.control.ofTab(owner, item.id) === "person") this.windows.markMayHaveChanged(item);
6836
- else await this.navigateTab(item, item.page.url(), signal);
6943
+ if (winner.kind === "dialog") {
6944
+ this.windows.holdDialog(live, winner.dialog);
6945
+ finished.catch(() => void 0);
6946
+ return {
6947
+ navigated: false,
6948
+ dialog: {
6949
+ type: winner.dialog.type(),
6950
+ message: winner.dialog.message()
6951
+ }
6952
+ };
6837
6953
  }
6838
- }
6839
- async navigateTab(live, url, signal) {
6840
- try {
6841
- const response = await this.goto(live.page, url, signal);
6842
- this.windows.onNavigated(live);
6843
- const address = live.page.url();
6844
- this.windows.noteUrl(live, address === "about:blank" ? url : address);
6845
- const load = await waitForLoad(live.page, signal);
6846
- if (load.dialog !== void 0) this.windows.holdDialog(live);
6847
- this.windows.touch(live);
6848
- const shown = await this.discover(live, live.page.url(), response, signal);
6849
- this.shown.set(live.id, shown);
6850
- const view = await this.pageFromShown(live, shown, {
6851
- ...load.load ? {} : { incomplete: {
6852
- load: load.load,
6853
- pendingRequests: load.pendingRequests
6854
- } },
6855
- ...load.dialog !== void 0 ? { dialog: load.dialog } : {}
6856
- }, signal);
6857
- return this.attachDownload(live, view, false);
6858
- } catch (error) {
6859
- if (isDownloadStart(error) || live.pendingDownload !== void 0) {
6860
- const view = await this.pageFromShown(live, this.shown.get(live.id), void 0, signal);
6861
- if (view.url === "" || view.url === "about:blank") view.url = canonical(url);
6862
- this.applyDocumentType(live, view);
6863
- return this.attachDownload(live, view, true);
6864
- }
6954
+ if (winner.kind === "chooser") {
6955
+ finished.catch(() => void 0);
6865
6956
  return {
6866
- tab: live.id,
6867
- url,
6868
- reason: error instanceof Error ? error.message : String(error)
6957
+ navigated: false,
6958
+ dialog: this.chooserHeld(live, winner.opened)
6869
6959
  };
6870
6960
  }
6961
+ const settledLoad = await Promise.race([settleAction(live.page, winner.navigated, requests, signal), chooser.opened.then((opened) => ({
6962
+ load: true,
6963
+ pendingRequests: 0,
6964
+ dialog: this.chooserHeld(live, opened)
6965
+ }))]);
6966
+ return {
6967
+ navigated: winner.navigated,
6968
+ ...settled(settledLoad)
6969
+ };
6970
+ } finally {
6971
+ requests.stop();
6972
+ nextDialog.cancel();
6973
+ chooser.stop();
6871
6974
  }
6872
- async sendAction(request, signal) {
6873
- const context = this.context;
6874
- if (context === void 0) return { kind: "lost" };
6875
- try {
6876
- const response = await context.request.fetch(request.url, {
6877
- method: request.method,
6878
- headers: request.headers,
6879
- maxRedirects: 0,
6880
- maxRetries: 0,
6881
- failOnStatusCode: false,
6882
- ...signal !== void 0 ? { signal } : {},
6883
- ...request.multipart !== void 0 ? { multipart: request.multipart } : {},
6884
- ...request.data !== void 0 ? { data: request.data } : {}
6885
- });
6886
- const headers = response.headers();
6887
- const location = headers.location;
6888
- const mediaType = headers["content-type"];
6975
+ }
6976
+ /**
6977
+ * `browser_evaluate`. A dialog the function opens is held like any other; a
6978
+ * stop or a takeover ends the wait and still reports the writes already sent.
6979
+ */
6980
+ async evaluateOn(live, op, target, signal) {
6981
+ const nextDialog = this.windows.nextDialog(live);
6982
+ let navigated = false;
6983
+ const onNav = (frame) => {
6984
+ if (frame.parentFrame() === null) navigated = true;
6985
+ };
6986
+ live.page.on("framenavigated", onNav);
6987
+ try {
6988
+ const evaluated = await evaluateMarked(live.page, op.function, target, op.callId, signal, nextDialog.dialog);
6989
+ const writes = formatWrites(evaluated.writes);
6990
+ const counted = evaluated.writes.length === 0 ? {} : { writes: evaluated.writes };
6991
+ if (evaluated.kind === "stopped") {
6992
+ const note = writes === "" ? "" : `\n${writes}`;
6993
+ if (this.control.ofTab(live.owner, live.id) === "person") throw await this.takenOver(live, note);
6994
+ throw new MhBrowserError(INTERRUPTED, `${WAITING_STOPPED}${note}`);
6995
+ }
6996
+ if (evaluated.kind === "dialog") {
6997
+ this.windows.holdDialog(live, evaluated.dialog);
6889
6998
  return {
6890
- kind: "response",
6891
- status: response.status(),
6892
- body: new Uint8Array(await untilAborted(response.body(), capped(signal, READ_MS))),
6893
- ...location === void 0 || location === "" ? {} : { location },
6894
- ...mediaType === void 0 ? {} : { mediaType }
6999
+ navigated: false,
7000
+ dialog: {
7001
+ type: evaluated.dialog.type(),
7002
+ message: evaluated.dialog.message()
7003
+ },
7004
+ summary: "",
7005
+ detail: writes,
7006
+ ...counted
6895
7007
  };
6896
- } catch (error) {
6897
- if (signal?.aborted === true) throw new MhBrowserError(INTERRUPTED, "stopped after sending; it may have taken effect");
6898
- this.ctx.logger.debug("declared action was not answered: %s", errorText(error));
6899
- return { kind: "lost" };
6900
7008
  }
7009
+ if (evaluated.kind === "navigated") return {
7010
+ navigated: true,
7011
+ summary: NAVIGATED_DURING_EVALUATE,
7012
+ detail: writes,
7013
+ ...counted
7014
+ };
7015
+ return {
7016
+ navigated,
7017
+ summary: evaluated.value,
7018
+ detail: writes,
7019
+ ...counted
7020
+ };
7021
+ } finally {
7022
+ live.page.off("framenavigated", onNav);
7023
+ nextDialog.cancel();
7024
+ }
7025
+ }
7026
+ async uploadHeld(live, op, signal) {
7027
+ const chooser = live.fileChooser;
7028
+ if (chooser === void 0) throw new MhBrowserError("INVALID_ARGS", "No file chooser visible");
7029
+ const paths = op.paths;
7030
+ if (paths === void 0 || paths.length === 0) {
7031
+ live.fileChooser = void 0;
7032
+ return { navigated: false };
7033
+ }
7034
+ const requests = trackActionRequests(live.page);
7035
+ let navigated = false;
7036
+ const onNav = (frame) => {
7037
+ if (frame.parentFrame() === null) navigated = true;
7038
+ };
7039
+ live.page.on("framenavigated", onNav);
7040
+ this.windows.beginDispatch(live.page);
7041
+ try {
7042
+ await chooser.setFiles(paths, signal === void 0 ? {} : { signal });
7043
+ live.fileChooser = void 0;
7044
+ await settleAction(live.page, navigated, requests, signal);
7045
+ return { navigated };
7046
+ } finally {
7047
+ live.page.off("framenavigated", onNav);
7048
+ this.windows.endDispatch(live.page);
7049
+ requests.stop();
6901
7050
  }
6902
- async saveResponse(url, root, signal) {
6903
- const context = this.context;
6904
- if (context === void 0) return {
6905
- kind: "error",
7051
+ }
7052
+ async shoot(live, op, signal) {
7053
+ if (op.fullPage === true && op.target !== void 0) throw new MhBrowserError("INVALID_ARGS", "fullPage cannot be used with element screenshots.");
7054
+ const type = op.type ?? "png";
7055
+ const snapshot = this.shown.get(live.id)?.snapshot ?? "";
7056
+ const locator = op.target === void 0 ? void 0 : await locate(live.page, op.target, snapshot);
7057
+ const options = {
7058
+ type,
7059
+ ...type === "jpeg" ? { quality: 90 } : {},
7060
+ ...op.scale !== void 0 ? { scale: op.scale } : {},
7061
+ ...op.fullPage === true ? { fullPage: true } : {},
7062
+ ...signal !== void 0 ? { signal } : {}
7063
+ };
7064
+ const bytes = locator === void 0 ? await live.page.screenshot(options) : await locator.screenshot(options);
7065
+ return {
7066
+ navigated: false,
7067
+ shot: {
7068
+ mediaType: `image/${type}`,
7069
+ bytes: new Uint8Array(bytes)
7070
+ }
7071
+ };
7072
+ }
7073
+ /** A snapshot limited to a target, a depth, or boxes. Refs still resolve against the full one. */
7074
+ async scopedSnapshot(tab, op, signal) {
7075
+ const options = {
7076
+ mode: "ai",
7077
+ ...op.depth !== void 0 ? { depth: op.depth } : {},
7078
+ ...op.boxes === true ? { boxes: true } : {}
7079
+ };
7080
+ const snapshot = this.shown.get(tab.id)?.snapshot ?? "";
7081
+ const limit = capped(signal, READ_MS);
7082
+ if (op.target !== void 0) return untilAborted((await locate(tab.page, op.target, snapshot)).ariaSnapshot(options), limit);
7083
+ return untilAborted(tab.page.ariaSnapshot(options), limit);
7084
+ }
7085
+ /** A file chooser the action opened. The tab stays in use until it navigates. */
7086
+ chooserHeld(live, chooser) {
7087
+ live.fileChooser = chooser;
7088
+ this.windows.holdInput(live);
7089
+ return {
7090
+ type: "filechooser",
7091
+ message: chooser.isMultiple() ? "choose files (several allowed) with browser_file_upload" : "choose one file with browser_file_upload"
7092
+ };
7093
+ }
7094
+ async refreshSnapshot(tab, signal) {
7095
+ const previous = this.shown.get(tab.id);
7096
+ const snapshot = tab.dialogHeld ? "" : await this.aria(tab, signal);
7097
+ if (previous === void 0) return {
7098
+ pageUrl: canonical(tab.page.url()),
7099
+ digest: "",
7100
+ kind: "snapshot",
7101
+ text: snapshot,
7102
+ snapshot
7103
+ };
7104
+ return {
7105
+ ...previous,
7106
+ snapshot
7107
+ };
7108
+ }
7109
+ async blockedView(tab) {
7110
+ const dialog = tab.pendingDialog;
7111
+ return this.pageFromShown(tab, this.shown.get(tab.id), {
7112
+ surface: "snapshot",
7113
+ ...dialog !== void 0 ? { dialog: {
7114
+ type: dialog.type(),
7115
+ message: dialog.message()
7116
+ } } : {}
7117
+ });
7118
+ }
7119
+ async goto(page, url, signal) {
7120
+ this.windows.beginDispatch(page);
7121
+ try {
7122
+ return await page.goto(url, {
7123
+ waitUntil: "domcontentloaded",
7124
+ timeout: NAVIGATION_MS,
7125
+ ...signal !== void 0 ? { signal } : {}
7126
+ });
7127
+ } finally {
7128
+ this.windows.endDispatch(page);
7129
+ }
7130
+ }
7131
+ async discover(tab, address, response, signal) {
7132
+ const main = response === null ? void 0 : await mainDocument(response, signal);
7133
+ const relocated = main !== void 0 && !samePage(main.finalUrl, address);
7134
+ const domLinks = relocated ? [] : await readDomLinks(tab.page, signal);
7135
+ const previous = this.shown.get(tab.id);
7136
+ return loadShown({
7137
+ pageUrl: canonical(address),
7138
+ ...optionalFragment(address),
7139
+ snapshot: await this.aria(tab, signal),
7140
+ ...main !== void 0 && !relocated ? { main } : {},
7141
+ ...domLinks.length > 0 ? { domLinks } : {},
7142
+ ...previous !== void 0 ? { previous } : {},
7143
+ relocate: relocated,
7144
+ fetch: (target, accept, ifNoneMatch) => this.fetchForRead(target, accept, ifNoneMatch, signal)
7145
+ });
7146
+ }
7147
+ fetchForRead(url, accept, ifNoneMatch, signal) {
7148
+ return this.fetch(url, {
7149
+ accept,
7150
+ ...ifNoneMatch !== void 0 ? { ifNoneMatch } : {},
7151
+ ...signal !== void 0 ? { signal } : {}
7152
+ });
7153
+ }
7154
+ async aria(tab, signal) {
7155
+ return untilAborted(tab.page.ariaSnapshot({ mode: "ai" }).catch((error) => {
7156
+ this.ctx.logger.debug("aria snapshot failed: %s", errorText(error));
7157
+ return "";
7158
+ }), capped(signal, READ_MS));
7159
+ }
7160
+ async pageFromShown(tab, shown, extra, signal) {
7161
+ const current = shown ?? {
7162
+ pageUrl: canonical(tab.url),
7163
+ digest: "",
7164
+ kind: "snapshot",
7165
+ text: "",
7166
+ snapshot: ""
7167
+ };
7168
+ const title = tab.dialogHeld ? "" : await untilAborted(tab.page.title().catch((error) => {
7169
+ this.ctx.logger.debug("page title failed: %s", errorText(error));
7170
+ return "";
7171
+ }), capped(signal, READ_MS));
7172
+ this.windows.noteTitle(tab, title);
7173
+ const view = {
7174
+ tab: tab.id,
7175
+ url: current.pageUrl,
7176
+ title,
7177
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
7178
+ representation: current.kind === "agent-view" ? {
7179
+ kind: "agent-view",
7180
+ text: current.text,
7181
+ ...current.version !== void 0 ? { version: current.version } : {},
7182
+ ...current.href !== void 0 ? { href: current.href } : {}
7183
+ } : {
7184
+ kind: "snapshot",
7185
+ text: current.snapshot,
7186
+ ...current.agentViewError !== void 0 ? { agentViewError: current.agentViewError } : {}
7187
+ },
7188
+ inPresence: this.book.isShown(tab.owner, canonical(current.pageUrl))
7189
+ };
7190
+ tab.inPresence = view.inPresence;
7191
+ if (extra?.surface === "snapshot") view.representation = snapshotSurface(current);
7192
+ if (current.fragment !== void 0) view.fragment = current.fragment;
7193
+ if (current.status !== void 0) view.status = current.status;
7194
+ if (current.mediaType !== void 0) view.mediaType = current.mediaType;
7195
+ if (current.body !== void 0) view.body = current.body;
7196
+ if (extra?.dialog !== void 0) view.dialog = extra.dialog;
7197
+ if (extra?.incomplete !== void 0) view.incomplete = extra.incomplete;
7198
+ if (extra?.waited !== void 0) view.waited = extra.waited;
7199
+ return view;
7200
+ }
7201
+ /**
7202
+ * Read one presence page. A known origin is read on the request channel,
7203
+ * with If-None-Match when the document was read before. Anything else uses
7204
+ * a tab already on the address, or opens one and closes it again.
7205
+ */
7206
+ async observePresence(owner, url, signal) {
7207
+ if (this.knownOrigin(url)) {
7208
+ const via = await this.readKnown(owner, url, signal);
7209
+ if (via === STOPPED) return observationOf(url, {
6906
7210
  url,
6907
- reason: "browser is not running"
6908
- };
6909
- try {
6910
- const { response, finalUrl } = await getWithCookies(context, url, signal);
6911
- const status = response.status;
6912
- const mediaType = response.headers.get("content-type") ?? void 0;
6913
- if (status < 200 || status >= 300) {
6914
- await response.body?.cancel().catch(() => void 0);
6915
- return {
6916
- kind: "error",
6917
- url: finalUrl,
6918
- status,
6919
- reason: `HTTP ${String(status)}`
6920
- };
7211
+ reason: WAITING_STOPPED
7212
+ });
7213
+ if (via !== void 0) return observationOf(url, via);
7214
+ }
7215
+ const existing = this.tabOn(owner, url);
7216
+ if (existing !== void 0) return observationOf(url, await this.refreshView(existing, signal));
7217
+ const opened = await this.openOne(owner, url, void 0, signal, false);
7218
+ this.keepAgentView(opened);
7219
+ const view = opened.view;
7220
+ if (opened.fresh && "tab" in view && view.tab !== void 0) {
7221
+ const live = this.windows.get(owner, view.tab);
7222
+ if (live !== void 0 && this.closable(owner, live)) {
7223
+ const agent = "representation" in view && view.representation.kind === "agent-view";
7224
+ await this.windows.closeTab(live, agent ? void 0 : `${live.id} (idle)`);
7225
+ if (agent) {
7226
+ const shown = { ...view };
7227
+ delete shown.tab;
7228
+ return observationOf(url, shown);
6921
7229
  }
6922
- const written = await writeDownload(root, filenameFrom(response.headers.get("content-disposition") ?? void 0, finalUrl), response.body ?? emptyBody());
6923
- return {
6924
- kind: "saved",
6925
- path: written.path,
6926
- url: finalUrl,
6927
- bytes: written.bytes,
6928
- sha256: written.sha256,
6929
- observed: (/* @__PURE__ */ new Date()).toISOString(),
6930
- ...mediaType === void 0 ? {} : { mediaType }
6931
- };
6932
- } catch (error) {
6933
- if (error instanceof MhBrowserError) throw error;
6934
- return {
6935
- kind: "error",
6936
- url,
6937
- reason: error instanceof Error ? error.message : String(error)
6938
- };
6939
7230
  }
6940
7231
  }
6941
- async attachDownload(live, view, wait) {
6942
- const saved = await this.takePendingDownload(live, wait);
6943
- if (saved !== void 0) view.download = saved;
6944
- return view;
7232
+ return observationOf(url, view);
7233
+ }
7234
+ tabOn(owner, url) {
7235
+ const pageUrl = canonical(url);
7236
+ const tabs = this.windows.list(owner).map((info) => this.windows.get(owner, info.tab)).filter((tab) => tab !== void 0 && canonical(tab.url) === pageUrl);
7237
+ tabs.sort((left, right) => right.touchedAt - left.touchedAt);
7238
+ return tabs[0];
7239
+ }
7240
+ async refreshView(live, signal) {
7241
+ this.windows.touch(live);
7242
+ if (live.dialogHeld) return this.pageFromShown(live, this.shown.get(live.id), void 0, signal);
7243
+ const address = live.page.url();
7244
+ const previous = this.shown.get(live.id);
7245
+ const shown = await loadShown({
7246
+ pageUrl: canonical(address),
7247
+ ...optionalFragment(address),
7248
+ snapshot: await this.aria(live, signal),
7249
+ ...previous !== void 0 ? { previous } : {},
7250
+ relocate: previous !== void 0 && !samePage(previous.pageUrl, address),
7251
+ fetch: (url, accept, ifNoneMatch) => this.fetchForRead(url, accept, ifNoneMatch, signal)
7252
+ });
7253
+ this.shown.set(live.id, shown);
7254
+ this.windows.noteUrl(live, address);
7255
+ return this.pageFromShown(live, shown, void 0, signal);
7256
+ }
7257
+ /** The most recently touched idle tab on this address. A tab the person holds is left alone. */
7258
+ idleTabOn(owner, url) {
7259
+ const pageUrl = canonical(url);
7260
+ const tabs = this.windows.list(owner).map((info) => this.windows.get(owner, info.tab)).filter((tab) => tab !== void 0 && canonical(tab.url) === pageUrl && !tab.occupied && this.control.ofTab(owner, tab.id) !== "person");
7261
+ tabs.sort((left, right) => right.touchedAt - left.touchedAt);
7262
+ return tabs[0];
7263
+ }
7264
+ /** Only Session windows are capped; the person's window is theirs to close. */
7265
+ async enforceCap(owner) {
7266
+ if (owner === "person") return;
7267
+ await this.windows.enforceCap(owner);
7268
+ }
7269
+ /** Other tabs on this address: idle ones reload, occupied or taken ones are marked. */
7270
+ async refreshIdle(owner, url, except, signal) {
7271
+ const pageUrl = canonical(url);
7272
+ const tabs = this.windows.list(owner).map((info) => this.windows.get(owner, info.tab)).filter((item) => item !== void 0 && canonical(item.url) === pageUrl);
7273
+ for (const item of tabs) {
7274
+ if (item.id === except) continue;
7275
+ if (item.occupied || this.control.ofTab(owner, item.id) === "person") this.windows.markMayHaveChanged(item);
7276
+ else await this.navigateTab(item, item.page.url(), signal);
6945
7277
  }
6946
- async takePendingDownload(live, wait) {
6947
- if (live.pendingDownload === void 0 && wait) await live.page.waitForEvent("download", { timeout: DOWNLOAD_EVENT_MS }).catch(() => void 0);
6948
- const download = live.pendingDownload;
6949
- if (download === void 0) return void 0;
6950
- live.pendingDownload = void 0;
6951
- return this.savePlaywrightDownload(live.owner, download);
6952
- }
6953
- async savePlaywrightDownload(owner, download) {
6954
- const target = this.workspaces.get(owner);
6955
- const url = download.url();
6956
- if (target === void 0) return {
6957
- kind: "error",
7278
+ }
7279
+ async navigateTab(live, url, signal) {
7280
+ try {
7281
+ const response = await this.goto(live.page, url, signal);
7282
+ this.windows.onNavigated(live);
7283
+ const address = live.page.url();
7284
+ this.windows.noteUrl(live, address === "about:blank" ? url : address);
7285
+ const load = await waitForLoad(live.page, signal);
7286
+ if (load.dialog !== void 0) this.windows.holdDialog(live);
7287
+ this.windows.touch(live);
7288
+ const shown = await this.discover(live, live.page.url(), response, signal);
7289
+ this.shown.set(live.id, shown);
7290
+ const view = await this.pageFromShown(live, shown, {
7291
+ ...load.load ? {} : { incomplete: {
7292
+ load: load.load,
7293
+ pendingRequests: load.pendingRequests
7294
+ } },
7295
+ ...load.dialog !== void 0 ? { dialog: load.dialog } : {}
7296
+ }, signal);
7297
+ return this.attachDownload(live, view, false);
7298
+ } catch (error) {
7299
+ if (isDownloadStart(error) || live.pendingDownload !== void 0) {
7300
+ const view = await this.pageFromShown(live, this.shown.get(live.id), void 0, signal);
7301
+ if (view.url === "" || view.url === "about:blank") view.url = canonical(url);
7302
+ this.applyDocumentType(live, view);
7303
+ return this.attachDownload(live, view, true);
7304
+ }
7305
+ return {
7306
+ tab: live.id,
6958
7307
  url,
6959
- reason: NO_WORKSPACE_REASON
7308
+ reason: error instanceof Error ? error.message : String(error)
7309
+ };
7310
+ }
7311
+ }
7312
+ async sendAction(request, signal) {
7313
+ const context = this.context;
7314
+ if (context === void 0) return { kind: "lost" };
7315
+ try {
7316
+ const response = await context.request.fetch(request.url, {
7317
+ method: request.method,
7318
+ headers: request.headers,
7319
+ maxRedirects: 0,
7320
+ maxRetries: 0,
7321
+ failOnStatusCode: false,
7322
+ ...signal !== void 0 ? { signal } : {},
7323
+ ...request.multipart !== void 0 ? { multipart: request.multipart } : {},
7324
+ ...request.data !== void 0 ? { data: request.data } : {}
7325
+ });
7326
+ const headers = response.headers();
7327
+ const location = headers.location;
7328
+ const mediaType = headers["content-type"];
7329
+ return {
7330
+ kind: "response",
7331
+ status: response.status(),
7332
+ body: new Uint8Array(await untilAborted(response.body(), capped(signal, READ_MS))),
7333
+ ...location === void 0 || location === "" ? {} : { location },
7334
+ ...mediaType === void 0 ? {} : { mediaType }
6960
7335
  };
6961
- if ("denied" in target) {
6962
- await download.cancel().catch(() => void 0);
7336
+ } catch (error) {
7337
+ if (signal?.aborted === true) throw new MhBrowserError(INTERRUPTED, "stopped after sending; it may have taken effect");
7338
+ this.ctx.logger.debug("declared action was not answered: %s", errorText(error));
7339
+ return { kind: "lost" };
7340
+ }
7341
+ }
7342
+ async saveResponse(url, root, signal) {
7343
+ const context = this.context;
7344
+ if (context === void 0) return {
7345
+ kind: "error",
7346
+ url,
7347
+ reason: "browser is not running"
7348
+ };
7349
+ try {
7350
+ const { response, finalUrl } = await getWithCookies(context, url, signal);
7351
+ const status = response.status;
7352
+ const mediaType = response.headers.get("content-type") ?? void 0;
7353
+ if (status < 200 || status >= 300) {
7354
+ await response.body?.cancel().catch(() => void 0);
6963
7355
  return {
6964
7356
  kind: "error",
6965
- url,
6966
- reason: target.denied
7357
+ url: finalUrl,
7358
+ status,
7359
+ reason: `HTTP ${String(status)}`
6967
7360
  };
6968
7361
  }
6969
- const written = await writeDownload(target.root, download.suggestedFilename(), await download.createReadStream());
7362
+ const written = await writeDownload(root, filenameFrom(response.headers.get("content-disposition") ?? void 0, finalUrl), response.body ?? emptyBody());
6970
7363
  return {
6971
7364
  kind: "saved",
6972
7365
  path: written.path,
6973
- url,
7366
+ url: finalUrl,
6974
7367
  bytes: written.bytes,
6975
7368
  sha256: written.sha256,
6976
- observed: (/* @__PURE__ */ new Date()).toISOString()
7369
+ observed: (/* @__PURE__ */ new Date()).toISOString(),
7370
+ ...mediaType === void 0 ? {} : { mediaType }
7371
+ };
7372
+ } catch (error) {
7373
+ if (error instanceof MhBrowserError) throw error;
7374
+ return {
7375
+ kind: "error",
7376
+ url,
7377
+ reason: error instanceof Error ? error.message : String(error)
6977
7378
  };
6978
7379
  }
6979
- applyDocumentType(live, view) {
6980
- const type = live.documentType;
6981
- if (view.mediaType === void 0 && type !== void 0) {
6982
- const bare = type.split(";")[0]?.trim().toLowerCase() ?? "";
6983
- if (bare !== "" && bare !== "text/html") view.mediaType = type;
6984
- }
6985
- if (view.status === void 0 && live.documentStatus !== void 0 && live.documentStatus >= 300) view.status = live.documentStatus;
6986
- }
6987
- /** A failed launch is logged here; calls that need the browser see it as `BROWSER_UNAVAILABLE`. */
6988
- launch() {
6989
- const started = this.start().catch((error) => {
6990
- const reason = error instanceof Error ? error.message : String(error);
6991
- this.ctx.logger.warn("browser did not start: %s", reason);
6992
- throw new MhBrowserError(BROWSER_UNAVAILABLE, `the browser did not start: ${reason}`);
6993
- });
6994
- started.catch(() => void 0);
6995
- return started;
6996
- }
6997
- async start() {
6998
- const choice = this.launchChoice();
6999
- const epoch = this.configEpoch;
7000
- const context = await launchBrowser(choice, this.locateEnv());
7001
- const pid = await browserPid(context, choice.profileDir);
7002
- if (pid !== void 0) this.pids.set(context, pid);
7003
- if (this.closing) {
7004
- await this.closeContext(context);
7005
- return;
7006
- }
7007
- this.context = context;
7008
- try {
7009
- await this.windows.attach(context, choice.profileDir, { headed: !choice.headless });
7010
- } catch (error) {
7011
- this.context = void 0;
7012
- this.windows.dropPages();
7013
- await this.closeContext(context);
7014
- throw error;
7015
- }
7016
- if (this.configEpoch === epoch) this.relaunchWanted = false;
7017
- context.browser()?.on("disconnected", () => {
7018
- if (this.closing || this.replacing || this.context !== context) return;
7019
- this.onExit();
7020
- });
7380
+ }
7381
+ async attachDownload(live, view, wait) {
7382
+ const saved = await this.takePendingDownload(live, wait);
7383
+ if (saved !== void 0) view.download = saved;
7384
+ return view;
7385
+ }
7386
+ async takePendingDownload(live, wait) {
7387
+ if (live.pendingDownload === void 0 && wait) await live.page.waitForEvent("download", { timeout: DOWNLOAD_EVENT_MS }).catch(() => void 0);
7388
+ const download = live.pendingDownload;
7389
+ if (download === void 0) return void 0;
7390
+ live.pendingDownload = void 0;
7391
+ return this.savePlaywrightDownload(live.owner, download);
7392
+ }
7393
+ async savePlaywrightDownload(owner, download) {
7394
+ const target = this.workspaces.get(owner);
7395
+ const url = download.url();
7396
+ if (target === void 0) return {
7397
+ kind: "error",
7398
+ url,
7399
+ reason: NO_WORKSPACE_REASON
7400
+ };
7401
+ if ("denied" in target) {
7402
+ await download.cancel().catch(() => void 0);
7403
+ return {
7404
+ kind: "error",
7405
+ url,
7406
+ reason: target.denied
7407
+ };
7021
7408
  }
7022
- /** No window opens on exit: the person may have quit it. Calls on old tabs find none. */
7023
- onExit() {
7024
- this.windows.suppressPersonInput();
7025
- this.windows.dropPages();
7026
- this.context = void 0;
7027
- this.exits.push(Date.now());
7028
- this.exited = true;
7029
- this.ready = Promise.resolve();
7030
- }
7031
- /**
7032
- * The browser for a call that needs a page. One that is not running starts
7033
- * again here. The exit limit stops unattended restarts; a person's request
7034
- * is one start per click and skips it.
7035
- */
7036
- up(byPerson = false) {
7037
- if (!this.exited || this.closing) return this.ready;
7038
- const now = Date.now();
7039
- while (this.exits.length > 0 && now - (this.exits[0] ?? now) > RELAUNCH_WINDOW_MS) this.exits.shift();
7040
- if (!byPerson && this.exits.length > RELAUNCH_LIMIT) {
7041
- this.ctx.logger.warn("browser keeps stopping; not starting it again yet");
7042
- return Promise.reject(new MhBrowserError(BROWSER_UNAVAILABLE, `the browser stopped or did not start ${String(this.exits.length)} times within ${String(RELAUNCH_WINDOW_MS / 1e3)} s; try again in a minute`));
7043
- }
7044
- this.exited = false;
7045
- const started = this.launch();
7046
- started.then(() => this.windows.resumePersonInput(), () => {
7047
- this.exited = true;
7048
- if (!this.closing) this.exits.push(Date.now());
7049
- });
7050
- this.ready = started;
7051
- return started;
7409
+ const written = await writeDownload(target.root, download.suggestedFilename(), await download.createReadStream());
7410
+ return {
7411
+ kind: "saved",
7412
+ path: written.path,
7413
+ url,
7414
+ bytes: written.bytes,
7415
+ sha256: written.sha256,
7416
+ observed: (/* @__PURE__ */ new Date()).toISOString()
7417
+ };
7418
+ }
7419
+ applyDocumentType(live, view) {
7420
+ const type = live.documentType;
7421
+ if (view.mediaType === void 0 && type !== void 0) {
7422
+ const bare = type.split(";")[0]?.trim().toLowerCase() ?? "";
7423
+ if (bare !== "" && bare !== "text/html") view.mediaType = type;
7424
+ }
7425
+ if (view.status === void 0 && live.documentStatus !== void 0 && live.documentStatus >= 300) view.status = live.documentStatus;
7426
+ }
7427
+ /** A failed launch is logged here; calls that need the browser see it as `BROWSER_UNAVAILABLE`. */
7428
+ launch() {
7429
+ const started = this.start().catch((error) => {
7430
+ const reason = error instanceof Error ? error.message : String(error);
7431
+ this.ctx.logger.warn("browser did not start: %s", reason);
7432
+ const notFound = error instanceof BrowserNotFoundError ? error.notFound : void 0;
7433
+ throw new MhBrowserError(BROWSER_UNAVAILABLE, `the browser did not start: ${reason}`, void 0, notFound);
7434
+ });
7435
+ started.catch(() => void 0);
7436
+ return started;
7437
+ }
7438
+ async start() {
7439
+ const env = this.locateEnv();
7440
+ const remembered = await readLastBrowser(this.profileRoot);
7441
+ const configured = this.executablePath.get();
7442
+ const plan = await planLaunch({
7443
+ choice: this.browserName.get(),
7444
+ configured,
7445
+ root: this.profileRoot,
7446
+ split: this.splitProfile,
7447
+ env,
7448
+ remembered,
7449
+ bundled: bundledChromiumLocation(env.access)
7450
+ });
7451
+ const epoch = this.configEpoch;
7452
+ const context = await launchBrowser({
7453
+ browser: plan.browser,
7454
+ headless: this.headless,
7455
+ profileDir: plan.profileDir,
7456
+ ...plan.channel ? {} : { channel: false },
7457
+ ...plan.executablePath !== void 0 ? { executablePath: plan.executablePath } : {}
7458
+ }, env);
7459
+ const pid = await browserPid(context, plan.profileDir);
7460
+ if (pid !== void 0) this.pids.set(context, pid);
7461
+ if (this.closing) {
7462
+ await this.closeContext(context);
7463
+ return;
7052
7464
  }
7053
- async stop() {
7054
- this.windows.suppressPersonInput();
7055
- await Promise.race([this.ready.catch(() => void 0), new Promise((resolve) => setTimeout(resolve, STOP_WAIT_MS))]);
7056
- const context = this.context;
7465
+ this.context = context;
7466
+ try {
7467
+ await this.windows.attach(context, plan.profileDir, { headed: !this.headless });
7468
+ } catch (error) {
7057
7469
  this.context = void 0;
7058
- if (context !== void 0) await this.closeContext(context);
7059
- }
7060
- /** Close a context the service is done with, and kill it if close stalls. */
7061
- async closeContext(context) {
7062
- await closeOrKill(() => context.close(), this.pids.get(context));
7063
- this.pids.delete(context);
7064
- }
7065
- refuseIfPerson(owner, tab) {
7066
- if (this.control.ofTab(owner, tab) !== "person") return;
7067
- throw new MhBrowserError("PERSON_IN_CONTROL", "the person is using this tab; call browser_handover with this tab to wait until they hand it back, or work in another tab");
7068
- }
7069
- async takenOver(live, note = "") {
7070
- try {
7071
- const page = await this.pageFromShown(live, this.shown.get(live.id), { surface: "snapshot" });
7072
- return new MhBrowserError("TAKEN_OVER", `${MAY_HAVE_TAKEN_EFFECT}${note}`, page);
7073
- } catch {
7074
- return new MhBrowserError("TAKEN_OVER", `${MAY_HAVE_TAKEN_EFFECT}${note}`);
7075
- }
7076
- }
7077
- presenceUrls(owner, tabs) {
7078
- const known = new Set(this.book.entries(owner).map((page) => page.url));
7079
- const urls = [];
7080
- for (const id of tabs) {
7081
- const address = this.windows.urlOf(owner, id);
7082
- if (address === void 0) continue;
7083
- const url = canonical(address);
7084
- if (!known.has(url) || urls.includes(url)) continue;
7085
- urls.push(url);
7086
- }
7087
- return urls;
7470
+ this.windows.dropPages();
7471
+ await this.closeContext(context);
7472
+ throw error;
7088
7473
  }
7089
- async snapshotNamed(owner, tab, signal) {
7090
- if (tab === void 0) return void 0;
7091
- const live = this.windows.get(owner, tab);
7092
- if (live === void 0) return void 0;
7093
- const shown = await this.refreshSnapshot(live, signal);
7094
- this.shown.set(live.id, shown);
7095
- return this.pageFromShown(live, shown, { surface: "snapshot" }, signal);
7096
- }
7097
- exclusive(owner, op, signal) {
7098
- const queued = enqueue(this.queues.get(owner) ?? Promise.resolve(), op, signal);
7099
- this.queues.set(owner, queued.tail);
7100
- queued.tail.then(() => {
7101
- if (this.queues.get(owner) === queued.tail) this.queues.delete(owner);
7102
- if (this.queues.size === 0) this.relaunchIfIdle();
7103
- });
7104
- return queued.run;
7474
+ if (plan.remember !== void 0) await writeLastBrowser(this.profileRoot, plan.remember).catch((error) => {
7475
+ const reason = error instanceof Error ? error.message : String(error);
7476
+ this.ctx.logger.warn("browser choice was not recorded: %s", reason);
7477
+ });
7478
+ if (this.configEpoch === epoch) this.relaunchWanted = false;
7479
+ context.browser()?.on("disconnected", () => {
7480
+ if (this.closing || this.replacing || this.context !== context) return;
7481
+ this.onExit();
7482
+ });
7483
+ }
7484
+ /** No window opens on exit: the person may have quit it. Calls on old tabs find none. */
7485
+ onExit() {
7486
+ this.windows.suppressPersonInput();
7487
+ this.windows.dropPages();
7488
+ this.context = void 0;
7489
+ this.exits.push(Date.now());
7490
+ this.exited = true;
7491
+ this.ready = Promise.resolve();
7492
+ }
7493
+ /**
7494
+ * The browser for a call that needs a page. One that is not running starts
7495
+ * again here. The exit limit stops unattended restarts; a person's request
7496
+ * is one start per click and skips it.
7497
+ */
7498
+ up(byPerson = false) {
7499
+ if (!this.exited || this.closing) return this.ready;
7500
+ const now = Date.now();
7501
+ while (this.exits.length > 0 && now - (this.exits[0] ?? now) > RELAUNCH_WINDOW_MS) this.exits.shift();
7502
+ if (!byPerson && this.exits.length > RELAUNCH_LIMIT) {
7503
+ this.ctx.logger.warn("browser keeps stopping; not starting it again yet");
7504
+ return Promise.reject(new MhBrowserError(BROWSER_UNAVAILABLE, `the browser stopped or did not start ${String(this.exits.length)} times within ${String(RELAUNCH_WINDOW_MS / 1e3)} s; try again in a minute`));
7505
+ }
7506
+ this.exited = false;
7507
+ const started = this.launch();
7508
+ started.then(() => this.windows.resumePersonInput(), () => {
7509
+ this.exited = true;
7510
+ if (!this.closing) this.exits.push(Date.now());
7511
+ });
7512
+ this.ready = started;
7513
+ return started;
7514
+ }
7515
+ async stop() {
7516
+ this.windows.suppressPersonInput();
7517
+ await Promise.race([this.ready.catch(() => void 0), new Promise((resolve) => setTimeout(resolve, STOP_WAIT_MS))]);
7518
+ const context = this.context;
7519
+ this.context = void 0;
7520
+ if (context !== void 0) await this.closeContext(context);
7521
+ }
7522
+ /** Close a context the service is done with, and kill it if close stalls. */
7523
+ async closeContext(context) {
7524
+ await closeOrKill(() => context.close(), this.pids.get(context));
7525
+ this.pids.delete(context);
7526
+ }
7527
+ refuseIfPerson(owner, tab) {
7528
+ if (this.control.ofTab(owner, tab) !== "person") return;
7529
+ throw new MhBrowserError("PERSON_IN_CONTROL", "the person is using this tab; call browser_handover with this tab to wait until they hand it back, or work in another tab");
7530
+ }
7531
+ async takenOver(live, note = "") {
7532
+ try {
7533
+ const page = await this.pageFromShown(live, this.shown.get(live.id), { surface: "snapshot" });
7534
+ return new MhBrowserError("TAKEN_OVER", `${MAY_HAVE_TAKEN_EFFECT}${note}`, page);
7535
+ } catch {
7536
+ return new MhBrowserError("TAKEN_OVER", `${MAY_HAVE_TAKEN_EFFECT}${note}`);
7105
7537
  }
7106
- launchChoice() {
7107
- const configured = this.executablePath.get();
7108
- return {
7109
- browser: this.browserName.get(),
7110
- headless: this.headless,
7111
- profileDir: this.profileDir,
7112
- ...configured !== void 0 && configured !== "" ? { executablePath: configured } : {}
7113
- };
7538
+ }
7539
+ presenceUrls(owner, tabs) {
7540
+ const known = new Set(this.book.entries(owner).map((page) => page.url));
7541
+ const urls = [];
7542
+ for (const id of tabs) {
7543
+ const address = this.windows.urlOf(owner, id);
7544
+ if (address === void 0) continue;
7545
+ const url = canonical(address);
7546
+ if (!known.has(url) || urls.includes(url)) continue;
7547
+ urls.push(url);
7114
7548
  }
7115
- locateEnv() {
7116
- return this.locator ?? hostLocateEnv();
7117
- }
7118
- idle() {
7119
- return this.queues.size === 0 && !this.control.busy();
7120
- }
7121
- /**
7122
- * Close and start again when a configuration change is waiting and nothing
7123
- * is using the browser. A browser that is not running keeps the new values
7124
- * for the next start. The close is not counted as a crash.
7125
- */
7126
- relaunchIfIdle() {
7127
- if (!this.relaunchWanted || this.closing || this.replacing) return;
7128
- if (!this.idle()) return;
7129
- if (this.context === void 0) {
7130
- if (this.exited) {
7131
- this.relaunchWanted = false;
7132
- return;
7133
- }
7134
- this.ready.then(() => this.relaunchIfIdle(), () => {
7135
- this.relaunchWanted = false;
7136
- });
7549
+ return urls;
7550
+ }
7551
+ async snapshotNamed(owner, tab, signal) {
7552
+ if (tab === void 0) return void 0;
7553
+ const live = this.windows.get(owner, tab);
7554
+ if (live === void 0) return void 0;
7555
+ const shown = await this.refreshSnapshot(live, signal);
7556
+ this.shown.set(live.id, shown);
7557
+ return this.pageFromShown(live, shown, { surface: "snapshot" }, signal);
7558
+ }
7559
+ exclusive(owner, op, signal) {
7560
+ const queued = enqueue(this.queues.get(owner) ?? Promise.resolve(), op, signal);
7561
+ this.queues.set(owner, queued.tail);
7562
+ queued.tail.then(() => {
7563
+ if (this.queues.get(owner) === queued.tail) this.queues.delete(owner);
7564
+ if (this.queues.size === 0) this.relaunchIfIdle();
7565
+ });
7566
+ return queued.run;
7567
+ }
7568
+ locateEnv() {
7569
+ return this.locator ?? hostLocateEnv();
7570
+ }
7571
+ idle() {
7572
+ return this.queues.size === 0 && !this.control.busy();
7573
+ }
7574
+ /**
7575
+ * Close and start again when a configuration change is waiting and nothing
7576
+ * is using the browser. A browser that is not running keeps the new values
7577
+ * for the next start. The close is not counted as a crash.
7578
+ */
7579
+ relaunchIfIdle() {
7580
+ if (!this.relaunchWanted || this.closing || this.replacing) return;
7581
+ if (!this.idle()) return;
7582
+ if (this.context === void 0) {
7583
+ if (this.exited) {
7584
+ this.relaunchWanted = false;
7137
7585
  return;
7138
7586
  }
7139
- this.relaunchWanted = false;
7140
- this.replacing = true;
7141
- const run = this.replaceBrowser();
7142
- this.ready = run;
7143
- const finish = () => {
7144
- this.replacing = false;
7145
- if (this.relaunchWanted) this.relaunchIfIdle();
7146
- };
7147
- run.then(finish, finish);
7587
+ this.ready.then(() => this.relaunchIfIdle(), () => {
7588
+ this.relaunchWanted = false;
7589
+ });
7590
+ return;
7148
7591
  }
7149
- async replaceBrowser() {
7150
- this.windows.suppressPersonInput();
7151
- const context = this.context;
7152
- this.context = void 0;
7153
- this.windows.dropPages();
7154
- if (context !== void 0) await this.closeContext(context);
7155
- if (this.closing) return;
7156
- this.exited = false;
7157
- try {
7158
- await this.launch();
7159
- this.windows.resumePersonInput();
7160
- } catch (error) {
7161
- this.exited = true;
7162
- throw error;
7163
- }
7592
+ this.relaunchWanted = false;
7593
+ this.replacing = true;
7594
+ const run = this.replaceBrowser();
7595
+ this.ready = run;
7596
+ const finish = () => {
7597
+ this.replacing = false;
7598
+ if (this.relaunchWanted) this.relaunchIfIdle();
7599
+ };
7600
+ run.then(finish, finish);
7601
+ }
7602
+ async replaceBrowser() {
7603
+ this.windows.suppressPersonInput();
7604
+ const context = this.context;
7605
+ this.context = void 0;
7606
+ this.windows.dropPages();
7607
+ if (context !== void 0) await this.closeContext(context);
7608
+ if (this.closing) return;
7609
+ this.exited = false;
7610
+ try {
7611
+ await this.launch();
7612
+ this.windows.resumePersonInput();
7613
+ } catch (error) {
7614
+ this.exited = true;
7615
+ throw error;
7164
7616
  }
7165
- };
7166
- })();
7617
+ }
7618
+ };
7167
7619
  const MAX_REDIRECTS = 10;
7168
7620
  /** GET with the profile's cookies for each hop, so the body can be streamed. */
7169
7621
  async function getWithCookies(context, url, signal) {
@@ -7936,6 +8388,7 @@ async function apply(ctx, config) {
7936
8388
  }
7937
8389
  });
7938
8390
  await ctx.plugin(MhBrowserService, resolved);
8391
+ ctx.plugin(browserRoutesPlugin);
7939
8392
  await ctx.plugin({
7940
8393
  name: "mh-browser-runtime",
7941
8394
  inject: ["mhBrowser", ...inject],