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,193 @@
1
+ ---
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 (57% smaller via compactSnapshot), ref-based clicks, coordinate control (CUA), viewport pinning, CAPTCHA solving (reCAPTCHA, Turnstile, hCaptcha, slider, OCR), 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, stealth via CloakBrowser as the default owned engine with zero exposed CDP ports, and an attached engine that drives the user's own signed-in browser through BrowserSkill (connectBrowserSkill, bskSnapshot, one-click onboarding via 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."
4
+ ---
5
+
6
+ # OmOWright
7
+
8
+ Browser automation as a code library. Install it with
9
+ `bun add github:code-yeongyu/omowright` (or import it by the path of a local
10
+ checkout). Bun >= 1.4 recommended, Node >= 22 supported.
11
+
12
+ Two engines, one library:
13
+
14
+ | Engine | Use when | Entry point |
15
+ |---|---|---|
16
+ | **Owned** (default) | scraping, WAF/bot-scored targets, headless, anything that must not touch the user's profile | `connectPipe` / `connectCloakProfile` — no CLI, no daemon, no open CDP port |
17
+ | **Attached** | the task needs the user's logged-in sessions, cookies, or open tabs | `connectBrowserSkill` — stock BrowserSkill daemon + extension; `references/browserskill.md` |
18
+
19
+ Never substitute one for the other silently: if the attached engine is not set
20
+ up, run `bskOnboard()` and tell the user its single remaining step. It installs
21
+ the extension only into the browser the user actually uses; when it returns
22
+ `needsChoice`, ask which browser that is and pass `{ browser: "<id>" }`.
23
+
24
+ ## Core loop (owned engine)
25
+
26
+ ```js
27
+ const { connectPipe, compactSnapshot } = await import("omowright");
28
+ const browser = await connectPipe({
29
+ browserPath: "<CloakBrowser binary>", // DEFAULT engine
30
+ browserArgs: ["--no-first-run", `--user-data-dir=${profileDir}`],
31
+ storageRoot: profileDir,
32
+ });
33
+ const page = await browser.newTab("https://example.com");
34
+ const tree = compactSnapshot(await page.snapshot()); // ALWAYS compact before reading
35
+ await page.locator("e1").click(); // refs come from the snapshot
36
+ const changes = compactSnapshot(await page.snapshot({ diff: true }));
37
+ await browser.close(); // then rm -rf the profile dir
38
+ ```
39
+
40
+ Snapshot once, act on refs, then re-snapshot with `{ diff: true }` after each batch
41
+ of actions. Unchanged elements keep their refs. Deltas have
42
+ `{ full: false, diff: { added, changed, removed, focused } }`: added/changed entries
43
+ contain `{ ref, tree }`, removed contains refs, and focused is a ref or `null`.
44
+ Changed lines omit unchanged labels/placeholders; they show current state and value.
45
+ `compactSnapshot` marks additions with `+`, changes with `~`, and removals as ref
46
+ ranges. A full result has `full: true` and a `reason` (no baseline, navigation,
47
+ changed snapshot options, unreferenced text changes, or a delta larger than the
48
+ tree). Read it as the new baseline. Baselines belong to each page; `diff: false`
49
+ returns the ordinary full snapshot and replaces its baseline.
50
+
51
+ ## Default engine: CloakBrowser
52
+
53
+ Use the CloakBrowser binary by default, not a plain headless shell — most real
54
+ targets sit behind WAFs or bot scoring, and CloakBrowser's source-level
55
+ fingerprint patches (Cloudflare Turnstile, FingerprintJS, BrowserScan) make it
56
+ the safe default. Plain headless shell is the speed fallback for trivially open
57
+ pages: any Chrome/Chromium or
58
+ `~/Library/Caches/ms-playwright/chromium_headless_shell-*/.../chrome-headless-shell`.
59
+
60
+ ```bash
61
+ python3 -c "import cloakbrowser; print(cloakbrowser.binary_info()['binary_path'])"
62
+ # -> ~/.cloakbrowser/chromium-<ver>/Chromium.app/Contents/MacOS/Chromium
63
+ ```
64
+
65
+ 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.
66
+
67
+ **CLOAKBROWSER ALLOWS ONE INSTANCE.** Probe before launching
68
+ (`curl -s -m 2 http://127.0.0.1:9242/json/version`). If one answers, `connectPipe`
69
+ HANGS during early init — attach with `connect()` instead. Full pattern:
70
+ `references/stealth.md`.
71
+
72
+ ## Getting past obstacles
73
+
74
+ A blocked page is a rung to climb, not a reason to stop and report.
75
+
76
+ | Rung | Use | Advance when |
77
+ |---|---|---|
78
+ | 1. `snapshot()` + `locator(ref)` | Anything with a usable ref | Ref absent, stale, obscured, or the click hits the wrong node twice |
79
+ | 1b. `snapshotWithLayers` / `describeLayers` | A blocking overlay explains two identical misses; dismiss it first | `@layers none`, or the overlay is gone and the click still misses |
80
+ | 2. `createCua(page)` coordinates | Canvas, extension popups, custom controls | Click misses, or screenshot and coordinates disagree |
81
+ | 3. Pin the viewport, retry rung 2 | Coordinate drift after a resize, DPI scale, or foreign tab | Coordinates land right but the widget still refuses input |
82
+ | 4. `createCaptcha(page)` | A challenge widget is the blocker | Widget solved, flow still stalls |
83
+ | 5. Read the browser log | Browser-level failure | The log names a cause outside the page |
84
+
85
+ **TWO IDENTICAL FAILURES SELECT THE NEXT RUNG — A THIRD IDENTICAL ATTEMPT IS A
86
+ DEFECT.** Verify after every action batch: `snapshot({ diff: true })` for DOM state,
87
+ fresh screenshot for visual state. Report a stop only when all rungs are
88
+ exhausted, naming which rung failed with what evidence.
89
+
90
+ **RUNG 5 ENDS IN A WRITTEN DIAGNOSIS, NEVER A SPECULATIVE CODE CHANGE.** A browser
91
+ process problem (missing entitlement, extension service-worker failure, FIDO
92
+ unavailable) is not fixed by editing automation code; editing it only burns a
93
+ debugging cycle.
94
+
95
+ ### Pin the viewport before trusting coordinates
96
+
97
+ CUA acts in viewport pixels. When the render surface and coordinate space
98
+ disagree, every coordinate is off by a constant and retrying repeats the miss:
99
+
100
+ ```js
101
+ await page._sendToTarget("Emulation.setDeviceMetricsOverride", {
102
+ width: 1440, height: 900, deviceScaleFactor: 1, mobile: false,
103
+ screenWidth: 1440, screenHeight: 900,
104
+ viewport: { x: 0, y: 0, width: 1440, height: 900, scale: 1 },
105
+ });
106
+ await page.refreshViewportSize(); // -> { width: 1440, height: 900 }
107
+ ```
108
+
109
+ Pin every page you act on, including tabs you did not open, then take a fresh
110
+ screenshot — coordinates read off an unpinned screenshot are stale.
111
+
112
+ ## Route by task
113
+
114
+ | Task | Read |
115
+ |---|---|
116
+ | The user's own signed-in browser and tabs, BrowserSkill sessions, trace-free `bskSnapshot`, one-click extension onboarding | `references/browserskill.md` |
117
+ | Visual browsing, coordinate UI, viewport pinning, extension popups | `presets/visual-browse/SKILL.md` — consider delegating, below |
118
+ | CAPTCHA (checkbox, slider, text OCR, image grid) | `presets/captcha/SKILL.md` — consider delegating, below |
119
+ | WAF/Cloudflare/bot-detection pages, CloakBrowser, cookie rules | `references/stealth.md` |
120
+ | First use, page API, snapshot options, locator rules | `references/quickstart.md`; dialogs and readiness in `TOOLS.md` |
121
+ | Driving a browser inside `eval` cells, kernel persistence, parallel lanes | `references/eval-kernel.md` |
122
+ | Tabs/windows/bookmarks/history/downloads/topSites (Chrome MV3) | `presets/chrome/SKILL.md` |
123
+ | API JSON instead of DOM scraping, wait for a request, infinite scroll, QA flight trace (jsonl/HAR), request routes | `presets/network/SKILL.md` |
124
+ | Cross-origin iframes and shadow DOM, overlays that swallow clicks, login/OTP handoff to a human, device emulation | `references/frames-layers-human.md` |
125
+ | Reading an item from the 1Password web vault (tab-scoped session, sign-in check, secret handling) | `references/1password.md` |
126
+
127
+ Preset and `TOOLS.md` paths are relative to the package root.
128
+
129
+ ## Hard rules
130
+
131
+ - **NEVER extract and inject cookies for Google (any property) or 1Password.**
132
+ Google's risk engine kills the session server-side and logs the user out of
133
+ their own browser; 1Password sessions are device-bound and never work from
134
+ cookies. Detail in `references/stealth.md`. Cookie reuse is fine for ordinary
135
+ sessions (Grafana, internal tools).
136
+ - **Always `compactSnapshot()`** before sending a snapshot to a model — the refs
137
+ map is ~54% of bytes and resolves in-page, so dropping it is free.
138
+ - **Refs die on every new snapshot.** Pass `page.locator("e1")` straight from the
139
+ latest snapshot; never reuse a ref across snapshots, never put one in CSS.
140
+ - **Refs stay page-level.** Child-frame refs look like `f1e3` and still go to
141
+ `page.locator("f1e3")`; never fetch a frame handle to click inside an iframe.
142
+ - Dialogs never block: `alert/confirm/prompt/beforeunload` are answered by the
143
+ dialog policy (default accept: `confirm() -> true`, `prompt() -> ""`). Change
144
+ it with `connectPipe({ dialogPolicy })`, `connect(url, { dialogPolicy })` or `browser.setDialogPolicy()`;
145
+ observe with `page.on('dialog')`, or answer inline with
146
+ `page.on('dialog', d => d.accept(text))` (a listener's answer replaces the
147
+ policy). Details in `TOOLS.md`.
148
+ - `goto` waits for meaningful content, not `readyState`: body plus (interactive
149
+ elements OR landmarks OR >= 20 text chars). Near-empty pages time out — use
150
+ `page.goto(url, { waitUntil: "commit" })` for those.
151
+ - Cleanup is paired: `await browser.close()` then `rm -rf` the profile dir in the
152
+ same `finally`.
153
+
154
+ ## Delegating the pixel loop
155
+
156
+ CAPTCHA solving and pixel-level visual browsing are iterative (screenshot, reason,
157
+ act, verify). When that loop would consume your own context, delegate the blocked
158
+ page to a `deep` subagent that loads these references. Drive it yourself when the
159
+ flow is short or the state is already in your hands.
160
+
161
+ When every rung fails on a login, a one-time code, or a challenge the captcha
162
+ preset can't clear, the human is the fallback: `requestHuman(page, { prompt,
163
+ until })` brings the tab to front, shows a Done banner, and resumes when the
164
+ condition holds. Recipe in `references/frames-layers-human.md`.
165
+
166
+ ```
167
+ task(category: "deep", run_in_background: true, prompt: `
168
+ TASK: Get past the CAPTCHA blocking <url> and return the post-solve state.
169
+ 1. Read `presets/captcha/SKILL.md`, `presets/visual-browse/SKILL.md` (package
170
+ root), and `references/stealth.md` (this skill).
171
+ 2. connectPipe with the CloakBrowser binary (default engine).
172
+ 3. Pin the viewport (setDeviceMetricsOverride 1440x900 + refreshViewportSize)
173
+ before computing any coordinate.
174
+ 4. createCaptcha(page) - click(bounds) for checkbox widgets, drag(from, to,
175
+ {steps}) for sliders, readText(bounds) for text (macOS Vision OCR default).
176
+ Image grids: page.annotatedScreenshot() + cua.click per cell.
177
+ 5. VERIFY with captcha.waitFor({ until }) on an application acceptance condition;
178
+ only outcome "matched" counts, a snapshot is not proof. Two failures of one
179
+ strategy select the next strategy; do not repeat a third time.
180
+ STOP WHEN the page is past the challenge, or all strategies are exhausted -
181
+ then report which failed and the browser-log evidence.
182
+ DELIVERABLE: post-solve snapshot tree + screenshot path.`)
183
+ ```
184
+
185
+ ## Choosing this over everything else
186
+
187
+ Plain `webfetch`/`curl` is fine for one static page. The moment a page needs JS,
188
+ interaction, login, screenshots, CAPTCHAs, or WAF bypass, use this skill rather
189
+ than ultimate-browsing: one library covers tiers 1-2 with a persistent browser,
190
+ smaller snapshots, and no agent-browser/CloakBrowser CLI plumbing. For
191
+ ulw-research browsing lanes, spawn `deep` lanes that `import()` this package in
192
+ eval cells — the browser persists across cells via `globalThis`, and
193
+ `compactSnapshot` keeps dozens of pages inside the context budget.
@@ -0,0 +1,118 @@
1
+ # 1Password web vault
2
+
3
+ Reading an item from the 1Password web app through OmOWright. Everything here
4
+ follows from one fact: the web vault is a zero-knowledge client.
5
+
6
+ ## The session lives in one tab
7
+
8
+ The unlocked vault key sits in **that tab's `sessionStorage`** (`mpa_session`),
9
+ not in a cookie. The `_tsession` cookie alone authenticates nothing. So:
10
+
11
+ - A new tab pointed at `/app` redirects to `/signin`, even with a signed-in tab
12
+ open beside it. That is 1Password working correctly, not a bug to route around.
13
+ - **Reuse the signed-in tab.** Closing it, or navigating it away from the vault,
14
+ loses access until someone signs in again.
15
+ - **Never extract or inject 1Password cookies.** Sessions are device-bound; a
16
+ cookie copied into another profile never produces a vault.
17
+
18
+ ## Signing in to the vault is a human step
19
+
20
+ Sign in interactively, inside a persistent profile (`connectCloakProfile()`, see
21
+ `stealth.md`), and hand the master password, Secret Key, and second factor to
22
+ a person with `requestHuman()` (`frames-layers-human.md`). Do not script
23
+ credential entry and do not retry a failed sign-in in a loop. When the tab sits
24
+ on `/signin` and no saved login is offered (next section), stop and say so.
25
+
26
+ ## Signing in with the extension's inline menu
27
+
28
+ When the 1Password browser extension is installed and unlocked, let **it** fill
29
+ the login. Its inline menu puts the secret into the field without the value ever
30
+ passing through your code, tool arguments, or logs. This covers both a 1Password
31
+ account sign-in page and any other site that needs a saved login or one-time code.
32
+
33
+ 1. Take a fresh snapshot first. If the destination already shows its signed-in
34
+ home and the expected account, no sign-in is needed.
35
+ 2. Click the username, password, or one-time-code field and snapshot again to see
36
+ the extension's inline menu. Pick the entry whose **host and account both
37
+ match**. Several accounts can be offered on the same host, so never pick by
38
+ position.
39
+ 3. **If the menu does not appear**, click the field again, then press
40
+ `ArrowDown` while it has focus, then snapshot. A field focused before a
41
+ sign-in finished often needs a fresh click. One missing menu does not prove the
42
+ extension is locked; only an explicit locked state does, and that is a human
43
+ step.
44
+ 4. A sign-in-only tab may **close itself** after authenticating. That is the
45
+ expected handoff. Reattach the original tab, take a fresh snapshot, and repeat
46
+ step 2 on the field that was waiting (for example a one-time-code field behind
47
+ single sign-on).
48
+ 5. Selecting an entry can fill **and** submit. Submit at most once; while the page
49
+ shows a signing-in state, wait and snapshot instead of resubmitting.
50
+ 6. Done means the destination shows its signed-in page and the right identity. A
51
+ filled field or a spinner is not done. Then carry on with the task that needed
52
+ the login; do not stop at "signed in".
53
+
54
+ If the inline menu keeps failing on a page that needs it, use the vault's own
55
+ copy control instead: open the item in the signed-in vault tab, click its copy
56
+ button, confirm the copied toast, then paste into the verified field with a real
57
+ key press (`ControlOrMeta+v` through the computer-use keyboard; a synthetic
58
+ `keyboard.press` can leave the field empty). Check only that the field is
59
+ non-empty. Never read the clipboard to test it, and never type or print the value.
60
+
61
+ Never print, screenshot, or store an item pane, a one-time code, or a sign-in
62
+ callback URL (anything carrying `code=` or `state=` parameters), and never
63
+ navigate to a callback URL saved in an item: it is stale and single-use.
64
+
65
+ Do not restart the browser to "fix" a signed-out tab: with a temporary profile,
66
+ a restart discards the login instead of refreshing it.
67
+
68
+ ## Checking you are signed in
69
+
70
+ Check `location.href`: a live session contains `/app#/` and never `/signin`.
71
+ Do **not** trust `document.title`. The single-page app changes its URL hash
72
+ without updating the title, so the title can read "sign in" while the vault is
73
+ open.
74
+
75
+ ```js
76
+ const url = await page.evaluate(() => location.href);
77
+ if (!url.includes("/app#/")) throw new Error("1password: not signed in");
78
+ ```
79
+
80
+ ## Searching and reading an item
81
+
82
+ Two lists coexist on the page, and mixing them up gives wrong answers:
83
+
84
+ - the search box's autocomplete `listbox` holds **your** query's results;
85
+ - the item-list region holds whatever query was last committed, possibly by
86
+ someone else sharing the browser.
87
+
88
+ Read only the autocomplete listbox, and drop its trailing "show all matches" row,
89
+ which is a navigation control, not an item. The listbox re-renders as you type,
90
+ so wait until two consecutive snapshots give the same title list.
91
+
92
+ Clear the search box before typing, since it may hold a previous query. Prefer
93
+ click and type over `locator.fill()` on a tab another automation also drives:
94
+ `fill()` installs an init script that can time out on a busy tab.
95
+
96
+ ```js
97
+ const { compactSnapshot } = await import("omowright");
98
+ await page.locator(searchRef).click();
99
+ await page.keyboard.press("Meta+a");
100
+ await page.keyboard.press("Backspace");
101
+ await page.keyboard.type(query);
102
+ const tree = compactSnapshot(await page.snapshot({ interactive: true }));
103
+ ```
104
+
105
+ Refs are reissued on every snapshot. Re-snapshot after each action, then click
106
+ the item and snapshot its detail region. Match on roles, not labels: the same
107
+ account can render in different UI languages.
108
+
109
+ ## Handling secrets
110
+
111
+ - Report metadata freely: item title, vault, username, URL, which fields exist.
112
+ - Concealed values render as `••••••`. Reveal a value only when the user asked
113
+ for that exact field, and return it to the caller. Never log it.
114
+ - Never write secrets into screenshots, trace files, HAR output, or logs.
115
+ Prefer a text snapshot to a screenshot, which can capture neighbouring entries.
116
+ - Report only the requested item's field, never other entries that happened to
117
+ appear in the same list.
118
+ - When done, clear the search and leave the tab on All Items.
@@ -0,0 +1,186 @@
1
+ # Attached engine: the user's own browser through BrowserSkill
2
+
3
+ OmOWright has two engines. The **owned** engine (`connectPipe`,
4
+ `connectCloakProfile`) launches a browser you control. The **attached** engine
5
+ drives the browser the user is already signed into, through Tencent
6
+ BrowserSkill (stock `bsk` daemon + Web Store extension, no fork). Pick the
7
+ attached engine when the task needs the user's sessions, cookies, or their
8
+ open tabs; pick the owned engine for scraping, WAF targets, headless runs, and
9
+ anything that should not touch the user's profile.
10
+
11
+ ## Core loop
12
+
13
+ ```js
14
+ const { connectBrowserSkill, bskSnapshot } = await import("omowright");
15
+
16
+ const session = await connectBrowserSkill({ name: "book a table", focused: false });
17
+ await session.navigate("https://example.com/");
18
+ const sync = () => session.cooperate("sync").then((r) => r.context_id);
19
+ const { tree, refs, css } = await bskSnapshot(session, { interactive: true, context: await sync() });
20
+ // tree and refs look exactly like page.snapshot(); css[ref] is a light-DOM
21
+ // selector for the same element (null inside shadow roots)
22
+ await session.click({ selector: css.e3 }, { context: await sync() }); // or "@e3" after session.observe()
23
+ await session.fill(css.e5, "hello", { clearBefore: true, context: await sync() });
24
+ await session.press("Enter", { context: await sync() });
25
+ await session.waitForNavigation({ waitUntil: "load" });
26
+ await session.stop(); // ALWAYS: returns borrowed tabs, closes the Agent Window
27
+ ```
28
+
29
+ ### Shared control (BrowserSkill 0.4+)
30
+
31
+ The person at the keyboard can work in the task tab while the agent does. The
32
+ extension therefore refuses every page action with `permission_denied` /
33
+ `data.reason: "cooperation_sync_required"` unless it carries the
34
+ `context_id` of the latest `session.cooperate("sync")`. A context is good
35
+ for one action: sync, decide from what the sync reported, act with
36
+ `{ context }`, then sync again. Gated: navigation (except the first
37
+ navigation of the untouched blank tab), every input method, `evaluate` (and
38
+ so `bskSnapshot`), `tabClose`, `resize`, `emulate`, `observe` with
39
+ `probeHover`, and `screenshot({ fullPage: true })`. Reads (`observe`,
40
+ `snapshot`, `getHtml`, `screenshot()`, `console`, `network`,
41
+ `waitForNavigation`) need no context. `dependsOn: ["@e2", ...]` narrows the
42
+ check to the observed regions the decision used.
43
+
44
+ On `cooperation_sync_required`, call `session.cooperate("wait", { timeoutMs })`
45
+ (at most 25 s) until it reports `ready`, sync again and replan from the live
46
+ page; never replay the refused action blindly. `user_aborted` means the
47
+ person stopped the task.
48
+
49
+ `connectBrowserSkill` talks to the daemon over its Unix-socket IPC directly —
50
+ no `bsk` process per call. It starts the daemon if needed (`bsk status`),
51
+ unless `BSK_AUTO_START=0`. On Windows, a host that forbids Job Object
52
+ breakaway makes `bsk status` refuse to detach; the library then registers a
53
+ per-user `bsk-daemon-<hash>` scheduled task that runs `bsk daemon start
54
+ --foreground` under `conhost.exe --headless`, so no console window opens.
55
+ It never falls back to a headless browser: when no
56
+ extension is connected it throws `no_browser_connected` and `bskDoctor()`
57
+ tells you the one step that is missing.
58
+
59
+ ## What the session can do
60
+
61
+ Every method maps 1:1 onto a daemon `tool.*` method; parameters are the
62
+ daemon's own names in camelCase (`waitUntil`, `clearBefore`, `maxTokens`).
63
+ Targets are a ref (`"e3"` / `"@e3"` from `session.observe()` or
64
+ `session.snapshot()`), a CSS selector, or `{ captureId, x, y }` from a
65
+ screenshot.
66
+
67
+ | Need | Call |
68
+ | --- | --- |
69
+ | Navigate / history | `navigate(url, {waitUntil, timeoutMs})`, `back()`, `forward()`, `reload({hard})`, `waitForNavigation()` |
70
+ | Read the page | `observe({maxTokens, cursor, probeHover})` (VOM text with `@eN` refs), `snapshot()`, `getHtml({ref, maxBytes})`, `bskSnapshot(session)` (OmOWright tree + css) |
71
+ | Act | `click(target, {button, clickCount, modifiers})`, `hover`, `fill(target, value)`, `press(key, {target, holdMs})`, `select(target, values)`, `focus`, `blur`, `scrollTo`, `wheel({deltaY})` |
72
+ | Script | `evaluate(expression, {awaitPromise, timeoutMs})` → `{ok, value, error}`; Agent Window tabs only |
73
+ | Pixels | `screenshot({ref})` → `{buffer, width, height, captureId}`; `screenshot({fullPage: true})` streams the capture back in chunks |
74
+ | Tabs | `tabList({scope: "user"})`, `tabCreate({url})`, `tabSelect(id)`, `tabClose(id)`, `tabBorrow(id)` (the user confirms), `tabReturn(id)` |
75
+ | Humans | `requestHelp({prompt, targets, completionCriteria, timeoutMs})` for login, CAPTCHA, OTP, payment — the extension shows an overlay and waits |
76
+ | Diagnostics | `console({since})`, `network({since})` (metadata only), `emulate({overrides})`, `resize(w, h)` |
77
+
78
+ Anything the daemon refuses comes back as a `BskRpcError` with the daemon's
79
+ `code` (`not_found`, `invalid_params`, `permission_denied`, `timeout`,
80
+ `cdp_failed`, `user_aborted`, `no_browser_connected`, ...). Long calls can be
81
+ cancelled: `const h = session.client.callWithHandle(...)`, then
82
+ `session.client.cancel(h.rpcId)`.
83
+
84
+ ## bskSnapshot leaves no trace
85
+
86
+ `bskSnapshot` evaluates the same page bundle `page.snapshot()` uses, wrapped so
87
+ `globalThis` is a local object: the page never sees `__omowright`, no
88
+ attribute is written, and a MutationObserver on the page counts zero records.
89
+ Refs are mapped to CSS paths (`#id` when unique, otherwise
90
+ `tag:nth-of-type(n)` chains) so a click goes through the daemon's `selector`
91
+ target. Elements inside shadow roots get `css: null` — use `session.observe()`
92
+ and its `@eN` ref for those.
93
+
94
+ The daemon itself enables `Runtime.enable` on every tab it drives (console
95
+ capture). That is BrowserSkill's stock behaviour and is a known CDP signal to
96
+ bot detection; for WAF-heavy targets use the owned engine with CloakBrowser
97
+ (`skills/omowright/references/stealth.md`).
98
+
99
+ ## Onboarding: everything except one click
100
+
101
+ ```js
102
+ const { bskDoctor, bskOnboard } = await import("omowright");
103
+ const report = await bskDoctor(); // {cli, daemon, browsers, primary, identification, browsersConnected, ready, nextStep}
104
+ if (!report.ready) {
105
+ const result = await bskOnboard({ browser: knownBrowserOrUndefined, onHumanStep: (s) => console.log(s.step) });
106
+ // result.needsChoice === true: nothing was registered; ask the user which
107
+ // browser they use (result.identification.candidates), then call again with
108
+ // { browser: "<id>" }.
109
+ // result.daemon.running === false: humanStep is null and nothing was
110
+ // registered; result.nextStep says how to start the daemon. Start it and
111
+ // call again before telling the user anything.
112
+ // otherwise result.humanStep is the single thing to tell the user, e.g.
113
+ // 'Quit Aside completely and open it again; a dialog offers to enable "BrowserSkill" — click Enable.'
114
+ }
115
+ ```
116
+
117
+ `daemon.startBlocked: true` means the host refused a detached daemon start
118
+ (Windows Job Object breakaway). Only a client that starts the daemon can see
119
+ that, so `bskOnboard()` reports it; `bskDoctor()`'s default client has
120
+ auto-start off and does not.
121
+
122
+ ### Which browser gets the extension
123
+
124
+ Exactly one: the browser the user actually uses. A profile directory on disk
125
+ proves nothing — Chrome leaves one behind after a single launch — so
126
+ `identifyBrowser` ranks the installed Chromium-family browsers (Chrome, Edge,
127
+ Brave, Chromium, Arc, Dia, Vivaldi, Opera, Comet, Aside, Naver Whale) by
128
+ usage signals from `probeBrowserSignals`:
129
+
130
+ | Signal | macOS | Linux | Windows |
131
+ | --- | --- | --- | --- |
132
+ | Default browser | LaunchServices `https` handler | `xdg-settings get default-web-browser` | `UserChoice` ProgId |
133
+ | Running now | the app bundle in `/Applications` or `~/Applications` (automation builds elsewhere do not count) | process name | `tasklist` image |
134
+ | Recent use | `Local State` / `Default/History` mtime within 7 days | same | same |
135
+
136
+ The decision, in order, with the `confidence` each step reports: an explicit
137
+ `browser` option or `OMOWRIGHT_BROWSER` (`explicit`); the one browser whose
138
+ extension is already connected to the daemon (`connected`); the default
139
+ browser when it is also in use (`default-and-in-use`), or when nothing else is
140
+ (`default`); the only browser in use (`only-in-use`), the only one running
141
+ (`only-running`) or the only one installed (`only-installed`) when no default
142
+ can be read. The extension names its browser from the user agent, and forks
143
+ such as Brave and Arc report `chrome`, so a `chrome` or `chromium` name counts
144
+ as connected only when exactly one browser able to send it is running.
145
+ Everything else — the default is Safari or Firefox, the default is idle while
146
+ another browser runs, several browsers are in use, or nothing shows use —
147
+ returns `needsChoice: true` with
148
+ every candidate and its signals, and registers nothing. Ask the user; if the
149
+ agent keeps a memory, look there first and record the answer.
150
+
151
+ `bskDoctor()` reports the same `identification` plus `registeredElsewhere`:
152
+ browsers that still carry an entry from an older onboarding. It never removes
153
+ them — deleting an external-extension entry uninstalls an extension the user
154
+ may have enabled; `unregisterExternalExtension({ browser })` does it on request.
155
+
156
+ `bskOnboard` runs, in order: the official `install.sh` / `install.ps1` into
157
+ `~/.local/bin` (any PATH lines the installer appends to shell rc files are
158
+ reverted — the library calls the binary by absolute path); `bsk status` to
159
+ start the daemon; then, for the identified browser only, Chrome's
160
+ external-extension registration for the Web Store listing:
161
+
162
+ | Platform | Where the entry goes | What the user does |
163
+ | --- | --- | --- |
164
+ | macOS | `<user data dir>/External Extensions/<id>.json` | relaunch the browser, click **Enable** once |
165
+ | Windows | `HKCU\Software\<vendor>\<browser>\Extensions\<id>` (`reg add`, no admin) | click **Enable** on the toolbar badge; no restart |
166
+ | Linux (Chromium) | `<user data dir>/External Extensions/<id>.json` | relaunch; installs silently |
167
+ | Linux (Chrome/Edge/Brave) | `/opt/google/chrome/extensions/<id>.json` etc. — needs root | otherwise: open the store link and click Add |
168
+ | Opera, and Vivaldi/Whale off macOS | no external-extension path | open the store link in that browser and click Add |
169
+
170
+ Then it waits on `system.status{wait_for_browser_ms}` until the extension
171
+ connects. Tell the user exactly `result.humanStep`, nothing more. If the user
172
+ uninstalled the extension from the browser UI earlier, Chrome blocklists the
173
+ id for external installs; `registerExternalExtension` detects that
174
+ (`reason: "blocklisted"`) and returns the store link instead.
175
+
176
+ Do not use enterprise policies (`ExtensionInstallForcelist`) from this
177
+ library: they brand the browser "managed by your organization" and the user
178
+ cannot remove the extension.
179
+
180
+ ## Remote browsers
181
+
182
+ The daemon that owns the user's browser must be reachable over its Unix
183
+ socket. On another machine, run the library where the daemon is (for example
184
+ through a machine mesh), or pair the extension to a daemon in server mode
185
+ (`bsk daemon start --mode server`, WSS required off loopback). Windows named
186
+ pipes are not discovered automatically; pass `sockPath` explicitly.
@@ -0,0 +1,100 @@
1
+ # Eval-kernel integration
2
+
3
+ The `eval` tool's JS kernel keeps top-level `globalThis` state across cells,
4
+ which makes it the cheapest way to drive OmOWright interactively and in
5
+ parallel. It does not keep child processes alive for you.
6
+
7
+ **ONLY `globalThis.*` SURVIVES ACROSS CELLS.** Top-level `const`/`let` bindings do
8
+ not; re-import or read from `globalThis` in later cells.
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:
15
+
16
+ 1. **One cell, whole job.** Connect, act, close in the same cell. Right for any
17
+ job that fits in one cell's runtime; the parallel lanes below are this shape.
18
+ 2. **A browser that must span cells.** Launch it outside the kernel's process
19
+ tree through the eval tool's background monitor, on a loopback debugging
20
+ port, and attach with `connect()` (`shell`, `profile`, `omwTools` come from
21
+ the setup cell below):
22
+
23
+ ```js
24
+ await tool.monitor({ description: "omowright browser", command: `${shell} --headless --no-first-run --remote-debugging-port=9333 --user-data-dir=${profile} about:blank` });
25
+ globalThis.omw = await omwTools.connect("http://127.0.0.1:9333"); // the port is loopback-only; close the monitor with kill_bash when done
26
+ ```
27
+
28
+ If you'd rather keep `connectPipe`, treat the browser as disposable: start
29
+ every cell with a probe and relaunch on failure.
30
+
31
+ ```js
32
+ try { await globalThis.omw.listTargets(); }
33
+ catch {
34
+ globalThis.omw = await omwTools.connectPipe({ browserPath: shell, browserArgs: ["--headless", "--no-first-run", `--user-data-dir=${profile}`], storageRoot: profile });
35
+ globalThis.omwPage = await omw.newTab("about:blank");
36
+ }
37
+ ```
38
+
39
+ ## Setup cell (once per session)
40
+
41
+ The pipe-launched form. It works for short sessions, but per the rule above the
42
+ process may not outlive this cell; probe it at the top of every later cell (or
43
+ switch to the monitor + `connect()` form).
44
+
45
+ ```js
46
+ const m = await import("omowright");
47
+ const fs = await import("node:fs");
48
+ const os = await import("node:os");
49
+ const path = await import("node:path");
50
+ const shell = fs.globSync(`${env("HOME")}/Library/Caches/ms-playwright/chromium_headless_shell-*/chrome-headless-shell-mac-arm64/chrome-headless-shell`).sort().at(-1);
51
+ const profile = fs.mkdtempSync(path.join(os.tmpdir(), "omowright-eval-"));
52
+ globalThis.omw = await m.connectPipe({
53
+ browserPath: shell,
54
+ browserArgs: ["--headless", "--no-first-run", `--user-data-dir=${profile}`],
55
+ storageRoot: profile,
56
+ });
57
+ globalThis.omwPage = await omw.newTab("about:blank");
58
+ globalThis.omwTools = m;
59
+ ```
60
+
61
+ ## Later cells
62
+
63
+ ```js
64
+ await omw.listTargets(); // throws if the kernel reaped the browser: rerun setup
65
+ await omwPage.goto("https://example.com");
66
+ console.log(omwTools.compactSnapshot(await omwPage.snapshot()));
67
+ await omwPage.locator("e1").click();
68
+ display(await omwPage.screenshot({ type: "png" })); // display() renders images inline
69
+ ```
70
+
71
+ ## Parallel lanes (research fan-out)
72
+
73
+ Each lane gets its own browser and profile: no shared state, and the pipe
74
+ transport has no ports to collide on. Every lane connects, acts, and closes
75
+ inside the cell, so the reaping rule never bites.
76
+
77
+ ```js
78
+ const results = await parallel([1, 2, 3].map(i => async () => {
79
+ const prof = fs.mkdtempSync(path.join(os.tmpdir(), `omw-lane${i}-`));
80
+ const br = await omwTools.connectPipe({ browserPath: shell, browserArgs: ["--headless", `--user-data-dir=${prof}`], storageRoot: prof });
81
+ try {
82
+ const p = await br.newTab(urls[i]);
83
+ return omwTools.compactSnapshot(await p.snapshot());
84
+ } finally {
85
+ await br.close();
86
+ fs.rmSync(prof, { recursive: true, force: true });
87
+ }
88
+ }));
89
+ ```
90
+
91
+ ## Cleanup cell
92
+
93
+ ```js
94
+ await omw.close().catch(() => {}); // no-op if the process is already gone
95
+ fs.rmSync(profile, { recursive: true, force: true });
96
+ delete globalThis.omw; delete globalThis.omwPage; delete globalThis.omwTools;
97
+ ```
98
+
99
+ For the monitor-launched form, stop the monitor after `close()` so the profile
100
+ directory isn't in use when you delete it.