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
package/src/pipe.js DELETED
@@ -1,418 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { finished } from "node:stream/promises";
3
- import {
4
- browserSpawnDetached,
5
- profileDirFromArgs,
6
- reapOrphanedBrowser,
7
- removeBrowserPidFile,
8
- terminateChild,
9
- writeBrowserPidFile,
10
- } from "./browser-process.js";
11
- import { BrowserConnection } from "./connection.js";
12
- import { Dialog, answerWithPolicy, normalizeDialogPolicy } from "./dialog-policy.js";
13
- import { NulFrameReader } from "./nul-frames.js";
14
- import { targetCreationCapability } from "./internal-capability.js";
15
- import { SerialEmitter as Emittery } from "./serial-emitter.js";
16
- import { CdpCommandTimeoutError, CdpPipeClosedError, CdpSessionDetachedError, CdpSessionCrashedError } from "./cdp-errors.js";
17
- export { CdpCommandTimeoutError, CdpPipeClosedError, CdpSessionDetachedError, CdpSessionCrashedError } from "./cdp-errors.js";
18
-
19
- const DEFAULT_COMMAND_TIMEOUT_MS = 30_000;
20
- const DEFAULT_READINESS_TIMEOUT_MS = 10_000;
21
- const GRACEFUL_CLOSE_TIMEOUT_MS = 2_000;
22
- const STDIO_TAIL_LIMIT = 16_384;
23
- const EXIT_STDERR_DRAIN_MS = 1_000;
24
-
25
- export class PipeCdpClient {
26
- #child;
27
- #writeStream;
28
- #readStream;
29
- #frames = new NulFrameReader();
30
- #seq = 1;
31
- #pending = new Map();
32
- #closedSessions = new Set();
33
- #sessionTargets = new Map();
34
- #launch;
35
- #launchId;
36
- #launchedAt = 0;
37
- #receivedBytes = 0;
38
- #malformedFrameCount = 0;
39
- #events = new Emittery();
40
- #connected = false;
41
- #commandTimeoutMs;
42
- #readinessTimeoutMs;
43
- #browserPath;
44
- #browserArgs;
45
- #spawnOptions;
46
- #stdioTail = "";
47
- #stderrHead = "";
48
- #dialogPolicy;
49
- transportEvents = new Emittery();
50
- logId;
51
-
52
- constructor({ browserPath, browserArgs = [], spawnOptions = {}, commandTimeoutMs, readinessTimeoutMs, logId, dialogPolicy }) {
53
- if (!browserPath) throw new TypeError("PipeCdpClient requires browserPath");
54
- this.#browserPath = browserPath;
55
- this.#browserArgs = browserArgs;
56
- this.#spawnOptions = spawnOptions;
57
- this.#commandTimeoutMs = commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
58
- this.#readinessTimeoutMs = readinessTimeoutMs ?? DEFAULT_READINESS_TIMEOUT_MS;
59
- this.logId = logId ?? `cdp-pipe-${Date.now()}`;
60
- this.#dialogPolicy = normalizeDialogPolicy(dialogPolicy);
61
- }
62
-
63
- get isConnected() { return this.#connected; }
64
- get isHeadless() { return this.#browserArgs.some(arg => /^--headless(?:=|$)/.test(arg)); }
65
- get childProcess() { return this.#child; }
66
- get dialogPolicy() { return this.#dialogPolicy; }
67
-
68
- setDialogPolicy(policy) {
69
- this.#dialogPolicy = normalizeDialogPolicy(policy);
70
- }
71
-
72
- async ensureConnected() {
73
- if (this.#connected) return;
74
- // Never inherit stdout/stderr: Chromium writes startup noise to both (e.g.
75
- // the PartitionAlloc shim's "Trying to load the allocator multiple times"
76
- // line and GoogleUpdater child logs), and inherited fds would spray it raw
77
- // onto the caller's tty (it corrupted the senpi TUI). Pipe + drain into a
78
- // bounded tail kept for launch diagnostics.
79
- const stdio = ["ignore", "pipe", "pipe", "pipe", "pipe"];
80
- const profileDir = profileDirFromArgs(this.#browserArgs);
81
- await reapOrphanedBrowser(profileDir);
82
- this.#child = spawn(this.#browserPath, [...this.#browserArgs, "--remote-debugging-pipe"], {
83
- detached: browserSpawnDetached,
84
- ...this.#spawnOptions,
85
- stdio,
86
- });
87
- // A spawn that fails (missing or non-executable browserPath) has no pid and
88
- // emits "error" instead of "spawn"; unheard, that error crashes the caller.
89
- const spawnFailed = new Promise(resolve => this.#child.once("error", resolve));
90
- if (this.#child.pid === undefined) {
91
- const error = await spawnFailed;
92
- this.#child = undefined;
93
- throw error;
94
- }
95
- const browserPid = this.#child.pid;
96
- // A helper process can keep an old launch's pipe open after that browser is
97
- // gone; its late events must never touch the launch that replaced it.
98
- const launch = {};
99
- this.#launch = launch;
100
- const owned = listener => (...args) => { if (this.#launch === launch) listener(...args); };
101
- this.#launchId = `${this.logId}:${browserPid}`;
102
- this.#launchedAt = performance.now();
103
- this.#receivedBytes = 0;
104
- this.#malformedFrameCount = 0;
105
- this.#frames = new NulFrameReader();
106
- this.#sessionTargets.clear();
107
- this.#closedSessions.clear();
108
- this.#child.once("exit", () => removeBrowserPidFile(profileDir, browserPid));
109
- this.#stdioTail = "";
110
- this.#stderrHead = "";
111
- const stderr = this.#child.stderr;
112
- for (const stream of [this.#child.stdout, stderr]) {
113
- if (!stream) continue;
114
- stream.setEncoding("utf8");
115
- stream.on("data", (chunk) => {
116
- this.#stdioTail = (this.#stdioTail + chunk).slice(-STDIO_TAIL_LIMIT);
117
- // Only the first stderr line is read: stop growing the head once it holds
118
- // a complete non-blank line or is full.
119
- if (stream === stderr && this.#stderrHead.length < STDIO_TAIL_LIMIT && !this.#stderrHead.trimStart().includes("\n")) {
120
- this.#stderrHead = (this.#stderrHead + chunk).slice(0, STDIO_TAIL_LIMIT);
121
- }
122
- });
123
- stream.on("error", () => {});
124
- }
125
- this.#writeStream = this.#child.stdio[3];
126
- this.#readStream = this.#child.stdio[4];
127
- this.#readStream.on("data", owned(chunk => this.#onData(chunk)));
128
- for (const event of ["end", "close"]) {
129
- this.#readStream.on(event, owned(() => this.#failCommands(CdpPipeClosedError, `CDP pipe read stream ${event}`)));
130
- }
131
- // A killed browser resets its end of the CDP pipes (ECONNRESET/EPIPE on Linux);
132
- // without a listener Node rethrows that as an uncaught exception in the caller.
133
- for (const stream of [this.#writeStream, this.#readStream]) {
134
- stream.on("error", owned(error => this.#failAll(Error(`CDP pipe error: ${error.code ?? error.message}`))));
135
- }
136
- this.#child.on("exit", owned(() => {
137
- this.#connected = false;
138
- this.#failAll(Error("CDP pipe browser exited"));
139
- this.transportEvents.emit("disconnected").catch(() => {});
140
- }));
141
- try {
142
- await writeBrowserPidFile(profileDir, browserPid);
143
- } catch (error) {
144
- await this.#quitFailedLaunch();
145
- throw error;
146
- }
147
- this.#connected = true;
148
- try {
149
- await this.#awaitReady();
150
- await this.#dispatch("Target.setDiscoverTargets", { discover: true }).catch(() => {});
151
- await this.transportEvents.emit("connected");
152
- } catch (error) {
153
- await this.#quitFailedLaunch();
154
- throw error;
155
- }
156
- }
157
-
158
- // Never leave a browser the caller holds no handle to: a rejected launch hands
159
- // back no client, so quit it (SIGTERM, then the bounded grace) before reporting.
160
- async #quitFailedLaunch() {
161
- const child = this.#child;
162
- this.#child = undefined;
163
- this.#connected = false;
164
- this.#failAll(Error("CDP pipe launch failed"));
165
- await terminateChild(child);
166
- }
167
-
168
- // Probes go through #dispatch, never send(): send() would relaunch a browser
169
- // that exited mid-check, each relaunch with a fresh budget (#123). A browser
170
- // that exits fails the launch at once, naming the exit.
171
- async #awaitReady() {
172
- const child = this.#child;
173
- const deadline = Date.now() + this.#readinessTimeoutMs;
174
- const exited = child.exitCode !== null || child.signalCode !== null
175
- ? Promise.resolve("exited")
176
- : new Promise(resolve => child.once("exit", () => resolve("exited")));
177
- let lastError;
178
- while (Date.now() < deadline) {
179
- try {
180
- const outcome = await Promise.race([
181
- this.#dispatch("Browser.getVersion", undefined, undefined, { timeoutMs: 1000 }),
182
- exited,
183
- ]);
184
- if (outcome !== "exited") return;
185
- } catch (error) {
186
- lastError = error;
187
- }
188
- if (child.exitCode !== null || child.signalCode !== null) throw await this.#exitedBeforeReady(child, deadline);
189
- let timer;
190
- try {
191
- await Promise.race([new Promise(resolve => { timer = setTimeout(resolve, 100); }), exited]);
192
- } finally {
193
- clearTimeout(timer);
194
- }
195
- }
196
- const reason = lastError ? String(lastError.message ?? lastError) : "no response";
197
- const tail = this.#stdioTail.trim();
198
- throw Error(
199
- `Browser did not become ready over the CDP pipe (${reason})` +
200
- (tail ? `\nBrowser stdio tail:\n${tail}` : ""),
201
- );
202
- }
203
-
204
- async #exitedBeforeReady(child, deadline) {
205
- // stderr can still hold unread output when "exit" fires; drain it. Bounded:
206
- // a surviving grandchild may hold the write end open indefinitely.
207
- if (child.stderr) {
208
- let timer;
209
- await Promise.race([
210
- finished(child.stderr).catch(() => {}),
211
- new Promise(resolve => { timer = setTimeout(resolve, Math.max(0, Math.min(EXIT_STDERR_DRAIN_MS, deadline - Date.now()))); }),
212
- ]);
213
- clearTimeout(timer);
214
- }
215
- const how = child.signalCode ? `signal ${child.signalCode}` : `exit code ${child.exitCode}`;
216
- const firstLine = this.#stderrHead.split("\n").map(line => line.trim()).find(Boolean);
217
- // The first line already follows the colon; drop its repeat from the tail.
218
- const tailLines = this.#stdioTail.trim().split("\n");
219
- const repeat = tailLines.findIndex(line => line.trim() === firstLine);
220
- if (repeat !== -1) tailLines.splice(repeat, 1);
221
- const tail = tailLines.join("\n").trim();
222
- return Error(
223
- `Browser exited before it became ready over the CDP pipe (${how})` +
224
- (firstLine ? `: ${firstLine}` : "") +
225
- (tail ? `\nBrowser stdio tail:\n${tail}` : ""),
226
- );
227
- }
228
-
229
- async send(method, params, sessionId, opts = {}) {
230
- if (method === "Target.createTarget" && opts.capability !== targetCreationCapability) throw Error("Target.createTarget is reserved for createAgentTabs");
231
- if (String(method).startsWith("OmO.")) {
232
- throw Error(`Extension commands are unavailable over pipe transport: ${method}`);
233
- }
234
- await this.ensureConnected();
235
- return this.#dispatch(method, params, sessionId, opts);
236
- }
237
-
238
- async #dispatch(method, params, sessionId, opts = {}) {
239
- const id = this.#seq++;
240
- const msg = { id, method };
241
- if (params !== undefined) msg.params = params;
242
- if (sessionId) msg.sessionId = sessionId;
243
- const entry = {
244
- method, sessionId, targetId: params?.targetId ?? this.#sessionTargets.get(sessionId),
245
- sentAt: performance.now(), receivedBytes: this.#receivedBytes,
246
- };
247
- if (this.#closedSessions.has(sessionId) && method !== "Page.close") {
248
- throw this.#commandError(CdpSessionDetachedError, "Page closed", entry);
249
- }
250
- if (this.#readStream.readableEnded || this.#readStream.destroyed) {
251
- throw this.#commandError(CdpPipeClosedError, "CDP pipe read stream closed", entry);
252
- }
253
- const { promise, resolve, reject } = Promise.withResolvers();
254
- const timeoutMs = opts.timeoutMs ?? this.#commandTimeoutMs;
255
- const timeout = timeoutMs > 0
256
- ? setTimeout(() => {
257
- this.#pending.delete(id);
258
- reject(this.#commandError(CdpCommandTimeoutError, "CDP command timeout", entry));
259
- }, timeoutMs)
260
- : undefined;
261
- this.#pending.set(id, { ...entry, resolve, reject, timeout });
262
- this.#writeStream.write(JSON.stringify(msg) + "\0");
263
- return promise;
264
- }
265
-
266
- on(method, fn) {
267
- return this.#events.on(method, ({ data }) => fn(data.payload, data.meta));
268
- }
269
-
270
- async discoverTargets() {
271
- const { targetInfos } = await this.send("Target.getTargets");
272
- return targetInfos.map(t => ({
273
- id: t.targetId,
274
- type: t.type,
275
- url: t.url ?? "",
276
- title: t.title ?? "",
277
- description: t.description,
278
- faviconUrl: t.faviconUrl,
279
- parentId: t.openerId,
280
- }));
281
- }
282
-
283
-
284
- closeSession(sessionId) {
285
- this.#closedSessions.add(sessionId);
286
- this.#failCommands(CdpSessionDetachedError, "Page closed", sessionId);
287
- }
288
-
289
- async close() {
290
- const child = this.#child;
291
- this.#child = undefined;
292
- if (child && child.exitCode === null) {
293
- const exited = new Promise(resolve => child.once("exit", resolve));
294
- let quitRequested = false;
295
- if (this.#connected) {
296
- await Promise.race([
297
- this.send("Browser.close", undefined, undefined, {
298
- timeoutMs: GRACEFUL_CLOSE_TIMEOUT_MS,
299
- }).then(() => { quitRequested = true; }, () => {}),
300
- exited,
301
- ]);
302
- }
303
- this.#connected = false;
304
- this.#failAll(Error("CDP pipe client closed"));
305
- if (child.exitCode === null) {
306
- let timer;
307
- try {
308
- await Promise.race([
309
- exited,
310
- new Promise(resolve => { timer = setTimeout(resolve, GRACEFUL_CLOSE_TIMEOUT_MS); }),
311
- ]);
312
- } finally {
313
- clearTimeout(timer);
314
- }
315
- }
316
- await terminateChild(child, { quitRequested });
317
- return;
318
- }
319
- this.#connected = false;
320
- this.#failAll(Error("CDP pipe client closed"));
321
- }
322
-
323
- #onData(chunk) {
324
- this.#receivedBytes += chunk.length;
325
- for (const raw of this.#frames.push(chunk)) {
326
- if (raw.length === 0) continue;
327
- let msg;
328
- try { msg = JSON.parse(raw); } catch { this.#malformedFrameCount++; continue; }
329
- this._handleTransportMessage(msg);
330
- }
331
- }
332
-
333
- _handleTransportMessage(msg) {
334
- if (typeof msg.id === "number") {
335
- const entry = this.#pending.get(msg.id);
336
- if (!entry) return;
337
- this.#pending.delete(msg.id);
338
- if (entry.timeout) clearTimeout(entry.timeout);
339
- if (msg.error) {
340
- const err = Error(msg.error.message ?? `CDP command failed: ${entry.method}`);
341
- err.code = msg.error.code;
342
- err.data = msg.error.data;
343
- entry.reject(err);
344
- } else {
345
- if (entry.method === "Target.attachToTarget" && msg.result?.sessionId) {
346
- this.#sessionTargets.set(msg.result.sessionId, entry.targetId);
347
- }
348
- entry.resolve(msg.result);
349
- }
350
- return;
351
- }
352
- if (typeof msg.method === "string") {
353
- if (msg.method === "Target.attachedToTarget" && msg.params?.sessionId && msg.params.targetInfo?.targetId) {
354
- this.#sessionTargets.set(msg.params.sessionId, msg.params.targetInfo.targetId);
355
- } else if (msg.method === "Target.detachedFromTarget" && msg.params?.sessionId) {
356
- this.#failCommands(CdpSessionDetachedError, "CDP session detached", msg.params.sessionId);
357
- this.#sessionTargets.delete(msg.params.sessionId);
358
- } else if (msg.method === "Inspector.targetCrashed" && msg.sessionId) {
359
- // The session outlives a renderer crash and Page.reload brings the target
360
- // back: Chromium answers a pending reload, so leave it and keep the
361
- // session's target. Commands the dead renderer held are answered only by a
362
- // later reload, with "Target crashed"; reject those now.
363
- this.#failCommands(CdpSessionCrashedError, "CDP session crashed", msg.sessionId, "Page.reload");
364
- }
365
- const meta = { sessionId: msg.sessionId };
366
- if (msg.method === "Page.javascriptDialogOpening" && msg.sessionId) {
367
- meta.dialog = new Dialog(msg.params, action => this.send("Page.handleJavaScriptDialog", action, msg.sessionId));
368
- }
369
- const emitted = this.#events.emit(msg.method, { data: { payload: msg.params, meta } }).catch(() => {});
370
- return meta.dialog
371
- ? emitted.then(() => answerWithPolicy(meta.dialog, this.#dialogPolicy, msg.params)).catch(() => {})
372
- : undefined;
373
- }
374
- }
375
-
376
- #commandError(ErrorType, reason, entry) {
377
- const now = performance.now();
378
- const receivedBytesSinceSend = this.#receivedBytes - entry.receivedBytes;
379
- const details = {
380
- method: entry.method, launchId: this.#launchId,
381
- sessionId: entry.sessionId ?? null,
382
- targetId: entry.targetId ?? this.#sessionTargets.get(entry.sessionId) ?? null,
383
- elapsedSinceLaunchMs: Math.round(now - this.#launchedAt),
384
- commandElapsedMs: Math.round(now - entry.sentAt),
385
- receivedReplyBytes: receivedBytesSinceSend > 0, receivedBytesSinceSend,
386
- malformedFrameCount: this.#malformedFrameCount,
387
- };
388
- const context = Object.entries(details).map(([key, value]) => `${key}=${value}`).join(", ");
389
- return new ErrorType(`${reason}: ${entry.method} (${context})`, details);
390
- }
391
-
392
- #failCommands(ErrorType, reason, sessionId, sparedMethod) {
393
- for (const [id, entry] of this.#pending) {
394
- if (sessionId !== undefined && entry.sessionId !== sessionId) continue;
395
- if (entry.method === sparedMethod) continue;
396
- if (entry.timeout) clearTimeout(entry.timeout);
397
- this.#pending.delete(id);
398
- entry.reject(this.#commandError(ErrorType, reason, entry));
399
- }
400
- }
401
-
402
- #failAll(err) {
403
- for (const entry of this.#pending.values()) {
404
- if (entry.timeout) clearTimeout(entry.timeout);
405
- entry.reject(err);
406
- }
407
- this.#pending.clear();
408
- }
409
- }
410
-
411
- export async function connectPipe({ browserPath, browserArgs = [], spawnOptions, storageRoot, commandTimeoutMs, readinessTimeoutMs, logId, dialogPolicy } = {}) {
412
- const client = new PipeCdpClient({ browserPath, browserArgs, spawnOptions, commandTimeoutMs, readinessTimeoutMs, logId, dialogPolicy });
413
- await client.ensureConnected();
414
- const connection = new BrowserConnection(client, { storageRoot });
415
- await connection.initialize();
416
- connection.browserProcess = client.childProcess;
417
- return connection;
418
- }
@@ -1,64 +0,0 @@
1
- import { execFile } from "node:child_process";
2
- import { readFile } from "node:fs/promises";
3
- import path from "node:path";
4
- import { promisify } from "node:util";
5
-
6
- const execFileAsync = promisify(execFile);
7
- const WINDOWS_START_TIME_TIMEOUT_MS = 15_000;
8
- let ownStartTime;
9
-
10
- // When the process holding `pid` started, in a form that only has to compare
11
- // equal to itself on this machine; null when the platform cannot say. A dead
12
- // holder's pid can be reused, and pid plus start time is what stays unique.
13
- export async function processStartTime(pid) {
14
- if (process.platform === "win32") {
15
- if (!Number.isInteger(pid) || pid <= 0) return null;
16
- // Win32_Process.CreationDate is readable for every process, not only the
17
- // caller's own (Get-Process StartTime is not), and a reused pid usually
18
- // belongs to someone else. FILETIME ticks keep the value locale-free.
19
- // PowerShell is spawned by absolute path: a bare name resolves from the cwd
20
- // before PATH, which another user may be able to write.
21
- const systemRoot = process.env.SystemRoot || process.env.windir || "C:\\Windows";
22
- try {
23
- const { stdout } = await execFileAsync(
24
- path.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
25
- [
26
- "-NoLogo",
27
- "-NoProfile",
28
- "-NonInteractive",
29
- "-Command",
30
- `(Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId=${pid}').CreationDate.ToFileTimeUtc()`,
31
- ],
32
- { timeout: WINDOWS_START_TIME_TIMEOUT_MS, windowsHide: true },
33
- );
34
- const ticks = String(stdout).trim();
35
- return /^\d+$/.test(ticks) ? ticks : null;
36
- } catch {
37
- return null;
38
- }
39
- }
40
- if (process.platform === "linux") {
41
- try {
42
- const text = await readFile(`/proc/${pid}/stat`, "utf8");
43
- // Field 22 (starttime); the fields after the parenthesised comm start at 3.
44
- return text.slice(text.lastIndexOf(")") + 2).split(" ")[19] ?? null;
45
- } catch {
46
- return null;
47
- }
48
- }
49
- try {
50
- const { stdout } = await execFileAsync("ps", ["-o", "lstart=", "-p", String(pid)], {
51
- env: { ...process.env, LC_ALL: "C", TZ: "UTC" },
52
- });
53
- return stdout.trim() || null;
54
- } catch {
55
- return null;
56
- }
57
- }
58
-
59
- // This process's own start time, looked up once: on Windows each lookup is a
60
- // PowerShell call.
61
- export function ownProcessStartTime() {
62
- ownStartTime ??= processStartTime(process.pid);
63
- return ownStartTime;
64
- }