@xbrowser/cli 1.34.0 → 1.36.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 (63) hide show
  1. package/README.md +137 -80
  2. package/dist/{browser-ZWEJ663M.js → browser-IEZOLTHA.js} +3 -3
  3. package/dist/{browser-GXL6V2JW.js → browser-NHQDQRXB.js} +3 -2
  4. package/dist/{browser-X7LO42UI.js → browser-XELRNYBL.js} +3 -3
  5. package/dist/cdp-driver-CCG3OJUQ.js +49 -0
  6. package/dist/{cdp-driver-GCFEMRFJ.js → cdp-driver-HBMCD7NU.js} +2 -2
  7. package/dist/{cdp-driver-QOUSRPR2.js → cdp-driver-MJD7YIQI.js} +2 -2
  8. package/dist/{cdp-driver-4MNHDU2J.js → cdp-driver-YJU4GRSV.js} +196 -95
  9. package/dist/chunk-2IOFJ6A3.js +149 -0
  10. package/dist/chunk-3SZTCI33.js +147 -0
  11. package/dist/{chunk-VYTQLZAX.js → chunk-5UXRFNXG.js} +28 -2
  12. package/dist/{chunk-NAIHOVDZ.js → chunk-63526WET.js} +2 -8
  13. package/dist/{chunk-YIL44YDX.js → chunk-6DS3T6UK.js} +196 -95
  14. package/dist/{chunk-J4NOL5XX.js → chunk-7KVH6MQG.js} +1099 -204
  15. package/dist/{chunk-N7DFS4V7.js → chunk-ENTENDF5.js} +9 -3
  16. package/dist/{chunk-R57Z5KZX.js → chunk-GVJ2UY65.js} +1078 -185
  17. package/dist/{chunk-3E6VVMK2.js → chunk-GYGVHWG3.js} +272 -1460
  18. package/dist/{chunk-2KPI5GKP.js → chunk-IYCB2KJL.js} +2 -8
  19. package/dist/chunk-KSB4PMCY.js +1380 -0
  20. package/dist/{chunk-RMYKVZIZ.js → chunk-L6QJUB33.js} +28 -2
  21. package/dist/{chunk-TBJUSUKF.js → chunk-NBT2CE3H.js} +140 -96
  22. package/dist/{chunk-DZ6XEPAH.js → chunk-PGEZJ6V3.js} +9 -3
  23. package/dist/chunk-RGL2YTWQ.js +64 -0
  24. package/dist/chunk-RL5FFY2Q.js +150 -0
  25. package/dist/{chunk-43TEMG4U.js → chunk-SBMVECDS.js} +3 -1
  26. package/dist/{chunk-BND5O5KC.js → chunk-SQLICOPZ.js} +177 -240
  27. package/dist/{chunk-O5PASNI7.js → chunk-UUW5EGES.js} +139 -237
  28. package/dist/{chunk-SH6OTPXN.js → chunk-WGWPWNIA.js} +78 -17
  29. package/dist/chunk-YW4BIJQL.js +489 -0
  30. package/dist/{chunk-R7AG7ONI.js → chunk-ZCZELQCS.js} +196 -95
  31. package/dist/chunk-ZR4NHTUV.js +39 -0
  32. package/dist/cli.js +2284 -307
  33. package/dist/convert-JNOM6H6A.js +490 -0
  34. package/dist/{convert-R3XXYKC6.js → convert-K6TLQEPX.js} +5 -3
  35. package/dist/{daemon-client-7D6EZNOE.js → daemon-client-AKQK5IIB.js} +79 -18
  36. package/dist/{daemon-client-HEGAXWGK.js → daemon-client-BBPQWLUX.js} +7 -1
  37. package/dist/daemon-main.js +2305 -164
  38. package/dist/human-interaction-BGAZC3JR.js +12 -0
  39. package/dist/human-interaction-TPKPEE7A.js +11 -0
  40. package/dist/human-interaction-ZSD3IX6Q.js +12 -0
  41. package/dist/index.d.ts +251 -97
  42. package/dist/index.js +2929 -298
  43. package/dist/{launcher-TOLF23ET.js → launcher-AUJK5QQM.js} +1 -1
  44. package/dist/{launcher-ZYB32LSZ.js → launcher-QBAZ6F5L.js} +1 -1
  45. package/dist/mistake-ledger-2B4N54CO.js +29 -0
  46. package/dist/{recovery-ORHJSBDN.js → recovery-5AGY7CV3.js} +4 -5
  47. package/dist/{recovery-XDKN63O5.js → recovery-7NRRHLS4.js} +2 -2
  48. package/dist/{recovery-JFGV3DBX.js → recovery-TIBRFGRP.js} +2 -2
  49. package/dist/run-routes-64IBBVOX.js +24 -0
  50. package/dist/run-routes-FG4LIACU.js +26 -0
  51. package/dist/{server-5U56MQD2.js → server-K22LJBO2.js} +5 -4
  52. package/dist/{server-R4OYD7ZC.js → server-ZHZDJJMG.js} +5 -3
  53. package/dist/{session-recorder-RUNQOJ7T.js → session-recorder-CNTY5KXF.js} +1 -1
  54. package/dist/{session-recorder-N7VEKJVW.js → session-recorder-KMKSQWEP.js} +1 -1
  55. package/dist/{session-replayer-GHEFFNGV.js → session-replayer-4TCLQI76.js} +1 -1
  56. package/dist/viewer-routes-CEO7HWCB.js +11 -0
  57. package/package.json +3 -2
  58. package/dist/chunk-ETCO4SNK.js +0 -206
  59. package/dist/chunk-QCV2PI7U.js +0 -184
  60. package/dist/convert-LB3GJTLR.js +0 -207
  61. package/dist/human-interaction-ISMMOJOK.js +0 -8
  62. package/dist/human-interaction-STTZZZ5N.js +0 -8
  63. package/dist/human-interaction-UXFYV7DU.js +0 -8
@@ -5,148 +5,6 @@ import {
5
5
  // src/human-interaction.ts
6
6
  import { execFile } from "child_process";
7
7
 
8
- // src/screencast.ts
9
- var ScreencastCapturer = class {
10
- interval;
11
- quality;
12
- type;
13
- maxWidth;
14
- maxHeight;
15
- isCapturing = false;
16
- frameCallback = null;
17
- // CDP Cast state
18
- cdpSession = null;
19
- sessionId = "";
20
- // Fallback polling state
21
- fallbackTimer = null;
22
- constructor(options = {}) {
23
- this.interval = options.interval || 100;
24
- this.quality = options.quality || 60;
25
- this.type = options.type || "jpeg";
26
- this.maxWidth = options.width || 1920;
27
- this.maxHeight = options.height || 1080;
28
- }
29
- /**
30
- * Start screencast capture using CDP Page.startScreencast.
31
- *
32
- * If CDP session creation fails (non-Chromium, restricted access),
33
- * automatically falls back to `page.screenshot()` polling.
34
- */
35
- async startCapture(page, sessionId, onFrame) {
36
- if (this.isCapturing) {
37
- throw new Error("Screencast is already capturing");
38
- }
39
- this.isCapturing = true;
40
- this.frameCallback = onFrame;
41
- this.sessionId = sessionId;
42
- try {
43
- const cdp = await page.context().newCDPSession(page);
44
- this.cdpSession = cdp;
45
- cdp.on("Page.screencastFrame", async (params) => {
46
- const cb = this.frameCallback;
47
- if (!cb) return;
48
- cdp.send("Page.screencastFrameAck", { sessionId: params.sessionId }).catch(() => {
49
- });
50
- const logicalViewport = page.viewportSize();
51
- const viewport = logicalViewport ?? {
52
- width: params.metadata?.deviceWidth || this.maxWidth,
53
- height: params.metadata?.deviceHeight || this.maxHeight
54
- };
55
- cb({
56
- id: crypto.randomUUID(),
57
- sessionId: this.sessionId,
58
- timestamp: Date.now(),
59
- data: Buffer.from(params.data, "base64"),
60
- url: page.url(),
61
- viewport
62
- });
63
- });
64
- await cdp.send("Page.startScreencast", {
65
- format: this.type === "png" ? "png" : "jpeg",
66
- quality: this.type === "jpeg" ? this.quality : void 0,
67
- maxWidth: this.maxWidth,
68
- maxHeight: this.maxHeight
69
- });
70
- } catch {
71
- this.cdpSession = null;
72
- this.startFallbackPolling(page, sessionId);
73
- }
74
- }
75
- /**
76
- * Fallback: periodic page.screenshot() polling when CDP Cast is unavailable.
77
- */
78
- startFallbackPolling(page, sessionId) {
79
- const captureLoop = async () => {
80
- if (!this.frameCallback) return;
81
- try {
82
- const frame = await this.captureFrame(page, sessionId);
83
- this.frameCallback(frame);
84
- } catch {
85
- }
86
- };
87
- captureLoop();
88
- this.fallbackTimer = setInterval(captureLoop, this.interval);
89
- }
90
- /**
91
- * Capture a single screenshot frame from the page (fallback mode).
92
- */
93
- async captureFrame(page, sessionId) {
94
- let viewport = page.viewportSize();
95
- if (!viewport) {
96
- try {
97
- viewport = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
98
- } catch {
99
- viewport = { width: 1920, height: 1080 };
100
- }
101
- }
102
- const screenshot = await page.screenshot({
103
- type: this.type,
104
- quality: this.type === "jpeg" ? this.quality : void 0
105
- });
106
- return {
107
- id: crypto.randomUUID(),
108
- sessionId,
109
- timestamp: Date.now(),
110
- data: screenshot,
111
- url: page.url(),
112
- viewport: viewport || { width: 0, height: 0 }
113
- };
114
- }
115
- /**
116
- * Stop the current screencast capture.
117
- */
118
- async stopCapture() {
119
- if (this.cdpSession) {
120
- try {
121
- this.cdpSession.off("Page.screencastFrame", () => {
122
- });
123
- await this.cdpSession.send("Page.stopScreencast");
124
- } catch {
125
- }
126
- try {
127
- await this.cdpSession.detach();
128
- } catch {
129
- }
130
- this.cdpSession = null;
131
- }
132
- if (this.fallbackTimer) {
133
- clearInterval(this.fallbackTimer);
134
- this.fallbackTimer = null;
135
- }
136
- this.isCapturing = false;
137
- this.frameCallback = null;
138
- }
139
- isActive() {
140
- return this.isCapturing;
141
- }
142
- setInterval(interval) {
143
- this.interval = interval;
144
- }
145
- setQuality(quality) {
146
- this.quality = quality;
147
- }
148
- };
149
-
150
8
  // src/captcha-detector.ts
151
9
  var CAPTCHA_SELECTORS = [
152
10
  { selector: 'iframe[src*="recaptcha"]', type: "recaptcha", confidence: "high" },
@@ -318,27 +176,52 @@ var WebhookNotifier = class {
318
176
  };
319
177
 
320
178
  // src/human-interaction.ts
179
+ var DEFAULT_HUMAN_INTERACTION_SESSION = "default";
180
+ var activeWaitsByServer = /* @__PURE__ */ new WeakMap();
181
+ function acquireWaitSlot(server, sessionName) {
182
+ let sessions = activeWaitsByServer.get(server);
183
+ if (!sessions) {
184
+ sessions = /* @__PURE__ */ new Map();
185
+ activeWaitsByServer.set(server, sessions);
186
+ }
187
+ if (sessions.has(sessionName)) return false;
188
+ sessions.set(sessionName, "starting");
189
+ return true;
190
+ }
191
+ function releaseWaitSlot(server, sessionName) {
192
+ activeWaitsByServer.get(server)?.delete(sessionName);
193
+ }
194
+ function isHumanWaitActive(server, sessionName) {
195
+ return activeWaitsByServer.get(server)?.get(sessionName) === "waiting";
196
+ }
321
197
  var HumanInteractionManager = class {
322
198
  wsServer;
323
199
  page;
324
- capturer;
200
+ sessionName;
325
201
  webhook;
326
202
  autoOpen;
327
- constructor(wsServer, page) {
203
+ constructor(wsServer, page, sessionName) {
328
204
  this.wsServer = wsServer;
329
205
  this.page = page;
330
- this.capturer = new ScreencastCapturer();
206
+ this.sessionName = sessionName && sessionName.trim() ? sessionName.trim() : DEFAULT_HUMAN_INTERACTION_SESSION;
331
207
  const cfg = getCaptchaConfig();
332
208
  this.webhook = new WebhookNotifier(cfg.notifyUrl);
333
209
  this.autoOpen = cfg.autoOpen;
334
- this.wsServer.registerSession("default", page);
210
+ this.wsServer.registerSession(this.sessionName, page);
211
+ }
212
+ /** The named session this manager interacts with. */
213
+ get session() {
214
+ return this.sessionName;
215
+ }
216
+ buildPreviewUrl() {
217
+ return `http://localhost:${this.wsServer.getPort()}/preview/${encodeURIComponent(this.sessionName)}`;
335
218
  }
336
219
  async sendWebhook(event, overrides = {}) {
337
220
  await this.webhook.notify({
338
221
  event,
339
222
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
340
223
  url: this.page.url(),
341
- previewUrl: `http://localhost:${this.wsServer.getPort()}`,
224
+ previewUrl: this.buildPreviewUrl(),
342
225
  ...overrides
343
226
  });
344
227
  }
@@ -355,11 +238,16 @@ var HumanInteractionManager = class {
355
238
  /**
356
239
  * Wait for a human to solve a CAPTCHA or complete an interaction.
357
240
  *
358
- * Starts screencast streaming, sends webhook and broadcast notifications,
359
- * then polls for CAPTCHA resolution or waits for a manual solve signal.
241
+ * Sends session-scoped notifications and waits for CAPTCHA resolution
242
+ * or a manual solve signal from a viewer bound to this session.
243
+ *
244
+ * Only one wait may be in flight per session per WSServer. The wait
245
+ * slot, listener, and timers are cleaned
246
+ * up on every exit path (auto-detected / preview / timeout / error).
360
247
  *
361
248
  * @param options - Configuration for timeout, auto-detection, and reason text.
362
249
  * @returns Result indicating whether the CAPTCHA was solved and by what method.
250
+ * @throws If a wait is already in progress for this session.
363
251
  */
364
252
  async waitForHuman(options = {}) {
365
253
  const {
@@ -368,105 +256,119 @@ var HumanInteractionManager = class {
368
256
  autoDetect = true,
369
257
  detectInterval = 2e3
370
258
  } = options;
371
- const captcha = await CaptchaDetector.detect(this.page);
372
- const captchaInfo = captcha.detected ? captcha : void 0;
373
- await this.capturer.startCapture(this.page, "default", (frame) => {
374
- this.wsServer.broadcast({
375
- type: "screenshot",
376
- data: {
377
- sessionId: frame.sessionId,
378
- id: frame.id,
379
- timestamp: frame.timestamp,
380
- data: frame.data,
381
- url: frame.url,
382
- viewport: frame.viewport
383
- }
384
- });
385
- });
386
- const previewUrl = `http://localhost:${this.wsServer.getPort()}`;
387
- await this.sendWebhook("captcha-detected", {
388
- reason: captchaInfo ? `${captchaInfo.type ?? "unknown"} CAPTCHA detected` : reason,
389
- timeout,
390
- targetUrl: this.page.url()
391
- });
392
- this.wsServer.broadcast({
393
- type: "captcha-detected",
394
- sessionId: "default",
395
- url: this.page.url(),
396
- reason: captchaInfo ? `${captchaInfo.type ?? "unknown"} CAPTCHA detected` : reason,
397
- timeout
398
- });
399
- this.tryAutoOpen(previewUrl);
400
- console.log("");
401
- console.log("\u26A0\uFE0F \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
402
- console.log(`\u26A0\uFE0F ${captchaInfo ? (captchaInfo.type ?? "UNKNOWN").toUpperCase() + " CAPTCHA" : "INTERACTION"} REQUIRED`);
403
- console.log(`\u26A0\uFE0F URL: ${this.page.url()}`);
404
- console.log(`\u26A0\uFE0F `);
405
- console.log(`\u26A0\uFE0F Solve via:`);
406
- console.log(`\u26A0\uFE0F \u{1F4FA} Preview: ${previewUrl}`);
407
- console.log(`\u26A0\uFE0F \u{1F310} Direct: ${this.page.url()}`);
408
- console.log(`\u26A0\uFE0F \u23ED\uFE0F Skip`);
409
- console.log(`\u26A0\uFE0F \u274C Abort`);
410
- console.log(`\u26A0\uFE0F `);
411
- console.log(`\u26A0\uFE0F \u23F3 Waiting... (${timeout}s timeout)`);
412
- console.log("\u26A0\uFE0F \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
413
- console.log("");
414
- return new Promise((resolve) => {
415
- let resolved = false;
416
- let pollTimer = null;
417
- let timeoutTimer = null;
418
- const cleanup = () => {
419
- if (pollTimer) clearInterval(pollTimer);
420
- if (timeoutTimer) clearTimeout(timeoutTimer);
421
- this.wsServer.removeListener("human-solved", onHumanSolved);
422
- this.capturer.stopCapture();
423
- };
424
- if (autoDetect && captchaInfo) {
425
- pollTimer = setInterval(async () => {
426
- if (resolved) return;
427
- try {
428
- const solved = await CaptchaDetector.isSolved(this.page, captchaInfo.selector);
429
- if (solved) {
430
- resolved = true;
431
- cleanup();
432
- this.wsServer.broadcast({ type: "resolved", sessionId: "default" });
433
- console.log("\u2705 CAPTCHA auto-detected as solved!");
434
- this.sendWebhook("captcha-resolved", { reason: "auto-detected" });
435
- resolve({ solved: true, method: "auto-detected" });
436
- }
437
- } catch {
438
- }
439
- }, detectInterval);
259
+ if (!acquireWaitSlot(this.wsServer, this.sessionName)) {
260
+ throw new Error(
261
+ `waitForHuman already in progress for session "${this.sessionName}" \u2014 only one human-interaction wait per session is allowed`
262
+ );
263
+ }
264
+ let slotReleased = false;
265
+ const releaseSlot = () => {
266
+ if (!slotReleased) {
267
+ slotReleased = true;
268
+ releaseWaitSlot(this.wsServer, this.sessionName);
440
269
  }
441
- const onHumanSolved = () => {
442
- if (!resolved) {
443
- resolved = true;
444
- cleanup();
445
- this.wsServer.broadcast({ type: "resolved", sessionId: "default" });
446
- console.log("\u2705 CAPTCHA solved via preview!");
447
- this.sendWebhook("captcha-resolved", { reason: "preview" });
448
- resolve({ solved: true, method: "preview" });
270
+ };
271
+ try {
272
+ const captcha = await CaptchaDetector.detect(this.page);
273
+ const captchaInfo = captcha.detected ? captcha : void 0;
274
+ const previewUrl = this.buildPreviewUrl();
275
+ const waitReason = captchaInfo ? `${captchaInfo.type ?? "unknown"} CAPTCHA detected` : reason;
276
+ console.log("");
277
+ console.log("\u26A0\uFE0F \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
278
+ console.log(`\u26A0\uFE0F ${captchaInfo ? (captchaInfo.type ?? "UNKNOWN").toUpperCase() + " CAPTCHA" : "INTERACTION"} REQUIRED (session: ${this.sessionName})`);
279
+ console.log(`\u26A0\uFE0F URL: ${this.page.url()}`);
280
+ console.log(`\u26A0\uFE0F `);
281
+ console.log(`\u26A0\uFE0F Solve via:`);
282
+ console.log(`\u26A0\uFE0F \u{1F4FA} Preview: ${previewUrl}`);
283
+ console.log(`\u26A0\uFE0F \u{1F310} Direct: ${this.page.url()}`);
284
+ console.log(`\u26A0\uFE0F \u23ED\uFE0F Skip`);
285
+ console.log(`\u26A0\uFE0F \u274C Abort`);
286
+ console.log(`\u26A0\uFE0F `);
287
+ console.log(`\u26A0\uFE0F \u23F3 Waiting... (${timeout}s timeout)`);
288
+ console.log("\u26A0\uFE0F \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
289
+ console.log("");
290
+ return await new Promise((resolve) => {
291
+ let resolved = false;
292
+ let pollTimer = null;
293
+ let timeoutTimer = null;
294
+ const cleanup = () => {
295
+ if (pollTimer) clearInterval(pollTimer);
296
+ if (timeoutTimer) clearTimeout(timeoutTimer);
297
+ this.wsServer.removeListener("human-solved", onHumanSolved);
298
+ releaseSlot();
299
+ };
300
+ if (autoDetect && captchaInfo) {
301
+ pollTimer = setInterval(async () => {
302
+ if (resolved) return;
303
+ try {
304
+ const solved = await CaptchaDetector.isSolved(this.page, captchaInfo.selector);
305
+ if (solved && !resolved) {
306
+ resolved = true;
307
+ cleanup();
308
+ this.wsServer.broadcastToSession(this.sessionName, {
309
+ type: "resolved",
310
+ sessionId: this.sessionName
311
+ });
312
+ console.log("\u2705 CAPTCHA auto-detected as solved!");
313
+ this.sendWebhook("captcha-resolved", { reason: "auto-detected" });
314
+ resolve({ solved: true, method: "auto-detected" });
315
+ }
316
+ } catch {
317
+ }
318
+ }, detectInterval);
449
319
  }
450
- };
451
- this.wsServer.on("human-solved", onHumanSolved);
452
- if (timeout > 0) {
453
- timeoutTimer = setTimeout(() => {
320
+ const onHumanSolved = (payload) => {
321
+ if (!payload || payload.sessionId !== this.sessionName) return;
454
322
  if (!resolved) {
455
323
  resolved = true;
456
324
  cleanup();
457
- console.log("\u23F0 Timeout - skipping");
458
- this.sendWebhook("captcha-resolved", { reason: "timeout" });
459
- resolve({ solved: false, method: "timeout" });
325
+ this.wsServer.broadcastToSession(this.sessionName, {
326
+ type: "resolved",
327
+ sessionId: this.sessionName
328
+ });
329
+ console.log("\u2705 CAPTCHA solved via preview!");
330
+ this.sendWebhook("captcha-resolved", { reason: "preview" });
331
+ resolve({ solved: true, method: "preview" });
460
332
  }
461
- }, timeout * 1e3);
462
- }
463
- });
333
+ };
334
+ this.wsServer.on("human-solved", onHumanSolved);
335
+ if (timeout > 0) {
336
+ timeoutTimer = setTimeout(() => {
337
+ if (!resolved) {
338
+ resolved = true;
339
+ cleanup();
340
+ this.wsServer.broadcastToSession(this.sessionName, {
341
+ type: "handoff-timeout",
342
+ sessionId: this.sessionName
343
+ });
344
+ console.log("\u23F0 Timeout - skipping");
345
+ this.sendWebhook("captcha-resolved", { reason: "timeout" });
346
+ resolve({ solved: false, method: "timeout" });
347
+ }
348
+ }, timeout * 1e3);
349
+ }
350
+ activeWaitsByServer.get(this.wsServer)?.set(this.sessionName, "waiting");
351
+ this.wsServer.broadcastToSession(this.sessionName, {
352
+ type: "captcha-detected",
353
+ sessionId: this.sessionName,
354
+ url: this.page.url(),
355
+ reason: waitReason,
356
+ timeout
357
+ });
358
+ void this.sendWebhook("captcha-detected", { reason: waitReason, timeout, targetUrl: this.page.url() });
359
+ this.tryAutoOpen(previewUrl);
360
+ });
361
+ } catch (err) {
362
+ releaseSlot();
363
+ throw err;
364
+ }
464
365
  }
465
366
  };
466
367
 
467
368
  export {
468
- ScreencastCapturer,
469
369
  CaptchaDetector,
470
370
  WebhookNotifier,
371
+ DEFAULT_HUMAN_INTERACTION_SESSION,
372
+ isHumanWaitActive,
471
373
  HumanInteractionManager
472
374
  };
@@ -11,12 +11,45 @@ import { createRequire } from "module";
11
11
  var require2 = createRequire(import.meta.url);
12
12
  var pkg = require2("../package.json");
13
13
  var version = pkg.version;
14
+ var buildId = true ? "mwuaecno" : "dev";
14
15
 
15
16
  // src/client/daemon-client.ts
16
17
  import { request as httpRequest } from "http";
17
- var DAEMON_PORT = 9224;
18
+ var DAEMON_PORT = parseInt(process.env.XBROWSER_DAEMON_PORT || "9224", 10);
18
19
  var DAEMON_BASE = `http://localhost:${DAEMON_PORT}`;
19
20
  var _ensurePromise = null;
21
+ function checkDaemonHealth(health, cli, skipBuildCheck, sessionsKnown) {
22
+ if (health.version && health.version !== cli.version) {
23
+ return { action: "restart", reason: `version daemon=${health.version} cli=${cli.version}` };
24
+ }
25
+ if (skipBuildCheck || !health.buildId || health.buildId === "dev" || cli.buildId === "dev" || health.buildId === cli.buildId) {
26
+ return { action: "use", reason: "" };
27
+ }
28
+ const reason = `build daemon=${health.buildId} cli=${cli.buildId}`;
29
+ const sessions = typeof health.activeSessions === "number" ? health.activeSessions : sessionsKnown;
30
+ if (typeof sessions === "number" && sessions > 0) {
31
+ return {
32
+ action: "refuse",
33
+ reason: `Refusing to restart the daemon: this CLI comes from a different build (${reason}), but the daemon is holding ${sessions} active session(s) that a restart would close. Run this build on its own daemon with XBROWSER_DAEMON_PORT=<port>, or set XBROWSER_DAEMON_SKIP_BUILD_CHECK=1 to use the running daemon as is.`
34
+ };
35
+ }
36
+ return { action: "restart", reason };
37
+ }
38
+ async function countDaemonSessions() {
39
+ try {
40
+ const res = await fetch(`${DAEMON_BASE}/rpc`, {
41
+ method: "POST",
42
+ headers: { "Content-Type": "application/json" },
43
+ body: JSON.stringify({ method: "session:list", params: {} }),
44
+ signal: AbortSignal.timeout(2e3)
45
+ });
46
+ if (!res.ok) return null;
47
+ const data = await res.json();
48
+ return Array.isArray(data) ? data.length : null;
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
20
53
  async function ensureDaemonRunning() {
21
54
  if (_ensurePromise) {
22
55
  try {
@@ -25,24 +58,32 @@ async function ensureDaemonRunning() {
25
58
  }
26
59
  _ensurePromise = null;
27
60
  }
61
+ const skipBuildCheck = process.env.XBROWSER_DAEMON_SKIP_BUILD_CHECK === "1";
28
62
  for (let attempt = 0; attempt < 3; attempt++) {
29
- const healthOk = await fetch(`${DAEMON_BASE}/health`, { signal: AbortSignal.timeout(2e3) }).then((r) => r.ok ? r.json() : null).then((d) => {
30
- if (d?.status === "ok") {
31
- if (d.version && d.version !== version) {
32
- return { needsRestart: true };
33
- }
34
- return { needsRestart: false };
35
- }
36
- return null;
63
+ const probe = await fetch(`${DAEMON_BASE}/health`, { signal: AbortSignal.timeout(2e3) }).then((r) => r.ok ? r.json() : null).then((d) => {
64
+ if (d?.status !== "ok") return null;
65
+ const cli = { version, buildId };
66
+ return { health: d, check: checkDaemonHealth(d, cli, skipBuildCheck) };
37
67
  }).catch(() => null);
38
- if (healthOk?.needsRestart === false) return;
39
- if (healthOk?.needsRestart === true) {
40
- console.error(`\u26A0\uFE0F Daemon version mismatch. Restarting...`);
68
+ if (!probe) {
69
+ if (attempt < 2) await new Promise((r) => setTimeout(r, 500));
70
+ continue;
71
+ }
72
+ let { check } = probe;
73
+ if (check.action === "restart" && check.reason.startsWith("build") && typeof probe.health.activeSessions !== "number") {
74
+ const sessions = await countDaemonSessions();
75
+ if (sessions !== null) {
76
+ check = checkDaemonHealth(probe.health, { version, buildId }, skipBuildCheck, sessions);
77
+ }
78
+ }
79
+ if (check.action === "use") return;
80
+ if (check.action === "refuse") throw new Error(check.reason);
81
+ if (check.action === "restart") {
82
+ console.error(`\u26A0\uFE0F Daemon ${check.reason} mismatch. Restarting...`);
41
83
  await stopDaemonProcess().catch(() => {
42
84
  });
43
85
  break;
44
86
  }
45
- if (attempt < 2) await new Promise((r) => setTimeout(r, 500));
46
87
  }
47
88
  console.error("\u{1F504} Starting daemon...");
48
89
  _ensurePromise = startDaemonProcess(DAEMON_PORT).then(() => {
@@ -139,13 +180,14 @@ async function forwardSessionClose(name) {
139
180
  async function forwardSessionList() {
140
181
  return rpcCall("session:list", {}, 5e3);
141
182
  }
142
- async function forwardExec(command, params, session = "default", cdpEndpoint, timeoutMs = 12e4) {
183
+ async function forwardExec(command, params, session = "default", cdpEndpoint, timeoutMs = 12e4, bridge) {
143
184
  const rpcParams = { command, params, session };
144
185
  if (cdpEndpoint) rpcParams.cdpEndpoint = cdpEndpoint;
186
+ if (bridge) rpcParams.bridge = true;
145
187
  try {
146
188
  return await rpcCall("exec", rpcParams, timeoutMs);
147
189
  } catch (e) {
148
- return { success: false, data: null, message: errMsg(e), duration: 0 };
190
+ return { success: false, data: null, message: friendlyDaemonError(e), duration: 0 };
149
191
  }
150
192
  }
151
193
  async function forwardPluginExec(command, params, session = "default", cdpEndpoint, timeoutMs = 12e4) {
@@ -154,7 +196,7 @@ async function forwardPluginExec(command, params, session = "default", cdpEndpoi
154
196
  try {
155
197
  return await rpcCall("plugin:exec", rpcParams, timeoutMs);
156
198
  } catch (e) {
157
- return { success: false, data: null, message: errMsg(e), duration: 0 };
199
+ return { success: false, data: null, message: friendlyDaemonError(e), duration: 0 };
158
200
  }
159
201
  }
160
202
  async function forwardChain(input, session = "default", cdpEndpoint) {
@@ -163,8 +205,24 @@ async function forwardChain(input, session = "default", cdpEndpoint) {
163
205
  try {
164
206
  return await rpcCall("chain", params, 12e4);
165
207
  } catch (e) {
166
- return { success: false, steps: [], totalDuration: 0, stoppedReason: errMsg(e) };
208
+ return { success: false, steps: [], totalDuration: 0, stoppedReason: friendlyDaemonError(e) };
209
+ }
210
+ }
211
+ async function forwardManagedRun(chain, session, fileMode = false) {
212
+ return rpcCall("session:run", { chain, session, fileMode }, 20 * 6e4);
213
+ }
214
+ async function forwardSessionState(action, session) {
215
+ return rpcCall(`session:${action}`, { session }, 12e4);
216
+ }
217
+ function friendlyDaemonError(e) {
218
+ const msg = errMsg(e);
219
+ if (/ECONNREFUSED/i.test(msg)) {
220
+ return `Daemon \u6216\u6D4F\u89C8\u5668\u4E0D\u53EF\u8FBE (${msg})\u3002\u8BF7\u76F4\u63A5\u91CD\u8BD5\uFF08daemon \u4F1A\u81EA\u52A8\u62C9\u8D77\uFF09\uFF0C\u6216\u68C0\u67E5 --cdp \u7AEF\u53E3\u662F\u5426\u6709\u6D4F\u89C8\u5668\u8FD0\u884C\u3002`;
221
+ }
222
+ if (/ETIMEDOUT|EHOSTUNREACH|ENETUNREACH/i.test(msg)) {
223
+ return `\u7F51\u7EDC\u4E0D\u53EF\u8FBE (${msg})\u3002\u8BF7\u68C0\u67E5\u9632\u706B\u5899\u6216 --cdp \u7AEF\u53E3\u3002`;
167
224
  }
225
+ return msg;
168
226
  }
169
227
  async function forwardAgentObserve(session = "default", options) {
170
228
  const params = { session };
@@ -251,6 +309,7 @@ async function forwardViewerCheckSelector(name, selector) {
251
309
 
252
310
  export {
253
311
  version,
312
+ checkDaemonHealth,
254
313
  isDaemonRunning,
255
314
  daemonPing,
256
315
  forwardSessionCreate,
@@ -259,6 +318,8 @@ export {
259
318
  forwardExec,
260
319
  forwardPluginExec,
261
320
  forwardChain,
321
+ forwardManagedRun,
322
+ forwardSessionState,
262
323
  forwardAgentObserve,
263
324
  forwardAgentAct,
264
325
  forwardAgentWait,