@xbrowser/cli 1.28.0 → 1.30.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 (48) hide show
  1. package/README.md +2 -2
  2. package/dist/{browser-4IYIHZ6R.js → browser-6PFTHZI3.js} +8 -6
  3. package/dist/{browser-NYYCR4O7.js → browser-I2NLJN2A.js} +5 -3
  4. package/dist/{browser-ZD53IMUJ.js → browser-KOUA4ZDA.js} +6 -4
  5. package/dist/{cdp-driver-EFEW4ZEN.js → cdp-driver-3ETNFQA4.js} +4 -4
  6. package/dist/{cdp-driver-HB744QB4.js → cdp-driver-U7HDQMQ5.js} +1578 -896
  7. package/dist/{cdp-driver-4X6Q62WI.js → cdp-driver-WBFJNOLD.js} +3 -3
  8. package/dist/{chunk-SEEWE5SJ.js → chunk-2KPI5GKP.js} +3 -0
  9. package/dist/{chunk-OEC7ZSFW.js → chunk-3K57RYVC.js} +1942 -1580
  10. package/dist/{chunk-75DNUI6M.js → chunk-6UJU2FJK.js} +146 -0
  11. package/dist/{chunk-FNXA6FDM.js → chunk-BND5O5KC.js} +2 -1
  12. package/dist/{chunk-KECYFWJO.js → chunk-BOZTIIBT.js} +441 -427
  13. package/dist/{chunk-WK3INZLA.js → chunk-KPTD3SNJ.js} +1121 -759
  14. package/dist/{chunk-OSZNJT4U.js → chunk-LM32MNBB.js} +79 -8
  15. package/dist/{chunk-T2AI24A5.js → chunk-NAIHOVDZ.js} +3 -0
  16. package/dist/{chunk-WYETQ5C7.js → chunk-NEE6EMYA.js} +14 -1
  17. package/dist/{chunk-3PUOISKE.js → chunk-NINETOM4.js} +524 -495
  18. package/dist/{chunk-SOPN4XDK.js → chunk-O5PASNI7.js} +2 -1
  19. package/dist/{chunk-ME5FO5YV.js → chunk-OCECE22C.js} +1578 -896
  20. package/dist/{chunk-HSYRAV3H.js → chunk-OSIDUT4H.js} +2151 -1440
  21. package/dist/{chunk-HBMEFSTB.js → chunk-QCV2PI7U.js} +2 -1
  22. package/dist/{chunk-IR6C24P7.js → chunk-RMYKVZIZ.js} +1103 -1043
  23. package/dist/{chunk-R3F4K2SB.js → chunk-SMYSNO4M.js} +10 -0
  24. package/dist/{chunk-J3HXZVSN.js → chunk-SPNWUUHA.js} +1452 -916
  25. package/dist/{chunk-PGKV24QN.js → chunk-TBJUSUKF.js} +1 -1
  26. package/dist/{chunk-V6KGBU5J.js → chunk-VYTQLZAX.js} +1091 -1040
  27. package/dist/cli.js +3447 -3377
  28. package/dist/daemon-main.js +1240 -786
  29. package/dist/{human-interaction-CTZ4IWXJ.js → human-interaction-ISMMOJOK.js} +2 -2
  30. package/dist/{human-interaction-HJCK45SL.js → human-interaction-STTZZZ5N.js} +1 -1
  31. package/dist/{human-interaction-V3VDGHHI.js → human-interaction-UXFYV7DU.js} +1 -1
  32. package/dist/index.d.ts +458 -476
  33. package/dist/index.js +3766 -3576
  34. package/dist/{launcher-SJ44X25U.js → launcher-TOLF23ET.js} +1 -1
  35. package/dist/{launcher-XHKIC4GP.js → launcher-ZYB32LSZ.js} +1 -1
  36. package/dist/{plugin-singleton-GGSBI3EG.js → plugin-singleton-A6RNITJW.js} +1 -1
  37. package/dist/{proxy-NKCYE76M.js → proxy-H3RIUOCN.js} +2 -2
  38. package/dist/{recovery-EBKORYEU.js → recovery-JFGV3DBX.js} +1 -1
  39. package/dist/{recovery-5C4FBA5O.js → recovery-ORHJSBDN.js} +2 -2
  40. package/dist/{recovery-IMZUGWSS.js → recovery-XDKN63O5.js} +1 -1
  41. package/dist/{server-26SE6YZR.js → server-TG47W7MV.js} +7 -7
  42. package/dist/{server-JXF3JOAM.js → server-U3YAX5MJ.js} +4 -4
  43. package/dist/{session-recorder-GEZVQBKW.js → session-recorder-N7VEKJVW.js} +1 -1
  44. package/dist/{session-recorder-563ISSJK.js → session-recorder-RUNQOJ7T.js} +1 -1
  45. package/dist/{session-replayer-TXTNTG33.js → session-replayer-XLWQ47BB.js} +1 -1
  46. package/dist/{stealth-QNSMIHQK.js → stealth-FMPZO2OB.js} +1 -1
  47. package/dist/{stealth-MHJNBJY7.js → stealth-MCKFKPZ6.js} +1 -1
  48. package/package.json +9 -3
package/dist/index.d.ts CHANGED
@@ -6,6 +6,40 @@ import { ZodType, ZodTypeDef, z } from 'zod';
6
6
 
7
7
  declare const version: any;
8
8
 
9
+ interface HookOutput {
10
+ _hook: string;
11
+ [key: string]: unknown;
12
+ }
13
+ interface ExecutionResult {
14
+ success: boolean;
15
+ data: unknown;
16
+ message?: string;
17
+ duration: number;
18
+ tips?: Tip[];
19
+ hookOutputs?: HookOutput[];
20
+ error?: {
21
+ code: string;
22
+ level: string;
23
+ };
24
+ }
25
+ interface ChainStepResult {
26
+ command: string;
27
+ raw: string;
28
+ success: boolean;
29
+ data: unknown;
30
+ message?: string;
31
+ duration: number;
32
+ tips?: Tip[];
33
+ hookOutputs?: HookOutput[];
34
+ }
35
+ interface ChainExecutionResult {
36
+ success: boolean;
37
+ steps: ChainStepResult[];
38
+ totalDuration: number;
39
+ stoppedAt?: number;
40
+ stoppedReason?: string;
41
+ }
42
+
9
43
  /**
10
44
  * stealth.ts — Behavioral stealth layer for CDP driver
11
45
  *
@@ -114,6 +148,11 @@ interface StealthConfig {
114
148
  interface XBBrowser {
115
149
  readonly disconnected: boolean;
116
150
  close(): Promise<void>;
151
+ /**
152
+ * Disconnect this WebSocket without closing pages or contexts. This is the
153
+ * safe cleanup path when a session attached to an existing user tab.
154
+ */
155
+ disconnect(): Promise<void>;
117
156
  newContext(opts?: XBContextOptions): Promise<XBContext>;
118
157
  contexts(): XBContext[];
119
158
  /**
@@ -288,6 +327,37 @@ interface XBPage {
288
327
  * 绕过页面同源策略(CDP 是调试通道)——跨域嵌入内容读写的唯一路径。
289
328
  */
290
329
  evaluateInFrame<R = unknown>(urlIncludes: string, expression: string): Promise<R>;
330
+ /** 浏览器级 iframe target 列表(OOPIF 只在这里可见,Page.getFrameTree 看不到) */
331
+ listFrameTargets(): Promise<Array<{
332
+ url: string;
333
+ targetId: string;
334
+ }>>;
335
+ /**
336
+ * 指定 OOPIF 的鼠标——Input 域事件派发到 iframe 自己的 session 才进得去
337
+ * (主页面 session 的输入被进程隔离挡在外面)。坐标 = iframe 局部坐标。
338
+ */
339
+ frameMouse(urlIncludes: string, opts?: {
340
+ fresh?: boolean;
341
+ }): Promise<XBMouse>;
342
+ /**
343
+ * 带重试的 frame 鼠标操作:session 失效(OOPIF 被 Chrome 异步销毁/
344
+ * 验证码 iframe 重建)时强制重 attach 再做一次。fn 内不要缓存 mouse
345
+ * 跨调用使用——重试时实例会换新(鼠标位置重置)。
346
+ */
347
+ runFrameMouse<T>(urlIncludes: string, fn: (mouse: XBMouse) => Promise<T>): Promise<T>;
348
+ /** 在 OOPIF 内点击选择器命中的元素(轮询等待 + stealth 落点) */
349
+ clickInFrame(urlIncludes: string, selector: string, opts?: {
350
+ timeoutMs?: number;
351
+ }): Promise<{
352
+ x: number;
353
+ y: number;
354
+ }>;
355
+ /** 在 OOPIF 内填输入框(点击聚焦 + insertText + 回读) */
356
+ fillInFrame(urlIncludes: string, selector: string, text: string, opts?: {
357
+ timeoutMs?: number;
358
+ }): Promise<{
359
+ value: string;
360
+ }>;
291
361
  bringToFront(): Promise<void>;
292
362
  setExtraHTTPHeaders(headers: Record<string, string>): Promise<void>;
293
363
  setOfflineMode(offline: boolean): Promise<void>;
@@ -407,7 +477,9 @@ interface XBMouse {
407
477
  button?: 'left' | 'right' | 'middle';
408
478
  clickCount?: number;
409
479
  delay?: number;
410
- stealth?: boolean;
480
+ stealth?: boolean; /** 元素宽高——stealth 落点偏移用(XBMouseImpl 已支持) */
481
+ elementWidth?: number;
482
+ elementHeight?: number;
411
483
  }): Promise<void>;
412
484
  dblclick(x: number, y: number, opts?: {
413
485
  button?: 'left' | 'right' | 'middle';
@@ -422,6 +494,8 @@ interface XBMouse {
422
494
  steps?: number;
423
495
  }): Promise<void>;
424
496
  wheel(deltaX: number, deltaY: number): Promise<void>;
497
+ /** 先移动到 (x,y) 再派发滚轮(trusted mouseWheel) */
498
+ wheelAt(x: number, y: number, deltaX: number, deltaY: number): Promise<void>;
425
499
  /** Drag from current position to (x,y) — drives the real HTML5 DnD pipeline */
426
500
  drag(x: number, y: number, opts?: {
427
501
  steps?: number;
@@ -485,6 +559,7 @@ interface XBScreenshotOptions {
485
559
  y: number;
486
560
  width: number;
487
561
  height: number;
562
+ scale?: number;
488
563
  };
489
564
  omitBackground?: boolean;
490
565
  timeout?: number;
@@ -551,6 +626,212 @@ interface XBRequest {
551
626
  response(): Promise<XBResponse | null>;
552
627
  }
553
628
 
629
+ /**
630
+ * CDP Interceptor — Core Types
631
+ *
632
+ * Models the JSON-RPC 2.0 messages flowing over the CDP WebSocket and
633
+ * defines the rule/decision system for intercepting, blocking, or
634
+ * transforming automation traffic to avoid anti-crawler detection.
635
+ */
636
+ /** Raw JSON-RPC 2.0 request as it appears on the wire */
637
+ interface CDPRequest {
638
+ id: number;
639
+ method: string;
640
+ params?: Record<string, unknown>;
641
+ sessionId?: string;
642
+ }
643
+ /** Raw JSON-RPC 2.0 response (success) */
644
+ interface CDPResponse {
645
+ id: number;
646
+ result?: Record<string, unknown>;
647
+ sessionId?: string;
648
+ }
649
+ /** Raw JSON-RPC 2.0 error response */
650
+ interface CDPError {
651
+ id: number;
652
+ error: {
653
+ code: number;
654
+ message: string;
655
+ data?: unknown;
656
+ };
657
+ sessionId?: string;
658
+ }
659
+ /** Union of all possible CDP messages */
660
+ type CDPMessage = CDPRequest | CDPResponse | CDPError;
661
+ /** Direction: from client → browser or browser → client */
662
+ type MessageDirection = 'client→browser' | 'browser→client';
663
+ /** Structured log entry for a single CDP message */
664
+ interface CDPLogEntry {
665
+ /** Unix timestamp in ms */
666
+ timestamp: number;
667
+ /** Message direction */
668
+ direction: MessageDirection;
669
+ /** Session identifier (for grouping messages) */
670
+ sessionId: string;
671
+ /** CDP method (e.g. "Runtime.evaluate"), undefined for responses */
672
+ method?: string;
673
+ /** Sanitized payload summary */
674
+ payload: Record<string, unknown>;
675
+ /** Rule decision that was applied, if any */
676
+ decision?: DecisionResult;
677
+ }
678
+ /**
679
+ * Severity of a rule violation
680
+ *
681
+ * - **danger**: definitely triggers anti-crawler detection — block immediately
682
+ * - **warn**: likely problematic — log and warn, but don't block yet
683
+ * - **info**: informational only — could be a future concern
684
+ */
685
+ type ViolationSeverity = 'danger' | 'warn' | 'info';
686
+ /**
687
+ * Action the interceptor should take for a matched message
688
+ *
689
+ * - **block**: reject the message, return CDP error, never reach browser
690
+ * - **transform**: modify the message before forwarding
691
+ * - **pass**: forward unchanged (log only)
692
+ */
693
+ type DecisionAction = 'block' | 'transform' | 'pass';
694
+ /** Result of a rule evaluation */
695
+ interface DecisionResult {
696
+ /** Matched rule id */
697
+ ruleId: string;
698
+ action: DecisionAction;
699
+ severity: ViolationSeverity;
700
+ /** Human-readable explanation of why this was flagged */
701
+ reason: string;
702
+ /** Suggested fix / alternative approach */
703
+ suggestion?: string;
704
+ /** Transformed params (only for 'transform' action) */
705
+ transformedParams?: Record<string, unknown>;
706
+ /** Custom CDP error code (only for 'block' action) */
707
+ errorCode?: number;
708
+ /** Custom CDP error message (only for 'block' action) */
709
+ errorMessage?: string;
710
+ }
711
+ /** Handler context passed to each rule */
712
+ interface RuleContext {
713
+ method: string;
714
+ params: Record<string, unknown>;
715
+ sessionId: string;
716
+ /** Direction: the message is being sent TO the browser */
717
+ direction: MessageDirection;
718
+ /** Per-session state store (rules can stash data here) */
719
+ sessionState: Map<string, unknown>;
720
+ }
721
+ /**
722
+ * A CDP interception rule
723
+ *
724
+ * Rules are evaluated **in priority order** (lower number = earlier).
725
+ * The first rule that returns a decision wins.
726
+ */
727
+ interface CDPInterceptorRule {
728
+ /** Unique rule identifier */
729
+ id: string;
730
+ /** Human-readable name */
731
+ name: string;
732
+ /** Priority: lower numbers are evaluated first */
733
+ priority: number;
734
+ /**
735
+ * Quick pre-filter — skip expensive checks for messages that can't match.
736
+ * Return false to skip this rule.
737
+ */
738
+ canHandle?(ctx: RuleContext): boolean;
739
+ /**
740
+ * Evaluate the message and return a decision.
741
+ * Return null to pass (no match).
742
+ */
743
+ evaluate(ctx: RuleContext): DecisionResult | null;
744
+ }
745
+ /** Configuration for the CDP interceptor proxy */
746
+ interface CDPInterceptorConfig {
747
+ /** Chromium CDP WebSocket endpoint (e.g. ws://localhost:9222/...) */
748
+ cdpEndpoint: string;
749
+ /** Port to listen on for incoming client connections */
750
+ listenPort?: number;
751
+ /** Rules to apply, defaults to built-in rules */
752
+ rules?: CDPInterceptorRule[];
753
+ /** Enable logging (default: true) */
754
+ enableLogging?: boolean;
755
+ /** Log output directory (default: no file logging) */
756
+ logDir?: string;
757
+ /** Block mode: 'strict' blocks danger only, 'paranoid' blocks warn+ */
758
+ blockMode?: 'strict' | 'paranoid';
759
+ }
760
+ /** Statistics collected during a proxy session */
761
+ interface CDPInterceptorStats {
762
+ totalMessages: number;
763
+ blockedMessages: number;
764
+ transformedMessages: number;
765
+ passedMessages: number;
766
+ /** Breakdown by rule id */
767
+ byRule: Record<string, {
768
+ matched: number;
769
+ blocked: number;
770
+ transformed: number;
771
+ }>;
772
+ }
773
+
774
+ interface ManagedSession {
775
+ id: string;
776
+ name: string;
777
+ context: XBContext;
778
+ page: XBPage;
779
+ browser: XBBrowser;
780
+ createdAt: string;
781
+ lastActivityAt: number;
782
+ isCDP?: boolean;
783
+ cdpEndpoint?: string;
784
+ /** True when CDP attach reused an existing user tab; close must only disconnect. */
785
+ reusedExistingPage?: boolean;
786
+ }
787
+ interface BrowserLaunchOptions {
788
+ headless?: boolean;
789
+ executablePath?: string;
790
+ cdpEndpoint?: string;
791
+ intercept?: boolean | CDPInterceptorConfig;
792
+ }
793
+
794
+ /**
795
+ * CDP Interceptor Proxy
796
+ *
797
+ * A thin WebSocket proxy that sits between any automation tool (Playwright,
798
+ * Puppeteer, etc.) and Chromium's CDP endpoint. Every JSON-RPC message is
799
+ * intercepted, analyzed against a rule engine, and either passed through,
800
+ * blocked (with error response), or transformed before reaching the browser.
801
+ *
802
+ * Usage:
803
+ * ```
804
+ * const proxy = new CDPInterceptorProxy({ cdpEndpoint: 'ws://localhost:9222/...' });
805
+ * await proxy.start(); // starts listening on a random port
806
+ * // Now connect your automation tool to: ws://localhost:{proxy.port}
807
+ * ```
808
+ */
809
+
810
+ declare class CDPInterceptorProxy {
811
+ private wss;
812
+ private engine;
813
+ private config;
814
+ private logger;
815
+ private started;
816
+ stats: CDPInterceptorStats;
817
+ constructor(config: CDPInterceptorConfig);
818
+ /** The port the proxy is listening on (only valid after start()) */
819
+ get port(): number;
820
+ /** Start the proxy server */
821
+ start(): Promise<number>;
822
+ /** Stop the proxy server */
823
+ stop(): Promise<void>;
824
+ /** Get accumulated statistics */
825
+ getStats(): CDPInterceptorStats;
826
+ /** Get recent log entries (for inspection) */
827
+ getRecentLogs(count?: number): CDPLogEntry[];
828
+ private handleConnection;
829
+ private handleClientMessage;
830
+ private handleBrowserMessage;
831
+ private parseMessage;
832
+ private recordDecision;
833
+ }
834
+
554
835
  /**
555
836
  * Configuration for the WebSocket server.
556
837
  */
@@ -640,6 +921,8 @@ type WSMessage = {
640
921
  interface ViewInfo {
641
922
  id: string;
642
923
  label: string;
924
+ kind: 'view' | 'image' | 'qr';
925
+ src?: string;
643
926
  rect: {
644
927
  x: number;
645
928
  y: number;
@@ -676,6 +959,13 @@ type WSInboundMessage = {
676
959
  type: 'snapshot_request';
677
960
  format?: string;
678
961
  quality?: number;
962
+ clip?: {
963
+ x: number;
964
+ y: number;
965
+ width: number;
966
+ height: number;
967
+ };
968
+ scale?: number;
679
969
  } | {
680
970
  type: 'bind';
681
971
  sessionId: string;
@@ -746,330 +1036,80 @@ interface CommandMessage {
746
1036
  sessionId: string;
747
1037
  command: string;
748
1038
  args: unknown[];
749
- phase: 'before' | 'after';
750
- result?: unknown;
751
- error?: string;
752
- timestamp: number;
753
- duration?: number;
754
- }
755
- /**
756
- * A server status change notification.
757
- */
758
- interface StatusMessage {
759
- status: 'connected' | 'disconnected' | 'error';
760
- sessionId?: string;
761
- message?: string;
762
- viewport?: {
763
- width: number;
764
- height: number;
765
- };
766
- }
767
- /**
768
- * WebSocket server for streaming browser screenshots and handling remote input.
769
- *
770
- * Two modes:
771
- * 1. **Standalone**: `start()` creates its own WS server on a port.
772
- * 2. **Attached**: `attachToServer(httpServer)` shares an existing HTTP server
773
- * via the WS upgrade mechanism (same port as HTTP, e.g., daemon port 9224).
774
- *
775
- * **Lazy screencast**: Screencast capture only starts when the first WS client
776
- * binds to a session, and stops when the last client for that session disconnects.
777
- *
778
- * Responsibilities are delegated to:
779
- * - **SessionManager**: client/session lifecycle, capturer start/stop, element monitors
780
- * - **StreamCoordinator**: frame processing, stream state, crop management
781
- * - **MessageDispatcher**: inbound message routing to typed handlers
782
- */
783
- declare class WSServer extends EventEmitter {
784
- private port;
785
- private host;
786
- private wsServer;
787
- private isRunning;
788
- private readonly streamCoordinator;
789
- private readonly sessionManager;
790
- private readonly messageDispatcher;
791
- constructor(config?: WSServerConfig);
792
- private setupSessionManagerEvents;
793
- registerSession(sessionId: string, page: XBPage, options?: {
794
- interval?: number;
795
- quality?: number;
796
- type?: 'jpeg' | 'png';
797
- width?: number;
798
- height?: number;
799
- }): void;
800
- /** Restart screencast for a session — used by viewer reconnect button. */
801
- reconnectSession(sessionId: string): Promise<void>;
802
- unregisterSession(sessionId: string): void;
803
- pauseScreencast(sessionId: string): Promise<void>;
804
- resumeScreencast(sessionId: string): Promise<void>;
805
- private startScreencastIfNeeded;
806
- private stopScreencastIfNeeded;
807
- bindClientToSession(clientId: string, sessionId: string): void;
808
- private sendBoundStatus;
809
- start(): Promise<void>;
810
- attachToServer(httpServer: Server, path?: string): Promise<void>;
811
- stop(): Promise<void>;
812
- private setupConnectionHandler;
813
- private handleInboundMessage;
814
- private handleClientDisconnect;
815
- private sendToClient;
816
- broadcastToSession(sessionId: string, message: WSMessage): void;
817
- broadcast(message: WSMessage): void;
818
- broadcastBinaryToSession(sessionId: string, payload: Buffer): void;
819
- getClientCount(): number;
820
- getSessionClientCount(sessionId: string): number;
821
- getRunning(): boolean;
822
- getPort(): number;
823
- }
824
-
825
- /**
826
- * Result of a single command execution.
827
- */
828
- interface HookOutput {
829
- _hook: string;
830
- [key: string]: unknown;
831
- }
832
- interface ExecutionResult {
833
- success: boolean;
834
- data: unknown;
835
- message?: string;
836
- duration: number;
837
- tips?: Tip[];
838
- hookOutputs?: HookOutput[];
839
- error?: {
840
- code: string;
841
- level: string;
842
- };
843
- }
844
- /**
845
- * Result of a single step within a command chain execution.
846
- */
847
- interface ChainStepResult {
848
- command: string;
849
- raw: string;
850
- success: boolean;
851
- data: unknown;
852
- message?: string;
853
- duration: number;
854
- tips?: Tip[];
855
- hookOutputs?: HookOutput[];
856
- }
857
- /**
858
- * Result of executing a command chain (multiple commands linked with &&, ||, etc.).
859
- */
860
- interface ChainExecutionResult {
861
- success: boolean;
862
- steps: ChainStepResult[];
863
- totalDuration: number;
864
- stoppedAt?: number;
865
- stoppedReason?: string;
866
- }
867
- /**
868
- * Set or clear the WebSocket server used for streaming command events.
869
- *
870
- * @param server - A WSServer instance to stream events to, or null to disable.
871
- */
872
- declare function setWSServer(server: WSServer | null): void;
873
- /**
874
- * Execute a single browser command against an existing session.
875
- *
876
- * Looks up the command by name, validates parameters via Zod schema,
877
- * resolves the target session, and runs the command handler.
878
- * Streams before/after events to the configured WebSocket server.
879
- *
880
- * @param commandName - Registered command name (e.g. "goto", "click", "fill").
881
- * @param params - Key-value parameters forwarded to the command handler.
882
- * @param sessionName - Name of the target session. Defaults to "default".
883
- * @returns An {@link ExecutionResult} with success status, data, and duration.
884
- *
885
- * @example
886
- * ```ts
887
- * const result = await executeCommand('click', { selector: '#submit' }, 'default');
888
- * if (result.success) console.log('Clicked!', result.data);
889
- * ```
890
- */
891
- declare function executeCommand(commandName: string, params: Record<string, unknown>, sessionName?: string, extraOpts?: {
892
- cdpEndpoint?: string;
893
- skipCleanup?: boolean;
894
- timeout?: number;
895
- _recoveryAttempted?: boolean;
896
- }): Promise<ExecutionResult>;
897
- /**
898
- * Execute a chain of browser commands parsed from a string expression.
899
- *
900
- * Supports `&&` (and-chain, stops on first failure), `||` (or-chain, stops on
901
- * first success), `;` (sequence separator), `->`, `,`, and `+` operators.
902
- * Automatically creates a browser session if none exists and destroys it
903
- * afterwards.
904
- *
905
- * @param input - Raw chain expression (e.g. `"goto https://example.com && click #btn"`).
906
- * @param options - Optional configuration for CDP endpoint, session name, and file mode.
907
- * @returns A {@link ChainExecutionResult} with per-step results and total duration.
908
- *
909
- * @example
910
- * ```ts
911
- * const result = await executeChain('goto https://example.com && click #btn');
912
- * console.log(result.success, result.steps.length);
913
- * ```
914
- */
915
- declare function executeChain(input: string, options?: {
916
- cdpEndpoint?: string;
917
- sessionName?: string;
918
- fileMode?: boolean;
919
- }): Promise<ChainExecutionResult>;
920
- /**
921
- * Check whether the given input string contains chain operators.
922
- *
923
- * Detects `&&`, `;`, `,`, `+`, and `->` surrounded by whitespace.
924
- *
925
- * @param input - The raw input string to test.
926
- * @returns `true` if chain operators are present.
927
- */
928
- declare function isChainInput(input: string): boolean;
929
-
930
- /**
931
- * CDP Interceptor — Core Types
932
- *
933
- * Models the JSON-RPC 2.0 messages flowing over the CDP WebSocket and
934
- * defines the rule/decision system for intercepting, blocking, or
935
- * transforming automation traffic to avoid anti-crawler detection.
936
- */
937
- /** Raw JSON-RPC 2.0 request as it appears on the wire */
938
- interface CDPRequest {
939
- id: number;
940
- method: string;
941
- params?: Record<string, unknown>;
942
- sessionId?: string;
943
- }
944
- /** Raw JSON-RPC 2.0 response (success) */
945
- interface CDPResponse {
946
- id: number;
947
- result?: Record<string, unknown>;
948
- sessionId?: string;
949
- }
950
- /** Raw JSON-RPC 2.0 error response */
951
- interface CDPError {
952
- id: number;
953
- error: {
954
- code: number;
955
- message: string;
956
- data?: unknown;
957
- };
958
- sessionId?: string;
959
- }
960
- /** Union of all possible CDP messages */
961
- type CDPMessage = CDPRequest | CDPResponse | CDPError;
962
- /** Direction: from client → browser or browser → client */
963
- type MessageDirection = 'client→browser' | 'browser→client';
964
- /** Structured log entry for a single CDP message */
965
- interface CDPLogEntry {
966
- /** Unix timestamp in ms */
967
- timestamp: number;
968
- /** Message direction */
969
- direction: MessageDirection;
970
- /** Session identifier (for grouping messages) */
971
- sessionId: string;
972
- /** CDP method (e.g. "Runtime.evaluate"), undefined for responses */
973
- method?: string;
974
- /** Sanitized payload summary */
975
- payload: Record<string, unknown>;
976
- /** Rule decision that was applied, if any */
977
- decision?: DecisionResult;
978
- }
979
- /**
980
- * Severity of a rule violation
981
- *
982
- * - **danger**: definitely triggers anti-crawler detection — block immediately
983
- * - **warn**: likely problematic — log and warn, but don't block yet
984
- * - **info**: informational only — could be a future concern
985
- */
986
- type ViolationSeverity = 'danger' | 'warn' | 'info';
987
- /**
988
- * Action the interceptor should take for a matched message
989
- *
990
- * - **block**: reject the message, return CDP error, never reach browser
991
- * - **transform**: modify the message before forwarding
992
- * - **pass**: forward unchanged (log only)
993
- */
994
- type DecisionAction = 'block' | 'transform' | 'pass';
995
- /** Result of a rule evaluation */
996
- interface DecisionResult {
997
- /** Matched rule id */
998
- ruleId: string;
999
- action: DecisionAction;
1000
- severity: ViolationSeverity;
1001
- /** Human-readable explanation of why this was flagged */
1002
- reason: string;
1003
- /** Suggested fix / alternative approach */
1004
- suggestion?: string;
1005
- /** Transformed params (only for 'transform' action) */
1006
- transformedParams?: Record<string, unknown>;
1007
- /** Custom CDP error code (only for 'block' action) */
1008
- errorCode?: number;
1009
- /** Custom CDP error message (only for 'block' action) */
1010
- errorMessage?: string;
1011
- }
1012
- /** Handler context passed to each rule */
1013
- interface RuleContext {
1014
- method: string;
1015
- params: Record<string, unknown>;
1016
- sessionId: string;
1017
- /** Direction: the message is being sent TO the browser */
1018
- direction: MessageDirection;
1019
- /** Per-session state store (rules can stash data here) */
1020
- sessionState: Map<string, unknown>;
1021
- }
1022
- /**
1023
- * A CDP interception rule
1024
- *
1025
- * Rules are evaluated **in priority order** (lower number = earlier).
1026
- * The first rule that returns a decision wins.
1027
- */
1028
- interface CDPInterceptorRule {
1029
- /** Unique rule identifier */
1030
- id: string;
1031
- /** Human-readable name */
1032
- name: string;
1033
- /** Priority: lower numbers are evaluated first */
1034
- priority: number;
1035
- /**
1036
- * Quick pre-filter — skip expensive checks for messages that can't match.
1037
- * Return false to skip this rule.
1038
- */
1039
- canHandle?(ctx: RuleContext): boolean;
1040
- /**
1041
- * Evaluate the message and return a decision.
1042
- * Return null to pass (no match).
1043
- */
1044
- evaluate(ctx: RuleContext): DecisionResult | null;
1039
+ phase: 'before' | 'after';
1040
+ result?: unknown;
1041
+ error?: string;
1042
+ timestamp: number;
1043
+ duration?: number;
1045
1044
  }
1046
- /** Configuration for the CDP interceptor proxy */
1047
- interface CDPInterceptorConfig {
1048
- /** Chromium CDP WebSocket endpoint (e.g. ws://localhost:9222/...) */
1049
- cdpEndpoint: string;
1050
- /** Port to listen on for incoming client connections */
1051
- listenPort?: number;
1052
- /** Rules to apply, defaults to built-in rules */
1053
- rules?: CDPInterceptorRule[];
1054
- /** Enable logging (default: true) */
1055
- enableLogging?: boolean;
1056
- /** Log output directory (default: no file logging) */
1057
- logDir?: string;
1058
- /** Block mode: 'strict' blocks danger only, 'paranoid' blocks warn+ */
1059
- blockMode?: 'strict' | 'paranoid';
1045
+ /**
1046
+ * A server status change notification.
1047
+ */
1048
+ interface StatusMessage {
1049
+ status: 'connected' | 'disconnected' | 'error';
1050
+ sessionId?: string;
1051
+ message?: string;
1052
+ viewport?: {
1053
+ width: number;
1054
+ height: number;
1055
+ };
1060
1056
  }
1061
- /** Statistics collected during a proxy session */
1062
- interface CDPInterceptorStats {
1063
- totalMessages: number;
1064
- blockedMessages: number;
1065
- transformedMessages: number;
1066
- passedMessages: number;
1067
- /** Breakdown by rule id */
1068
- byRule: Record<string, {
1069
- matched: number;
1070
- blocked: number;
1071
- transformed: number;
1072
- }>;
1057
+ /**
1058
+ * WebSocket server for streaming browser screenshots and handling remote input.
1059
+ *
1060
+ * Two modes:
1061
+ * 1. **Standalone**: `start()` creates its own WS server on a port.
1062
+ * 2. **Attached**: `attachToServer(httpServer)` shares an existing HTTP server
1063
+ * via the WS upgrade mechanism (same port as HTTP, e.g., daemon port 9224).
1064
+ *
1065
+ * **Lazy screencast**: Screencast capture only starts when the first WS client
1066
+ * binds to a session, and stops when the last client for that session disconnects.
1067
+ *
1068
+ * Responsibilities are delegated to:
1069
+ * - **SessionManager**: client/session lifecycle, capturer start/stop, element monitors
1070
+ * - **StreamCoordinator**: frame processing, stream state, crop management
1071
+ * - **MessageDispatcher**: inbound message routing to typed handlers
1072
+ */
1073
+ declare class WSServer extends EventEmitter {
1074
+ private port;
1075
+ private host;
1076
+ private wsServer;
1077
+ private isRunning;
1078
+ private readonly streamCoordinator;
1079
+ private readonly sessionManager;
1080
+ private readonly messageDispatcher;
1081
+ constructor(config?: WSServerConfig);
1082
+ private setupSessionManagerEvents;
1083
+ registerSession(sessionId: string, page: XBPage, options?: {
1084
+ interval?: number;
1085
+ quality?: number;
1086
+ type?: 'jpeg' | 'png';
1087
+ width?: number;
1088
+ height?: number;
1089
+ }): void;
1090
+ /** Restart screencast for a session — used by viewer reconnect button. */
1091
+ reconnectSession(sessionId: string): Promise<void>;
1092
+ unregisterSession(sessionId: string): void;
1093
+ pauseScreencast(sessionId: string): Promise<void>;
1094
+ resumeScreencast(sessionId: string): Promise<void>;
1095
+ private startScreencastIfNeeded;
1096
+ private stopScreencastIfNeeded;
1097
+ bindClientToSession(clientId: string, sessionId: string): void;
1098
+ private sendBoundStatus;
1099
+ start(): Promise<void>;
1100
+ attachToServer(httpServer: Server, path?: string): Promise<void>;
1101
+ stop(): Promise<void>;
1102
+ private setupConnectionHandler;
1103
+ private handleInboundMessage;
1104
+ private handleClientDisconnect;
1105
+ private sendToClient;
1106
+ broadcastToSession(sessionId: string, message: WSMessage): void;
1107
+ broadcast(message: WSMessage): void;
1108
+ broadcastBinaryToSession(sessionId: string, payload: Buffer): void;
1109
+ getClientCount(): number;
1110
+ getSessionClientCount(sessionId: string): number;
1111
+ getRunning(): boolean;
1112
+ getPort(): number;
1073
1113
  }
1074
1114
 
1075
1115
  /**
@@ -1158,6 +1198,8 @@ interface BrowserCommandContext extends Omit<CommandContext, 'waitForHuman' | 'd
1158
1198
  browserContext: XBContext;
1159
1199
  sessionId?: string;
1160
1200
  cdpEndpoint?: string;
1201
+ /** 全局 --frame <url-substring>:命令级 --frame 优先于此默认值(OOPIF 路由) */
1202
+ frame?: string;
1161
1203
  waitForHuman?: (options?: WaitForHumanOptions) => Promise<WaitForHumanResult>;
1162
1204
  detectAntiBot?: (page: XBPage, config?: DetectionConfig) => Promise<DetectionResult>;
1163
1205
  }
@@ -1203,31 +1245,6 @@ declare function getWSServerFromCache(browserContext: XBContext): WSServer | und
1203
1245
  */
1204
1246
  declare function setWSServerCache(browserContext: XBContext, server: WSServer): void;
1205
1247
 
1206
- /**
1207
- * Represents a managed browser session with its Playwright context, page,
1208
- * and its own dedicated Browser connection.
1209
- */
1210
- interface ManagedSession {
1211
- id: string;
1212
- name: string;
1213
- context: XBContext;
1214
- page: XBPage;
1215
- browser: XBBrowser;
1216
- createdAt: string;
1217
- lastActivityAt: number;
1218
- isCDP?: boolean;
1219
- cdpEndpoint?: string;
1220
- }
1221
- /**
1222
- * Options for launching or connecting to a browser instance.
1223
- */
1224
- interface BrowserLaunchOptions {
1225
- headless?: boolean;
1226
- executablePath?: string;
1227
- cdpEndpoint?: string;
1228
- /** Enable CDP-level interception for anti-crawler protection */
1229
- intercept?: boolean | CDPInterceptorConfig;
1230
- }
1231
1248
  /**
1232
1249
  * Get or create the shared browser instance (lazy singleton).
1233
1250
  *
@@ -1256,23 +1273,6 @@ declare function findSession(name: string): ManagedSession | undefined;
1256
1273
  * @returns Array of all active sessions.
1257
1274
  */
1258
1275
  declare function getAllSessions(): ManagedSession[];
1259
- /**
1260
- * Create a new browser session with a page and optional initial URL.
1261
- *
1262
- * Each session gets its own dedicated Browser connection. If connecting via
1263
- * CDP, reuses existing pages when possible instead of creating a new
1264
- * context/page pair.
1265
- *
1266
- * @param name - Unique name for the session.
1267
- * @param url - Optional URL to navigate to after creation.
1268
- * @param options - Browser launch or CDP connection options.
1269
- * @returns The newly created managed session.
1270
- *
1271
- * @example
1272
- * ```ts
1273
- * const session = await createSession('default', 'https://example.com');
1274
- * ```
1275
- */
1276
1276
  declare function createSession(name: string, url?: string, options?: BrowserLaunchOptions): Promise<ManagedSession>;
1277
1277
  /**
1278
1278
  * Close a session by its name or ID.
@@ -1303,6 +1303,48 @@ declare function destroyBrowser(): Promise<void>;
1303
1303
  */
1304
1304
  declare function resetForTesting(): void;
1305
1305
 
1306
+ declare function setWSServer(server: WSServer | null): void;
1307
+
1308
+ /**
1309
+ * Execute a single browser command against an existing session.
1310
+ *
1311
+ * Looks up the command by name, validates parameters via Zod schema,
1312
+ * resolves the target session, and runs the command handler.
1313
+ * Streams before/after events to the configured WebSocket server.
1314
+ *
1315
+ * @param commandName - Registered command name (e.g. "goto", "click", "fill").
1316
+ * @param params - Key-value parameters forwarded to the command handler.
1317
+ * @param sessionName - Name of the target session. Defaults to "default".
1318
+ * @returns An {@link ExecutionResult} with success status, data, and duration.
1319
+ *
1320
+ * @example
1321
+ * ```ts
1322
+ * const result = await executeCommand('click', { selector: '#submit' }, 'default');
1323
+ * if (result.success) console.log('Clicked!', result.data);
1324
+ * ```
1325
+ */
1326
+ declare function executeCommand(commandName: string, params: Record<string, unknown>, sessionName?: string, extraOpts?: {
1327
+ cdpEndpoint?: string;
1328
+ skipCleanup?: boolean;
1329
+ timeout?: number;
1330
+ _recoveryAttempted?: boolean;
1331
+ }): Promise<ExecutionResult>;
1332
+ declare function executeChain(input: string, options?: {
1333
+ cdpEndpoint?: string;
1334
+ sessionName?: string;
1335
+ fileMode?: boolean;
1336
+ frame?: string;
1337
+ }): Promise<ChainExecutionResult>;
1338
+ /**
1339
+ * Check whether the given input string contains chain operators.
1340
+ *
1341
+ * Detects `&&`, `;`, `,`, `+`, and `->` surrounded by whitespace.
1342
+ *
1343
+ * @param input - The raw input string to test.
1344
+ * @returns `true` if chain operators are present.
1345
+ */
1346
+ declare function isChainInput(input: string): boolean;
1347
+
1306
1348
  /**
1307
1349
  * Describes a single scope level in the browser automation hierarchy.
1308
1350
  */
@@ -1342,6 +1384,14 @@ interface BrowserCommandDefinition<P extends ZodType<unknown, ZodTypeDef, unknow
1342
1384
  * The executor will resolve `eN` ref values to real selectors before calling the handler.
1343
1385
  */
1344
1386
  selectorParams?: string[];
1387
+ /**
1388
+ * Usage examples shown in `--help` output. Rendered by xcli-core's helpGenerator.
1389
+ */
1390
+ examples?: Array<{
1391
+ cmd: string;
1392
+ description?: string;
1393
+ output?: string;
1394
+ }>;
1345
1395
  handler: (params: z.infer<P>, ctx: BrowserCommandContext) => Promise<unknown>;
1346
1396
  }
1347
1397
  /**
@@ -1354,6 +1404,11 @@ interface RegisteredCommand {
1354
1404
  readonly parameters?: ZodType<unknown>;
1355
1405
  readonly result?: ZodType<unknown>;
1356
1406
  readonly selectorParams?: string[];
1407
+ readonly examples?: Array<{
1408
+ cmd: string;
1409
+ description?: string;
1410
+ output?: string;
1411
+ }>;
1357
1412
  readonly handler: (params: Record<string, unknown>, ctx: BrowserCommandContext) => Promise<unknown>;
1358
1413
  }
1359
1414
  /**
@@ -2096,6 +2151,28 @@ interface RecordingSummary {
2096
2151
  elements: Record<string, ElementRef>;
2097
2152
  checkpoints: CheckpointEntry[];
2098
2153
  }
2154
+ interface CompactSummaryFlowItem {
2155
+ step: number;
2156
+ action: string;
2157
+ }
2158
+ interface CompactSummaryApi {
2159
+ method: string;
2160
+ url: string;
2161
+ path: string;
2162
+ status: number;
2163
+ contentType: string;
2164
+ responseSize: number;
2165
+ requestBody?: unknown;
2166
+ }
2167
+ interface RecordingCompactSummary {
2168
+ startUrl: string;
2169
+ recordedAt: string;
2170
+ durationMs: number;
2171
+ totalActions: number;
2172
+ totalNetworkRequests: number;
2173
+ flow: CompactSummaryFlowItem[];
2174
+ keyApis: CompactSummaryApi[];
2175
+ }
2099
2176
  type CheckpointType = 'dialog' | 'captcha' | 'login' | 'iframe' | 'slider' | 'custom';
2100
2177
  interface CheckpointEntry {
2101
2178
  id: number;
@@ -2161,14 +2238,13 @@ declare class SessionRecorder {
2161
2238
  private startUrl;
2162
2239
  private startedAt;
2163
2240
  private actions;
2164
- private network;
2241
+ private networkCapture;
2165
2242
  private contextChanges;
2166
2243
  private checkpoints;
2167
2244
  /** Proactive baseline scan of filter/sort/tab/menu regions. Keyed by
2168
2245
  * containerSelector so re-scans after navigation replace rather than dup. */
2169
2246
  private discoveredFilters;
2170
2247
  private actionCounter;
2171
- private networkCounter;
2172
2248
  private contextCounter;
2173
2249
  private checkpointCounter;
2174
2250
  private pollTimer;
@@ -2176,19 +2252,11 @@ declare class SessionRecorder {
2176
2252
  private lastActionTs;
2177
2253
  private activePages;
2178
2254
  private lastKnownUrl;
2179
- /** Dedup map: key = normalizedType|tag|value → expiration timestamp.
2180
- * Replaces old single-entry cdpActionDedup for bidirectional dedup. */
2181
2255
  private dedupMap;
2182
2256
  private dedupActionCount;
2183
- /** Network dedup: last request key for short-window dedup */
2184
- private _lastRequestKey;
2185
- private _lastRequestTs;
2186
2257
  private _isRecording;
2187
2258
  private streamMode;
2188
- /** Snapshot throttle: prevents too many screenshots during rapid inputs.
2189
- * Keyed by 'type|elementSelector', value = last snapshot timestamp. */
2190
2259
  private snapshotThrottle;
2191
- /** Ambient action types: filtered out in clean mode */
2192
2260
  private static readonly AMBIENT_TYPES;
2193
2261
  constructor(context: XBContext, page: XBPage, sessionName: string);
2194
2262
  get isRecording(): boolean;
@@ -2242,58 +2310,9 @@ declare class SessionRecorder {
2242
2310
  private handleFileChooser;
2243
2311
  private pollActions;
2244
2312
  private flushPendingActions;
2245
- /**
2246
- * Capture a screenshot of the target element for key action types.
2247
- * Returns a base64-encoded PNG string, or undefined if the element has no
2248
- * selector or the screenshot fails (non-critical — never blocks recording).
2249
- *
2250
- * Only captures for: click, input, change, dblclick, and their CDP counterparts.
2251
- *
2252
- * Retry strategy (3 attempts, 3s each):
2253
- * 1. element screenshot via locator
2254
- * 2. retry element screenshot (element may have been animating/detached)
2255
- * 3. fallback to viewport screenshot (so we always get *something*)
2256
- */
2257
- private captureElementScreenshot;
2258
- /**
2259
- * Action types that trigger auto-snapshot capture.
2260
- * Hover is excluded — it's too noisy and rarely changes the page visually.
2261
- * Popup_appear captures the popup state (after only).
2262
- */
2263
- private static readonly SNAPSHOT_TYPES;
2264
- /**
2265
- * Throttle key for snapshot capture to avoid too many during rapid inputs.
2266
- * Returns true if this action should be throttled (skip snapshot).
2267
- */
2268
- private isSnapshotThrottled;
2269
- /**
2270
- * Capture a viewport screenshot + compact accessibility tree for a key action.
2271
- * - PNG stored in .tmp/snapshots/ (temporary, easy to clean up)
2272
- * - aria tree stored inline as compact text on the action (searchable via grep)
2273
- *
2274
- * Non-blocking (errors silently caught). Throttled for rapid inputs.
2275
- */
2276
- private captureAutoSnapshot;
2277
- /**
2278
- * After a click, wait 300ms then scan for popover/dropdown/menu elements
2279
- * near the click position. This runs server-side to avoid race conditions
2280
- * with the client-side poll interval.
2281
- */
2282
- private captureClickContext;
2283
- private detectCheckpoints;
2284
- /**
2285
- * After a key action (click/submit/input), check for success signals:
2286
- * URL changes, recent successful network responses, dialog appearances.
2287
- */
2288
- private verifyAction;
2289
2313
  private flushToDisk;
2290
2314
  private writeFinalOutput;
2291
2315
  private buildData;
2292
- private buildSummary;
2293
- private matchActionToNetwork;
2294
- private searchObjectForValue;
2295
- private buildMarkdownSummary;
2296
- static readMarkdownSummary(sessionName: string): string | null;
2297
2316
  }
2298
2317
 
2299
2318
  interface PlaybackOptions {
@@ -2742,31 +2761,35 @@ declare function parseCommandChain(input: string, options?: ParseOptions): Parse
2742
2761
 
2743
2762
  declare function normalizeSelector(input: string): string;
2744
2763
 
2745
- type AgentTargetAction = 'click' | 'fill' | 'type' | 'press' | 'select' | 'check' | 'hover';
2764
+ /**
2765
+ * 交互元素快照目标。
2766
+ *
2767
+ * 字段精简原则:只保留对 AI 决策和实际操作有意义的字段。
2768
+ * 已移除的零副作用字段(实测无消费方,详见 docs/snapshot-benchmark.md):
2769
+ * - `box`(坐标):AI 用 ref 操作,坐标无用;viewer 截图裁剪用另一套 box
2770
+ * - `actions`(动作数组):可由 role/tag 推导,actOnPage 不读取
2771
+ * - `visible`:默认只采集可见元素,全为 true,零信息量
2772
+ */
2746
2773
  interface AgentTarget {
2747
2774
  ref: string;
2748
2775
  selector: string;
2749
2776
  role: string;
2750
2777
  name: string;
2751
2778
  tag: string;
2752
- visible: boolean;
2779
+ /** 是否可用;false 时 compact 文本输出 disabled 标签 */
2753
2780
  enabled: boolean;
2781
+ /** 是否可编辑(input/textarea/select/contenteditable);compact 输出 editable 标签 */
2754
2782
  editable: boolean;
2783
+ /** checkbox/radio 的选中态;compact 输出 checked/unchecked 标签 */
2755
2784
  checked?: boolean;
2785
+ /** 可编辑元素的当前值(截断 120 字符) */
2756
2786
  value?: string;
2757
- box?: {
2758
- x: number;
2759
- y: number;
2760
- width: number;
2761
- height: number;
2762
- };
2763
- actions: AgentTargetAction[];
2764
2787
  }
2765
2788
  interface AgentObservation {
2766
2789
  url: string;
2767
2790
  title: string;
2791
+ /** 页面状态哈希;actOnPage 用它做 ref staleness(过期)检测 */
2768
2792
  screenHash: string;
2769
- timestamp: string;
2770
2793
  targets: AgentTarget[];
2771
2794
  compact?: string;
2772
2795
  selectors?: Record<string, string>;
@@ -3026,47 +3049,6 @@ declare class HTTPServer {
3026
3049
  } | null;
3027
3050
  }
3028
3051
 
3029
- /**
3030
- * CDP Interceptor Proxy
3031
- *
3032
- * A thin WebSocket proxy that sits between any automation tool (Playwright,
3033
- * Puppeteer, etc.) and Chromium's CDP endpoint. Every JSON-RPC message is
3034
- * intercepted, analyzed against a rule engine, and either passed through,
3035
- * blocked (with error response), or transformed before reaching the browser.
3036
- *
3037
- * Usage:
3038
- * ```
3039
- * const proxy = new CDPInterceptorProxy({ cdpEndpoint: 'ws://localhost:9222/...' });
3040
- * await proxy.start(); // starts listening on a random port
3041
- * // Now connect your automation tool to: ws://localhost:{proxy.port}
3042
- * ```
3043
- */
3044
-
3045
- declare class CDPInterceptorProxy {
3046
- private wss;
3047
- private engine;
3048
- private config;
3049
- private logger;
3050
- private started;
3051
- stats: CDPInterceptorStats;
3052
- constructor(config: CDPInterceptorConfig);
3053
- /** The port the proxy is listening on (only valid after start()) */
3054
- get port(): number;
3055
- /** Start the proxy server */
3056
- start(): Promise<number>;
3057
- /** Stop the proxy server */
3058
- stop(): Promise<void>;
3059
- /** Get accumulated statistics */
3060
- getStats(): CDPInterceptorStats;
3061
- /** Get recent log entries (for inspection) */
3062
- getRecentLogs(count?: number): CDPLogEntry[];
3063
- private handleConnection;
3064
- private handleClientMessage;
3065
- private handleBrowserMessage;
3066
- private parseMessage;
3067
- private recordDecision;
3068
- }
3069
-
3070
3052
  /**
3071
3053
  * CDP Interceptor — Rule Engine
3072
3054
  *
@@ -3268,4 +3250,4 @@ declare function advise(decision: DecisionResult, originalMethod: string): Advis
3268
3250
  /** Convenience factory: create and start a CDP interceptor proxy with defaults. */
3269
3251
  declare function createCDPInterceptor(config: CDPInterceptorConfig): Promise<CDPInterceptorProxy>;
3270
3252
 
3271
- export { type APIRequest, type APIResponse, type AdvisoryResult, type AgentActionInput, type AgentActionResult, type AgentObservation, type AgentTarget, type AgentWaitInput, type AgentWaitResult, type AnalysisResult, BROWSER_SCOPE, type BatchCollectResult, type BrowserCommandContext, type BrowserCommandDefinition, type BrowserLaunchOptions, type BuiltinCommand, type BuiltinContext, type CDPError, type CDPInterceptorConfig, CDPInterceptorProxy, type CDPInterceptorRule, type CDPInterceptorStats, type CDPLogEntry, type CDPMessage, type CDPRequest, type CDPResponse, type CaptchaDetectionResult, CaptchaDetector, type ChainExecutionResult, type ChainRequest, type ChainStepResult, type CollectResult, type CollectorConfig, type CommandMessage, type CompanyInfo, type ContextChange, type DaemonInfo, DataCollector, DataStorage, type DecisionAction, type DecisionResult, type DomainStat, type ElementRef, type ExecRequest, type ExecutionResult, HTTPServer, type HTTPServerConfig, type HTTPServerError, HumanInteractionManager, type InstallOptions, type InstalledPlugin, type ManagedSession, type MessageDirection, type NetworkEntry, type ParsedPipeline, PlaybackEngine, type PlaybackOptions, type PlaybackResult, PluginInstaller, type PluginLoaderOptions, type RecordedEvent, RecorderController, type RecorderStatus, type Recording, type RecordingControlFile, type RecordingData, type RecordingEvent, type RecordingSession, type RecordingStep, type RecordingSummary, type RegisteredCommand, ResultAnalyzer, type RuleContext, type RuleEngine, type ScopeDefinition, type ScopeLevel, ScreencastCapturer, type ScreencastFrame, type ScreencastMessage, type ScreencastOptions, type SearchResult, type ManagedSession as SessionInfo, SessionRecorder, type StatusMessage, type StorageConfig, type UserAction, type ViolationSeverity, type WSInboundMessage, type WSMessage, WSServer, type WSServerConfig, type WaitForHumanOptions, type WaitForHumanResult, WebhookNotifier, type WebhookPayload, XBrowserPluginLoader, actOnPage, advise, allBuiltins, assertPageScope, attachWaitForHuman, automationSignalsRule, checkBrowserScope, routeCommand as cliRoute, closeAllSessions as closeAllBrowserSessions, closeAllSessions, closeSession, closeSessionByName, createCDPInterceptor, createRuleEngine, createSession, destroyBrowser, destroyBrowser as destroySessionManager, domMutationRule, emulationOverrideRule, eventSimulationRule, executeChain, executeCommand, extractAndSave, extractRecording, filterRecording, findSession, findSession as findSessionInfo, fingerprintingRule, generateBashScript, generateJSScript, generatePythonScript, getAllSessions as getAllBrowserSessions, getAllCommands, getBrowser, getBuiltin, getCaptchaConfig, getCommand, getCommandNames, getCompanyType, getDaemonProcessStatus, getPageScreenHash, getPlatformName, getSessionPage, getWSServerFromCache, inputKeystrokeRule, isChainInput, getAllSessions as listAllBrowserSessions, listSessions, mouseTrajectoryRule, networkAnomalyRule, normalizeSelector, observePage, openSession, pageLifecycleRule, parseCommandChain, parseExcludeTypes, printExtractSummary, registerCommand, resetForTesting, setWSServer, setWSServerCache, startDaemonProcess, stopDaemonProcess, version, waitForPage };
3253
+ export { type APIRequest, type APIResponse, type AdvisoryResult, type AgentActionInput, type AgentActionResult, type AgentObservation, type AgentTarget, type AgentWaitInput, type AgentWaitResult, type AnalysisResult, BROWSER_SCOPE, type BatchCollectResult, type BrowserCommandContext, type BrowserCommandDefinition, type BrowserLaunchOptions, type BuiltinCommand, type BuiltinContext, type CDPError, type CDPInterceptorConfig, CDPInterceptorProxy, type CDPInterceptorRule, type CDPInterceptorStats, type CDPLogEntry, type CDPMessage, type CDPRequest, type CDPResponse, type CaptchaDetectionResult, CaptchaDetector, type ChainExecutionResult, type ChainRequest, type ChainStepResult, type CollectResult, type CollectorConfig, type CommandMessage, type CompanyInfo, type ContextChange, type DaemonInfo, DataCollector, DataStorage, type DecisionAction, type DecisionResult, type DomainStat, type ElementRef, type ExecRequest, type ExecutionResult, HTTPServer, type HTTPServerConfig, type HTTPServerError, HumanInteractionManager, type InstallOptions, type InstalledPlugin, type ManagedSession, type MessageDirection, type NetworkEntry, type ParsedPipeline, PlaybackEngine, type PlaybackOptions, type PlaybackResult, PluginInstaller, type PluginLoaderOptions, type RecordedEvent, RecorderController, type RecorderStatus, type Recording, type RecordingCompactSummary, type RecordingControlFile, type RecordingData, type RecordingEvent, type RecordingSession, type RecordingStep, type RecordingSummary, type RegisteredCommand, ResultAnalyzer, type RuleContext, type RuleEngine, type ScopeDefinition, type ScopeLevel, ScreencastCapturer, type ScreencastFrame, type ScreencastMessage, type ScreencastOptions, type SearchResult, type ManagedSession as SessionInfo, SessionRecorder, type StatusMessage, type StorageConfig, type UserAction, type ViolationSeverity, type WSInboundMessage, type WSMessage, WSServer, type WSServerConfig, type WaitForHumanOptions, type WaitForHumanResult, WebhookNotifier, type WebhookPayload, XBrowserPluginLoader, actOnPage, advise, allBuiltins, assertPageScope, attachWaitForHuman, automationSignalsRule, checkBrowserScope, routeCommand as cliRoute, closeAllSessions as closeAllBrowserSessions, closeAllSessions, closeSession, closeSessionByName, createCDPInterceptor, createRuleEngine, createSession, destroyBrowser, destroyBrowser as destroySessionManager, domMutationRule, emulationOverrideRule, eventSimulationRule, executeChain, executeCommand, extractAndSave, extractRecording, filterRecording, findSession, findSession as findSessionInfo, fingerprintingRule, generateBashScript, generateJSScript, generatePythonScript, getAllSessions as getAllBrowserSessions, getAllCommands, getBrowser, getBuiltin, getCaptchaConfig, getCommand, getCommandNames, getCompanyType, getDaemonProcessStatus, getPageScreenHash, getPlatformName, getSessionPage, getWSServerFromCache, inputKeystrokeRule, isChainInput, getAllSessions as listAllBrowserSessions, listSessions, mouseTrajectoryRule, networkAnomalyRule, normalizeSelector, observePage, openSession, pageLifecycleRule, parseCommandChain, parseExcludeTypes, printExtractSummary, registerCommand, resetForTesting, setWSServer, setWSServerCache, startDaemonProcess, stopDaemonProcess, version, waitForPage };