omowright 0.3.2 → 0.3.3

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/README.md CHANGED
@@ -121,8 +121,7 @@ const run = collectWhileScrolling(page, snoop, {
121
121
  maxScrolls: 15, // or after this many scroll rounds
122
122
  extract: (json) => json.items, // pull items out of each JSON body
123
123
  scroll: "wheel", // "end" jumps to the bottom instead
124
- settleMs: 800, // wait for the next page to land
125
- });
124
+ }); // a round ends when the next response lands; settleMs (default 800) only bounds a silent round
126
125
  let step;
127
126
  while (!(step = await run.next()).done) items.push(step.value);
128
127
  step.value; // { rounds, total, stoppedBecause: "minItems" | "maxScrolls" | "noGrowth" }
package/TOOLS.md CHANGED
@@ -286,7 +286,8 @@ loop; the module files next to it are implementation detail.
286
286
  encodedDataLength, body, base64Encoded, bodySkipped, failed, errorText,
287
287
  startedAt, finishedAt`.
288
288
  - `collectWhileScrolling(page, snoop, { minItems, maxScrolls=10, extract, scroll:
289
- "wheel"|"end", settleMs=800 })`: async generator. Each round scrolls, settles, drains
289
+ "wheel"|"end", settleMs=800 })`: async generator. Each round scrolls, waits for the next
290
+ response or page growth (at most `settleMs`), drains
290
291
  `snoop.popJson()` through `extract(json) => items[]`, yield each item. Returns
291
292
  `{ rounds, total, stoppedBecause: "minItems"|"maxScrolls"|"noGrowth" }`.
292
293
  - `createTrace(page, { dir, screenshots=true, network=true, console=true,
@@ -355,7 +356,9 @@ loop; the module files next to it are implementation detail.
355
356
  `BskRpcError` `no_browser_connected` when no extension is attached, and
356
357
  `extension_outdated` when the chosen extension is 0.4.0 (its task tab groups
357
358
  stay in the user's browser after the task); with no `browser` named it picks
358
- an up-to-date connected browser over a 0.4.0 one. Never launches a browser of
359
+ an up-to-date connected browser over a 0.4.0 one. An extension before 0.4.0
360
+ has no shared control: `cooperate("sync")` resolves without a `context_id`
361
+ there and actions run ungated. Never launches a browser of
359
362
  its own.
360
363
  - `BskSession`: `navigate`, `back`, `forward`, `reload`, `observe`, `snapshot`,
361
364
  `getHtml`, `screenshot({ ref, fullPage })`, `click`, `hover`, `fill`,
package/dist/emulate.d.ts CHANGED
@@ -53,6 +53,7 @@ export declare const DEVICE_PRESETS: Readonly<{
53
53
  platform: undefined;
54
54
  };
55
55
  }>;
56
+ export declare function emulatedDevice(page: object): DevicePreset | undefined;
56
57
  /**
57
58
  * Emulate a device on the given page.
58
59
  * @param {object} page - The page object with cdp.send(), resolveSessionId(), evaluate(), refreshViewportSize()
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.3",
35669
35707
  description: "OmOWright browser automation for standard Chromium CDP endpoints.",
35670
35708
  keywords: [
35671
35709
  "accessibility-snapshot",
@@ -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
  }
@@ -37256,7 +37319,11 @@ class BskSession {
37256
37319
  });
37257
37320
  }
37258
37321
  cooperate(action, { tabId, timeoutMs, maxTokens } = {}) {
37259
- return this.tool("cooperate", { action, tab_id: tabId, timeout_ms: timeoutMs, max_tokens: maxTokens });
37322
+ return this.tool("cooperate", { action, tab_id: tabId, timeout_ms: timeoutMs, max_tokens: maxTokens }).catch((error) => {
37323
+ if (error instanceof BskRpcError && error.code === "unknown_method")
37324
+ return { context_id: undefined, supported: false, ready: true };
37325
+ throw error;
37326
+ });
37260
37327
  }
37261
37328
  navigate(url, { tabId, waitUntil, timeoutMs, ...shared } = {}) {
37262
37329
  return this.tool("navigate", {
@@ -37378,6 +37445,8 @@ class BskSession {
37378
37445
  tab_id: tabId,
37379
37446
  timeout_ms: timeoutMs,
37380
37447
  ...sharedTab(shared)
37448
+ }).catch((error) => {
37449
+ throw redactValue(error, value);
37381
37450
  });
37382
37451
  }
37383
37452
  press(key, {
@@ -36,6 +36,7 @@ export interface NetworkSnoopOptions {
36
36
  maxEntries?: number | undefined;
37
37
  maxBodyBytes?: number | undefined;
38
38
  }
39
+ export declare const JSON_MIME: RegExp;
39
40
  /**
40
41
  * Buffers CDP network traffic for a single page session.
41
42
  *
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Strips a value being entered (fill/type) out of the error its failure raised, so a secret typed
3
+ * into a form never reaches an agent transcript (#335). The layers below (a CDP transport, the
4
+ * BrowserSkill daemon) may quote the command they refused, raw or JSON-escaped, in the message,
5
+ * the stack, a `data` payload or a cause; each is rewritten in place down the cause chain.
6
+ */
7
+ export declare function redactValue(error: unknown, value: string): unknown;
@@ -1,12 +1,10 @@
1
- /**
2
- * Scroll-driven collection over a network snoop (see ./network-snoop.ts).
3
- */
4
1
  export interface ScrollPage {
5
2
  viewportSize(): {
6
3
  width: number;
7
4
  height: number;
8
5
  } | null | undefined;
9
6
  evaluate<T>(pageFunction: () => T): Promise<T>;
7
+ evaluate<T, A>(pageFunction: (arg: A) => T | PromiseLike<T>, arg: A): Promise<T>;
10
8
  mouse: {
11
9
  move(x: number, y: number): Promise<unknown>;
12
10
  wheel(deltaX: number, deltaY: number): Promise<unknown>;
@@ -14,14 +12,26 @@ export interface ScrollPage {
14
12
  }
15
13
  export interface JsonSnoop {
16
14
  popJson(): Iterable<unknown>;
15
+ /** Resolves on the next buffered entry the predicate accepts; rejects after timeoutMs. */
16
+ waitFor(match: (entry: {
17
+ mimeType: string | null;
18
+ }) => unknown, options: {
19
+ timeoutMs: number;
20
+ }): Promise<unknown>;
17
21
  }
18
22
  export type ScrollMode = "wheel" | "end";
23
+ /** The timer that bounds each round; defaults to the global setTimeout/clearTimeout. */
24
+ export interface ScrollClock {
25
+ setTimeout(callback: () => void, ms: number): unknown;
26
+ clearTimeout(handle: unknown): void;
27
+ }
19
28
  export interface CollectWhileScrollingOptions {
20
29
  minItems?: number;
21
30
  maxScrolls?: number;
22
31
  extract?: (json: unknown) => Iterable<unknown>;
23
32
  scroll?: ScrollMode;
24
33
  settleMs?: number;
34
+ clock?: ScrollClock;
25
35
  }
26
36
  export interface CollectWhileScrollingResult {
27
37
  rounds: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omowright",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "OmOWright browser automation for standard Chromium CDP endpoints.",
5
5
  "keywords": [
6
6
  "accessibility-snapshot",
@@ -59,7 +59,6 @@ const gen = collectWhileScrolling(page, snoop, {
59
59
  maxScrolls: 15,
60
60
  extract: (json) => json.items ?? [],
61
61
  scroll: "wheel", // "end" jumps to the bottom instead
62
- settleMs: 800,
63
62
  });
64
63
  let step;
65
64
  while (!(step = await gen.next()).done) items.push(step.value);
@@ -67,7 +66,9 @@ step.value; // { rounds, total, stoppedBecause }
67
66
  ```
68
67
 
69
68
  `for await (const item of gen)` works too when you don't need the return
70
- value. The loop drains first, then scrolls, and stops on `minItems`,
69
+ value. A round ends as soon as the next response lands or the page grows;
70
+ `settleMs` (default 800) only bounds a round in which neither happens, so leave
71
+ it alone unless the endpoint is slower than that. The loop drains first, then scrolls, and stops on `minItems`,
71
72
  `maxScrolls`, or two consecutive rounds where the document height didn't grow
72
73
  (`noGrowth`). The default `extract` accepts bodies that are already arrays.
73
74
 
@@ -36,16 +36,8 @@ disagree, every coordinate is wrong by the same constant offset and retrying
36
36
  repeats the miss. Pin both to one box:
37
37
 
38
38
  ```js
39
- await page._sendToTarget("Emulation.setDeviceMetricsOverride", {
40
- width: 1440,
41
- height: 900,
42
- deviceScaleFactor: 1,
43
- mobile: false,
44
- screenWidth: 1440,
45
- screenHeight: 900,
46
- viewport: { x: 0, y: 0, width: 1440, height: 900, scale: 1 },
47
- });
48
- const size = await page.refreshViewportSize(); // -> { width: 1440, height: 900 }
39
+ const { repinViewport, DEFAULT_AGENT_VIEWPORT } = await import("omowright");
40
+ const size = await repinViewport(page, DEFAULT_AGENT_VIEWPORT); // -> { width: 1440, height: 900 }
49
41
  ```
50
42
 
51
43
  Pin every page you act on, including tabs you did not open, then take a fresh
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: omowright
3
- description: "The default code-driven browser path for interactive browsing work: drives any browser from code with token-efficient a11y snapshots (compactSnapshot drops the refs map), ref-based clicks, coordinate control (CUA), viewport pinning, CAPTCHA input helpers for reCAPTCHA, Turnstile, hCaptcha, slider and text OCR, with a human fallback (not a solver), Chrome MV3 APIs (tabs/bookmarks/history/downloads/topSites), network snoop (read API JSON instead of DOM), flight-recorder trace (jsonl + HAR + screenshots), OOPIF-aware snapshots, dialog policy, human handoff for login/OTP, device emulation, request routes, and one connectBrowser() entry that picks the engine in priority order: the user's agent browser (Aside, Ego Lite), then the user's own browser through BrowserSkill, then the owned stealth CloakBrowser with zero exposed CDP ports; each engine has its own setup check (asideOnboard, bskOnboard). MUST USE for interactive browser work: scraping, blocked/WAF/JS-rendered pages, logins, the user's logged-in sites and open tabs, extension popups, form filling, screenshots, web QA, CAPTCHAs. The ulw-research browsing lane runs on ultimate-browsing, not this skill."
3
+ description: "The default code-driven browser path for interactive browsing work: token-efficient a11y snapshots (compactSnapshot drops the refs map), ref-based clicks, condition waits instead of fixed delays, coordinate control (CUA), viewport pinning, CAPTCHA input helpers (reCAPTCHA, Turnstile, hCaptcha, slider, text OCR) with a human fallback, Chrome MV3 APIs, network snoop (read API JSON instead of DOM), flight-recorder trace, OOPIF-aware snapshots, dialog policy, human handoff for login/OTP, device emulation, request routes, and one connectBrowser() entry that picks the engine in order: the user's agent browser (Aside, Ego Lite), the user's own browser through BrowserSkill, then the owned stealth CloakBrowser with zero exposed CDP ports. MUST USE for interactive browser work: scraping, blocked/WAF/JS-rendered pages, logins, the user's logged-in sites and open tabs, extension popups, form filling, screenshots, web QA, CAPTCHAs. The ulw-research browsing lane runs on ultimate-browsing, not this skill."
4
4
  ---
5
5
 
6
6
  # OmOWright
@@ -74,18 +74,37 @@ empty tree, not an error. A search does not move the diff baseline, and `find` c
74
74
  be combined with `diff`. `maxChars` still caps the whole captured tree before the
75
75
  search runs, so leave it off when searching a large page.
76
76
 
77
+ ## Wait for a state, never for a clock
78
+
79
+ **NEVER WRITE A FIXED DELAY** (`Bun.sleep`, `setTimeout`, `waitForTimeout`): it fails on a
80
+ slow page and wastes itself on a fast one. Wait for the state you need, and start the
81
+ wait before the action that causes it.
82
+
83
+ | Waiting for | Call |
84
+ | --- | --- |
85
+ | Something appearing or changing in the page | `page.waitForFunction(fn, arg, { timeout })` (options are the THIRD argument), `page.locator(ref).waitFor({ state: "visible" })` |
86
+ | The request an action triggers | `const got = page.waitForResponse(urlOrPredicate)`, act, `await got`; `snoop.waitFor(match)` with a snoop open |
87
+ | A navigation | `page.waitForURL(globOrRegExp)`, `page.waitForLoadState("networkidle")` |
88
+ | A new tab | `page.waitForEvent("popup")`, subscribed before the click |
89
+ | A person (login, OTP, CAPTCHA) | `requestHuman(page, { prompt, until })` |
90
+
91
+ Nothing follows `goto` or `newTab`: both already wait for content. A wait that can outlast
92
+ one tool call (a person, a deploy, a slow job) is not awaited in that call: start it, hand
93
+ its completion to your harness's watcher, keep working. Pattern in
94
+ `references/eval-kernel.md`.
95
+
77
96
  ## Owned engine: CloakBrowser
78
97
 
79
98
  When omowright owns the browser, use the CloakBrowser binary, not a plain headless shell: most real
80
99
  targets sit behind WAFs or bot scoring, and CloakBrowser's source-level
81
100
  fingerprint patches (Cloudflare Turnstile, FingerprintJS, BrowserScan) make it
82
101
  the safe choice. Plain headless shell is the speed fallback for trivially open
83
- pages: any Chrome/Chromium or
84
- `~/Library/Caches/ms-playwright/chromium_headless_shell-*/.../chrome-headless-shell`.
102
+ pages. Take either path from code, never from a guess:
85
103
 
86
- ```bash
87
- python3 -c "import cloakbrowser; print(cloakbrowser.binary_info()['binary_path'])"
88
- # -> ~/.cloakbrowser/chromium-<ver>/Chromium.app/Contents/MacOS/Chromium
104
+ ```js
105
+ const { findCloakBrowserPath, detectBrowsers } = await import("omowright");
106
+ const browserPath = findCloakBrowserPath(); // newest ~/.cloakbrowser/chromium-*; throws when none is installed (set CLOAKBROWSER_BIN off macOS)
107
+ const chrome = detectBrowsers().find((b) => b.installed)?.binary; // an installed Chrome-family binary, for the fallback
89
108
  ```
90
109
 
91
110
  For a reused authenticated profile, use `connectCloakProfile({ profileDir, fingerprintSeed })` from the package (or the `omowright-cloak --profile "$HOME/.local/share/omowright-cloak" --url <url> --once --snapshot` launcher). First use pins a fingerprint seed in a mode-`0600` metadata file inside the mode-`0700` profile; later runs reuse it and **REJECT a conflicting seed** instead of silently changing identity. It passes the fixed `--fingerprint=<seed>` plus the platform flag on every `connectPipe()` launch. The seed is an identity pin, not a credential store.
@@ -124,18 +143,15 @@ CUA acts in viewport pixels. When the render surface and coordinate space
124
143
  disagree, every coordinate is off by a constant and retrying repeats the miss:
125
144
 
126
145
  ```js
127
- await page._sendToTarget("Emulation.setDeviceMetricsOverride", {
128
- width: 1440,
129
- height: 900,
130
- deviceScaleFactor: 1,
131
- mobile: false,
132
- screenWidth: 1440,
133
- screenHeight: 900,
134
- viewport: { x: 0, y: 0, width: 1440, height: 900, scale: 1 },
135
- });
136
- await page.refreshViewportSize(); // -> { width: 1440, height: 900 }
146
+ const { repinViewport, DEFAULT_AGENT_VIEWPORT } = await import("omowright");
147
+ await repinViewport(page, DEFAULT_AGENT_VIEWPORT); // -> { width: 1440, height: 900 }
137
148
  ```
138
149
 
150
+ For a device instead of a box, `emulate(page, "iphone-14")` (also `pixel-7`, `ipad-air`,
151
+ `desktop-1440`) sets metrics, touch and user agent together, and
152
+ `page.emulateMedia({ colorScheme })` covers media features. Raw `Emulation.*` CDP is never
153
+ needed for either.
154
+
139
155
  Pin every page you act on, including tabs you did not open, then take a fresh
140
156
  screenshot — coordinates read off an unpinned screenshot are stale.
141
157
 
@@ -166,9 +182,12 @@ Preset and `TOOLS.md` paths are relative to the package root.
166
182
  their own browser; 1Password sessions are device-bound and never work from
167
183
  cookies. Detail in `references/stealth.md`. Cookie reuse is fine for ordinary
168
184
  sessions (Grafana, internal tools).
169
- - **Always `compactSnapshot()`** before sending a snapshot to a model — the refs
170
- map resolves in-page, so dropping it is free; it was 7% to 64% of the bytes
171
- across pages measured on 2026-11-09.
185
+ - **Read within a budget.** `compactSnapshot()` before a model reads any snapshot
186
+ (the refs map resolves in-page; it was 7% to 64% of the bytes, measured
187
+ 2026-11-09). Check `snapshotTokens(snapshot)` (`{ bytes, estTokens }`) before
188
+ printing a tree you have not measured, and narrow a large one with `find`,
189
+ `selector`, `interactive: true` or `maxChars`. `page.evaluate` returns the
190
+ fields you need, never `innerHTML` or a whole document's `innerText`.
172
191
  - **Refs die on every new snapshot.** Pass `page.locator("e1")` straight from the
173
192
  latest snapshot; never reuse a ref across snapshots, never put one in CSS.
174
193
  - **Refs stay page-level.** Child-frame refs look like `f1e3` and still go to
@@ -67,6 +67,19 @@ Targets are a ref (`"e3"` / `"@e3"` from `session.observe()` or
67
67
  `session.snapshot()`), a CSS selector, or `{ captureId, x, y }` from a
68
68
  screenshot.
69
69
 
70
+ On an extension older than 0.4.0 there is no shared control: `cooperate("sync")`
71
+ resolves without a `context_id` and actions run ungated, so the loop above runs
72
+ unchanged there.
73
+
74
+ A `BskSession` is not a page: it has no `goto`, `locator` or `listTargets`.
75
+ Read with `observe({ maxTokens })` first: it is the cheapest read, needs no
76
+ sync context, and its `@eN` refs work inside shadow roots and frames. To wait,
77
+ use `navigate(url, { waitUntil: "networkidle" })` for a page that renders after
78
+ load and `waitForNavigation()` after an action that navigates; for a later
79
+ state, `evaluate` a promise that resolves when the state holds
80
+ (`{ awaitPromise: true, timeoutMs, context }`; `evaluate` is a gated action).
81
+ Never a fixed delay.
82
+
70
83
  | Need | Call |
71
84
  | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
72
85
  | Navigate / history | `navigate(url, {waitUntil, timeoutMs})`, `back()`, `forward()`, `reload({hard})`, `waitForNavigation()` |
@@ -7,11 +7,15 @@ parallel. It does not keep child processes alive for you.
7
7
  **ONLY `globalThis.*` SURVIVES ACROSS CELLS.** Top-level `const`/`let` bindings do
8
8
  not; re-import or read from `globalThis` in later cells.
9
9
 
10
- **A BROWSER SPAWNED IN A CELL CAN DIE WHEN THAT CELL SETTLES.** Measured, not
11
- assumed: `Bun.spawn` children were killed with SIGKILL at cell completion, and
12
- `connectPipe` (which uses `child_process.spawn` without detaching) lost a
13
- browser between two cells. A `globalThis.omw` handle whose process is gone
14
- rejects every call. Two patterns hold up:
10
+ **CONNECT ONCE AND KEEP THE HANDLE ON `globalThis`.** A new connect in every
11
+ cell throws away the page state and pays the launch again.
12
+
13
+ **WHETHER A BROWSER SPAWNED IN A CELL OUTLIVES IT DEPENDS ON THE HARNESS.**
14
+ Measured both ways: an older eval kernel killed `Bun.spawn` children with
15
+ SIGKILL at cell completion and lost a `connectPipe` browser between two cells;
16
+ omo's kernel kept a `connectPipe` browser and an unawaited `waitForFunction`
17
+ alive across cells (2026-11-26). A `globalThis.omw` handle whose process is gone
18
+ rejects every call, so probe before reuse. Two patterns hold up everywhere:
15
19
 
16
20
  1. **One cell, whole job.** Connect, act, close in the same cell. Right for any
17
21
  job that fits in one cell's runtime; the parallel lanes below are this shape.
@@ -81,6 +85,33 @@ await omwPage.locator("e1").click();
81
85
  display(await omwPage.screenshot({ type: "png" })); // display() renders images inline
82
86
  ```
83
87
 
88
+ ## Waits that outlast a cell
89
+
90
+ A cell that awaits a person, a deploy or a slow job is detached by the harness
91
+ (after 30 s in omo) and then holds the kernel: every later cell queues behind
92
+ it. Subscribe the harness watcher first, start the wait without awaiting it, and
93
+ return:
94
+
95
+ ```js
96
+ const flag = path.join(os.tmpdir(), `omowright-signed-in-${Date.now()}.flag`);
97
+ await tool.monitor({ description: "sign-in finished", path: flag, event: "create" });
98
+ globalThis.omwWait = omwPage
99
+ .waitForFunction(() => document.querySelector("[data-user]") !== null, undefined, { timeout: 600_000 })
100
+ .then(
101
+ () => fs.writeFileSync(flag, "ok"),
102
+ (error) => fs.writeFileSync(flag, `failed: ${error.message}`),
103
+ );
104
+ ```
105
+
106
+ The cell returns at once, the kernel stays free for other cells on the same
107
+ `omwPage`, and the file event wakes the turn on success and on timeout alike,
108
+ so a wait never ends silently. Read the flag, then continue from the live page.
109
+ Measured on 2026-11-26: the event arrived as the page state flipped, and a 2 s
110
+ bound reported `WaitForFunctionTimeoutError` at 2004 ms. `tool.monitor` is omo's
111
+ watcher; in another harness use its file or command watch. The same rule covers
112
+ a dev server or a deploy the page depends on: watch it with a command monitor
113
+ that prints one line when it is ready, never with a loop in a cell.
114
+
84
115
  ## Parallel lanes (research fan-out)
85
116
 
86
117
  Each lane gets its own browser and profile: no shared state, and the pipe
@@ -101,6 +101,12 @@ const result = await requestHuman(page, {
101
101
  if (result.outcome !== "continued") throw new Error(`handoff ${result.outcome}`);
102
102
  ```
103
103
 
104
+ **IN AN EVAL CELL, DO NOT `await` THE HANDOFF.** A person takes longer than a
105
+ cell, and an awaited handoff holds the kernel until they finish. Subscribe the
106
+ harness watcher, start `requestHuman(...)` without `await`, write its outcome to
107
+ the watched file in `.then`, and return; the page stays usable from other cells
108
+ meanwhile. Pattern in `eval-kernel.md` (next to this file), "Waits that outlast a cell".
109
+
104
110
  The call brings the window to the front, injects a shadow-DOM banner with your
105
111
  prompt and a Done button, then polls every `pollMs` for `until` or the button.
106
112
  Pass an `AbortSignal` as `signal` to cancel from your side. The banner is
@@ -129,4 +135,5 @@ fields (`width, height, deviceScaleFactor, mobile, hasTouch, userAgent,
129
135
  platform`) for a custom device. The original UA is captured on the first call
130
136
  per page, so `null` always returns to where you started. Re-snapshot after
131
137
  switching: layout changes move refs, and a mobile layout often swaps a nav bar
132
- for a menu button.
138
+ for a menu button. Media features are separate:
139
+ `page.emulateMedia({ colorScheme: "dark", reducedMotion: "reduce" })`.
@@ -65,9 +65,16 @@ await page.pdf({ path, format?, margin? });
65
65
  await page.locator("e1").click(); // ref or CSS
66
66
  await page.locator("input[name=q]").fill("text");
67
67
  await page.keyboard.press("Enter"); await page.mouse.wheel(0, 400);
68
+ await page.waitForFunction(() => window.ready === true, undefined, { timeout: 10_000 }); // a page state; options are the 3rd argument
69
+ const saved = page.waitForResponse("**/api/cart"); // start the wait, then act, then await it
70
+ await page.locator("e7").click(); await saved;
71
+ await page.waitForURL("**/dashboard"); await page.waitForLoadState("networkidle");
68
72
  await page.close();
69
73
  ```
70
74
 
75
+ Wait with these, never with a fixed delay; the full table is in `SKILL.md` ("Wait for a
76
+ state, never for a clock").
77
+
71
78
  ## Snapshot discipline
72
79
 
73
80
  ```js