omowright 0.2.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 (174) hide show
  1. package/README.md +24 -22
  2. package/TOOLS.md +6 -6
  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} +11 -55
  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 +2 -2
  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 +29 -32
  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 +3 -3
  106. package/skills/omowright/references/stealth.md +7 -7
  107. package/src/agent-tabs.js +0 -179
  108. package/src/aria-hidden.js +0 -47
  109. package/src/bridge-schemas.js +0 -44
  110. package/src/bridge-transport.js +0 -83
  111. package/src/browser-context.js +0 -105
  112. package/src/browser-process.js +0 -127
  113. package/src/bsk/browser-signals.js +0 -90
  114. package/src/bsk/browsers.js +0 -114
  115. package/src/bsk/connect.js +0 -75
  116. package/src/bsk/daemon-info.js +0 -100
  117. package/src/bsk/external-extension.js +0 -110
  118. package/src/bsk/identify-browser.js +0 -88
  119. package/src/bsk/install-cli.js +0 -81
  120. package/src/bsk/ipc-client.js +0 -236
  121. package/src/bsk/onboard.js +0 -140
  122. package/src/bsk/screenshot.js +0 -49
  123. package/src/bsk/session.js +0 -131
  124. package/src/bsk/snapshot.js +0 -56
  125. package/src/bsk/targets.js +0 -25
  126. package/src/captcha-wait.js +0 -79
  127. package/src/captcha.js +0 -142
  128. package/src/cdp-errors.js +0 -23
  129. package/src/cdp-methods.js +0 -69
  130. package/src/chrome-profile.js +0 -176
  131. package/src/chrome.js +0 -194
  132. package/src/cloak-profile.js +0 -266
  133. package/src/connection.js +0 -234
  134. package/src/console-events.js +0 -12
  135. package/src/cookies.js +0 -39
  136. package/src/core.js +0 -1702
  137. package/src/cua.js +0 -74
  138. package/src/dialog-policy.js +0 -80
  139. package/src/emulate.js +0 -127
  140. package/src/events.js +0 -111
  141. package/src/frames-snapshot.js +0 -138
  142. package/src/har.js +0 -103
  143. package/src/human-handoff.js +0 -124
  144. package/src/injected.js +0 -3
  145. package/src/instance-lock.js +0 -74
  146. package/src/instances.js +0 -490
  147. package/src/internal-capability.js +0 -1
  148. package/src/launch-endpoint.js +0 -185
  149. package/src/layers.js +0 -138
  150. package/src/llm.js +0 -201
  151. package/src/lock-backend-win32.js +0 -54
  152. package/src/lock-backend.js +0 -81
  153. package/src/native-host-win32.js +0 -201
  154. package/src/network-events.js +0 -223
  155. package/src/network-snoop.js +0 -229
  156. package/src/nul-frames.js +0 -28
  157. package/src/open-shadow-query.js +0 -101
  158. package/src/owner-only.js +0 -196
  159. package/src/page-bundle.js +0 -1478
  160. package/src/page-events.js +0 -45
  161. package/src/page-routes.js +0 -94
  162. package/src/page-setup.js +0 -239
  163. package/src/pipe.js +0 -418
  164. package/src/process-start-time.js +0 -64
  165. package/src/routes.js +0 -256
  166. package/src/running-browser.js +0 -85
  167. package/src/scroll-collect.js +0 -73
  168. package/src/serial-emitter.js +0 -17
  169. package/src/shared-connections.js +0 -285
  170. package/src/snapshot-diff.js +0 -75
  171. package/src/text-matching.js +0 -101
  172. package/src/trace.js +0 -183
  173. package/src/url-match.js +0 -148
  174. package/src/viewport.js +0 -12
@@ -1,140 +0,0 @@
1
- import { homedir } from "node:os";
2
- import { findBskBinary } from "./daemon-info.js";
3
- import { BskIpcClient } from "./ipc-client.js";
4
- import { isTabGroupingExtension, listBrowsers, TAB_GROUPING_EXTENSION_STEP } from "./connect.js";
5
- import { catalogBrowsers, externalExtensionEntry, registerExternalExtension, STORE_PAGE_URLS } from "./external-extension.js";
6
- import { probeBrowserSignals } from "./browser-signals.js";
7
- import { identifyBrowser } from "./identify-browser.js";
8
- import { existsSync, readFileSync } from "node:fs";
9
- import { cliVersionDefault, installBskCli } from "./install-cli.js";
10
-
11
- const DEFAULT_WAIT_TOTAL_MS = 180_000;
12
-
13
- function resolveBskBin(bskBin, env) {
14
- if (bskBin === null) return null;
15
- return bskBin ?? findBskBinary(env);
16
- }
17
-
18
- async function cliReport({ bskBin, env, cliVersion }) {
19
- const bin = resolveBskBin(bskBin, env);
20
- if (!bin) return { installed: false, bskBin: null, version: null };
21
- const raw = await cliVersion(bin);
22
- return raw ? { installed: true, bskBin: bin, version: raw.replace(/^bsk\s+/, "") } : { installed: false, bskBin: bin, version: null };
23
- }
24
-
25
- async function daemonReport(client, waitForBrowserMs) {
26
- try {
27
- const status = await client.call("system.status", waitForBrowserMs > 0 ? { wait_for_browser_ms: waitForBrowserMs } : {}, { idPrefix: "status" });
28
- return { running: true, version: status.daemon_version, protocolVersion: status.protocol_version, browsers: status.browsers ?? [], sessions: status.sessions ?? [] };
29
- } catch (error) {
30
- return { running: false, error: error.message, code: error.code, startBlocked: NO_BREAKAWAY.test(error.message), browsers: [], sessions: [] };
31
- }
32
- }
33
-
34
- // bsk's refusal when the host's Windows Job Object forbids breakaway: a detached start fails the same way every retry.
35
- const NO_BREAKAWAY = /Job Object|breakaway/i;
36
- const FOREGROUND_STEP = "run `bsk daemon start --foreground` in a persistent background session of the agent host (one that outlives the command, not a one-shot shell call), then check it with `bsk status` from a separate call";
37
-
38
- function daemonStep(daemon) {
39
- if (daemon.startBlocked) return `Start the BrowserSkill daemon: this host does not let a command detach it (Windows Job Object breakaway is prohibited), so retrying \`bsk status\` or \`bsk daemon start\` fails the same way; ${FOREGROUND_STEP}.`;
40
- return `Start the BrowserSkill daemon: bskOnboard() (or \`bsk status\` once) starts it. If the host reaps background processes or the start fails, ${FOREGROUND_STEP}; do not retry a detached \`bsk daemon start\`.`;
41
- }
42
-
43
- const NO_BROWSER_STEP = `No Chromium-family browser was found. Install one (Chrome, Edge, Brave, Arc, ...), then add the extension from ${STORE_PAGE_URLS.chrome}.`;
44
-
45
- function withRegistration(platform, browser) {
46
- const entry = externalExtensionEntry({ platform, browser });
47
- const extensionRegistered = entry.kind === "file" && existsSync(entry.path) && readFileSync(entry.path, "utf8") === entry.content;
48
- return { ...browser, registration: entry, extensionRegistered };
49
- }
50
-
51
- async function identify({ platform, home, env, exists, browser, connected, signals, probeSignals, now }) {
52
- const catalog = catalogBrowsers({ platform, home, env, exists }).map((b) => withRegistration(platform, b));
53
- const observed = signals ?? await probeSignals({ platform, home, browsers: catalog.filter((b) => b.hasProfile) });
54
- const explicit = browser ?? env.OMOWRIGHT_BROWSER ?? null;
55
- const { primary, ...identification } = identifyBrowser({ catalog, signals: observed, explicit: explicit || null, connected, now });
56
- const browsers = catalog.filter((b) => b.installed);
57
- const registeredElsewhere = browsers.filter((b) => b.extensionRegistered && b.id !== identification.primaryId).map((b) => b.id);
58
- return { browsers, identification: { ...identification, registeredElsewhere }, primary };
59
- }
60
-
61
- function choiceStep(identification) {
62
- const listed = identification.candidates.map((c) => `${c.label} [${c.id}]${c.signals.length ? ` — ${c.signals.join(", ")}` : ""}`).join("; ");
63
- const hint = identification.suggested ? ` Likely ${identification.suggested}, but confirm first.` : "";
64
- return `Ask the user which browser they actually use (${identification.reason}). Candidates: ${listed}.${hint} Then re-run with browser: "<id>"; register nothing until they answer.`;
65
- }
66
-
67
- function nextStepFor({ cli, daemon, browsers, browsersConnected, identification, primary }) {
68
- if (browsersConnected.length > 0) return browsersConnected.every(isTabGroupingExtension) ? TAB_GROUPING_EXTENSION_STEP : null;
69
- if (!cli.installed) return "Install the bsk CLI (bskOnboard() runs the official installer).";
70
- if (!daemon.running) return daemonStep(daemon);
71
- if (browsers.length === 0 && !primary) return NO_BROWSER_STEP;
72
- if (identification.needsChoice) return choiceStep(identification);
73
- if (!primary.extensionRegistered && primary.registration.kind !== "store") return `Register the BrowserSkill extension for ${primary.label} (bskOnboard() does this), then let the user enable it.`;
74
- return primary.registration.humanStep;
75
- }
76
-
77
- export async function bskDoctor({
78
- platform = process.platform, home = homedir(), env = process.env, client, bskBin, cliVersion = cliVersionDefault, waitForBrowserMs = 0,
79
- exists = existsSync, browser, signals, probeSignals = probeBrowserSignals, now = Date.now(),
80
- } = {}) {
81
- const cli = await cliReport({ bskBin, env, cliVersion });
82
- const ipc = client ?? new BskIpcClient({ env, bskBin: cli.bskBin ?? undefined, autoStart: false });
83
- const daemon = await daemonReport(ipc, waitForBrowserMs);
84
- const { browsers, identification, primary } = await identify({ platform, home, env, exists, browser, connected: daemon.browsers.map((b) => b.browser_name), signals, probeSignals, now });
85
- const browsersConnected = daemon.browsers;
86
- const outdatedExtensions = browsersConnected.filter(isTabGroupingExtension);
87
- const report = { cli, daemon, browsers, primary: primary ?? null, identification, browsersConnected, outdatedExtensions, ready: browsersConnected.length > outdatedExtensions.length };
88
- report.nextStep = nextStepFor(report);
89
- return report;
90
- }
91
-
92
- export async function bskOnboard({
93
- platform = process.platform, home = homedir(), env = process.env, client, bskBin, installDir,
94
- installCli = installBskCli, cliVersion = cliVersionDefault, onHumanStep = () => {},
95
- waitForBrowserMs = 15_000, waitTotalMs = DEFAULT_WAIT_TOTAL_MS,
96
- exists = existsSync, browser, signals, probeSignals = probeBrowserSignals, now = Date.now(),
97
- } = {}) {
98
- let cli = await cliReport({ bskBin, env, cliVersion });
99
- let install = null;
100
- if (!cli.installed) {
101
- install = await installCli({ platform, home, installDir });
102
- cli = install.installed ? await cliReport({ bskBin: install.bskBin, env, cliVersion }) : cli;
103
- }
104
- const ipc = client ?? new BskIpcClient({ env, bskBin: cli.bskBin ?? undefined, autoStart: true });
105
- let daemon = await daemonReport(ipc, 0);
106
- const { browsers, identification, primary } = await identify({ platform, home, env, exists, browser, connected: daemon.browsers.map((b) => b.browser_name), signals, probeSignals, now });
107
- const registrations = [];
108
- let humanStep = null;
109
- let needsChoice = false;
110
- if (daemon.browsers.length === 0) {
111
- if (browsers.length === 0 && !primary) {
112
- humanStep = NO_BROWSER_STEP;
113
- } else if (identification.needsChoice) {
114
- needsChoice = true;
115
- humanStep = choiceStep(identification);
116
- } else if (daemon.running) {
117
- // A down daemon hides whether the extension is already enabled, so no step goes to the user until it is up.
118
- const registration = await registerExternalExtension({ platform, browser: primary });
119
- registrations.push({ browser: primary.id, ...registration });
120
- humanStep = registration.humanStep;
121
- onHumanStep({ browser: primary.id, step: registration.humanStep, registered: registration.registered, needsRestart: registration.needsRestart });
122
- }
123
- }
124
- const deadline = Date.now() + waitTotalMs;
125
- let browsersConnected = daemon.browsers;
126
- while (!needsChoice && browsersConnected.length === 0 && daemon.running && Date.now() < deadline) {
127
- browsersConnected = await listBrowsers(ipc, { waitForBrowserMs });
128
- if (waitForBrowserMs === 0) break;
129
- }
130
- daemon = { ...daemon, browsers: browsersConnected };
131
- // An installed 0.4.0 extension needs the user to update it, not another registration: see bskDoctor.
132
- const outdatedExtensions = browsersConnected.filter(isTabGroupingExtension);
133
- const ready = browsersConnected.length > outdatedExtensions.length;
134
- if (!ready && outdatedExtensions.length > 0) {
135
- humanStep = TAB_GROUPING_EXTENSION_STEP;
136
- onHumanStep({ browser: outdatedExtensions[0].browser_name, step: humanStep, registered: true, needsRestart: false });
137
- }
138
- const nextStep = ready ? null : humanStep ?? nextStepFor({ cli, daemon, browsers, browsersConnected, identification, primary });
139
- return { cli, install, daemon, browsers, primary: primary ?? null, identification, needsChoice, registrations, humanStep: ready ? null : humanStep, nextStep, browsersConnected, outdatedExtensions, ready };
140
- }
@@ -1,49 +0,0 @@
1
- export async function captureScreenshot(session, { ref, tabId, fullPage = false, scope, timeoutMs, context, dependsOn } = {}) {
2
- if (!fullPage) {
3
- const result = await session.tool("screenshot", { ref, tab_id: tabId });
4
- return {
5
- buffer: Buffer.from(result.image_base64, "base64"),
6
- width: result.width,
7
- height: result.height,
8
- format: result.format,
9
- captureId: result.capture_id ?? null,
10
- captureUnavailable: result.capture_unavailable ?? null,
11
- tabId: result.tab_id,
12
- dialogs: result.dialogs ?? [],
13
- };
14
- }
15
- const started = await session.tool("screenshot_full_page", { scope, tab_id: tabId, timeout_ms: timeoutMs, context_id: context, depends_on: dependsOn });
16
- const buffer = await readCapture(session, started.capture_id, started.byte_size);
17
- return {
18
- buffer,
19
- width: started.width,
20
- height: started.height,
21
- format: started.format,
22
- captureId: started.capture_id,
23
- scope: started.scope ?? scope ?? null,
24
- tabId: started.tab_id,
25
- dialogs: started.dialogs ?? [],
26
- };
27
- }
28
-
29
- async function readCapture(session, captureId, byteSize) {
30
- const chunks = [];
31
- let offset = 0;
32
- try {
33
- for (;;) {
34
- const chunk = await session.tool("screenshot_read", { capture_id: captureId, offset });
35
- const bytes = Buffer.from(chunk.data_base64 ?? "", "base64");
36
- chunks.push(bytes);
37
- if (chunk.eof || bytes.length === 0) break;
38
- if (chunk.next_offset <= offset) throw new Error(`screenshot_read did not advance past offset ${offset}`);
39
- offset = chunk.next_offset;
40
- }
41
- } finally {
42
- await session.tool("screenshot_release", { capture_id: captureId }).catch(() => {});
43
- }
44
- const buffer = Buffer.concat(chunks);
45
- if (typeof byteSize === "number" && buffer.length !== byteSize) {
46
- throw new Error(`screenshot capture ${captureId}: expected ${byteSize} bytes, assembled ${buffer.length}`);
47
- }
48
- return buffer;
49
- }
@@ -1,131 +0,0 @@
1
- import { compact, optionalTarget, resolveTarget } from "./targets.js";
2
- import { captureScreenshot } from "./screenshot.js";
3
-
4
- const SESSION_STOP_TIMEOUT_MS = 3_600_000;
5
-
6
- // BrowserSkill 0.4 refuses a page action (cooperation_sync_required) unless it
7
- // carries the single-use context_id of the latest tool.cooperate sync, and the
8
- // daemon never fills it in for the caller. Any other key left over after a method's own options
9
- // is a misspelling (for example `contextId`) that would otherwise send no context, so it throws.
10
- function sharedTab({ context, dependsOn, ...unknown }) {
11
- const extra = Object.keys(unknown);
12
- if (extra.length > 0) {
13
- throw new TypeError(`unknown option ${extra.map((key) => JSON.stringify(key)).join(", ")}: a shared-tab action takes { context, dependsOn } besides its own options`);
14
- }
15
- return { context_id: context, depends_on: dependsOn };
16
- }
17
-
18
- export class BskSession {
19
- #client; #stopped = false;
20
-
21
- constructor(client, { sessionId, browserInstanceId = null, agentWindowId = null, interaction = null } = {}) {
22
- if (typeof sessionId !== "string" || sessionId.length === 0) throw new TypeError("BskSession requires a sessionId");
23
- this.#client = client;
24
- this.sessionId = sessionId;
25
- this.browserInstanceId = browserInstanceId;
26
- this.agentWindowId = agentWindowId;
27
- this.interaction = interaction;
28
- }
29
-
30
- get client() { return this.#client; }
31
- get stopped() { return this.#stopped; }
32
-
33
- tool(name, params = {}) {
34
- if (this.#stopped) return Promise.reject(new Error(`BrowserSkill session ${this.sessionId} is stopped`));
35
- return this.#client.call(`tool.${name}`, compact({ session_id: this.sessionId, ...params }), { idPrefix: name.replace(/_/g, "-") });
36
- }
37
-
38
- cooperate(action, { tabId, timeoutMs, maxTokens } = {}) {
39
- return this.tool("cooperate", { action, tab_id: tabId, timeout_ms: timeoutMs, max_tokens: maxTokens });
40
- }
41
-
42
- navigate(url, { tabId, waitUntil, timeoutMs, ...shared } = {}) {
43
- return this.tool("navigate", { url, tab_id: tabId, wait_until: waitUntil, timeout_ms: timeoutMs, ...sharedTab(shared) });
44
- }
45
- back({ tabId, waitUntil, timeoutMs, ...shared } = {}) {
46
- return this.tool("navigate_back", { tab_id: tabId, wait_until: waitUntil, timeout_ms: timeoutMs, ...sharedTab(shared) });
47
- }
48
- forward({ tabId, waitUntil, timeoutMs, ...shared } = {}) {
49
- return this.tool("navigate_forward", { tab_id: tabId, wait_until: waitUntil, timeout_ms: timeoutMs, ...sharedTab(shared) });
50
- }
51
- reload({ tabId, waitUntil, timeoutMs, hard, ...shared } = {}) {
52
- return this.tool("reload", { tab_id: tabId, wait_until: waitUntil, timeout_ms: timeoutMs, hard, ...sharedTab(shared) });
53
- }
54
-
55
- observe({ cursor, tabId, maxDepth, maxTokens, debugSurfaces, probeHover, ...shared } = {}) {
56
- return this.tool("observe", { cursor, tab_id: tabId, max_depth: maxDepth, max_tokens: maxTokens, debug_surfaces: debugSurfaces, probe_hover: probeHover, ...sharedTab(shared) });
57
- }
58
- snapshot({ tabId, maxDepth, maxTokens } = {}) {
59
- return this.tool("snapshot", { tab_id: tabId, max_depth: maxDepth, max_tokens: maxTokens });
60
- }
61
- getHtml({ ref, tabId, maxBytes } = {}) {
62
- return this.tool("get_html", { ref, tab_id: tabId, max_bytes: maxBytes });
63
- }
64
- screenshot(options) { return captureScreenshot(this, options); }
65
-
66
- click(target, { button, clickCount, modifiers, tabId, timeoutMs, ...shared } = {}) {
67
- return this.tool("click", { ...resolveTarget(target), button, click_count: clickCount, modifiers, tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
68
- }
69
- hover(target, { modifiers, settleMs, tabId, timeoutMs, ...shared } = {}) {
70
- return this.tool("hover", { ...resolveTarget(target), modifiers, settle_ms: settleMs, tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
71
- }
72
- focus(target, { tabId, timeoutMs, ...shared } = {}) {
73
- return this.tool("focus", { ...resolveTarget(target), tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
74
- }
75
- blur(target, { tabId, timeoutMs, ...shared } = {}) {
76
- return this.tool("blur", { ...resolveTarget(target), tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
77
- }
78
- fill(target, value, { clearBefore, tabId, timeoutMs, ...shared } = {}) {
79
- return this.tool("fill", { ...resolveTarget(target), value, clear_before: clearBefore, tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
80
- }
81
- press(key, { target, modifiers, holdMs, tabId, timeoutMs, ...shared } = {}) {
82
- return this.tool("press", { key, ...optionalTarget(target), modifiers, hold_ms: holdMs, tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
83
- }
84
- select(target, values, { tabId, timeoutMs, ...shared } = {}) {
85
- return this.tool("select", { ...resolveTarget(target), values: Array.isArray(values) ? values : [values], tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
86
- }
87
- scrollTo(target, { tabId, timeoutMs, ...shared } = {}) {
88
- return this.tool("scroll_to", { ...resolveTarget(target), tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
89
- }
90
- wheel({ deltaX = 0, deltaY = 0, target, modifiers, tabId, timeoutMs, ...shared } = {}) {
91
- return this.tool("wheel", { ...optionalTarget(target), delta_x: deltaX, delta_y: deltaY, modifiers, tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
92
- }
93
-
94
- evaluate(expression, { tabId, awaitPromise, returnByValue, timeoutMs, ...shared } = {}) {
95
- return this.tool("evaluate", { expression, tab_id: tabId, await_promise: awaitPromise, return_by_value: returnByValue, timeout_ms: timeoutMs, ...sharedTab(shared) });
96
- }
97
-
98
- tabList({ scope } = {}) { return this.tool("tab_list", { scope }); }
99
- tabCreate({ url, active, index } = {}) { return this.tool("tab_create", { url, active, index }); }
100
- tabClose(tabId, shared = {}) { return this.tool("tab_close", { tab_id: tabId, ...sharedTab(shared) }); }
101
- tabSelect(tabId) { return this.tool("tab_select", { tab_id: tabId }); }
102
- tabBorrow(tabId, { confirmationTimeoutMs } = {}) {
103
- return this.tool("tab_borrow", { tab_id: tabId, confirmation_timeout_ms: confirmationTimeoutMs });
104
- }
105
- tabReturn(tabId) { return this.tool("tab_return", { tab_id: tabId }); }
106
-
107
- waitForNavigation({ tabId, waitUntil, timeoutMs } = {}) {
108
- return this.tool("wait_for_navigation", { tab_id: tabId, wait_until: waitUntil, timeout_ms: timeoutMs });
109
- }
110
- requestHelp({ prompt, title, targets, completionCriteria, tabId, timeoutMs } = {}) {
111
- return this.tool("request_help", {
112
- prompt, title, tab_id: tabId, timeout_ms: timeoutMs,
113
- targets: targets?.map((t) => resolveTarget(t)),
114
- completion_criteria: completionCriteria,
115
- });
116
- }
117
- console({ tabId, since, limit, maxTextChars, includeStack } = {}) {
118
- return this.tool("console", { tab_id: tabId, since, limit, max_text_chars: maxTextChars, include_stack: includeStack });
119
- }
120
- network({ tabId, since, limit, maxTextChars } = {}) {
121
- return this.tool("network", { tab_id: tabId, since, limit, max_text_chars: maxTextChars });
122
- }
123
- resize(width, height, shared = {}) { return this.tool("window_resize", { width, height, ...sharedTab(shared) }); }
124
- emulate({ tabId, off, overrides, ...shared } = {}) { return this.tool("emulate", { tab_id: tabId, off, overrides, ...sharedTab(shared) }); }
125
-
126
- async stop() {
127
- if (this.#stopped) return null;
128
- this.#stopped = true;
129
- return this.#client.call("session.stop", { session_id: this.sessionId }, { idPrefix: "session-stop", timeoutMs: SESSION_STOP_TIMEOUT_MS });
130
- }
131
- }
@@ -1,56 +0,0 @@
1
- // OmOWright-style {tree, refs} snapshot from a BrowserSkill session without
2
- // leaving a trace in the page: the page bundle assigns `globalThis.__omowright`
3
- // exactly once, so shadowing `globalThis` with a local object keeps the real
4
- // window untouched, and the css paths let a ref be clicked through the
5
- // daemon's `selector` target (no DOM attribute is written).
6
- import { pageBundle } from "../injected.js";
7
-
8
- const CSS_PATH_FN = String(function cssPath(el) {
9
- if (!(el instanceof Element)) return null;
10
- if (el.getRootNode() !== document) return null;
11
- const parts = [];
12
- let node = el;
13
- while (node && node.nodeType === 1 && node !== document.documentElement) {
14
- let part = node.localName;
15
- if (node.id && /^[A-Za-z_][\w-]*$/.test(node.id) && document.querySelectorAll("#" + node.id).length === 1) {
16
- parts.unshift("#" + node.id);
17
- return parts.join(" > ");
18
- }
19
- const parent = node.parentElement;
20
- if (parent) {
21
- const same = Array.from(parent.children).filter((c) => c.localName === node.localName);
22
- if (same.length > 1) part += `:nth-of-type(${same.indexOf(node) + 1})`;
23
- }
24
- parts.unshift(part);
25
- node = parent;
26
- }
27
- parts.unshift("html");
28
- return parts.join(" > ");
29
- });
30
-
31
- export function buildSnapshotExpression(options = {}) {
32
- return `(function () {
33
- const globalThis = {};
34
- ${pageBundle}
35
- const api = globalThis.__omowright;
36
- const result = api.takeSnapshot(${JSON.stringify(options)});
37
- const cssPath = ${CSS_PATH_FN};
38
- const css = {};
39
- for (const ref of Object.keys(result.refs || {})) css[ref] = cssPath(api.elementRegistry.get(ref));
40
- return { tree: result.tree, refs: result.refs || {}, css, error: result.error };
41
- })()`;
42
- }
43
-
44
- export async function bskSnapshot(session, { tabId, timeoutMs, context, dependsOn, ...snapshotOptions } = {}) {
45
- const reply = await session.evaluate(buildSnapshotExpression(snapshotOptions), {
46
- tabId, timeoutMs, context, dependsOn, awaitPromise: false, returnByValue: true,
47
- });
48
- if (!reply || reply.ok === false) {
49
- const text = reply?.error?.text ?? "unknown error";
50
- throw new Error(`bskSnapshot failed inside the page: ${text}`);
51
- }
52
- const value = reply.value;
53
- if (!value || typeof value.tree !== "string") throw new Error("bskSnapshot: page returned no tree");
54
- if (value.error) throw new Error(`bskSnapshot: ${value.error}`);
55
- return { tree: value.tree, refs: value.refs, css: value.css };
56
- }
@@ -1,25 +0,0 @@
1
- const REF_SHAPE = /^@?e\d+$/;
2
-
3
- export function resolveTarget(target) {
4
- if (typeof target === "string") {
5
- return REF_SHAPE.test(target) ? { ref: target } : { selector: target };
6
- }
7
- if (target && typeof target === "object") {
8
- if (typeof target.ref === "string") return { ref: target.ref };
9
- if (typeof target.selector === "string") return { selector: target.selector };
10
- if (typeof target.captureId === "string") {
11
- return { capture_id: target.captureId, image_x: target.x, image_y: target.y };
12
- }
13
- }
14
- throw new TypeError("target must be a ref ('e3' / '@e3'), a CSS selector, or {captureId, x, y}");
15
- }
16
-
17
- export function optionalTarget(target) {
18
- return target === undefined ? {} : resolveTarget(target);
19
- }
20
-
21
- export function compact(params) {
22
- const out = {};
23
- for (const [key, value] of Object.entries(params)) if (value !== undefined) out[key] = value;
24
- return out;
25
- }
@@ -1,79 +0,0 @@
1
- const MAX_TIMER_MS = 2147483647;
2
- const STOP = Symbol("wait stopped");
3
-
4
- export async function waitForCaptcha(page, {
5
- until, timeoutMs = 10000, pollMs = 100, signal,
6
- } = {}) {
7
- if (typeof until !== "function") throw new TypeError("until must be a function");
8
- if (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > MAX_TIMER_MS) {
9
- throw new RangeError("timeoutMs must be between 0 and 2147483647");
10
- }
11
- if (!Number.isFinite(pollMs) || pollMs <= 0 || pollMs > MAX_TIMER_MS) {
12
- throw new RangeError("pollMs must be greater than 0 and at most 2147483647");
13
- }
14
- if (signal !== undefined && (typeof signal?.aborted !== "boolean"
15
- || typeof signal.addEventListener !== "function" || typeof signal.removeEventListener !== "function")) {
16
- throw new TypeError("signal must be AbortSignal-compatible");
17
- }
18
-
19
- const started = performance.now();
20
- const deadline = started + timeoutMs;
21
- const operation = new AbortController();
22
- let deadlineTimer;
23
- let pollTimer;
24
- let stop;
25
- const stopped = new Promise(resolve => { stop = () => resolve(STOP); });
26
- const terminal = () => signal?.aborted ? "cancelled"
27
- : performance.now() >= deadline ? "timed_out" : null;
28
- const result = outcome => ({ outcome, elapsedMs: performance.now() - started });
29
- const scheduleDeadline = () => {
30
- const remaining = deadline - performance.now();
31
- if (remaining <= 0) stop();
32
- else deadlineTimer = setTimeout(scheduleDeadline, Math.ceil(remaining));
33
- };
34
-
35
- try {
36
- const initial = terminal();
37
- if (initial) return result(initial);
38
- signal?.addEventListener("abort", stop, { once: true });
39
- scheduleDeadline();
40
- // The first evaluation only yields to cancellation: a scheduling stall
41
- // between the call and this microtask must not time the wait out unevaluated.
42
- let evaluated = false;
43
- for (;;) {
44
- let accepted;
45
- try {
46
- // Promise.race keeps a rejection handler on a non-cooperative predicate
47
- // even after this wait has timed out or been cancelled.
48
- accepted = await Promise.race([
49
- Promise.resolve().then(() => (evaluated ? terminal() : signal?.aborted)
50
- ? STOP : until(page, { signal: operation.signal })),
51
- stopped,
52
- ]);
53
- } catch (error) {
54
- const outcome = terminal();
55
- if (outcome) return result(outcome);
56
- throw error;
57
- }
58
- evaluated = true;
59
- const outcome = terminal();
60
- if (outcome) return result(outcome);
61
- if (accepted === true) return result("matched");
62
- await Promise.race([
63
- new Promise(resolve => {
64
- pollTimer = setTimeout(resolve, Math.ceil(Math.min(pollMs, deadline - performance.now())));
65
- }),
66
- stopped,
67
- ]);
68
- clearTimeout(pollTimer);
69
- const afterDelay = terminal();
70
- if (afterDelay) return result(afterDelay);
71
- }
72
- } finally {
73
- clearTimeout(deadlineTimer);
74
- clearTimeout(pollTimer);
75
- signal?.removeEventListener("abort", stop);
76
- operation.abort();
77
- stop();
78
- }
79
- }
package/src/captcha.js DELETED
@@ -1,142 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import path from "node:path";
5
- import { compactSnapshot } from "./llm.js";
6
- import { waitForCaptcha } from "./captcha-wait.js";
7
-
8
- const DEFAULT_DRAG_STEPS = 20;
9
- const POST_ACTION_SETTLE_MS = 3000;
10
-
11
- function validatePoint(point) {
12
- if (!Number.isFinite(point?.x) || !Number.isFinite(point?.y)) {
13
- throw new TypeError("point coordinates must be finite numbers");
14
- }
15
- }
16
-
17
- function validateSteps(steps) {
18
- if (!Number.isSafeInteger(steps) || steps <= 0) {
19
- throw new RangeError("steps must be a positive safe integer");
20
- }
21
- }
22
-
23
- function validateSettleMs(value) {
24
- if (!Number.isFinite(value) || value < 0 || value > 2147483647) {
25
- throw new RangeError("settleMs must be between 0 and 2147483647");
26
- }
27
- }
28
-
29
- const MACOS_VISION_OCR_SWIFT = `
30
- import Vision
31
- import AppKit
32
- let path = CommandLine.arguments[1]
33
- guard let nsImage = NSImage(contentsOfFile: path),
34
- let cgImage = nsImage.cgImage(forProposedRect: nil, context: nil, hints: nil) else { exit(2) }
35
- let request = VNRecognizeTextRequest()
36
- request.recognitionLevel = .accurate
37
- request.usesLanguageCorrection = false
38
- let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
39
- do { try handler.perform([request]) } catch { exit(3) }
40
- let text = (request.results ?? [])
41
- .compactMap { $0.topCandidates(1).first?.string }
42
- .joined(separator: " ")
43
- print(text)
44
- `;
45
-
46
- export async function macOSVisionOcr(pngBuffer) {
47
- if (process.platform !== "darwin") {
48
- throw new Error("macOSVisionOcr is only available on macOS; pass a custom ocr(buffer) instead");
49
- }
50
- const dir = mkdtempSync(path.join(tmpdir(), "omowright-ocr-"));
51
- try {
52
- const imagePath = path.join(dir, "region.png");
53
- const scriptPath = path.join(dir, "ocr.swift");
54
- writeFileSync(imagePath, pngBuffer);
55
- writeFileSync(scriptPath, MACOS_VISION_OCR_SWIFT);
56
- return await new Promise((resolve, reject) => {
57
- const child = spawn("swift", [scriptPath, imagePath], { stdio: ["ignore", "pipe", "pipe"] });
58
- let stdout = "";
59
- let stderr = "";
60
- child.stdout.on("data", chunk => { stdout += chunk; });
61
- child.stderr.on("data", chunk => { stderr += chunk; });
62
- child.on("error", reject);
63
- child.on("close", code => {
64
- if (code === 0) {
65
- const text = stdout.trim();
66
- resolve(text.length > 0 ? text : null);
67
- } else {
68
- reject(new Error(`Vision OCR failed (exit ${code}): ${stderr.trim()}`));
69
- }
70
- });
71
- });
72
- } finally {
73
- rmSync(dir, { recursive: true, force: true });
74
- }
75
- }
76
-
77
- export function createCaptcha(page, options = {}) {
78
- const ocr = options.ocr ?? macOSVisionOcr;
79
-
80
- function centerOf(bounds) {
81
- validatePoint(bounds);
82
- if (!Number.isFinite(bounds.width) || bounds.width <= 0
83
- || !Number.isFinite(bounds.height) || bounds.height <= 0
84
- || !Number.isFinite(bounds.x + bounds.width) || !Number.isFinite(bounds.y + bounds.height)) {
85
- throw new RangeError("bounds must have positive finite dimensions and finite edges");
86
- }
87
- return { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };
88
- }
89
-
90
- async function settleAndSnapshot(settleMs) {
91
- await new Promise(resolve => setTimeout(resolve, settleMs));
92
- return compactSnapshot(await page.snapshot());
93
- }
94
-
95
- return {
96
- page,
97
-
98
- waitFor(opts) {
99
- return waitForCaptcha(page, opts);
100
- },
101
-
102
- async click(bounds, opts = {}) {
103
- const center = centerOf(bounds);
104
- const point = opts.point === undefined ? center : opts.point;
105
- validatePoint(point);
106
- if (point.x < bounds.x || point.x >= bounds.x + bounds.width
107
- || point.y < bounds.y || point.y >= bounds.y + bounds.height) {
108
- throw new RangeError("point must be inside bounds");
109
- }
110
- const settleMs = opts.settleMs === undefined ? POST_ACTION_SETTLE_MS : opts.settleMs;
111
- validateSettleMs(settleMs);
112
- if (opts.approachSteps !== undefined) {
113
- validateSteps(opts.approachSteps);
114
- await page.mouse.move(point.x, point.y, { steps: opts.approachSteps });
115
- }
116
- await page.mouse.click(point.x, point.y);
117
- return settleAndSnapshot(settleMs);
118
- },
119
-
120
- async drag(from, to, opts = {}) {
121
- validatePoint(from);
122
- validatePoint(to);
123
- const steps = opts.steps === undefined ? DEFAULT_DRAG_STEPS : opts.steps;
124
- validateSteps(steps);
125
- const settleMs = opts.settleMs === undefined ? POST_ACTION_SETTLE_MS : opts.settleMs;
126
- validateSettleMs(settleMs);
127
- await page.mouse.move(from.x, from.y);
128
- await page.mouse.down();
129
- try {
130
- await page.mouse.move(to.x, to.y, { steps });
131
- } finally {
132
- await page.mouse.up();
133
- }
134
- return settleAndSnapshot(settleMs);
135
- },
136
-
137
- async readText(bounds) {
138
- const buffer = await page.screenshot(bounds ? { type: "png", clip: bounds } : { type: "png" });
139
- return ocr(buffer);
140
- },
141
- };
142
- }
package/src/cdp-errors.js DELETED
@@ -1,23 +0,0 @@
1
- class CdpCommandError extends Error {
2
- constructor(name, message, details) {
3
- super(message);
4
- Object.assign(this, details);
5
- this.name = name;
6
- }
7
- }
8
-
9
- export class CdpCommandTimeoutError extends CdpCommandError {
10
- constructor(message, details) { super("CdpCommandTimeoutError", message, details); }
11
- }
12
-
13
- export class CdpPipeClosedError extends CdpCommandError {
14
- constructor(message, details) { super("CdpPipeClosedError", message, details); }
15
- }
16
-
17
- export class CdpSessionDetachedError extends CdpCommandError {
18
- constructor(message, details) { super("CdpSessionDetachedError", message, details); }
19
- }
20
-
21
- export class CdpSessionCrashedError extends CdpCommandError {
22
- constructor(message, details) { super("CdpSessionCrashedError", message, details); }
23
- }