omowright 0.3.2 → 0.3.4

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/dist/index.js CHANGED
@@ -24457,6 +24457,29 @@ async function emulateMedia(options = {}) {
24457
24457
  await updateSessions(this, state);
24458
24458
  }
24459
24459
 
24460
+ // src/redact-value.ts
24461
+ function redactValue(error, value) {
24462
+ if (value.length === 0)
24463
+ return error;
24464
+ const replacement = `<redacted, ${value.length} chars>`;
24465
+ const forms = [...new Set([value, JSON.stringify(value).slice(1, -1)])].toSorted((left, right) => right.length - left.length).map((form) => form.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
24466
+ const pattern = new RegExp(`(?<![\\p{L}\\p{N}])(?:${forms.join("|")})(?![\\p{L}\\p{N}])`, "gu");
24467
+ const scrub = (text) => text.replace(pattern, replacement);
24468
+ if (typeof error === "string")
24469
+ return scrub(error);
24470
+ const seen = new Set;
24471
+ for (let link = error;link instanceof Error && !seen.has(link); link = link.cause) {
24472
+ seen.add(link);
24473
+ link.message = scrub(link.message);
24474
+ if (link.stack !== undefined)
24475
+ link.stack = scrub(link.stack);
24476
+ const data = Reflect.get(link, "data");
24477
+ if (data !== undefined)
24478
+ Reflect.set(link, "data", JSON.parse(scrub(JSON.stringify(data) ?? "null")));
24479
+ }
24480
+ return error;
24481
+ }
24482
+
24460
24483
  // src/core.ts
24461
24484
  function definedOrThrow(value) {
24462
24485
  if (value === undefined)
@@ -27465,8 +27488,12 @@ function createLocatorClass() {
27465
27488
  await clickElement(this.#e, jn, xn, this.#e.modifierState);
27466
27489
  }
27467
27490
  async fill(xn) {
27468
- let jn = await this.#r();
27469
- await fillElement(this.#e, jn, xn);
27491
+ try {
27492
+ let jn = await this.#r();
27493
+ await fillElement(this.#e, jn, xn);
27494
+ } catch (jn) {
27495
+ throw redactValue(jn, xn);
27496
+ }
27470
27497
  }
27471
27498
  async selectOption(xn) {
27472
27499
  let jn = await this.#r();
@@ -27485,8 +27512,12 @@ function createLocatorClass() {
27485
27512
  await pressElement(this.#e, jn, xn, this.#e.keyboard);
27486
27513
  }
27487
27514
  async pressSequentially(xn, jn = {}) {
27488
- let Vn = await this.#r();
27489
- await pressSequentiallyElement(this.#e, Vn, xn, jn.delay, this.#e.keyboard);
27515
+ try {
27516
+ let Vn = await this.#r();
27517
+ await pressSequentiallyElement(this.#e, Vn, xn, jn.delay, this.#e.keyboard);
27518
+ } catch (Vn) {
27519
+ throw redactValue(Vn, xn);
27520
+ }
27490
27521
  }
27491
27522
  async hover() {
27492
27523
  let xn = await this.#r();
@@ -30394,6 +30425,104 @@ async function acquireSharedConnection(webSocketDebuggerUrl, options, { open, ti
30394
30425
  }
30395
30426
  }
30396
30427
 
30428
+ // src/emulate.ts
30429
+ var DEVICE_PRESETS = Object.freeze({
30430
+ "iphone-14": {
30431
+ width: 390,
30432
+ height: 844,
30433
+ deviceScaleFactor: 3,
30434
+ mobile: true,
30435
+ hasTouch: true,
30436
+ userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",
30437
+ platform: "iPhone"
30438
+ },
30439
+ "pixel-7": {
30440
+ width: 412,
30441
+ height: 915,
30442
+ deviceScaleFactor: 2.625,
30443
+ mobile: true,
30444
+ hasTouch: true,
30445
+ userAgent: "Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",
30446
+ platform: "Linux armv8l"
30447
+ },
30448
+ "ipad-air": {
30449
+ width: 820,
30450
+ height: 1180,
30451
+ deviceScaleFactor: 2,
30452
+ mobile: true,
30453
+ hasTouch: true,
30454
+ userAgent: "Mozilla/5.0 (iPad; CPU OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",
30455
+ platform: "MacIntel"
30456
+ },
30457
+ "desktop-1440": {
30458
+ width: 1440,
30459
+ height: 900,
30460
+ deviceScaleFactor: 1,
30461
+ mobile: false,
30462
+ hasTouch: false,
30463
+ userAgent: undefined,
30464
+ platform: undefined
30465
+ }
30466
+ });
30467
+ var presetsByName = DEVICE_PRESETS;
30468
+ var originalUAs = new WeakMap;
30469
+ var emulatedDevices = new WeakMap;
30470
+ function emulatedDevice(page) {
30471
+ return emulatedDevices.get(page);
30472
+ }
30473
+ async function emulate(page, presetNameOrObject) {
30474
+ let preset;
30475
+ if (presetNameOrObject === null) {
30476
+ preset = null;
30477
+ } else if (typeof presetNameOrObject === "string") {
30478
+ const named = presetsByName[presetNameOrObject];
30479
+ if (!named) {
30480
+ throw new Error(`unknown device preset: ${presetNameOrObject}`);
30481
+ }
30482
+ preset = named;
30483
+ } else {
30484
+ preset = presetNameOrObject;
30485
+ }
30486
+ const sessionId = await page.resolveSessionId();
30487
+ if (preset === null) {
30488
+ await page.cdp.send("Emulation.clearDeviceMetricsOverride", {}, sessionId);
30489
+ await page.cdp.send("Emulation.setTouchEmulationEnabled", { enabled: false }, sessionId);
30490
+ emulatedDevices.delete(page);
30491
+ const originalUA = originalUAs.get(page);
30492
+ if (originalUA) {
30493
+ await page.cdp.send("Emulation.setUserAgentOverride", { userAgent: originalUA }, sessionId);
30494
+ }
30495
+ } else {
30496
+ if (!originalUAs.has(page)) {
30497
+ const ua = await page.evaluate(() => navigator.userAgent);
30498
+ originalUAs.set(page, ua);
30499
+ }
30500
+ await page.cdp.send("Emulation.setDeviceMetricsOverride", {
30501
+ width: preset.width,
30502
+ height: preset.height,
30503
+ deviceScaleFactor: preset.deviceScaleFactor,
30504
+ mobile: preset.mobile,
30505
+ screenWidth: preset.width,
30506
+ screenHeight: preset.height
30507
+ }, sessionId);
30508
+ emulatedDevices.set(page, preset);
30509
+ await page.cdp.send("Emulation.setTouchEmulationEnabled", {
30510
+ enabled: preset.hasTouch,
30511
+ maxTouchPoints: preset.hasTouch ? 5 : 1
30512
+ }, sessionId);
30513
+ if (preset.userAgent !== undefined) {
30514
+ await page.cdp.send("Emulation.setUserAgentOverride", {
30515
+ userAgent: preset.userAgent,
30516
+ platform: preset.platform
30517
+ }, sessionId);
30518
+ }
30519
+ }
30520
+ if (page.refreshViewportSize) {
30521
+ await page.refreshViewportSize();
30522
+ }
30523
+ return preset;
30524
+ }
30525
+
30397
30526
  // src/agent-tabs.ts
30398
30527
  var managers = new WeakMap;
30399
30528
  var CAPABILITY = targetCreationCapability;
@@ -30497,13 +30626,13 @@ class AgentTabManager {
30497
30626
  const version = await this.#connection.cdp.send("Browser.getVersion").catch(() => null);
30498
30627
  return /Headless/i.test(version?.product ?? "");
30499
30628
  }
30500
- #queueRepin(record, viewport, reportErrors = false) {
30629
+ #queueRepin(record, viewport, reportErrors = false, device) {
30501
30630
  const size = { ...viewport };
30502
30631
  const operation = record.repinQueue.then(async () => {
30503
30632
  try {
30504
30633
  if (record.page === null)
30505
30634
  throw new TypeError("Cannot read properties of null (reading 'resolveSessionId')");
30506
- await repinViewport(record.page, size);
30635
+ await repinViewport(record.page, device ?? size, device);
30507
30636
  } catch (error) {
30508
30637
  if (reportErrors)
30509
30638
  console.warn(`[agent-tabs] viewport repin failed for ${record.targetId}`, error);
@@ -30517,7 +30646,7 @@ class AgentTabManager {
30517
30646
  return operation;
30518
30647
  }
30519
30648
  async#repin(record) {
30520
- await this.#queueRepin(record, record.viewport, true);
30649
+ await this.#queueRepin(record, record.viewport, true, record.page === null ? undefined : emulatedDevice(record.page));
30521
30650
  }
30522
30651
  async repin(tabOrTargetId, viewport = this.viewport) {
30523
30652
  const id = typeof tabOrTargetId === "string" ? tabOrTargetId : tabOrTargetId?.targetId;
@@ -35468,97 +35597,6 @@ function createChromeApi2(connection, options = {}) {
35468
35597
  }
35469
35598
  return chrome;
35470
35599
  }
35471
- // src/emulate.ts
35472
- var DEVICE_PRESETS = Object.freeze({
35473
- "iphone-14": {
35474
- width: 390,
35475
- height: 844,
35476
- deviceScaleFactor: 3,
35477
- mobile: true,
35478
- hasTouch: true,
35479
- userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",
35480
- platform: "iPhone"
35481
- },
35482
- "pixel-7": {
35483
- width: 412,
35484
- height: 915,
35485
- deviceScaleFactor: 2.625,
35486
- mobile: true,
35487
- hasTouch: true,
35488
- userAgent: "Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",
35489
- platform: "Linux armv8l"
35490
- },
35491
- "ipad-air": {
35492
- width: 820,
35493
- height: 1180,
35494
- deviceScaleFactor: 2,
35495
- mobile: true,
35496
- hasTouch: true,
35497
- userAgent: "Mozilla/5.0 (iPad; CPU OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",
35498
- platform: "MacIntel"
35499
- },
35500
- "desktop-1440": {
35501
- width: 1440,
35502
- height: 900,
35503
- deviceScaleFactor: 1,
35504
- mobile: false,
35505
- hasTouch: false,
35506
- userAgent: undefined,
35507
- platform: undefined
35508
- }
35509
- });
35510
- var presetsByName = DEVICE_PRESETS;
35511
- var originalUAs = new WeakMap;
35512
- async function emulate(page, presetNameOrObject) {
35513
- let preset;
35514
- if (presetNameOrObject === null) {
35515
- preset = null;
35516
- } else if (typeof presetNameOrObject === "string") {
35517
- const named = presetsByName[presetNameOrObject];
35518
- if (!named) {
35519
- throw new Error(`unknown device preset: ${presetNameOrObject}`);
35520
- }
35521
- preset = named;
35522
- } else {
35523
- preset = presetNameOrObject;
35524
- }
35525
- const sessionId = await page.resolveSessionId();
35526
- if (preset === null) {
35527
- await page.cdp.send("Emulation.clearDeviceMetricsOverride", {}, sessionId);
35528
- await page.cdp.send("Emulation.setTouchEmulationEnabled", { enabled: false }, sessionId);
35529
- const originalUA = originalUAs.get(page);
35530
- if (originalUA) {
35531
- await page.cdp.send("Emulation.setUserAgentOverride", { userAgent: originalUA }, sessionId);
35532
- }
35533
- } else {
35534
- if (!originalUAs.has(page)) {
35535
- const ua = await page.evaluate(() => navigator.userAgent);
35536
- originalUAs.set(page, ua);
35537
- }
35538
- await page.cdp.send("Emulation.setDeviceMetricsOverride", {
35539
- width: preset.width,
35540
- height: preset.height,
35541
- deviceScaleFactor: preset.deviceScaleFactor,
35542
- mobile: preset.mobile,
35543
- screenWidth: preset.width,
35544
- screenHeight: preset.height
35545
- }, sessionId);
35546
- await page.cdp.send("Emulation.setTouchEmulationEnabled", {
35547
- enabled: preset.hasTouch,
35548
- maxTouchPoints: preset.hasTouch ? 5 : 1
35549
- }, sessionId);
35550
- if (preset.userAgent !== undefined) {
35551
- await page.cdp.send("Emulation.setUserAgentOverride", {
35552
- userAgent: preset.userAgent,
35553
- platform: preset.platform
35554
- }, sessionId);
35555
- }
35556
- }
35557
- if (page.refreshViewportSize) {
35558
- await page.refreshViewportSize();
35559
- }
35560
- return preset;
35561
- }
35562
35600
  // src/frames-snapshot.ts
35563
35601
  var AUTO_ATTACH = { autoAttach: true, waitForDebuggerOnStart: false, flatten: true };
35564
35602
  var REF_PATTERN2 = /^(f\d+)?e\d+$/;
@@ -35665,7 +35703,7 @@ async function snapshotWithFrames(page, opts = {}) {
35665
35703
  // package.json
35666
35704
  var package_default = {
35667
35705
  name: "omowright",
35668
- version: "0.3.2",
35706
+ version: "0.3.4",
35669
35707
  description: "OmOWright browser automation for standard Chromium CDP endpoints.",
35670
35708
  keywords: [
35671
35709
  "accessibility-snapshot",
@@ -35716,7 +35754,7 @@ var package_default = {
35716
35754
  "test:cloak-profile": "bun test test/cloak-profile.test.ts test/cloak-profile.integration.test.ts",
35717
35755
  typecheck: "bun check --no-script --no-pretty -p tsconfig.json",
35718
35756
  "typecheck:control": "bun scripts/typecheck-control.ts",
35719
- check: "bun run typecheck:control && bun run typecheck && bun run lint && bun run fmt:check",
35757
+ check: "bun scripts/bsk-protocol.ts --check && bun run typecheck:control && bun run typecheck && bun run lint && bun run fmt:check",
35720
35758
  lint: "oxlint --deny-warnings src bin bridge test scripts && bun scripts/lint-ratchet.ts",
35721
35759
  "lint:ratchet:update": "bun scripts/lint-ratchet.ts --update",
35722
35760
  "lint:fix": "oxlint --fix src bin bridge test scripts",
@@ -36358,6 +36396,7 @@ async function* collectWhileScrolling(page, snoop, options = {}) {
36358
36396
  scroll = "wheel",
36359
36397
  settleMs = 800
36360
36398
  } = options;
36399
+ const clock = options.clock ?? globalThis;
36361
36400
  if (scroll !== "wheel" && scroll !== "end")
36362
36401
  throw new TypeError(`Unknown scroll mode: ${String(scroll)}`);
36363
36402
  let rounds = 0;
@@ -36396,9 +36435,33 @@ async function* collectWhileScrolling(page, snoop, options = {}) {
36396
36435
  unchanged = 0;
36397
36436
  }
36398
36437
  lastHeight = height;
36438
+ let timer;
36439
+ const deadline = new Promise((resolve) => {
36440
+ timer = clock.setTimeout(resolve, settleMs);
36441
+ });
36442
+ const response = snoop.waitFor((entry) => JSON_MIME.test(String(entry.mimeType ?? "")), { timeoutMs: settleMs }).catch(() => deadline);
36443
+ const growth = page.evaluate(({ baseline, cleanupMs }) => new Promise((resolve) => {
36444
+ const element = document.scrollingElement;
36445
+ if (!element)
36446
+ throw new TypeError("Cannot read properties of null (reading 'scrollHeight')");
36447
+ const finish = (grew) => {
36448
+ observer.disconnect();
36449
+ clearTimeout(cleanup);
36450
+ resolve(grew);
36451
+ };
36452
+ const observer = new ResizeObserver(() => {
36453
+ if (element.scrollHeight > baseline)
36454
+ finish(true);
36455
+ });
36456
+ const cleanup = setTimeout(() => finish(false), cleanupMs);
36457
+ observer.observe(element);
36458
+ if (element.scrollHeight > baseline)
36459
+ finish(true);
36460
+ }), { baseline: height, cleanupMs: settleMs }).then((grew) => grew ? undefined : deadline, () => deadline);
36399
36461
  await scrollOnce(page, scroll);
36400
36462
  rounds += 1;
36401
- await new Promise((resolve) => setTimeout(resolve, settleMs));
36463
+ await Promise.race([deadline, response, growth]);
36464
+ clock.clearTimeout(timer);
36402
36465
  }
36403
36466
  return { rounds, total, stoppedBecause };
36404
36467
  }
@@ -37129,7 +37192,7 @@ function decodeResponse(line, rpcId, method) {
37129
37192
  }
37130
37193
  // src/bsk/targets.ts
37131
37194
  var REF_SHAPE = /^@?e\d+$/;
37132
- function resolveTarget(target) {
37195
+ function elementTarget(target) {
37133
37196
  if (typeof target === "string") {
37134
37197
  return REF_SHAPE.test(target) ? { ref: target } : { selector: target };
37135
37198
  }
@@ -37139,14 +37202,31 @@ function resolveTarget(target) {
37139
37202
  return { ref: spec.ref };
37140
37203
  if (typeof spec.selector === "string")
37141
37204
  return { selector: spec.selector };
37205
+ }
37206
+ return;
37207
+ }
37208
+ function resolveTarget(target) {
37209
+ const element = elementTarget(target);
37210
+ if (element)
37211
+ return element;
37212
+ if (target && typeof target === "object") {
37213
+ const spec = target;
37142
37214
  if (typeof spec.captureId === "string") {
37215
+ if (typeof spec.x !== "number" || typeof spec.y !== "number")
37216
+ throw new TypeError("a {captureId, x, y} target needs numeric x and y image coordinates");
37143
37217
  return { capture_id: spec.captureId, image_x: spec.x, image_y: spec.y };
37144
37218
  }
37145
37219
  }
37146
37220
  throw new TypeError("target must be a ref ('e3' / '@e3'), a CSS selector, or {captureId, x, y}");
37147
37221
  }
37148
- function optionalTarget(target) {
37149
- return target === undefined ? {} : resolveTarget(target);
37222
+ function resolveElementTarget(target) {
37223
+ const element = elementTarget(target);
37224
+ if (element)
37225
+ return element;
37226
+ throw new TypeError("target must be a ref ('e3' / '@e3') or a CSS selector");
37227
+ }
37228
+ function optionalElementTarget(target) {
37229
+ return target === undefined ? {} : resolveElementTarget(target);
37150
37230
  }
37151
37231
  function compact(params) {
37152
37232
  const out = {};
@@ -37156,13 +37236,22 @@ function compact(params) {
37156
37236
  return out;
37157
37237
  }
37158
37238
 
37239
+ // src/bsk/shared-tab.ts
37240
+ function sharedTab({ context, observation, expect, dependsOn, ...unknown }) {
37241
+ const extra = Object.keys(unknown);
37242
+ if (extra.length > 0) {
37243
+ throw new TypeError(`unknown option ${extra.map((key) => JSON.stringify(key)).join(", ")}: a shared-tab action takes { context, observation, expect, dependsOn } besides its own options`);
37244
+ }
37245
+ return { context_id: context, observation_id: observation, expect, depends_on: dependsOn };
37246
+ }
37247
+
37159
37248
  // src/bsk/screenshot.ts
37160
37249
  function fromBase64(value, field) {
37161
37250
  if (typeof value !== "string")
37162
37251
  throw new TypeError(`${field} is not base64 text`);
37163
37252
  return Buffer.from(value, "base64");
37164
37253
  }
37165
- async function captureScreenshot(session, { ref, tabId, fullPage = false, scope, timeoutMs, context, dependsOn } = {}) {
37254
+ async function captureScreenshot(session, { ref, tabId, fullPage = false, scope, timeoutMs, ...shared } = {}) {
37166
37255
  if (!fullPage) {
37167
37256
  const result = await session.tool("screenshot", { ref, tab_id: tabId });
37168
37257
  return {
@@ -37180,16 +37269,18 @@ async function captureScreenshot(session, { ref, tabId, fullPage = false, scope,
37180
37269
  scope,
37181
37270
  tab_id: tabId,
37182
37271
  timeout_ms: timeoutMs,
37183
- context_id: context,
37184
- depends_on: dependsOn
37272
+ ...sharedTab(shared)
37185
37273
  });
37186
- const buffer = await readCapture(session, readProperty(started, "capture_id"), readProperty(started, "byte_size"));
37274
+ const captureId = readProperty(started, "capture_id");
37275
+ if (typeof captureId !== "string")
37276
+ throw new TypeError("screenshot_full_page returned no capture_id");
37277
+ const buffer = await readCapture(session, captureId, readProperty(started, "byte_size"));
37187
37278
  return {
37188
37279
  buffer,
37189
37280
  width: readProperty(started, "width"),
37190
37281
  height: readProperty(started, "height"),
37191
37282
  format: readProperty(started, "format"),
37192
- captureId: readProperty(started, "capture_id"),
37283
+ captureId,
37193
37284
  scope: readProperty(started, "scope") ?? scope ?? null,
37194
37285
  tabId: readProperty(started, "tab_id"),
37195
37286
  dialogs: readProperty(started, "dialogs") ?? []
@@ -37220,19 +37311,85 @@ async function readCapture(session, captureId, byteSize) {
37220
37311
  return buffer;
37221
37312
  }
37222
37313
 
37314
+ // src/bsk/first-navigate.ts
37315
+ var BOOTSTRAP_REFUSAL = "The initial task tab changed; synchronize before acting";
37316
+ var BOOTSTRAP_SETTLE_TIMEOUT_MS = 1e4;
37317
+ var INITIAL_BLANK_URLS = new Set(["", "about:blank"]);
37318
+ function isBootstrapRefusal(error) {
37319
+ return error instanceof BskRpcError && error.code === "permission_denied" && error.message === BOOTSTRAP_REFUSAL && optionalProperty(error.data, "reason") === "cooperation_sync_required" && optionalProperty(error.data, "effect_state") === "none";
37320
+ }
37321
+ function taskTab(tabs, tabId) {
37322
+ const list = listOrEmpty(readProperty(tabs, "tabs"), "tab_list tabs");
37323
+ return tabId === undefined ? list.find((tab) => optionalProperty(tab, "active") === true) : list.find((tab) => optionalProperty(tab, "tab_id") === tabId);
37324
+ }
37325
+ async function settleInitialTab(session, refusal, tabId) {
37326
+ const waited = await session.waitForNavigation({
37327
+ ...tabId === undefined ? {} : { tabId },
37328
+ waitUntil: "load",
37329
+ timeoutMs: BOOTSTRAP_SETTLE_TIMEOUT_MS
37330
+ });
37331
+ const reached = optionalProperty(waited, "reached");
37332
+ const tab = taskTab(await session.tabList({ scope: "agent" }), tabId);
37333
+ const url = optionalProperty(tab, "url");
37334
+ if (reached === "load" && INITIAL_BLANK_URLS.has(url))
37335
+ return;
37336
+ const where = tab === undefined ? "no task tab is listed" : `tab ${String(optionalProperty(tab, "tab_id"))} is at ${url === "" ? "(no URL yet)" : String(url)}`;
37337
+ throw new BskRpcError(refusal.code, `${refusal.message}: the first navigate was refused before the task tab settled, and it was not sent again because wait_for_navigation reached ${JSON.stringify(reached)} and ${where}`, refusal.data);
37338
+ }
37339
+
37340
+ // src/bsk/dom-reads.ts
37341
+ function readNodes(session, target, { fields, maxNodes, maxBytes, tabId, timeoutMs, context } = {}) {
37342
+ return session.tool("read", {
37343
+ ...optionalElementTarget(target),
37344
+ fields,
37345
+ max_nodes: maxNodes,
37346
+ max_bytes: maxBytes,
37347
+ tab_id: tabId,
37348
+ timeout_ms: timeoutMs,
37349
+ context_id: context
37350
+ });
37351
+ }
37352
+ function extractItems(session, action, { target, itemSelector, fields, maxRows, maxColumns, maxBytes, targetId, tabId, timeoutMs } = {}) {
37353
+ return session.tool("extract", {
37354
+ action,
37355
+ ...optionalElementTarget(target),
37356
+ item_selector: itemSelector,
37357
+ fields,
37358
+ max_rows: maxRows,
37359
+ max_columns: maxColumns,
37360
+ max_bytes: maxBytes,
37361
+ target_id: targetId,
37362
+ tab_id: tabId,
37363
+ timeout_ms: timeoutMs
37364
+ });
37365
+ }
37366
+ function waitForElement(session, target, { state, pollMs, tabId, timeoutMs }) {
37367
+ return session.tool("wait_for_element", {
37368
+ ...resolveElementTarget(target),
37369
+ state,
37370
+ poll_ms: pollMs,
37371
+ tab_id: tabId,
37372
+ timeout_ms: timeoutMs
37373
+ });
37374
+ }
37375
+
37223
37376
  // src/bsk/session.ts
37224
37377
  var SESSION_STOP_TIMEOUT_MS = 3600000;
37225
- function sharedTab({ context, dependsOn, ...unknown }) {
37226
- const extra = Object.keys(unknown);
37227
- if (extra.length > 0) {
37228
- throw new TypeError(`unknown option ${extra.map((key) => JSON.stringify(key)).join(", ")}: a shared-tab action takes { context, dependsOn } besides its own options`);
37229
- }
37230
- return { context_id: context, depends_on: dependsOn };
37378
+ var text = (value) => typeof value === "string" ? value : undefined;
37379
+ function cooperateReply(reply) {
37380
+ const fields = typeof reply === "object" && reply !== null ? reply : {};
37381
+ const nested = optionalProperty(optionalProperty(reply, "observation"), "observation_id");
37382
+ return {
37383
+ ...fields,
37384
+ context_id: text(optionalProperty(reply, "context_id")),
37385
+ observation_id: text(optionalProperty(reply, "observation_id")) ?? text(nested)
37386
+ };
37231
37387
  }
37232
37388
 
37233
37389
  class BskSession {
37234
37390
  #client;
37235
37391
  #stopped = false;
37392
+ #acted = false;
37236
37393
  constructor(client, { sessionId, browserInstanceId = null, agentWindowId = null, interaction = null } = {}) {
37237
37394
  if (typeof sessionId !== "string" || sessionId.length === 0)
37238
37395
  throw new TypeError("BskSession requires a sessionId");
@@ -37248,6 +37405,14 @@ class BskSession {
37248
37405
  get stopped() {
37249
37406
  return this.#stopped;
37250
37407
  }
37408
+ #call(name, params) {
37409
+ return this.tool(name, params);
37410
+ }
37411
+ #act(name, params, shared) {
37412
+ const wire = { ...params, ...sharedTab(shared) };
37413
+ this.#acted = true;
37414
+ return this.tool(name, wire);
37415
+ }
37251
37416
  tool(name, params = {}) {
37252
37417
  if (this.#stopped)
37253
37418
  return Promise.reject(new Error(`BrowserSkill session ${this.sessionId} is stopped`));
@@ -37255,33 +37420,41 @@ class BskSession {
37255
37420
  idPrefix: name.replace(/_/g, "-")
37256
37421
  });
37257
37422
  }
37258
- cooperate(action, { tabId, timeoutMs, maxTokens } = {}) {
37259
- return this.tool("cooperate", { action, tab_id: tabId, timeout_ms: timeoutMs, max_tokens: maxTokens });
37260
- }
37261
- navigate(url, { tabId, waitUntil, timeoutMs, ...shared } = {}) {
37262
- return this.tool("navigate", {
37263
- url,
37423
+ cooperate(action, {
37424
+ tabId,
37425
+ timeoutMs,
37426
+ maxTokens,
37427
+ controlPolicy
37428
+ } = {}) {
37429
+ return this.#call("cooperate", {
37430
+ action,
37264
37431
  tab_id: tabId,
37265
- wait_until: waitUntil,
37266
37432
  timeout_ms: timeoutMs,
37267
- ...sharedTab(shared)
37433
+ max_tokens: maxTokens,
37434
+ control_policy: controlPolicy
37435
+ }).then(cooperateReply, (error) => {
37436
+ if (error instanceof BskRpcError && error.code === "unknown_method")
37437
+ return { context_id: undefined, observation_id: undefined, supported: false, ready: true };
37438
+ throw error;
37268
37439
  });
37269
37440
  }
37441
+ async navigate(url, { tabId, waitUntil, timeoutMs, ...shared } = {}) {
37442
+ const send = () => this.#act("navigate", { url, tab_id: tabId, wait_until: waitUntil, timeout_ms: timeoutMs }, shared);
37443
+ const first = !this.#acted && shared.context === undefined;
37444
+ try {
37445
+ return await send();
37446
+ } catch (error) {
37447
+ if (!first || !isBootstrapRefusal(error))
37448
+ throw error;
37449
+ await settleInitialTab(this, error, tabId);
37450
+ return send();
37451
+ }
37452
+ }
37270
37453
  back({ tabId, waitUntil, timeoutMs, ...shared } = {}) {
37271
- return this.tool("navigate_back", {
37272
- tab_id: tabId,
37273
- wait_until: waitUntil,
37274
- timeout_ms: timeoutMs,
37275
- ...sharedTab(shared)
37276
- });
37454
+ return this.#act("navigate_back", { tab_id: tabId, wait_until: waitUntil, timeout_ms: timeoutMs }, shared);
37277
37455
  }
37278
37456
  forward({ tabId, waitUntil, timeoutMs, ...shared } = {}) {
37279
- return this.tool("navigate_forward", {
37280
- tab_id: tabId,
37281
- wait_until: waitUntil,
37282
- timeout_ms: timeoutMs,
37283
- ...sharedTab(shared)
37284
- });
37457
+ return this.#act("navigate_forward", { tab_id: tabId, wait_until: waitUntil, timeout_ms: timeoutMs }, shared);
37285
37458
  }
37286
37459
  reload({
37287
37460
  tabId,
@@ -37290,13 +37463,7 @@ class BskSession {
37290
37463
  hard,
37291
37464
  ...shared
37292
37465
  } = {}) {
37293
- return this.tool("reload", {
37294
- tab_id: tabId,
37295
- wait_until: waitUntil,
37296
- timeout_ms: timeoutMs,
37297
- hard,
37298
- ...sharedTab(shared)
37299
- });
37466
+ return this.#act("reload", { tab_id: tabId, wait_until: waitUntil, timeout_ms: timeoutMs, hard }, shared);
37300
37467
  }
37301
37468
  observe({
37302
37469
  cursor,
@@ -37307,25 +37474,24 @@ class BskSession {
37307
37474
  probeHover,
37308
37475
  ...shared
37309
37476
  } = {}) {
37310
- return this.tool("observe", {
37477
+ return this.#act("observe", {
37311
37478
  cursor,
37312
37479
  tab_id: tabId,
37313
37480
  max_depth: maxDepth,
37314
37481
  max_tokens: maxTokens,
37315
37482
  debug_surfaces: debugSurfaces,
37316
- probe_hover: probeHover,
37317
- ...sharedTab(shared)
37318
- });
37483
+ probe_hover: probeHover
37484
+ }, shared);
37319
37485
  }
37320
37486
  snapshot({
37321
37487
  tabId,
37322
37488
  maxDepth,
37323
37489
  maxTokens
37324
37490
  } = {}) {
37325
- return this.tool("snapshot", { tab_id: tabId, max_depth: maxDepth, max_tokens: maxTokens });
37491
+ return this.#call("snapshot", { tab_id: tabId, max_depth: maxDepth, max_tokens: maxTokens });
37326
37492
  }
37327
37493
  getHtml({ ref, tabId, maxBytes } = {}) {
37328
- return this.tool("get_html", { ref, tab_id: tabId, max_bytes: maxBytes });
37494
+ return this.#call("get_html", { ref, tab_id: tabId, max_bytes: maxBytes });
37329
37495
  }
37330
37496
  screenshot(options) {
37331
37497
  return captureScreenshot(this, options);
@@ -37338,15 +37504,7 @@ class BskSession {
37338
37504
  timeoutMs,
37339
37505
  ...shared
37340
37506
  } = {}) {
37341
- return this.tool("click", {
37342
- ...resolveTarget(target),
37343
- button,
37344
- click_count: clickCount,
37345
- modifiers,
37346
- tab_id: tabId,
37347
- timeout_ms: timeoutMs,
37348
- ...sharedTab(shared)
37349
- });
37507
+ return this.#act("click", { ...resolveTarget(target), button, click_count: clickCount, modifiers, tab_id: tabId, timeout_ms: timeoutMs }, shared);
37350
37508
  }
37351
37509
  hover(target, {
37352
37510
  modifiers,
@@ -37355,29 +37513,17 @@ class BskSession {
37355
37513
  timeoutMs,
37356
37514
  ...shared
37357
37515
  } = {}) {
37358
- return this.tool("hover", {
37359
- ...resolveTarget(target),
37360
- modifiers,
37361
- settle_ms: settleMs,
37362
- tab_id: tabId,
37363
- timeout_ms: timeoutMs,
37364
- ...sharedTab(shared)
37365
- });
37516
+ return this.#act("hover", { ...resolveElementTarget(target), modifiers, settle_ms: settleMs, tab_id: tabId, timeout_ms: timeoutMs }, shared);
37366
37517
  }
37367
37518
  focus(target, { tabId, timeoutMs, ...shared } = {}) {
37368
- return this.tool("focus", { ...resolveTarget(target), tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
37519
+ return this.#act("focus", { ...resolveElementTarget(target), tab_id: tabId, timeout_ms: timeoutMs }, shared);
37369
37520
  }
37370
37521
  blur(target, { tabId, timeoutMs, ...shared } = {}) {
37371
- return this.tool("blur", { ...resolveTarget(target), tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
37522
+ return this.#act("blur", { ...resolveElementTarget(target), tab_id: tabId, timeout_ms: timeoutMs }, shared);
37372
37523
  }
37373
37524
  fill(target, value, { clearBefore, tabId, timeoutMs, ...shared } = {}) {
37374
- return this.tool("fill", {
37375
- ...resolveTarget(target),
37376
- value,
37377
- clear_before: clearBefore,
37378
- tab_id: tabId,
37379
- timeout_ms: timeoutMs,
37380
- ...sharedTab(shared)
37525
+ return this.#act("fill", { ...resolveElementTarget(target), value, clear_before: clearBefore, tab_id: tabId, timeout_ms: timeoutMs }, shared).catch((error) => {
37526
+ throw redactValue(error, value);
37381
37527
  });
37382
37528
  }
37383
37529
  press(key, {
@@ -37388,32 +37534,18 @@ class BskSession {
37388
37534
  timeoutMs,
37389
37535
  ...shared
37390
37536
  } = {}) {
37391
- return this.tool("press", {
37392
- key,
37393
- ...optionalTarget(target),
37394
- modifiers,
37395
- hold_ms: holdMs,
37396
- tab_id: tabId,
37397
- timeout_ms: timeoutMs,
37398
- ...sharedTab(shared)
37399
- });
37537
+ return this.#act("press", { key, ...optionalElementTarget(target), modifiers, hold_ms: holdMs, tab_id: tabId, timeout_ms: timeoutMs }, shared);
37400
37538
  }
37401
37539
  select(target, values, { tabId, timeoutMs, ...shared } = {}) {
37402
- return this.tool("select", {
37403
- ...resolveTarget(target),
37540
+ return this.#act("select", {
37541
+ ...resolveElementTarget(target),
37404
37542
  values: Array.isArray(values) ? values : [values],
37405
37543
  tab_id: tabId,
37406
- timeout_ms: timeoutMs,
37407
- ...sharedTab(shared)
37408
- });
37544
+ timeout_ms: timeoutMs
37545
+ }, shared);
37409
37546
  }
37410
37547
  scrollTo(target, { tabId, timeoutMs, ...shared } = {}) {
37411
- return this.tool("scroll_to", {
37412
- ...resolveTarget(target),
37413
- tab_id: tabId,
37414
- timeout_ms: timeoutMs,
37415
- ...sharedTab(shared)
37416
- });
37548
+ return this.#act("scroll_to", { ...resolveElementTarget(target), tab_id: tabId, timeout_ms: timeoutMs }, shared);
37417
37549
  }
37418
37550
  wheel({
37419
37551
  deltaX = 0,
@@ -37424,50 +37556,83 @@ class BskSession {
37424
37556
  timeoutMs,
37425
37557
  ...shared
37426
37558
  } = {}) {
37427
- return this.tool("wheel", {
37428
- ...optionalTarget(target),
37559
+ return this.#act("wheel", {
37560
+ ...optionalElementTarget(target),
37429
37561
  delta_x: deltaX,
37430
37562
  delta_y: deltaY,
37431
37563
  modifiers,
37432
37564
  tab_id: tabId,
37433
- timeout_ms: timeoutMs,
37434
- ...sharedTab(shared)
37435
- });
37565
+ timeout_ms: timeoutMs
37566
+ }, shared);
37436
37567
  }
37437
- evaluate(expression, { tabId, awaitPromise, returnByValue, timeoutMs, ...shared } = {}) {
37438
- return this.tool("evaluate", {
37568
+ evaluate(expression, { tabId, awaitPromise, returnByValue, timeoutMs, unverified, ...shared } = {}) {
37569
+ return this.#act("evaluate", {
37439
37570
  expression,
37440
37571
  tab_id: tabId,
37441
37572
  await_promise: awaitPromise,
37442
37573
  return_by_value: returnByValue,
37443
37574
  timeout_ms: timeoutMs,
37444
- ...sharedTab(shared)
37445
- });
37575
+ unverified
37576
+ }, shared);
37577
+ }
37578
+ read(target, options) {
37579
+ return readNodes(this, target, options);
37580
+ }
37581
+ extract(action, options) {
37582
+ return extractItems(this, action, options);
37583
+ }
37584
+ waitForElement(target, options) {
37585
+ return waitForElement(this, target, options);
37586
+ }
37587
+ drag(source, {
37588
+ target,
37589
+ delta,
37590
+ mode,
37591
+ button,
37592
+ durationMs,
37593
+ holdMs,
37594
+ modifiers,
37595
+ tabId,
37596
+ timeoutMs,
37597
+ ...shared
37598
+ } = {}) {
37599
+ return this.#act("drag", {
37600
+ source,
37601
+ target,
37602
+ delta,
37603
+ mode,
37604
+ button,
37605
+ duration_ms: durationMs,
37606
+ hold_ms: holdMs,
37607
+ modifiers,
37608
+ tab_id: tabId,
37609
+ timeout_ms: timeoutMs
37610
+ }, shared);
37446
37611
  }
37447
37612
  tabList({ scope } = {}) {
37448
- return this.tool("tab_list", { scope });
37613
+ return this.#call("tab_list", { scope });
37449
37614
  }
37450
37615
  tabCreate({ url, active, index } = {}) {
37451
- return this.tool("tab_create", { url, active, index });
37616
+ return this.#call("tab_create", { url, active, index });
37452
37617
  }
37453
37618
  tabClose(tabId, shared = {}) {
37454
- return this.tool("tab_close", { tab_id: tabId, ...sharedTab(shared) });
37619
+ return this.#act("tab_close", { tab_id: tabId }, shared);
37455
37620
  }
37456
37621
  tabSelect(tabId) {
37457
- return this.tool("tab_select", { tab_id: tabId });
37622
+ return this.#call("tab_select", { tab_id: tabId });
37458
37623
  }
37459
37624
  tabBorrow(tabId, { confirmationTimeoutMs } = {}) {
37460
- return this.tool("tab_borrow", { tab_id: tabId, confirmation_timeout_ms: confirmationTimeoutMs });
37625
+ return this.#call("tab_borrow", { tab_id: tabId, confirmation_timeout_ms: confirmationTimeoutMs });
37461
37626
  }
37462
37627
  tabReturn(tabId) {
37463
- return this.tool("tab_return", { tab_id: tabId });
37628
+ return this.#call("tab_return", { tab_id: tabId });
37464
37629
  }
37465
37630
  waitForNavigation({
37466
37631
  tabId,
37467
37632
  waitUntil,
37468
37633
  timeoutMs
37469
37634
  } = {}) {
37470
- return this.tool("wait_for_navigation", { tab_id: tabId, wait_until: waitUntil, timeout_ms: timeoutMs });
37635
+ return this.#call("wait_for_navigation", { tab_id: tabId, wait_until: waitUntil, timeout_ms: timeoutMs });
37471
37636
  }
37472
37637
  requestHelp({
37473
37638
  prompt,
@@ -37476,13 +37641,13 @@ class BskSession {
37476
37641
  completionCriteria,
37477
37642
  tabId,
37478
37643
  timeoutMs
37479
- } = {}) {
37480
- return this.tool("request_help", {
37644
+ }) {
37645
+ return this.#call("request_help", {
37481
37646
  prompt,
37482
37647
  title,
37483
37648
  tab_id: tabId,
37484
37649
  timeout_ms: timeoutMs,
37485
- targets: targets?.map((t) => resolveTarget(t)),
37650
+ targets: targets?.map((t) => resolveElementTarget(t)),
37486
37651
  completion_criteria: completionCriteria
37487
37652
  });
37488
37653
  }
@@ -37493,7 +37658,7 @@ class BskSession {
37493
37658
  maxTextChars,
37494
37659
  includeStack
37495
37660
  } = {}) {
37496
- return this.tool("console", {
37661
+ return this.#call("console", {
37497
37662
  tab_id: tabId,
37498
37663
  since,
37499
37664
  limit,
@@ -37507,10 +37672,10 @@ class BskSession {
37507
37672
  limit,
37508
37673
  maxTextChars
37509
37674
  } = {}) {
37510
- return this.tool("network", { tab_id: tabId, since, limit, max_text_chars: maxTextChars });
37675
+ return this.#call("network", { tab_id: tabId, since, limit, max_text_chars: maxTextChars });
37511
37676
  }
37512
37677
  resize(width, height, shared = {}) {
37513
- return this.tool("window_resize", { width, height, ...sharedTab(shared) });
37678
+ return this.#act("window_resize", { width, height }, shared);
37514
37679
  }
37515
37680
  emulate({
37516
37681
  tabId,
@@ -37518,7 +37683,7 @@ class BskSession {
37518
37683
  overrides,
37519
37684
  ...shared
37520
37685
  } = {}) {
37521
- return this.tool("emulate", { tab_id: tabId, off, overrides, ...sharedTab(shared) });
37686
+ return this.#act("emulate", { tab_id: tabId, off, overrides }, shared);
37522
37687
  }
37523
37688
  async stop() {
37524
37689
  if (this.#stopped)
@@ -37684,11 +37849,13 @@ function buildSnapshotExpression(options = {}) {
37684
37849
  return { tree: result.tree, refs: result.refs || {}, css, error: result.error };
37685
37850
  })()`;
37686
37851
  }
37687
- async function bskSnapshot(session, { tabId, timeoutMs, context, dependsOn, ...snapshotOptions } = {}) {
37852
+ async function bskSnapshot(session, { tabId, timeoutMs, context, observation, expect, dependsOn, ...snapshotOptions } = {}) {
37688
37853
  const reply = await session.evaluate(buildSnapshotExpression(snapshotOptions), {
37689
37854
  tabId,
37690
37855
  timeoutMs,
37691
37856
  context,
37857
+ observation,
37858
+ expect,
37692
37859
  dependsOn,
37693
37860
  awaitPromise: false,
37694
37861
  returnByValue: true