omowright 0.0.0 → 0.2.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 (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +290 -2
  3. package/TOOLS.md +487 -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 +88 -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 +195 -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 +109 -0
  18. package/skills/omowright/references/stealth.md +174 -0
  19. package/src/agent-tabs.js +179 -0
  20. package/src/aria-hidden.js +47 -0
  21. package/src/bridge-schemas.js +44 -0
  22. package/src/bridge-transport.js +83 -0
  23. package/src/browser-context.js +105 -0
  24. package/src/browser-process.js +127 -0
  25. package/src/bsk/browser-signals.js +90 -0
  26. package/src/bsk/browsers.js +114 -0
  27. package/src/bsk/connect.js +75 -0
  28. package/src/bsk/daemon-info.js +100 -0
  29. package/src/bsk/external-extension.js +110 -0
  30. package/src/bsk/identify-browser.js +88 -0
  31. package/src/bsk/install-cli.js +81 -0
  32. package/src/bsk/ipc-client.js +236 -0
  33. package/src/bsk/onboard.js +140 -0
  34. package/src/bsk/screenshot.js +49 -0
  35. package/src/bsk/session.js +131 -0
  36. package/src/bsk/snapshot.js +56 -0
  37. package/src/bsk/targets.js +25 -0
  38. package/src/captcha-wait.js +79 -0
  39. package/src/captcha.js +142 -0
  40. package/src/cdp-errors.js +23 -0
  41. package/src/cdp-methods.js +69 -0
  42. package/src/chrome-profile.js +176 -0
  43. package/src/chrome.js +194 -0
  44. package/src/cloak-profile.js +266 -0
  45. package/src/connection.js +234 -0
  46. package/src/console-events.js +12 -0
  47. package/src/cookies.js +39 -0
  48. package/src/core.js +1702 -0
  49. package/src/cua.js +74 -0
  50. package/src/dialog-policy.js +80 -0
  51. package/src/emulate.js +127 -0
  52. package/src/events.js +111 -0
  53. package/src/frames-snapshot.js +138 -0
  54. package/src/har.js +103 -0
  55. package/src/human-handoff.js +124 -0
  56. package/src/index.js +89 -0
  57. package/src/injected.js +3 -0
  58. package/src/instance-lock.js +74 -0
  59. package/src/instances.js +490 -0
  60. package/src/internal-capability.js +1 -0
  61. package/src/launch-endpoint.js +185 -0
  62. package/src/layers.js +138 -0
  63. package/src/llm.js +201 -0
  64. package/src/lock-backend-win32.js +54 -0
  65. package/src/lock-backend.js +81 -0
  66. package/src/native-host-win32.js +201 -0
  67. package/src/network-events.js +223 -0
  68. package/src/network-snoop.js +229 -0
  69. package/src/nul-frames.js +28 -0
  70. package/src/open-shadow-query.js +101 -0
  71. package/src/owner-only.js +196 -0
  72. package/src/page-bundle.js +1478 -0
  73. package/src/page-events.js +45 -0
  74. package/src/page-routes.js +94 -0
  75. package/src/page-setup.js +239 -0
  76. package/src/pipe.js +418 -0
  77. package/src/process-start-time.js +64 -0
  78. package/src/routes.js +256 -0
  79. package/src/running-browser.js +85 -0
  80. package/src/scroll-collect.js +73 -0
  81. package/src/serial-emitter.js +17 -0
  82. package/src/shared-connections.js +285 -0
  83. package/src/snapshot-diff.js +75 -0
  84. package/src/text-matching.js +101 -0
  85. package/src/trace.js +183 -0
  86. package/src/url-match.js +148 -0
  87. package/src/viewport.js +12 -0
package/TOOLS.md ADDED
@@ -0,0 +1,487 @@
1
+ # OmOWright tools — agent-facing reference
2
+
3
+ Drive a browser with Playwright-shaped JS. Two transports: `connectPipe`
4
+ (launch a browser, zero TCP port) and `connect(cdpHttpUrl)` (attach to a
5
+ running Chromium DevTools endpoint).
6
+
7
+ ## Core loop
8
+
9
+ 1. Open or attach a tab: `connection.newTab(url)` / `connection.attachPage(targetId)`.
10
+ 2. Read the page with `page.snapshot()` — never `page.content()` for reading.
11
+ 3. Act through `page.locator(refOrCss)` using `[ref=eN]` ids from the snapshot.
12
+
13
+ ## Tools
14
+
15
+ - `newTab(url)` — open a tab, waits for interactivity, returns page.
16
+ - `listTargets()` — list open tabs (id, type, url, title).
17
+ - `attachPage(targetId)` — attach an existing tab.
18
+ - `page.goto(url)` — navigate; resolves when interactive with the main-frame
19
+ document response (the final hop after redirects), or `null` for a
20
+ same-document navigation such as a `#hash` change. `page.reload()`,
21
+ `page.goBack()` and `page.goForward()` resolve the same way once the new
22
+ document is active (they do not wait for `load`), and `null` when there is
23
+ no history entry (also `null` when the transport emits no network events).
24
+ The response is the object described under `page.on("request" | "response")`;
25
+ its body stays readable after the call.
26
+ - `page.waitForURL(url, { timeout?, waitUntil? })` — wait until the page URL
27
+ matches a Playwright glob (`**` crosses `/`, `*` does not, `{a,b}` is a
28
+ choice, `?` is a literal question mark), a RegExp, or a predicate
29
+ `(url: URL) => boolean`. With `waitUntil` it then waits for that load state;
30
+ without it, it returns as soon as the URL matches.
31
+ - `page.waitForLoadState(state, { timeout? })` — `domcontentloaded` and `load`
32
+ wait for those document events; `networkidle` waits until no request has been
33
+ in flight for 500 ms (requests already running when the wait starts are not
34
+ seen); `interactive` (default) and `stable` use the `goto` readiness probe.
35
+ - `page.setContent(html, { waitUntil, timeout })` — replace the document with
36
+ `html`; waits for `load` by default (`domcontentloaded`, `networkidle`,
37
+ `commit`), timeout 30000ms (0 disables it).
38
+ - `page.waitForTimeout(ms)` — discouraged: a fixed sleep. Wait for the state
39
+ you need instead (`locator.waitFor`, `page.waitForURL`, `page.waitForLoadState`).
40
+ - `page.waitForEvent("popup")` / `page.on("popup", listener)` — deliver the
41
+ newly opened page after attachment and interactivity. Subscribe before
42
+ `window.open(...)` or a `target="_blank"` click. The result supports `url()`,
43
+ `snapshot()`, `goto()`, and the other page methods. The old `{ url, windowName }`
44
+ event metadata is available as `popup.popupMetadata` (`url` is the originally
45
+ requested URL; `popup.url()` is the current URL). Only popups from agent-owned
46
+ tabs with an active popup listener or waiter are adopted. User tabs attached
47
+ with `attachPage()` and unobserved popups remain untouched. Adopted popups are
48
+ registered with `createAgentTabs(connection)` and closed with its owned tabs
49
+ or the connection. Disconnecting leaves ordinary `newTab()` tabs open.
50
+ A popup that closes before attachment rejects its popup waiter promptly.
51
+ - `page.snapshot(options?)` — PRIMARY read. Returns `{tree, refs}`; tree lines
52
+ look like `- link "Learn more" [ref=e1]`. Options: `maxDepth` (50),
53
+ `maxChars`, `interactive`, `showHidden`, `selector`, `ref`.
54
+ - `compactSnapshot(snapshot)` — returns the raw tree without the refs map
55
+ (refs resolve in-page; the map is ~54% of bytes on real pages). Use before
56
+ sending snapshots to a model.
57
+ - `page.locator(refOrCss)` — `click`, `fill`, `press`, `pressSequentially`,
58
+ `hover`, `check`, `selectOption`, `dragTo`, `setInputFiles`, `textContent`,
59
+ `innerText`, `allTextContents`, `allInnerTexts`, `isVisible`, `waitFor`,
60
+ `first/nth/last`, `filter`, `and` (both match), `or` (either matches, document order).
61
+ - `page.getByRole(role, options?)`, `getByText(text, { exact })`,
62
+ `getByLabel(text, { exact })`, `getByPlaceholder(text, { exact })`,
63
+ `getByAltText(text, { exact })`, `getByTitle(text, { exact })`,
64
+ `getByTestId(testId)` — Playwright locators. Frames (`page.frames()`,
65
+ `page.mainFrame()`), frame locators (`page.frameLocator(css)`) and locators
66
+ (`page.locator(css).getByTestId(id)`, scoped to that locator) have the same
67
+ getters. They match inside open shadow roots, never inside closed ones.
68
+ For placeholder, alt text and title, a string matches a
69
+ case-insensitive substring of the attribute, `exact: true` the whole
70
+ case-sensitive value, and a RegExp the raw value. `getByTestId` matches
71
+ `data-testid` exactly (or by RegExp); `selectors.setTestIdAttribute(name)`
72
+ switches the attribute for locators created afterwards.
73
+ - `page.evaluate(expression)` — run JS in the page.
74
+ - `page.addInitScript(script, arg?)` — register a function (with one serializable
75
+ argument), a source string, `{ content }`, or `{ path }` (relative to the
76
+ working directory). It runs in the main world before document scripts on
77
+ every navigation and child-frame attachment/navigation, including
78
+ out-of-process frames. It does not run in the current document.
79
+ - `page.exposeFunction(name, callback)` — install an async function on every
80
+ frame's `window`, including existing frames and future documents. Browser
81
+ calls forward their arguments to the host callback; its result resolves the
82
+ browser promise and a thrown error rejects it. Duplicate names reject.
83
+ Supports JSON-like values, `undefined`, non-finite numbers, `-0` and bigints.
84
+ This member enables Runtime on demand and keeps it enabled for the binding's
85
+ lifetime; ordinary page setup does not enable Runtime.
86
+ - `page.exposeBinding(name, callback)` — like `exposeFunction`, but the host
87
+ callback receives `{ context, page, frame }` before the browser arguments.
88
+ `context` is the real `page.context()` object and `frame` is the calling
89
+ frame, including a same-process or out-of-process child. Bindings survive
90
+ frame and page navigation and are installed in existing frames.
91
+ - `page.setExtraHTTPHeaders(headers)` — replace the page's extra request
92
+ headers, including frame requests; values must be strings. Pass `{}` to
93
+ clear them. Network ownership is shared with readiness and request capture,
94
+ so ending a transient subscription does not remove the headers.
95
+ - `page.setViewportSize({ width, height })` — set positive integer CSS-pixel
96
+ viewport and screen dimensions. On an agent-owned tab this also updates
97
+ its navigation pin, using the manager's serialized repin queue.
98
+ - `page.emulateMedia({ media?, colorScheme?, reducedMotion?, forcedColors?, contrast? })`
99
+ — emulate CSS media and preferences. `media` accepts `"screen"` or `"print"`;
100
+ `colorScheme` accepts `"light"`, `"dark"` or `"no-preference"`;
101
+ `reducedMotion` accepts `"reduce"` or `"no-preference"`;
102
+ `forcedColors` accepts `"active"` or `"none"`; `contrast` accepts `"more"` or
103
+ `"no-preference"`. Omitted properties retain their overrides; `null` clears
104
+ that property's override. Applies to current and future frame sessions.
105
+ - `page.context()` — the page's browser context (shared by pages in the same
106
+ context on this connection). Cookie reads, writes and clears are scoped to
107
+ that CDP browser context, including when attached to an incognito tab.
108
+ The supported [Playwright context methods](https://playwright.dev/docs/api/class-browsercontext)
109
+ are:
110
+ - `context.cookies(urls?)` — all cookies, or those affecting a URL string or
111
+ array of URLs. Returns `{ name, value, domain, path, expires, httpOnly,
112
+ secure, sameSite, partitionKey? }`; `expires` is Unix seconds (`-1` for a
113
+ session cookie).
114
+ - `context.addCookies(cookies)` — each cookie requires `name`, `value` and
115
+ either `url` or both `domain` and `path`. Optional fields: `expires`,
116
+ `httpOnly`, `secure`, `sameSite` (`"Strict"`, `"Lax"`, `"None"`) and
117
+ `partitionKey`. Unlike raw-export `injectCookies`, this preserves
118
+ same-name cookies at different paths.
119
+ - `context.clearCookies({ name?, domain?, path? }?)` — clear all cookies or
120
+ only those matching every supplied string or RegExp filter.
121
+ - `context.storageState({ path? }?)` — return `{ cookies, origins }`, where
122
+ each origin is `{ origin, localStorage: [{ name, value }] }`. Includes
123
+ localStorage for HTTP(S) origins observed by attached pages, even after
124
+ navigating away or closing them. A temporary, intercepted blank page reads
125
+ storage without running those sites' scripts or navigating existing pages.
126
+ With `path`, also write the same JSON, creating parent directories; relative
127
+ paths resolve from the current working directory. IndexedDB is not included.
128
+ Restore cookies with `addCookies(state.cookies)` and localStorage by
129
+ navigating a fresh page to each origin and setting its saved entries.
130
+ - `context.newPage()` — create an agent-owned blank page in this context.
131
+ - `page.waitForRequest(urlOrPredicate, { timeout? })` /
132
+ `page.waitForResponse(urlOrPredicate, { timeout? })` — wait for the next
133
+ matching request or response headers (default timeout: 30000ms). Match an
134
+ exact URL string, a RegExp, or a sync/async predicate over the object.
135
+ Register the wait before triggering the request.
136
+ - `page.on("request" | "response", listener)` — observe traffic; the returned
137
+ function unsubscribes, as does `page.off(event, listener)`. Both waits and
138
+ listeners receive objects with `url()`, `method()`, `headers()` (lowercase
139
+ names), and async `body()` (Buffer), `text()`, `json()`. Request bodies are
140
+ the CDP request's post data; responses also expose `status()` and `ok()`
141
+ (status 200-299). Response body reads wait for transfer completion and
142
+ decode base64 when necessary.
143
+ Bodies are cached on completion for response objects delivered to listeners.
144
+ If the transport refuses `Network.getResponseBody`, these reads reject with
145
+ the exported `NetworkBodyUnavailableError` (the transport error is `cause`),
146
+ never `null`. Failed transfers and redirects also reject body reads.
147
+ Network subscriptions and domain ownership are shared with
148
+ `createNetworkSnoop()` and readiness tracking. They start on demand and
149
+ release after the last consumer and its pending response bodies finish;
150
+ no Runtime domain is enabled. A refused Network enable does not break page
151
+ setup, but a transport that emits no network events will time out waits.
152
+ - `page.waitForFunction(pageFunction, arg?, { timeout, polling })` — wait for
153
+ app-specific page state instead of sleeping. Runs `pageFunction(arg)` (a
154
+ function, or a string expression) in the page's main world until it returns a
155
+ truthy value, then resolves with that value by value: DOM nodes and functions
156
+ come back as `{}`, and a value CDP cannot return by value (a cycle such as
157
+ `window`, a symbol or a bigint) as `true`. `polling` is `"raf"` (default,
158
+ every animation frame, or every 100 ms when the page gets no frames, as a
159
+ background tab of a headful browser does) or a positive number of
160
+ milliseconds. `timeout`
161
+ defaults to 30000; `0` waits forever. A same-tab navigation during the wait
162
+ re-runs the function in the new document. An error thrown by the function,
163
+ or closing the page, rejects at once; a timeout rejects with
164
+ `WaitForFunctionTimeoutError` (exported; `timeoutMs`, and the message
165
+ carries the function source cut at 200 characters). Example:
166
+ `await page.waitForFunction(n => document.querySelector(".badge")?.textContent === String(n), 3)`.
167
+ - `page.screenshot(options?)` — image bytes (path, fullPage, clip, type, quality).
168
+ - `page.pdf(options?)` — PDF bytes (path, format, margin, printBackground).
169
+ - `page.keyboard` / `page.mouse` — press, type, insertText / move, click, wheel.
170
+ - `page.on(event, listener)` / `page.off(event, listener)` /
171
+ `page.waitForEvent(event, { timeout?, predicate? })` — page events; `on`
172
+ returns an unsubscribe function. The accepted names are the exported
173
+ `PAGE_EVENT_NAMES`: `close`, `console`, `crash`, `dialog`,
174
+ `domcontentloaded`, `download`, `filechooser`, `frameattached`,
175
+ `framedetached`, `framenavigated`, `load`, `pageerror`, `popup`, `request`,
176
+ `response`. Any other name throws a `TypeError` that lists them.
177
+ `pageerror` receives an `Error` (page `name`, `message` and `stack`) for each
178
+ uncaught exception or unhandled rejection in the page or its frames. The
179
+ Runtime domain it needs is enabled only while a `pageerror` or `console`
180
+ listener or an exposed function exists (pages can detect it), and exceptions thrown before the
181
+ subscription are not replayed. `close` fires once the tab is gone, whether
182
+ `page.close()`, `window.close()`, the user or another client closed it; the
183
+ page is disposed with it.
184
+ - `createCua(page)` — coordinate fallback (visual-browse equivalent): `click`,
185
+ `doubleClick`, `drag({path})`, `move`, `scroll`, `type`, `keypress`,
186
+ `getVisibleScreenshot()` (base64 PNG). Use only when refs/locators cannot
187
+ target the UI (canvas, custom controls, stale refs).
188
+ - `createCaptcha(page, { ocr? })` — input, OCR, and explicit condition helpers,
189
+ not a general CAPTCHA solver. `click(bounds, opts?)` defaults to the center;
190
+ optional `opts.point` is an absolute top-level viewport CSS-pixel point inside
191
+ the bounds. Positive integer `opts.approachSteps` adds intermediate movement,
192
+ not a human-likeness guarantee. Re-measure after scrolling/resizing; iframe
193
+ bounds alone do not locate a checkbox. `drag(from, to, {steps?, settleMs?})`
194
+ defaults to 20 steps. Both return a compact snapshot tree string after
195
+ settling (`settleMs` defaults to 3000ms, allows 0), not proof of acceptance.
196
+ `waitFor({until, timeoutMs = 10000, pollMs = 100, signal?})` separately returns
197
+ `{outcome: "matched" | "timed_out" | "cancelled", elapsedMs}`, with no tree.
198
+ Use `click(bounds, {settleMs: 0})`, then an application-specific acceptance
199
+ predicate: only literal `true` matches. Checks are serial under one deadline;
200
+ abort takes priority over timeout, then match. Predicate errors propagate;
201
+ cancellation cannot retract dispatched input/requests or interrupt blocking
202
+ synchronous code. Take `page.screenshot()` separately for visual evidence.
203
+ `readText(bounds?)` OCRs a screenshot region and returns text or `null`, never
204
+ a tree. It defaults to macOS Vision (`macOSVisionOcr`); pass
205
+ `ocr: async (pngBuffer) => string` on other platforms or to use a vision model.
206
+ Full bounds, timing, cancellation, and acceptance examples:
207
+ [CAPTCHA skill](presets/captcha/SKILL.md).
208
+ - `createChromeApi(connection, { profilePath?, downloadDir? })` — Chrome
209
+ MV3-shaped APIs: `tabs.query/get`, `windows.get/getCurrent/getAll` (no
210
+ `focused` field and `windows.getLastFocused` throws: CDP exposes no window
211
+ focus), `bookmarks.*` (read-only), `history.search/getVisits`,
212
+ `downloads.search/download`, `topSites.get`. Profile-backed methods need
213
+ `profilePath`. Write methods throw `UnsupportedOperationError` (extension
214
+ bridge required). Full reference: presets/chrome/.
215
+ - `injectCookies(page, cookies)` — inject raw cookie exports (e.g. from a
216
+ real browser profile) with CDP sanitization handled: negative `expires`
217
+ dropped, `__Host-` cookies forced secure + root path + url-scoped,
218
+ `SameSite=None` dropped when not secure, name+domain deduped.
219
+ `sanitizeCookies(cookies)` is the pure transform if you need it.
220
+
221
+ Every tool below is exported from `src/index.js`, the same import as the core
222
+ loop; the module files next to it are implementation detail.
223
+
224
+ - `connectNamed(name, { browserPath, browserArgs, profileDir, registryRoot?,
225
+ dialogPolicy?, probeTimeoutMs?, launchTimeoutMs?, connectTimeoutMs?,
226
+ lockTimeoutMs? })`:
227
+ attach-or-launch a named Chromium. A healthy registered instance is attached;
228
+ a stale record is cleaned up and relaunched; a live pid whose recorded port
229
+ refuses connections, or answers as a different browser, is treated as a reused
230
+ pid (stale → relaunch), while an endpoint that hangs or answers wrongly throws
231
+ an `unresponsive holder` error naming the holder (name, pid, endpoint). The
232
+ record stores the browser's `webSocketDebuggerUrl` (it carries the browser
233
+ GUID) and an attach happens only while the endpoint still answers with it, so
234
+ a reused pid plus a rebound port cannot hand you a stranger's browser. Every
235
+ wait is bounded: discovery by `probeTimeoutMs`, the launch by
236
+ `launchTimeoutMs`, the CDP handshake by `connectTimeoutMs`, the registry lock
237
+ by `lockTimeoutMs` (default: the other three plus a margin).
238
+ The registry lock is kernel-held and released when its holder closes it or
239
+ exits. A timeout names the `.flock` path; use `lsof`, `fuser`, or Windows
240
+ `handle.exe` on that path to find its holder.
241
+ **The named endpoint is unauthenticated.** CDP listens on 127.0.0.1 with a
242
+ kernel-chosen port: off the network, but any local process or user can drive
243
+ that browser. Name-less launches (`connectPipe`, `connectCloakProfile()`
244
+ without `name`) expose no port at all.
245
+ `newTab()` works on both paths; `close()` from the launcher terminates the
246
+ browser and removes its record, from an attached client it only detaches.
247
+ Attaches in one process share one CDP connection per browser, because
248
+ Chrome asks the user to allow remote debugging once per connection: each
249
+ attach returns a handle on it, `close()` releases that handle, and the last
250
+ release disconnects. Every connection handle is also async-disposable, so a
251
+ script can write `await using browser = await connect(url)`: the handle is
252
+ released when the scope ends, also on a throw, and the script exits without
253
+ a trailing `close()` or `process.exit()`. Agent tabs stay open for the next
254
+ script's `attachPage(targetId)`; popups the script attached are closed with
255
+ the connection, so create tabs that must outlive the script with
256
+ `createAgentTabs`. A dropped socket is reconnected once, and a browser
257
+ with another GUID always gets its own connection. Callers passing different
258
+ connection options (storage root, client options, `dialogPolicy`) are not
259
+ shared. A holder never changes what another holder gets: on a shared handle
260
+ `setDialogPolicy` throws `SharedConnectionError` (`error.code ===
261
+ "shared_connection"`; pass `dialogPolicy` when attaching instead), a sole holder's `setDialogPolicy` works and that
262
+ connection is never shared again, properties set on a handle stay on it,
263
+ writing or defining `cdp`, `close` or `setDialogPolicy` on a handle throws
264
+ `TypeError`, the shared client can't be written through it, and listeners
265
+ added through `handle.cdp` are removed by that handle's `close()`.
266
+ `handle.cdp.transportEvents.clearListeners()` removes only that handle's
267
+ transport listeners, and `handle.cdp.transportEvents.emit()` throws
268
+ `TypeError`. The connection keeps a frozen copy of the options it was
269
+ attached with, so mutating your options object after attaching changes
270
+ nothing. `handle.cdp.dialogPolicy` on a shared connection is that frozen
271
+ copy (or a frozen default when you passed none), not your object, so it
272
+ can't be changed in place. `setDialogPolicy(undefined)` resets to the default (accept every
273
+ dialog).
274
+ `listInstances()` returns every record (`{ name, pid, endpoint,
275
+ webSocketDebuggerUrl, profileDir, browserPath, startedAt }`) with `alive` /
276
+ `responsive` liveness.
277
+ - `createNetworkSnoop(page, { match?, bodies=true, maxEntries=500, maxBodyBytes? })`:
278
+ buffer finished network entries for one page. `match` is a predicate or
279
+ `{ url: string|RegExp, method, mimeType, resourceType }`. Methods: `pop()`
280
+ (drain), `peek()` (copy), `popJson()` (drain and parse JSON bodies),
281
+ `waitFor(match, { timeoutMs })` (resolves with the next matching entry),
282
+ `summary({ max })` (one line per entry: method status mime bytes url),
283
+ `dispose()`. Entries carry `requestId, url, method, resourceType, status,
284
+ statusText, mimeType, requestHeaders, responseHeaders, postData,
285
+ encodedDataLength, body, base64Encoded, bodySkipped, failed, errorText,
286
+ startedAt, finishedAt`.
287
+ - `collectWhileScrolling(page, snoop, { minItems, maxScrolls=10, extract, scroll:
288
+ "wheel"|"end", settleMs=800 })`: async generator. Each round scrolls, settles, drains
289
+ `snoop.popJson()` through `extract(json) => items[]`, yield each item. Returns
290
+ `{ rounds, total, stoppedBecause: "minItems"|"maxScrolls"|"noGrowth" }`.
291
+ - `createTrace(page, { dir, screenshots=true, network=true, console=true,
292
+ maxBodyBytes?, events? })`: flight recorder. `step(name, fn)` runs `fn` with
293
+ before/after screenshots and timing, `mark(name, data)` drops a marker,
294
+ `stop()` flushes and returns the summary. Writes `dir/trace.jsonl` (kinds:
295
+ step, network, console, dialog, navigation, download, mark, warning),
296
+ `dir/trace.har` (HAR 1.2), `dir/summary.json`, and
297
+ `dir/screenshots/<seq>-<slug>-before|after.png`. `trace.dir` is the resolved
298
+ directory. Never sends `Runtime.enable`.
299
+ - `toHar(entries, { creator?, pages? })`: pure HAR 1.2 builder over snoop entries.
300
+ - `reconcileFrames(page)`: re-links OOPIF child frames that lost their parent;
301
+ returns the frames it added. `snapshotWithFrames(page, opts?)`: snapshot that
302
+ runs the repair first and adds `missingFrames` only when a frame could not be
303
+ entered at all. Details in "Frames (OOPIF) and shadow DOM" below.
304
+ - `requestHuman(page, { prompt, until?, timeoutMs=300000, pollMs=500, signal? })`:
305
+ bring the window to front, show a shadow-DOM banner with a Done button, and
306
+ wait. `until` is `{ url: string|RegExp }`, `{ selector }`, or
307
+ `async (page) => boolean`. Resolves `{ outcome: "continued"|"timed_out"|
308
+ "cancelled", elapsedMs, reason: "until"|"done-button"|"timed_out"|"signal" }`.
309
+ The banner is removed on every path.
310
+ - `describeLayers(page, { grid=5 })`: hit-test a grid over the viewport and
311
+ report `{ blocking: null | { tagName, role, name, coverage, position,
312
+ selectorHint, ariaModal }, candidates, viewport }`. `layersHeader(result)`
313
+ renders `@layers none` or `@layers blocking=<role|tag> "<name>" coverage=NN%
314
+ hint=<sel>`. `snapshotWithLayers(page, opts?)` prepends that header to
315
+ `tree` and adds a `layers` field.
316
+ - `DEVICE_PRESETS` (`"iphone-14"` 390x844 @3x touch, `"pixel-7"` 412x915,
317
+ `"ipad-air"` 820x1180, `"desktop-1440"` 1440x900) and
318
+ `emulate(page, nameOrPreset)`: set metrics, touch, and UA together;
319
+ `emulate(page, null)` clears the override and restores the UA captured on the
320
+ first call.
321
+ - `page.route(urlGlobOrRegExpOrPredicate, handler, { times }?)`,
322
+ `page.unroute(url, handler?)`, `page.unrouteAll()`: request interception.
323
+ Strings match the whole URL: `*` excludes `/`, `**` crosses directories,
324
+ `{png,jpg}` matches alternatives, and `?` is literal. Predicates receive
325
+ a `URL`. The newest matching handler runs first; `route.fallback()` passes
326
+ to the next match, while `route.continue({ url, method, headers, postData })`
327
+ sends directly to the network. Handlers receive `(route, request)`;
328
+ `route.request()` returns that request, with `url()`, `method()`, `headers()`,
329
+ `postData()` and `resourceType()`. Respond with
330
+ `route.fulfill({ status, headers, contentType, body, json, path })` or
331
+ `route.abort(errorCode?)` (default `"failed"`, also `"blockedbyclient"`, etc.).
332
+ `times` limits matching invocations. Fetch stays off until registration and
333
+ is disabled after the last route is removed or exhausted. Page methods and
334
+ `createRoutes(page)` share one dispatcher; `unrouteAll()` clears both.
335
+ - `createRoutes(page)`: legacy request interception. `route(match, handler)`,
336
+ `unroute(match?)`, `dispose()`, `enabled`. `match` is a glob string (`*` and
337
+ `?`; plain substring otherwise), a RegExp, or a predicate over
338
+ `{ url, method, resourceType, headers }`. The handler receives `{ request,
339
+ continue(overrides), fulfill({ status, headers, contentType, body }),
340
+ abort(reason) }`. `Fetch.enable` is sent on the first `route()` only.
341
+ - Dialog policy: `connectPipe({ dialogPolicy })`, `connect(url, { dialogPolicy })`,
342
+ `new PipeCdpClient({ dialogPolicy })`, `client.setDialogPolicy(policy)`, `client.dialogPolicy`,
343
+ `BrowserConnection.setDialogPolicy(policy)`. Pure helpers in
344
+ `src/dialog-policy.js`: `normalizeDialogPolicy(policy)`,
345
+ `resolveDialogAction(policy, dialogParams)`. See "Dialogs" below.
346
+
347
+ ## Attached engine (BrowserSkill)
348
+
349
+ - `connectBrowserSkill({ name, browser, width, height, focused, home, sockPath,
350
+ autoStart, timeoutMs })`: starts a session in the user's own browser through
351
+ the BrowserSkill daemon's IPC socket and returns a `BskSession`. `browser`
352
+ takes an instance id, a unique label, or a browser name such as `"chrome"`
353
+ that exactly one connected browser carries. Throws
354
+ `BskRpcError` `no_browser_connected` when no extension is attached, and
355
+ `extension_outdated` when the chosen extension is 0.4.0 (its task tab groups
356
+ stay in the user's browser after the task); with no `browser` named it picks
357
+ an up-to-date connected browser over a 0.4.0 one. Never launches a browser of
358
+ its own.
359
+ - `BskSession`: `navigate`, `back`, `forward`, `reload`, `observe`, `snapshot`,
360
+ `getHtml`, `screenshot({ ref, fullPage })`, `click`, `hover`, `fill`,
361
+ `press`, `select`, `focus`, `blur`, `scrollTo`, `wheel`, `evaluate`,
362
+ `tabList`, `tabCreate`, `tabClose`, `tabSelect`, `tabBorrow`, `tabReturn`,
363
+ `waitForNavigation`, `requestHelp`, `console`, `network`, `resize`,
364
+ `emulate`, `cooperate(action)`, `stop()`. Targets: `"e3"` / `"@e3"` (daemon
365
+ refs), a CSS selector, or `{ captureId, x, y }`. BrowserSkill 0.4 refuses
366
+ page actions (`cooperation_sync_required`) without `{ context }` from the
367
+ latest `cooperate("sync")`; `dependsOn` narrows that check
368
+ (`skills/omowright/references/browserskill.md`).
369
+ - `bskSnapshot(session, options)`: OmOWright `{ tree, refs, css }` from an
370
+ attached tab with no page global and no DOM mutation; `css[ref]` is `null`
371
+ inside shadow roots.
372
+ - `bskDoctor({ browser })` / `bskOnboard({ browser, onHumanStep })`: CLI install
373
+ (official installer, rc-file changes reverted), daemon start, then Web Store
374
+ extension registration through Chrome's External Extensions
375
+ (`registerExternalExtension` / `unregisterExternalExtension`) for the one
376
+ browser the user actually uses, then a wait on
377
+ `system.status{wait_for_browser_ms}`. The one human step is returned as
378
+ `humanStep`; `needsChoice: true` means nothing was registered and the user
379
+ has to name the browser. While the daemon is down nothing is registered,
380
+ `humanStep` is `null`, and `nextStep` says how to start the daemon; otherwise
381
+ `nextStep` is the same step as `humanStep` (`null` once ready).
382
+ - `identifyBrowser({ catalog, signals, explicit, connected })` /
383
+ `probeBrowserSignals()` / `catalogBrowsers()` / `detectBrowsers()`: the
384
+ browser choice on its own — the daemon's connected `browser_name`s, default
385
+ browser, running process and recent-use signals, ranked; ambiguity returns
386
+ `needsChoice` instead of a guess.
387
+ - `BskIpcClient` / `BskRpcError` / `readDaemonInfo` / `resolveBskHome`: the
388
+ raw JSON Lines IPC client (`call`, `callWithHandle`, `cancel`) for daemon
389
+ methods the session does not wrap.
390
+
391
+ ## Rules
392
+
393
+ - Ref ids are virtual: pass them straight to `page.locator('e1')`, never into
394
+ CSS selectors. Every new snapshot invalidates earlier ref ids. Attached-engine
395
+ refs from `session.observe()` are `@eN` strings for `session.click("@e3")`;
396
+ `bskSnapshot` refs are clicked through `css[ref]`.
397
+ - Raw CDP `page._sendToTarget(method, params)` exists but is an escape hatch;
398
+ prefer the tools above.
399
+
400
+ ## Dialogs (alert / confirm / prompt / beforeunload)
401
+
402
+ Every JavaScript dialog is **answered at the transport layer**: by a `dialog`
403
+ listener that answers it, otherwise by a dialog policy, so the page never hangs
404
+ waiting for a human, including a click that triggers `window.print()`. The default policy accepts everything, which keeps
405
+ the old behaviour: `alert()` returns immediately, `confirm()` returns `true`,
406
+ `prompt()` returns `""`, `beforeunload` never blocks navigation, and dialogs
407
+ during page load are handled the same way (`page.goto()` still completes because
408
+ readiness is content-probe based).
409
+
410
+ A policy is either an object or a function:
411
+
412
+ ```js
413
+ const browser = await connectPipe({ browserPath, browserArgs, storageRoot,
414
+ dialogPolicy: { accept: false } }); // confirm() -> false, prompt() -> null
415
+ browser.setDialogPolicy({ accept: true, promptText: "agent@example.com" }); // prompt() -> the text
416
+ browser.setDialogPolicy(dialog => { // { type, message, defaultPrompt, url }
417
+ if (dialog.type === "beforeunload") return true;
418
+ return { accept: !/delete/i.test(dialog.message), promptText: dialog.defaultPrompt };
419
+ });
420
+ browser.cdp.dialogPolicy; // read the current policy (client getter)
421
+ ```
422
+
423
+ - `{ accept: false }` dismisses: `confirm()` returns `false`, `prompt()` returns
424
+ `null`. `alert()` returns either way.
425
+ - `promptText` is the value `prompt()` resolves to when accepted.
426
+ - A function policy may return `boolean` or `{ accept, promptText }`, sync or
427
+ async. A policy that throws falls back to accept, so a bug in the policy
428
+ cannot hang the page.
429
+ - `connectPipe({ dialogPolicy })` and `connect(url, { dialogPolicy })` set it
430
+ up front; `browser.setDialogPolicy()` swaps it later (it forwards to the pipe
431
+ or WebSocket client and throws for a transport without policy support).
432
+ - `page.on('dialog', dialog => ...)` hands each listener a Playwright-style
433
+ `Dialog`: `type()`, `message()`, `defaultValue()` (the prompt's default
434
+ text), `url`, `accept(promptText?)` and `dismiss()`. A listener that answers
435
+ replaces the policy for that dialog. The policy answers once the listeners
436
+ have run and none of them answered, so a listener that only looks (a trace,
437
+ `page.waitForEvent('dialog')`) leaves the dialog to the policy:
438
+
439
+ ```js
440
+ page.on("dialog", dialog =>
441
+ dialog.type() === "prompt" ? dialog.accept("agent@example.com") : dialog.dismiss());
442
+ ```
443
+
444
+ Answer inside the listener or in a promise it returns: the policy waits for
445
+ that promise. A dialog is answered once: a second `accept()` / `dismiss()`,
446
+ or one after the policy answered, rejects.
447
+ - CDP listeners of `Page.javascriptDialogOpening` get the same `Dialog` as
448
+ `meta.dialog`. On a shared connection the policy is the connection's and a
449
+ listener belongs to the handle that added it: it answers until that handle
450
+ closes, then the policy answers again.
451
+
452
+ ## Frames (OOPIF) and shadow DOM
453
+
454
+ - Out-of-process iframes are stitched into the snapshot as child trees under
455
+ the owning `- iframe [ref=eK]:` line. Child refs look like `f<N>e<M>` and go
456
+ straight to `page.locator("f1e3")`; the page routes them to the right frame
457
+ session. There is no separate frame object to hold.
458
+ - Plain `page.snapshot()` sees OOPIFs that existed before `attachPage()`; no
459
+ extra call is needed for the common case.
460
+ - Closed shadow roots hide the host link, so a frame inside one lands in an
461
+ orphan `- iframe:` block at the end of the tree. Its refs still work.
462
+ - `reconcileFrames(page)` re-links child frames whose parent link was lost (it
463
+ returns the frames it added). `snapshotWithFrames(page)` runs that repair and
464
+ reports `missingFrames` only when a frame could not be entered at all. Reach
465
+ for these when a snapshot shows an `iframe` with no children you expected.
466
+ - Rough edge: the first click into a freshly adopted OOPIF can land on the
467
+ embedder. Re-snapshot and click the ref again.
468
+
469
+ ## Stealth notes
470
+
471
+ - The `Network` domain is already enabled for every page session, and pages
472
+ cannot observe it. `createNetworkSnoop` and `createTrace` add no new signal.
473
+ - `Fetch` interception changes request timing and blocking patterns that bot
474
+ defenses can fingerprint. It's off until the first `createRoutes().route()`
475
+ call, and `dispose()` turns it off again. Keep routes out of stealth runs.
476
+ - None of these modules send `Runtime.enable`; `requestHuman` and
477
+ `describeLayers` use `page.evaluate`, which shares the existing path.
478
+ - Device emulation swaps the UA and metrics; pair it with a matching
479
+ fingerprint seed when the target scores consistency.
480
+
481
+ ## Readiness probe
482
+
483
+ `page.goto()` waits for meaningful content, not just `document.readyState`:
484
+ the page is ready when `body` exists AND (interactive elements > 0 OR
485
+ landmarks > 0 OR visible text >= 20 chars). A near-empty page (e.g.
486
+ `<h1>ok</h1>`) never satisfies the probe and `goto` times out after 30s — use
487
+ `page.goto(url, { waitUntil: "commit" })` for content-free fixtures.
@@ -0,0 +1,112 @@
1
+ #!/usr/bin/env node
2
+
3
+ import {
4
+ compactSnapshot,
5
+ connectCloakProfile,
6
+ resolveCloakProfile,
7
+ } from "../src/index.js";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+
11
+ const HELP = `Usage: omowright-cloak [options]
12
+
13
+ Launch CloakBrowser through OmOWright with a stable persistent profile.
14
+
15
+ Options:
16
+ --profile <dir> Persistent Chromium profile directory
17
+ --seed <10000-99999>
18
+ Pin the fingerprint seed on first use
19
+ --browser <path> CloakBrowser Chromium binary path
20
+ --name <name> Register as a named instance; attach when already live.
21
+ A named browser listens on an unauthenticated 127.0.0.1
22
+ CDP port; without --name there is no port at all.
23
+ --url <url> Open a URL (default: about:blank)
24
+ --once Print state, close the browser, preserve the profile
25
+ --snapshot Include an interactive accessibility snapshot
26
+ --help Show this help
27
+
28
+ Environment:
29
+ CLOAK_PROFILE_DIR Default profile directory override
30
+ CLOAK_FINGERPRINT_SEED First-use seed override
31
+ CLOAKBROWSER_BIN CloakBrowser binary path override
32
+ `;
33
+
34
+ function parseArgs(argv) {
35
+ const options = { url: "about:blank", once: false, snapshot: false };
36
+ for (let index = 0; index < argv.length; index += 1) {
37
+ const arg = argv[index];
38
+ if (arg === "--help") return { help: true };
39
+ if (arg === "--once") {
40
+ options.once = true;
41
+ continue;
42
+ }
43
+ if (arg === "--snapshot") {
44
+ options.snapshot = true;
45
+ continue;
46
+ }
47
+ if (["--profile", "--seed", "--browser", "--name", "--url"].includes(arg)) {
48
+ const value = argv[++index];
49
+ if (!value) throw new Error(`${arg} requires a value`);
50
+ options[arg.slice(2)] = value;
51
+ continue;
52
+ }
53
+ throw new Error(`unknown option: ${arg}`);
54
+ }
55
+ return options;
56
+ }
57
+
58
+ const options = parseArgs(process.argv.slice(2));
59
+ if (options.help) {
60
+ console.log(HELP);
61
+ process.exit(0);
62
+ }
63
+
64
+ const profileDir = path.resolve(
65
+ options.profile ??
66
+ process.env.CLOAK_PROFILE_DIR ??
67
+ path.join(os.homedir(), ".local", "share", "omowright-cloak"),
68
+ );
69
+ const profile = await resolveCloakProfile({
70
+ profileDir,
71
+ fingerprintSeed: options.seed,
72
+ });
73
+ let browser;
74
+ let shuttingDown = false;
75
+ async function shutdown(code = 0) {
76
+ if (shuttingDown) return;
77
+ shuttingDown = true;
78
+ await browser?.close();
79
+ process.exit(code);
80
+ }
81
+
82
+ process.once("SIGINT", () => void shutdown(130));
83
+ process.once("SIGTERM", () => void shutdown(143));
84
+
85
+ try {
86
+ browser = await connectCloakProfile({
87
+ profileDir,
88
+ fingerprintSeed: profile.fingerprintSeed,
89
+ browserPath: options.browser,
90
+ name: options.name,
91
+ });
92
+ const page = await browser.newTab(options.url);
93
+ const result = {
94
+ ok: true,
95
+ url: await page.url(),
96
+ title: await page.title(),
97
+ profileDir,
98
+ fingerprintSeed: profile.fingerprintSeed,
99
+ metadataPath: profile.metadataPath,
100
+ };
101
+ if (options.snapshot) {
102
+ result.snapshot = compactSnapshot(
103
+ await page.snapshot({ interactive: true }),
104
+ );
105
+ }
106
+ console.log(JSON.stringify(result, null, 2));
107
+ if (!options.once) {
108
+ await new Promise(() => {});
109
+ }
110
+ } finally {
111
+ if (!shuttingDown) await browser?.close();
112
+ }