omowright 0.0.0 → 0.1.0

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.
Files changed (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +282 -2
  3. package/TOOLS.md +366 -0
  4. package/bin/omowright-cloak.mjs +112 -0
  5. package/package.json +57 -4
  6. package/presets/agent-events/SKILL.md +75 -0
  7. package/presets/captcha/SKILL.md +129 -0
  8. package/presets/chrome/SKILL.md +84 -0
  9. package/presets/cloak-bridge/SKILL.md +43 -0
  10. package/presets/network/SKILL.md +126 -0
  11. package/presets/visual-browse/SKILL.md +103 -0
  12. package/skills/omowright/SKILL.md +193 -0
  13. package/skills/omowright/references/1password.md +118 -0
  14. package/skills/omowright/references/browserskill.md +186 -0
  15. package/skills/omowright/references/eval-kernel.md +100 -0
  16. package/skills/omowright/references/frames-layers-human.md +123 -0
  17. package/skills/omowright/references/quickstart.md +96 -0
  18. package/skills/omowright/references/stealth.md +174 -0
  19. package/src/agent-tabs.js +160 -0
  20. package/src/bridge-schemas.js +44 -0
  21. package/src/bridge-transport.js +57 -0
  22. package/src/browser-process.js +122 -0
  23. package/src/bsk/browser-signals.js +90 -0
  24. package/src/bsk/browsers.js +114 -0
  25. package/src/bsk/connect.js +45 -0
  26. package/src/bsk/daemon-info.js +100 -0
  27. package/src/bsk/external-extension.js +110 -0
  28. package/src/bsk/identify-browser.js +88 -0
  29. package/src/bsk/install-cli.js +81 -0
  30. package/src/bsk/ipc-client.js +236 -0
  31. package/src/bsk/onboard.js +133 -0
  32. package/src/bsk/screenshot.js +49 -0
  33. package/src/bsk/session.js +131 -0
  34. package/src/bsk/snapshot.js +56 -0
  35. package/src/bsk/targets.js +25 -0
  36. package/src/captcha-wait.js +74 -0
  37. package/src/captcha.js +142 -0
  38. package/src/cdp-errors.js +23 -0
  39. package/src/cdp-methods.js +61 -0
  40. package/src/chrome-profile.js +176 -0
  41. package/src/chrome.js +192 -0
  42. package/src/cloak-profile.js +266 -0
  43. package/src/connection.js +135 -0
  44. package/src/cookies.js +29 -0
  45. package/src/core.js +1710 -0
  46. package/src/cua.js +74 -0
  47. package/src/dialog-policy.js +80 -0
  48. package/src/emulate.js +127 -0
  49. package/src/events.js +111 -0
  50. package/src/frames-snapshot.js +138 -0
  51. package/src/har.js +103 -0
  52. package/src/human-handoff.js +122 -0
  53. package/src/index.js +86 -0
  54. package/src/injected.js +3 -0
  55. package/src/instance-lock.js +230 -0
  56. package/src/instances.js +493 -0
  57. package/src/internal-capability.js +1 -0
  58. package/src/launch-endpoint.js +185 -0
  59. package/src/layers.js +138 -0
  60. package/src/llm.js +201 -0
  61. package/src/lock-file.js +130 -0
  62. package/src/native-host-win32.js +201 -0
  63. package/src/network-events.js +201 -0
  64. package/src/network-snoop.js +229 -0
  65. package/src/open-shadow-query.js +22 -0
  66. package/src/owner-only.js +109 -0
  67. package/src/page-bundle.js +1397 -0
  68. package/src/page-routes.js +94 -0
  69. package/src/pipe.js +391 -0
  70. package/src/routes.js +256 -0
  71. package/src/running-browser.js +85 -0
  72. package/src/scroll-collect.js +73 -0
  73. package/src/serial-emitter.js +17 -0
  74. package/src/shared-connections.js +278 -0
  75. package/src/snapshot-diff.js +75 -0
  76. package/src/trace.js +183 -0
  77. package/src/url-match.js +148 -0
  78. package/src/viewport.js +12 -0
@@ -0,0 +1,129 @@
1
+ ---
2
+ name: captcha
3
+ description: Interact with challenge widgets in an authorized automation flow using checkbox clicks, slider drags, text OCR, and image-grid input. Verify completion with an application-specific condition.
4
+ ---
5
+
6
+ # Captcha
7
+
8
+ `createCaptcha(page, { ocr? })` provides input and OCR helpers, not a general
9
+ CAPTCHA solver. `click` and `drag` return a compact snapshot tree string after
10
+ settling. `readText` returns text or `null`. A snapshot, token, or disappearing
11
+ widget alone does not prove that the application accepted the challenge.
12
+
13
+ This is rung 4 of the ladder in `presets/visual-browse/SKILL.md`. Pin the viewport
14
+ before measuring coordinates (`Emulation.setDeviceMetricsOverride` and
15
+ `refreshViewportSize`), and measure again after scrolling, resizing, or reflow.
16
+
17
+ ```js
18
+ import { createCaptcha } from "omowright";
19
+ const captcha = createCaptcha(page);
20
+ ```
21
+
22
+ ## Checkbox widgets
23
+
24
+ `click(bounds)` clicks the **center**, not the left-center. Measure the actual
25
+ checkbox bounds, or provide an explicit point within a measured widget rectangle.
26
+ All bounds and points use absolute top-level viewport CSS pixels. Coordinates
27
+ can target a visible control inside a frame without switching frames, but a
28
+ cross-origin iframe's outer bounds do not locate its checkbox. Account for frame
29
+ geometry; an opaque or missing frame in a snapshot is not evidence of no challenge.
30
+
31
+ For an application-owned widget with a DOM-accessible checkbox:
32
+
33
+ ```js
34
+ const bounds = await page.evaluate(`(() => {
35
+ const el = document.querySelector("#captcha-checkbox");
36
+ if (!el) throw new Error("Checkbox not found");
37
+ const r = el.getBoundingClientRect();
38
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
39
+ })()`);
40
+
41
+ await captcha.click(bounds, {
42
+ point: { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 },
43
+ approachSteps: 12,
44
+ settleMs: 0,
45
+ });
46
+ const result = await captcha.waitFor({
47
+ // Replace with your application's authoritative acceptance condition.
48
+ until: page => page.evaluate(
49
+ `document.querySelector("#application-status")?.dataset.accepted === "true"`
50
+ ),
51
+ timeoutMs: 10000,
52
+ pollMs: 100,
53
+ });
54
+ if (result.outcome !== "matched") {
55
+ throw new Error(`Acceptance not confirmed: ${result.outcome}`);
56
+ }
57
+ // Capture visual evidence separately; waitFor never returns a tree or image.
58
+ const image = await page.screenshot({ type: "png" });
59
+ ```
60
+
61
+ `point` is optional; omit it to retain center targeting. `approachSteps` is an
62
+ optional positive integer for intermediate pointer movement before clicking.
63
+ Omitting it retains the direct click. Interpolation is not a human-likeness or
64
+ acceptance guarantee. Bounds must have finite coordinates and positive finite
65
+ dimensions; the point must be inside `[x, x + width)` and `[y, y + height)`.
66
+ Invalid geometry is rejected before input, not clamped or coerced.
67
+
68
+ ## Completion is separate from input
69
+
70
+ `captcha.waitFor({ until, timeoutMs = 10000, pollMs = 100, signal } = {})`
71
+ returns exactly `{ outcome: "matched" | "timed_out" | "cancelled", elapsedMs }`.
72
+ It never clicks, takes a snapshot, or infers server acceptance. You can check an
73
+ already-accepted application without sending input.
74
+
75
+ `until` is required and called as `until(page, { signal: operationSignal })`;
76
+ one-argument predicates also work. Only literal `true` matches, not a truthy
77
+ string or object. The first check runs immediately; subsequent checks are serial,
78
+ after `pollMs`, bounded by one monotonic deadline. Predicate errors before
79
+ termination propagate unchanged. `timeoutMs` must be finite in `[0, 2147483647]`;
80
+ `pollMs` must be finite in `(0, 2147483647]`. A supplied `signal` must be
81
+ AbortSignal-compatible. Invalid arguments throw TypeError or RangeError without
82
+ running the predicate; values are not coerced.
83
+
84
+ At completion boundaries, cancellation takes priority over the deadline, and
85
+ the deadline over a match. A pre-aborted signal runs no predicate and returns
86
+ `cancelled`; a zero timeout runs no predicate and returns `timed_out` unless
87
+ already aborted. Async predicates and delays are bounded by abort/deadline,
88
+ without overlapping checks. The owned operation signal is aborted on every
89
+ terminal exit; owned timers and external abort listeners are cleaned up.
90
+ A non-cooperative predicate can remain pending after return; late rejection does
91
+ not change the result or become an unhandled rejection. Cancellation cannot
92
+ retract dispatched input or requests, or interrupt blocking synchronous code.
93
+
94
+ ## Slider and puzzle drags
95
+
96
+ ```js
97
+ const tree = await captcha.drag({ x: 150, y: 300 }, { x: 450, y: 300 }, { steps: 40 });
98
+ ```
99
+
100
+ Endpoints must be finite viewport points. `steps` is a positive integer (default
101
+ 20); it controls intermediate movement, not whether the application accepts the
102
+ result. Mouse release is attempted even if movement fails.
103
+
104
+ ## Text and number captchas
105
+
106
+ ```js
107
+ const text = await captcha.readText({ x: 100, y: 200, width: 200, height: 60 });
108
+ if (text !== null) await page.locator("input[name=captcha]").fill(text);
109
+ ```
110
+
111
+ The built-in `macOSVisionOcr` uses macOS Vision via Swift. Elsewhere, inject an
112
+ OCR function: `createCaptcha(page, { ocr: async (pngBuffer) => "recognized text" })`.
113
+ `readText(bounds?)` screenshots a cropped region, or the whole viewport when
114
+ bounds are absent, and returns OCR text or `null`, never a snapshot tree.
115
+ Recognizing text is not proof of submission or acceptance.
116
+
117
+ ## Image-grid challenges and diagnosis
118
+
119
+ `page.annotatedScreenshot()` overlays numbered boxes on interactive elements.
120
+ Use the image to identify targets and `createCua(page)` for coordinate input;
121
+ verify the application's result separately after submission.
122
+
123
+ `click` and `drag` accept finite supported timer milliseconds as `settleMs`
124
+ (default 3000, including 0 to disable the settling delay). They still take a
125
+ snapshot with `settleMs: 0`; that delay is not a completion check or an overall
126
+ timeout. If targeting fails, re-measure geometry. If input lands but acceptance
127
+ does not follow, inspect the application state rather than assuming extra steps,
128
+ a longer delay, or a different engine will solve it. See
129
+ [CAPTCHA quality and comparison](../../docs/captcha-quality.md) for the limits.
@@ -0,0 +1,84 @@
1
+ ---
2
+ name: chrome
3
+ description: Read this when you need Chrome MV3-shaped APIs — bookmarks, tabs, windows, history, downloads, or top sites — in standalone OmOWright.
4
+ ---
5
+
6
+ # Chrome MV3 APIs (standalone)
7
+
8
+ `createChromeApi(connection, options?)` returns MV3-shaped namespaces backed by
9
+ CDP and the browser's own profile files — no extension required.
10
+
11
+ ```js
12
+ import { createChromeApi } from "omowright";
13
+
14
+ const chrome = createChromeApi(connection, {
15
+ profilePath: "/path/to/user-data-dir", // enables bookmarks/history/topSites/downloads.search
16
+ downloadDir: "/path/to/downloads", // optional, defaults to a temp dir
17
+ });
18
+ ```
19
+
20
+ **PROFILE-BACKED METHODS THROW `UnsupportedOperationError` WITHOUT `profilePath`.**
21
+ A `connectPipe` browser gets a fresh profile, so bookmarks and history are empty
22
+ there — these APIs matter when attaching to a real user browser via `connect()` or
23
+ reading a real profile directory. Profile reads are read-only and WAL-safe against a running
24
+ browser.
25
+
26
+ ## tabs — CDP `Target.getTargets`
27
+
28
+ - `chrome.tabs.query({ url?: string | string[], title?, windowId? })` — `url`
29
+ takes MV3 match patterns (`*://*.example.com/*`), `title` is a substring match. **THESE THREE
30
+ ARE THE ONLY HONORED FILTERS.**
31
+ - `chrome.tabs.get(tabId)` — `tabId` is a string; throws when no tab has it.
32
+ - Returns `{ id, url, title, windowId, active, pinned, audible, discarded, groupId, index }`.
33
+ **IDS ARE CDP TARGET-ID STRINGS, NOT MV3 NUMBERS**, and the last six fields are
34
+ fixed defaults — they are not observable over CDP.
35
+
36
+ Tab lifecycle stays on `connection.newTab(url)` / `page.close()`; interaction on
37
+ `page.goto()` / `page.locator()`.
38
+
39
+ ## windows — CDP `Browser.getWindowForTarget`
40
+
41
+ `get(windowId, queryOptions?)`, `getCurrent(queryOptions?)`,
42
+ `getLastFocused(queryOptions?)`, `getAll(queryOptions?)`.
43
+
44
+ - `queryOptions: { populate?: boolean }` — `populate: true` adds a `tabs` array.
45
+ - Returns `{ id, focused, type, state, alwaysOnTop, incognito, tabs? }`.
46
+ - Headless sessions have exactly one window; `getCurrent`/`getLastFocused` return
47
+ the first.
48
+
49
+ ## bookmarks — profile `Bookmarks` JSON, read-only
50
+
51
+ `get(idOrIdList)`, `getChildren(id)`, `getRecent(numberOfItems)`,
52
+ `getSubTree(id)`, `getTree()`, `search(query)` where `query` is a string or
53
+ `{ query?, url?, title? }`.
54
+
55
+ Nodes: `{ id, title, type: "url" | "folder", url?, dateAdded?, children? }`.
56
+
57
+ ## history — profile `History` SQLite, read-only
58
+
59
+ - `search({ text, startTime?, endTime?, maxResults? })` — times are Unix ms.
60
+ Returns `[{ id, url, title, visitCount, lastVisitTime }]`, newest first.
61
+ - `getVisits({ url })` — returns `[{ id, url, visitTime, transition }]`.
62
+
63
+ ## downloads — `History` SQLite + `Browser.setDownloadBehavior`
64
+
65
+ - `search({ url?, filename?, limit? })` — returns
66
+ `[{ id, url, filename, startTime, bytesReceived, totalBytes, state }]`; state is
67
+ `complete | canceled | interrupted | in_progress`. Needs `profilePath`.
68
+ - `download({ url, filename? })` — downloads through the real browser and resolves
69
+ `{ id, url, filename, state: "complete" }` with `filename` as the absolute saved
70
+ path. 30s timeout; rejects when the URL starts no download. It uses an in-page
71
+ anchor click rather than `Page.navigate`, which hangs on download navigations,
72
+ and re-asserts the download behavior on every call because tab initialization
73
+ resets it.
74
+
75
+ ## topSites — profile `Top Sites` SQLite
76
+
77
+ `get()` returns `[{ url, title }]` ordered by rank, max 50.
78
+
79
+ ## Write methods require the extension bridge
80
+
81
+ These throw `UnsupportedOperationError` because they would mutate the user's own
82
+ browser state: `bookmarks.create/update/move/remove/removeTree`,
83
+ `history.addUrl/deleteUrl/deleteRange`,
84
+ `downloads.pause/resume/cancel/erase`, and all of `chrome.tabGroups`.
@@ -0,0 +1,43 @@
1
+ ---
2
+ name: cloak-bridge
3
+ description: Use when a user-driven CloakBrowser profile needs MV3 Chrome writes/events through the native messaging bridge.
4
+ ---
5
+
6
+ # CloakBrowser bridge
7
+
8
+ Opt-in, zero-TCP extension channel. Load `bridge/extension` as an MV3 unpacked
9
+ extension; install the native host with the exact 32-character extension ID. The
10
+ host manifest needs an absolute executable path and exactly one
11
+ `chrome-extension://<id>/` allowed origin. **STDOUT IS PROTOCOL-ONLY; DIAGNOSTICS
12
+ GO TO STDERR.**
13
+
14
+ ```js
15
+ import { createBridgeClient, createChromeApi } from "omowright";
16
+ const bridge = createBridgeClient({ extensionId, stdin, stdout });
17
+ const chrome = createChromeApi(connection, { profilePath, bridge });
18
+ ```
19
+
20
+ Launch the pinned binary
21
+ `~/.cloakbrowser/chromium-145.0.7632.109.2/Chromium.app/Contents/MacOS/Chromium`
22
+ with `--load-extension=/absolute/path/to/bridge/extension` and optionally exactly
23
+ one `--silent-debugger-extension-api` — it only suppresses the warning; it is not
24
+ authorization.
25
+
26
+ ## Support matrix
27
+
28
+ | API | Bridge behavior |
29
+ |---|---|
30
+ | bookmarks.create/move/remove | Supported only when negotiated |
31
+ | history.deleteUrl/deleteRange | Supported only when negotiated |
32
+ | tabGroups.update | Supported only when negotiated |
33
+ | debugger.attach/detach | Supported only when negotiated, numeric tab IDs only |
34
+ | notifications, tabGroups, tabs, windows events | Forwarded without replay |
35
+ | bookmarks.update/removeTree | Unsupported |
36
+ | history.addUrl | Unsupported |
37
+ | downloads.pause/resume/cancel/erase | Unsupported |
38
+ | standalone reads and downloads.download | Existing CDP/profile behavior |
39
+
40
+ **NEVER RETRY A MUTATION AFTER DISCONNECT — COMPLETION IS INDETERMINATE.**
41
+ Subscribe to events before triggering actions. CloakBrowser native-host
42
+ registration requires a verified `nativeMessagingHostDir`; the product directory
43
+ **CANNOT** be guessed from `--user-data-dir` or the application filename.
@@ -0,0 +1,126 @@
1
+ ---
2
+ name: network
3
+ description: Read the network instead of the DOM. Snoop JSON API responses, wait for a request instead of sleeping, collect items while scrolling, record a QA flight trace (jsonl, HAR, screenshots), and intercept requests with routes.
4
+ ---
5
+
6
+ # Network
7
+
8
+ Every page session already has the `Network` domain on, so watching traffic
9
+ costs nothing and pages can't see it. All four tools come from the package
10
+ entrypoint:
11
+
12
+ ```js
13
+ const { createNetworkSnoop, collectWhileScrolling, createTrace, createRoutes } =
14
+ await import("omowright");
15
+ ```
16
+
17
+ ## Snoop before you scrape
18
+
19
+ When a page renders a list, a table, or search results, the data almost always
20
+ arrived as JSON one request earlier. That JSON is complete, typed, and free of
21
+ truncated labels. Snapshot to find and click; snoop to read.
22
+
23
+ ```js
24
+ const snoop = createNetworkSnoop(page, { match: { url: /\/api\//, mimeType: "json" } }); // strings match as substrings
25
+ await page.goto("https://example.com/search?q=widgets");
26
+ const results = snoop.popJson(); // parsed bodies, buffer drained
27
+ console.log(snoop.summary({ max: 20 })); // "GET 200 application/json 8123B https://..."
28
+ snoop.dispose();
29
+ ```
30
+
31
+ Create the snoop before the navigation or click that produces the traffic.
32
+ Entries land when the response finishes, so `match` may test `status` and
33
+ `mimeType`. `pop()` gives raw entries; `peek()` copies without draining.
34
+
35
+ ## Wait for the request, not the clock
36
+
37
+ A fixed sleep either wastes time or fails on a slow day. Wait for the response
38
+ you need instead:
39
+
40
+ ```js
41
+ const saved = snoop.waitFor({ url: "/api/cart", method: "POST" }, { timeoutMs: 10000 });
42
+ await page.locator("e7").click();
43
+ const entry = await saved; // { status, body, ... }
44
+ if (entry.status !== 200) throw new Error(`cart save failed: ${entry.status} ${entry.statusText}`);
45
+ ```
46
+
47
+ Start the wait first, then act; a response that finishes before `waitFor` is
48
+ called goes to the buffer, not the waiter.
49
+
50
+ ## Collect while scrolling
51
+
52
+ Infinite lists load pages over XHR as you scroll. Drive the scroll and drain
53
+ the snoop in one loop:
54
+
55
+ ```js
56
+ const snoop = createNetworkSnoop(page, { match: { url: /\/feed\?/ } });
57
+ const items = [];
58
+ const gen = collectWhileScrolling(page, snoop, {
59
+ minItems: 200,
60
+ maxScrolls: 15,
61
+ extract: json => json.items ?? [],
62
+ scroll: "wheel", // "end" jumps to the bottom instead
63
+ settleMs: 800,
64
+ });
65
+ let step;
66
+ while (!(step = await gen.next()).done) items.push(step.value);
67
+ step.value; // { rounds, total, stoppedBecause }
68
+ ```
69
+
70
+ `for await (const item of gen)` works too when you don't need the return
71
+ value. The loop drains first, then scrolls, and stops on `minItems`,
72
+ `maxScrolls`, or two consecutive rounds where the document height didn't grow
73
+ (`noGrowth`). The default `extract` accepts bodies that are already arrays.
74
+
75
+ ## Flight recorder for QA
76
+
77
+ `createTrace` records what happened while you drove the page, so a failed run
78
+ is a directory to read rather than a memory to reconstruct:
79
+
80
+ ```js
81
+ const trace = createTrace(page, { dir: "/tmp/checkout-trace" });
82
+ await trace.step("open cart", () => page.goto("https://example.com/cart"));
83
+ await trace.step("apply coupon", async () => {
84
+ await page.locator("e3").fill("SAVE10");
85
+ await page.locator("e4").click();
86
+ });
87
+ trace.mark("expected total", { total: "90.00" });
88
+ const summary = await trace.stop(); // { steps, events, network, startedAt, endedAt, url }
89
+ ```
90
+
91
+ What lands in `dir`:
92
+
93
+ - `trace.jsonl`: one JSON object per line, ordered by `seq`. `kind` is one of
94
+ `step` (name, `durationMs`, `error`, screenshot paths), `network`, `console`,
95
+ `dialog`, `navigation`, `download`, `mark`, `warning`. Grep it:
96
+ `rg '"kind":"console"' trace.jsonl` or `jq -c 'select(.kind=="step")'`.
97
+ - `trace.har`: HAR 1.2 of every finished request; open it in DevTools or any
98
+ HAR viewer to see timings and bodies.
99
+ - `summary.json`: the object `stop()` returned.
100
+ - `screenshots/<seq>-<slug>-before.png` and `-after.png` for every step.
101
+
102
+ Steps rethrow, so call `stop()` in a `finally` to keep the evidence from a
103
+ failure. The recorder rides the existing network and console paths.
104
+
105
+ ## Routes: intercept with care
106
+
107
+ `createRoutes(page)` blocks, rewrites, or fakes requests:
108
+
109
+ ```js
110
+ const routes = createRoutes(page);
111
+ await routes.route("*/analytics/*", ({ abort }) => abort("BlockedByClient"));
112
+ await routes.route(/\/api\/flags$/, ({ fulfill }) =>
113
+ fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ beta: true }) }));
114
+ await routes.route(({ method }) => method === "POST", ({ request, continue: go }) =>
115
+ go({ headers: { ...request.headers, "x-test-run": "1" } }));
116
+ // ... drive the page ...
117
+ await routes.dispose(); // Fetch.disable
118
+ ```
119
+
120
+ Glob strings use `*` and `?`; a string without either is a substring match. A
121
+ handler that throws or never settles lets the request continue, with a warning.
122
+
123
+ Stealth caveat: `Fetch.enable` goes out on the first `route()`, and
124
+ interception changes the timing and blocking patterns that bot defenses score.
125
+ Leave routes off for WAF-protected targets and stealth profiles; use the snoop,
126
+ which is passive, to read the same traffic.
@@ -0,0 +1,103 @@
1
+ ---
2
+ name: visual-browse
3
+ description: Coordinate-level browser control for UI that snapshots, refs, and locators cannot target - canvas apps, extension popups, OS-drawn dialogs, custom drag surfaces. Read this when a DOM-targeted action fails twice, when the next decision depends on rendered pixels, or when CUA clicks land on the wrong element.
4
+ ---
5
+
6
+ # Visual Browse
7
+
8
+ `createCua(page)` drives the page by viewport coordinates when DOM targeting
9
+ cannot. It is rung 2 of the ladder below, not a last resort you ask permission
10
+ to reach.
11
+
12
+ ## Escalation ladder
13
+
14
+ **TWO IDENTICAL FAILURES ON THE SAME TARGET MEAN CLIMB, NOT RETRY.** The failure
15
+ itself selects the next rung — never pause to ask which one.
16
+
17
+ | Rung | Use | Advance when |
18
+ |---|---|---|
19
+ | 1. `page.snapshot()` + `page.locator(ref)` | Everything with a usable ref | Ref is absent, stale, obscured, or the click lands on the wrong node twice |
20
+ | 2. `createCua(page)` coordinates | Canvas, extension popups, custom controls, drag surfaces | The click misses, or the screenshot and the coordinates disagree |
21
+ | 3. Pin the viewport, then retry rung 2 | Coordinate drift: window resized, DPI scaled, or the tab was created at a different size | Coordinates land correctly but the widget still refuses input |
22
+ | 4. `createCaptcha(page)` | A challenge widget is what blocks progress | The widget is solved but the flow still stalls |
23
+ | 5. Environment diagnosis | Browser-level failure (entitlements, extension service worker, FIDO) | Logs name a cause outside the page |
24
+
25
+ **RUNG 5 ENDS IN A WRITTEN DIAGNOSIS, NEVER A CODE CHANGE.** When the browser log
26
+ names the cause (service-worker failure, missing entitlement, FIDO unavailable),
27
+ stop retrying and report it. Automation code cannot fix a browser-process problem.
28
+
29
+ Return to refs and locators as soon as DOM targeting works again. Coordinates are
30
+ the expensive path.
31
+
32
+ ## Pin the viewport before trusting coordinates
33
+
34
+ CUA acts in viewport pixels. When the render surface and the coordinate space
35
+ disagree, every coordinate is wrong by the same constant offset and retrying
36
+ repeats the miss. Pin both to one box:
37
+
38
+ ```js
39
+ await page._sendToTarget("Emulation.setDeviceMetricsOverride", {
40
+ width: 1440, height: 900, deviceScaleFactor: 1, mobile: false,
41
+ screenWidth: 1440, screenHeight: 900,
42
+ viewport: { x: 0, y: 0, width: 1440, height: 900, scale: 1 },
43
+ });
44
+ const size = await page.refreshViewportSize(); // -> { width: 1440, height: 900 }
45
+ ```
46
+
47
+ Pin every page you act on, including tabs you did not open, then take a fresh
48
+ screenshot — coordinates read off an unpinned screenshot are stale.
49
+
50
+ Pin rather than retry when: the click reports success but nothing changes; the
51
+ same offset is wrong on every target; screenshot dimensions disagree with the
52
+ coordinates you computed.
53
+
54
+ ## API
55
+
56
+ ```js
57
+ import { createCua } from "omowright";
58
+
59
+ const cua = createCua(page);
60
+ await cua.click({ x, y, button?, keypress? }); // keypress: modifiers held during click
61
+ await cua.doubleClick({ x, y, keypress? });
62
+ await cua.drag({ path: [{ x, y }, ...], keys? }); // mousedown at first point, move through path, mouseup
63
+ await cua.move({ x, y, keys? });
64
+ await cua.scroll({ x, y, scrollX, scrollY, keypress? });
65
+ await cua.type({ text });
66
+ await cua.keypress({ keys: ["ControlOrMeta", "a"] }); // ControlOrMeta = Meta on macOS, Control elsewhere
67
+ const base64Png = await cua.getVisibleScreenshot();
68
+ ```
69
+
70
+ Modifiers: `Alt`, `Control`, `ControlOrMeta`, `Meta`, `Shift`. Aliases: `Cmd`,
71
+ `Command`, `Ctrl`, `Option`. The CUA instance is bound to the page it was created
72
+ from — focus or attach the right tab first.
73
+
74
+ ## Look, act, verify
75
+
76
+ Look before acting when coordinates are unknown, and **VERIFY AFTER EVERY
77
+ PAGE-CHANGING ACTION — AN UNVERIFIED CUA ACTION HAS NOT HAPPENED.** Fresh
78
+ screenshot for visual state, fresh snapshot for DOM state.
79
+
80
+ - `cua.getVisibleScreenshot()` - base64 PNG.
81
+ - `page.screenshot({ path })` - file; cite the path when there is no `display()`.
82
+ - `page.annotatedScreenshot()` - numbered boxes over interactive elements.
83
+ - Eval/REPL kernel: `display(Buffer.from(await cua.getVisibleScreenshot(), "base64"))`.
84
+
85
+ A popup, modal, or cookie banner overlaying the target is cleared first —
86
+ everything behind it is unreachable. On layered canvas and editor surfaces,
87
+ prefer coarse sidebar and toolbar controls over precise clicks on stacked objects.
88
+
89
+ ## Surfaces that only CUA reaches
90
+
91
+ Browser chrome and OS-drawn UI have no DOM, so rung 1 is skipped entirely:
92
+
93
+ - **Extension popups** (password managers, wallets): click the toolbar icon by
94
+ coordinate, then act inside the popup by coordinate.
95
+ - **Platform credential dialogs** (passkey, Touch ID, OS password prompts): drawn
96
+ by the OS. If a click cannot satisfy them, that is rung 5 — read the browser
97
+ log rather than clicking harder.
98
+ - **Native select popups and file pickers**: prefer `locator.selectOption()` /
99
+ `locator.setInputFiles()`; use coordinates only for custom-rendered controls.
100
+
101
+ Values that leave the page through the system clipboard (a one-time code copied
102
+ by an extension) are read back with `pbpaste` on macOS and **VALIDATED BY SHAPE
103
+ BEFORE USE** — an unvalidated read silently carries whatever was there before.