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,49 @@
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
+ }
@@ -0,0 +1,131 @@
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
+ }
@@ -0,0 +1,56 @@
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
+ }
@@ -0,0 +1,25 @@
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
+ }
@@ -0,0 +1,74 @@
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
+ for (;;) {
41
+ let accepted;
42
+ try {
43
+ // Promise.race keeps a rejection handler on a non-cooperative predicate
44
+ // even after this wait has timed out or been cancelled.
45
+ accepted = await Promise.race([
46
+ Promise.resolve().then(() => terminal() ? STOP : until(page, { signal: operation.signal })),
47
+ stopped,
48
+ ]);
49
+ } catch (error) {
50
+ const outcome = terminal();
51
+ if (outcome) return result(outcome);
52
+ throw error;
53
+ }
54
+ const outcome = terminal();
55
+ if (outcome) return result(outcome);
56
+ if (accepted === true) return result("matched");
57
+ await Promise.race([
58
+ new Promise(resolve => {
59
+ pollTimer = setTimeout(resolve, Math.ceil(Math.min(pollMs, deadline - performance.now())));
60
+ }),
61
+ stopped,
62
+ ]);
63
+ clearTimeout(pollTimer);
64
+ const afterDelay = terminal();
65
+ if (afterDelay) return result(afterDelay);
66
+ }
67
+ } finally {
68
+ clearTimeout(deadlineTimer);
69
+ clearTimeout(pollTimer);
70
+ signal?.removeEventListener("abort", stop);
71
+ operation.abort();
72
+ stop();
73
+ }
74
+ }
package/src/captcha.js ADDED
@@ -0,0 +1,142 @@
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
+ }
@@ -0,0 +1,23 @@
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
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Every CDP command the page path sends (`connect()`, the page API, frame snapshots, agent tabs and their viewport
3
+ * pin). A scoped endpoint can allow exactly these and refuse the rest. Optional modules send more and need a full
4
+ * endpoint: routes, emulation, cookies, `createEvents()` (`Browser.setDownloadBehavior`), the
5
+ * bridge and `connectPipe`. `test/scoped-endpoint.test.mjs` runs navigate, snapshot, fill, click, evaluate,
6
+ * screenshot and agent tabs through such an endpoint; the other listed methods (PDF, history, reload, dialogs, file
7
+ * upload, screencast, lifecycle) are listed from the source, not exercised there. No cookie read is listed: an
8
+ * endpoint must refuse `Network.getCookies` rather than answer it without its `urls` filter.
9
+ */
10
+ export const OMOWRIGHT_PAGE_CDP_METHODS = Object.freeze([
11
+ "Browser.getVersion",
12
+ "DOM.describeNode",
13
+ "DOM.enable",
14
+ "DOM.getBoxModel",
15
+ "DOM.getContentQuads",
16
+ "DOM.getDocument",
17
+ "DOM.querySelectorAll",
18
+ "DOM.resolveNode",
19
+ "DOM.scrollIntoViewIfNeeded",
20
+ "DOM.setFileInputFiles",
21
+ "Emulation.setDeviceMetricsOverride",
22
+ "Emulation.setFocusEmulationEnabled",
23
+ "Input.dispatchKeyEvent",
24
+ "Input.dispatchMouseEvent",
25
+ "Input.insertText",
26
+ "Inspector.enable",
27
+ "Network.disable",
28
+ "Network.enable",
29
+ "Network.getResponseBody",
30
+ "Page.addScriptToEvaluateOnNewDocument",
31
+ "Page.captureScreenshot",
32
+ "Page.close",
33
+ "Page.createIsolatedWorld",
34
+ "Page.enable",
35
+ "Page.getFrameTree",
36
+ "Page.getLayoutMetrics",
37
+ "Page.getNavigationHistory",
38
+ "Page.handleJavaScriptDialog",
39
+ "Page.navigate",
40
+ "Page.navigateToHistoryEntry",
41
+ "Page.printToPDF",
42
+ "Page.reload",
43
+ "Page.removeScriptToEvaluateOnNewDocument",
44
+ "Page.screencastFrameAck",
45
+ "Page.setInterceptFileChooserDialog",
46
+ "Page.setWebLifecycleState",
47
+ "Page.startScreencast",
48
+ "Page.stopScreencast",
49
+ "Runtime.callFunctionOn",
50
+ "Runtime.evaluate",
51
+ "Runtime.releaseObject",
52
+ "Target.activateTarget",
53
+ "Target.attachToTarget",
54
+ "Target.closeTarget",
55
+ "Target.createTarget",
56
+ "Target.detachFromTarget",
57
+ "Target.getTargetInfo",
58
+ "Target.getTargets",
59
+ "Target.setAutoAttach",
60
+ "Target.setDiscoverTargets",
61
+ ]);