THEZYZSTUDIO commited on
Commit
a8f4448
ยท
verified ยท
1 Parent(s): 3f4f28d

Upload computer_mode_v20-1.py

Browse files
Files changed (1) hide show
  1. computer_mode_v20-1.py +1834 -0
computer_mode_v20-1.py ADDED
@@ -0,0 +1,1834 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ THE Z AI โ€” Computer Mode Server v20 "Headless-Native"
3
+ =====================================================================================
4
+ ุฅุนุงุฏุฉ ูƒุชุงุจุฉ ูƒุงู…ู„ุฉ ู…ู† ุงู„ุตูุฑ โ€” ุจู†ูŠุฉ ู…ุฎุชู„ูุฉ ุชู…ุงู…ุงู‹ ุนู† v11-v13.
5
+
6
+ โ”€โ”€ ู„ู…ุงุฐุง ุฅุนุงุฏุฉ ูƒุชุงุจุฉ ูƒุงู…ู„ุฉุŸ โ”€โ”€
7
+ ุงู„ุจู†ูŠุฉ ุงู„ู‚ุฏูŠู…ุฉ (v11-v13) ุงุนุชู…ุฏุช ุนู„ู‰:
8
+ Xvfb (X server ูˆู‡ู…ูŠ ู…ู†ูุตู„) + Firefox/Chromium ุนุงุฏูŠ ูŠุฑุณู… ุนู„ูŠู‡ + ุงู„ุชู‚ุงุท
9
+ ุงู„ุดุงุดุฉ ุจุฃุฏุงุฉ ุฎุงุฑุฌูŠุฉ (import/ImageMagickุŒ ุฃูˆ python-xlibุŒ ุฃูˆ xwd) + xdotool
10
+ ู„ูƒู„ ุญุฑูƒุฉ ูุฃุฑุฉ/ูƒูŠุจูˆุฑุฏ.
11
+ ู‡ุฐุง ูŠุนู†ูŠ *ุนู…ู„ูŠุชูŠู† ู…ู†ูุตู„ุชูŠู†* ู„ูƒู„ ู…ุณุชุฎุฏู… (Xvfb + ุงู„ู…ุชุตูุญ) + ุนู…ู„ูŠุฉ subprocess
12
+ ุซุงู„ุซุฉ ู„ูƒู„ ู„ู‚ุทุฉ ุดุงุดุฉ ูˆุงุญุฏุฉุŒ ูˆูƒู„ู‡ุง ุชุชูˆุงุตู„ ุนุจุฑ ุจุฑูˆุชูˆูƒูˆู„ X11 ุงู„ุซู‚ูŠู„. ุนู„ู‰ ุณูŠุฑูุฑ
13
+ ู…ูˆุงุฑุฏ ู…ุญุฏูˆุฏุฉ (HF Free: 2 vCPU/16GB ู…ุดุชุฑูƒุฉ)ุŒ ู‡ุฐุง ูŠุนู†ูŠ ุงุณุชู‡ู„ุงูƒ ุฐุงูƒุฑุฉ/CPU ุฃุนู„ู‰
14
+ ุจูƒุซูŠุฑ ู…ู† ุงู„ู„ุงุฒู…ุŒ ูˆุฃูŠ ุจุทุก ุนุงุจุฑ ููŠ X11 ูŠููุณูŽู‘ุฑ ูƒู€"ูุดู„ ุงู„ุชู‚ุงุท" ููŠููุนู‘ู„ ุฑูŠุณุชุงุฑุช
15
+ ุชู„ู‚ุงุฆูŠ ู„ู„ุฌู„ุณุฉ ูƒุงู…ู„ุฉ โ€” ูˆู‡ุฐุง ุจุงู„ุถุจุท ู…ุง ูƒุงู† ูŠุณุจุจ ุงู„ุฑูŠุณุชุงุฑุช ุงู„ู…ุชูƒุฑุฑ ูˆุงู„ุฃุฎุทุงุก.
16
+
17
+ โ”€โ”€ ุงู„ุจู†ูŠุฉ ุงู„ุฌุฏูŠุฏุฉ v20 โ”€โ”€
18
+ Chromium ุจูˆุถุน "--headless=new" (ุงู„ูˆุถุน ุงู„ุฑุณู…ูŠ ุงู„ุญุฏูŠุซ ู…ู† Google) *ูู‚ุท*.
19
+ ุจุฏูˆู† Xvfb. ุจุฏูˆู† X server ู…ู† ุฃูŠ ู†ูˆุน. Chromium ูŠุฑู†ุฏุฑ ุงู„ุตูุญุฉ ุจุงู„ูƒุงู…ู„ ุฏุงุฎู„ูŠุงู‹
20
+ ููŠ ุงู„ุฐุงูƒุฑุฉ (ู†ูุณ ู…ุญุฑูƒ ุงู„ุฑู†ุฏุฑ ุงู„ุญู‚ูŠู‚ูŠุŒ ุจุฏูˆู† ู†ุงูุฐุฉ ู…ุฑุฆูŠุฉ)ุŒ ูˆู†ุชุญุฏุซ ู…ุนู‡ ุญุตุฑูŠุงู‹
21
+ ุนุจุฑ Chrome DevTools Protocol (CDP) ุนุจุฑ WebSocket ูˆุงุญุฏ ู„ูƒู„ ู…ุณุชุฎุฏู…:
22
+ - Page.captureScreenshot โ†’ ู„ู‚ุทุฉ ุงู„ุดุงุดุฉ (JPEG) ู…ุจุงุดุฑุฉ ู…ู† ุงู„ู…ุชุตูุญ ู†ูุณู‡ุŒ
23
+ ุจุฏูˆู† subprocess ุฎุงุฑุฌูŠุŒ ุจุฏูˆู† ูุญุต "ู‡ู„ ุงู„ุตูˆุฑุฉ
24
+ ุณูˆุฏุงุก" (headless ู„ุง ูŠูู†ุชุฌ ุดุงุดุงุช ุณูˆุฏุงุก ุฃุตู„ุงู‹
25
+ ู„ุฃู†ู‡ ู„ุง ูŠุนุชู…ุฏ ุนู„ู‰ X server ู‚ุฏ ูŠุชุนุทู„).
26
+ - Input.dispatchMouseEvent โ†’ ุญุฑูƒุฉ/ู†ู‚ุฑ/ุณุญุจ ุงู„ูุฃุฑุฉ (ุจุฏู„ xdotool mousemove/click)
27
+ - Input.dispatchKeyEvent โ†’ ูƒุชุงุจุฉ/ุงุฎุชุตุงุฑุงุช ู„ูˆุญุฉ ุงู„ู…ูุงุชูŠุญ (ุจุฏู„ xdotool key/type)
28
+ - Page.navigate โ†’ ูุชุญ ุฑุงุจุท/ุชุจูˆูŠุจ ุฌุฏูŠุฏ
29
+ - Runtime.evaluate โ†’ ู„ุตู‚ ุงู„ู†ุต ุงู„ุนุฑุจูŠ (clipboard ุจุฏูŠู„)ุŒ ุชู†ููŠุฐ ุณูƒุฑุจุช ู…ุณุงุนุฏ
30
+
31
+ ู†ุชูŠุฌุฉ ู‡ุฐุง ุงู„ุชุจุณูŠุท:
32
+ - ุนู…ู„ูŠุฉ ูˆุงุญุฏุฉ ูู‚ุท ู„ูƒู„ ู…ุณุชุฎุฏู… (Chromium) ุจุฏู„ ุนู…ู„ูŠุชูŠู† (Xvfb+ู…ุชุตูุญ).
33
+ - ุงุณุชู‡ู„ุงูƒ ุฐุงูƒุฑุฉ ุฃู‚ู„ ุจุดูƒู„ ู…ู„ุญูˆุธ (ู„ุง X server ู…ู†ูุตู„ ูŠูุจู‚ูŠ framebuffer ููŠ ุงู„ุฐุงูƒุฑุฉ).
34
+ - ู„ุง ูˆุฌูˆุฏ ู„ู…ูู‡ูˆู… "ูุดู„ ุงู„ุชู‚ุงุท ุงู„ุดุงุดุฉ" ุงู„ุฐูŠ ูƒุงู† ูŠููุนู‘ู„ ุฑูŠุณุชุงุฑุช โ€” ู„ูˆ ูุดู„ CDP
35
+ ูุงู„ู…ุดูƒู„ุฉ ุงู„ูˆุญูŠุฏุฉ ุงู„ู…ู…ูƒู†ุฉ ู‡ูŠ ุฃู† Chromium ู†ูุณู‡ ุชูˆู‚ูุŒ ูู†ูุนูŠุฏ ุชุดุบูŠู„ู‡ ู‡ูˆ ูู‚ุท
36
+ (ู„ุง ุญุงุฌุฉ ู„ุฃูŠ "reset" ุฃูˆุณุน ูŠู…ุณุญ ุจุฑูˆูุงูŠู„ุงุช ุฃูˆ Xvfb ู„ุฃู†ู‡ ุบูŠุฑ ู…ูˆุฌูˆุฏ ุฃุตู„ุงู‹).
37
+ - ุฃุฎู ุชุนู‚ูŠุฏุงู‹: ุฃุฏุงุฉ ุชุญูƒู… ูˆุงุญุฏุฉ (CDP) ุจุฏู„ ุฎู„ูŠุท (xdotool + import + xlib + xwd).
38
+
39
+ โ”€โ”€ ู…ุง ุงู„ุฐูŠ ุฃูุฒูŠู„ ู…ู† v13 ูˆู„ู…ุงุฐุง โ”€โ”€
40
+ ุฃุฏูˆุงุช "browser_get_elements / browser_click_element / browser_type_into_element /
41
+ browser_find_element / browser_get_page_text / browser_execute_js / browser_navigate
42
+ (CDP) / browser_scroll_to_element / browser_get_state" โ€” ู‡ุฐู‡ ู„ู… ุชูƒู† ุชูุณุชุฎุฏู… ุฅุทู„ุงู‚ุงู‹
43
+ ู…ู† ุงู„ูˆุงุฌู‡ุฉ ุงู„ุฃู…ุงู…ูŠุฉ (index.html) ุจุนุฏ ูุญุต ุงู„ูƒูˆุฏ ุงู„ูุนู„ูŠุ› ุงู„ูˆุงุฌู‡ุฉ ุชูุฑุณู„ ูู‚ุท:
44
+ screenshot, terminal, mouse_move, mouse_click, mouse_drag, keyboard_type,
45
+ keyboard_hotkey, keyboard_press, scroll, clipboard_write, clipboard_read, paste,
46
+ open_app, open_tab, close_tab, browser_back, browser_forward, browser_search,
47
+ screen_info, reset_computer. ุฅุฒุงู„ุฉ ุงู„ูƒูˆุฏ ุงู„ู…ูŠุช ู‚ู„ู‘ู„ุช ุงู„ุชุนู‚ูŠุฏ ูˆุงู„ู€ WebSocket
48
+ overhead ู„ุฃุฏูˆุงุช ู„ุง ุฃุญุฏ ูŠุณุชุฏุนูŠู‡ุง.
49
+
50
+ โ”€โ”€ ุงู„ุชูˆุงูู‚ ู…ุน ุงู„ูˆุงุฌู‡ุฉ ุงู„ุฃู…ุงู…ูŠุฉ โ”€โ”€
51
+ ุงู„ุจุฑูˆุชูˆูƒูˆู„ (ุฃุณู…ุงุก actionsุŒ ุฃุณู…ุงุก ุญู‚ูˆู„ ุฑุณุงุฆู„ screenshot/terminal_result/
52
+ computer_reset/error/connected/screen_info) ู…ุทุงุจู‚ 100% ู„ู…ุง ุชุชูˆู‚ุนู‡
53
+ index_plus_prompt_enhanced_v2-3.html โ€” ู„ุง ุญุงุฌุฉ ู„ุฃูŠ ุชุนุฏูŠู„ ููŠ ุงู„ูุฑูˆู†ุช ุฅู†ุฏ.
54
+
55
+ โ”€โ”€ v20.1 โ€” ุฅุถุงูุงุช: ุชุนุฏุฏ ุงู„ู…ุชุตูุญุงุช + ุจุญุซ ุฑุณู…ูŠ ุจุฏูˆู† ูƒุงุจุชุดุง โ”€โ”€
56
+ 1) ุชุนุฏุฏ ุงู„ู…ุชุตูุญุงุช (Multi-Browser Fallback):
57
+ ุนู†ุฏ ุฅู‚ู„ุงุน ุงู„ุณูŠุฑูุฑุŒ ูŠููุญุต ูƒู„ ู…ุฑุดุญูŠ ุงู„ู…ุชุตูุญ ุงู„ู…ุนุฑูˆููŠู† (Chromium ุจุฃุณู…ุงุฆู‡
58
+ ุงู„ู…ุฎุชู„ูุฉ ุญุณุจ ุงู„ุชูˆุฒูŠุนุฉุŒ ChromeุŒ EdgeุŒ Brave...) ุจุชุดุบูŠู„ ุญู‚ูŠู‚ูŠ ูุนู„ูŠ (ู…ูˆ ู…ุฌุฑุฏ
59
+ "ู‡ู„ ู…ูˆุฌูˆุฏ ุจุงู„ู…ุณุงุฑ") ูˆุงุฎุชูŠ๏ฟฝ๏ฟฝุฑ ุฃูˆู„ ูˆุงุญุฏ ูŠุณุชุฌูŠุจ ูุนู„ุงู‹ ุนู„ู‰ CDP. ู„ูˆ ุงู„ู…ุชุตูุญ
60
+ ุงู„ู…ุนุชู…ุฏ ูุดู„ ู„ุงุญู‚ุงู‹ ุฃุซู†ุงุก ุชุดุบูŠู„ ุฌู„ุณุฉ ู…ุณุชุฎุฏู… ุญู‚ูŠู‚ูŠุฉ (ู…ุซู„ุงู‹ ุชุญุฏูŠุซ ูƒุณุฑ ุงู„ุซู†ุงุฆูŠ)ุŒ
61
+ ุงู„ุณูŠุฑูุฑ ูŠุฌุฑุจ ุจู‚ูŠุฉ ุงู„ู…ุฑุดุญูŠู† ุชู„ู‚ุงุฆูŠุงู‹ ูˆูŠุนุชู…ุฏ ุฃูˆู„ ุจุฏูŠู„ ู†ุงุฌุญ ู„ุจู‚ูŠุฉ ุงู„ุฌู„ุณุงุช โ€”
62
+ ุจุฏูˆู† ุฃูŠ ุชุฏุฎู„ ูŠุฏูˆูŠ ุฃูˆ ุฅุนุงุฏุฉ ู†ุดุฑ.
63
+
64
+ 2) Brave Search API โ€” ู‚ู†ุงุฉ ุจุญุซ ุฑุณู…ูŠุฉ ุจุฏูˆู† ูƒุงุจุชุดุง ุฅุทู„ุงู‚ุงู‹:
65
+ ุงู„ู…ุดูƒู„ุฉ ุงู„ุฃุตู„ูŠุฉ: ูุชุญ duckduckgo.com/google.com ูƒู…ูˆู‚ุน ูุนู„ูŠ ุนุจุฑ ุงู„ู…ุชุตูุญ
66
+ ู„ุฃุฌู„ "ุงู„ุจุญุซ ุนู† ู…ุนู„ูˆู…ุฉ" ูŠูˆุงุฌู‡ ูƒุงุจุชุดุง ุญุชู…ูŠุงู‹ุŒ ู„ุฃู† ู‡ุฐูŠ ุงู„ู…ุญุฑูƒุงุช ู…ุตู…ู…ุฉ ู„ู…ู†ุน
67
+ ุงู„ุทู„ุจุงุช ุงู„ุขู„ูŠุฉ ุชุญุฏูŠุฏุงู‹. ุงู„ุญู„: ุจุฏู„ ุฒูŠุงุฑุฉ ุงู„ู…ูˆู‚ุนุŒ ุงู„ุฐูƒุงุก ุงู„ุงุตุทู†ุงุนูŠ ูŠุฑุณู„ ุฃู…ุฑ
68
+ terminal ุจุตูŠุบุฉ search: ู†ุต ุงู„ุงุณุชุนู„ุงู… (ุจุฏู„ curl ู…ุนู‚ุฏ) ููŠูุณุชุฏุนู‰ Brave
69
+ Search API ู…ุจุงุดุฑุฉ (ุจุฏูˆู† ูุชุญ ุฃูŠ ู…ุชุตูุญุŒ ุจุฏูˆู† ูƒุงุจุชุดุงุŒ ู„ุฃู†ู‡ ู…ุฑุฎู‘ุต ู„ู‡ุฐุง ุงู„ุบุฑุถ
70
+ ุชุญุฏูŠุฏุงู‹ ู…ู† ู…ุฒูˆู‘ุฏู‡). ูุชุญ ู…ุชุตูุญ Computer Mode ุงู„ูุนู„ูŠ ูŠุจู‚ู‰ ู…ุญููˆุธุงู‹ ูู‚ุท ู„ู…ุง
71
+ ูŠุญุชุงุฌ ุงู„ู…ุณุชุฎุฏู… "ุชุตูุญ ู…ูˆู‚ุน ุจุนูŠู†ู‡ ุจุตุฑูŠุงู‹" ุฃูˆ ุงู„ุชูุงุนู„ ู…ุน ุตูุญุฉ ู…ุนูŠู†ุฉ โ€” ุจุงู„ุถุจุท
72
+ ู†ูุณ ูู„ุณูุฉ ุนู…ู„ ูˆูƒู„ุงุก ู…ุซู„ Manus: ุจุญุซ ู†ุธูŠู ุนุจุฑ API ู„ุณุทุฑ ุงู„ุฃูˆุงู…ุฑ ุฃูˆู„ุงู‹ุŒ ูˆู…ุชุตูุญ
73
+ ุญู‚ูŠู‚ูŠ ูู‚ุท ู„ู„ุชุตูุญ ุงู„ูุนู„ูŠ.
74
+
75
+ ุงู„ุชูุนูŠู„: ุนูŠู‘ู† ู…ุชุบูŠู‘ุฑ ุจูŠุฆุฉ BRAVE_API_KEY (ู…ู†
76
+ https://api-dashboard.search.brave.com โ€” ููŠู‡ ุจุงู‚ุฉ ู…ุฌุงู†ูŠุฉ 2000 ุงุณุชุนู„ุงู…/ุดู‡ุฑ)
77
+ ุนู„ู‰ ู…ู†ุตุฉ ุงู„ู†ุดุฑ (Render/HF Spaces โ†’ Settings โ†’ Environment Variables).
78
+ ุจุฏูˆู† ุงู„ู…ูุชุงุญุŒ ูŠุณุชู…ุฑ ุงู„ุณูŠุฑูุฑ ุจุงู„ุนู…ู„ ุนุจุฑ ู…ุตุงุฏุฑ API ุงู„ู…ุฌุงู†ูŠุฉ ุงู„ุจุฏูŠู„ุฉ
79
+ (DuckDuckGo Instant Answer, Wikipedia, HackerNews, Reddit) ุชู„ู‚ุงุฆูŠุงู‹.
80
+
81
+ โ”€โ”€ v20.2 โ€” Camoufox: ู…ุญุฑูƒ ู…ุชุตูุญ ุซุงู†ู ู…ุถุงุฏ ู„ู„ูƒุดู โ”€โ”€
82
+ ุงู„ู…ุดูƒู„ุฉ: ุญุชู‰ ู…ุน Brave Search APIุŒ ุฃุญูŠุงู†ุงู‹ ุงู„ู…ุณุชุฎุฏู… ูŠุทู„ุจ ูุนู„ูŠุงู‹ "ุชุตูู‘ุญ
83
+ ู…ูˆู‚ุน ู…ุนูŠู‘ู† ุจุตุฑูŠุงู‹" (ู…ูˆ ุจุญุซ)ุŒ ูˆุจุนุถ ุงู„ู…ูˆุงู‚ุน (ุฎุตูˆุตุงู‹ ุงู„ู…ุญู…ูŠุฉ ุจู€ Cloudflare/
84
+ DataDome) ุชูƒุชุดู Chromium ุงู„ุนุงุฏูŠ ููˆุฑุงู‹ ุญุชู‰ ู„ูˆ headlessุŒ ู„ุฃู†ู‡ ูŠุณุฑู‘ุจ ุนู„ุงู…ุงุช
85
+ ุฃุชู…ุชุฉ ูˆุงุถุญุฉ (navigator.webdriver=trueุŒ ุจุตู…ุฉ toString ู…ูƒุดูˆูุฉุŒ ุฅู„ุฎ).
86
+
87
+ ุงู„ุญู„: ู…ุญุฑูƒ ุจุฏูŠู„ ุงุฎุชูŠุงุฑูŠ (Camoufox โ€” Firefox ู…ุนุฏูŽู‘ู„ ู…ู† ู…ุณุชูˆู‰ C++ุŒ ู…ูุชูˆุญ
88
+ ุงู„ู…ุตุฏุฑ ูˆู…ุฌุงู†ูŠ ุจุงู„ูƒุงู…ู„) ูŠูุฎููŠ ู‡ุฐูŠ ุงู„ุนู„ุงู…ุงุช ูˆูŠู†ุชุฌ ุจุตู…ุฉ ู…ุชุตูุญ ูˆุงู‚ุนูŠุฉ ุฅุญุตุงุฆูŠุงู‹.
89
+ ูŠููุนูŽู‘ู„ ุนุจุฑ ุฃู…ุฑ ุฌุฏูŠุฏ ูŠุฑุณู„ู‡ ุงู„ูุฑูˆู†ุช ุฅู†ุฏ:
90
+ {"action": "switch_engine", "data": {"engine": "camoufox"}}
91
+ ูˆู„ู„ุฑุฌูˆุน ู„ู„ู…ุญุฑูƒ ุงู„ุงูุชุฑุงุถูŠ ุงู„ุณุฑูŠุน:
92
+ {"action": "switch_engine", "data": {"engine": "chromium"}}
93
+ ุจู‚ูŠุฉ ูƒู„ ุงู„ุฃูˆุงู…ุฑ (screenshot, mouse_click, keyboard_type...) ุชุจู‚ู‰ ุจู†ูุณ
94
+ ุงู„ุตูŠุบุฉ ูˆุงู„ุจุฑูˆุชูˆูƒูˆู„ ุชู…ุงู…ุงู‹ โ€” ูู‚ุท ุชูู†ููŽู‘ุฐ ุนุจุฑ ุงู„ู…ุญุฑูƒ ุงู„ู†ุดุท ู„ู„ู…ุณุชุฎุฏู…ุŒ ุจุฏูˆู†
95
+ ุฃูŠ ุชุนุฏูŠู„ ู…ุทู„ูˆุจ ุนู„ู‰ ุงู„ูุฑูˆู†ุช ุฅู†ุฏ ู„ุชูˆุฌูŠู‡ ุงู„ุฃูˆุงู…ุฑ ุจู†ูุณู‡ุง.
96
+
97
+ ุชู†ุจูŠู‡ ูˆุงู‚ุนูŠ ู…ู‡ู…: Camoufox ูŠู‚ู„ู„ ุธู‡ูˆุฑ ุงู„ูƒุงุจุชุดุง ุจุดูƒู„ ู…ู„ุญูˆุธุŒ ู„ูƒู†ู‡ **ู„ูŠุณ ุญู„ุงู‹
98
+ ุณุญุฑูŠุงู‹ 100%** โ€” ู…ูˆุงุซูŠู‚ Camoufox ู†ูุณู‡ุง ุชุฐูƒุฑ ุฃู† ู…ูˆุงู‚ุน ู…ุชู‚ุฏู…ุฉ ุฌุฏุงู‹ ู‚ุฏ ุชูƒุชุดูู‡
99
+ ุฃุญูŠุงู†ุงู‹ ุนุจุฑ ุชุญู„ูŠู„ ุจุตู…ุงุช ู…ุชู‚ุฏู…. ูƒู…ุง ุฃู† ุณู…ุนุฉ IP ุงู„ุณูŠุฑูุฑ (Render/HF) ุชุจู‚ู‰
100
+ ุนุงู…ู„ุงู‹ ู…ู†ูุตู„ุงู‹ุ› Camoufox ูŠุนุงู„ุฌ ุจุตู…ุฉ *ุงู„ู…ุชุตูุญ*ุŒ ู„ุง ุจุตู…ุฉ *ุงู„ุดุจูƒุฉ/IP*.
101
+
102
+ ุงู„ู…ุชุทู„ุจุงุช: pip install camoufox[geoip] playwrightุŒ ุซู…
103
+ playwright install firefox (ุฃูˆ camoufox fetch ู„ุชู†ุฒูŠู„ ุงู„ุซู†ุงุฆูŠ ุงู„ู…ุนุฏูŽู‘ู„
104
+ ุชู„ู‚ุงุฆูŠุงู‹ ุนู†ุฏ ุฃูˆู„ ุงุณุชุฎุฏุงู…ุŒ ~150-300MB ู„ู…ุฑุฉ ูˆุงุญุฏุฉ). ุจุฏูˆู† ู‡ุฐูŠ ุงู„ุญุฒู…ุŒ ุฃูˆุงู…ุฑ
105
+ switch_engine ุฅู„ู‰ camoufox ุชูุดู„ ุจุฃู…ุงู† ูˆุชูุจู‚ูŠ ุงู„ุฌู„ุณุฉ ุนู„ู‰ Chromium.
106
+ """
107
+
108
+ import asyncio
109
+ import base64
110
+ import hashlib
111
+ import json
112
+ import os
113
+ import re
114
+ import subprocess
115
+ import threading
116
+ import time
117
+ import urllib.parse
118
+ from typing import Optional
119
+
120
+ from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Query
121
+ from fastapi.middleware.cors import CORSMiddleware
122
+ from fastapi.responses import JSONResponse, HTMLResponse
123
+ import uvicorn
124
+
125
+ try:
126
+ import websockets as ws_lib
127
+ _WS_LIB_AVAILABLE = True
128
+ except ImportError:
129
+ _WS_LIB_AVAILABLE = False
130
+ print("โš ๏ธ websockets ุบูŠุฑ ู…ุซุจู‘ุชุฉ โ€” pip install websockets (ู…ุทู„ูˆุจุฉ ู„ู‡ุฐุง ุงู„ุฅุตุฏุงุฑ)")
131
+
132
+
133
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
134
+ # โ”€โ”€ ุงู„ุฅุนุฏุงุฏุงุช ุงู„ุนุงู…ุฉ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
135
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
136
+
137
+ # ุฃู‚ุตู‰ ุนุฏุฏ ุฌู„ุณุงุช ู…ุชุฒุงู…ู†ุฉ. ุฑู‚ู… ูˆุงู‚ุนูŠ ู„ุณูŠุฑูุฑ ู…ูˆุงุฑุฏ ู…ุญุฏูˆุฏุฉ (HF Free CPU
138
+ # Basic: 2 vCPU/16GB ู…ุดุชุฑูƒุฉ) โ€” ูƒู„ ุฌู„ุณุฉ = ุนู…ู„ูŠุฉ Chromium ูˆุงุญุฏุฉ ูู‚ุท ุงู„ุขู†
139
+ # (ุจุฏู„ Xvfb+ู…ุชุตูุญ ุณุงุจู‚ุงู‹)ุŒ ูุงู„ุญู…ู„ ุงู„ูุนู„ูŠ ู„ูƒู„ ู…ุณุชุฎุฏู… ุฃุฎู ู…ู† ุงู„ู†ุตู ุชู‚ุฑูŠุจุงู‹
140
+ # ู…ู‚ุงุฑู†ุฉ ุจุงู„ุจู†ูŠุฉ ุงู„ู‚ุฏูŠู…ุฉุŒ ู„ูƒู† ู†ุจู‚ูŠ ุฑู‚ู…ุงู‹ ู…ุชุญูุธุงู‹ ุจุฏู„ ุงู„ุงูุชุฑุงุถ ุงู„ู…ุชูุงุฆู„.
141
+ MAX_SESSIONS = 40
142
+
143
+ CDP_PORT_BASE = 9300
144
+ SCREEN_W, SCREEN_H = 1280, 800
145
+
146
+ _sessions_lock = threading.Lock()
147
+ _cdp_port_pool_lock = threading.Lock()
148
+ _used_ports: set = set()
149
+
150
+
151
+ def _detect_chromium() -> str:
152
+ """
153
+ ูŠูƒุชุดู ุฃูŠ ู…ุชุตูุญ ู…ุชูˆูุฑ ุนู„ู‰ ู‡ุฐุง ุงู„ุณูŠุฑูุฑ โ€” ูŠุฌุฑุจ ูƒู„ ุงู„ุฃุณู…ุงุก ุงู„ุดุงุฆุนุฉ (Chromium,
154
+ Chrome, Chromium ุงู„ุฑุณู…ูŠ ุจุฃุดูƒุงู„ู‡ ุงู„ู…ุฎุชู„ูุฉ ุญุณุจ ุชูˆุฒูŠุนุฉ Linux)ุŒ ู…ูˆ ุงุณู… ูˆุงุญุฏ ุจุณ.
155
+ """
156
+ return _pick_working_browser()
157
+
158
+
159
+ # ูƒู„ ุงู„ุฃุณู…ุงุก ุงู„ุดุงุฆุนุฉ ู„ุซู†ุงุฆูŠุงุช ุงู„ู…ุชุตูุญ ุนู„ู‰ ุชูˆุฒูŠุนุงุช Linux ุงู„ู…ุฎุชู„ูุฉ (Debian/UbuntuุŒ
160
+ # AlpineุŒ RPM-based) โ€” ุงู„ุฐูƒุงุก ุงู„ุงุตุทู†ุงุนูŠ (ุนุจุฑ ู‡ุฐู‡ ุงู„ุฏุงู„ุฉ) ูŠุฌุฑุจ ูƒู„ ูˆุงุญุฏ ุจุงู„ุชุฑุชูŠุจ
161
+ # ูˆูŠุณุชุฎุฏู… ุฃูˆู„ ูˆุงุญุฏ ูŠุนู…ู„ ูุนู„ูŠุงู‹ุŒ ุจุฏู„ ุงู„ุงุนุชู…ุงุฏ ุนู„ู‰ ุงุณู… ูˆุงุญุฏ ู‚ุฏ ู„ุง ูŠูˆุฌุฏ ุนู„ู‰ ุตูˆุฑุฉ
162
+ # ุงู„ุญุงูˆูŠุฉ ุงู„ู…ุณุชุฎุฏู…ุฉ.
163
+ _BROWSER_CANDIDATES = [
164
+ "chromium-browser", # Debian/Ubuntu
165
+ "chromium", # Alpine/Arch/Fedora
166
+ "google-chrome-stable", # Google Chrome ุงู„ุฑุณู…ูŠ
167
+ "google-chrome",
168
+ "chromium-freeworld", # ุจุนุถ ุชูˆุฒูŠุนุงุช RPM
169
+ "ungoogled-chromium", # ู†ุณุฎุฉ ุฎุตูˆุตูŠุฉ ู…ู† Chromium
170
+ "microsoft-edge-stable", # Edge (ู…ุจู†ูŠ ุนู„ู‰ ChromiumุŒ ูŠุฏุนู… ู†ูุณ CDP)
171
+ "brave-browser", # Brave (ู…ุจู†ูŠ ุนู„ู‰ ChromiumุŒ ูŠุฏุนู… ู†ูุณ CDP)
172
+ ]
173
+
174
+
175
+ def _binary_exists(name: str) -> bool:
176
+ r = subprocess.run(["which", name], capture_output=True, text=True)
177
+ return r.returncode == 0 and bool(r.stdout.strip())
178
+
179
+
180
+ def _test_browser_launch(binary: str, timeout: float = 6.0) -> bool:
181
+ """
182
+ ุงุฎุชุจุงุฑ ุญู‚ูŠู‚ูŠ: ูŠุดุบู‘ู„ ุงู„ู…ุชุตูุญ ูุนู„ูŠุงู‹ ุจูˆุถุน headless ุนู„ู‰ ู…ู†ูุฐ CDP ู…ุคู‚ุช
183
+ ูˆูŠุชุฃูƒุฏ ุฃู†ู‡ ูŠุณุชุฌูŠุจ โ€” ู…ูˆ ู…ุฌุฑุฏ ูุญุต "ู…ูˆุฌูˆุฏ ุจุงู„ู…ุณุงุฑ"ุŒ ู„ุฃู† ุฃุญูŠุงู†ุงู‹ ุงู„ุซู†ุงุฆูŠ
184
+ ู…ูˆุฌูˆุฏ ู„ูƒู† ู…ูƒุณูˆุฑ (ู…ูƒุชุจุงุช ู†ุงู‚ุตุฉุŒ ุฅู„ุฎ).
185
+ """
186
+ test_port = CDP_PORT_BASE + 9999 # ู…ู†ูุฐ ู…ุฎุตุต ู„ู„ุงุฎุชุจุงุฑ ูู‚ุทุŒ ู„ุง ูŠุชุนุงุฑุถ ู…ุน ุงู„ุฌู„ุณุงุช
187
+ try:
188
+ subprocess.run(["pkill", "-9", "-f", f"[r]emote-debugging-port={test_port}"],
189
+ capture_output=True, timeout=3)
190
+ except Exception:
191
+ pass
192
+ try:
193
+ proc = subprocess.Popen([
194
+ binary, "--headless=new", f"--remote-debugging-port={test_port}",
195
+ "--remote-debugging-address=127.0.0.1", "--disable-gpu", "--no-sandbox",
196
+ "--disable-dev-shm-usage", "--no-first-run", "about:blank",
197
+ ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
198
+ except Exception:
199
+ return False
200
+
201
+ ok = False
202
+ deadline = time.time() + timeout
203
+ try:
204
+ import urllib.request
205
+ while time.time() < deadline:
206
+ try:
207
+ with urllib.request.urlopen(f"http://127.0.0.1:{test_port}/json/version", timeout=1.0) as r:
208
+ if r.status == 200:
209
+ ok = True
210
+ break
211
+ except Exception:
212
+ time.sleep(0.3)
213
+ finally:
214
+ try:
215
+ proc.kill()
216
+ proc.wait(timeout=3)
217
+ except Exception:
218
+ pass
219
+ try:
220
+ subprocess.run(["pkill", "-9", "-f", f"[r]emote-debugging-port={test_port}"],
221
+ capture_output=True, timeout=3)
222
+ except Exception:
223
+ pass
224
+ return ok
225
+
226
+
227
+ def _pick_working_browser() -> str:
228
+ """
229
+ ูŠุฌุฑุจ ูƒู„ ู…ุฑุดุญูŠ ุงู„ู…ุชุตูุญ ุจุงู„ุชุฑุชูŠุจ: ุฃูˆู„ุงู‹ ูŠุชุฃูƒุฏ ุฃู† ุงู„ุซู†ุงุฆูŠ ู…ูˆุฌูˆุฏ ุนู„ู‰ ุงู„ู‚ุฑุต
230
+ (ุณุฑูŠุน)ุŒ ูˆุฅุฐุง ูˆุฌุฏุŒ ูŠุฎุชุจุฑู‡ ูุนู„ูŠุงู‹ ุจุชุดุบูŠู„ู‡ ูˆุงู„ุชุฃูƒุฏ ุฃู†ู‡ ูŠุณุชุฌูŠุจ ุนู„ู‰ CDP
231
+ (ุงุฎุชุจุงุฑ ุญู‚ูŠู‚ูŠุŒ ู„ุง ุงูุชุฑุงุถ). ุฃูˆู„ ู…ุชุตูุญ "ุญูŠ" ูุนู„ุงู‹ ูŠูุนุชู…ุฏ ู„ุจู‚ูŠุฉ ุนู…ุฑ ุงู„ุณูŠุฑูุฑ.
232
+ """
233
+ found_but_untested = []
234
+ for name in _BROWSER_CANDIDATES:
235
+ if _binary_exists(name):
236
+ found_but_untested.append(name)
237
+
238
+ if not found_but_untested:
239
+ print("โŒ ู„ุง ูŠูˆุฌุฏ ุฃูŠ ู…ุชุตูุญ ู…๏ฟฝ๏ฟฝุจู‘ุช ุนู„ู‰ ู‡ุฐุง ุงู„ุณูŠุฑูุฑ ู…ู† ุจูŠู† ุงู„ู…ุฑุดุญูŠู† ุงู„ู…ุนุฑูˆููŠู†:")
240
+ print(f" {', '.join(_BROWSER_CANDIDATES)}")
241
+ print(" ุซุจู‘ุช ูˆุงุญุฏุงู‹ ุนุจุฑ: apt-get install chromium")
242
+ return "chromium-browser" # ุงูุชุฑุงุถูŠุŒ ุญุชู‰ ู„ูˆ ุบูŠุฑ ู…ูˆุฌูˆุฏุŒ ู„ูŠูƒูˆู† ุงุณู… ูˆุงุถุญ ุจุงู„ุณุฌู„ุงุช
243
+
244
+ print(f"๐Ÿ” ู…ุชุตูุญุงุช ู…ูˆุฌูˆุฏุฉ ุนู„ู‰ ุงู„ู‚ุฑุต: {', '.join(found_but_untested)} โ€” ูŠุฌุฑูŠ ุงุฎุชุจุงุฑ ูƒู„ ูˆุงุญุฏ ูุนู„ูŠุงู‹...")
245
+ for name in found_but_untested:
246
+ print(f" ๐Ÿงช ุงุฎุชุจุงุฑ {name} ...")
247
+ if _test_browser_launch(name):
248
+ print(f" โœ… {name} ูŠุนู…ู„ ูุนู„ูŠุงู‹ โ€” ุณูŠูุนุชู…ุฏ ู„ูƒู„ ุงู„ุฌู„ุณุงุช")
249
+ return name
250
+ else:
251
+ print(f" โŒ {name} ู…ูˆุฌูˆุฏ ู„ูƒู† ูุดู„ ุจุงู„ุชุดุบูŠู„ ุงู„ูุนู„ูŠ (ู…ูƒุชุจุงุช ู†ุงู‚ุตุฉ ุฃูˆ ุซู†ุงุฆูŠ ู…ุนุทูˆุจ)")
252
+
253
+ # ูƒู„ ุดูŠุก ูˆูุฌุฏ ู„ูƒู† ูุดู„ ุงู„ุงุฎุชุจุงุฑ ุงู„ุญูŠ โ€” ุงุณุชุฎุฏู… ุฃูˆู„ ู…ูˆุฌูˆุฏ ูƒุฎูŠุงุฑ ุฃุฎูŠุฑ ู…ุน ุชุญุฐูŠุฑ ูˆุงุถุญ
254
+ print(f"โš ๏ธ ูƒู„ ุงู„ู…ุชุตูุญุงุช ุงู„ู…ูˆุฌูˆุฏุฉ ูุดู„ุช ุจุงุฎุชุจุงุฑ ุงู„ุชุดุบูŠู„ ุงู„ุญูŠ. ุณูŠูุณุชุฎุฏู… '{found_but_untested[0]}' "
255
+ f"ูƒุฎูŠุงุฑ ุงูุชุฑุงุถูŠ ุฃุฎูŠุฑุŒ ู„ูƒู† ูŠูู†ุตุญ ุจูุญุต ุชุซุจูŠุช ุงู„ู…ุชุตูุญ ุนู„ู‰ ู‡ุฐุง ุงู„ุณูŠุฑูุฑ.")
256
+ return found_but_untested[0]
257
+
258
+
259
+ BROWSER_BIN = _detect_chromium()
260
+
261
+
262
+ def _alloc_cdp_port() -> int:
263
+ """ูŠุฎุตุต ู…ู†ูุฐ CDP ุญุฑ ู„ู…ุณุชุฎุฏู… ุฌุฏูŠุฏ."""
264
+ with _cdp_port_pool_lock:
265
+ p = CDP_PORT_BASE
266
+ while p in _used_ports:
267
+ p += 1
268
+ _used_ports.add(p)
269
+ return p
270
+
271
+
272
+ def _release_cdp_port(port: int):
273
+ with _cdp_port_pool_lock:
274
+ _used_ports.discard(port)
275
+
276
+
277
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
278
+ # โ”€โ”€ Camoufox โ€” ู…ุญุฑูƒ ู…ุชุตูุญ ุจุฏูŠู„ ู…ุถุงุฏ ู„ู„ูƒุดู (ุงุฎุชูŠุงุฑูŠุŒ ุจุฌุงู†ุจ Chromium) โ”€โ”€
279
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
280
+ # ู„ู…ุงุฐุง ู…ุญุฑูƒ ุซุงู†ูŠ ู…ู†ูุตู„ุŸ Camoufox ู‡ูˆ Firefox ู…ุนุฏูŽู‘ู„ ู…ู† ู…ุณุชูˆู‰ C++ (ู…ูˆ ุญู‚ู†
281
+ # JavaScript ู‚ุงุจู„ ู„ู„ูƒุดู) ูŠูุฎููŠ ุนู„ุงู…ุงุช ุงู„ุฃุชู…ุชุฉ (navigator.webdriver ูˆุบูŠุฑู‡ุง)
282
+ # ูˆูŠูˆู„ู‘ุฏ ุจุตู…ุฉ ู…ุชุตูุญ ู…ุชู‘ุณู‚ุฉ ูˆูˆุงู‚ุนูŠุฉ ุฅุญุตุงุฆูŠุงู‹ (ู†ุธุงู… ุชุดุบูŠู„ุŒ ุฏู‚ุฉ ุดุงุดุฉุŒ ุฎุทูˆุทุŒ
283
+ # WebGL...) ุนุจุฑ ู…ูƒุชุจุฉ BrowserForge. ู‡ุฐุง ูŠู‚ู„ู„ ุธู‡ูˆุฑ ูƒุงุจุชุดุง ุงู„ู…ูˆุงู‚ุน ุงู„ู…ุญู…ูŠุฉ
284
+ # ุจุดุฏุฉ (Cloudflare, DataDome) ุจุดูƒู„ ู…ู„ุญูˆุธ โ€” ู„ูƒู†ู‡ **ู„ูŠุณ ุถู…ุงู†ุงู‹ ู…ุทู„ู‚ุงู‹** (ุญุชู‰
285
+ # ู…ูˆุซู‘ู‚ Camoufox ู†ูุณู‡ ูŠุฐูƒุฑ ุฃู† ู…ูˆุงู‚ุน ู…ุชู‚ุฏู…ุฉ ู‚ุฏ ุชูƒุชุดูู‡ ุฃุญูŠุงู†ุงู‹).
286
+ #
287
+ # ุงู„ูุฑู‚ ุงู„ุฌูˆู‡ุฑูŠ ุนู† Chromium/CDP: ูˆุงุฌู‡ุฉ Camoufox ุงู„ุฑุณู…ูŠุฉ ู‡ูŠ Python+Playwright
288
+ # (ู…ูˆ CDP ุฎุงู…)ุŒ ูุชุญูƒู…ู†ุง ููŠู‡ ูŠู…ุฑ ุนุจุฑ Playwright API (page.mouse, page.keyboard,
289
+ # page.screenshot) ุจุฏู„ ุฑุณุงุฆู„ CDP JSON ุงู„ู…ุจุงุดุฑุฉ ุงู„ู…ุณุชุฎุฏู…ุฉ ู…ุน Chromium. ู„ุฐู„ูƒ
290
+ # ุจู†ูŠู†ุงู‡ ูƒู€"ู…ุญุฑูƒ ุจุฏูŠู„" ู…ุณุชู‚ู„ ุจุฌุงู†ุจ CDPSessionุŒ ุจู†ูุณ ุจุฑูˆุชูˆูƒูˆู„ ุงู„ุฃูƒุดู†ุงุช ุงู„ุฎุงุฑุฌูŠ
291
+ # (screenshot/mouse_click/keyboard_type...) ุญุชู‰ ู„ุง ูŠุชุฃุซุฑ ุงู„ูุฑูˆู†ุช ุฅู†ุฏ ุฅุทู„ุงู‚ุงู‹.
292
+ #
293
+ # ุงู„ุชูุนูŠู„: ุชู„ู‚ุงุฆูŠ ุจุงู„ูƒุงู…ู„ โ€” ู„ุง ุญุงุฌุฉ ู„ุฃูŠ ุฅุนุฏุงุฏ. Camoufox ุญุฒู…ุฉ ุจุงูŠุซูˆู† ุนุงุฏูŠุฉ
294
+ # (pip install camoufox[geoip] + playwright)ุŒ ุฃูˆู„ ุงุณุชุฎุฏุงู… ูŠูู†ุฒู‘ู„ ุซู†ุงุฆูŠ
295
+ # Firefox ุงู„ู…ุนุฏูŽู‘ู„ ุชู„ู‚ุงุฆูŠุงู‹ (~150-300MB ู…ุฑุฉ ูˆุงุญุฏุฉ ูู‚ุทุŒ ูŠูุฎุฒูŽู‘ู† ูˆูŠูุนุงุฏ ุงุณุชุฎุฏุงู…ู‡).
296
+
297
+ try:
298
+ from camoufox.async_api import AsyncCamoufox
299
+ _CAMOUFOX_LIB_AVAILABLE = True
300
+ except ImportError:
301
+ _CAMOUFOX_LIB_AVAILABLE = False
302
+ print("โ„น๏ธ ู…ูƒุชุจุฉ camoufox ุบูŠุฑ ู…ุซุจู‘ุชุฉ โ€” pip install camoufox playwright ู„ุชูุนูŠู„ ุงู„ู…ุญุฑูƒ ุงู„ู…ุถุงุฏ ู„ู„ูƒุดู")
303
+
304
+ CAMOUFOX_ENABLED = os.environ.get("CAMOUFOX_ENABLED", "1").strip() not in ("0", "false", "no")
305
+
306
+
307
+ class CamoufoxSession:
308
+ """
309
+ ุฌู„ุณุฉ Camoufox ูˆุงุญุฏุฉ ู„ูƒู„ ู…ุณุชุฎุฏู… โ€” ุจุฏูŠู„ ู„ู€ CDPSession ู„ูƒู† ู…ุจู†ูŠ ููˆู‚
310
+ Playwright ุจุฏู„ CDP ุฎุงู…. ูŠูˆูุฑ ู†ูุณ ู†ูˆุน ุงู„ุนู…ู„ูŠุงุช (screenshot, mouse,
311
+ keyboard, navigate) ุจูˆุงุฌู‡ุฉ ู…ูˆุญู‘ุฏุฉ (dict ู†ุชุงุฆุฌ) ู„ุชูุณุชู‡ู„ูƒ ู…ู† ู†ูุณ ู…ุนุงู„ุฌ
312
+ ุงู„ุฃูƒุดู†ุงุช (handle_action) ุฏูˆู† ุชุบูŠูŠุฑ ุจุฑูˆุชูˆูƒูˆู„ ุงู„ูุฑูˆู†ุช ุฅู†ุฏ.
313
+ """
314
+
315
+ def __init__(self, user_id: str):
316
+ self.user_id = user_id
317
+ self._cm = None # AsyncCamoufox context manager instance
318
+ self._browser = None # Playwright Browser
319
+ self._context = None # Playwright BrowserContext
320
+ self.page = None # Playwright Page ุงู„ุญุงู„ูŠุฉ
321
+ self._mouse_x = SCREEN_W // 2
322
+ self._mouse_y = SCREEN_H // 2
323
+
324
+ @property
325
+ def alive(self) -> bool:
326
+ return self.page is not None and not self.page.is_closed()
327
+
328
+ async def start(self) -> bool:
329
+ if not _CAMOUFOX_LIB_AVAILABLE:
330
+ print("[camoufox] โŒ ุงู„ู…ูƒุชุจุฉ ุบูŠุฑ ู…ุซุจูŽู‘ุชุฉ ุนู„ู‰ ู‡ุฐุง ุงู„ุณูŠุฑูุฑ")
331
+ return False
332
+ try:
333
+ profile = _profile_dir("camoufox_" + self.user_id)
334
+ self._cm = AsyncCamoufox(
335
+ headless=True, # Camoufox ูŠุฏุนู… headless ุญู‚ูŠู‚ูŠ ุจุฃู…ุงู† (ูŠูุฎููŠ ุนู„ุงู…ุงุช ุงู„ูƒุดู ุญุชู‰ ููŠ ู‡ุฐุง ุงู„ูˆุถุน)
336
+ humanize=True, # ุญุฑูƒุฉ ูุฃุฑุฉ ุดุจูŠู‡ุฉ ุจุงู„ุจุดุฑ (ู…ู†ุญู†ูŠุงุช Bezier ุจุฏู„ ุฎุทูˆุท ู…ุณุชู‚ูŠู…ุฉ)
337
+ geoip=False, # ู„ุง ู†ุญุชุงุฌ ุถุจุท ุฌุบุฑุงููŠ ุชู„ู‚ุงุฆูŠ ุนุจุฑ ุจุฑูˆูƒุณูŠ ู‡ู†ุง
338
+ persistent_context=True,
339
+ user_data_dir=profile,
340
+ window=(SCREEN_W, SCREEN_H),
341
+ )
342
+ self._context = await self._cm.__aenter__()
343
+ # ููŠ persistent_context=TrueุŒ ุงู„ูƒุงุฆู† ุงู„ู…ูุนุงุฏ ู‡ูˆ BrowserContext ู…ุจุงุดุฑุฉ
344
+ pages = self._context.pages
345
+ self.page = pages[0] if pages else await self._context.new_page()
346
+ await self.page.set_viewport_size({"width": SCREEN_W, "height": SCREEN_H})
347
+ print(f"[camoufox] โœ… ุฌู„ุณุฉ ุฌุฏูŠุฏุฉ ู„ู€ '{self.user_id}' ุฌุงู‡ุฒุฉ")
348
+ return True
349
+ except Exception as e:
350
+ print(f"[camoufox] โŒ ูุดู„ ุจุฏุก ุงู„ุฌู„ุณุฉ: {e}")
351
+ await self.close()
352
+ return False
353
+
354
+ async def close(self):
355
+ try:
356
+ if self._cm:
357
+ await self._cm.__aexit__(None, None, None)
358
+ except Exception:
359
+ pass
360
+ self._cm = None
361
+ self._context = None
362
+ self.page = None
363
+
364
+ async def screenshot_b64(self) -> "str | None":
365
+ if not self.alive:
366
+ return None
367
+ try:
368
+ raw = await self.page.screenshot(type="jpeg", quality=75)
369
+ return base64.b64encode(raw).decode()
370
+ except Exception as e:
371
+ print(f"[camoufox] โŒ ูุดู„ ุงู„ุชู‚ุงุท ุงู„ุดุงุดุฉ: {e}")
372
+ return None
373
+
374
+ async def mouse_move(self, x: int, y: int):
375
+ if self.alive:
376
+ await self.page.mouse.move(x, y)
377
+ self._mouse_x, self._mouse_y = x, y
378
+
379
+ async def mouse_click(self, x: int, y: int, button: str = "left", double: bool = False):
380
+ if not self.alive:
381
+ return
382
+ await self.page.mouse.move(x, y)
383
+ if double:
384
+ await self.page.mouse.dblclick(x, y, button=button)
385
+ else:
386
+ await self.page.mouse.click(x, y, button=button)
387
+ self._mouse_x, self._mouse_y = x, y
388
+
389
+ async def mouse_drag(self, x1: int, y1: int, x2: int, y2: int):
390
+ if not self.alive:
391
+ return
392
+ await self.page.mouse.move(x1, y1)
393
+ await self.page.mouse.down()
394
+ await self.page.mouse.move(x2, y2, steps=10)
395
+ await self.page.mouse.up()
396
+ self._mouse_x, self._mouse_y = x2, y2
397
+
398
+ async def scroll(self, x: int, y: int, delta_y: int):
399
+ if not self.alive:
400
+ return
401
+ await self.page.mouse.move(x, y)
402
+ await self.page.mouse.wheel(0, delta_y)
403
+
404
+ async def type_text(self, text: str):
405
+ if self.alive:
406
+ await self.page.keyboard.type(text, delay=25) # ุชุฃุฎูŠุฑ ุฎููŠู ุจูŠู† ุงู„ุญุฑูˆู โ€” ุฃูƒุซุฑ ูˆุงู‚ุนูŠุฉ ุจุดุฑูŠุงู‹
407
+
408
+ async def key_press(self, key_name: str):
409
+ if self.alive:
410
+ await self.page.keyboard.press(key_name)
411
+
412
+ async def hotkey(self, keys: list):
413
+ if not self.alive:
414
+ return
415
+ combo = "+".join(keys)
416
+ await self.page.keyboard.press(combo)
417
+
418
+ async def navigate(self, url: str) -> bool:
419
+ if not self.alive:
420
+ return False
421
+ try:
422
+ await self.page.goto(url, timeout=20000, wait_until="domcontentloaded")
423
+ return True
424
+ except Exception as e:
425
+ print(f"[camoufox] โš ๏ธ ูุดู„ ุงู„ุชู†ู‚ู‘ู„ ุฅู„ู‰ {url}: {e}")
426
+ return False
427
+
428
+ async def go_back(self):
429
+ if self.alive:
430
+ try:
431
+ await self.page.go_back(timeout=8000)
432
+ except Exception:
433
+ pass
434
+
435
+ async def go_forward(self):
436
+ if self.alive:
437
+ try:
438
+ await self.page.go_forward(timeout=8000)
439
+ except Exception:
440
+ pass
441
+
442
+
443
+ # ุฌู„ุณุงุช Camoufox ู…ู†ูุตู„ุฉ ุนู† ุฌู„ุณุงุช Chromium/CDP โ€” ู…ูุชุงุญู‡ุง user_id ุฃูŠุถุงู‹ุŒ ู„ูƒู†
444
+ # ู‚ุงู…ูˆุณ ู…ุณุชู‚ู„ ู„ุฃู† ู…ุญุฑูƒ ุงู„ู…ุณุชุฎุฏู… ู‚ุฏ ูŠุชุจุฏู‘ู„ ุจูŠู† ุงู„ุงุซู†ูŠู† ุฃุซู†ุงุก ุงู„ุฌู„ุณุฉ ู†ูุณู‡ุง.
445
+ _camoufox_sessions: dict = {}
446
+ _camoufox_lock = threading.Lock()
447
+
448
+
449
+ async def get_camoufox_session(user_id: str) -> "CamoufoxSession | None":
450
+ """ูŠูุฑุฌุน ุฌู„ุณุฉ Camoufox ู…๏ฟฝ๏ฟฝุฌูˆุฏุฉ ุฃูˆ ูŠู†ุดุฆ ูˆุงุญุฏุฉ ุฌุฏูŠุฏุฉ ุนู†ุฏ ุงู„ุญุงุฌุฉ."""
451
+ if not CAMOUFOX_ENABLED or not _CAMOUFOX_LIB_AVAILABLE:
452
+ return None
453
+ with _camoufox_lock:
454
+ sess = _camoufox_sessions.get(user_id)
455
+ if sess and sess.alive:
456
+ return sess
457
+ sess = CamoufoxSession(user_id)
458
+ ok = await sess.start()
459
+ if not ok:
460
+ return None
461
+ with _camoufox_lock:
462
+ _camoufox_sessions[user_id] = sess
463
+ return sess
464
+
465
+
466
+ async def destroy_camoufox_session(user_id: str):
467
+ with _camoufox_lock:
468
+ sess = _camoufox_sessions.pop(user_id, None)
469
+ if sess:
470
+ await sess.close()
471
+
472
+
473
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
474
+ # โ”€โ”€ CDP Session โ€” ุงู„ุงุชุตุงู„ ุงู„ู…ุจุงุดุฑ ุจู€ Chromium ุนุจุฑ DevTools Protocol โ”€โ”€
475
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
476
+
477
+ class CDPSession:
478
+ """
479
+ ุงุชุตุงู„ WebSocket ูˆุงุญุฏ ุจุฌู„ุณุฉ Chromium headless ูˆุงุญุฏุฉ. ูƒู„ ุงู„ุฃูˆุงู…ุฑ
480
+ (screenshot, mouse, keyboard, navigate) ุชู…ุฑ ู…ู† ู‡ู†ุง. ุงุชุตุงู„ ูˆุงุญุฏ ูŠูุนุงุฏ
481
+ ุงุณุชุฎุฏุงู…ู‡ ุทูˆุงู„ ุญูŠุงุฉ ุงู„ุฌู„ุณุฉ ุจุฏู„ ูุชุญ ุงุชุตุงู„ ุฌุฏูŠุฏ ู„ูƒู„ ุฃู…ุฑ.
482
+ """
483
+
484
+ def __init__(self, port: int):
485
+ self.port = port
486
+ self._ws = None
487
+ self._msg_id = 0
488
+ self._pending: dict = {}
489
+ self._recv_task: Optional[asyncio.Task] = None
490
+ self._send_lock = asyncio.Lock()
491
+ self._target_id = None
492
+
493
+ async def connect(self, timeout: float = 6.0) -> bool:
494
+ if not _WS_LIB_AVAILABLE:
495
+ return False
496
+ # ุฌุฑู‘ุจ ุนุฏุฉ ู…ุฑุงุช ู„ุฃู† Chromium ู‚ุฏ ูŠุญุชุงุฌ ู„ุญุธุฉ ุจุนุฏ ุงู„ุฅู‚ู„ุงุน ู‚ุจู„ ูุชุญ ู…ู†ูุฐ CDP
497
+ deadline = time.time() + timeout
498
+ tabs = None
499
+ while time.time() < deadline:
500
+ try:
501
+ import urllib.request
502
+ with urllib.request.urlopen(
503
+ f"http://127.0.0.1:{self.port}/json/list", timeout=1.5
504
+ ) as r:
505
+ tabs = json.loads(r.read())
506
+ break
507
+ except Exception:
508
+ await asyncio.sleep(0.25)
509
+ if tabs is None:
510
+ print(f"[CDP:{self.port}] โŒ Chromium ู„ุง ูŠุณุชุฌูŠุจ ุนู„ู‰ ู…ู†ูุฐ CDP")
511
+ return False
512
+
513
+ ws_url = None
514
+ for t in tabs:
515
+ if t.get("type") == "page":
516
+ ws_url = t.get("webSocketDebuggerUrl")
517
+ self._target_id = t.get("id")
518
+ break
519
+ if not ws_url:
520
+ print(f"[CDP:{self.port}] โŒ ู„ุง ูŠูˆุฌุฏ ุชุจูˆูŠุจ ุตูุญุฉ ู…ุชุงุญ")
521
+ return False
522
+
523
+ try:
524
+ self._ws = await asyncio.wait_for(
525
+ ws_lib.connect(ws_url, ping_interval=15, ping_timeout=10, max_size=64 * 1024 * 1024),
526
+ timeout=timeout,
527
+ )
528
+ except Exception as e:
529
+ print(f"[CDP:{self.port}] โŒ ูุดู„ ุงุชุตุงู„ WebSocket: {e}")
530
+ return False
531
+
532
+ self._recv_task = asyncio.create_task(self._recv_loop())
533
+
534
+ # ูุนู‘ู„ ุงู„ู†ุทุงู‚ุงุช ุงู„ู…ุทู„ูˆุจุฉ
535
+ await self.send("Page.enable", timeout=5.0)
536
+ await self.send("Runtime.enable", timeout=5.0)
537
+ await self.send("DOM.enable", timeout=5.0)
538
+ # ุงุถุจุท ุญุฌู… ุงู„ุดุงุดุฉ ุงู„ุงูุชุฑุงุถูŠ ุนุจุฑ Emulation (headless ุจุฏูˆู† ู†ุงูุฐุฉ ูุนู„ูŠุฉุŒ
539
+ # ู‡ุฐุง ูŠุญุฏุฏ ุฃุจุนุงุฏ ุงู„ุฑู†ุฏุฑ ุงู„ุฏุงุฎู„ูŠ)
540
+ await self.send("Emulation.setDeviceMetricsOverride", {
541
+ "width": SCREEN_W, "height": SCREEN_H,
542
+ "deviceScaleFactor": 1, "mobile": False,
543
+ }, timeout=5.0)
544
+ print(f"[CDP:{self.port}] โœ… ู…ุชุตู„ ุจุฌู„ุณุฉ Chromium")
545
+ return True
546
+
547
+ async def _recv_loop(self):
548
+ try:
549
+ async for raw in self._ws:
550
+ try:
551
+ msg = json.loads(raw)
552
+ except Exception:
553
+ continue
554
+ mid = msg.get("id")
555
+ if mid is not None and mid in self._pending:
556
+ fut = self._pending.pop(mid)
557
+ if not fut.done():
558
+ fut.set_result(msg)
559
+ except Exception:
560
+ pass
561
+ finally:
562
+ for fut in self._pending.values():
563
+ if not fut.done():
564
+ fut.set_exception(ConnectionError("CDP disconnected"))
565
+ self._pending.clear()
566
+ self._ws = None
567
+
568
+ async def send(self, method: str, params: dict = None, timeout: float = 10.0):
569
+ if not self._ws:
570
+ return None
571
+ async with self._send_lock:
572
+ self._msg_id += 1
573
+ mid = self._msg_id
574
+ fut = asyncio.get_event_loop().create_future()
575
+ self._pending[mid] = fut
576
+ try:
577
+ await self._ws.send(json.dumps({"id": mid, "method": method, "params": params or {}}))
578
+ return await asyncio.wait_for(fut, timeout=timeout)
579
+ except Exception:
580
+ self._pending.pop(mid, None)
581
+ return None
582
+
583
+ @property
584
+ def alive(self) -> bool:
585
+ return self._ws is not None
586
+
587
+ async def close(self):
588
+ if self._recv_task:
589
+ self._recv_task.cancel()
590
+ if self._ws:
591
+ try:
592
+ await self._ws.close()
593
+ except Exception:
594
+ pass
595
+ self._ws = None
596
+
597
+
598
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
599
+ # โ”€โ”€ ุชุดุบูŠู„/ุฅูŠู‚ุงู ุนู…ู„ูŠุฉ Chromium headless โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
600
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
601
+
602
+ def _profile_dir(user_id: str) -> str:
603
+ safe = re.sub(r"[^a-zA-Z0-9_.-]", "_", user_id) or "anon"
604
+ d = os.path.expanduser(f"~/.zai_chromium_profiles/{safe}")
605
+ os.makedirs(d, exist_ok=True)
606
+ return d
607
+
608
+
609
+ def _launch_browser_process(binary: str, port: int, profile: str) -> "subprocess.Popen | None":
610
+ cmd = [
611
+ binary,
612
+ "--headless=new", # ุงู„ูˆุถุน ุงู„ุฑุณู…ูŠ ุงู„ุญุฏูŠุซ โ€” ู„ุง ุญุงุฌุฉ ู„ุฃูŠ display
613
+ f"--remote-debugging-port={port}",
614
+ "--remote-debugging-address=127.0.0.1",
615
+ "--disable-gpu",
616
+ "--no-sandbox",
617
+ "--disable-dev-shm-usage",
618
+ "--disable-extensions",
619
+ "--disable-notifications",
620
+ "--disable-popup-blocking",
621
+ "--disable-translate",
622
+ "--disable-sync",
623
+ "--disable-background-timer-throttling",
624
+ "--disable-backgrounding-occluded-windows",
625
+ "--disable-renderer-backgrounding",
626
+ "--disable-features=Translate,BackForwardCache",
627
+ "--no-first-run",
628
+ "--no-default-browser-check",
629
+ "--mute-audio",
630
+ "--hide-scrollbars",
631
+ f"--window-size={SCREEN_W},{SCREEN_H}",
632
+ f"--user-data-dir={profile}",
633
+ "--js-flags=--max-old-space-size=256", # ุณู‚ู ุฐุงูƒุฑุฉ JS โ€” ูŠู…ู†ุน ุชุจูˆูŠุจ ุซู‚ูŠู„ ู…ู† ุงุณุชู‡ู„ุงูƒ ูƒู„ ุงู„ุฑุงู…
634
+ "about:blank",
635
+ ]
636
+ try:
637
+ proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
638
+ return proc
639
+ except FileNotFoundError:
640
+ return None
641
+ except Exception as e:
642
+ print(f"[chromium] โŒ ูุดู„ ุชุดุบูŠู„ {binary}: {e}")
643
+ return None
644
+
645
+
646
+ def _start_chromium(port: int, user_id: str) -> "subprocess.Popen | None":
647
+ """
648
+ ูŠูุดุบู‘ู„ ู…ุชุตูุญุงู‹ ุจูˆุถุน headless=new ุนู„ู‰ ู…ู†ูุฐ CDP ู…ุฎุตุต. ู„ุง XvfbุŒ ู„ุง DISPLAYุŒ
649
+ ู„ุง ู†ุงูุฐุฉ โ€” ุงู„ุฑู†ุฏุฑ ุจุงู„ูƒุงู…ู„ ุฏุงุฎู„ูŠ (in-process) ู„ู…ุญุฑูƒ ุงู„ู…ุชุตูุญ ู†ูุณู‡.
650
+
651
+ ุฐูƒุงุก ุฅุถุงููŠ: ู„ูˆ ุงู„ู…ุชุตูุญ ุงู„ุญุงู„ูŠ (BROWSER_BIN) ูุดู„ ุจุงู„ุฅู‚ู„ุงุน ูุนู„ูŠุงู‹ ูˆู‚ุช ุงู„ุชุดุบูŠู„
652
+ ุงู„ุญู‚ูŠู‚ูŠ (ู…ูˆ ูˆู‚ุช ุงู„ูุญุต ุงู„ุฃูˆู„ูŠ)ุŒ ูŠุฌุฑู‘ุจ ุจู‚ูŠุฉ ุงู„ู…ุชุตูุญุงุช ุงู„ู…ุฑุดุญุฉ ุชู„ู‚ุงุฆูŠุงู‹ ุจุฏู„
653
+ ุงู„ูุดู„ ุงู„ูƒุงู…ู„ุŒ ูˆูŠุญุฏู‘ุซ BROWSER_BIN ู„ู„ู…ุชุตูุญ ุงู„ู„ูŠ ู†ุฌุญ ู„ูŠูุณุชุฎุฏู… ู…ุจุงุดุฑุฉ ุจุงู„ุฌู„ุณุงุช
654
+ ุงู„ู‚ุงุฏู…ุฉ (ุจุฏูˆู† ุฅุนุงุฏุฉ ุชุฌุฑุจุฉ ูƒู„ ุงู„ู…ุชุตูุญุงุช ุงู„ูุงุดู„ุฉ ู…ู† ุฌุฏูŠุฏ ูƒู„ ู…ุฑุฉ).
655
+ """
656
+ global BROWSER_BIN
657
+ profile = _profile_dir(user_id)
658
+ try:
659
+ subprocess.run(["pkill", "-9", "-f", f"[r]emote-debugging-port={port}"],
660
+ capture_output=True, timeout=3)
661
+ time.sleep(0.2)
662
+ except Exception:
663
+ pass
664
+
665
+ proc = _launch_browser_process(BROWSER_BIN, port, profile)
666
+ if proc is not None:
667
+ print(f"[chromium] ๐Ÿš€ ุจุฏุฃ '{BROWSER_BIN}' (PID {proc.pid}) ุนู„ู‰ ู…ู†ูุฐ CDP {port} โ€” headless=new")
668
+ return proc
669
+
670
+ print(f"[chromium] โš ๏ธ ูุดู„ '{BROWSER_BIN}' ูุนู„ูŠุงู‹ โ€” ุฃุฌุฑุจ ุจู‚ูŠุฉ ุงู„ู…ุชุตูุญุงุช ุงู„ู…ุนุฑูˆูุฉ ุชู„ู‚ุงุฆูŠุงู‹...")
671
+ for alt in _BROWSER_CANDIDATES:
672
+ if alt == BROWSER_BIN or not _binary_exists(alt):
673
+ continue
674
+ proc = _launch_browser_process(alt, port, profile)
675
+ if proc is not None:
676
+ print(f"[chromium] โœ… ู†ุฌุญ ุงู„ุจุฏูŠู„ '{alt}' โ€” ุณูŠูุนุชู…ุฏ ู„ุจู‚ูŠุฉ ุงู„ุฌู„ุณุงุช ู…ู† ุงู„ุขู†")
677
+ BROWSER_BIN = alt
678
+ return proc
679
+
680
+ print(f"[chromium] โŒ ูุดู„ุช ูƒู„ ุงู„ู…ุชุตูุญุงุช ุงู„ู…ุชุงุญุฉ ุนู„ู‰ ู‡ุฐุง ุงู„ุณูŠุฑูุฑ")
681
+ return None
682
+
683
+
684
+ def _kill_chromium(proc: "subprocess.Popen | None", port: int):
685
+ if proc:
686
+ try:
687
+ proc.kill()
688
+ proc.wait(timeout=3)
689
+ except Exception:
690
+ pass
691
+ try:
692
+ subprocess.run(["pkill", "-9", "-f", f"[r]emote-debugging-port={port}"],
693
+ capture_output=True, timeout=3)
694
+ except Exception:
695
+ pass
696
+
697
+
698
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
699
+ # โ”€โ”€ ุฅุฏุงุฑุฉ ุงู„ุฌู„ุณุงุช (ู…ุณุชุฎุฏู… โ†’ CDPSession + Chromium process) โ”€โ”€โ”€โ”€โ”€
700
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
701
+
702
+ # user_id โ†’ {
703
+ # "port": int, "proc": Popen, "cdp": CDPSession|None,
704
+ # "active_ws": WebSocket|None, "created": float,
705
+ # "consecutive_failures": int, "last_frame_hash": str,
706
+ # "last_mouse_x": int, "last_mouse_y": int,
707
+ # }
708
+ _sessions: dict = {}
709
+
710
+
711
+ async def get_or_create_session(user_id: str, ws: WebSocket) -> dict:
712
+ with _sessions_lock:
713
+ sess = _sessions.get(user_id)
714
+ if sess:
715
+ sess["active_ws"] = ws
716
+ print(f"[session] ๐Ÿ” ุฅุนุงุฏุฉ ุงุชุตุงู„ '{user_id}' ุนู„ู‰ ู…ู†ูุฐ {sess['port']}")
717
+ return sess
718
+
719
+ if len(_sessions) >= MAX_SESSIONS:
720
+ # ุฃุนุฏ ุงุณุชุฎุฏุงู… ุฃู‚ุฏู… ุฌู„ุณุฉ ุบูŠุฑ ู…ุชุตู„ุฉ ุจุฏู„ ุฑูุถ ุงู„ู…ุณุชุฎุฏู… ุงู„ุฌุฏูŠุฏ
721
+ idle = [(uid, s) for uid, s in _sessions.items() if not s.get("active_ws")]
722
+ if idle:
723
+ oldest_uid = min(idle, key=lambda t: t[1]["created"])[0]
724
+ old = _sessions.pop(oldest_uid)
725
+ _kill_chromium(old.get("proc"), old["port"])
726
+ _release_cdp_port(old["port"])
727
+ print(f"[session] โ™ป๏ธ ุฃูุฒูŠู„ุช ุฌู„ุณุฉ ุฎุงู…ู„ุฉ ู‚ุฏูŠู…ุฉ '{oldest_uid}' ู„ุฅูุณุงุญ ุงู„ู…ุฌุงู„")
728
+
729
+ port = _alloc_cdp_port()
730
+ sess = {
731
+ "user_id": user_id,
732
+ "port": port,
733
+ "proc": None,
734
+ "cdp": None,
735
+ "active_ws": ws,
736
+ "created": time.time(),
737
+ "consecutive_failures": 0,
738
+ "last_frame_hash": "",
739
+ "last_mouse_x": SCREEN_W // 2,
740
+ "last_mouse_y": SCREEN_H // 2,
741
+ "shot_lock": asyncio.Lock(),
742
+ "engine": "chromium", # "chromium" (ุงูุชุฑุงุถูŠุŒ ุนุจุฑ CDP) ุฃูˆ "camoufox" (ู…ุถุงุฏ ู„ู„ูƒุดูุŒ ุนุจุฑ Playwright)
743
+ }
744
+ _sessions[user_id] = sess
745
+ print(f"[session] โœ… ู…ุณุชุฎุฏู… ุฌุฏูŠุฏ '{user_id}' โ†’ ู…ู†ูุฐ CDP {port}")
746
+ return sess
747
+
748
+
749
+ async def ensure_browser_running(sess: dict) -> bool:
750
+ """ูŠุชุฃูƒุฏ ุฃู† Chromium + ุงุชุตุงู„ CDP ูŠุนู…ู„ุงู† ู„ู‡ุฐู‡ ุงู„ุฌู„ุณุฉ. ูŠูุดุบู‘ู„ู‡ู…ุง ุฅุฐุง ู„ุฒู…."""
751
+ if sess.get("cdp") and sess["cdp"].alive:
752
+ return True
753
+
754
+ if not sess.get("proc") or sess["proc"].poll() is not None:
755
+ proc = await asyncio.to_thread(_start_chromium, sess["port"], sess["user_id"])
756
+ sess["proc"] = proc
757
+ if proc is None:
758
+ return False
759
+
760
+ cdp = CDPSession(sess["port"])
761
+ ok = await cdp.connect(timeout=8.0)
762
+ if ok:
763
+ sess["cdp"] = cdp
764
+ return True
765
+ return False
766
+
767
+
768
+ async def reset_session(user_id: str) -> bool:
769
+ """ูŠูุนูŠุฏ ุชุดุบูŠู„ Chromium ุจุงู„ูƒุงู…ู„ ู„ู‡ุฐุง ุงู„ู…ุณุชุฎุฏู… โ€” ุงู„ุฅุตู„ุงุญ ุงู„ุดุงู…ู„ ุงู„ูˆุญูŠุฏ ุงู„ู…ุทู„ูˆุจ ุงู„ุขู†ุŒ
770
+ ุจู…ุง ุฃู†ู‡ ู„ุง ูŠูˆุฌุฏ Xvfb ุฃูˆ ู…ู„ูุงุช ุฌู„ุณุฉ X ู…ู†ูุตู„ุฉ ูŠุฌุจ ุชู†ุธูŠูู‡ุง."""
771
+ with _sessions_lock:
772
+ sess = _sessions.get(user_id)
773
+ if not sess:
774
+ return False
775
+ proc, port = sess.get("proc"), sess["port"]
776
+ old_cdp = sess.get("cdp")
777
+
778
+ if old_cdp:
779
+ await old_cdp.close()
780
+ await asyncio.to_thread(_kill_chromium, proc, port)
781
+
782
+ new_proc = await asyncio.to_thread(_start_chromium, port, user_id)
783
+ new_cdp = CDPSession(port)
784
+ ok = await new_cdp.connect(timeout=8.0) if new_proc else False
785
+
786
+ with _sessions_lock:
787
+ if user_id in _sessions:
788
+ _sessions[user_id]["proc"] = new_proc
789
+ _sessions[user_id]["cdp"] = new_cdp if ok else None
790
+ _sessions[user_id]["consecutive_failures"] = 0
791
+ _sessions[user_id]["last_frame_hash"] = ""
792
+ print(f"[reset] {'โœ…' if ok else 'โŒ'} ุฅุนุงุฏุฉ ุถุจุท '{user_id}' ุนู„ู‰ ู…ู†ูุฐ {port}")
793
+ return ok
794
+
795
+
796
+ async def destroy_session_ws(user_id: str, ws: WebSocket):
797
+ """ุนู†ุฏ ุงู†ู‚ุทุงุน WebSocket โ€” ู†ูุจู‚ูŠ Chromium ุดุบุงู„ุงู‹ (ุงู„ุฌู„ุณุฉ ู…ุญููˆุธุฉ) ูˆูู‚ุท ู†ุฒูŠู„ ุงู„ุงุชุตุงู„."""
798
+ with _sessions_lock:
799
+ sess = _sessions.get(user_id)
800
+ if sess and sess.get("active_ws") is ws:
801
+ sess["active_ws"] = None
802
+ print(f"[session] ๐Ÿ“ด '{user_id}' ู‚ุทุน ุงู„ุงุชุตุงู„ (ุงู„ุฌู„ุณุฉ ู…ุญููˆุธุฉ)")
803
+
804
+
805
+ async def destroy_session_full(user_id: str):
806
+ with _sessions_lock:
807
+ sess = _sessions.pop(user_id, None)
808
+ if sess:
809
+ if sess.get("cdp"):
810
+ await sess["cdp"].close()
811
+ await asyncio.to_thread(_kill_chromium, sess.get("proc"), sess["port"])
812
+ _release_cdp_port(sess["port"])
813
+ await destroy_camoufox_session(user_id)
814
+
815
+
816
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
817
+ # โ”€โ”€ ู„ู‚ุทุฉ ุงู„ุดุงุดุฉ โ€” ุนุจุฑ CDP ู…ุจุงุดุฑุฉ (ุจุฏูˆู† subprocess ุฎุงุฑุฌูŠ) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
818
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
819
+
820
+ async def cdp_screenshot(sess: dict, quality: int = 75) -> "tuple[str, int, int] | None":
821
+ """
822
+ ูŠู„ุชู‚ุท ู„ู‚ุทุฉ ุดุงุดุฉ ุนุจุฑ Page.captureScreenshot โ€” ุฃู…ุฑ CDP ูˆุงุญุฏ ูŠุฑุฌุน JPEG
823
+ base64 ุฌุงู‡ุฒ ู…ุจุงุดุฑุฉ ู…ู† ู…ุญุฑูƒ ุงู„ุฑู†ุฏุฑ ุงู„ุฏุงุฎู„ูŠ ู„ู€ Chromium. ู„ุง ูŠูˆุฌุฏ X server
824
+ ูŠู…ูƒู† ุฃู† "ูŠุชุฌู…ุฏ"ุŒ ู„ุง ุญุงุฌุฉ ู„ูุญุต "ู‡ู„ ุงู„ุตูˆุฑุฉ ุณูˆุฏุงุก"ุŒ ูˆู„ุง ุนู…ู„ูŠุฉ subprocess
825
+ ุฎุงุฑุฌูŠุฉ (import/xwd) ู‚ุฏ ุชูุดู„ ุจุณุจุจ ุฃุฏูˆุงุช ู…ูู‚ูˆุฏุฉ ุนู„ู‰ ุงู„ุณูŠุฑูุฑ.
826
+ ูŠูุนูŠุฏ (base64_jpeg, width, height) ุฃูˆ None ุนู†ุฏ ุงู„ูุดู„.
827
+ """
828
+ cdp = sess.get("cdp")
829
+ if not cdp or not cdp.alive:
830
+ return None
831
+ result = await cdp.send("Page.captureScreenshot", {
832
+ "format": "jpeg", "quality": quality, "fromSurface": True, "captureBeyondViewport": False,
833
+ }, timeout=8.0)
834
+ if not result:
835
+ return None
836
+ data = result.get("result", {}).get("data")
837
+ if not data:
838
+ return None
839
+ return data, SCREEN_W, SCREEN_H
840
+
841
+
842
+ def _draw_mouse_marker_on_jpeg(b64_jpeg: str, mx: int, my: int) -> str:
843
+ """ูŠุฑุณู… ุนู„ุงู…ุฉ ุตุบูŠุฑุฉ ู„ู…ูˆู‚ุน ุงู„ูุฃุฑุฉ ููˆู‚ ุงู„ุตูˆุฑุฉ (ู…ุทู„ูˆุจุฉ ุจุตุฑูŠุงู‹ ู„ู„ุฐูƒุงุก ุงู„ุงุตุทู†ุงุนูŠ
844
+ ู„ูŠุฑู‰ ุฃูŠู† ุงู„ู…ุคุดุฑ). ุงู„ุนู…ู„ูŠุฉ ุฎููŠูุฉ (ุฑุณู… ูู‚ุทุŒ ุจุฏูˆู† resize) ูุชูุจู‚ูŠ ุฒู…ู† ูƒู„ ู„ู‚ุทุฉ ู…ู†ุฎูุถุงู‹."""
845
+ try:
846
+ from PIL import Image, ImageDraw
847
+ import io as _io
848
+ raw = base64.b64decode(b64_jpeg)
849
+ img = Image.open(_io.BytesIO(raw)).convert("RGB")
850
+ draw = ImageDraw.Draw(img)
851
+ r = 9
852
+ draw.ellipse([(mx - r, my - r), (mx + r, my + r)], outline=(255, 60, 60), width=2)
853
+ draw.line([(mx - 14, my), (mx + 14, my)], fill=(255, 60, 60), width=1)
854
+ draw.line([(mx, my - 14), (mx, my + 14)], fill=(255, 60, 60), width=1)
855
+ buf = _io.BytesIO()
856
+ img.save(buf, format="JPEG", quality=80, optimize=True)
857
+ return base64.b64encode(buf.getvalue()).decode()
858
+ except Exception:
859
+ return b64_jpeg # ู„ูˆ ูุดู„ ุงู„ุฑุณู… ู„ุฃูŠ ุณุจุจุŒ ุฃุนุฏ ุงู„ุตูˆุฑุฉ ุงู„ุฃุตู„ูŠุฉ ุจุฏู„ ุงู„ูุดู„ ุงู„ูƒุงู…ู„
860
+
861
+
862
+ def _grid_variant(b64_jpeg: str, grid_step: int, color: tuple, label_every: int) -> str:
863
+ """
864
+ ูŠู†ุชุฌ ู†ุณุฎุฉ ู…ู† ุงู„ุตูˆุฑุฉ ู…ุน ุดุจูƒุฉ ุฅุญุฏุงุซูŠุงุช ู…ุฑุณูˆู…ุฉ ููˆู‚ู‡ุง โ€” ุชุณุงุนุฏ ุงู„ุฐูƒุงุก ุงู„ุงุตุทู†ุงุนูŠ
865
+ ุนู„ู‰ ุชุญุฏูŠุฏ ุฅุญุฏุงุซูŠุงุช ุฏู‚ูŠู‚ุฉ ู„ู„ู†ู‚ุฑ. ู†ูุณ ููƒุฑุฉ v13 ู„ูƒู† ู…ุจู†ูŠุฉ ููˆู‚ JPEG ุงู„ุฌุงู‡ุฒ ู…ู†
866
+ CDP ู…ุจุงุดุฑุฉ ุจุฏู„ ุฅุนุงุฏุฉ ุงู„ุฑุณู… ู…ู† raw pixels.
867
+ """
868
+ try:
869
+ from PIL import Image, ImageDraw
870
+ import io as _io
871
+ raw = base64.b64decode(b64_jpeg)
872
+ img = Image.open(_io.BytesIO(raw)).convert("RGB")
873
+ draw = ImageDraw.Draw(img, "RGBA")
874
+ w, h = img.size
875
+ major = (*color, 130)
876
+ minor = (*color, 40)
877
+ x = grid_step
878
+ while x < w:
879
+ is_major = x % label_every == 0
880
+ draw.line([(x, 0), (x, h)], fill=major if is_major else minor, width=1)
881
+ if is_major:
882
+ draw.rectangle([(x + 1, 2), (x + 34, 15)], fill=(0, 0, 0, 175))
883
+ draw.text((x + 2, 3), str(x), fill=color)
884
+ x += grid_step
885
+ y = grid_step
886
+ while y < h:
887
+ is_major = y % label_every == 0
888
+ draw.line([(0, y), (w, y)], fill=major if is_major else minor, width=1)
889
+ if is_major:
890
+ draw.rectangle([(2, y + 1), (38, y + 14)], fill=(0, 0, 0, 175))
891
+ draw.text((3, y + 2), str(y), fill=color)
892
+ y += grid_step
893
+ final = img.convert("RGB")
894
+ buf = _io.BytesIO()
895
+ final.save(buf, format="JPEG", quality=78, optimize=True)
896
+ return base64.b64encode(buf.getvalue()).decode()
897
+ except Exception:
898
+ return b64_jpeg
899
+
900
+
901
+ async def capture_full(sess: dict, quality: int = 75) -> dict:
902
+ """
903
+ ูŠู„ุชู‚ุท ู„ู‚ุทุฉ ูˆุงุญุฏุฉ ูˆูŠู†ุชุฌ ู…ู†ู‡ุง: ู†ุณุฎุฉ ู†ุธูŠูุฉ + ู†ุณุฎุฉ ุจุนู„ุงู…ุฉ ุงู„ูุฃุฑุฉ + ุดุจูƒุชุงู†
904
+ ุฅุญุฏุงุซูŠุงุช (ุนุงุฏูŠุฉ ูˆุฏู‚ูŠู‚ุฉ) โ€” ุจู†ูุณ ุชู†ุณูŠู‚ ุญู‚ูˆู„ ุงู„ุฑุฏ ุงู„ุฐูŠ ุชุชูˆู‚ุนู‡ ุงู„ูˆุงุฌู‡ุฉ ุงู„ุฃู…ุงู…ูŠุฉ
905
+ (data, data_grid, data_grid2, data_grid3, width, height, mouse_x, mouse_y).
906
+
907
+ ูŠุนู…ู„ ู…ุน ูƒู„ุง ุงู„ู…ุญุฑูƒูŠู† ุญุณุจ sess["engine"]:
908
+ "chromium" (ุงูุชุฑุงุถูŠ) โ†’ ุนุจุฑ CDP ู…ุจุงุดุฑุฉ (cdp_screenshot)
909
+ "camoufox" โ†’ ุนุจุฑ Playwright screenshot (ุฃุจุทุฃ ู‚ู„ูŠู„ุงู‹ ู„ูƒู† ู…ุถุงุฏ ู„ู„ูƒุดู)
910
+ """
911
+ if sess.get("engine") == "camoufox":
912
+ cam = await get_camoufox_session(sess["user_id"])
913
+ if not cam:
914
+ return {"data": "", "data_grid": "", "data_grid2": "", "data_grid3": "",
915
+ "width": SCREEN_W, "height": SCREEN_H,
916
+ "mouse_x": sess.get("last_mouse_x", 0), "mouse_y": sess.get("last_mouse_y", 0),
917
+ "is_placeholder": True}
918
+ raw_b64 = await cam.screenshot_b64()
919
+ if not raw_b64:
920
+ return {"data": "", "data_grid": "", "data_grid2": "", "data_grid3": "",
921
+ "width": SCREEN_W, "height": SCREEN_H,
922
+ "mouse_x": sess.get("last_mouse_x", 0), "mouse_y": sess.get("last_mouse_y", 0),
923
+ "is_placeholder": True}
924
+ w, h = SCREEN_W, SCREEN_H
925
+ mx, my = sess.get("last_mouse_x", w // 2), sess.get("last_mouse_y", h // 2)
926
+
927
+ def _build_cam():
928
+ clean = _draw_mouse_marker_on_jpeg(raw_b64, mx, my)
929
+ grid1 = _grid_variant(clean, 50, (0, 255, 180), 100)
930
+ grid2 = _grid_variant(clean, 20, (255, 60, 60), 60)
931
+ return clean, grid1, grid2
932
+
933
+ clean, grid1, grid2 = await asyncio.to_thread(_build_cam)
934
+ return {"data": clean, "data_grid": grid1, "data_grid2": grid2, "data_grid3": grid2,
935
+ "width": w, "height": h, "mouse_x": mx, "mouse_y": my, "is_placeholder": False}
936
+
937
+ shot = await cdp_screenshot(sess, quality)
938
+ if not shot:
939
+ return {"data": "", "data_grid": "", "data_grid2": "", "data_grid3": "",
940
+ "width": SCREEN_W, "height": SCREEN_H,
941
+ "mouse_x": sess.get("last_mouse_x", 0), "mouse_y": sess.get("last_mouse_y", 0),
942
+ "is_placeholder": True}
943
+
944
+ raw_b64, w, h = shot
945
+ mx, my = sess.get("last_mouse_x", w // 2), sess.get("last_mouse_y", h // 2)
946
+
947
+ def _build():
948
+ clean = _draw_mouse_marker_on_jpeg(raw_b64, mx, my)
949
+ grid1 = _grid_variant(clean, 50, (0, 255, 180), 100)
950
+ grid2 = _grid_variant(clean, 20, (255, 60, 60), 60)
951
+ return clean, grid1, grid2
952
+
953
+ clean, grid1, grid2 = await asyncio.to_thread(_build)
954
+ return {
955
+ "data": clean, "data_grid": grid1, "data_grid2": grid2, "data_grid3": grid2,
956
+ "width": w, "height": h, "mouse_x": mx, "mouse_y": my,
957
+ "is_placeholder": False,
958
+ }
959
+
960
+
961
+ def _frame_hash(data: str) -> str:
962
+ return hashlib.md5(data.encode()).hexdigest()
963
+
964
+
965
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
966
+ # โ”€โ”€ ูุฃุฑุฉ/ูƒูŠุจูˆุฑุฏ โ€” ุนุจุฑ CDP Input domain (ุจุฏูˆู† xdotool/X server) โ”€โ”€
967
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
968
+
969
+ async def cdp_mouse_move(sess: dict, x: int, y: int):
970
+ cdp = sess.get("cdp")
971
+ if not cdp or not cdp.alive:
972
+ return
973
+ await cdp.send("Input.dispatchMouseEvent", {
974
+ "type": "mouseMoved", "x": x, "y": y,
975
+ }, timeout=4.0)
976
+ sess["last_mouse_x"], sess["last_mouse_y"] = x, y
977
+
978
+
979
+ async def cdp_mouse_click(sess: dict, x: int, y: int, button: str = "left", double: bool = False):
980
+ cdp = sess.get("cdp")
981
+ if not cdp or not cdp.alive:
982
+ return
983
+ await cdp_mouse_move(sess, x, y)
984
+ click_count = 2 if double else 1
985
+ await cdp.send("Input.dispatchMouseEvent", {
986
+ "type": "mousePressed", "x": x, "y": y, "button": button, "clickCount": click_count,
987
+ }, timeout=4.0)
988
+ await asyncio.sleep(0.04)
989
+ await cdp.send("Input.dispatchMouseEvent", {
990
+ "type": "mouseReleased", "x": x, "y": y, "button": button, "clickCount": click_count,
991
+ }, timeout=4.0)
992
+
993
+
994
+ async def cdp_mouse_drag(sess: dict, x1: int, y1: int, x2: int, y2: int, steps: int = 8):
995
+ cdp = sess.get("cdp")
996
+ if not cdp or not cdp.alive:
997
+ return
998
+ await cdp_mouse_move(sess, x1, y1)
999
+ await cdp.send("Input.dispatchMouseEvent", {
1000
+ "type": "mousePressed", "x": x1, "y": y1, "button": "left", "clickCount": 1,
1001
+ }, timeout=4.0)
1002
+ for i in range(1, steps + 1):
1003
+ ix = x1 + (x2 - x1) * i // steps
1004
+ iy = y1 + (y2 - y1) * i // steps
1005
+ await cdp.send("Input.dispatchMouseEvent", {
1006
+ "type": "mouseMoved", "x": ix, "y": iy, "button": "left",
1007
+ }, timeout=3.0)
1008
+ await asyncio.sleep(0.02)
1009
+ await cdp.send("Input.dispatchMouseEvent", {
1010
+ "type": "mouseReleased", "x": x2, "y": y2, "button": "left", "clickCount": 1,
1011
+ }, timeout=4.0)
1012
+ sess["last_mouse_x"], sess["last_mouse_y"] = x2, y2
1013
+
1014
+
1015
+ async def cdp_scroll(sess: dict, x: int, y: int, delta_y: int):
1016
+ cdp = sess.get("cdp")
1017
+ if not cdp or not cdp.alive:
1018
+ return
1019
+ await cdp.send("Input.dispatchMouseEvent", {
1020
+ "type": "mouseWheel", "x": x, "y": y, "deltaX": 0, "deltaY": delta_y,
1021
+ }, timeout=4.0)
1022
+
1023
+
1024
+ # ุฎุฑูŠุทุฉ ุฃุณู…ุงุก ู…ูุงุชูŠุญ ุดุงุฆุนุฉ โ†’ ุฃูƒูˆุงุฏ CDP (windowsVirtualKeyCode + key)
1025
+ _KEY_MAP = {
1026
+ "Return": (13, "Enter"), "Enter": (13, "Enter"),
1027
+ "Tab": (9, "Tab"), "Escape": (27, "Escape"), "BackSpace": (8, "Backspace"),
1028
+ "Delete": (46, "Delete"), "Left": (37, "ArrowLeft"), "Right": (39, "ArrowRight"),
1029
+ "Up": (38, "ArrowUp"), "Down": (40, "ArrowDown"), "Home": (36, "Home"), "End": (35, "End"),
1030
+ "space": (32, " "), "F5": (116, "F5"),
1031
+ }
1032
+
1033
+
1034
+ async def cdp_key_press(sess: dict, key_name: str):
1035
+ cdp = sess.get("cdp")
1036
+ if not cdp or not cdp.alive:
1037
+ return
1038
+ code, key = _KEY_MAP.get(key_name, (0, key_name))
1039
+ params = {"type": "keyDown", "key": key}
1040
+ if code:
1041
+ params["windowsVirtualKeyCode"] = code
1042
+ params["nativeVirtualKeyCode"] = code
1043
+ await cdp.send("Input.dispatchKeyEvent", params, timeout=4.0)
1044
+ params["type"] = "keyUp"
1045
+ await cdp.send("Input.dispatchKeyEvent", params, timeout=4.0)
1046
+
1047
+
1048
+ async def cdp_hotkey(sess: dict, keys: list):
1049
+ """ุงุฎุชุตุงุฑ ู…ุชุนุฏุฏ ุงู„ู…ูุงุชูŠุญ ู…ุซู„ ['ctrl','l'] ุฃูˆ ['alt','Left']."""
1050
+ cdp = sess.get("cdp")
1051
+ if not cdp or not cdp.alive:
1052
+ return
1053
+ modifiers = 0
1054
+ mod_map = {"alt": 1, "ctrl": 2, "control": 2, "meta": 4, "shift": 8}
1055
+ plain_keys = []
1056
+ for k in keys:
1057
+ kl = k.lower()
1058
+ if kl in mod_map:
1059
+ modifiers |= mod_map[kl]
1060
+ else:
1061
+ plain_keys.append(k)
1062
+ for k in plain_keys:
1063
+ code, key = _KEY_MAP.get(k, (ord(k[0].upper()) if len(k) == 1 else 0, k))
1064
+ await cdp.send("Input.dispatchKeyEvent", {
1065
+ "type": "rawKeyDown", "key": key, "modifiers": modifiers,
1066
+ "windowsVirtualKeyCode": code, "nativeVirtualKeyCode": code,
1067
+ }, timeout=4.0)
1068
+ await cdp.send("Input.dispatchKeyEvent", {
1069
+ "type": "keyUp", "key": key, "modifiers": modifiers,
1070
+ "windowsVirtualKeyCode": code, "nativeVirtualKeyCode": code,
1071
+ }, timeout=4.0)
1072
+
1073
+
1074
+ async def cdp_type_text(sess: dict, text: str):
1075
+ """
1076
+ ูŠูƒุชุจ ู†ุตุงู‹ ุนุจุฑ Input.insertText โ€” ูŠุฏุนู… ูƒู„ ุงู„ู„ุบุงุช (ุนุฑุจูŠ/ุฅู†ุฌู„ูŠุฒูŠ/ูุฑู†ุณูŠ)
1077
+ ุจุดูƒู„ ุฃุตู„ูŠ ุนุจุฑ CDP ู†ูุณู‡ุŒ ุจุฏูˆู† ุญุงุฌุฉ ู„ู€ xclip ุฃูˆ ุญูŠู„ุฉ clipboard+paste
1078
+ ุงู„ุชูŠ ูƒุงู†ุช ุถุฑูˆุฑูŠุฉ ุณุงุจู‚ุงู‹ ุจุณุจุจ ู‚ูŠูˆุฏ xdotool ู…ุน ุงู„ู†ุตูˆุต ุบูŠุฑ ุงู„ู„ุงุชูŠู†ูŠุฉ.
1079
+ """
1080
+ cdp = sess.get("cdp")
1081
+ if not cdp or not cdp.alive:
1082
+ return
1083
+ await cdp.send("Input.insertText", {"text": text}, timeout=6.0)
1084
+
1085
+
1086
+ async def cdp_navigate(sess: dict, url: str) -> bool:
1087
+ cdp = sess.get("cdp")
1088
+ if not cdp or not cdp.alive:
1089
+ return False
1090
+ result = await cdp.send("Page.navigate", {"url": url}, timeout=15.0)
1091
+ return bool(result and "error" not in result.get("result", {}))
1092
+
1093
+
1094
+ async def cdp_clipboard_write(sess: dict, text: str):
1095
+ """ูŠู†ุณุฎ ู†ุตุงู‹ ู„ุญุงูุธุฉ afterward-paste ุฏุงุฎู„ูŠุฉ ุนุจุฑ ู…ุชุบูŠู‘ุฑ JS ุจุณูŠุท (ุจุฏูŠู„ ุฎููŠู
1096
+ ู„ู€ xclipุŒ ู„ุฃู†ู‡ ู„ุง ูŠูˆุฌุฏ X server ู‡ู†ุง ุฃุตู„ุงู‹ ุชูุจู†ู‰ ุนู„ูŠู‡ ุญุงูุธุฉ ู†ุธุงู… ุญู‚ูŠู‚ูŠุฉ)."""
1097
+ cdp = sess.get("cdp")
1098
+ if not cdp or not cdp.alive:
1099
+ return
1100
+ js = f"window.__zclip = {json.dumps(text)};"
1101
+ await cdp.send("Runtime.evaluate", {"expression": js}, timeout=4.0)
1102
+
1103
+
1104
+ async def cdp_clipboard_read(sess: dict) -> str:
1105
+ cdp = sess.get("cdp")
1106
+ if not cdp or not cdp.alive:
1107
+ return ""
1108
+ result = await cdp.send("Runtime.evaluate", {
1109
+ "expression": "window.__zclip || ''", "returnByValue": True,
1110
+ }, timeout=4.0)
1111
+ if not result:
1112
+ return ""
1113
+ return result.get("result", {}).get("result", {}).get("value", "") or ""
1114
+
1115
+
1116
+ async def cdp_get_screen_info(sess: dict) -> dict:
1117
+ return {"width": SCREEN_W, "height": SCREEN_H,
1118
+ "mouse_x": sess.get("last_mouse_x", 0), "mouse_y": sess.get("last_mouse_y", 0)}
1119
+
1120
+
1121
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1122
+ # โ”€โ”€ SafeSearch โ€” ู†ูุณ ู…ู†ุทู‚ v13 ู…ุญููˆุธุงู‹ ูƒู…ุง ู‡ูˆ (ูŠุนู…ู„ ุจุดูƒู„ ุฌูŠุฏ) โ”€โ”€โ”€โ”€
1123
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1124
+
1125
+ _BING_RE = re.compile(r"https?://(?:www\.)?bing\.com[^\s'\"]*")
1126
+ _DDG_RE = re.compile(r"https?://(?:www\.)?duckduckgo\.com[^\s'\"]*")
1127
+ _GOOG_RE = re.compile(r"https?://(?:www\.)?google\.[a-z.]+[^\s'\"]*")
1128
+
1129
+
1130
+ def _safe_search(text: str) -> str:
1131
+ def _bing(m):
1132
+ u = m.group(0)
1133
+ return re.sub(r"adlt=\w+", "adlt=strict", u) if "adlt=" in u else u + ("&" if "?" in u else "?") + "adlt=strict"
1134
+
1135
+ def _ddg(m):
1136
+ u = m.group(0)
1137
+ return re.sub(r"kp=\d", "kp=1", u) if "kp=" in u else u + ("&" if "?" in u else "?") + "kp=1"
1138
+
1139
+ def _goog(m):
1140
+ u = m.group(0)
1141
+ return re.sub(r"safe=\w+", "safe=strict", u) if "safe=" in u else u + ("&" if "?" in u else "?") + "safe=strict"
1142
+
1143
+ return _GOOG_RE.sub(_goog, _DDG_RE.sub(_ddg, _BING_RE.sub(_bing, text)))
1144
+
1145
+
1146
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1147
+ # โ”€โ”€ Terminal โ€” ุชู†ููŠุฐ ุฃูˆุงู…ุฑ bash (ู…ู†ูุตู„ ุชู…ุงู…ุงู‹ ุนู† Chromium) โ”€โ”€โ”€โ”€โ”€โ”€
1148
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1149
+
1150
+ _terminal_sem = asyncio.Semaphore(6)
1151
+ _PKILL_RE = re.compile(r"\b(pkill|killall)\s+(-9\s+)?-f\s+(['\"]?)([a-zA-Z0-9_./-]+)\3")
1152
+
1153
+
1154
+ def _sanitize_pkill(cmd: str) -> str:
1155
+ def _fix(m):
1156
+ tool, d9, _q, p = m.group(1), m.group(2) or "", m.group(3), m.group(4)
1157
+ sp = f"[{p[0]}]{p[1:]}" if len(p) > 1 else p
1158
+ return f"{tool} {d9}-f '{sp}'"
1159
+ return _PKILL_RE.sub(_fix, cmd)
1160
+
1161
+
1162
+ async def run_cmd(cmd: str, timeout: int = 60) -> dict:
1163
+ cmd = _sanitize_pkill(_safe_search(cmd))
1164
+ async with _terminal_sem:
1165
+ env = {**os.environ, "PYTHONIOENCODING": "utf-8", "LANG": "en_US.UTF-8"}
1166
+
1167
+ def _exec():
1168
+ try:
1169
+ r = subprocess.run(cmd, shell=True, capture_output=True, text=True,
1170
+ timeout=timeout, env=env, executable="/bin/bash")
1171
+ return {"stdout": r.stdout[-15000:], "stderr": r.stderr[-3000:], "returncode": r.returncode}
1172
+ except subprocess.TimeoutExpired:
1173
+ return {"stdout": "", "stderr": f"โฑ๏ธ Timeout {timeout}s", "returncode": -1}
1174
+ except Exception as e:
1175
+ return {"stdout": "", "stderr": str(e), "returncode": -1}
1176
+
1177
+ return await asyncio.to_thread(_exec)
1178
+
1179
+
1180
+ def _search_sources(query: str) -> list:
1181
+ q = urllib.parse.quote_plus(query)
1182
+ return [
1183
+ {"name": "DuckDuckGo Instant",
1184
+ "cmd": f"curl -s --max-time 15 'https://api.duckduckgo.com/?q={q}&format=json&no_html=1&skip_disambig=1' | python3 -c \"import sys,json;d=json.load(sys.stdin);a=d.get('AbstractText','');r=d.get('RelatedTopics',[]);print('ANS:',a or 'none');[print('-',x.get('Text','')[:200]) for x in r[:6] if isinstance(x,dict)]\""},
1185
+ {"name": "Wikipedia EN",
1186
+ "cmd": f"curl -s --max-time 12 'https://en.wikipedia.org/api/rest_v1/page/summary/{q}' | python3 -c \"import sys,json;d=json.load(sys.stdin);print(d.get('title','')+'\\n'+d.get('extract','')[:1200])\""},
1187
+ {"name": "DuckDuckGo HTML",
1188
+ "cmd": f"curl -sL --max-time 15 -H 'User-Agent: Mozilla/5.0' 'https://html.duckduckgo.com/html/?q={q}' | python3 -c \"import sys,re;h=sys.stdin.read();s=re.findall(r'class=.result__snippet[^>]*>(.*?)</a>',h,re.DOTALL);clean=lambda x:re.sub('<[^>]+>','',x).strip();[print(str(i+1)+'. '+clean(x)[:200]) for i,x in enumerate(s[:7])]\""},
1189
+ {"name": "HackerNews",
1190
+ "cmd": f"curl -s --max-time 12 'https://hn.algolia.com/api/v1/search?query={q}&hitsPerPage=6&tags=story' | python3 -c \"import sys,json;d=json.load(sys.stdin);[print(str(i+1)+'. '+h.get('title','')+' Pts:'+str(h.get('points',0))) for i,h in enumerate(d.get('hits',[])[:5])]\""},
1191
+ {"name": "Reddit",
1192
+ "cmd": f"curl -sL --max-time 12 -H 'Accept: application/json' 'https://www.reddit.com/search.json?q={q}&sort=new&limit=6' | python3 -c \"import sys,json;d=json.load(sys.stdin);[print(str(i+1)+'. '+p['data'].get('title','')[:160]) for i,p in enumerate(d.get('data',{{}}).get('children',[])[:5])]\""},
1193
+ ]
1194
+
1195
+
1196
+ def _result_empty(s: str) -> bool:
1197
+ if not s or len(s.strip()) < 15:
1198
+ return True
1199
+ return "ans: none" in s.lower()
1200
+
1201
+
1202
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1203
+ # โ”€โ”€ Brave Search API โ€” ู‚ู†ุงุฉ ุงู„ุจุญุซ ุงู„ุฑุณู…ูŠุฉ ุงู„ู…ุตุฑูŽู‘ุญ ุจู‡ุง โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1204
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1205
+ # ุนู„ู‰ ุนูƒุณ ุฒูŠุงุฑุฉ duckduckgo.com/google.com ูƒู…ูˆู‚ุน ูุนู„ูŠ ุนุจุฑ ุงู„ู…ุชุตูุญ (ุงู„ู„ูŠ ูŠูˆุงุฌู‡
1206
+ # ูƒุงุจุชุดุง ู„ุฃู† ู‡ุฐูŠ ุงู„ู…ุญุฑูƒุงุช ุชูƒุฑู‡ ุงู„ุทู„ุจุงุช ุงู„ุขู„ูŠุฉ)ุŒ Brave Search API ู…ุตู…ู… ุฃุตู„ุงู‹
1207
+ # ู„ูŠูุณุชุฎุฏู… ุจุฑู…ุฌูŠุงู‹ โ€” ุจุฏูˆู† ูƒุงุจุชุดุง ุฅุทู„ุงู‚ุงู‹ุŒ ู„ุฃู†ู‡ ู…ุฑุฎู‘ุต ู„ู‡ุฐุง ุงู„ุบุฑุถ ุชุญุฏูŠุฏุงู‹.
1208
+ # ู‡ุฐุง ุจุงู„ุถุจุท ุฃุณู„ูˆุจ Manus: ุจุญุซ ู†ุธูŠู ุนุจุฑ API/ุณุทุฑ ุฃูˆุงู…ุฑ ูŠุฑุฌุน ู†ุชุงุฆุฌ ู†ุตูŠุฉ ู…ุจุงุดุฑุฉุŒ
1209
+ # ูุชุญ ู…ุชุตูุญ ูุนู„ูŠ ูŠูุญูุธ ูู‚ุท ู„ู…ุง ูŠุญุชุงุฌ ุงู„ู…ุณุชุฎุฏู… "ุชุตูุญ ู…ูˆู‚ุน ุจุนูŠู†ู‡ ุจุตุฑูŠุงู‹".
1210
+ #
1211
+ # ุงู„ุชูุนูŠู„: ุนูŠู‘ู† ู…ุชุบูŠู‘ุฑ ุงู„ุจูŠุฆุฉ BRAVE_API_KEY ุจู…ูุชุงุญูƒ ู…ู†
1212
+ # https://api-dashboard.search.brave.com (ููŠู‡ tier ู…ุฌุงู†ูŠ โ€” 2000 ุงุณุชุนู„ุงู…/ุดู‡ุฑ).
1213
+
1214
+ BRAVE_API_KEY = os.environ.get("BRAVE_API_KEY", "").strip()
1215
+ BRAVE_ENDPOINT = "https://api.search.brave.com/res/v1/web/search"
1216
+
1217
+
1218
+ async def brave_search(query: str, count: int = 8) -> dict:
1219
+ """
1220
+ ูŠุณุชุฏุนูŠ Brave Search API ู…ุจุงุดุฑุฉ (ุจุฏูˆู† ู…ุชุตูุญุŒ ุจุฏูˆู† ูƒุงุจุชุดุง). ูŠูุนูŠุฏ ู†ุชุงุฆุฌ
1221
+ ู…ู†ุณู‘ู‚ุฉ ู†ุตูŠุงู‹ ุจู†ูุณ ุดูƒู„ ู…ุฎุฑุฌุงุช run_cmd ุงู„ุนุงุฏูŠุฉุŒ ุนุดุงู† ุชู†ุฏู…ุฌ ุจุณู„ุงุณุฉ ู…ุน ุจู‚ูŠุฉ
1222
+ ู…ู†ุทู‚ ุงู„ุชุฑู…ู†ุงู„ ูˆุงู„ูุฑูˆู†ุช ุฅู†ุฏ ุจุฏูˆู† ุฃูŠ ุชุนุฏูŠู„ ุฅุถุงููŠ ู…ุทู„ูˆุจ ู‡ู†ุงูƒ.
1223
+ """
1224
+ if not BRAVE_API_KEY:
1225
+ return {"stdout": "", "stderr": "BRAVE_API_KEY ุบูŠุฑ ู…ูุนุฑูŽู‘ู โ€” ุฑุงุฌุน ุงู„ุฅุนุฏุงุฏุงุช", "returncode": -1}
1226
+
1227
+ def _fetch():
1228
+ import urllib.request
1229
+ import urllib.error
1230
+ url = f"{BRAVE_ENDPOINT}?q={urllib.parse.quote_plus(query)}&count={min(count, 20)}&safesearch=moderate"
1231
+ req = urllib.request.Request(url, headers={
1232
+ "Accept": "application/json",
1233
+ "Accept-Encoding": "gzip",
1234
+ "X-Subscription-Token": BRAVE_API_KEY,
1235
+ })
1236
+ try:
1237
+ with urllib.request.urlopen(req, timeout=15) as r:
1238
+ raw = r.read()
1239
+ if r.info().get("Content-Encoding") == "gzip":
1240
+ import gzip
1241
+ raw = gzip.decompress(raw)
1242
+ return json.loads(raw), None
1243
+ except urllib.error.HTTPError as e:
1244
+ body = e.read().decode(errors="ignore")[:300]
1245
+ return None, f"HTTP {e.code}: {body}"
1246
+ except Exception as e:
1247
+ return None, str(e)
1248
+
1249
+ data, err = await asyncio.to_thread(_fetch)
1250
+ if err:
1251
+ return {"stdout": "", "stderr": f"Brave Search error: {err}", "returncode": -1}
1252
+
1253
+ lines = []
1254
+ # ุงู„ุฅุฌุงุจุฉ ุงู„ุณุฑูŠุนุฉ (infobox) ุฅู† ูˆูุฌุฏุช
1255
+ infobox = data.get("infobox", {}) or {}
1256
+ if infobox.get("long_desc") or infobox.get("description"):
1257
+ lines.append("ANS: " + (infobox.get("long_desc") or infobox.get("description", ""))[:400])
1258
+
1259
+ web_results = (data.get("web", {}) or {}).get("results", []) or []
1260
+ for i, r in enumerate(web_results[:count], 1):
1261
+ title = r.get("title", "")
1262
+ desc = re.sub(r"<[^>]+>", "", r.get("description", ""))
1263
+ url = r.get("url", "")
1264
+ lines.append(f"{i}. {title}\n {desc[:220]}\n {url}")
1265
+
1266
+ if not lines:
1267
+ return {"stdout": "", "stderr": "ู„ุง ุชูˆุฌุฏ ู†ุชุงุฆุฌ ู…ู† Brave Search ู„ู‡ุฐุง ุงู„ุงุณุชุนู„ุงู…", "returncode": 0}
1268
+
1269
+ return {"stdout": "\n".join(lines)[:15000], "stderr": "", "returncode": 0}
1270
+
1271
+
1272
+ # ู†ู…ุท ูŠู„ุชู‚ุท ุฃู…ุฑ ุจุญุซ "ุฒุงุฆู" ู…ุฎุตุต ูŠูุฑุณู„ู‡ ุงู„ุฐูƒุงุก ุงู„ุงุตุทู†ุงุนูŠ ุนุจุฑ ุฃุฏุงุฉ terminal
1273
+ # ุจุตูŠุบุฉ ุจุณูŠุทุฉ: search: ู†ุต ุงู„ุงุณุชุนู„ุงู… (ุฃูˆ search "ู†ุต ุงู„ุงุณุชุนู„ุงู…")
1274
+ _SEARCH_CMD_RE = re.compile(r"^\s*search\s*:?\s*[\"']?(.+?)[\"']?\s*$", re.IGNORECASE)
1275
+
1276
+
1277
+ async def run_cmd_smart(cmd: str, timeout: int = 60) -> dict:
1278
+ # โ”€โ”€ ุฃูˆู„ูˆูŠุฉ ู‚ุตูˆู‰: ุฃู…ุฑ ุจุญุซ ุตุฑูŠุญ "search: ..." โ†’ Brave Search API ู…ุจุงุดุฑุฉ โ”€โ”€
1279
+ m_search = _SEARCH_CMD_RE.match(cmd)
1280
+ if m_search and "curl" not in cmd and "http" not in cmd:
1281
+ query = m_search.group(1).strip()
1282
+ if BRAVE_API_KEY:
1283
+ res = await brave_search(query)
1284
+ if res["returncode"] == 0 and not _result_empty(res["stdout"]):
1285
+ return res
1286
+ # ูุดู„ Brave (ู…ูุชุงุญ ุฎุงุทุฆ/ุญุตุฉ ู…ู†ุชู‡ูŠุฉ) โ†’ ุงุณุชู…ุฑ ุจุงู„ุฎุทุฉ ุงู„ุจุฏูŠู„ุฉ ุฃุฏู†ุงู‡
1287
+ # ู„ุง ูŠูˆุฌุฏ ู…ูุชุงุญ Brave ุฃูˆ ูุดู„ ุงู„ุทู„ุจ โ†’ ุงุณุชุฎุฏู… ู…ุตุงุฏุฑ API ุงู„ู…ุฌุงู†ูŠุฉ ุงู„ุฃุฎุฑู‰
1288
+ return await _fallback_search_sources(query)
1289
+
1290
+ res = await run_cmd(cmd, timeout)
1291
+ if res["returncode"] == 0 and not _result_empty(res["stdout"]):
1292
+ return res
1293
+ is_search = "curl" in cmd and any(x in cmd for x in ["search", "duckduck", "bing", "google", "wikipedia", "reddit"])
1294
+ if not is_search:
1295
+ return res
1296
+ m = re.search(r"[?&]q=([^&'\"\s]+)", cmd)
1297
+ query = urllib.parse.unquote(m.group(1).replace("+", " ")).strip() if m else ""
1298
+ if len(query) < 3:
1299
+ return res
1300
+ return await _fallback_search_sources(query, prior_result=res)
1301
+
1302
+
1303
+ async def _fallback_search_sources(query: str, prior_result: dict = None) -> dict:
1304
+ """ูŠุฌุฑุจ Brave ุฃูˆู„ุงู‹ (ู„ูˆ ู…ุชุงุญ)ุŒ ุซู… ู…ุตุงุฏุฑ API ุงู„ู…ุฌุงู†ูŠุฉ ุงู„ุฃุฎุฑู‰ (DuckDuckGo
1305
+ Instant Answer, Wikipedia, HackerNews, Reddit) โ€” ูƒู„ ู‡ุฐูŠ APIs ุฑุณู…ูŠุฉ
1306
+ ูˆู…ุตุฑูŽู‘ุญ ุจุงุณุชุฎุฏุงู…ู‡ุง ุขู„ูŠุงู‹ุŒ ู„ุง ุชุญุชุงุฌ ูุชุญ ู…ุชุตูุญ ูˆู„ุง ุชูˆุงุฌู‡ ูƒุงุจุชุดุง ุฅุทู„ุงู‚ุงู‹."""
1307
+ if BRAVE_API_KEY:
1308
+ res = await brave_search(query)
1309
+ if res["returncode"] == 0 and not _result_empty(res["stdout"]):
1310
+ return res
1311
+
1312
+ results = []
1313
+ for src in _search_sources(query):
1314
+ r2 = await run_cmd(src["cmd"], 20)
1315
+ if not _result_empty(r2["stdout"]):
1316
+ results.append(f"[{src['name']}]\n{r2['stdout']}")
1317
+ if len(results) >= 2:
1318
+ break
1319
+ if results:
1320
+ return {"stdout": "\n\n".join(results)[:15000], "stderr": "", "returncode": 0}
1321
+ return prior_result or {"stdout": "", "stderr": "ู„ู… ูŠูุนุซุฑ ุนู„ู‰ ู†ุชุงุฆุฌ ู…ู† ุฃูŠ ู…ุตุฏุฑ", "returncode": -1}
1322
+
1323
+
1324
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1325
+ # โ”€โ”€ FastAPI App โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1326
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1327
+
1328
+ app = FastAPI(title="Z-Computer-Mode v20 โ€” Headless-Native")
1329
+ app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True,
1330
+ allow_methods=["*"], allow_headers=["*"])
1331
+
1332
+
1333
+ @app.get("/", response_class=HTMLResponse)
1334
+ async def root():
1335
+ with _sessions_lock:
1336
+ n = len(_sessions)
1337
+ rows = "".join(
1338
+ f"<tr><td>{uid[:30]}</td><td>{s['port']}</td>"
1339
+ f"<td>{'๐ŸŸข ู…ุชุตู„' if s.get('active_ws') else 'โšซ ุบูŠุฑ ู…ุชุตู„'}</td></tr>"
1340
+ for uid, s in _sessions.items()
1341
+ )
1342
+ return f"""<!DOCTYPE html><html><head><meta charset="utf-8">
1343
+ <title>Z Computer Mode v20</title>
1344
+ <style>body{{background:#080808;color:#00d4aa;font-family:monospace;padding:40px}}
1345
+ h1{{color:#4a90d9}}.ok{{color:#00ff88}}.info{{color:#888;font-size:13px}}
1346
+ table{{border-collapse:collapse;width:100%}}td,th{{border:1px solid #333;padding:6px 10px;font-size:13px}}
1347
+ th{{background:#1a1a2e;color:#4a90d9}}</style></head><body>
1348
+ <h1>๐Ÿ–ฅ๏ธ THE Z AI โ€” Computer Mode Server v20 (Headless-Native)</h1>
1349
+ <p class="ok">โœ… ูŠุนู…ู„ โ€” ุจุฏูˆู† XvfbุŒ Chromium headless=new ูู‚ุท</p>
1350
+ <p>๐ŸŒ ุงู„ู…ุชุตูุญ ุงู„ู…ุนุชู…ุฏ: <b>{BROWSER_BIN}</b></p>
1351
+ <p>๐Ÿ” Brave Search API: <b>{'โœ… ู…ูุนู‘ู„' if BRAVE_API_KEY else 'โŒ ุบูŠุฑ ู…ูุนุฑูŽู‘ู (ุนูŠู‘ู† BRAVE_API_KEY)'}</b></p>
1352
+ <p>๐ŸฆŠ Camoufox (ู…ุถุงุฏ ู„ู„ูƒุดู): <b>{'โœ… ู…ุชุงุญ โ€” ุฅุฑุณุงู„ action: switch_engine ู„ู„ุชูุนูŠู„' if _CAMOUFOX_LIB_AVAILABLE and CAMOUFOX_ENABLED else 'โŒ ุบูŠุฑ ู…ุชุงุญ'}</b></p>
1353
+ <p>๐Ÿ‘ฅ ุงู„ุฌู„ุณุงุช ุงู„ู†ุดุทุฉ: <b>{n}</b> / {MAX_SESSIONS}</p>
1354
+ <hr style="border-color:#333"><h3>๐Ÿ‘ค ุงู„ุฌู„ุณุงุช</h3>
1355
+ <table><tr><th>User ID</th><th>CDP Port</th><th>ุงู„ุญุงู„ุฉ</th></tr>
1356
+ {rows or '<tr><td colspan="3" style="text-align:center;color:#666">ู„ุง ุชูˆุฌุฏ ุฌู„ุณุงุช</td></tr>'}
1357
+ </table>
1358
+ <hr style="border-color:#333">
1359
+ <p class="info">Endpoints: /health ยท /ws?user_id=email (WebSocket)</p>
1360
+ </body></html>"""
1361
+
1362
+
1363
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1364
+ # โ”€โ”€ ู…ุนุงู„ุฌ ุงู„ุฃูˆุงู…ุฑ โ€” ุจุฑูˆุชูˆูƒูˆู„ ู…ุทุงุจู‚ 100% ู„ู„ูˆุงุฌู‡ุฉ ุงู„ุฃู…ุงู…ูŠุฉ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1365
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1366
+ # ุงู„ุฃูˆุงู…ุฑ ุงู„ู…ุฏุนูˆู…ุฉ (ูƒู„ ู…ุง ุชุฑุณู„ู‡ index_plus_prompt_enhanced_v2-3.html ูุนู„ูŠุงู‹):
1367
+ # screenshot, terminal, mouse_move, mouse_click, mouse_drag, keyboard_type,
1368
+ # keyboard_hotkey, keyboard_press, scroll, clipboard_write, clipboard_read,
1369
+ # paste, open_app, open_tab, close_tab, browser_back, browser_forward,
1370
+ # browser_search, screen_info, reset_computer
1371
+
1372
+ # ุนุชุจุฉ ุฃุจุณุท ุจูƒุซูŠุฑ ู…ู† v13: ุจู…ุง ุฃู† ู„ุง ูŠูˆุฌุฏ X server ู…ู†ูุตู„ ูŠู…ูƒู† ุฃู† "ูŠุชุฌู…ุฏ" ุฏูˆู†
1373
+ # ุฃู† ูŠุชูˆู‚ู Chromium ู†ูุณู‡ุŒ ุฃูŠ ูุดู„ ุงู„ุชู‚ุงุท ุงู„ุขู† ูŠุนู†ูŠ ุนู…ู„ูŠุงู‹ ุฃู† Chromium ุชูˆู‚ู ุฃูˆ
1374
+ # ุงุชุตุงู„ CDP ุงู†ู‚ุทุน โ€” ูุดู„ุฉ ูˆุงุญุฏุฉ ูƒุงููŠุฉ ู„ู„ุชุฃูƒุฏ ูˆู…ุญุงูˆู„ุฉ ุฅุนุงุฏุฉ ุงู„ุงุชุตุงู„ ู…ุจุงุดุฑุฉ ู‚ุจู„
1375
+ # ุงู„ู„ุฌูˆุก ู„ุฅุนุงุฏุฉ ุชุดุบูŠู„ ุงู„ุนู…ู„ูŠุฉ ุจุงู„ูƒุงู…ู„.
1376
+ _RECONNECT_THRESHOLD = 1
1377
+ _FULL_RESET_THRESHOLD = 3
1378
+ _MAX_ROUNDS = 4
1379
+
1380
+
1381
+ async def handle_action(ws: WebSocket, msg: dict, sess: dict):
1382
+ action = msg.get("action", "")
1383
+ data = msg.get("data", {})
1384
+
1385
+ async def send(obj):
1386
+ try:
1387
+ await ws.send_text(json.dumps(obj, ensure_ascii=False))
1388
+ except Exception:
1389
+ pass
1390
+
1391
+ async def do_screenshot(label: str = "", auto: bool = False):
1392
+ """
1393
+ ูŠู„ุชู‚ุท ูˆูŠุฑุณู„ ู„ู‚ุทุฉ ุดุงุดุฉุŒ ู…ุน ุชุนุงููŠ ุชู„ู‚ุงุฆูŠ ุจุณูŠุท:
1394
+ ูุดู„ุฉ 1 โ†’ ุฃุนุฏ ุงู„ุงุชุตุงู„ ุจู€ CDP ูู‚ุท (Chromium ุบุงู„ุจุงู‹ ุญูŠุŒ ุงู„ุงุชุตุงู„ ูู‚ุท ุณู‚ุท)
1395
+ ูุดู„ุฉ 3 โ†’ ุฃุนุฏ ุชุดุบูŠู„ Chromium ุจุงู„ูƒุงู…ู„ (reset_session)
1396
+ ุจุนุฏ ุฐู„ูƒ โ†’ ุฃุฑุณู„ computer_reset ุตุฑุงุญุฉ ู„ู„ุนู…ูŠู„ ุจุฏู„ ุงู„ุตู…ุช
1397
+ """
1398
+ for _round in range(_MAX_ROUNDS):
1399
+ ok_browser = await ensure_browser_running(sess)
1400
+ if not ok_browser:
1401
+ sess["consecutive_failures"] += 1
1402
+ else:
1403
+ async with sess["shot_lock"]:
1404
+ result = await capture_full(sess, quality=75)
1405
+ if result.get("data") and not result.get("is_placeholder"):
1406
+ sess["consecutive_failures"] = 0
1407
+ fh = _frame_hash(result["data"])
1408
+ if not auto or fh != sess.get("last_frame_hash", ""):
1409
+ sess["last_frame_hash"] = fh
1410
+ await send({
1411
+ "type": "screenshot",
1412
+ "data": result["data"],
1413
+ "data_grid": result.get("data_grid", ""),
1414
+ "data_grid2": result.get("data_grid2", ""),
1415
+ "data_grid3": result.get("data_grid3", ""),
1416
+ "ts": int(time.time() * 1000),
1417
+ "auto": auto, "label": label,
1418
+ "screen_width": result["width"], "screen_height": result["height"],
1419
+ "mouse_x": result["mouse_x"], "mouse_y": result["mouse_y"],
1420
+ "has_grid": True,
1421
+ })
1422
+ return
1423
+ sess["consecutive_failures"] += 1
1424
+
1425
+ fails = sess["consecutive_failures"]
1426
+ if fails >= _FULL_RESET_THRESHOLD:
1427
+ await send({"type": "computer_reset",
1428
+ "msg": "๐Ÿ”„ ุฅุนุงุฏุฉ ุชุดุบูŠู„ ุชู„ู‚ุงุฆูŠุฉ ู„ู„ูƒู…ุจูŠูˆุชุฑ ุจุนุฏ ูุดู„ ู…ุชูƒุฑุฑ โ€” ู„ุญุธุงุช ูˆูŠุนูˆุฏ ุทุจูŠุนูŠุงู‹",
1429
+ "auto": True})
1430
+ await reset_session(sess["user_id"])
1431
+ await asyncio.sleep(1.0)
1432
+ continue
1433
+ elif fails >= _RECONNECT_THRESHOLD:
1434
+ # ุฃุนุฏ ุงู„ุงุชุตุงู„ ุจู€ CDP ูู‚ุท (ุฃุฎู ุจูƒุซูŠุฑ ู…ู† ุฅุนุงุฏุฉ ุชุดุบูŠู„ Chromium ุจุงู„ูƒุงู…ู„)
1435
+ sess["cdp"] = None
1436
+ await asyncio.sleep(0.3)
1437
+ continue
1438
+ await asyncio.sleep(0.3)
1439
+
1440
+ # ุงุณุชู†ูุฏู†ุง ูƒู„ ุงู„ู…ุญุงูˆู„ุงุช โ€” ุฃุนู„ู… ุงู„ุนู…ูŠู„ ุตุฑุงุญุฉ ุจุฏู„ ุงู„ุตู…ุช ุงู„ุฃุจุฏูŠ
1441
+ await send({"type": "computer_reset",
1442
+ "msg": "โš ๏ธ ุงุณุชู…ุฑุช ู…ุดูƒู„ุฉ ุงู„ุงู„ุชู‚ุงุท โ€” ุงู„ุฑุฌุงุก ุทู„ุจ ู„ู‚ุทุฉ ุดุงุดุฉ ุฌุฏูŠุฏุฉ",
1443
+ "auto": True})
1444
+
1445
+ def bg_shot(label: str = "", delay: float = 0.5):
1446
+ async def _run():
1447
+ await asyncio.sleep(delay)
1448
+ await do_screenshot(label, auto=True)
1449
+ asyncio.create_task(_run())
1450
+
1451
+ # โ”€โ”€ reset_computer โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1452
+ if action == "reset_computer":
1453
+ await send({"type": "ack", "action": "reset_computer", "status": "resetting"})
1454
+ await reset_session(sess["user_id"])
1455
+ await asyncio.sleep(1.0)
1456
+ await do_screenshot("after reset")
1457
+ await send({"type": "computer_reset", "msg": "โœ… ุชู… ุฅุนุงุฏุฉ ุถุจุท ุงู„ูƒู…ุจูŠูˆุชุฑ โ€” ุงู„ุดุงุดุฉ ุฌุฏูŠุฏุฉ ุชู…ุงู…ุงู‹"})
1458
+ return
1459
+
1460
+ # โ”€โ”€ screenshot โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1461
+ if action == "screenshot":
1462
+ _task = asyncio.create_task(do_screenshot("explicit screenshot"))
1463
+ def _on_done(t: asyncio.Task):
1464
+ exc = t.exception() if not t.cancelled() else None
1465
+ if exc:
1466
+ print(f"[screenshot-task:{sess['user_id']}] โŒ {exc}")
1467
+ _task.add_done_callback(_on_done)
1468
+ return
1469
+
1470
+ # โ”€โ”€ terminal โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1471
+ if action == "terminal":
1472
+ cmd = data.get("cmd", "")
1473
+ if not cmd:
1474
+ await send({"type": "terminal_result", "stdout": "", "stderr": "no cmd", "returncode": -1})
1475
+ return
1476
+ res = await run_cmd_smart(cmd, int(data.get("timeout", 60)))
1477
+ await send({"type": "terminal_result", "cmd": cmd, "stdout": res["stdout"],
1478
+ "stderr": res.get("stderr", ""), "returncode": res["returncode"]})
1479
+ return
1480
+
1481
+ # โ”€โ”€ ูŠุญุชุงุฌ ุงู„ู…ุชุตูุญ ุดุบุงู„ุงู‹ุŸ ุชุฃูƒุฏ ุฃูˆู„ุงู‹ ู„ุจู‚ูŠุฉ ุงู„ุฃูˆุงู…ุฑ โ”€โ”€
1482
+ engine = sess.get("engine", "chromium")
1483
+ if engine == "chromium":
1484
+ await ensure_browser_running(sess)
1485
+ else:
1486
+ cam = await get_camoufox_session(sess["user_id"])
1487
+ if not cam:
1488
+ # ูุดู„ ุจุฏุก Camoufox (ู…ูƒุชุจุฉ ุบูŠุฑ ู…ุซุจูŽู‘ุชุฉ/ูุดู„ ุฅู‚ู„ุงุน) โ†’ ุงุฑุฌุน ุชู„ู‚ุงุฆูŠุงู‹ ู„ู€ Chromium
1489
+ print(f"[engine] โš ๏ธ ูุดู„ Camoufox ู„ู€ '{sess['user_id']}' โ€” ุฑุฌูˆุน ุชู„ู‚ุงุฆูŠ ู„ู€ Chromium")
1490
+ sess["engine"] = "chromium"
1491
+ engine = "chromium"
1492
+ await ensure_browser_running(sess)
1493
+
1494
+ # โ”€โ”€ switch_engine โ€” ุชุจุฏูŠู„ ู…ุญุฑูƒ ุงู„ู…ุชุตูุญ ู„ู„ู…ุณุชุฎุฏู… (chromium โ‡„ camoufox) โ”€โ”€
1495
+ if action == "switch_engine":
1496
+ target = data.get("engine", "chromium")
1497
+ if target not in ("chromium", "camoufox"):
1498
+ await send({"type": "error", "msg": f"Unknown engine: '{target}'"})
1499
+ return
1500
+ if target == "camoufox" and not _CAMOUFOX_LIB_AVAILABLE:
1501
+ await send({"type": "error", "msg": "Camoufox ุบูŠุฑ ู…ุซุจูŽู‘ุช ุนู„ู‰ ู‡ุฐุง ุงู„ุณูŠุฑูุฑ"})
1502
+ return
1503
+ sess["engine"] = target
1504
+ sess["last_frame_hash"] = ""
1505
+ await send({"type": "ack", "action": "switch_engine", "engine": target,
1506
+ "msg": f"โœ… ุชู… ุงู„ุชุจุฏูŠู„ ู„ู…ุญุฑูƒ '{target}'"
1507
+ + (" โ€” ู…ุชุตูุญ ู…ุถุงุฏ ู„ู„ูƒุดูุŒ ุฃุจุทุฃ ู‚ู„ูŠู„ุงู‹ ู„ูƒู† ูŠุชุฌู†ุจ ูƒุงุจุชุดุง ุงู„ู…ูˆุงู‚ุน ุงู„ู…ุญู…ูŠุฉ ุจุดุฏุฉ"
1508
+ if target == "camoufox" else " โ€” ุงู„ู…ุญุฑูƒ ุงู„ุงูุชุฑุงุถูŠ ุงู„ุณุฑูŠุน")})
1509
+ bg_shot(f"after switch to {target}", delay=0.8)
1510
+ return
1511
+
1512
+ if action == "mouse_move":
1513
+ x, y = int(data.get("x", 0)), int(data.get("y", 0))
1514
+ if engine == "camoufox":
1515
+ await cam.mouse_move(x, y)
1516
+ else:
1517
+ await cdp_mouse_move(sess, x, y)
1518
+ await send({"type": "ack", "action": "mouse_move", "x": x, "y": y})
1519
+
1520
+ elif action == "mouse_click":
1521
+ x, y = int(data.get("x", 0)), int(data.get("y", 0))
1522
+ btn = {"left": "left", "middle": "middle", "right": "right"}.get(data.get("button", "left"), "left")
1523
+ double = bool(data.get("double", False))
1524
+ if engine == "camoufox":
1525
+ await cam.mouse_click(x, y, btn, double)
1526
+ else:
1527
+ await cdp_mouse_click(sess, x, y, btn, double)
1528
+ await send({"type": "ack", "action": "mouse_click", "x": x, "y": y, "button": btn})
1529
+ bg_shot("after click", delay=0.5)
1530
+
1531
+ elif action == "mouse_drag":
1532
+ x1, y1 = int(data.get("x1", 0)), int(data.get("y1", 0))
1533
+ x2, y2 = int(data.get("x2", 0)), int(data.get("y2", 0))
1534
+ if engine == "camoufox":
1535
+ await cam.mouse_drag(x1, y1, x2, y2)
1536
+ else:
1537
+ await cdp_mouse_drag(sess, x1, y1, x2, y2)
1538
+ await send({"type": "ack", "action": "mouse_drag"})
1539
+ bg_shot("after drag", delay=0.4)
1540
+
1541
+ elif action == "keyboard_type":
1542
+ text = _safe_search(data.get("text", ""))
1543
+ if text:
1544
+ if engine == "camoufox":
1545
+ await cam.type_text(text)
1546
+ else:
1547
+ await cdp_type_text(sess, text)
1548
+ await send({"type": "ack", "action": "keyboard_type", "method": engine})
1549
+
1550
+ elif action == "keyboard_hotkey":
1551
+ keys = data.get("keys", [])
1552
+ if keys:
1553
+ if engine == "camoufox":
1554
+ await cam.hotkey(keys)
1555
+ else:
1556
+ await cdp_hotkey(sess, keys)
1557
+ await send({"type": "ack", "action": "keyboard_hotkey", "keys": keys})
1558
+
1559
+ elif action == "keyboard_press":
1560
+ key = data.get("key", "")
1561
+ if key:
1562
+ if engine == "camoufox":
1563
+ await cam.key_press(key)
1564
+ else:
1565
+ await cdp_key_press(sess, key)
1566
+ await send({"type": "ack", "action": "keyboard_press"})
1567
+
1568
+ elif action == "scroll":
1569
+ x, y = int(data.get("x", SCREEN_W // 2)), int(data.get("y", SCREEN_H // 2))
1570
+ clicks = max(-5, min(5, int(data.get("clicks", 3))))
1571
+ if engine == "camoufox":
1572
+ await cam.scroll(x, y, delta_y=-clicks * 100)
1573
+ else:
1574
+ await cdp_scroll(sess, x, y, delta_y=-clicks * 100)
1575
+ await send({"type": "ack", "action": "scroll", "clicks": clicks})
1576
+
1577
+ elif action == "clipboard_write":
1578
+ text = data.get("text", "")
1579
+ if engine != "camoufox":
1580
+ await cdp_clipboard_write(sess, text)
1581
+ # ููŠ CamoufoxุŒ ุงู„ู†ุณุฎ ุงู„ูุนู„ูŠ ูŠูุญุงูƒู‰ ุนุจุฑ paste ู…ุจุงุดุฑุฉ (ู„ุง ุญุงุฌุฉ ู„ุชุฎุฒูŠู† ู…ู†ูุตู„)
1582
+ await send({"type": "ack", "action": "clipboard_write", "length": len(text)})
1583
+
1584
+ elif action == "clipboard_read":
1585
+ text = await cdp_clipboard_read(sess) if engine != "camoufox" else ""
1586
+ await send({"type": "clipboard_content", "text": text})
1587
+
1588
+ elif action == "paste":
1589
+ text = data.get("text", "")
1590
+ if text:
1591
+ if engine == "camoufox":
1592
+ await cam.type_text(text)
1593
+ else:
1594
+ await cdp_clipboard_write(sess, text)
1595
+ await cdp_type_text(sess, text)
1596
+ await send({"type": "ack", "action": "paste"})
1597
+
1598
+ elif action == "open_app":
1599
+ # ููŠ ู‡ุฐู‡ ุงู„ุจู†ูŠุฉ Chromium/Camoufox ู‡ูˆ "ุงู„ุชุทุจูŠู‚" ุงู„ูˆุญูŠุฏุ› ุฃูŠ ุฃู…ุฑ ูŠุญูˆูŠ
1600
+ # firefox/chromium/chrome ูŠููู‡ู… ูƒุทู„ุจ ูุชุญ ุตูุญุฉ ูุงุฑุบุฉ ุฌุฏูŠุฏุฉ ููŠ ๏ฟฝ๏ฟฝูุณ ุงู„ู…ุชุตูุญ.
1601
+ cmd = _safe_search(data.get("cmd", ""))
1602
+ url_match = re.search(r"https?://\S+", cmd)
1603
+ target_url = url_match.group(0) if url_match else "about:blank"
1604
+ if engine == "camoufox":
1605
+ await cam.navigate(target_url)
1606
+ else:
1607
+ await cdp_navigate(sess, target_url)
1608
+ await send({"type": "ack", "action": "open_app", "cmd": cmd})
1609
+ bg_shot("after open_app", delay=1.0)
1610
+
1611
+ elif action == "open_tab":
1612
+ url = _safe_search(data.get("url", "") or "about:blank")
1613
+ if engine == "camoufox":
1614
+ await cam.navigate(url)
1615
+ else:
1616
+ await cdp_navigate(sess, url)
1617
+ await send({"type": "ack", "action": "open_tab", "url": url})
1618
+ bg_shot("after open_tab", delay=1.2)
1619
+
1620
+ elif action == "close_tab":
1621
+ if engine == "camoufox":
1622
+ await cam.navigate("about:blank")
1623
+ else:
1624
+ await cdp_navigate(sess, "about:blank")
1625
+ await send({"type": "ack", "action": "close_tab"})
1626
+ bg_shot("after close_tab", delay=0.4)
1627
+
1628
+ elif action == "browser_back":
1629
+ if engine == "camoufox":
1630
+ await cam.go_back()
1631
+ else:
1632
+ cdp = sess.get("cdp")
1633
+ if cdp and cdp.alive:
1634
+ hist = await cdp.send("Page.getNavigationHistory", timeout=4.0)
1635
+ if hist:
1636
+ entries = hist.get("result", {}).get("entries", [])
1637
+ idx = hist.get("result", {}).get("currentIndex", 0)
1638
+ if idx > 0:
1639
+ await cdp.send("Page.navigateToHistoryEntry", {"entryId": entries[idx - 1]["id"]}, timeout=5.0)
1640
+ await send({"type": "ack", "action": "browser_back"})
1641
+ bg_shot("after back", delay=0.6)
1642
+
1643
+ elif action == "browser_forward":
1644
+ if engine == "camoufox":
1645
+ await cam.go_forward()
1646
+ else:
1647
+ cdp = sess.get("cdp")
1648
+ if cdp and cdp.alive:
1649
+ hist = await cdp.send("Page.getNavigationHistory", timeout=4.0)
1650
+ if hist:
1651
+ entries = hist.get("result", {}).get("entries", [])
1652
+ idx = hist.get("result", {}).get("currentIndex", 0)
1653
+ if idx < len(entries) - 1:
1654
+ await cdp.send("Page.navigateToHistoryEntry", {"entryId": entries[idx + 1]["id"]}, timeout=5.0)
1655
+ await send({"type": "ack", "action": "browser_forward"})
1656
+ bg_shot("after forward", delay=0.6)
1657
+
1658
+ elif action == "browser_search":
1659
+ url = _safe_search(data.get("url", "") or data.get("query", ""))
1660
+ if not re.match(r"^https?://", url):
1661
+ url = "https://duckduckgo.com/?q=" + urllib.parse.quote_plus(url)
1662
+ if engine == "camoufox":
1663
+ await cam.navigate(url)
1664
+ else:
1665
+ await cdp_navigate(sess, url)
1666
+ await send({"type": "ack", "action": "browser_search"})
1667
+ bg_shot("after search", delay=1.0)
1668
+
1669
+ elif action == "screen_info":
1670
+ info = await cdp_get_screen_info(sess)
1671
+ await send({"type": "screen_info", "width": info["width"], "height": info["height"],
1672
+ "mouse_x": info["mouse_x"], "mouse_y": info["mouse_y"],
1673
+ "browser": BROWSER_BIN if engine == "chromium" else "camoufox (Firefox anti-detect)",
1674
+ "engine": engine})
1675
+
1676
+ else:
1677
+ await send({"type": "error", "msg": f"Unknown action: '{action}'"})
1678
+
1679
+
1680
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1681
+ # โ”€โ”€ WebSocket Endpoint โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1682
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1683
+
1684
+ @app.websocket("/ws")
1685
+ async def websocket_endpoint(ws: WebSocket, user_id: str = Query(default="anonymous")):
1686
+ await ws.accept()
1687
+ sess = await get_or_create_session(user_id, ws)
1688
+ await ensure_browser_running(sess)
1689
+
1690
+ async def _heartbeat():
1691
+ while True:
1692
+ await asyncio.sleep(20)
1693
+ try:
1694
+ await ws.send_text(json.dumps({"type": "ping", "ts": int(time.time() * 1000)}))
1695
+ except Exception:
1696
+ break
1697
+
1698
+ hb_task = asyncio.create_task(_heartbeat())
1699
+
1700
+ try:
1701
+ info = await cdp_get_screen_info(sess)
1702
+ await ws.send_text(json.dumps({
1703
+ "type": "connected",
1704
+ "screen_width": info["width"], "screen_height": info["height"],
1705
+ "browser": BROWSER_BIN, "display": f"headless:{sess['port']}",
1706
+ "user_id": user_id, "session_id": id(ws),
1707
+ "msg": f"Z Computer Mode v20 | User: {user_id} | Port: {sess['port']} | "
1708
+ f"Browser: {BROWSER_BIN} (headless=new) | Screen: {info['width']}x{info['height']}",
1709
+ }, ensure_ascii=False))
1710
+
1711
+ # ู„ู‚ุทุฉ ุดุงุดุฉ ุฃูˆู„ูŠุฉ
1712
+ result = await capture_full(sess, quality=72)
1713
+ if result.get("data"):
1714
+ await ws.send_text(json.dumps({
1715
+ "type": "screenshot", "data": result["data"],
1716
+ "data_grid": result.get("data_grid", ""), "data_grid2": result.get("data_grid2", ""),
1717
+ "data_grid3": result.get("data_grid3", ""), "ts": int(time.time() * 1000),
1718
+ "label": "Initial screen", "screen_width": result["width"], "screen_height": result["height"],
1719
+ "mouse_x": result["mouse_x"], "mouse_y": result["mouse_y"], "has_grid": True,
1720
+ }, ensure_ascii=False))
1721
+ sess["last_frame_hash"] = _frame_hash(result["data"])
1722
+ except Exception as e:
1723
+ print(f"[ws:{user_id}] ุฎุทุฃ ุนู†ุฏ ุงู„ุจุฏุก: {e}")
1724
+
1725
+ try:
1726
+ while True:
1727
+ raw = await ws.receive_text()
1728
+ try:
1729
+ msg = json.loads(raw)
1730
+ if msg.get("type") == "pong":
1731
+ continue
1732
+ await handle_action(ws, msg, sess)
1733
+ except json.JSONDecodeError:
1734
+ pass
1735
+ except WebSocketDisconnect:
1736
+ pass
1737
+ except Exception as e:
1738
+ print(f"[ws:{user_id}] ุฎุทุฃ: {e}")
1739
+ finally:
1740
+ hb_task.cancel()
1741
+ await destroy_session_ws(user_id, ws)
1742
+
1743
+
1744
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1745
+ # โ”€โ”€ REST Endpoints โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1746
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1747
+
1748
+ @app.get("/screenshot")
1749
+ async def rest_screenshot(user_id: str = "anonymous"):
1750
+ with _sessions_lock:
1751
+ sess = _sessions.get(user_id)
1752
+ if not sess:
1753
+ return JSONResponse({"error": "no session for this user_id"}, status_code=404)
1754
+ await ensure_browser_running(sess)
1755
+ result = await capture_full(sess, quality=75)
1756
+ return JSONResponse({
1757
+ "image": result["data"], "image_grid": result.get("data_grid", ""),
1758
+ "image_grid2": result.get("data_grid2", ""), "image_grid3": result.get("data_grid3", ""),
1759
+ "ts": int(time.time() * 1000), "screen_width": result["width"], "screen_height": result["height"],
1760
+ "mouse_x": result["mouse_x"], "mouse_y": result["mouse_y"], "has_grid": True,
1761
+ "user_id": user_id,
1762
+ })
1763
+
1764
+
1765
+ @app.post("/terminal")
1766
+ async def rest_terminal(body: dict):
1767
+ return JSONResponse(await run_cmd_smart(body.get("cmd", ""), body.get("timeout", 60)))
1768
+
1769
+
1770
+ @app.get("/health")
1771
+ async def health():
1772
+ with _sessions_lock:
1773
+ n = len(_sessions)
1774
+ users = [
1775
+ {"user_id": uid, "cdp_port": s["port"], "connected": bool(s.get("active_ws")),
1776
+ "browser_alive": bool(s.get("cdp") and s["cdp"].alive),
1777
+ "engine": s.get("engine", "chromium")}
1778
+ for uid, s in _sessions.items()
1779
+ ]
1780
+ return {"status": "ok", "version": "v20.1-headless-native+camoufox", "browser": BROWSER_BIN,
1781
+ "brave_search_enabled": bool(BRAVE_API_KEY),
1782
+ "camoufox_available": bool(_CAMOUFOX_LIB_AVAILABLE and CAMOUFOX_ENABLED),
1783
+ "active_sessions": n, "max_sessions": MAX_SESSIONS, "users": users}
1784
+
1785
+
1786
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1787
+ # โ”€โ”€ Background Cleanup โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1788
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1789
+
1790
+ async def _cleanup_idle_sessions():
1791
+ """ูŠูุฒูŠู„ ุฌู„ุณุงุช ุงู„ู…ุณุชุฎุฏู…ูŠู† ุบูŠุฑ ุงู„ู†ุดุทูŠู† (ุจุฏูˆู† ุงุชุตุงู„ WebSocket ู…ู†ุฐ ุฃูƒุซุฑ ู…ู†
1792
+ ุณุงุนุฉ) โ€” ูŠูˆู‚ู Chromium ุงู„ุฎุงุต ุจู‡ู… ูุนู„ูŠุงู‹ ู„ุชุญุฑูŠุฑ ุงู„ุฐุงูƒุฑุฉ."""
1793
+ while True:
1794
+ await asyncio.sleep(1800)
1795
+ now = time.time()
1796
+ with _sessions_lock:
1797
+ idle_uids = [uid for uid, s in _sessions.items()
1798
+ if not s.get("active_ws") and now - s.get("created", now) > 3600]
1799
+ for uid in idle_uids:
1800
+ print(f"[cleanup] ๐Ÿ—‘๏ธ ุฅุฒุงู„ุฉ ุฌู„ุณุฉ ุฎุงู…ู„ุฉ '{uid}'")
1801
+ await destroy_session_full(uid)
1802
+
1803
+
1804
+ @app.on_event("startup")
1805
+ async def startup():
1806
+ asyncio.create_task(_cleanup_idle_sessions())
1807
+ print("โœ… Z Computer Mode v20 ุฌุงู‡ุฒ โ€” Headless-Native (ุจุฏูˆู† Xvfb)")
1808
+ print(f" ุงู„ู…ุชุตูุญ ุงู„ู…ุนุชู…ุฏ: {BROWSER_BIN} (--headless=new)")
1809
+ print(f" ู…ุฑุดุญูˆ ุงู„ู…ุชุตูุญ ุงู„ู…ูุญูˆุตูˆู†: {', '.join(_BROWSER_CANDIDATES)}")
1810
+ print(f" ุฃู‚ุตู‰ ุฌู„ุณุงุช ู…ุชุฒุงู…ู†ุฉ: {MAX_SESSIONS}")
1811
+ print(f" ู†ุทุงู‚ ู…ู†ุงูุฐ CDP: {CDP_PORT_BASE}+")
1812
+ print(f" websockets lib: {'โœ…' if _WS_LIB_AVAILABLE else 'โŒ (pip install websockets)'}")
1813
+ if BRAVE_API_KEY:
1814
+ print(" ๐Ÿ” Brave Search API: โœ… ู…ูุนู‘ู„ โ€” ุงู„ุจุญุซ ุณูŠุชู… ุนุจุฑู‡ ุฃูˆู„ุงู‹ (ุจุฏูˆู† ูƒุงุจุชุดุง)")
1815
+ else:
1816
+ print(" ๐Ÿ” Brave Search API: โŒ ุบูŠุฑ ู…ูุนุฑูŽู‘ู โ€” ุนูŠู‘ู† BRAVE_API_KEY ู„ุชูุนูŠู„ู‡")
1817
+ print(" (ุจุฏูˆู†ู‡ุŒ ุงู„ุจุญุซ ุณูŠุนุชู…ุฏ ุนู„ู‰ DuckDuckGo/Wikipedia APIs ุงู„ู…ุฌุงู†ูŠุฉ ูƒุจุฏูŠู„)")
1818
+ if _CAMOUFOX_LIB_AVAILABLE and CAMOUFOX_ENABLED:
1819
+ print(" ๐ŸฆŠ Camoufox (ู…ุชุตูุญ ู…ุถุงุฏ ู„ู„ูƒุดู): โœ… ู…ุชุงุญ โ€” ุนุจุฑ action: switch_engine {engine: camoufox}")
1820
+ else:
1821
+ print(" ๐ŸฆŠ Camoufox: โŒ ุบูŠุฑ ู…ุชุงุญ โ€” pip install camoufox playwright && playwright install firefox")
1822
+ print(" Connect: wss://your-space.hf.space/ws?user_id=EMAIL")
1823
+
1824
+
1825
+ if __name__ == "__main__":
1826
+ port = int(os.environ.get("PORT", 7860))
1827
+ uvicorn.run("app:app", host="0.0.0.0", port=port, log_level="info")
1828
+
1829
+
1830
+
1831
+
1832
+
1833
+
1834
+