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,185 +0,0 @@
1
- import { watch } from "node:fs";
2
- import { readFile, stat } from "node:fs/promises";
3
- import path from "node:path";
4
-
5
- // fs.watch can drop or delay directory events on a loaded host (seconds, or
6
- // never), so the file is also re-read on this interval until the launch settles.
7
- const ACTIVE_PORT_POLL_MS = 100;
8
-
9
- function httpEndpointFromWebSocket(webSocketUrl) {
10
- const endpoint = new URL(webSocketUrl);
11
- endpoint.protocol = endpoint.protocol === "wss:" ? "https:" : "http:";
12
- endpoint.pathname = "/";
13
- endpoint.search = "";
14
- endpoint.hash = "";
15
- return endpoint.toString().replace(/\/$/, "");
16
- }
17
-
18
- // Chromium writes `<port>\n/devtools/browser/<guid>`; the second line names the browser.
19
- function parseActivePort(text) {
20
- const [portLine, browserPath] = text.trim().split(/\r?\n/);
21
- const port = Number(portLine);
22
- if (!Number.isInteger(port) || port < 1 || port > 65_535) return null;
23
- return {
24
- endpoint: `http://127.0.0.1:${port}`,
25
- browserPath: browserPath?.trim() || null,
26
- };
27
- }
28
-
29
- function activePortIdentity(info) {
30
- return { ino: info.ino, mtimeMs: info.mtimeMs, size: info.size };
31
- }
32
-
33
- // A DevToolsActivePort that is already there before the spawn was written by
34
- // an earlier run or by another browser on the same profile (#74). Taken before
35
- // the spawn, so discovery can tell it from the file the new browser writes.
36
- // The bytes are kept as well as the identity: an identity change does not prove
37
- // the bytes changed (Linux updates mtime before it copies a write's data, and a
38
- // touch or an in-place rewrite moves it too), and stale bytes name another
39
- // browser whose id the launch check would then compare against itself (#107).
40
- export async function snapshotActivePort(profileDir) {
41
- if (!profileDir) return null;
42
- const activePortPath = path.join(profileDir, "DevToolsActivePort");
43
- try {
44
- const identity = activePortIdentity(await stat(activePortPath));
45
- return { ...identity, text: await readFile(activePortPath, "utf8") };
46
- } catch (error) {
47
- if (error?.code === "ENOENT") return null;
48
- throw error;
49
- }
50
- }
51
-
52
- function isSameFile(info, previous) {
53
- return (
54
- previous !== null &&
55
- info.ino === previous.ino &&
56
- info.mtimeMs === previous.mtimeMs &&
57
- info.size === previous.size
58
- );
59
- }
60
-
61
- // The endpoint is the launched browser's only if it answers with the browser id
62
- // that browser reported, and the browser is still the one we spawned.
63
- export function assertLaunchedBrowser(child, report, webSocketDebuggerUrl) {
64
- if (child.exitCode !== null || child.signalCode !== null) {
65
- throw new Error(
66
- `browser exited before its DevTools endpoint ${report.endpoint} could be verified`,
67
- );
68
- }
69
- const answered = new URL(webSocketDebuggerUrl).pathname;
70
- if (report.browserPath === null || answered !== report.browserPath) {
71
- throw new Error(
72
- `DevTools endpoint ${report.endpoint} answers as ${answered}, not as the launched browser (${report.browserPath ?? "no browser id reported"})`,
73
- );
74
- }
75
- }
76
-
77
- export async function discoverLaunchedEndpoint(
78
- child,
79
- { profileDir, timeoutMs, previousActivePort = null } = {},
80
- ) {
81
- const activePortPath = profileDir
82
- ? path.join(profileDir, "DevToolsActivePort")
83
- : null;
84
-
85
- return new Promise((resolve, reject) => {
86
- let settled = false;
87
- let stderr = "";
88
- let activePortWatcher;
89
- let activePortReading = false;
90
- let activePortChangedWhileReading = false;
91
- const cleanups = [];
92
-
93
- const finish = (error, endpoint) => {
94
- if (settled) return;
95
- settled = true;
96
- for (const cleanup of cleanups.splice(0)) cleanup();
97
- activePortWatcher?.close();
98
- if (error) reject(error);
99
- else resolve(endpoint);
100
- };
101
-
102
- const readActivePort = async () => {
103
- const info = await stat(activePortPath);
104
- if (isSameFile(activePortIdentity(info), previousActivePort)) return;
105
- const text = await readFile(activePortPath, "utf8");
106
- if (previousActivePort !== null && text === previousActivePort.text) return;
107
- const report = parseActivePort(text);
108
- if (report) finish(null, report);
109
- };
110
-
111
- const tryActivePort = async () => {
112
- if (!activePortPath || settled) return;
113
- if (activePortReading) {
114
- activePortChangedWhileReading = true;
115
- return;
116
- }
117
- activePortReading = true;
118
- try {
119
- do {
120
- activePortChangedWhileReading = false;
121
- await readActivePort();
122
- } while (activePortChangedWhileReading && !settled);
123
- } catch (error) {
124
- if (error?.code !== "ENOENT") finish(error);
125
- } finally {
126
- activePortReading = false;
127
- }
128
- };
129
-
130
- const onStderr = (chunk) => {
131
- stderr = `${stderr}${chunk}`.slice(-16_384);
132
- const match = /DevTools listening on (ws:\/\/\S+)/.exec(stderr);
133
- if (match) {
134
- finish(null, {
135
- endpoint: httpEndpointFromWebSocket(match[1]),
136
- browserPath: new URL(match[1]).pathname,
137
- });
138
- }
139
- else void tryActivePort();
140
- };
141
- const onError = (error) => finish(error);
142
- const onExit = (code, signal) => {
143
- finish(
144
- new Error(
145
- `browser exited before exposing DevTools (code ${code}, signal ${signal ?? "none"})${stderr ? `\n${stderr}` : ""}`,
146
- ),
147
- );
148
- };
149
- child.stderr.setEncoding("utf8");
150
- child.stderr.on("data", onStderr);
151
- child.once("error", onError);
152
- child.once("exit", onExit);
153
- cleanups.push(() => child.stderr.off("data", onStderr));
154
- cleanups.push(() => child.off("error", onError));
155
- cleanups.push(() => child.off("exit", onExit));
156
-
157
- if (activePortPath) {
158
- try {
159
- activePortWatcher = watch(profileDir, (event, filename) => {
160
- if (
161
- (event === "rename" || event === "change") &&
162
- (!filename ||
163
- filename.toString() === path.basename(activePortPath))
164
- ) {
165
- void tryActivePort();
166
- }
167
- });
168
- } catch (error) {
169
- if (error?.code !== "ENOENT") finish(error);
170
- }
171
- void tryActivePort();
172
- const poll = setInterval(() => void tryActivePort(), ACTIVE_PORT_POLL_MS);
173
- cleanups.push(() => clearInterval(poll));
174
- }
175
-
176
- const timeout = setTimeout(() => {
177
- finish(
178
- new Error(
179
- `browser did not expose a DevTools endpoint within ${timeoutMs}ms${stderr ? `\n${stderr}` : ""}`,
180
- ),
181
- );
182
- }, timeoutMs);
183
- cleanups.push(() => clearTimeout(timeout));
184
- });
185
- }
package/src/layers.js DELETED
@@ -1,138 +0,0 @@
1
- export async function describeLayers(page, { grid = 5 } = {}) {
2
- return page.evaluate(gridSize => {
3
- const width = Math.round(globalThis.visualViewport?.width ?? globalThis.innerWidth ?? 0);
4
- const height = Math.round(globalThis.visualViewport?.height ?? globalThis.innerHeight ?? 0);
5
- const viewport = { width, height };
6
- const total = gridSize * gridSize;
7
- const hits = new Map();
8
-
9
- function pierceTopmost(x, y) {
10
- const stack = document.elementsFromPoint(x, y);
11
- let el = stack[0] ?? null;
12
- const seen = new Set();
13
- while (el?.shadowRoot && typeof el.shadowRoot.elementsFromPoint === "function") {
14
- if (seen.has(el)) break;
15
- seen.add(el);
16
- const inner = el.shadowRoot.elementsFromPoint(x, y) ?? [];
17
- const next = inner.find(node => node && node !== el);
18
- if (!next) break;
19
- el = next;
20
- }
21
- return el;
22
- }
23
-
24
- function parentOf(node) {
25
- if (!node) return null;
26
- if (node.parentElement) return node.parentElement;
27
- const root = node.getRootNode?.();
28
- return root?.host ?? null;
29
- }
30
-
31
- function promote(el) {
32
- const minArea = 0.5 * width * height;
33
- let node = el;
34
- while (node && node.nodeType === 1) {
35
- const position = getComputedStyle(node).position;
36
- if (position === "fixed" || position === "sticky" || position === "absolute") {
37
- const rect = node.getBoundingClientRect();
38
- if (rect.width * rect.height >= minArea) return node;
39
- }
40
- node = parentOf(node);
41
- }
42
- return el;
43
- }
44
-
45
- function labelledByText(el) {
46
- const ids = (el.getAttribute("aria-labelledby") || "").trim();
47
- if (!ids) return "";
48
- return ids.split(/\s+/).map(id => document.getElementById(id)?.textContent?.trim() ?? "").filter(Boolean).join(" ");
49
- }
50
-
51
- function elementName(el) {
52
- const ariaLabel = el.getAttribute("aria-label");
53
- if (ariaLabel) return ariaLabel;
54
- const labelled = labelledByText(el);
55
- if (labelled) return labelled;
56
- const heading = el.querySelector("h1,h2,h3,h4,h5,h6")?.textContent?.trim();
57
- if (heading) return heading;
58
- return ((el.innerText || el.textContent || "").trim().replace(/\s+/g, " ")).slice(0, 80);
59
- }
60
-
61
- function selectorHint(el) {
62
- if (el.id) return `#${el.id}`;
63
- const classes = [...el.classList].join(".");
64
- return classes ? `${el.tagName.toLowerCase()}.${classes}` : el.tagName.toLowerCase();
65
- }
66
-
67
- function describe(el, coverage) {
68
- return {
69
- tagName: el.tagName,
70
- role: el.getAttribute("role") || "",
71
- name: elementName(el),
72
- coverage,
73
- position: getComputedStyle(el).position,
74
- selectorHint: selectorHint(el),
75
- ariaModal: el.getAttribute("aria-modal") === "true",
76
- };
77
- }
78
-
79
- function isMainContent(el) {
80
- if (el === document.documentElement || el === document.body) return true;
81
- if (el.tagName === "MAIN") return true;
82
- return (el.getAttribute("role") || "").toLowerCase() === "main";
83
- }
84
-
85
- function isBlocking(el, info) {
86
- if (info.coverage < 0.6) return false;
87
- if (getComputedStyle(el).pointerEvents === "none") return false;
88
- const role = (info.role || "").toLowerCase();
89
- if (role === "dialog" || role === "alertdialog") return true;
90
- if (info.ariaModal) return true;
91
- if (isMainContent(el)) return false;
92
- return info.position === "fixed" || info.position === "absolute";
93
- }
94
-
95
- const insetX = width * 0.05;
96
- const insetY = height * 0.05;
97
- const spanX = width * 0.9;
98
- const spanY = height * 0.9;
99
- for (let row = 0; row < gridSize; row++) {
100
- for (let col = 0; col < gridSize; col++) {
101
- const x = insetX + ((col + 0.5) * spanX) / gridSize;
102
- const y = insetY + ((row + 0.5) * spanY) / gridSize;
103
- const top = pierceTopmost(x, y);
104
- if (!top) continue;
105
- const candidate = promote(top);
106
- hits.set(candidate, (hits.get(candidate) ?? 0) + 1);
107
- }
108
- }
109
-
110
- const candidates = [...hits.entries()]
111
- .map(([el, count]) => {
112
- const info = describe(el, total > 0 ? count / total : 0);
113
- return { el, info };
114
- })
115
- .sort((a, b) => b.info.coverage - a.info.coverage);
116
-
117
- const blockingEntry = candidates.find(entry => isBlocking(entry.el, entry.info));
118
- return {
119
- blocking: blockingEntry ? blockingEntry.info : null,
120
- candidates: candidates.map(entry => entry.info),
121
- viewport,
122
- };
123
- }, grid);
124
- }
125
-
126
- export function layersHeader(result) {
127
- const blocking = result?.blocking;
128
- if (!blocking) return "@layers none";
129
- const who = blocking.role || blocking.tagName;
130
- const pct = Math.round(blocking.coverage * 100);
131
- return `@layers blocking=${who} "${blocking.name}" coverage=${pct}% hint=${blocking.selectorHint}`;
132
- }
133
-
134
- export async function snapshotWithLayers(page, snapshotOptions) {
135
- const snapshot = await page.snapshot(snapshotOptions);
136
- const layers = await describeLayers(page);
137
- return { ...snapshot, layers, tree: `${layersHeader(layers)}\n${snapshot.tree}` };
138
- }
package/src/llm.js DELETED
@@ -1,201 +0,0 @@
1
- const SNAPSHOT_PARSE_ERROR =
2
- "compactSnapshot expected a snapshot() result (JSON string or {tree, refs} object)";
3
-
4
- export function compactSnapshot(snapshot) {
5
- const obj = typeof snapshot === "string" ? JSON.parse(snapshot) : snapshot;
6
- if (obj?.full === false && obj.diff) {
7
- const { added, changed, removed, focused } = obj.diff;
8
- const lines = [
9
- ...added.map(node => `+ ${node.tree}`),
10
- ...changed.map(node => `~ ${node.tree}`),
11
- ];
12
- if (removed.length) lines.push(`- ${refRanges(removed)}`);
13
- lines.push(`@focused ${focused ?? "none"}`);
14
- return lines.join("\n");
15
- }
16
- if (!obj || typeof obj.tree !== "string") throw new TypeError(SNAPSHOT_PARSE_ERROR);
17
- return obj.tree;
18
- }
19
-
20
- function refRanges(refs) {
21
- const sorted = refs.map(ref => {
22
- const [, prefix, number] = /^((?:f\d+)?e)(\d+)$/.exec(ref);
23
- return { prefix, number: Number(number) };
24
- }).sort((a, b) => a.prefix.localeCompare(b.prefix) || a.number - b.number);
25
- const ranges = [];
26
- for (let i = 0; i < sorted.length; i++) {
27
- const first = sorted[i];
28
- let last = first;
29
- while (sorted[i + 1]?.prefix === first.prefix && sorted[i + 1].number === last.number + 1) last = sorted[++i];
30
- ranges.push(first === last ? `${first.prefix}${first.number}` : `${first.prefix}${first.number}-${last.prefix}${last.number}`);
31
- }
32
- return ranges.join(", ");
33
- }
34
-
35
- export function snapshotTokens(snapshot) {
36
- const text = typeof snapshot === "string" ? snapshot : JSON.stringify(snapshot);
37
- return { bytes: Buffer.byteLength(text, "utf8"), estTokens: Math.ceil(Buffer.byteLength(text, "utf8") / 4) };
38
- }
39
-
40
- export const toolSchemas = [
41
- {
42
- name: "newTab",
43
- description: "Open a tab and return its page. Waits for interactivity.",
44
- parameters: { type: "object", properties: { url: { type: "string" } }, required: ["url"] },
45
- },
46
- {
47
- name: "attachPage",
48
- description: "Attach to an existing tab by targetId from listTargets().",
49
- parameters: { type: "object", properties: { targetId: { type: "string" } }, required: ["targetId"] },
50
- },
51
- {
52
- name: "page.goto",
53
- description: "Navigate the page; resolves when the page looks interactive.",
54
- parameters: { type: "object", properties: { url: { type: "string" } }, required: ["url"] },
55
- },
56
- {
57
- name: "page.snapshot",
58
- description: "PRIMARY page read. Snapshot once, act on refs, then use {diff:true} for changes. Full fallbacks carry full:true and a reason. Options: diff, maxDepth, maxChars, interactive, showHidden, selector, ref.",
59
- parameters: { type: "object", properties: { options: { type: "object" } } },
60
- },
61
- {
62
- name: "page.locator",
63
- description: "Resolve a ref id (e.g. 'e1') or CSS selector to a Locator: click, fill, press, hover, check, selectOption, dragTo, setInputFiles, textContent, isVisible, waitFor.",
64
- parameters: { type: "object", properties: { selectorOrRef: { type: "string" } }, required: ["selectorOrRef"] },
65
- },
66
- {
67
- name: "page.evaluate",
68
- description: "Run JS in the page and return the result.",
69
- parameters: { type: "object", properties: { expression: { type: "string" } }, required: ["expression"] },
70
- },
71
- {
72
- name: "page.screenshot",
73
- description: "Capture page image bytes (path, fullPage, clip, type, quality).",
74
- parameters: { type: "object", properties: { options: { type: "object" } } },
75
- },
76
- {
77
- name: "page.pdf",
78
- description: "Print the page to PDF bytes (path, format, margin, printBackground).",
79
- parameters: { type: "object", properties: { options: { type: "object" } } },
80
- },
81
- {
82
- name: "compactSnapshot",
83
- description: "Compact page.snapshot() before reading: full results become raw trees; diffs use +/~ lines and removed ref ranges. Refs resolve in-page.",
84
- parameters: { type: "object", properties: { snapshot: {} }, required: ["snapshot"] },
85
- },
86
- {
87
- name: "createCua",
88
- description: "Coordinate fallback for UI that refs cannot target: click/doubleClick/drag/move/scroll/type/keypress at viewport points, getVisibleScreenshot() as base64 PNG.",
89
- parameters: { type: "object", properties: { page: {} }, required: ["page"] },
90
- },
91
- {
92
- name: "createCaptcha",
93
- description: "Captcha helpers: click(bounds) and drag(from,to) return a post-action snapshot tree; readText(bounds?) OCRs a screenshot region (macOS Vision default, custom ocr injectable).",
94
- parameters: { type: "object", properties: { page: {}, options: { type: "object" } }, required: ["page"] },
95
- },
96
- {
97
- name: "createChromeApi",
98
- description: "Chrome MV3-shaped APIs: tabs.query/get, windows.*, bookmarks/history/topSites (read-only from profile files), downloads.search/download. Writes throw UnsupportedOperationError.",
99
- parameters: { type: "object", properties: { connection: {}, options: { type: "object" } }, required: ["connection"] },
100
- },
101
- {
102
- name: "injectCookies",
103
- description: "Inject raw cookie exports into a page with CDP sanitization handled (negative expires dropped, __Host- forced secure+root path+url-scoped, SameSite=None dropped when not secure, name+domain deduped).",
104
- parameters: { type: "object", properties: { page: {}, cookies: { type: "array" } }, required: ["page", "cookies"] },
105
- },
106
- {
107
- name: "createNetworkSnoop",
108
- description: "Buffer a page's CDP network traffic and return {pop,peek,popJson,waitFor,summary,dispose}; match is a predicate or {url,method,mimeType,resourceType}.",
109
- parameters: { type: "object", properties: { page: {}, match: {}, bodies: { type: "boolean" }, maxEntries: { type: "number" }, maxBodyBytes: { type: "number" } }, required: ["page"] },
110
- },
111
- {
112
- name: "snoop.waitFor",
113
- description: "Wait until a finished entry matches a predicate or {url,method,mimeType,resourceType}; timeoutMs defaults to 30000.",
114
- parameters: { type: "object", properties: { match: {}, timeoutMs: { type: "number" } } },
115
- },
116
- {
117
- name: "snoop.popJson",
118
- description: "Drain the buffer and parse JSON bodies; skips non-JSON mime types and payloads that fail to parse.",
119
- parameters: { type: "object", properties: {} },
120
- },
121
- {
122
- name: "snoop.summary",
123
- description: "Return a compact text view of buffered entries (method, status, mimeType, size, url) capped by {max}.",
124
- parameters: { type: "object", properties: { max: { type: "number" } } },
125
- },
126
- {
127
- name: "collectWhileScrolling",
128
- description: "Async generator that scrolls the page, drains snoop.popJson(), and yields extracted items until minItems, maxScrolls, or noGrowth.",
129
- parameters: { type: "object", properties: { page: {}, snoop: {}, minItems: { type: "number" }, maxScrolls: { type: "number" }, extract: {}, scroll: { type: "string", enum: ["wheel", "end"] }, settleMs: { type: "number" } }, required: ["page", "snoop"] },
130
- },
131
- {
132
- name: "createTrace",
133
- description: "Start a page flight recorder that writes dir/trace.jsonl, dir/trace.har, dir/summary.json and screenshots; never sends Runtime.enable.",
134
- parameters: { type: "object", properties: { page: {}, dir: { type: "string" }, screenshots: { type: "boolean" }, network: { type: "boolean" }, console: { type: "boolean" }, maxBodyBytes: { type: "number" }, events: {} }, required: ["page", "dir"] },
135
- },
136
- {
137
- name: "trace.step",
138
- description: "Run named fn as a traced step with optional before/after screenshots; records the error and rethrows on failure.",
139
- parameters: { type: "object", properties: { name: { type: "string" }, fn: {} }, required: ["name", "fn"] },
140
- },
141
- {
142
- name: "trace.stop",
143
- description: "Flush listeners, write summary.json and trace.har, dispose the snoop, and return the summary for dir.",
144
- parameters: { type: "object", properties: {} },
145
- },
146
- {
147
- name: "reconcileFrames",
148
- description: "Adopt OOPIF iframe targets missing from FrameManager so later snapshots include them; returns the frames that were added.",
149
- parameters: { type: "object", properties: { page: {} }, required: ["page"] },
150
- },
151
- {
152
- name: "snapshotWithFrames",
153
- description: "Reconcile missing OOPIF frames then snapshot; refs stay page-level: page.locator(ref), never frame.locator.",
154
- parameters: { type: "object", properties: { page: {}, options: { type: "object" } }, required: ["page"] },
155
- },
156
- {
157
- name: "connectPipe.dialogPolicy",
158
- description: "Wire connectPipe({dialogPolicy}), connect(url, {dialogPolicy}) and setDialogPolicy to {accept,promptText} or (dialog)=>boolean|{accept,promptText}; a throwing policy accepts.",
159
- parameters: { type: "object", properties: { accept: { type: "boolean" }, promptText: { type: "string" } } },
160
- },
161
- {
162
- name: "requestHuman",
163
- description: "Pause for a human: inject a shadow-DOM Done banner, bringToFront first, and remove the banner on every path; until is {url}|{selector}|async predicate.",
164
- parameters: { type: "object", properties: { page: {}, prompt: { type: "string" }, until: {}, timeoutMs: { type: "number" }, pollMs: { type: "number" }, signal: {} }, required: ["page"] },
165
- },
166
- {
167
- name: "describeLayers",
168
- description: "Sample a viewport grid and return {blocking,candidates,viewport} so overlay coverage and selectorHint are visible.",
169
- parameters: { type: "object", properties: { page: {}, grid: { type: "number" } }, required: ["page"] },
170
- },
171
- {
172
- name: "snapshotWithLayers",
173
- description: "Prepend a @layers header to the snapshot tree and attach a layers field so overlays are visible before the a11y tree.",
174
- parameters: { type: "object", properties: { page: {}, options: { type: "object" } }, required: ["page"] },
175
- },
176
- {
177
- name: "emulate",
178
- description: "Apply a DEVICE_PRESETS name, a custom metrics object, or null to restore the original UA captured on first call.",
179
- parameters: { type: "object", properties: { page: {}, preset: {} }, required: ["page", "preset"] },
180
- },
181
- {
182
- name: "createRoutes",
183
- description: "Install page request interception; Fetch.enable is sent only on the first route(); interception is fingerprintable, keep it off by default.",
184
- parameters: { type: "object", properties: { page: {} }, required: ["page"] },
185
- },
186
- {
187
- name: "route.continue",
188
- description: "Continue an intercepted request, optionally overriding url, method, headers, or postData.",
189
- parameters: { type: "object", properties: { url: { type: "string" }, method: { type: "string" }, headers: { type: "object" }, postData: {} } },
190
- },
191
- {
192
- name: "route.fulfill",
193
- description: "Fulfill an intercepted request with {status,headers,contentType,body} instead of hitting the network.",
194
- parameters: { type: "object", properties: { status: { type: "number" }, headers: { type: "object" }, contentType: { type: "string" }, body: {} } },
195
- },
196
- {
197
- name: "route.abort",
198
- description: "Abort an intercepted request with a CDP errorReason (defaults to Failed).",
199
- parameters: { type: "object", properties: { reason: { type: "string" } } },
200
- },
201
- ];
@@ -1,54 +0,0 @@
1
- import { dlopen, ptr } from "bun:ffi";
2
- import path from "node:path";
3
-
4
- const systemRoot = process.env.SystemRoot || process.env.windir || "C:\\Windows";
5
- const { symbols } = dlopen(path.win32.join(systemRoot, "System32", "ntdll.dll"), {
6
- // NTSTATUS is returned in the same native call, unlike GetLastError's
7
- // thread-local state, whose preservation across FFI/JS is not guaranteed.
8
- NtCreateFile: {
9
- args: ["buffer", "u32", "buffer", "buffer", "ptr", "u32", "u32", "u32", "u32", "ptr", "u32"],
10
- returns: "u32",
11
- },
12
- NtClose: { args: ["u64"], returns: "u32" },
13
- RtlNtStatusToDosError: { args: ["u32"], returns: "u32" },
14
- });
15
-
16
- function nativeError(operation, lockPath, status) {
17
- const error = symbols.RtlNtStatusToDosError(status);
18
- return Object.assign(
19
- new Error(`instance lock ${operation} failed for ${lockPath} (Windows error ${error}, NTSTATUS 0x${status.toString(16)})`),
20
- { code: "ERR_INSTANCE_LOCK" },
21
- );
22
- }
23
-
24
- export function tryAcquireWindows(lockPath) {
25
- // Bun Windows is 64-bit: UNICODE_STRING has its pointer at offset 8 and
26
- // OBJECT_ATTRIBUTES is 48 bytes. Translate the Win32 extended namespace to NT.
27
- const filename = Buffer.from(`${path.toNamespacedPath(path.resolve(lockPath)).replace(/^\\\\\?\\/, "\\??\\")}\0`, "utf16le");
28
- const name = Buffer.alloc(16);
29
- name.writeUInt16LE(filename.length - 2, 0);
30
- name.writeUInt16LE(filename.length, 2);
31
- name.writeBigUInt64LE(BigInt(ptr(filename)), 8);
32
- const attributes = Buffer.alloc(48);
33
- attributes.writeUInt32LE(48, 0);
34
- attributes.writeBigUInt64LE(BigInt(ptr(name)), 16);
35
- attributes.writeUInt32LE(0x40, 24); // OBJ_CASE_INSENSITIVE, not OBJ_INHERIT.
36
- const handleOut = Buffer.alloc(8);
37
- const ioStatus = Buffer.alloc(16);
38
- // GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, share mode 0, FILE_OPEN_IF
39
- // (OPEN_ALWAYS), synchronous non-directory file. NULL security descriptor
40
- // inherits the registry's DACL; no truncation, deletion, or inheritance.
41
- const status = symbols.NtCreateFile(
42
- handleOut, 0xc0100000, attributes, ioStatus, null, 0x80, 0, 3, 0x60, null, 0,
43
- );
44
- // STATUS_SHARING_VIOLATION is exactly ERROR_SHARING_VIOLATION (32).
45
- if (status === 0xc0000043) return null;
46
- if (status >= 0x80000000) throw nativeError("NtCreateFile", lockPath, status);
47
- const handle = handleOut.readBigUInt64LE();
48
- return {
49
- release() {
50
- const status = symbols.NtClose(handle);
51
- if (status >= 0x80000000) throw nativeError("NtClose", lockPath, status);
52
- },
53
- };
54
- }
@@ -1,81 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { constants } from "node:fs";
3
- import { open } from "node:fs/promises";
4
-
5
- // xnu bsd/sys/fcntl.h: O_EXLOCK and O_NONBLOCK. Node does not export O_EXLOCK.
6
- const DARWIN_EXCLUSIVE_NONBLOCK = 0x20 | 0x4;
7
- // libuv include/uv/win.h: UV_FS_O_EXLOCK makes CreateFile's share mode zero.
8
- const WINDOWS_EXCLUSIVE = 0x10000000;
9
- const probedPaths = new Set();
10
-
11
- async function lockLinux(fd) {
12
- return new Promise((resolve, reject) => {
13
- const child = spawn("flock", ["-n", "3"], {
14
- stdio: ["ignore", "ignore", "pipe", fd],
15
- });
16
- let stderr = "";
17
- child.stderr.setEncoding("utf8");
18
- child.stderr.on("data", (chunk) => { stderr += chunk; });
19
- child.once("error", (error) => {
20
- reject(error.code === "ENOENT"
21
- ? new Error(`instance lock needs the flock utility (util-linux or busybox) on Linux: ${error.message}`, { cause: error })
22
- : error);
23
- });
24
- // close follows exit and drains stderr, so real utility errors are intact.
25
- child.once("close", (code, signal) => {
26
- if (code === 0) resolve(true);
27
- // util-linux and BusyBox are silent on EWOULDBLOCK. BusyBox also
28
- // returns 1 for real errors, but prints their errno description.
29
- else if (code === 1 && stderr.trim() === "") resolve(false);
30
- else reject(Object.assign(
31
- new Error(`instance lock flock failed (${signal ?? code}): ${stderr.trim()}`),
32
- { code: "ERR_INSTANCE_LOCK" },
33
- ));
34
- });
35
- });
36
- }
37
-
38
- export async function tryAcquire(lockPath) {
39
- const platform = process.platform;
40
- // Bun on Windows drops libuv's exclusive-open bit. Use the same kernel
41
- // share reservation directly; Node and non-Windows runtimes never load FFI.
42
- if (platform === "win32" && process.versions.bun) {
43
- const { tryAcquireWindows } = await import("./lock-backend-win32.js");
44
- return tryAcquireWindows(lockPath);
45
- }
46
- let flags = constants.O_RDWR | constants.O_CREAT;
47
- if (platform === "darwin") flags |= DARWIN_EXCLUSIVE_NONBLOCK;
48
- else if (platform === "win32") flags |= WINDOWS_EXCLUSIVE;
49
- else if (platform !== "linux") throw new Error(`instance lock is unsupported on ${platform}`);
50
-
51
- let handle;
52
- try {
53
- handle = await open(lockPath, flags, 0o600);
54
- } catch (error) {
55
- if (platform === "darwin" && ["EAGAIN", "EWOULDBLOCK"].includes(error.code)) return null;
56
- if (platform === "win32" && error.code === "EBUSY") return null;
57
- throw error;
58
- }
59
- try {
60
- if (platform === "linux" && !await lockLinux(handle.fd)) {
61
- await handle.close();
62
- return null;
63
- }
64
- } catch (error) {
65
- await handle.close();
66
- throw error;
67
- }
68
- // The runtime opens close-on-exec; only the one-shot flock child receives it.
69
- // Never unlink: another opener must always reach the same kernel object.
70
- return { release: () => handle.close() };
71
- }
72
-
73
- export async function probeOnce(lockPath) {
74
- if (probedPaths.has(lockPath)) return;
75
- const second = await tryAcquire(lockPath);
76
- if (second !== null) {
77
- await second.release();
78
- throw new Error(`instance lock is not enforced for ${lockPath} on this runtime and filesystem`);
79
- }
80
- probedPaths.add(lockPath);
81
- }