omowright 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +290 -2
  3. package/TOOLS.md +487 -0
  4. package/bin/omowright-cloak.mjs +112 -0
  5. package/package.json +57 -4
  6. package/presets/agent-events/SKILL.md +75 -0
  7. package/presets/captcha/SKILL.md +129 -0
  8. package/presets/chrome/SKILL.md +88 -0
  9. package/presets/cloak-bridge/SKILL.md +43 -0
  10. package/presets/network/SKILL.md +126 -0
  11. package/presets/visual-browse/SKILL.md +103 -0
  12. package/skills/omowright/SKILL.md +193 -0
  13. package/skills/omowright/references/1password.md +118 -0
  14. package/skills/omowright/references/browserskill.md +195 -0
  15. package/skills/omowright/references/eval-kernel.md +100 -0
  16. package/skills/omowright/references/frames-layers-human.md +123 -0
  17. package/skills/omowright/references/quickstart.md +109 -0
  18. package/skills/omowright/references/stealth.md +174 -0
  19. package/src/agent-tabs.js +179 -0
  20. package/src/aria-hidden.js +47 -0
  21. package/src/bridge-schemas.js +44 -0
  22. package/src/bridge-transport.js +83 -0
  23. package/src/browser-context.js +105 -0
  24. package/src/browser-process.js +127 -0
  25. package/src/bsk/browser-signals.js +90 -0
  26. package/src/bsk/browsers.js +114 -0
  27. package/src/bsk/connect.js +75 -0
  28. package/src/bsk/daemon-info.js +100 -0
  29. package/src/bsk/external-extension.js +110 -0
  30. package/src/bsk/identify-browser.js +88 -0
  31. package/src/bsk/install-cli.js +81 -0
  32. package/src/bsk/ipc-client.js +236 -0
  33. package/src/bsk/onboard.js +140 -0
  34. package/src/bsk/screenshot.js +49 -0
  35. package/src/bsk/session.js +131 -0
  36. package/src/bsk/snapshot.js +56 -0
  37. package/src/bsk/targets.js +25 -0
  38. package/src/captcha-wait.js +79 -0
  39. package/src/captcha.js +142 -0
  40. package/src/cdp-errors.js +23 -0
  41. package/src/cdp-methods.js +69 -0
  42. package/src/chrome-profile.js +176 -0
  43. package/src/chrome.js +194 -0
  44. package/src/cloak-profile.js +266 -0
  45. package/src/connection.js +234 -0
  46. package/src/console-events.js +12 -0
  47. package/src/cookies.js +39 -0
  48. package/src/core.js +1702 -0
  49. package/src/cua.js +74 -0
  50. package/src/dialog-policy.js +80 -0
  51. package/src/emulate.js +127 -0
  52. package/src/events.js +111 -0
  53. package/src/frames-snapshot.js +138 -0
  54. package/src/har.js +103 -0
  55. package/src/human-handoff.js +124 -0
  56. package/src/index.js +89 -0
  57. package/src/injected.js +3 -0
  58. package/src/instance-lock.js +74 -0
  59. package/src/instances.js +490 -0
  60. package/src/internal-capability.js +1 -0
  61. package/src/launch-endpoint.js +185 -0
  62. package/src/layers.js +138 -0
  63. package/src/llm.js +201 -0
  64. package/src/lock-backend-win32.js +54 -0
  65. package/src/lock-backend.js +81 -0
  66. package/src/native-host-win32.js +201 -0
  67. package/src/network-events.js +223 -0
  68. package/src/network-snoop.js +229 -0
  69. package/src/nul-frames.js +28 -0
  70. package/src/open-shadow-query.js +101 -0
  71. package/src/owner-only.js +196 -0
  72. package/src/page-bundle.js +1478 -0
  73. package/src/page-events.js +45 -0
  74. package/src/page-routes.js +94 -0
  75. package/src/page-setup.js +239 -0
  76. package/src/pipe.js +418 -0
  77. package/src/process-start-time.js +64 -0
  78. package/src/routes.js +256 -0
  79. package/src/running-browser.js +85 -0
  80. package/src/scroll-collect.js +73 -0
  81. package/src/serial-emitter.js +17 -0
  82. package/src/shared-connections.js +285 -0
  83. package/src/snapshot-diff.js +75 -0
  84. package/src/text-matching.js +101 -0
  85. package/src/trace.js +183 -0
  86. package/src/url-match.js +148 -0
  87. package/src/viewport.js +12 -0
@@ -0,0 +1,79 @@
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 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,69 @@
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
+ "Emulation.setEmulatedMedia",
24
+ "Input.dispatchKeyEvent",
25
+ "Input.dispatchMouseEvent",
26
+ "Input.insertText",
27
+ "Inspector.enable",
28
+ "Network.disable",
29
+ "Network.enable",
30
+ "Network.getResponseBody",
31
+ "Network.setExtraHTTPHeaders",
32
+ "Page.addScriptToEvaluateOnNewDocument",
33
+ "Page.captureScreenshot",
34
+ "Page.close",
35
+ "Page.createIsolatedWorld",
36
+ "Page.enable",
37
+ "Page.getFrameTree",
38
+ "Page.getLayoutMetrics",
39
+ "Page.getNavigationHistory",
40
+ "Page.handleJavaScriptDialog",
41
+ "Page.navigate",
42
+ "Page.navigateToHistoryEntry",
43
+ "Page.printToPDF",
44
+ "Page.reload",
45
+ "Page.removeScriptToEvaluateOnNewDocument",
46
+ "Page.screencastFrameAck",
47
+ "Page.setInterceptFileChooserDialog",
48
+ "Page.setWebLifecycleState",
49
+ "Page.startScreencast",
50
+ "Page.stopScreencast",
51
+ "Runtime.callFunctionOn",
52
+ "Runtime.addBinding",
53
+ "Runtime.disable",
54
+ "Runtime.discardConsoleEntries",
55
+ "Runtime.enable",
56
+ "Runtime.evaluate",
57
+ "Runtime.releaseObject",
58
+ "Runtime.removeBinding",
59
+ "Runtime.runIfWaitingForDebugger",
60
+ "Target.activateTarget",
61
+ "Target.attachToTarget",
62
+ "Target.closeTarget",
63
+ "Target.createTarget",
64
+ "Target.detachFromTarget",
65
+ "Target.getTargetInfo",
66
+ "Target.getTargets",
67
+ "Target.setAutoAttach",
68
+ "Target.setDiscoverTargets",
69
+ ]);
@@ -0,0 +1,176 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { UnsupportedOperationError } from "./core.js";
4
+
5
+ let DatabaseCtor;
6
+ async function loadSqlite() {
7
+ if (DatabaseCtor) return DatabaseCtor;
8
+ try {
9
+ const mod = await import("node:sqlite");
10
+ DatabaseCtor = file => new mod.DatabaseSync(file, { readOnly: true, readBigInts: true });
11
+ } catch {
12
+ const mod = await import("bun:sqlite");
13
+ DatabaseCtor = file => new mod.Database(file, { readonly: true });
14
+ }
15
+ return DatabaseCtor;
16
+ }
17
+
18
+ const CHROME_EPOCH_OFFSET_MS = 11_644_473_600_000;
19
+ const chromeTimeToMs = time => Number(BigInt(time) / 1000n) - CHROME_EPOCH_OFFSET_MS;
20
+ const msToChromeTime = ms => BigInt(Math.floor((ms + CHROME_EPOCH_OFFSET_MS) * 1000));
21
+
22
+ export { chromeTimeToMs };
23
+
24
+ const EXTENSION_BRIDGE_REQUIRED = "requires the extension bridge in standalone OmOWright";
25
+
26
+ export function createProfileApis(profilePath) {
27
+ function profileDir() {
28
+ if (!profilePath) {
29
+ throw new UnsupportedOperationError(
30
+ "chrome.bookmarks/history/topSites need a profilePath (the browser's user-data-dir); pass it to createChromeApi(connection, { profilePath })",
31
+ );
32
+ }
33
+ return path.join(profilePath, "Default");
34
+ }
35
+
36
+ async function openDb(fileName) {
37
+ const file = path.join(profileDir(), fileName);
38
+ if (!existsSync(file)) return null;
39
+ const ctor = await loadSqlite();
40
+ return ctor(file);
41
+ }
42
+
43
+ async function withDb(fileName, fn) {
44
+ const db = await openDb(fileName);
45
+ if (!db) return [];
46
+ try {
47
+ return fn(db);
48
+ } finally {
49
+ db.close();
50
+ }
51
+ }
52
+
53
+ function bookmarkRoots() {
54
+ const file = path.join(profileDir(), "Bookmarks");
55
+ if (!existsSync(file)) return [];
56
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
57
+ return Object.values(parsed.roots ?? {}).filter(node => node && typeof node === "object" && node.id);
58
+ }
59
+
60
+ function walkBookmarks(nodes, visit, acc = []) {
61
+ for (const node of nodes) {
62
+ visit(node, acc);
63
+ if (Array.isArray(node.children)) walkBookmarks(node.children, visit, acc);
64
+ }
65
+ return acc;
66
+ }
67
+
68
+ function findBookmark(id) {
69
+ for (const root of bookmarkRoots()) {
70
+ const found = walkBookmarks([root], (node, acc) => {
71
+ if (node.id === String(id)) acc.push(node);
72
+ });
73
+ if (found.length > 0) return found[0];
74
+ }
75
+ return null;
76
+ }
77
+
78
+ function toBookmark(node) {
79
+ const out = { id: node.id, title: node.name ?? "", type: node.type };
80
+ if (node.url) out.url = node.url;
81
+ if (node.date_added) out.dateAdded = chromeTimeToMs(node.date_added);
82
+ if (node.children) out.children = node.children.map(toBookmark);
83
+ return out;
84
+ }
85
+
86
+ const bookmarks = {
87
+ async get(idOrIdList) {
88
+ const ids = Array.isArray(idOrIdList) ? idOrIdList : [idOrIdList];
89
+ return ids.map(findBookmark).filter(Boolean).map(toBookmark);
90
+ },
91
+ async getChildren(id) {
92
+ const node = findBookmark(id);
93
+ return (node?.children ?? []).map(toBookmark);
94
+ },
95
+ async getRecent(numberOfItems) {
96
+ const urls = walkBookmarks(bookmarkRoots(), (node, acc) => {
97
+ if (node.type === "url") acc.push(node);
98
+ });
99
+ return urls
100
+ .sort((a, b) => Number(b.date_added ?? 0) - Number(a.date_added ?? 0))
101
+ .slice(0, numberOfItems)
102
+ .map(toBookmark);
103
+ },
104
+ async getSubTree(id) {
105
+ const node = findBookmark(id);
106
+ return node ? [toBookmark(node)] : [];
107
+ },
108
+ async getTree() {
109
+ return bookmarkRoots().map(toBookmark);
110
+ },
111
+ async search(query) {
112
+ const needle = typeof query === "string" ? query.toLowerCase() : (query.query ?? "").toLowerCase();
113
+ const url = typeof query === "object" ? query.url?.toLowerCase() : undefined;
114
+ const title = typeof query === "object" ? query.title?.toLowerCase() : undefined;
115
+ return walkBookmarks(bookmarkRoots(), (node, acc) => {
116
+ if (node.type !== "url") return;
117
+ const name = (node.name ?? "").toLowerCase();
118
+ const href = (node.url ?? "").toLowerCase();
119
+ const ok = (needle && (name.includes(needle) || href.includes(needle)))
120
+ || (url && href.includes(url))
121
+ || (title && name.includes(title));
122
+ if (ok) acc.push(node);
123
+ }).map(toBookmark);
124
+ },
125
+ async create() { throw new UnsupportedOperationError(`chrome.bookmarks.create ${EXTENSION_BRIDGE_REQUIRED}`); },
126
+ async update() { throw new UnsupportedOperationError(`chrome.bookmarks.update ${EXTENSION_BRIDGE_REQUIRED}`); },
127
+ async move() { throw new UnsupportedOperationError(`chrome.bookmarks.move ${EXTENSION_BRIDGE_REQUIRED}`); },
128
+ async remove() { throw new UnsupportedOperationError(`chrome.bookmarks.remove ${EXTENSION_BRIDGE_REQUIRED}`); },
129
+ async removeTree() { throw new UnsupportedOperationError(`chrome.bookmarks.removeTree ${EXTENSION_BRIDGE_REQUIRED}`); },
130
+ };
131
+
132
+ const history = {
133
+ async search(query) {
134
+ const text = `%${query.text ?? ""}%`;
135
+ const start = query.startTime != null ? msToChromeTime(query.startTime) : 0n;
136
+ const end = query.endTime != null ? msToChromeTime(query.endTime) : 99999999999999999n;
137
+ const max = query.maxResults ?? 100;
138
+ return (await withDb("History", db => db.prepare(
139
+ `SELECT id, url, title, visit_count, last_visit_time FROM urls
140
+ WHERE (url LIKE ? OR title LIKE ?) AND last_visit_time BETWEEN ? AND ?
141
+ ORDER BY last_visit_time DESC LIMIT ?`,
142
+ ).all(text, text, start, end, max).map(row => ({
143
+ id: String(row.id),
144
+ url: row.url,
145
+ title: row.title ?? "",
146
+ visitCount: Number(row.visit_count),
147
+ lastVisitTime: chromeTimeToMs(row.last_visit_time),
148
+ }))));
149
+ },
150
+ async getVisits(details) {
151
+ return (await withDb("History", db => db.prepare(
152
+ `SELECT v.id, v.visit_time, v.transition FROM visits v
153
+ JOIN urls u ON u.id = v.url WHERE u.url = ?
154
+ ORDER BY v.visit_time DESC`,
155
+ ).all(details.url).map(row => ({
156
+ id: String(row.id),
157
+ url: details.url,
158
+ visitTime: chromeTimeToMs(row.visit_time),
159
+ transition: Number(row.transition),
160
+ }))));
161
+ },
162
+ async addUrl() { throw new UnsupportedOperationError(`chrome.history.addUrl ${EXTENSION_BRIDGE_REQUIRED}`); },
163
+ async deleteUrl() { throw new UnsupportedOperationError(`chrome.history.deleteUrl ${EXTENSION_BRIDGE_REQUIRED}`); },
164
+ async deleteRange() { throw new UnsupportedOperationError(`chrome.history.deleteRange ${EXTENSION_BRIDGE_REQUIRED}`); },
165
+ };
166
+
167
+ const topSites = {
168
+ async get() {
169
+ return (await withDb("Top Sites", db => db.prepare(
170
+ `SELECT url, title, url_rank FROM top_sites ORDER BY url_rank ASC LIMIT 50`,
171
+ ).all())).map(row => ({ url: row.url, title: row.title ?? "" }));
172
+ },
173
+ };
174
+
175
+ return { bookmarks, history, topSites, withDb };
176
+ }
package/src/chrome.js ADDED
@@ -0,0 +1,194 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { tmpdir } from "node:os";
4
+ import { UnsupportedOperationError } from "./core.js";
5
+ import { createProfileApis, chromeTimeToMs } from "./chrome-profile.js";
6
+
7
+ const EXTENSION_BRIDGE_REQUIRED = "requires the extension bridge in standalone OmOWright";
8
+ // CDP has no window-focus state, and document.hasFocus() is no substitute: OmOWright
9
+ // enables focus emulation on every page it attaches to (other automation clients do
10
+ // too), so those pages report focus, background agent windows included (#122).
11
+ const WINDOW_FOCUS_UNKNOWN = "is unavailable in standalone OmOWright: CDP exposes no window focus state; " +
12
+ "track chrome.windows.onFocusChanged through the extension bridge instead";
13
+ const DOWNLOAD_TIMEOUT_MS = 30_000;
14
+
15
+ function matchUrlPattern(url, pattern) {
16
+ const patterns = Array.isArray(pattern) ? pattern : [pattern];
17
+ return patterns.some(item => {
18
+ if (!item.includes("*")) return url.startsWith(item);
19
+ const regex = new RegExp(`^${item.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`);
20
+ return regex.test(url);
21
+ });
22
+ }
23
+
24
+ export function createChromeApi(connection, options = {}) {
25
+ const profile = createProfileApis(options.profilePath);
26
+ const cdp = connection.cdp;
27
+
28
+ async function pageTargets() {
29
+ return (await connection.listTargets()).filter(target => target.type === "page");
30
+ }
31
+
32
+ async function toTab(target) {
33
+ let windowId = 0;
34
+ try {
35
+ const win = await cdp.send("Browser.getWindowForTarget", { targetId: target.targetId ?? target.id });
36
+ windowId = win.windowId;
37
+ } catch {}
38
+ return {
39
+ id: target.targetId ?? target.id,
40
+ url: target.url ?? "",
41
+ title: target.title ?? "",
42
+ windowId,
43
+ active: false,
44
+ pinned: false,
45
+ audible: false,
46
+ discarded: false,
47
+ groupId: -1,
48
+ index: -1,
49
+ };
50
+ }
51
+
52
+ const tabs = {
53
+ async query(queryInfo = {}) {
54
+ let targets = await pageTargets();
55
+ if (queryInfo.url) targets = targets.filter(t => matchUrlPattern(t.url ?? "", queryInfo.url));
56
+ if (queryInfo.title) targets = targets.filter(t => (t.title ?? "").includes(queryInfo.title));
57
+ const out = [];
58
+ for (const target of targets) {
59
+ const tab = await toTab(target);
60
+ if (queryInfo.windowId != null && tab.windowId !== queryInfo.windowId) continue;
61
+ out.push(tab);
62
+ }
63
+ return out;
64
+ },
65
+ async get(tabId) {
66
+ const targets = await pageTargets();
67
+ const target = targets.find(t => (t.targetId ?? t.id) === tabId);
68
+ if (!target) throw new Error(`No tab with id: ${tabId}`);
69
+ return toTab(target);
70
+ },
71
+ };
72
+
73
+ async function collectWindows(queryOptions = {}) {
74
+ const byWindow = new Map();
75
+ for (const target of await pageTargets()) {
76
+ const tab = await toTab(target);
77
+ const list = byWindow.get(tab.windowId) ?? [];
78
+ list.push(tab);
79
+ byWindow.set(tab.windowId, list);
80
+ }
81
+ return [...byWindow.entries()].map(([windowId, windowTabs]) => {
82
+ const win = {
83
+ id: windowId,
84
+ type: "normal",
85
+ state: "normal",
86
+ alwaysOnTop: false,
87
+ incognito: false,
88
+ };
89
+ if (queryOptions.populate) win.tabs = windowTabs;
90
+ return win;
91
+ });
92
+ }
93
+
94
+ const windows = {
95
+ async get(windowId, queryOptions = {}) {
96
+ const all = await collectWindows(queryOptions);
97
+ const win = all.find(item => item.id === windowId);
98
+ if (!win) throw new Error(`No window with id: ${windowId}`);
99
+ return win;
100
+ },
101
+ async getCurrent(queryOptions = {}) {
102
+ const all = await collectWindows(queryOptions);
103
+ if (all.length === 0) throw new Error("No browser window found");
104
+ return all[0];
105
+ },
106
+ async getLastFocused() {
107
+ throw new UnsupportedOperationError(`chrome.windows.getLastFocused ${WINDOW_FOCUS_UNKNOWN}`);
108
+ },
109
+ async getAll(queryOptions = {}) {
110
+ return collectWindows(queryOptions);
111
+ },
112
+ };
113
+
114
+ const downloads = {
115
+ async search(query = {}) {
116
+ return profile.withDb("History", db => {
117
+ const rows = db.prepare(
118
+ `SELECT d.id, d.target_path, d.start_time, d.received_bytes, d.total_bytes, d.state,
119
+ (SELECT url FROM downloads_url_chains c WHERE c.id = d.id AND c.chain_index = 0) AS url
120
+ FROM downloads d ORDER BY d.start_time DESC LIMIT ?`,
121
+ ).all(query.limit ?? 100);
122
+ return rows
123
+ .map(row => ({
124
+ id: Number(row.id),
125
+ url: row.url ?? "",
126
+ filename: row.target_path,
127
+ startTime: row.start_time ? new Date(chromeTimeToMs(row.start_time)).toISOString() : null,
128
+ bytesReceived: Number(row.received_bytes),
129
+ totalBytes: Number(row.total_bytes),
130
+ state: Number(row.state) === 1 ? "complete" : Number(row.state) === 2 ? "canceled" : Number(row.state) === 3 ? "interrupted" : "in_progress",
131
+ }))
132
+ .filter(item => !query.url || item.url.includes(query.url))
133
+ .filter(item => !query.filename || item.filename.includes(query.filename));
134
+ });
135
+ },
136
+
137
+ async download(downloadOptions) {
138
+ const downloadDir = options.downloadDir ?? path.join(tmpdir(), "omowright-downloads");
139
+ mkdirSync(downloadDir, { recursive: true });
140
+
141
+ let resolveBegin;
142
+ let resolveDone;
143
+ let rejectDone;
144
+ const began = new Promise(resolve => { resolveBegin = resolve; });
145
+ const done = new Promise((resolve, reject) => { resolveDone = resolve; rejectDone = reject; });
146
+ const offBegin = cdp.on("Browser.downloadWillBegin", params => resolveBegin(params));
147
+ const offProgress = cdp.on("Browser.downloadProgress", params => {
148
+ if (params.state === "completed") resolveDone(params);
149
+ else if (params.state === "canceled") rejectDone(new Error("Download was canceled"));
150
+ });
151
+ const timer = setTimeout(() => rejectDone(new Error(`chrome.downloads.download timed out after ${DOWNLOAD_TIMEOUT_MS}ms`)), DOWNLOAD_TIMEOUT_MS);
152
+
153
+ const page = await connection.newTab("about:blank");
154
+ try {
155
+ await cdp.send("Browser.setDownloadBehavior", { behavior: "allow", downloadPath: downloadDir, eventsEnabled: true });
156
+ await page.evaluate(`(() => {
157
+ const a = document.createElement("a");
158
+ a.href = ${JSON.stringify(downloadOptions.url)};
159
+ document.body.appendChild(a);
160
+ a.click();
161
+ })()`);
162
+ const begin = await Promise.race([began, done.then(() => null)]);
163
+ if (!begin) throw new Error("No download started for the given URL");
164
+ await done;
165
+ const filename = downloadOptions.filename ?? begin.suggestedFilename;
166
+ return {
167
+ id: begin.guid,
168
+ url: begin.url ?? downloadOptions.url,
169
+ filename: path.join(downloadDir, filename ?? "download"),
170
+ state: "complete",
171
+ };
172
+ } finally {
173
+ clearTimeout(timer);
174
+ offBegin();
175
+ offProgress();
176
+ await page.close().catch(() => {});
177
+ }
178
+ },
179
+
180
+ async pause() { throw new UnsupportedOperationError(`chrome.downloads.pause ${EXTENSION_BRIDGE_REQUIRED}`); },
181
+ async resume() { throw new UnsupportedOperationError(`chrome.downloads.resume ${EXTENSION_BRIDGE_REQUIRED}`); },
182
+ async cancel() { throw new UnsupportedOperationError(`chrome.downloads.cancel ${EXTENSION_BRIDGE_REQUIRED}`); },
183
+ async erase() { throw new UnsupportedOperationError(`chrome.downloads.erase ${EXTENSION_BRIDGE_REQUIRED}`); },
184
+ };
185
+
186
+ return {
187
+ tabs,
188
+ windows,
189
+ downloads,
190
+ bookmarks: profile.bookmarks,
191
+ history: profile.history,
192
+ topSites: profile.topSites,
193
+ };
194
+ }