omowright 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +290 -2
  3. package/TOOLS.md +487 -0
  4. package/bin/omowright-cloak.mjs +112 -0
  5. package/package.json +57 -4
  6. package/presets/agent-events/SKILL.md +75 -0
  7. package/presets/captcha/SKILL.md +129 -0
  8. package/presets/chrome/SKILL.md +88 -0
  9. package/presets/cloak-bridge/SKILL.md +43 -0
  10. package/presets/network/SKILL.md +126 -0
  11. package/presets/visual-browse/SKILL.md +103 -0
  12. package/skills/omowright/SKILL.md +193 -0
  13. package/skills/omowright/references/1password.md +118 -0
  14. package/skills/omowright/references/browserskill.md +195 -0
  15. package/skills/omowright/references/eval-kernel.md +100 -0
  16. package/skills/omowright/references/frames-layers-human.md +123 -0
  17. package/skills/omowright/references/quickstart.md +109 -0
  18. package/skills/omowright/references/stealth.md +174 -0
  19. package/src/agent-tabs.js +179 -0
  20. package/src/aria-hidden.js +47 -0
  21. package/src/bridge-schemas.js +44 -0
  22. package/src/bridge-transport.js +83 -0
  23. package/src/browser-context.js +105 -0
  24. package/src/browser-process.js +127 -0
  25. package/src/bsk/browser-signals.js +90 -0
  26. package/src/bsk/browsers.js +114 -0
  27. package/src/bsk/connect.js +75 -0
  28. package/src/bsk/daemon-info.js +100 -0
  29. package/src/bsk/external-extension.js +110 -0
  30. package/src/bsk/identify-browser.js +88 -0
  31. package/src/bsk/install-cli.js +81 -0
  32. package/src/bsk/ipc-client.js +236 -0
  33. package/src/bsk/onboard.js +140 -0
  34. package/src/bsk/screenshot.js +49 -0
  35. package/src/bsk/session.js +131 -0
  36. package/src/bsk/snapshot.js +56 -0
  37. package/src/bsk/targets.js +25 -0
  38. package/src/captcha-wait.js +79 -0
  39. package/src/captcha.js +142 -0
  40. package/src/cdp-errors.js +23 -0
  41. package/src/cdp-methods.js +69 -0
  42. package/src/chrome-profile.js +176 -0
  43. package/src/chrome.js +194 -0
  44. package/src/cloak-profile.js +266 -0
  45. package/src/connection.js +234 -0
  46. package/src/console-events.js +12 -0
  47. package/src/cookies.js +39 -0
  48. package/src/core.js +1702 -0
  49. package/src/cua.js +74 -0
  50. package/src/dialog-policy.js +80 -0
  51. package/src/emulate.js +127 -0
  52. package/src/events.js +111 -0
  53. package/src/frames-snapshot.js +138 -0
  54. package/src/har.js +103 -0
  55. package/src/human-handoff.js +124 -0
  56. package/src/index.js +89 -0
  57. package/src/injected.js +3 -0
  58. package/src/instance-lock.js +74 -0
  59. package/src/instances.js +490 -0
  60. package/src/internal-capability.js +1 -0
  61. package/src/launch-endpoint.js +185 -0
  62. package/src/layers.js +138 -0
  63. package/src/llm.js +201 -0
  64. package/src/lock-backend-win32.js +54 -0
  65. package/src/lock-backend.js +81 -0
  66. package/src/native-host-win32.js +201 -0
  67. package/src/network-events.js +223 -0
  68. package/src/network-snoop.js +229 -0
  69. package/src/nul-frames.js +28 -0
  70. package/src/open-shadow-query.js +101 -0
  71. package/src/owner-only.js +196 -0
  72. package/src/page-bundle.js +1478 -0
  73. package/src/page-events.js +45 -0
  74. package/src/page-routes.js +94 -0
  75. package/src/page-setup.js +239 -0
  76. package/src/pipe.js +418 -0
  77. package/src/process-start-time.js +64 -0
  78. package/src/routes.js +256 -0
  79. package/src/running-browser.js +85 -0
  80. package/src/scroll-collect.js +73 -0
  81. package/src/serial-emitter.js +17 -0
  82. package/src/shared-connections.js +285 -0
  83. package/src/snapshot-diff.js +75 -0
  84. package/src/text-matching.js +101 -0
  85. package/src/trace.js +183 -0
  86. package/src/url-match.js +148 -0
  87. package/src/viewport.js +12 -0
package/src/pipe.js ADDED
@@ -0,0 +1,418 @@
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
+ }
@@ -0,0 +1,64 @@
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
+ }