Repository navigation
Expand file tree
/
Copy pathengine.py
More file actions
1668 lines (1559 loc) · 77.4 KB
/
Copy pathengine.py
File metadata and controls
1668 lines (1559 loc) · 77.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Muse generation engine: drives muse.ai with a real web session to complete image/video generation.
NOTE: several DOM-matching regexes keep Chinese alternatives (e.g. 发送, 下载) because muse.ai may render a Chinese-locale UI. Do not remove them during translation cleanup.
Verified flow:
inject cookies -> open https://muse.ai/ -> locate textarea (placeholder message)
-> Input.insertText fill -> click "Send"
-> wait for a new attachment container [data-testid^=hatch-chat-attachment-presentation-]
-> fetch blob bytes from img/video inside that container -> save to disk
"""
from __future__ import annotations
import base64
import mimetypes
import urllib.request
import json
import logging
import os
import re
import shutil
import subprocess
import time
import uuid
from cdp import CDP, http_json
log = logging.getLogger("muse2api")
ATT_SEL = '[data-testid^="hatch-chat-attachment-presentation-"]'
# Core cookies that decide account life/death (missing or expired = session invalid)
ESSENTIAL_COOKIES = ("hatch_sess", "hatch_gw", "hatch_vml",
"hatch_native_auth_device")
# ---------------------------------------------------------------------------
# Stealth injection – two-layer approach:
# 1. stealth.min.js – puppeteer-extra-plugin-stealth bundle (MIT), covering
# 16 evasions: webdriver, chrome.runtime/app/csi/loadTimes, plugins,
# iframe.contentWindow, media.codecs, hardwareConcurrency, languages,
# permissions, webgl.vendor, window.outerdimensions, sourceurl, UA.
# Regenerate: cd tools && npx extract-stealth-evasions
# 2. Hardware override script – thin JS generated at startup from the real
# Chrome version + a hardware profile (WebGL renderer, concurrency, mem).
# Runs after layer 1 so it wins any conflicts.
# ---------------------------------------------------------------------------
def _load_stealth_bundle() -> str:
"""Load tools/stealth.min.js relative to this file; return empty str on miss."""
here = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(here, "tools", "stealth.min.js")
try:
with open(path, encoding="utf-8") as f:
return f.read()
except OSError:
log.warning("stealth.min.js not found at %s – running without puppeteer-extra stealth bundle", path)
return ""
# Loaded once at import time; empty string = file missing (non-fatal).
_STEALTH_BUNDLE = _load_stealth_bundle()
def _detect_chrome_version(chrome_exe: str) -> tuple[int, str]:
"""Return (major, full_version) for the Chrome binary at *chrome_exe*.
Resolution order (fast-to-slow, all Windows/POSIX safe):
1. Walk the parent directory for a NN.x.x.x sub-directory (instant, no spawn).
2. ``chrome --version`` subprocess (macOS/Linux only; skipped on Windows).
Falls back to (154, '154.0.8037.97') so the engine never hard-crashes.
"""
# --- method 1: version directory next to the exe (Windows & Linux) -----
try:
parent = os.path.dirname(os.path.abspath(chrome_exe))
for entry in os.listdir(parent):
m = re.match(r'^(\d+)\.(\d+\.\d+\.\d+)$', entry)
if m and os.path.isdir(os.path.join(parent, entry)):
return int(m.group(1)), entry # e.g. (154, '154.0.8037.97')
except Exception:
pass
# --- method 2: subprocess --version (macOS/Linux; ~1s, avoid on Windows) -
if os.name != "nt":
try:
out = subprocess.check_output(
[chrome_exe, "--version"], stderr=subprocess.DEVNULL, timeout=8
).decode().strip()
m = re.search(r"(\d+)\.(\d+\.\d+\.\d+)", out)
if m:
return int(m.group(1)), m.group(1) + "." + m.group(2)
except Exception:
pass
# --- fallback -----------------------------------------------------------
return 154, "154.0.8037.97"
# Hardware profile pool.
# Keyed by (major % len) so a given Chrome version always maps to the same
# profile — stable across requests, no randomness that detectors flag.
_HW_PROFILES = [
{ # 0 – Intel integrated (most common laptop GPU)
"vendor": "Google Inc. (Intel)",
"renderer": "ANGLE (Intel, Intel(R) Iris(R) Xe Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)",
"cores": 8, "mem": 8,
},
{ # 1 – NVIDIA mid-range desktop
"vendor": "Google Inc. (NVIDIA)",
"renderer": "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 Direct3D11 vs_5_0 ps_5_0, D3D11)",
"cores": 16, "mem": 16,
},
{ # 2 – AMD mid-range desktop
"vendor": "Google Inc. (AMD)",
"renderer": "ANGLE (AMD, AMD Radeon RX 6700 XT Direct3D11 vs_5_0 ps_5_0, D3D11)",
"cores": 12, "mem": 16,
},
{ # 3 – Intel UHD (desktop / workstation)
"vendor": "Google Inc. (Intel)",
"renderer": "ANGLE (Intel, Intel(R) UHD Graphics 770 Direct3D11 vs_5_0 ps_5_0, D3D11)",
"cores": 8, "mem": 8,
},
]
def _hw_override_js(hw: dict) -> str:
"""Return a small JS snippet that overrides WebGL vendor/renderer,
hardwareConcurrency, and deviceMemory with values from *hw*.
Runs AFTER stealth.min.js so it wins any conflicts."""
vendor = json.dumps(hw["vendor"])
renderer = json.dumps(hw["renderer"])
cores = hw["cores"]
mem = hw["mem"]
return f"""(() => {{
// Layer-2 hardware overrides (dynamic, matches real Chrome version profile)
const _orig = Function.prototype.toString;
const _nat = new WeakMap();
function _setNat(fn, name) {{
try {{ Object.defineProperty(fn, 'name', {{ value: name, configurable: true }}); }} catch(e) {{}}
_nat.set(fn, name); return fn;
}}
// WebGL vendor + renderer (overrides stealth.min.js defaults with profile-matched strings)
try {{
const _patch = (proto) => {{
if (!proto) return;
const _old = proto.getParameter;
proto.getParameter = _setNat(function(p) {{
if (p === 0x9245) return {vendor};
if (p === 0x9246) return {renderer};
return _old.apply(this, arguments);
}}, 'getParameter');
}};
_patch(WebGLRenderingContext.prototype);
if (typeof WebGL2RenderingContext !== 'undefined') _patch(WebGL2RenderingContext.prototype);
}} catch(e) {{}}
// hardwareConcurrency + deviceMemory
try {{
Object.defineProperty(navigator, 'hardwareConcurrency', {{
get: _setNat(() => {cores}, 'get hardwareConcurrency'), configurable: true
}});
}} catch(e) {{}}
try {{
Object.defineProperty(navigator, 'deviceMemory', {{
get: _setNat(() => {mem}, 'get deviceMemory'), configurable: true
}});
}} catch(e) {{}}
// Canvas noise – tiny deterministic per-session offset so every
// readback is unique but stable within a session (avoids blank-canvas detection)
try {{
const _noise = (Math.random() * 0.1) - 0.05;
const _origToBlob = HTMLCanvasElement.prototype.toBlob;
const _origToData = HTMLCanvasElement.prototype.toDataURL;
const _origGetImage = CanvasRenderingContext2D.prototype.getImageData;
HTMLCanvasElement.prototype.toDataURL = _setNat(function(...args) {{
const ctx = this.getContext('2d');
if (ctx) {{
const id = ctx.getImageData(0, 0, this.width || 1, this.height || 1);
id.data[0] = Math.max(0, id.data[0] + _noise * 255 | 0);
ctx.putImageData(id, 0, 0);
}}
return _origToData.apply(this, args);
}}, 'toDataURL');
HTMLCanvasElement.prototype.toBlob = _setNat(function(cb, ...args) {{
const ctx = this.getContext('2d');
if (ctx) {{
const id = ctx.getImageData(0, 0, this.width || 1, this.height || 1);
id.data[0] = Math.max(0, id.data[0] + _noise * 255 | 0);
ctx.putImageData(id, 0, 0);
}}
return _origToBlob.call(this, cb, ...args);
}}, 'toBlob');
CanvasRenderingContext2D.prototype.getImageData = _setNat(function(...args) {{
const id = _origGetImage.apply(this, args);
id.data[0] = Math.max(0, id.data[0] + _noise * 255 | 0);
return id;
}}, 'getImageData');
}} catch(e) {{}}
// AudioContext hash noise – shifts the oscillator output by a tiny epsilon
try {{
const _origGetChan = AudioBuffer.prototype.getChannelData;
AudioBuffer.prototype.getChannelData = _setNat(function(ch) {{
const arr = _origGetChan.call(this, ch);
if (arr.length > 0) arr[0] += _noise * 1e-7;
return arr;
}}, 'getChannelData');
}} catch(e) {{}}
// Timezone consistency – lock Intl.DateTimeFormat to a real US/EU timezone
// so it matches the Windows locale rather than exposing a headless server TZ
try {{
const _tz = Intl.DateTimeFormat().resolvedOptions().timeZone || 'America/New_York';
const _origDTF = Intl.DateTimeFormat;
Intl.DateTimeFormat = _setNat(function(locales, opts) {{
opts = Object.assign({{ timeZone: _tz }}, opts || {{}});
return new _origDTF(locales, opts);
}}, 'DateTimeFormat');
Object.defineProperty(Intl.DateTimeFormat, 'prototype', {{
value: _origDTF.prototype, configurable: true
}});
}} catch(e) {{}}
// navigator.connection – RTT and type consistent with a cable/WiFi desktop
try {{
if (navigator.connection) {{
Object.defineProperties(navigator.connection, {{
rtt: {{ get: _setNat(() => 50, 'get rtt'), configurable: true }},
downlink: {{ get: _setNat(() => 10, 'get downlink'), configurable: true }},
effectiveType: {{ get: _setNat(() => '4g', 'get effectiveType'), configurable: true }},
saveData: {{ get: _setNat(() => false, 'get saveData'), configurable: true }},
}});
}}
}} catch(e) {{}}
}})();"""
def _build_stealth_profile(chrome_exe: str) -> dict:
"""Build a complete stealth profile dict for the given Chrome binary.
Returns a dict with keys:
user_agent – UA string for Emulation.setUserAgentOverride
ua_metadata – userAgentMetadata dict for same CDP call
bundle_js – puppeteer-extra stealth bundle (layer 1, 16 evasions)
hw_js – hardware/canvas/audio/TZ override script (layer 2)
"""
major, full = _detect_chrome_version(chrome_exe)
hw = _HW_PROFILES[major % len(_HW_PROFILES)]
log.info("Stealth profile: Chrome %s (%s), GPU=%s", major, full, hw["vendor"])
user_agent = (
f"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
f"AppleWebKit/537.36 (KHTML, like Gecko) "
f"Chrome/{major}.0.0.0 Safari/537.36"
)
ua_metadata = {
"brands": [
{"brand": "Google Chrome", "version": str(major)},
{"brand": "Chromium", "version": str(major)},
{"brand": "Not=A?Brand", "version": "24"},
],
"fullVersionList": [
{"brand": "Google Chrome", "version": full},
{"brand": "Chromium", "version": full},
{"brand": "Not=A?Brand", "version": "24.0.0.0"},
],
"fullVersion": full,
"platform": "Windows",
"platformVersion": "10.0.0",
"architecture": "x86",
"model": "",
"mobile": False,
"bitness": "64",
"wow64": False,
}
return {
"user_agent": user_agent,
"ua_metadata": ua_metadata,
"bundle_js": _STEALTH_BUNDLE,
"hw_js": _hw_override_js(hw),
}
class MuseAuthError(RuntimeError):
pass
class MuseGenerationError(RuntimeError):
pass
def _is_elevated() -> bool:
"""True when running with Administrator rights (Windows) or as root (POSIX).
Chrome refuses to stay attached to an elevated launcher: it exits and
re-spawns de-elevated, leaving our process handle dead and the CDP port
closed -- every launch then times out with no useful error."""
if os.name == "nt":
try:
import ctypes
return bool(ctypes.windll.shell32.IsUserAnAdmin())
except Exception: # noqa: BLE001
return False
try:
return os.geteuid() == 0
except AttributeError:
return False
class MuseEngine:
def __init__(self, cfg):
self.cfg = cfg
self.proc: subprocess.Popen | None = None
self.browser: CDP | None = None
self.page: CDP | None = None
self.current_acc_id: str | None = None
self._last_http_renew: dict[str, float] = {}
self._log = None
self.last_used: float = 0.0 # last time the browser served a generation (for idle shutdown)
self.idle_stopped_at: float = 0.0 # when idle shutdown last fired (so warmup doesn't undo it)
self._spawned: bool = False # True when WE launched the browser (vs reusing a foreign CDP session)
os.makedirs(cfg.profile_dir, exist_ok=True)
# ---------------- Browser lifecycle ----------------
def _debug_url(self):
return f"http://127.0.0.1:{self.cfg.cdp_port}/json/version"
def start(self):
# Every generation path calls start() (always under the caller's lock),
# so this timestamp doubles as the idle-shutdown clock.
self.last_used = time.time()
if self.proc and self.proc.poll() is None and self.browser:
return
# Running elevated breaks Chrome badly: the elevated launcher exits and
# re-spawns the real browser de-elevated ("--do-not-de-elevate"), so our
# process handle points at a dead process and the CDP port never comes
# up from our side. Warn loudly instead of failing cryptically later.
if _is_elevated():
log.warning("Process is running as Administrator: Chrome will refuse to stay attached "
"(it re-spawns de-elevated and the debug port never opens). "
"Restart this service from a NON-elevated terminal / do NOT use 'Run as administrator'.")
env = dict(os.environ)
env.setdefault("HOME", self.cfg.home_dir)
env["PATH"] = (self.cfg.extra_path + os.pathsep + env.get("PATH", "")) if self.cfg.extra_path else env.get("PATH", "")
# NOTE: the browser is intentionally kept warm (see _keepalive_loop in app.py)
# for ~2s first-byte latency, so it always costs ~200-400MB RSS while running.
# These flags trim the fat: no extensions/components/audio subsystems.
args = [
self.cfg.chromium,
"--headless=new", "--no-sandbox", "--disable-gpu",
"--disable-dev-shm-usage", "--disable-background-networking",
"--disable-extensions", "--disable-component-update", "--mute-audio",
"--no-first-run", "--no-default-browser-check",
"--autoplay-policy=no-user-gesture-required",
"--window-size=1440,2400",
f"--remote-debugging-port={self.cfg.cdp_port}",
"--remote-allow-origins=*",
f"--user-data-dir={self.cfg.profile_dir}",
# ---- RAM / process count reduction ----
"--disable-background-timer-throttling",
"--disable-backgrounding-occluded-windows",
"--disable-breakpad", # no crashpad handler process
"--disable-client-side-phishing-detection",
"--disable-hang-monitor",
"--disable-ipc-flooding-protection",
"--disable-prompt-on-repost",
"--disable-renderer-backgrounding",
"--disable-sync", # no profile-sync network traffic
"--disable-translate", # no translation service
"--metrics-recording-only", # no UMA upload
"--no-pings", # no hyperlink ping requests
"--password-store=basic", # skip OS keychain integration
"--use-mock-keychain",
"about:blank",
]
# Try to reuse an existing healthy CDP
if not self.proc:
try:
v = http_json(self._debug_url(), timeout=1)
if v and "webSocketDebuggerUrl" in v:
self.browser = CDP(v["webSocketDebuggerUrl"], timeout=180)
self._spawned = False
return
except Exception:
pass
# Clean up leftover locks
for lock_name in ("SingletonLock", "SingletonSocket", "SingletonCookie"):
lp = os.path.join(self.cfg.profile_dir, lock_name)
if os.path.exists(lp) or os.path.islink(lp):
try:
os.unlink(lp)
except Exception:
pass
os.makedirs(self.cfg.data_dir, exist_ok=True)
if self._log is not None: # retry after a failed start: don't leak the old handle
try:
self._log.close()
except Exception: # noqa: BLE001
pass
self._log = open(os.path.join(self.cfg.data_dir, "chromium.log"), "ab", buffering=0)
cwd_dir = self.cfg.home_dir if (self.cfg.home_dir and os.path.isdir(self.cfg.home_dir)) else None
# Windows: hide the browser's console window; POSIX: keep defaults.
popen_kwargs: dict = {}
if os.name == "nt":
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
if creationflags:
popen_kwargs["creationflags"] = creationflags
self.proc = subprocess.Popen(args, stdout=self._log, stderr=subprocess.STDOUT,
env=env, cwd=cwd_dir, **popen_kwargs)
last = None
for _ in range(90):
try:
v = http_json(self._debug_url(), timeout=2)
self.browser = CDP(v["webSocketDebuggerUrl"], timeout=180)
self._spawned = True
return
except Exception as exc: # noqa: BLE001
last = exc
time.sleep(1)
raise MuseGenerationError(f"Chromium failed to start: {last}")
def _kill_profile_tree(self):
"""Windows: kill our headless browser tree.
Chrome's launcher exits while the real browser lives on as a child, so
our Popen handle is useless. Children do NOT carry our profile path in
their command line, so: find the real main process (our profile path in
its cmdline, no --type=... child marker) and taskkill /T it, which takes
the whole tree down. The dedicated user-data-dir means we can never hit
the user's own Chrome."""
# Chrome keeps our path separators verbatim, so match both slash styles.
prof = self.cfg.profile_dir.replace("'", "''")
prof_bs = prof.replace("/", "\\")
ps = (
"$hit = @(Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\" "
"| Where-Object { ($_.CommandLine -like "
f"'*{prof}*' -or $_.CommandLine -like '*{prof_bs}*') "
"-and $_.CommandLine -notlike '*--type=*' }); "
"$hit | ForEach-Object { taskkill /F /T /PID $_.ProcessId }"
)
try:
subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", ps],
capture_output=True, timeout=30)
except Exception: # noqa: BLE001
pass
def stop(self):
for c in (self.page, self.browser):
if c:
c.close()
self.page = self.browser = None
if self.proc and (self._spawned or self.proc.poll() is None):
if os.name == "nt" and self._spawned:
# Chrome's launcher exits while the real browser (child) lives on,
# so our Popen handle points at a dead process. taskkill /T on it
# would miss the tree. Instead kill every chrome.exe whose command
# line references our dedicated profile dir -- that uniquely
# identifies our browser and never touches the user's own Chrome.
self._kill_profile_tree()
try:
self.proc.wait(timeout=10)
except Exception: # noqa: BLE001
pass
elif self.proc.poll() is None:
self.proc.terminate()
try:
self.proc.wait(timeout=10)
except Exception: # noqa: BLE001
self.proc.kill()
self.proc = None
self._spawned = False
# Release the log handle: on Windows an open file cannot be deleted,
# which breaks temp-profile cleanup in tests and manual profile wipes.
if self._log is not None:
try:
self._log.close()
except Exception: # noqa: BLE001
pass
self._log = None
def stop_if_idle(self, idle_min: int) -> bool:
"""Stop the browser if it served nothing for idle_min minutes. Returns True when stopped.
Callers MUST hold the generation lock (or otherwise guarantee no request
is in flight): stopping mid-generation would kill the active page.
A later start() transparently relaunches. last_used == 0 means the
browser never ran here, so there is nothing to stop."""
if not idle_min or idle_min <= 0 or not self.last_used:
return False
# Only our own child can be killed; a reused foreign CDP session is left alone.
if not self._spawned or self.proc is None:
return False
if time.time() - self.last_used < idle_min * 60:
return False
self.stop()
self.idle_stopped_at = time.time()
log.info("Browser idle for %dm, stopped to free RAM; next request will relaunch it", idle_min)
return True
# ---------------- Pages ----------------
def _open_page(self):
import requests
try:
pages = requests.get(f"http://127.0.0.1:{self.cfg.cdp_port}/json/list", timeout=3).json()
for p in pages:
if p.get("type") == "page":
pid = p.get("id")
if pid:
requests.get(f"http://127.0.0.1:{self.cfg.cdp_port}/json/close/{pid}", timeout=2)
except Exception:
pass
tgt = requests.put(
f"http://127.0.0.1:{self.cfg.cdp_port}/json/new?about:blank",
timeout=10).json()
page = CDP(tgt["webSocketDebuggerUrl"], timeout=180)
page.send("Network.enable")
page.send("Page.enable")
page.send("Runtime.enable")
page.send("Browser.setDownloadBehavior",
{"behavior": "allow", "downloadPath": self.cfg.download_dir})
try:
_sp = _build_stealth_profile(self.cfg.chromium)
page.send("Emulation.setUserAgentOverride", {
"userAgent": _sp["user_agent"],
"platform": "Win32",
"userAgentMetadata": _sp["ua_metadata"],
})
# Layer 1: puppeteer-extra stealth bundle (16 evasions)
if _sp["bundle_js"]:
page.send("Page.addScriptToEvaluateOnNewDocument", {"source": _sp["bundle_js"]})
# Layer 2: hardware / canvas / audio / TZ overrides matching real Chrome version
page.send("Page.addScriptToEvaluateOnNewDocument", {"source": _sp["hw_js"]})
except Exception:
pass
return page
@staticmethod
def renew_session_http(cookies: dict, expires: dict | None = None,
wake_vm: bool = True) -> dict:
"""Renew hatch_vml (+48h) / hatch_sess (+30d) / hatch_gw (+1y) via muse.ai/api/session,
and wake the cloud workspace VM via /api/hatch/vm/wake when needed."""
import requests
cur_cookies = dict(cookies or {})
cur_exp = dict(expires or {})
headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36",
"Origin": "https://muse.ai",
"Referer": "https://muse.ai/thread/new",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Dest": "empty",
"Cookie": "; ".join(f"{k}={v}" for k, v in cur_cookies.items() if v),
}
try:
r = requests.get("https://muse.ai/api/session", headers=headers,
timeout=12, allow_redirects=False)
except requests.RequestException as exc:
# Do not echo request content: the exception may carry a credentialed proxy URL.
raise MuseGenerationError(
f"/api/session network request failed ({type(exc).__name__}); check server network/proxy and retry") from None
if r.status_code == 401:
raise MuseAuthError("Session auth failed (/api/session HTTP 401); confirm login on the official site, then re-import cookies")
if r.status_code != 200:
hint = ("Access denied; check server egress/region/access restrictions; this alone does not prove cookies are invalid"
if r.status_code == 403 else "Upstream request failed; retry later and check server network")
raise MuseGenerationError(f"/api/session HTTP {r.status_code}: {hint}")
try:
sj = r.json()
except ValueError:
raise MuseGenerationError("/api/session HTTP 200 returned non-JSON; session state unconfirmed") from None
if not isinstance(sj, dict) or sj.get("status") != "assigned":
raise MuseGenerationError("/api/session HTTP 200 did not return an assigned session; check account/workspace state on the official site")
for c in r.cookies:
if c.value:
cur_cookies[c.name] = c.value
if c.expires:
cur_exp[c.name] = int(float(c.expires))
vm_id = sj.get("vm_id")
vm_state = sj.get("vm_state")
wake_ok = False
if wake_vm and vm_id and vm_state != "DISABLED":
try:
headers["Cookie"] = "; ".join(f"{k}={v}" for k, v in cur_cookies.items() if v)
rw = requests.post("https://muse.ai/api/hatch/vm/wake", headers=headers, json={
"vm_id": vm_id,
"retry_count": 0,
"connect_attempt_id": str(uuid.uuid4()),
}, timeout=8)
wake_ok = rw.status_code == 200
except Exception:
pass
return {
"ok": sj.get("status") == "assigned",
"status": sj.get("status"),
"vm_id": vm_id,
"vm_state": vm_state,
"wake_ok": wake_ok,
"cookies": cur_cookies,
"cookies_exp": cur_exp,
}
def _apply_cookies(self, page: CDP, cookies: dict, expires: dict | None = None):
"""Inject cookies. Fully clears old-account cookies for isolation, and never passes past-dated expires that would make Chromium drop hatch_vml."""
try:
page.send("Network.clearBrowserCookies")
except Exception:
pass
now = time.time()
for name, value in cookies.items():
if not value:
continue
exp = (expires or {}).get(name)
try:
exp_val = float(exp) if exp and float(exp) > now + 3600 else (now + 7 * 86400)
except (TypeError, ValueError):
exp_val = now + 7 * 86400
for dom in (".muse.ai", "muse.ai"):
params = {
"name": name,
"value": value,
"domain": dom,
"path": "/",
"secure": True,
"expires": exp_val,
}
try:
page.send("Network.setCookie", params)
except Exception: # noqa: BLE001
pass
def read_cookies(self) -> dict[str, dict]:
"""Read cookies back from the current page (**including httpOnly**, which page JS cannot do).
Returns {name: {"value":..., "expires": unix seconds or -1}}.
Purpose: muse.ai renews some cookies on visits; reading them back into the pool keeps accounts fresh
so accounts expire less easily.
"""
if not self.page:
return {}
try:
msg = self.page.send("Network.getCookies",
{"urls": [self.cfg.site_url]}, timeout=20)
except Exception: # noqa: BLE001
return {}
out: dict[str, dict] = {}
for c in (msg.get("result", {}).get("cookies") or []):
name = c.get("name")
if not name:
continue
try:
exp = int(float(c.get("expires", -1)))
except (TypeError, ValueError):
exp = -1
out[name] = {"value": c.get("value", ""), "expires": exp}
return out
def _wait_ws_ready(self, page: CDP, timeout: float = 15.0) -> bool:
"""Wait until the muse.ai page finishes React hydration and is no longer in the Connecting... state."""
deadline = time.time() + timeout
while time.time() < deadline:
try:
st = page.js("""(function(){
if (document.readyState !== 'complete') return 'loading';
if (!document.querySelector('textarea')) return 'no-ta';
var h = document.querySelector('[data-hatch-shell-hydration-state]');
if (h && h.getAttribute('data-hatch-shell-hydration-state') !== 'hydrated') return 'hydrating';
var statusEl = document.querySelector('[class*="text-body-status"]');
if (statusEl && statusEl.innerText.indexOf('Connecting...') !== -1) return 'connecting';
return 'ready';
})()""")
if st == "ready":
return True
except Exception:
pass
time.sleep(0.04)
return False
def reset_thread(self, for_chat: bool = False):
"""Close leftover dialogs and ensure a clean session with a ready WebSocket.
For plain-text chat (for_chat=True), reuse the existing warm connection for ~2s responses when the hot page has no attachments, no stuck state, and few bubbles."""
if not self.page:
return
try:
# 1. Close leftover dialogs
self.page.js("""(function(){
var d = document.querySelector('[role="dialog"]');
if (d) {
var b = d.querySelector('button[aria-label*="close" i], button');
if (b) b.click();
}
})()""")
# 2. Check current thread state
state = self.page.js("""(function(forChat){
var scope = document.querySelector('main,[class*="chat-scroll"],[class*="hatch-chat-scroll"]') || document.body;
var bubbleCount = scope ? scope.querySelectorAll('div[class*="hatch-chat-groupable-bubble"]').length : 0;
var hasAtts = document.querySelectorAll('[data-testid^="hatch-chat-attachment-presentation-"]').length > 0;
var hasStop = !!(document.querySelector('[data-testid="hatch-composer-stop-button"]')
|| document.querySelector('button[aria-label*="Stop" i]')
|| document.querySelector('button[aria-label*="停止"]'));
var statusEl = document.querySelector('[class*="text-body-status"]');
var isConnecting = statusEl && statusEl.innerText.indexOf('Connecting...') !== -1;
var bodyTxt = document.body ? (document.body.innerText || '') : '';
var hasStuck = bodyTxt.indexOf('Still sending') !== -1 || isConnecting;
// If clean with zero bubbles and ready textarea, no reset needed
if (bubbleCount === 0 && !hasAtts && !hasStop && !hasStuck && !!document.querySelector('textarea')) {
return 'clean';
}
// Fast path for new chats: click in-page compose button (<40ms, zero navigation latency)
var composeBtn = document.querySelector('[data-testid="hatch-chat-compose"]')
|| document.querySelector('[aria-label="New side chat"]')
|| document.querySelector('[aria-label="New chat"]');
if (composeBtn && !hasStuck && !hasAtts) {
composeBtn.click();
return 'clicked-compose';
}
return 'needs-nav';
})(%s)""" % ("true" if for_chat else "false"))
if state == "clicked-compose":
t_end = time.time() + 0.8
while time.time() < t_end:
time.sleep(0.03)
cnt = self.page.js("document.querySelectorAll('div[class*=\"hatch-chat-groupable-bubble\"]').length") or 0
if cnt == 0 and self.page.js("!!document.querySelector('textarea')"):
return
state = "needs-nav"
if state == "needs-nav":
self.page.send("Page.navigate", {"url": "https://muse.ai/thread/new"})
t_end = time.time() + 10.0
while time.time() < t_end:
time.sleep(0.04)
ready = self.page.js("""(function(){
return document.readyState === 'complete'
&& !!document.querySelector('textarea')
&& document.querySelectorAll('div[class*="hatch-chat-groupable-bubble"]').length === 0;
})()""")
if ready:
break
self._wait_ws_ready(self.page, timeout=12.0)
except Exception:
pass
def ensure_page(self, cookies: dict, expires: dict | None = None, account_id: str | None = None):
if self.page is not None and (account_id is None or getattr(self, "current_acc_id", None) == account_id):
try:
if self.page.js("!!document.querySelector('textarea')"):
return self.page
except Exception:
pass
if self.page:
try:
self.page.close()
except Exception:
pass
self.page = None
# Only call /api/session on the main path when the last HTTP renewal was over 10 minutes ago, to avoid blocking on every account switch
last_map = getattr(self, "_last_http_renew", None)
if last_map is None:
last_map = {}
self._last_http_renew = last_map
now_ts = time.time()
if not account_id or (now_ts - last_map.get(account_id, 0) > 600):
try:
renewed = self.renew_session_http(cookies, expires, wake_vm=True)
if renewed.get("cookies"):
cookies = renewed["cookies"]
if renewed.get("cookies_exp"):
expires = renewed["cookies_exp"]
if account_id:
last_map[account_id] = now_ts
except MuseAuthError:
raise
except Exception as e:
log.warning("Pre-renewal /api/session failed (continuing with browser load): %s", e)
page = self._open_page()
self._apply_cookies(page, cookies, expires)
page.send("Page.navigate", {"url": "https://muse.ai/thread/new"})
for _ in range(self.cfg.login_wait * 2):
time.sleep(0.15)
try:
# Check for textarea or dormant composer that activates upon click
has_ta = page.js("""(function(){
var ta = document.querySelector('textarea');
if (ta) return true;
var c = document.querySelector('[data-hatch-composer-chrome="true"]')
|| document.querySelector('[data-hatch-composer-root="true"]')
|| document.querySelector('[data-testid="hatch-composer-placeholder-overlay"]');
if (c) { c.click(); }
return !!document.querySelector('textarea');
})()""")
if has_ta:
self.page = page
self.current_acc_id = account_id
self._wait_ws_ready(page, timeout=15.0)
return page
except Exception:
pass
try:
if page.js("!!document.querySelector('textarea')"):
self.page = page
self.current_acc_id = account_id
self._wait_ws_ready(page, timeout=15.0)
return page
except Exception: # noqa: BLE001
pass
# Distinguish "session invalid (kicked back to the login page)" from "page load stuck" so the error hint matches the cause
try:
body = (page.js("document.body.innerText.slice(0,1200)") or "").lower()
except Exception: # noqa: BLE001
body = ""
page.close()
if re.search(r"log in|sign in|create an account|登录|use another account", body):
raise MuseAuthError("Session was signed out by muse.ai (possibly squeezed out by another login or flagged by risk control), "
"please re-import cookies with the browser extension")
raise MuseGenerationError("muse.ai page load timed out (chat input never appeared); check server network and retry; session not confirmed invalid")
def refresh(self, cookies: dict, expires: dict | None = None):
if self.page:
self.page.close()
self.page = None
return self.ensure_page(cookies, expires)
# ---------------- Quota (Settings panel) ----------------
# muse.ai quotas live under the bottom Settings menu -> Settings item -> settings panel's
# General -> Usage section, shaped like:
# Free plan
# Weekly limit resets on Sep 30
# 1% used
# Additional tokens / Never expires / 0% used (2B tokens left)
def _click_point(self, x: int, y: int):
for t in ("mousePressed", "mouseReleased"):
self.page.send("Input.dispatchMouseEvent",
{"type": t, "x": x, "y": y,
"button": "left", "clickCount": 1})
_CLICK_JS = (
"(function(){var sel=%s;"
"var b=[...document.querySelectorAll(sel)]"
".filter(function(x){return x.offsetParent!==null;})[0];"
"if(!b)return null;var r=b.getBoundingClientRect();"
"return JSON.stringify({x:Math.round(r.x+r.width/2),"
"y:Math.round(r.y+r.height/2)});})()")
def quota(self, cookies: dict, expires: dict | None = None) -> dict:
"""Open the Settings panel to read quota. Returns a structured dict; raises when unreadable."""
self.ensure_page(cookies, expires)
p = self.page
time.sleep(1)
# 1) Click the bottom-left Settings button (aria-label=Settings)
raw = p.js(self._CLICK_JS % json.dumps('button[aria-label="Settings"]'))
if not raw:
raise MuseGenerationError("Settings button not found")
pt = json.loads(raw)
self._click_point(pt["x"], pt["y"])
time.sleep(1.6)
# 2) Click the Settings item in the popup menu
raw = p.js(
"(function(){"
"var els=[...document.querySelectorAll('div,span,li,[role=menuitem],button')]"
".filter(function(e){return e.offsetParent!==null"
"&&(e.textContent||'').trim()==='Settings'"
"&&e.getAttribute('aria-label')!=='Settings'"
"&&e.children.length<=3;});"
"if(!els.length)return null;"
"var el=els[els.length-1];var r=el.getBoundingClientRect();"
"return JSON.stringify({x:Math.round(r.x+r.width/2),"
"y:Math.round(r.y+r.height/2)});})()")
if not raw:
raise MuseGenerationError("Settings menu did not pop up")
pt = json.loads(raw)
self._click_point(pt["x"], pt["y"])
time.sleep(3.0)
# 3) Read the settings panel text
txt = ""
for _ in range(6):
txt = p.js(
"(function(){var d=document.querySelector('[role=dialog],[aria-modal=true]');"
"return d?(d.innerText||''):'';})()") or ""
if "Usage" in txt or "used" in txt:
break
time.sleep(1.2)
# 4) Close the panel (Escape)
for t in ("keyDown", "keyUp"):
p.send("Input.dispatchKeyEvent",
{"type": t, "key": "Escape", "code": "Escape",
"windowsVirtualKeyCode": 27, "nativeVirtualKeyCode": 27})
time.sleep(0.5)
return self._parse_quota(txt)
@staticmethod
def _parse_quota(txt: str) -> dict:
"""Parse quota fields from the settings panel text."""
lines = [ln.strip() for ln in (txt or "").split("\n") if ln.strip()]
out: dict = {"raw": "\n".join(lines[:40])}
# Plan name: Free plan / xxx plan
for ln in lines:
m = re.match(r"^(.+?)\s*plan$", ln, re.I)
if m:
out["plan"] = ln
break
# Weekly limit resets on Sep 30
m = re.search(r"Weekly limit resets? on (.+)", txt or "")
if m:
out["weekly_reset"] = m.group(1).strip()
# Weekly usage: the first "N% used" (appearing after the plan line)
m = re.search(r"(\d+)%\s*used", txt or "")
if m:
out["weekly_used_pct"] = int(m.group(1))
# Extra tokens: "0% used (2B tokens left)"
m = re.search(r"(\d+)%\s*used\s*\(([^)]+)\)", txt or "")
if m:
out["extra_used_pct"] = int(m.group(1))
out["extra_left"] = m.group(2).strip()
if "Never expires" in (txt or ""):
out["extra_expires"] = "never"
out["found"] = bool(out.get("plan") or "weekly_used_pct" in out)
return out
# ---------------- Attachments (generation results) ----------------
_ATT_JS = (
"(function(){"
"var list = []; var seen = new Set();"
"function addEl(el, tid){"
" if(!el || seen.has(el)) return;"
" seen.add(el);"
" if(el.closest('form, [class*=chat-user-bubble], [class*=\"group/msg\"]')) return;"
" var v = el.querySelector('video') || (el.tagName === 'VIDEO' ? el : null);"
" var img = el.querySelector('img') || (el.tagName === 'IMG' ? el : null);"
" var isVid = (tid || '').includes('video') || !!v;"
" var primary = isVid ? (v || img) : (img || v);"
" var src = primary ? (primary.currentSrc || primary.src || '') : '';"
" if(src && !seen.has(src)){"
" seen.add(src);"
" list.push({"
" tid: tid || el.getAttribute('data-testid') || (isVid ? 'video' : 'image'),"
" hasVideo: !!v,"
" hasImg: !!img,"
" src: src,"
" vSrc: v ? (v.currentSrc || v.src || '') : '',"
" iSrc: img ? (img.currentSrc || img.src || '') : '',"
" w: primary ? (primary.videoWidth || primary.naturalWidth || 0) : 0,"
" h: primary ? (primary.videoHeight || primary.naturalHeight || 0) : 0"
" });"
" }"
"}"
"document.querySelectorAll('[data-testid^=\"hatch-chat-attachment-presentation-\"]').forEach(function(a){ addEl(a, a.getAttribute('data-testid')); });"
"document.querySelectorAll('div[class*=\"hatch-agent-bubble-bg\"] img, div[class*=\"hatch-agent-bubble-bg\"] video').forEach(function(m){"
" var s = m.currentSrc || m.src || '';"
" if(s && !s.includes('avatar') && !s.includes('emoji')) addEl(m.parentElement || m, 'agent-media');"
"});"
"return JSON.stringify(list);"
"})()"
)
def attachments(self) -> list[dict]:
try:
raw = self.page.js(self._ATT_JS)
return json.loads(raw) if raw else []
except Exception: # noqa: BLE001
return []
# ---------------- Sending ----------------
# Check "text really entered the input + Send button really rendered".
# Both are required: the Send button only renders when React state holds text --
# its presence proves React actually received the input (not just a DOM value change).
_SEND_STATE_JS = (
"(function(){var ta=document.querySelector('textarea');"
"var b=[...document.querySelectorAll('button,[role=button]')]"
".find(function(x){return /发送|send/i.test(x.getAttribute('aria-label')||'');});"
"return JSON.stringify({v:ta?ta.value:'',btn:b?(b.disabled?2:1):0});})()"
)
def _send(self, prompt: str):
# 1. Ensure the textarea is scrolled into the center of the viewport and truly focused
try:
self.page.js("""(function(){
var ta = document.querySelector('textarea');
if (!ta) {
var c = document.querySelector('[data-hatch-composer-chrome="true"]')
|| document.querySelector('[data-hatch-composer-root="true"]')
|| document.querySelector('[data-testid="hatch-composer-placeholder-overlay"]');
if (c) c.click();
ta = document.querySelector('textarea');
}
if (ta) {
ta.scrollIntoView({block: 'center', inline: 'nearest'});
ta.focus();