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,124 +0,0 @@
1
- function injectHumanBanner(prompt) {
2
- if (document.querySelector('[data-omowright-human="1"]')) return true;
3
- const host = document.createElement("div");
4
- host.setAttribute("data-omowright-human", "1");
5
- host.style.cssText = "position:fixed;top:0;left:0;right:0;z-index:2147483647;display:block;visibility:visible;opacity:1;pointer-events:auto;";
6
- const root = host.attachShadow({ mode: "open" });
7
- const bar = document.createElement("div");
8
- bar.setAttribute("style", "display:flex;align-items:center;gap:12px;padding:10px 16px;background:#111;color:#fff;font:14px/1.4 system-ui,sans-serif;");
9
- const message = document.createElement("span");
10
- message.textContent = prompt == null ? "" : String(prompt);
11
- const button = document.createElement("button");
12
- button.textContent = "Done";
13
- button.addEventListener("click", () => {
14
- window.__omowrightHumanDone = true;
15
- });
16
- bar.append(message, button);
17
- root.append(bar);
18
- (document.documentElement ?? document.body).appendChild(host);
19
- return true;
20
- }
21
-
22
- function humanBannerPresent() {
23
- return document.querySelector('[data-omowright-human="1"]') !== null;
24
- }
25
-
26
- function humanDoneFlag() {
27
- return window.__omowrightHumanDone === true;
28
- }
29
-
30
- function querySelectorExists(selector) {
31
- return document.querySelector(selector) !== null;
32
- }
33
-
34
- function removeHumanBanner() {
35
- document.querySelectorAll('[data-omowright-human="1"]').forEach(node => node.remove());
36
- try {
37
- delete window.__omowrightHumanDone;
38
- } catch {
39
- window.__omowrightHumanDone = undefined;
40
- }
41
- }
42
-
43
- function sleep(ms, signal) {
44
- return new Promise(resolve => {
45
- if (signal?.aborted) {
46
- resolve();
47
- return;
48
- }
49
- const timer = setTimeout(() => {
50
- signal?.removeEventListener("abort", onAbort);
51
- resolve();
52
- }, ms);
53
- function onAbort() {
54
- clearTimeout(timer);
55
- resolve();
56
- }
57
- signal?.addEventListener("abort", onAbort, { once: true });
58
- });
59
- }
60
-
61
- async function ensureBanner(page, prompt) {
62
- try {
63
- if (await page.evaluate(humanBannerPresent)) return;
64
- await page.evaluate(injectHumanBanner, prompt ?? "");
65
- } catch {
66
- // Page may be mid-navigation; the next poll retries.
67
- }
68
- }
69
-
70
- async function matchesUntil(page, until) {
71
- if (until == null) return false;
72
- if (typeof until === "function") return Boolean(await until(page));
73
- if (typeof until === "object") {
74
- if (Object.prototype.hasOwnProperty.call(until, "url")) {
75
- const current = page.url();
76
- const expected = until.url;
77
- if (expected instanceof RegExp) return expected.test(current);
78
- return String(current).includes(String(expected));
79
- }
80
- if (typeof until.selector === "string") {
81
- try {
82
- return Boolean(await page.evaluate(querySelectorExists, until.selector));
83
- } catch {
84
- return false;
85
- }
86
- }
87
- }
88
- return false;
89
- }
90
-
91
- async function isDone(page) {
92
- try {
93
- return await page.evaluate(humanDoneFlag) === true;
94
- } catch {
95
- return false;
96
- }
97
- }
98
-
99
- export async function requestHuman(page, { prompt, until, timeoutMs = 300000, pollMs = 500, signal } = {}) {
100
- const started = Date.now();
101
- const finish = (outcome, reason) => ({ outcome, elapsedMs: Date.now() - started, reason });
102
-
103
- try {
104
- await page.bringToFront().catch(() => {});
105
- await ensureBanner(page, prompt);
106
-
107
- for (;;) {
108
- if (signal?.aborted) return finish("cancelled", "signal");
109
- // Check the conditions before the deadline: a slow bringToFront or banner
110
- // injection must not time the wait out before its first check.
111
- if (await matchesUntil(page, until)) return finish("continued", "until");
112
- if (await isDone(page)) return finish("continued", "done-button");
113
- if (Date.now() - started >= timeoutMs) return finish("timed_out", "timed_out");
114
- // Human waits are idle time, not a race against a specific event; a timer
115
- // poll loop is the correct tool here.
116
- await ensureBanner(page, prompt);
117
- const remaining = timeoutMs - (Date.now() - started);
118
- if (remaining <= 0) return finish("timed_out", "timed_out");
119
- await sleep(Math.min(pollMs, remaining), signal);
120
- }
121
- } finally {
122
- await page.evaluate(removeHumanBanner).catch(() => {});
123
- }
124
- }
package/src/injected.js DELETED
@@ -1,3 +0,0 @@
1
- import { readFileSync } from "node:fs";
2
-
3
- export const pageBundle = readFileSync(new URL("./page-bundle.js", import.meta.url), "utf8");
@@ -1,74 +0,0 @@
1
- import { unlink } from "node:fs/promises";
2
- import { setTimeout as sleep } from "node:timers/promises";
3
- import { probeOnce, tryAcquire } from "./lock-backend.js";
4
-
5
- const localLocks = new Map();
6
-
7
- export function isPidAlive(pid) {
8
- try {
9
- process.kill(pid, 0);
10
- return true;
11
- } catch (error) {
12
- if (error?.code === "EPERM") return true;
13
- if (error?.code === "ESRCH") return false;
14
- throw error;
15
- }
16
- }
17
-
18
- export async function unlinkIfPresent(target) {
19
- await unlink(target).catch((error) => {
20
- if (error?.code !== "ENOENT") throw error;
21
- });
22
- }
23
-
24
- async function acquireLock(lockPath, timeoutMs) {
25
- const deadline = performance.now() + timeoutMs;
26
- let delay = 10;
27
- for (;;) {
28
- const held = await tryAcquire(lockPath);
29
- if (held) {
30
- try {
31
- await probeOnce(lockPath);
32
- return held;
33
- } catch (error) {
34
- await held.release();
35
- throw error;
36
- }
37
- }
38
- const remaining = deadline - performance.now();
39
- if (remaining <= 0) throw new Error(`timed out waiting for instance lock ${lockPath}`);
40
- await sleep(Math.min(remaining, delay * (0.75 + Math.random() * 0.5)));
41
- delay = Math.min(delay * 2, 250);
42
- }
43
- }
44
-
45
- async function acquireLocalLock(key) {
46
- const previous = localLocks.get(key) ?? Promise.resolve();
47
- let releaseCurrent;
48
- const current = new Promise((resolve) => {
49
- releaseCurrent = resolve;
50
- });
51
- const tail = previous.then(() => current);
52
- localLocks.set(key, tail);
53
- await previous;
54
- return () => {
55
- releaseCurrent();
56
- if (localLocks.get(key) === tail) localLocks.delete(key);
57
- };
58
- }
59
-
60
- // The kernel owns exclusion and crash release; the local FIFO avoids polling
61
- // between callers in this process. Neither acquisition nor release removes files.
62
- export async function withLock(lockPath, { timeoutMs }, run) {
63
- const releaseLocal = await acquireLocalLock(lockPath);
64
- try {
65
- const held = await acquireLock(lockPath, timeoutMs);
66
- try {
67
- return await run();
68
- } finally {
69
- await held.release();
70
- }
71
- } finally {
72
- releaseLocal();
73
- }
74
- }
package/src/instances.js DELETED
@@ -1,490 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { createHash, randomUUID } from "node:crypto";
3
- import {
4
- mkdir,
5
- open,
6
- readFile,
7
- readdir,
8
- rename,
9
- unlink,
10
- } from "node:fs/promises";
11
- import os from "node:os";
12
- import path from "node:path";
13
- import { profileDirFromArgs, terminateChild } from "./browser-process.js";
14
- import { openConnection } from "./connection.js";
15
- import { isPidAlive, unlinkIfPresent, withLock } from "./instance-lock.js";
16
- import {
17
- assertLaunchedBrowser,
18
- discoverLaunchedEndpoint,
19
- snapshotActivePort,
20
- } from "./launch-endpoint.js";
21
- import { restrictToOwner } from "./owner-only.js";
22
- import { acquireSharedConnection } from "./shared-connections.js";
23
-
24
- const RECORD_VERSION = 2;
25
- const DEFAULT_REGISTRY_ROOT = path.join(
26
- os.homedir(),
27
- ".local",
28
- "share",
29
- "omowright",
30
- "instances",
31
- );
32
- const DEFAULT_PROBE_TIMEOUT_MS = 1_000;
33
- const DEFAULT_LAUNCH_TIMEOUT_MS = 10_000;
34
- const DEFAULT_CONNECT_TIMEOUT_MS = 10_000;
35
- const BROWSER_CLOSE_TIMEOUT_MS = 2_000;
36
- // Waiting for the lock has to outlast the slowest honest critical section
37
- // (probe + launch + CDP attach); a shorter budget makes a second caller give up
38
- // at the exact moment the first one is about to publish its record.
39
- const LOCK_TIMEOUT_MARGIN_MS = 5_000;
40
- // Same sum the per-call resolver below computes, for callers with no overrides.
41
- const DEFAULT_LOCK_TIMEOUT_MS = resolveLockTimeoutMs({});
42
-
43
- function normalizeName(name) {
44
- if (
45
- typeof name !== "string" ||
46
- !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)
47
- ) {
48
- throw new TypeError(
49
- "instance name must start with a letter or number and contain only letters, numbers, dots, dashes, or underscores",
50
- );
51
- }
52
- return name;
53
- }
54
-
55
- function registryPaths(registryRoot, name) {
56
- const root = path.resolve(registryRoot ?? DEFAULT_REGISTRY_ROOT);
57
- return {
58
- root,
59
- recordPath: path.join(root, `${name}.json`),
60
- lockPath: path.join(root, `${name}.flock`),
61
- };
62
- }
63
-
64
- async function ensureRegistryRoot(root) {
65
- await mkdir(root, { recursive: true, mode: 0o700 });
66
- await restrictToOwner(root, "directory");
67
- }
68
-
69
- function isRecord(value, expectedName) {
70
- return (
71
- value !== null &&
72
- typeof value === "object" &&
73
- value.version === RECORD_VERSION &&
74
- value.name === expectedName &&
75
- Number.isInteger(value.pid) &&
76
- value.pid > 0 &&
77
- typeof value.endpoint === "string" &&
78
- value.endpoint.length > 0 &&
79
- typeof value.webSocketDebuggerUrl === "string" &&
80
- value.webSocketDebuggerUrl.length > 0 &&
81
- (typeof value.profileDir === "string" || value.profileDir === null) &&
82
- typeof value.browserPath === "string" &&
83
- value.browserPath.length > 0 &&
84
- typeof value.startedAt === "string" &&
85
- !Number.isNaN(Date.parse(value.startedAt))
86
- );
87
- }
88
-
89
- async function readRecord(recordPath, expectedName) {
90
- let text;
91
- try {
92
- text = await readFile(recordPath, "utf8");
93
- } catch (error) {
94
- if (error?.code === "ENOENT") return { exists: false, record: null };
95
- throw error;
96
- }
97
-
98
- try {
99
- const record = JSON.parse(text);
100
- return {
101
- exists: true,
102
- record: isRecord(record, expectedName) ? record : null,
103
- };
104
- } catch {
105
- return { exists: true, record: null };
106
- }
107
- }
108
-
109
- async function writeRecordAtomic(root, recordPath, record) {
110
- const tempPath = path.join(
111
- root,
112
- `.${record.name}.${process.pid}.${randomUUID()}.tmp`,
113
- );
114
- let handle;
115
- try {
116
- handle = await open(tempPath, "wx", 0o600);
117
- await handle.writeFile(`${JSON.stringify(record, null, 2)}\n`, "utf8");
118
- await handle.close();
119
- handle = null;
120
- await restrictToOwner(tempPath, "file");
121
- await rename(tempPath, recordPath);
122
- await restrictToOwner(recordPath, "file");
123
- } catch (error) {
124
- await handle?.close().catch(() => {});
125
- await unlink(tempPath).catch(() => {});
126
- throw error;
127
- }
128
- }
129
-
130
- function isConnectionRefused(error) {
131
- for (let cause = error; cause; cause = cause?.cause) {
132
- if (
133
- cause.code === "ECONNREFUSED" ||
134
- cause.code === "ENOTFOUND" ||
135
- // Bun's fetch reports refused connections with this code.
136
- cause.code === "ConnectionRefused"
137
- ) {
138
- return true;
139
- }
140
- }
141
- return false;
142
- }
143
-
144
- async function probeEndpoint(endpoint, timeoutMs) {
145
- const versionUrl = new URL("/json/version", endpoint);
146
- const response = await fetch(versionUrl, {
147
- signal: AbortSignal.timeout(timeoutMs),
148
- });
149
- if (!response.ok) {
150
- throw new Error(
151
- `CDP discovery request failed (${response.status} ${response.statusText})`,
152
- );
153
- }
154
- const version = await response.json();
155
- if (
156
- typeof version?.webSocketDebuggerUrl !== "string" ||
157
- version.webSocketDebuggerUrl.length === 0
158
- ) {
159
- throw new Error("CDP discovery response lacks webSocketDebuggerUrl");
160
- }
161
- return version;
162
- }
163
-
164
- function resolveConnectTimeoutMs(options) {
165
- return options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
166
- }
167
-
168
- function resolveLockTimeoutMs(options) {
169
- if (options.lockTimeoutMs !== undefined) return options.lockTimeoutMs;
170
- return (
171
- (options.launchTimeoutMs ?? DEFAULT_LAUNCH_TIMEOUT_MS) +
172
- (options.probeTimeoutMs ?? resolveConnectTimeoutMs(options)) +
173
- resolveConnectTimeoutMs(options) +
174
- LOCK_TIMEOUT_MARGIN_MS
175
- );
176
- }
177
-
178
- function nameLockOptions(options) {
179
- return {
180
- timeoutMs: resolveLockTimeoutMs(options),
181
- };
182
- }
183
-
184
- // `/json/version` answering proves nothing about the WebSocket upgrade behind
185
- // it, so the session handshake carries its own bound.
186
- async function connectWithin(endpoint, options, timeoutMs) {
187
- const pending = openConnection(endpoint, options);
188
- let timer;
189
- try {
190
- return await Promise.race([
191
- pending,
192
- new Promise((_, reject) => {
193
- timer = setTimeout(
194
- () =>
195
- reject(
196
- new Error(
197
- `timed out after ${timeoutMs}ms opening a CDP session on ${endpoint}`,
198
- ),
199
- ),
200
- timeoutMs,
201
- );
202
- }),
203
- ]);
204
- } catch (error) {
205
- // A session that lands after the bound would otherwise hold a live socket.
206
- pending.then(
207
- (connection) => connection.close().catch(() => {}),
208
- () => {},
209
- );
210
- throw error;
211
- } finally {
212
- clearTimeout(timer);
213
- }
214
- }
215
-
216
- async function removeOwnedRecord(recordPath, name, pid) {
217
- const loaded = await readRecord(recordPath, name);
218
- if (loaded.record?.pid !== pid) return;
219
- await unlinkIfPresent(recordPath);
220
- }
221
-
222
- function connectionOptions(options, profileDir) {
223
- const result = { ...(options.connectionOptions ?? {}) };
224
- if (options.storageRoot !== undefined) result.storageRoot = options.storageRoot;
225
- else if (result.storageRoot === undefined && profileDir) {
226
- result.storageRoot = profileDir;
227
- }
228
- if (options.client !== undefined) {
229
- result.client = {
230
- ...(result.client ?? {}),
231
- ...options.client,
232
- };
233
- }
234
- // Part of the sharing key too: callers asking for different dialog policies
235
- // never share one connection.
236
- if (options.dialogPolicy !== undefined) result.dialogPolicy = options.dialogPolicy;
237
- return result;
238
- }
239
-
240
- // Asked over CDP first, as the pipe transport does: on Windows no signal can
241
- // ask a browser to quit, and Chrome cleans up only on a clean quit. Only a live
242
- // browser on a live socket is asked: CdpClient.send would otherwise reconnect
243
- // through the recorded port, which is not an identity (another process may
244
- // hold it by now). The connection is closed as soon as the request is answered,
245
- // before the quitting browser drops its socket: a drop on an open client starts
246
- // its auto-reconnect loop, which would keep the caller's process alive. Then,
247
- // like the pipe transport, the browser gets a bounded wait to exit before
248
- // terminateChild steps in.
249
- async function askBrowserToQuit(connection, child, disconnect) {
250
- if (child.exitCode !== null || child.signalCode !== null || !connection.cdp.isConnected) {
251
- await disconnect();
252
- return false;
253
- }
254
- const exited = new Promise((resolve) => child.once("exit", resolve));
255
- const quitRequested = await Promise.race([
256
- connection.cdp
257
- .send("Browser.close", undefined, undefined, { timeoutMs: BROWSER_CLOSE_TIMEOUT_MS })
258
- .then(() => true, () => false),
259
- exited.then(() => true),
260
- ]);
261
- await disconnect();
262
- if (child.exitCode === null && child.signalCode === null) {
263
- let timer;
264
- await Promise.race([
265
- exited,
266
- new Promise((resolve) => { timer = setTimeout(resolve, BROWSER_CLOSE_TIMEOUT_MS); }),
267
- ]);
268
- clearTimeout(timer);
269
- }
270
- return quitRequested;
271
- }
272
-
273
- async function launchNamed(
274
- name,
275
- { root, recordPath, lockPath },
276
- options,
277
- ) {
278
- if (typeof options.browserPath !== "string" || options.browserPath.length === 0) {
279
- throw new TypeError(
280
- `connectNamed("${name}") requires browserPath when no healthy instance is registered`,
281
- );
282
- }
283
- const browserArgs = [...(options.browserArgs ?? [])];
284
- const profileDir = options.profileDir
285
- ? path.resolve(options.profileDir)
286
- : profileDirFromArgs(browserArgs);
287
- const previousActivePort = await snapshotActivePort(profileDir);
288
- const child = spawn(
289
- options.browserPath,
290
- [
291
- ...browserArgs,
292
- "--remote-debugging-address=127.0.0.1",
293
- "--remote-debugging-port=0",
294
- ],
295
- {
296
- // A named browser is shared through the registry, so it has to outlive
297
- // the process that launched it. On Windows libuv puts every non-detached
298
- // child in a kill-on-close job object, which kills the browser the
299
- // moment its launcher exits (#90); detached keeps it out of that job
300
- // (DETACHED_PROCESS also gives a console-subsystem browser no console).
301
- // No windowsHide: it would start a headful browser's window hidden.
302
- ...(process.platform === "win32" ? { detached: true } : {}),
303
- ...(options.spawnOptions ?? {}),
304
- stdio: ["ignore", "ignore", "pipe"],
305
- },
306
- );
307
-
308
- let connection;
309
- try {
310
- const launchTimeoutMs = options.launchTimeoutMs ?? DEFAULT_LAUNCH_TIMEOUT_MS;
311
- const report = await discoverLaunchedEndpoint(child, {
312
- profileDir,
313
- timeoutMs: launchTimeoutMs,
314
- previousActivePort,
315
- });
316
- const { endpoint } = report;
317
- // The browser's own WebSocket URL carries its GUID: recording it makes a
318
- // later attach prove it reached this browser and not whatever else ends up
319
- // on the port once this pid is gone.
320
- const { webSocketDebuggerUrl } = await probeEndpoint(
321
- endpoint,
322
- launchTimeoutMs,
323
- );
324
- assertLaunchedBrowser(child, report, webSocketDebuggerUrl);
325
- connection = await connectWithin(
326
- endpoint,
327
- connectionOptions(options, profileDir),
328
- resolveConnectTimeoutMs(options),
329
- );
330
- const record = {
331
- version: RECORD_VERSION,
332
- name,
333
- pid: child.pid,
334
- endpoint,
335
- webSocketDebuggerUrl,
336
- profileDir,
337
- browserPath: path.resolve(options.browserPath),
338
- startedAt: new Date().toISOString(),
339
- };
340
- await writeRecordAtomic(root, recordPath, record);
341
- connection.browserProcess = child;
342
- const disconnect = connection.close.bind(connection);
343
- connection.close = async () => {
344
- let failure;
345
- const quitRequested = await askBrowserToQuit(connection, child, async () => {
346
- try {
347
- await disconnect();
348
- } catch (error) {
349
- failure = error;
350
- }
351
- });
352
- await terminateChild(child, { quitRequested });
353
- // The browser this record points at is gone, so the record goes with it
354
- // instead of waiting for the next caller to clean it up.
355
- try {
356
- await withLock(lockPath, nameLockOptions(options), () =>
357
- removeOwnedRecord(recordPath, name, child.pid),
358
- );
359
- } catch (error) {
360
- failure ??= error;
361
- }
362
- if (failure) throw failure;
363
- };
364
- return connection;
365
- } catch (error) {
366
- await connection?.close().catch(() => {});
367
- await terminateChild(child);
368
- throw error;
369
- }
370
- }
371
-
372
- export async function withEngineLock(registryRoot, engineKey, run) {
373
- const root = path.resolve(registryRoot ?? DEFAULT_REGISTRY_ROOT);
374
- await ensureRegistryRoot(root);
375
- const digest = createHash("sha256")
376
- .update(path.resolve(engineKey))
377
- .digest("hex")
378
- .slice(0, 16);
379
- const lockPath = path.join(root, `_engine-${digest}.flock`);
380
- return withLock(
381
- lockPath,
382
- { timeoutMs: DEFAULT_LOCK_TIMEOUT_MS },
383
- run,
384
- );
385
- }
386
-
387
- export async function connectNamed(name, options = {}) {
388
- const normalizedName = normalizeName(name);
389
- const paths = registryPaths(options.registryRoot, normalizedName);
390
- await ensureRegistryRoot(paths.root);
391
- return withLock(paths.lockPath, nameLockOptions(options), () =>
392
- attachOrLaunch(normalizedName, paths, options),
393
- );
394
- }
395
-
396
- async function attachOrLaunch(normalizedName, paths, options) {
397
- const loaded = await readRecord(paths.recordPath, normalizedName);
398
- if (loaded.record) {
399
- await restrictToOwner(paths.recordPath, "file");
400
- if (isPidAlive(loaded.record.pid)) {
401
- let version = null;
402
- try {
403
- version = await probeEndpoint(
404
- loaded.record.endpoint,
405
- // Attaching is not a one-second listInstances health check. A
406
- // healthy holder may still be busy finishing startup under load.
407
- options.probeTimeoutMs ?? resolveConnectTimeoutMs(options),
408
- );
409
- } catch (error) {
410
- if (!isConnectionRefused(error)) {
411
- throw new Error(
412
- `unresponsive holder "${normalizedName}" pid ${loaded.record.pid} endpoint ${loaded.record.endpoint}: ${error.message}`,
413
- { cause: error },
414
- );
415
- }
416
- // A live pid whose recorded debug port refuses connections is a
417
- // reused pid, not a holder: the record is stale and the launch
418
- // below reclaims it.
419
- }
420
- // A pid that came back and a port any local process can rebind are
421
- // not an identity. Only the recorded WebSocket URL (it carries the
422
- // browser GUID) says this is our browser; anything else answering
423
- // there is a stranger, so the record is stale, not a holder.
424
- if (
425
- version?.webSocketDebuggerUrl === loaded.record.webSocketDebuggerUrl
426
- ) {
427
- // Connecting to the recorded GUID URL, not the port, keeps the shared
428
- // connection's auto-reconnect from landing on a different browser.
429
- const { webSocketDebuggerUrl } = loaded.record;
430
- const timeoutMs = resolveConnectTimeoutMs(options);
431
- try {
432
- return await acquireSharedConnection(
433
- webSocketDebuggerUrl,
434
- connectionOptions(options, loaded.record.profileDir),
435
- {
436
- open: (shared) =>
437
- connectWithin(webSocketDebuggerUrl, shared, timeoutMs),
438
- timeoutMs,
439
- },
440
- );
441
- } catch (error) {
442
- throw new Error(
443
- `unresponsive holder "${normalizedName}" pid ${loaded.record.pid} endpoint ${loaded.record.endpoint}: ${error.message}`,
444
- { cause: error },
445
- );
446
- }
447
- }
448
- }
449
- }
450
-
451
- if (loaded.exists) {
452
- await unlink(paths.recordPath).catch((error) => {
453
- if (error?.code !== "ENOENT") throw error;
454
- });
455
- }
456
- return await launchNamed(normalizedName, paths, options);
457
- }
458
-
459
- export async function listInstances(options = {}) {
460
- const root = path.resolve(options.registryRoot ?? DEFAULT_REGISTRY_ROOT);
461
- await ensureRegistryRoot(root);
462
- const entries = await readdir(root, { withFileTypes: true });
463
- const records = await Promise.all(
464
- entries
465
- .filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
466
- .map(async (entry) => {
467
- const expectedName = entry.name.slice(0, -".json".length);
468
- const recordPath = path.join(root, entry.name);
469
- const loaded = await readRecord(recordPath, expectedName);
470
- if (!loaded.record) return null;
471
- await restrictToOwner(recordPath, "file");
472
- const alive = isPidAlive(loaded.record.pid);
473
- let responsive = false;
474
- if (alive) {
475
- responsive = await probeEndpoint(
476
- loaded.record.endpoint,
477
- options.probeTimeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS,
478
- ).then(
479
- (version) =>
480
- version.webSocketDebuggerUrl === loaded.record.webSocketDebuggerUrl,
481
- () => false,
482
- );
483
- }
484
- return { ...loaded.record, alive, responsive };
485
- }),
486
- );
487
- return records
488
- .filter((record) => record !== null)
489
- .sort((left, right) => left.name.localeCompare(right.name));
490
- }
@@ -1 +0,0 @@
1
- export const targetCreationCapability = Symbol("omowright.targetCreationCapability");