omowright 0.1.0 → 0.3.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 (165) hide show
  1. package/README.md +33 -23
  2. package/TOOLS.md +140 -19
  3. package/dist/agent-tabs.d.ts +56 -0
  4. package/dist/aria-hidden.d.ts +1 -0
  5. package/dist/aside/cli-binary.d.ts +7 -0
  6. package/dist/aside/cli-contract.d.ts +9 -0
  7. package/dist/aside/errors.d.ts +8 -0
  8. package/dist/aside/line-transport.d.ts +11 -0
  9. package/dist/aside/mcp-transport.d.ts +11 -0
  10. package/dist/aside/onboard.d.ts +76 -0
  11. package/dist/aside/session-types.d.ts +68 -0
  12. package/dist/aside/session.d.ts +20 -0
  13. package/{bin/omowright-cloak.mjs → dist/bin/omowright-cloak.js} +28 -31
  14. package/dist/bridge-schemas.d.ts +326 -0
  15. package/dist/bridge-transport.d.ts +144 -0
  16. package/dist/browser-context.d.ts +4024 -0
  17. package/dist/browser-process.d.ts +10 -0
  18. package/dist/bsk/browser-signals.d.ts +23 -0
  19. package/dist/bsk/browsers.d.ts +46 -0
  20. package/dist/bsk/connect.d.ts +23 -0
  21. package/dist/bsk/daemon-info.d.ts +16 -0
  22. package/dist/bsk/external-extension.d.ts +74 -0
  23. package/dist/bsk/identify-browser.d.ts +48 -0
  24. package/dist/bsk/install-cli.d.ts +37 -0
  25. package/dist/bsk/ipc-client.d.ts +45 -0
  26. package/dist/bsk/onboard.d.ts +96 -0
  27. package/dist/bsk/reply-fields.d.ts +3 -0
  28. package/dist/bsk/screenshot.d.ts +24 -0
  29. package/dist/bsk/session.d.ts +142 -0
  30. package/dist/bsk/snapshot.d.ts +16 -0
  31. package/dist/bsk/targets.d.ts +20 -0
  32. package/dist/captcha-wait.d.ts +17 -0
  33. package/dist/captcha.d.ts +46 -0
  34. package/dist/cdp-errors.d.ts +38 -0
  35. package/dist/cdp-methods.d.ts +10 -0
  36. package/dist/cdp-protocol.d.ts +459 -0
  37. package/dist/chrome-profile.d.ts +77 -0
  38. package/dist/chrome.d.ts +130 -0
  39. package/dist/cloak-profile.d.ts +43 -0
  40. package/dist/connection.d.ts +4024 -0
  41. package/dist/console-events.d.ts +22 -0
  42. package/dist/cookies.d.ts +42 -0
  43. package/dist/core.d.ts +10810 -0
  44. package/dist/cua.d.ts +56 -0
  45. package/dist/dialog-policy.d.ts +43 -0
  46. package/dist/ego/bindings.d.ts +68 -0
  47. package/dist/ego/cdp-client.d.ts +28 -0
  48. package/dist/ego/client.d.ts +8 -0
  49. package/dist/ego/errors.d.ts +7 -0
  50. package/dist/emulate.d.ts +62 -0
  51. package/dist/engines.d.ts +59 -0
  52. package/dist/events.d.ts +93 -0
  53. package/dist/frames-snapshot.d.ts +58 -0
  54. package/dist/har.d.ts +88 -0
  55. package/dist/human-handoff.d.ts +30 -0
  56. package/{src/index.js → dist/index.d.ts} +12 -53
  57. package/dist/index.js +39262 -0
  58. package/dist/injected.d.ts +1 -0
  59. package/dist/instance-lock.d.ts +5 -0
  60. package/dist/instances.d.ts +45 -0
  61. package/dist/internal-capability.d.ts +1 -0
  62. package/dist/launch-endpoint.d.ts +34 -0
  63. package/dist/layers.d.ts +31 -0
  64. package/dist/llm.d.ts +1349 -0
  65. package/dist/lock-backend-win32-xbcm60vz.js +57 -0
  66. package/dist/lock-backend-win32.d.ts +3 -0
  67. package/dist/lock-backend.d.ts +6 -0
  68. package/dist/native-host-win32.d.ts +38 -0
  69. package/dist/network-events.d.ts +66 -0
  70. package/dist/network-snoop.d.ts +56 -0
  71. package/dist/nul-frames.d.ts +4 -0
  72. package/dist/open-shadow-query.d.ts +1 -0
  73. package/dist/owner-only.d.ts +15 -0
  74. package/dist/page-bundle.js +1587 -0
  75. package/dist/page-events.d.ts +25 -0
  76. package/dist/page-routes.d.ts +30 -0
  77. package/dist/page-setup.d.ts +55 -0
  78. package/dist/pipe.d.ts +71 -0
  79. package/dist/process-start-time.d.ts +2 -0
  80. package/dist/read-property.d.ts +2 -0
  81. package/dist/routes.d.ts +60 -0
  82. package/dist/running-browser.d.ts +39 -0
  83. package/dist/scroll-collect.d.ts +36 -0
  84. package/dist/serial-emitter.d.ts +5 -0
  85. package/dist/shared-connections.d.ts +11 -0
  86. package/dist/snapshot-diff.d.ts +57 -0
  87. package/dist/text-matching.d.ts +21 -0
  88. package/dist/trace.d.ts +59 -0
  89. package/dist/url-match.d.ts +7 -0
  90. package/dist/viewport.d.ts +26 -0
  91. package/dist/ws.d.ts +62 -0
  92. package/package.json +47 -26
  93. package/presets/agent-events/SKILL.md +1 -1
  94. package/presets/captcha/SKILL.md +1 -3
  95. package/presets/chrome/SKILL.md +11 -7
  96. package/presets/cloak-bridge/SKILL.md +11 -11
  97. package/presets/network/SKILL.md +15 -13
  98. package/presets/visual-browse/SKILL.md +14 -10
  99. package/skills/omowright/SKILL.md +77 -47
  100. package/skills/omowright/references/aside.md +50 -0
  101. package/skills/omowright/references/browserskill.md +39 -33
  102. package/skills/omowright/references/ego.md +24 -0
  103. package/skills/omowright/references/eval-kernel.md +44 -23
  104. package/skills/omowright/references/frames-layers-human.md +16 -7
  105. package/skills/omowright/references/quickstart.md +17 -4
  106. package/skills/omowright/references/stealth.md +7 -7
  107. package/src/agent-tabs.js +0 -160
  108. package/src/bridge-schemas.js +0 -44
  109. package/src/bridge-transport.js +0 -57
  110. package/src/browser-process.js +0 -122
  111. package/src/bsk/browser-signals.js +0 -90
  112. package/src/bsk/browsers.js +0 -114
  113. package/src/bsk/connect.js +0 -45
  114. package/src/bsk/daemon-info.js +0 -100
  115. package/src/bsk/external-extension.js +0 -110
  116. package/src/bsk/identify-browser.js +0 -88
  117. package/src/bsk/install-cli.js +0 -81
  118. package/src/bsk/ipc-client.js +0 -236
  119. package/src/bsk/onboard.js +0 -133
  120. package/src/bsk/screenshot.js +0 -49
  121. package/src/bsk/session.js +0 -131
  122. package/src/bsk/snapshot.js +0 -56
  123. package/src/bsk/targets.js +0 -25
  124. package/src/captcha-wait.js +0 -74
  125. package/src/captcha.js +0 -142
  126. package/src/cdp-errors.js +0 -23
  127. package/src/cdp-methods.js +0 -61
  128. package/src/chrome-profile.js +0 -176
  129. package/src/chrome.js +0 -192
  130. package/src/cloak-profile.js +0 -266
  131. package/src/connection.js +0 -135
  132. package/src/cookies.js +0 -29
  133. package/src/core.js +0 -1710
  134. package/src/cua.js +0 -74
  135. package/src/dialog-policy.js +0 -80
  136. package/src/emulate.js +0 -127
  137. package/src/events.js +0 -111
  138. package/src/frames-snapshot.js +0 -138
  139. package/src/har.js +0 -103
  140. package/src/human-handoff.js +0 -122
  141. package/src/injected.js +0 -3
  142. package/src/instance-lock.js +0 -230
  143. package/src/instances.js +0 -493
  144. package/src/internal-capability.js +0 -1
  145. package/src/launch-endpoint.js +0 -185
  146. package/src/layers.js +0 -138
  147. package/src/llm.js +0 -201
  148. package/src/lock-file.js +0 -130
  149. package/src/native-host-win32.js +0 -201
  150. package/src/network-events.js +0 -201
  151. package/src/network-snoop.js +0 -229
  152. package/src/open-shadow-query.js +0 -22
  153. package/src/owner-only.js +0 -109
  154. package/src/page-bundle.js +0 -1397
  155. package/src/page-routes.js +0 -94
  156. package/src/pipe.js +0 -391
  157. package/src/routes.js +0 -256
  158. package/src/running-browser.js +0 -85
  159. package/src/scroll-collect.js +0 -73
  160. package/src/serial-emitter.js +0 -17
  161. package/src/shared-connections.js +0 -278
  162. package/src/snapshot-diff.js +0 -75
  163. package/src/trace.js +0 -183
  164. package/src/url-match.js +0 -148
  165. package/src/viewport.js +0 -12
@@ -1,12 +1,9 @@
1
1
  # Attached engine: the user's own browser through BrowserSkill
2
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.
3
+ BrowserSkill is third in `connectBrowser()`'s order, after Aside and Ego Lite.
4
+ It drives the browser the user is already signed into (Chrome, Edge, Brave)
5
+ through Tencent BrowserSkill (stock `bsk` daemon + Web Store extension, no
6
+ fork), so it serves tasks that need the user's sessions, cookies, or open tabs.
10
7
 
11
8
  ## Core loop
12
9
 
@@ -19,11 +16,11 @@ const sync = () => session.cooperate("sync").then((r) => r.context_id);
19
16
  const { tree, refs, css } = await bskSnapshot(session, { interactive: true, context: await sync() });
20
17
  // tree and refs look exactly like page.snapshot(); css[ref] is a light-DOM
21
18
  // selector for the same element (null inside shadow roots)
22
- await session.click({ selector: css.e3 }, { context: await sync() }); // or "@e3" after session.observe()
19
+ await session.click({ selector: css.e3 }, { context: await sync() }); // or "@e3" after session.observe()
23
20
  await session.fill(css.e5, "hello", { clearBefore: true, context: await sync() });
24
21
  await session.press("Enter", { context: await sync() });
25
22
  await session.waitForNavigation({ waitUntil: "load" });
26
- await session.stop(); // ALWAYS: returns borrowed tabs, closes the Agent Window
23
+ await session.stop(); // ALWAYS: returns borrowed tabs, closes the Agent Window
27
24
  ```
28
25
 
29
26
  ### Shared control (BrowserSkill 0.4+)
@@ -54,7 +51,13 @@ per-user `bsk-daemon-<hash>` scheduled task that runs `bsk daemon start
54
51
  --foreground` under `conhost.exe --headless`, so no console window opens.
55
52
  It never falls back to a headless browser: when no
56
53
  extension is connected it throws `no_browser_connected` and `bskDoctor()`
57
- tells you the one step that is missing.
54
+ tells you the one step that is missing. It also refuses extension 0.4.0 with
55
+ `extension_outdated`: that release puts each task's tabs into a "BrowserSkill"
56
+ tab group the browser saves and syncs, so the group outlives the task. With no
57
+ `browser` named, an up-to-date connected browser is picked instead; otherwise
58
+ the user updates the extension to 0.4.1 or later and deletes any saved
59
+ "BrowserSkill" groups by hand. `bskDoctor()` reports such browsers in
60
+ `outdatedExtensions` and is not `ready` while they are the only ones connected.
58
61
 
59
62
  ## What the session can do
60
63
 
@@ -64,16 +67,16 @@ Targets are a ref (`"e3"` / `"@e3"` from `session.observe()` or
64
67
  `session.snapshot()`), a CSS selector, or `{ captureId, x, y }` from a
65
68
  screenshot.
66
69
 
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)` |
70
+ | Need | Call |
71
+ | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
72
+ | Navigate / history | `navigate(url, {waitUntil, timeoutMs})`, `back()`, `forward()`, `reload({hard})`, `waitForNavigation()` |
73
+ | Read the page | `observe({maxTokens, cursor, probeHover})` (VOM text with `@eN` refs), `snapshot()`, `getHtml({ref, maxBytes})`, `bskSnapshot(session)` (OmOWright tree + css) |
74
+ | Act | `click(target, {button, clickCount, modifiers})`, `hover`, `fill(target, value)`, `press(key, {target, holdMs})`, `select(target, values)`, `focus`, `blur`, `scrollTo`, `wheel({deltaY})` |
75
+ | Script | `evaluate(expression, {awaitPromise, timeoutMs})` → `{ok, value, error}`; Agent Window tabs only |
76
+ | Pixels | `screenshot({ref})` → `{buffer, width, height, captureId}`; `screenshot({fullPage: true})` streams the capture back in chunks |
77
+ | Tabs | `tabList({scope: "user"})`, `tabCreate({url})`, `tabSelect(id)`, `tabClose(id)`, `tabBorrow(id)` (the user confirms), `tabReturn(id)` |
78
+ | Humans | `requestHelp({prompt, targets, completionCriteria, timeoutMs})` for login, CAPTCHA, OTP, payment — the extension shows an overlay and waits |
79
+ | Diagnostics | `console({since})`, `network({since})` (metadata only), `emulate({overrides})`, `resize(w, h)` |
77
80
 
78
81
  Anything the daemon refuses comes back as a `BskRpcError` with the daemon's
79
82
  `code` (`not_found`, `invalid_params`, `permission_denied`, `timeout`,
@@ -100,12 +103,15 @@ bot detection; for WAF-heavy targets use the owned engine with CloakBrowser
100
103
 
101
104
  ```js
102
105
  const { bskDoctor, bskOnboard } = await import("omowright");
103
- const report = await bskDoctor(); // {cli, daemon, browsers, primary, identification, browsersConnected, ready, nextStep}
106
+ const report = await bskDoctor(); // {cli, daemon, browsers, primary, identification, browsersConnected, ready, nextStep}
104
107
  if (!report.ready) {
105
108
  const result = await bskOnboard({ browser: knownBrowserOrUndefined, onHumanStep: (s) => console.log(s.step) });
106
109
  // result.needsChoice === true: nothing was registered; ask the user which
107
110
  // browser they use (result.identification.candidates), then call again with
108
111
  // { browser: "<id>" }.
112
+ // result.outdatedExtensions non-empty and ready === false: the only connected
113
+ // extension is 0.4.0; humanStep (also sent to onHumanStep) tells the user to
114
+ // update it to 0.4.1 or later and delete saved "BrowserSkill" tab groups.
109
115
  // result.daemon.running === false: humanStep is null and nothing was
110
116
  // registered; result.nextStep says how to start the daemon. Start it and
111
117
  // call again before telling the user anything.
@@ -127,11 +133,11 @@ proves nothing — Chrome leaves one behind after a single launch — so
127
133
  Brave, Chromium, Arc, Dia, Vivaldi, Opera, Comet, Aside, Naver Whale) by
128
134
  usage signals from `probeBrowserSignals`:
129
135
 
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 |
136
+ | Signal | macOS | Linux | Windows |
137
+ | --------------- | ------------------------------------------------------------------------------------------------ | -------------------------------------- | ------------------- |
138
+ | Default browser | LaunchServices `https` handler | `xdg-settings get default-web-browser` | `UserChoice` ProgId |
139
+ | Running now | the app bundle in `/Applications` or `~/Applications` (automation builds elsewhere do not count) | process name | `tasklist` image |
140
+ | Recent use | `Local State` / `Default/History` mtime within 7 days | same | same |
135
141
 
136
142
  The decision, in order, with the `confidence` each step reports: an explicit
137
143
  `browser` option or `OMOWRIGHT_BROWSER` (`explicit`); the one browser whose
@@ -159,13 +165,13 @@ reverted — the library calls the binary by absolute path); `bsk status` to
159
165
  start the daemon; then, for the identified browser only, Chrome's
160
166
  external-extension registration for the Web Store listing:
161
167
 
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 |
168
+ | Platform | Where the entry goes | What the user does |
169
+ | ---------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------- |
170
+ | macOS | `<user data dir>/External Extensions/<id>.json` | relaunch the browser, click **Enable** once |
171
+ | Windows | `HKCU\Software\<vendor>\<browser>\Extensions\<id>` (`reg add`, no admin) | click **Enable** on the toolbar badge; no restart |
172
+ | Linux (Chromium) | `<user data dir>/External Extensions/<id>.json` | relaunch; installs silently |
173
+ | Linux (Chrome/Edge/Brave) | `/opt/google/chrome/extensions/<id>.json` etc. — needs root | otherwise: open the store link and click Add |
174
+ | Opera, and Vivaldi/Whale off macOS | no external-extension path | open the store link in that browser and click Add |
169
175
 
170
176
  Then it waits on `system.status{wait_for_browser_ms}` until the extension
171
177
  connects. Tell the user exactly `result.humanStep`, nothing more. If the user
@@ -0,0 +1,24 @@
1
+ # Ego Lite engine: an agent task space in the user's Ego browser
2
+
3
+ Ego Lite is second in `connectBrowser()`'s order. Its CDP bindings
4
+ (`globalThis.ego`) exist only inside a script run by `ego-browser nodejs`, so
5
+ load omowright there by absolute path:
6
+
7
+ ```bash
8
+ ego-browser nodejs -e "const { connectBrowser } = await import('file:///<abs>/omowright/src/index.js'); const { handle: browser } = await connectBrowser({ allow: ['ego'] }); const page = await browser.newTab('https://example.com'); console.log(await page.title()); await browser.close();"
9
+ ```
10
+
11
+ The script runs as ESM with top-level await, outside your shell's working
12
+ directory and environment: use absolute paths and write inputs into the script.
13
+
14
+ `connectEgo({ taskName, profileId, taskSpace })` (or `connectBrowser({ ego: {...} })`)
15
+ creates an agent task space and selects it, because Ego sends raw CDP only for
16
+ the selected, agent-owned space. `taskSpace: <numeric id>` reuses one the agent
17
+ already claimed. The handle is a `BrowserConnection`: the full Page API,
18
+ `compactSnapshot` and CUA apply. `handle.taskSpace` names the space.
19
+
20
+ One client at a time owns Ego's callbacks in a runtime: a second connect
21
+ rejects with `ego_busy` and changes nothing, so close the first.
22
+ `close()` releases the callbacks and leaves the user's browser running.
23
+ Sends Ego refuses (the user took the space over, no space selected) reject at
24
+ once with Ego's `error_code`, such as `EGO_TASK_SPACE_USER_CONTROLLED`.
@@ -21,17 +21,25 @@ rejects every call. Two patterns hold up:
21
21
  the setup cell below):
22
22
 
23
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
24
+ await tool.monitor({
25
+ description: "omowright browser",
26
+ command: `${shell} --headless --no-first-run --remote-debugging-port=9333 --user-data-dir=${profile} about:blank`,
27
+ });
28
+ 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
29
  ```
27
30
 
28
- If you'd rather keep `connectPipe`, treat the browser as disposable: start
29
- every cell with a probe and relaunch on failure.
31
+ If you'd rather keep `connectPipe`, treat the browser as disposable: start
32
+ every cell with a probe and relaunch on failure.
30
33
 
31
34
  ```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
+ try {
36
+ await globalThis.omw.listTargets();
37
+ } catch {
38
+ globalThis.omw = await omwTools.connectPipe({
39
+ browserPath: shell,
40
+ browserArgs: ["--headless", "--no-first-run", `--user-data-dir=${profile}`],
41
+ storageRoot: profile,
42
+ });
35
43
  globalThis.omwPage = await omw.newTab("about:blank");
36
44
  }
37
45
  ```
@@ -47,7 +55,12 @@ const m = await import("omowright");
47
55
  const fs = await import("node:fs");
48
56
  const os = await import("node:os");
49
57
  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);
58
+ const shell = fs
59
+ .globSync(
60
+ `${env("HOME")}/Library/Caches/ms-playwright/chromium_headless_shell-*/chrome-headless-shell-mac-arm64/chrome-headless-shell`,
61
+ )
62
+ .sort()
63
+ .at(-1);
51
64
  const profile = fs.mkdtempSync(path.join(os.tmpdir(), "omowright-eval-"));
52
65
  globalThis.omw = await m.connectPipe({
53
66
  browserPath: shell,
@@ -61,11 +74,11 @@ globalThis.omwTools = m;
61
74
  ## Later cells
62
75
 
63
76
  ```js
64
- await omw.listTargets(); // throws if the kernel reaped the browser: rerun setup
77
+ await omw.listTargets(); // throws if the kernel reaped the browser: rerun setup
65
78
  await omwPage.goto("https://example.com");
66
79
  console.log(omwTools.compactSnapshot(await omwPage.snapshot()));
67
80
  await omwPage.locator("e1").click();
68
- display(await omwPage.screenshot({ type: "png" })); // display() renders images inline
81
+ display(await omwPage.screenshot({ type: "png" })); // display() renders images inline
69
82
  ```
70
83
 
71
84
  ## Parallel lanes (research fan-out)
@@ -75,25 +88,33 @@ transport has no ports to collide on. Every lane connects, acts, and closes
75
88
  inside the cell, so the reaping rule never bites.
76
89
 
77
90
  ```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
- }));
91
+ const results = await parallel(
92
+ [1, 2, 3].map((i) => async () => {
93
+ const prof = fs.mkdtempSync(path.join(os.tmpdir(), `omw-lane${i}-`));
94
+ const br = await omwTools.connectPipe({
95
+ browserPath: shell,
96
+ browserArgs: ["--headless", `--user-data-dir=${prof}`],
97
+ storageRoot: prof,
98
+ });
99
+ try {
100
+ const p = await br.newTab(urls[i]);
101
+ return omwTools.compactSnapshot(await p.snapshot());
102
+ } finally {
103
+ await br.close();
104
+ fs.rmSync(prof, { recursive: true, force: true });
105
+ }
106
+ }),
107
+ );
89
108
  ```
90
109
 
91
110
  ## Cleanup cell
92
111
 
93
112
  ```js
94
- await omw.close().catch(() => {}); // no-op if the process is already gone
113
+ await omw.close().catch(() => {}); // no-op if the process is already gone
95
114
  fs.rmSync(profile, { recursive: true, force: true });
96
- delete globalThis.omw; delete globalThis.omwPage; delete globalThis.omwTools;
115
+ delete globalThis.omw;
116
+ delete globalThis.omwPage;
117
+ delete globalThis.omwTools;
97
118
  ```
98
119
 
99
120
  For the monitor-launched form, stop the monitor after `close()` so the profile
@@ -4,8 +4,17 @@ Four modules for the moments when the plain snapshot-and-click loop stalls.
4
4
  All come from the package entrypoint:
5
5
 
6
6
  ```js
7
- const { reconcileFrames, snapshotWithFrames, describeLayers, layersHeader, snapshotWithLayers,
8
- requestHuman, DEVICE_PRESETS, emulate, compactSnapshot } = await import("omowright");
7
+ const {
8
+ reconcileFrames,
9
+ snapshotWithFrames,
10
+ describeLayers,
11
+ layersHeader,
12
+ snapshotWithLayers,
13
+ requestHuman,
14
+ DEVICE_PRESETS,
15
+ emulate,
16
+ compactSnapshot,
17
+ } = await import("omowright");
9
18
  ```
10
19
 
11
20
  ## Out-of-process iframes and shadow DOM
@@ -58,7 +67,7 @@ console.log(layersHeader(layers));
58
67
  if (layers.blocking) {
59
68
  // Dismiss through a fresh ref: snapshot the overlay by its hint, click its button.
60
69
  const tree = compactSnapshot(await page.snapshot({ selector: layers.blocking.selectorHint, interactive: true }));
61
- await page.locator(/\[ref=(e\d+)\]/.exec(tree)[1]).click(); // first interactive ref inside the overlay
70
+ await page.locator(/\[ref=(e\d+)\]/.exec(tree)[1]).click(); // first interactive ref inside the overlay
62
71
  }
63
72
  ```
64
73
 
@@ -85,7 +94,7 @@ captcha preset can't clear, hand the tab to the person and wait for a signal:
85
94
  ```js
86
95
  const result = await requestHuman(page, {
87
96
  prompt: "Sign in with your account, then click Done.",
88
- until: { url: /\/dashboard/ }, // or { selector: "nav.account" } or async page => boolean
97
+ until: { url: /\/dashboard/ }, // or { selector: "nav.account" } or async page => boolean
89
98
  timeoutMs: 300000,
90
99
  });
91
100
  // { outcome: "continued" | "timed_out" | "cancelled", elapsedMs, reason: "until" | "done-button" | "timed_out" | "signal" }
@@ -107,11 +116,11 @@ browser and continue from that session.
107
116
  `emulate` sets viewport metrics, touch, and user agent in one call:
108
117
 
109
118
  ```js
110
- await emulate(page, "iphone-14"); // 390x844 @3x, touch, iOS Safari UA
119
+ await emulate(page, "iphone-14"); // 390x844 @3x, touch, iOS Safari UA
111
120
  await page.goto("https://example.com");
112
121
  await page.screenshot({ path: "/tmp/home-iphone.png" });
113
- await emulate(page, "desktop-1440"); // 1440x900, mouse
114
- await emulate(page, null); // clear the override, restore the original UA
122
+ await emulate(page, "desktop-1440"); // 1440x900, mouse
123
+ await emulate(page, null); // clear the override, restore the original UA
115
124
  ```
116
125
 
117
126
  Presets in `DEVICE_PRESETS`: `iphone-14` (390x844), `pixel-7` (412x915),
@@ -68,16 +68,29 @@ await page.close();
68
68
  ## Snapshot discipline
69
69
 
70
70
  ```js
71
- const snap = await page.snapshot(); // { tree, refs } or JSON string
72
- const tree = compactSnapshot(snap); // raw tree, ~57% smaller
73
- await page.snapshot({ interactive: true }); // interactive elements only
71
+ const snap = await page.snapshot(); // { tree, refs } or JSON string
72
+ const tree = compactSnapshot(snap); // raw tree, ~57% smaller
73
+ await page.snapshot({ interactive: true }); // controls, headings, landmarks and state feedback
74
74
  await page.snapshot({ maxDepth: 20, maxChars: 4000, selector: "main" });
75
75
  ```
76
76
 
77
77
  Tree lines look like `- link "Learn more" [ref=e1]` — feed `e1` to
78
78
  `page.locator("e1")`. **EVERY NEW SNAPSHOT INVALIDATES EARLIER REFS**: re-snapshot
79
79
  after each state change, never act on a stale ref. Start with
80
- `interactive: true`; escalate to a full snapshot only when the target is missing.
80
+ `interactive: true`; escalate to a full snapshot when a target or needed text is
81
+ missing or truncated. Interactive reads keep capped text for clickable nodes,
82
+ scrollable containers and live regions: roles alert, alertdialog, status, log,
83
+ timer and marquee, and any `aria-live="polite"` or `"assertive"` element such as
84
+ a toast. A clickable or scrollable node keeps up to 100 characters of its own
85
+ text. Every other piece of text inside a live region counts toward that region's
86
+ 100 characters in total, however many items it holds, so two toasts each keep
87
+ their own text and a long log keeps only its start. A live region nested inside
88
+ a clickable or scrollable node, such as a toast in a scrollable pane, keeps its
89
+ own 100 characters beside the node's. Clickable or scrollable nodes inside or
90
+ around a live region keep their own 100 on top, so a scrollable `role="log"`
91
+ keeps up to 100 characters of its own text plus 100 for entries that are kept
92
+ nodes (`aria-live="off"` text is dropped; an invalid `aria-live` value counts
93
+ as unset). Other free-standing body prose is omitted.
81
94
 
82
95
  ## Readiness and dialogs
83
96
 
@@ -43,10 +43,10 @@ on a machine you trust and only when the instance is meant to be shared.
43
43
  ```js
44
44
  const { connectNamed, listInstances } = await import("omowright");
45
45
  const browser = await connectNamed("cloak-main", {
46
- browserPath, // required only when a launch is needed (connectCloakProfile resolves it)
46
+ browserPath, // required only when a launch is needed (connectCloakProfile resolves it)
47
47
  browserArgs,
48
- profileDir, // recorded with the instance; used for endpoint discovery
49
- registryRoot, // defaults to ~/.local/share/omowright/instances
48
+ profileDir, // recorded with the instance; used for endpoint discovery
49
+ registryRoot, // defaults to ~/.local/share/omowright/instances
50
50
  });
51
51
  const page = await browser.newTab("https://target.com");
52
52
  await listInstances();
@@ -75,7 +75,7 @@ curl -s -m 2 http://127.0.0.1:9242/json/version # Browser info -> an instance
75
75
  const browser = await connect("http://127.0.0.1:9242");
76
76
  const page = await browser.newTab("https://target.com");
77
77
  // ... work ...
78
- await page.close(); // close only YOUR tab
78
+ await page.close(); // close only YOUR tab
79
79
  ```
80
80
 
81
81
  ## Launch
@@ -84,7 +84,7 @@ await page.close(); // close only YOUR tab
84
84
  const { connectCloakProfile } = await import("omowright");
85
85
  const browser = await connectCloakProfile({
86
86
  profileDir: `${process.env.HOME}/.local/share/omowright-cloak`,
87
- fingerprintSeed: 63498, // first use pins it; later runs reuse it and reject a mismatch
87
+ fingerprintSeed: 63498, // first use pins it; later runs reuse it and reject a mismatch
88
88
  });
89
89
  ```
90
90
 
@@ -116,8 +116,8 @@ extract them to JSON and inject with the package helper:
116
116
  ```js
117
117
  import { injectCookies } from "omowright";
118
118
  const cookies = JSON.parse(await fs.promises.readFile(cookieFile, "utf8"));
119
- await injectCookies(page, cookies); // sanitize + Network.setCookies
120
- await page.goto(url); // cookies apply on navigation
119
+ await injectCookies(page, cookies); // sanitize + Network.setCookies
120
+ await page.goto(url); // cookies apply on navigation
121
121
  ```
122
122
 
123
123
  `injectCookies` drops `expires <= 0`, forces `secure` + root path + url-scoping
package/src/agent-tabs.js DELETED
@@ -1,160 +0,0 @@
1
- import { DEFAULT_AGENT_VIEWPORT, repinViewport } from "./viewport.js";
2
- import { targetCreationCapability } from "./internal-capability.js";
3
-
4
- const managers = new WeakMap();
5
- const CAPABILITY = targetCreationCapability;
6
-
7
- function optionsKey(options = {}) {
8
- return JSON.stringify({
9
- viewport: { ...DEFAULT_AGENT_VIEWPORT, ...(options.viewport ?? {}) },
10
- closeTimeoutMs: options.closeTimeoutMs ?? 5_000,
11
- });
12
- }
13
-
14
- export class AgentTabManager {
15
- #connection;
16
- #owned = new Map();
17
- #unsubscribers = [];
18
- #disposed = false;
19
- #closing = new Map();
20
- viewport;
21
- closeTimeoutMs;
22
- ready;
23
-
24
- constructor(connection, options = {}) {
25
- if (!connection?.cdp) throw new TypeError("createAgentTabs requires a browser connection");
26
- this.#connection = connection;
27
- this.viewport = Object.freeze({ ...DEFAULT_AGENT_VIEWPORT, ...(options.viewport ?? {}) });
28
- this.closeTimeoutMs = options.closeTimeoutMs ?? 5_000;
29
- this.#unsubscribers.push(connection.cdp.on("Target.targetDestroyed", info => this.#destroyed(info?.targetId)));
30
- this.#unsubscribers.push(connection.cdp.on("Target.targetCrashed", info => this.#destroyed(info?.targetId)));
31
- this.#unsubscribers.push(connection.cdp.transportEvents?.on?.("disconnected", () => {
32
- for (const id of [...this.#owned.keys()]) this.#destroyed(id, Error("Browser transport disconnected"));
33
- }));
34
- this.ready = Promise.resolve(connection.cdp.ensureConnected?.());
35
- }
36
-
37
- async create(url = "about:blank", options = {}) {
38
- if (this.#disposed) throw Error("Agent tab manager is disposed");
39
- await this.ready;
40
- const viewport = { ...this.viewport, ...(options.viewport ?? {}) };
41
- // A headed browser keeps a background tab in a shared window hidden: it never
42
- // paints (Page.captureScreenshot hangs) and requestAnimationFrame never fires.
43
- // Its own window doesn't take focus from the user's tab, and the tab renders
44
- // (verified headed on Linux and macOS).
45
- const result = await this.#connection.cdp.send("Target.createTarget", { url, background: true, newWindow: true }, undefined, { capability: CAPABILITY });
46
- const targetId = result.targetId;
47
- // CloakBrowser headless defers renderer startup for background targets until
48
- // activation; activating before attach avoids Page.enable timing out.
49
- if (await this.#isHeadless()) await this.#connection.cdp.send("Target.activateTarget", { targetId });
50
- const record = { targetId, page: null, viewport: Object.freeze({ ...viewport }), repinQueue: Promise.resolve() };
51
- this.#owned.set(targetId, record);
52
- try {
53
- record.page = await this.#connection.attachPage(targetId);
54
- await repinViewport(record.page, record.viewport);
55
- record.navigationOff = record.page.on?.("framenavigated", event => {
56
- if (!event.parentFrameId) this.#repin(record);
57
- });
58
- return this.#public(record);
59
- } catch (error) {
60
- await this.#connection.cdp.send("Target.closeTarget", { targetId }).catch(() => {});
61
- throw error;
62
- }
63
- }
64
-
65
- #public(record) {
66
- return Object.freeze({ targetId: record.targetId, page: record.page, viewport: { ...record.viewport }, close: options => this.close(record.targetId, options) });
67
- }
68
- get(targetId) { const record = this.#owned.get(targetId); return record ? this.#public(record) : null; }
69
- list() { return [...this.#owned.values()].map(record => this.#public(record)); }
70
- async #isHeadless() {
71
- if (typeof this.#connection.cdp.isHeadless === "boolean") return this.#connection.cdp.isHeadless;
72
- const version = await this.#connection.cdp.send("Browser.getVersion").catch(() => null);
73
- return /Headless/i.test(version?.product ?? "");
74
- }
75
- #queueRepin(record, viewport, reportErrors = false) {
76
- const size = { ...viewport };
77
- const operation = record.repinQueue.then(async () => {
78
- try { await repinViewport(record.page, size); }
79
- catch (error) { if (reportErrors) console.warn(`[agent-tabs] viewport repin failed for ${record.targetId}`, error); else throw error; }
80
- record.viewport = Object.freeze(size);
81
- return { ...size };
82
- });
83
- record.repinQueue = operation.catch(() => {});
84
- return operation;
85
- }
86
- async #repin(record) { await this.#queueRepin(record, record.viewport, true); }
87
- async repin(tabOrTargetId, viewport = this.viewport) {
88
- const id = typeof tabOrTargetId === "string" ? tabOrTargetId : tabOrTargetId?.targetId;
89
- const record = this.#owned.get(id);
90
- if (!record) throw Error(`Target ${id} is not owned by this manager`);
91
- return this.#queueRepin(record, viewport);
92
- }
93
-
94
- async close(tabOrTargetId, options = {}) {
95
- const id = typeof tabOrTargetId === "string" ? tabOrTargetId : tabOrTargetId?.targetId;
96
- const record = this.#owned.get(id);
97
- if (!record) throw Error(`Target ${id} is not owned by this manager`);
98
- const existing = this.#closing.get(id);
99
- if (existing) return existing.promise;
100
- let resolveOperation, rejectOperation;
101
- const promise = new Promise((resolve, reject) => { resolveOperation = resolve; rejectOperation = reject; });
102
- const entry = { promise, reject: rejectOperation };
103
- this.#closing.set(id, entry);
104
- this.#close(record, options).then(resolveOperation, rejectOperation).finally(() => {
105
- if (this.#closing.get(id) === entry) this.#closing.delete(id);
106
- });
107
- return promise;
108
- }
109
-
110
- async #close(record, options) {
111
- let resolveDestroy, rejectDestroy;
112
- const destroyed = new Promise((resolve, reject) => { resolveDestroy = resolve; rejectDestroy = reject; });
113
- const timeout = setTimeout(() => rejectDestroy(Error(`Timed out waiting for target ${record.targetId} to close`)), options.timeoutMs ?? this.closeTimeoutMs);
114
- const off = this.#connection.cdp.on("Target.targetDestroyed", info => { if (info?.targetId === record.targetId) resolveDestroy(); });
115
- const offDisconnect = this.#connection.cdp.transportEvents?.on?.("disconnected", () => rejectDestroy(Error("Browser transport disconnected")));
116
- try {
117
- if (options.runBeforeUnload && record.page) await record.page.cdp.send("Page.close", undefined, await record.page.resolveSessionId()).catch(() => this.#connection.cdp.send("Target.closeTarget", { targetId: record.targetId }));
118
- else await this.#connection.cdp.send("Target.closeTarget", { targetId: record.targetId });
119
- if (this.#owned.has(record.targetId)) await destroyed;
120
- } finally {
121
- clearTimeout(timeout); off(); offDisconnect?.();
122
- // Ownership is removed only by Target.targetDestroyed (or transport loss).
123
- if (!this.#owned.has(record.targetId)) record.navigationOff?.();
124
- }
125
- }
126
-
127
- #destroyed(id, error) {
128
- const record = this.#owned.get(id);
129
- if (!record) return;
130
- record.navigationOff?.();
131
- this.#owned.delete(id);
132
- if (error) this.#closing.get(id)?.reject(error);
133
- }
134
- async closeAll(options = {}) {
135
- const results = await Promise.allSettled([...this.#owned.keys()].map(id => this.close(id, options)));
136
- const failures = results.filter(result => result.status === "rejected").map(result => result.reason);
137
- if (failures.length) throw new AggregateError(failures, "Failed to close one or more agent tabs");
138
- }
139
- async dispose(options = { closeOwned: true }) {
140
- if (this.#disposed) return;
141
- let failure;
142
- if (options.closeOwned !== false) try { await this.closeAll(options); } catch (error) { failure = error; }
143
- this.#disposed = true;
144
- for (const off of this.#unsubscribers) off();
145
- this.#unsubscribers = [];
146
- if (failure) throw failure;
147
- }
148
- }
149
-
150
- export function createAgentTabs(connection, options = {}) {
151
- const current = managers.get(connection);
152
- if (current) {
153
- if (current._optionsKey !== optionsKey(options)) throw new TypeError("Conflicting AgentTabManager options");
154
- return current;
155
- }
156
- const manager = new AgentTabManager(connection, options);
157
- Object.defineProperty(manager, "_optionsKey", { value: optionsKey(options) });
158
- managers.set(connection, manager);
159
- return manager;
160
- }
@@ -1,44 +0,0 @@
1
- import * as z from "zod";
2
-
3
- export const HOST_NAME = "com.omowright.cloakbridge";
4
- export const PROTOCOL = 1;
5
- export const MAX_MESSAGE_BYTES = 1024 * 1024;
6
- export const EVENT_NAMES = Object.freeze(["notifications.shown", "notifications.clicked", "notifications.closed", "tabGroups.created", "tabGroups.updated", "tabGroups.moved", "tabs.activated", "windows.focusChanged"]);
7
- export const COMMAND_NAMES = Object.freeze(["bookmarks.create", "bookmarks.move", "bookmarks.remove", "history.deleteUrl", "history.deleteRange", "tabGroups.update", "debugger.attach", "debugger.detach"]);
8
- export const MUTATING_COMMANDS = new Set(COMMAND_NAMES);
9
- const id = z.string().min(1).max(128);
10
- const uuid = z.string().regex(/^[0-9a-fA-F-]{16,128}$/);
11
- const finite = z.number().finite();
12
- const color = z.enum(["grey", "blue", "red", "yellow", "green", "pink", "purple", "cyan", "orange"]);
13
- const group = z.object({ id: z.number().int().min(0), collapsed: z.boolean(), color, title: z.string().max(1024).nullable().optional(), windowId: z.number().int().min(-1) }).strict();
14
- const bookmarkNode = z.lazy(() => z.object({ id: z.string().min(1), parentId: z.string().min(1).optional(), index: z.number().int().min(0).optional(), title: z.string(), url: z.string().optional(), dateAdded: finite.min(0).optional(), dateGroupModified: finite.min(0).optional(), dateLastUsed: finite.min(0).optional(), folderType: z.string().optional(), syncing: z.boolean().optional(), unmodifiable: z.string().optional(), type: z.enum(["bookmark", "folder", "url"]).optional(), children: z.array(bookmarkNode).optional() }).strict());
15
- const empty = z.object({}).strict();
16
- export const payloadSchemas = {
17
- "notifications.shown": z.object({ notificationId: z.string().min(1).max(1024) }).strict(),
18
- "notifications.clicked": z.object({ notificationId: z.string().min(1).max(1024) }).strict(),
19
- "notifications.closed": z.object({ notificationId: z.string().min(1).max(1024), byUser: z.boolean() }).strict(),
20
- "tabGroups.created": z.object({ group }).strict(), "tabGroups.updated": z.object({ group }).strict(), "tabGroups.moved": z.object({ group }).strict(),
21
- "tabs.activated": z.object({ tabId: z.number().int().min(0), windowId: z.number().int().min(-1), previousTabId: z.number().int().min(0).optional() }).strict(),
22
- "windows.focusChanged": z.object({ windowId: z.number().int().min(-1) }).strict(),
23
- };
24
- export const commandParams = {
25
- "bookmarks.create": z.object({ details: z.object({ parentId: z.string().min(1).optional(), index: z.number().int().min(0).optional(), title: z.string().max(8192), url: z.string().url().max(8192).optional() }).strict() }).strict(),
26
- "bookmarks.move": z.object({ details: z.object({ id: z.string().min(1), parentId: z.string().min(1).optional(), index: z.number().int().min(0).optional() }).strict() }).strict(),
27
- "bookmarks.remove": z.object({ details: z.object({ id: z.string().min(1) }).strict() }).strict(),
28
- "history.deleteUrl": z.object({ details: z.object({ url: z.string().url().max(8192) }).strict() }).strict(),
29
- "history.deleteRange": z.object({ details: z.object({ startTime: finite.min(0), endTime: finite.min(0) }).strict() }).strict().refine(v => v.details.startTime <= v.details.endTime, "startTime must not exceed endTime"),
30
- "tabGroups.update": z.object({ details: z.object({ groupId: z.number().int().min(0), updateProperties: z.object({ collapsed: z.boolean().optional(), color: color.optional(), title: z.string().max(1024).nullable().optional() }).strict().refine(v => Object.keys(v).length > 0, "updateProperties must not be empty") }).strict() }).strict(),
31
- "debugger.attach": z.object({ details: z.object({ tabId: z.number().int().min(0), requiredVersion: z.string().regex(/^\d+\.\d+$/) }).strict() }).strict(),
32
- "debugger.detach": z.object({ details: z.object({ tabId: z.number().int().min(0) }).strict() }).strict(),
33
- };
34
- export const resultSchemas = { "bookmarks.create": bookmarkNode, "bookmarks.move": bookmarkNode, "bookmarks.remove": empty, "history.deleteUrl": empty, "history.deleteRange": empty, "tabGroups.update": group, "debugger.attach": z.object({ tabId: z.number().int().min(0), attached: z.literal(true), requiredVersion: z.string() }).strict(), "debugger.detach": z.object({ tabId: z.number().int().min(0), detached: z.literal(true) }).strict() };
35
- const base = { protocol: z.literal(PROTOCOL) };
36
- function unique(values, ctx) { if (new Set(values).size !== values.length) ctx.addIssue({ code: z.ZodIssueCode.custom, message: "array entries must be unique" }); }
37
- const names = allowed => z.array(z.enum([...allowed])).superRefine(unique);
38
- export const ExtensionHelloSchema = z.object({ ...base, type: z.literal("hello"), role: z.literal("extension"), connectionId: id, extensionId: z.string().regex(/^[a-p]{32}$/), extensionVersion: z.string().min(1).max(64), events: names(EVENT_NAMES), commands: names(COMMAND_NAMES), maxMessageBytes: z.number().int().min(1).max(MAX_MESSAGE_BYTES) }).strict();
39
- export const HostHelloSchema = z.object({ ...base, type: z.literal("hello"), role: z.literal("host"), connectionId: id, hostName: z.literal(HOST_NAME), hostVersion: z.string().min(1).max(64), events: names(EVENT_NAMES), commands: names(COMMAND_NAMES), maxMessageBytes: z.number().int().min(1).max(MAX_MESSAGE_BYTES) }).strict();
40
- export const EventSchema = z.object({ ...base, type: z.literal("event"), connectionId: id, seq: z.number().int().min(1), occurredAt: z.number().int().min(0), name: z.enum(EVENT_NAMES), payload: z.record(z.string(), z.unknown()) }).strict().superRefine((v, ctx) => { if (!payloadSchemas[v.name].safeParse(v.payload).success) ctx.addIssue({ code: z.ZodIssueCode.custom, message: "invalid event payload" }); });
41
- export const CommandSchema = z.object({ ...base, type: z.literal("command"), requestId: uuid, name: z.enum(COMMAND_NAMES), params: z.record(z.string(), z.unknown()), deadlineAt: z.number().int().min(0).optional() }).strict().superRefine((v, ctx) => { if (!commandParams[v.name].safeParse(v.params).success) ctx.addIssue({ code: z.ZodIssueCode.custom, message: "invalid command parameters" }); });
42
- const errorSchema = z.object({ code: z.enum(["INVALID_MESSAGE", "UNKNOWN_COMMAND", "UNSUPPORTED_COMMAND", "CHROME_ERROR", "DEBUGGER_ERROR", "NATIVE_HOST_DISCONNECTED", "TIMEOUT", "PAYLOAD_TOO_LARGE", "INTERNAL_ERROR"]), message: z.string().min(1).max(512), details: z.record(z.string(), z.unknown()).optional() }).strict();
43
- const responseNames = [...COMMAND_NAMES, "protocolError"];
44
- export const ResponseSchema = z.object({ ...base, type: z.literal("response"), requestId: uuid, name: z.enum(responseNames), ok: z.boolean(), result: z.unknown().optional(), error: errorSchema.optional() }).strict().superRefine((v, ctx) => { const valid = v.ok ? v.result !== undefined && v.error === undefined && v.name !== "protocolError" : v.error !== undefined && v.result === undefined; if (!valid) ctx.addIssue({ code: z.ZodIssueCode.custom, message: "response must contain exactly one result or error" }); if (v.ok && resultSchemas[v.name] && !resultSchemas[v.name].safeParse(v.result).success) ctx.addIssue({ code: z.ZodIssueCode.custom, message: "invalid command result" }); });