myagent-ai 1.30.0 → 1.30.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -33,6 +33,7 @@ import asyncio
33
33
  import json
34
34
  import os
35
35
  import shutil
36
+ import threading
36
37
  import time
37
38
  from pathlib import Path
38
39
  from typing import Any, Dict, List, Optional
@@ -89,7 +90,9 @@ class StealthBrowser:
89
90
  mgr = get_browser_profile_manager()
90
91
  profile = mgr.get_profile(self.profile_name)
91
92
  profile.ensure_dirs()
92
- self._user_data_dir = str(profile.user_data_dir)
93
+ # DrissionPage 的 set_user_data_path 会自动在路径下创建 Default 目录
94
+ # 我们直接用 profile_dir 作为 user-data-dir,避免嵌套
95
+ self._user_data_dir = str(profile.profile_dir)
93
96
  return self._user_data_dir
94
97
 
95
98
  async def start(self) -> SkillResult:
@@ -107,8 +110,9 @@ class StealthBrowser:
107
110
  co = ChromiumOptions()
108
111
 
109
112
  # 设置用户数据目录(Profile 持久化)
113
+ # 注意:只用 set_argument,不用 set_user_data_path,因为后者会
114
+ # 在路径下再套一层 Default/ 子目录,导致路径混乱
110
115
  if user_data:
111
- co.set_user_data_path(user_data)
112
116
  co.set_argument(f"--user-data-dir={user_data}")
113
117
 
114
118
  # 反检测核心参数
@@ -120,20 +124,16 @@ class StealthBrowser:
120
124
  co.set_argument("--disable-infobars")
121
125
  co.set_argument("--disable-extensions")
122
126
 
123
- # VNC/容器环境适配
124
- if os.environ.get("DISPLAY"):
125
- co.set_argument(f"--display={os.environ['DISPLAY']}")
127
+ # 容器环境(无论有无 DISPLAY 都加上,避免切换环境后出错)
128
+ co.set_argument("--no-sandbox")
129
+ co.set_argument("--disable-setuid-sandbox")
130
+ co.set_argument("--disable-dev-shm-usage")
131
+ co.set_argument("--disable-gpu")
126
132
 
127
133
  # 无头模式
128
134
  if self._headless:
129
135
  co.headless()
130
136
 
131
- # 容器环境
132
- if not os.environ.get("DISPLAY"):
133
- co.set_argument("--no-sandbox")
134
- co.set_argument("--disable-setuid-sandbox")
135
- co.set_argument("--disable-gpu")
136
-
137
137
  # 自动检测浏览器路径
138
138
  browser_path = self._detect_browser()
139
139
  if browser_path:
@@ -146,17 +146,27 @@ class StealthBrowser:
146
146
  self._browser = Chromium(co)
147
147
  self._page = self._browser.latest_tab
148
148
 
149
+ # 如果浏览器已崩溃或无法获取 tab
150
+ if not self._page:
151
+ return SkillResult(
152
+ success=False,
153
+ error="启动浏览器后无法获取页面标签(Chrome 可能未正确启动)",
154
+ )
155
+
149
156
  # 隐藏 webdriver 标志(额外注入)
150
157
  try:
151
- self._page.run_js("""
152
- Object.defineProperty(navigator, 'webdriver', {get: () => undefined});
153
- Object.defineProperty(navigator, 'plugins', {get: () => [1, 2, 3, 4, 5]});
154
- Object.defineProperty(navigator, 'languages', {get: () => ['zh-CN', 'zh', 'en']});
155
- window.chrome = {runtime: {}};
156
- """)
158
+ self._page.run_js(
159
+ "Object.defineProperty(navigator,'webdriver',{get:()=>undefined});"
160
+ "Object.defineProperty(navigator,'plugins',{get:()=>[1,2,3,4,5]});"
161
+ "Object.defineProperty(navigator,'languages',{get:()=>['zh-CN','zh','en']});"
162
+ "window.chrome={runtime:{}};"
163
+ )
157
164
  except Exception as e:
158
165
  logger.debug(f"反检测 JS 注入提示: {e}")
159
166
 
167
+ # 等待浏览器完全就绪
168
+ time.sleep(1)
169
+
160
170
  self._started = True
161
171
  logger.info(
162
172
  f"反检测浏览器已启动 (profile={self.profile_name}, "
@@ -177,17 +187,18 @@ class StealthBrowser:
177
187
 
178
188
  async def close(self) -> SkillResult:
179
189
  """关闭浏览器"""
190
+ self._started = False
180
191
  try:
181
192
  if self._browser:
182
193
  self._browser.quit()
183
194
  self._browser = None
184
195
  self._page = None
185
- self._started = False
186
196
  logger.info("反检测浏览器已关闭")
187
197
  return SkillResult(success=True, message="浏览器已关闭")
188
198
  except Exception as e:
189
199
  logger.error(f"关闭浏览器异常: {e}")
190
- self._started = False
200
+ self._browser = None
201
+ self._page = None
191
202
  return SkillResult(success=True, message="浏览器已关闭")
192
203
 
193
204
  async def navigate(self, url: str, wait: float = 2.0) -> SkillResult:
@@ -198,7 +209,7 @@ class StealthBrowser:
198
209
  try:
199
210
  self._page.get(url)
200
211
  if wait > 0:
201
- time.sleep(wait)
212
+ await asyncio.sleep(wait)
202
213
 
203
214
  title = self._page.title or ""
204
215
  current_url = self._page.url or ""
@@ -225,7 +236,7 @@ class StealthBrowser:
225
236
  )
226
237
  ele.click()
227
238
  if wait > 0:
228
- time.sleep(wait)
239
+ await asyncio.sleep(wait)
229
240
  return SkillResult(success=True, message=f"已点击: {selector}")
230
241
  except Exception as e:
231
242
  return SkillResult(success=False, error=f"点击失败: {e}")
@@ -248,7 +259,7 @@ class StealthBrowser:
248
259
  ele.clear()
249
260
  ele.input(value)
250
261
  if wait > 0:
251
- time.sleep(wait)
262
+ await asyncio.sleep(wait)
252
263
  return SkillResult(
253
264
  success=True,
254
265
  message=f"已填写 {selector}: {value[:50]}{'...' if len(value) > 50 else ''}",
@@ -303,7 +314,17 @@ class StealthBrowser:
303
314
  return SkillResult(success=False, error="浏览器未启动")
304
315
 
305
316
  try:
306
- text = self._page.text or ""
317
+ # Bug Fix: DrissionPage 没有 page.text 属性
318
+ # 需要通过 page.ele('tag:html').text 获取页面文本
319
+ try:
320
+ text = self._page.ele('tag:html').text or ""
321
+ except Exception:
322
+ # 降级:用 BS4 从 html 提取文本
323
+ try:
324
+ from bs4 import BeautifulSoup
325
+ text = BeautifulSoup(self._page.html or "", "html.parser").get_text(strip=True, separator="\n")
326
+ except Exception:
327
+ text = ""
307
328
  title = self._page.title or ""
308
329
  url = self._page.url or ""
309
330
 
@@ -375,16 +396,21 @@ class StealthBrowser:
375
396
  return SkillResult(success=False, error="浏览器未启动")
376
397
 
377
398
  try:
399
+ # DrissionPage cookies() 返回 CookiesList(list 子类),每项是 dict
378
400
  cookies = self._page.cookies()
379
401
  cookie_list = []
380
402
  if cookies:
381
403
  for c in cookies:
382
- cookie_list.append({
383
- "name": c.get("name", ""),
384
- "value": c.get("value", ""),
385
- "domain": c.get("domain", ""),
386
- "path": c.get("path", "/"),
387
- })
404
+ # CookiesList 中的每项是 dict,但 key 可能不全
405
+ if isinstance(c, dict):
406
+ cookie_list.append({
407
+ "name": c.get("name", ""),
408
+ "value": c.get("value", ""),
409
+ "domain": c.get("domain", ""),
410
+ "path": c.get("path", "/"),
411
+ })
412
+ else:
413
+ cookie_list.append(str(c))
388
414
 
389
415
  return SkillResult(
390
416
  success=True,
@@ -404,10 +430,15 @@ class StealthBrowser:
404
430
  cookie_list = []
405
431
  if cookies:
406
432
  for c in cookies:
407
- cookie_list.append(dict(c))
433
+ # CookiesList 中每项是 dict,确保可序列化
434
+ if isinstance(c, dict):
435
+ cookie_list.append(dict(c))
436
+ else:
437
+ cookie_list.append(str(c))
408
438
 
409
439
  from core.browser_profile import get_browser_profile_manager
410
440
  mgr = get_browser_profile_manager()
441
+ # 保存时用 profile_name 对应的原始 BrowserProfile(不加 user_data 子路径)
411
442
  profile = mgr.get_profile(self.profile_name)
412
443
  profile.save_cookies(cookie_list)
413
444
 
@@ -430,6 +461,8 @@ class StealthBrowser:
430
461
  cookies = profile.load_cookies()
431
462
 
432
463
  if cookies:
464
+ # Bug Fix: page.set.cookies 是 CookiesSetter 对象(可调用)
465
+ # 直接调用 page.set.cookies(cookies_list) 即可
433
466
  self._page.set.cookies(cookies)
434
467
  return SkillResult(
435
468
  success=True,
@@ -449,7 +482,13 @@ class StealthBrowser:
449
482
  return SkillResult(success=False, error="浏览器未启动")
450
483
 
451
484
  try:
452
- self._page.clear_cookies()
485
+ # Bug Fix: DrissionPage 没有 page.clear_cookies() 方法
486
+ # 正确方式是 page.set.cookies.clear() 或 page.clear_cache()
487
+ try:
488
+ self._page.set.cookies.clear()
489
+ except Exception:
490
+ self._page.clear_cache(cookies=True)
491
+
453
492
  from core.browser_profile import get_browser_profile_manager
454
493
  mgr = get_browser_profile_manager()
455
494
  profile = mgr.get_profile(self.profile_name)
@@ -479,13 +518,17 @@ class StealthBrowser:
479
518
  )
480
519
  logger.info(f"[{self.profile_name}] 等待用户手动操作: {reason}")
481
520
 
482
- # 简单的等待机制:轮询页面变化
521
+ # Bug Fix: 使用 asyncio.sleep 避免阻塞事件循环
483
522
  start = time.time()
484
523
  last_url = self._page.url if self._page else ""
524
+ poll_interval = 3
485
525
  while time.time() - start < timeout:
486
- time.sleep(3)
526
+ await asyncio.sleep(poll_interval)
487
527
  if self._page:
488
- current_url = self._page.url or ""
528
+ try:
529
+ current_url = self._page.url or ""
530
+ except Exception:
531
+ break # 浏览器已关闭
489
532
  # 如果 URL 发生变化,说明用户完成了操作
490
533
  if current_url != last_url and current_url:
491
534
  elapsed = int(time.time() - start)
@@ -506,11 +549,13 @@ class StealthBrowser:
506
549
  if not self._started or not self._page:
507
550
  return False
508
551
  try:
509
- # 检查页面是否仍然有效
552
+ # 检查页面是否仍然有效(try 访问 url,如果浏览器已崩溃会抛异常)
510
553
  _ = self._page.url
511
554
  return True
512
555
  except Exception:
513
- self._started = False
556
+ # 不要在这里重置 _started,由 close() 方法负责
557
+ # 避免在异步上下文中误判
558
+ logger.debug(f"页面检查失败 (profile={self.profile_name}),浏览器可能已关闭")
514
559
  return False
515
560
 
516
561
  @staticmethod
@@ -560,10 +605,10 @@ class StealthBrowser:
560
605
  # ── 全局浏览器实例管理 ──────────────────────────────────────
561
606
 
562
607
  _browsers: Dict[str, StealthBrowser] = {}
563
- _browser_lock = asyncio.Lock()
608
+ _browser_lock = threading.Lock()
564
609
 
565
610
 
566
- async def get_stealth_browser(
611
+ def get_stealth_browser(
567
612
  profile_name: str = "default",
568
613
  headless: bool = False,
569
614
  ) -> StealthBrowser:
@@ -571,8 +616,9 @@ async def get_stealth_browser(
571
616
  获取反检测浏览器实例(按 profile_name 复用)。
572
617
 
573
618
  同一 profile 名称返回相同实例,避免重复启动。
619
+ Bug Fix: 改用同步锁 + 同步返回,避免在非 async 上下文中死锁。
574
620
  """
575
- async with _browser_lock:
621
+ with _browser_lock:
576
622
  if profile_name in _browsers:
577
623
  browser = _browsers[profile_name]
578
624
  if browser._started and browser._ensure_page():
@@ -583,21 +629,37 @@ async def get_stealth_browser(
583
629
  return browser
584
630
 
585
631
 
586
- async def close_stealth_browser(profile_name: str = "") -> None:
587
- """关闭浏览器实例"""
588
- async with _browser_lock:
632
+ def close_stealth_browser(profile_name: str = "") -> None:
633
+ """关闭浏览器实例(同步版本)"""
634
+ with _browser_lock:
589
635
  if profile_name and profile_name in _browsers:
590
- await _browsers[profile_name].close()
636
+ browser = _browsers[profile_name]
637
+ # 同步调用内部关闭逻辑
638
+ browser._started = False
639
+ try:
640
+ if browser._browser:
641
+ browser._browser.quit()
642
+ except Exception:
643
+ pass
644
+ browser._browser = None
645
+ browser._page = None
591
646
  del _browsers[profile_name]
592
647
  elif not profile_name:
593
648
  for name, browser in _browsers.items():
594
649
  try:
595
- await browser.close()
650
+ browser._started = False
651
+ if browser._browser:
652
+ browser._browser.quit()
596
653
  except Exception:
597
654
  pass
598
655
  _browsers.clear()
599
656
 
600
657
 
658
+ async def close_stealth_browser_async(profile_name: str = "") -> None:
659
+ """关闭浏览器实例(异步版本,供 async 上下文调用)"""
660
+ close_stealth_browser(profile_name)
661
+
662
+
601
663
  # ── 技能类(供 SkillRegistry 自动发现)─────────────────────
602
664
 
603
665
 
@@ -783,7 +845,8 @@ class StealthBrowserCloseSkill(Skill):
783
845
  ]
784
846
 
785
847
  async def execute(self, profile: str = "", **kw) -> SkillResult:
786
- await close_stealth_browser(profile_name=profile)
848
+ # close_stealth_browser 现在是同步函数,直接调用
849
+ close_stealth_browser(profile_name=profile)
787
850
  return SkillResult(success=True, message="浏览器已关闭")
788
851
 
789
852
 
@@ -141,8 +141,14 @@ class BrowserProfile:
141
141
  self.profile_dir.mkdir(parents=True, exist_ok=True)
142
142
 
143
143
  def is_initialized(self) -> bool:
144
- """检查 Profile 是否已初始化(有 user_data 目录)"""
145
- return self.user_data_dir.is_dir()
144
+ """检查 Profile 是否已初始化(有 profile 目录且包含浏览器数据)"""
145
+ if not self.profile_dir.is_dir():
146
+ return False
147
+ # 检查目录下是否有实际内容(不空)
148
+ try:
149
+ return any(self.profile_dir.iterdir())
150
+ except OSError:
151
+ return False
146
152
 
147
153
  def get_size_mb(self) -> float:
148
154
  """获取 Profile 占用空间(MB)"""
package/main.py CHANGED
@@ -427,25 +427,28 @@ class MyAgentApp:
427
427
  self.skill_registry.register(skill_cls())
428
428
 
429
429
  # ── 反检测浏览器技能 (DrissionPage — v1.30.0) ──
430
- from aiskills.browser_stealth import (
431
- StealthBrowserStartSkill, StealthBrowserNavigateSkill,
432
- StealthBrowserClickSkill, StealthBrowserFillSkill,
433
- StealthBrowserScreenshotSkill, StealthBrowserEvalSkill,
434
- StealthBrowserGetContentSkill, StealthBrowserCookieSkill,
435
- StealthBrowserCloseSkill, StealthBrowserWaitManualSkill,
436
- StealthBrowserWaitSkill,
437
- BrowserProfileListSkill, BrowserProfileCreateSkill, BrowserProfileDeleteSkill,
438
- )
439
- for skill_cls in [
440
- StealthBrowserStartSkill, StealthBrowserNavigateSkill,
441
- StealthBrowserClickSkill, StealthBrowserFillSkill,
442
- StealthBrowserScreenshotSkill, StealthBrowserEvalSkill,
443
- StealthBrowserGetContentSkill, StealthBrowserCookieSkill,
444
- StealthBrowserCloseSkill, StealthBrowserWaitManualSkill,
445
- StealthBrowserWaitSkill,
446
- BrowserProfileListSkill, BrowserProfileCreateSkill, BrowserProfileDeleteSkill,
447
- ]:
448
- self.skill_registry.register(skill_cls())
430
+ try:
431
+ from aiskills.browser_stealth import (
432
+ StealthBrowserStartSkill, StealthBrowserNavigateSkill,
433
+ StealthBrowserClickSkill, StealthBrowserFillSkill,
434
+ StealthBrowserScreenshotSkill, StealthBrowserEvalSkill,
435
+ StealthBrowserGetContentSkill, StealthBrowserCookieSkill,
436
+ StealthBrowserCloseSkill, StealthBrowserWaitManualSkill,
437
+ StealthBrowserWaitSkill,
438
+ BrowserProfileListSkill, BrowserProfileCreateSkill, BrowserProfileDeleteSkill,
439
+ )
440
+ for skill_cls in [
441
+ StealthBrowserStartSkill, StealthBrowserNavigateSkill,
442
+ StealthBrowserClickSkill, StealthBrowserFillSkill,
443
+ StealthBrowserScreenshotSkill, StealthBrowserEvalSkill,
444
+ StealthBrowserGetContentSkill, StealthBrowserCookieSkill,
445
+ StealthBrowserCloseSkill, StealthBrowserWaitManualSkill,
446
+ StealthBrowserWaitSkill,
447
+ BrowserProfileListSkill, BrowserProfileCreateSkill, BrowserProfileDeleteSkill,
448
+ ]:
449
+ self.skill_registry.register(skill_cls())
450
+ except ImportError as e:
451
+ self.logger.warning(f"反检测浏览器技能注册跳过(DrissionPage 未安装): {e}")
449
452
 
450
453
  # ── [v1.22.0] 内置平台工具不再注册存根 ──
451
454
  # command, recall_memory, file_send, playaudio, playvideo, web_control
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "myagent-ai",
3
- "version": "1.30.0",
3
+ "version": "1.30.1",
4
4
  "description": "本地桌面端执行型AI助手 - Open Interpreter 风格 | Local Desktop Execution-Oriented AI Assistant",
5
5
  "main": "main.py",
6
6
  "bin": {
package/scripts/cli.py CHANGED
@@ -859,7 +859,8 @@ async def cmd_stealth_close(args):
859
859
  a = p.parse_args(args)
860
860
 
861
861
  from aiskills.browser_stealth import close_stealth_browser
862
- await close_stealth_browser(profile_name=a.profile)
862
+ # close_stealth_browser 现在是同步函数
863
+ close_stealth_browser(profile_name=a.profile)
863
864
  print("反检测浏览器已关闭")
864
865
 
865
866
 
package/worklog.md CHANGED
@@ -1,4 +1,29 @@
1
1
  ---
2
+ Task ID: [20260421-01]
3
+ Agent: Main Agent
4
+ Task: 反检测浏览器集成 - Phase 2 网站专用技能 (v1.30.0)
5
+
6
+ Work Log:
7
+ - 检查现有实现状态:browser_stealth.py + browser_profile.py + CLI + SKILL.md 已在之前的会话中完成
8
+ - 修复 main.py _register_builtin_skills():添加 13 个 stealth browser 技能类注册
9
+ - 创建 6 个网站专用 SKILL.md 操作指南:
10
+ * aiskills/site-gmail/SKILL.md — Gmail 收发邮件、搜索、附件
11
+ * aiskills/site-x-com/SKILL.md — X.com 发推、回复、搜索、点赞
12
+ * aiskills/site-weibo/SKILL.md — 微博发帖、转发、评论、搜索
13
+ * aiskills/site-wechat-mp/SKILL.md — 微信公众号扫码登录、图文发布
14
+ * aiskills/site-douyin/SKILL.md — 抖音浏览、搜索、发布视频、评论
15
+ * aiskills/site-mail139/SKILL.md — 139邮箱收发邮件、搜索
16
+ - 更新版本号 1.29.0 → 1.30.0
17
+ - Git commit + push + npm publish
18
+
19
+ Stage Summary:
20
+ - 修复: stealth browser 技能类注册到 SkillRegistry
21
+ - 新增: 6 个网站操作 SKILL.md 指南 (约 20KB 内容)
22
+ - 发布: myagent-ai@1.30.0 (npm + GitHub)
23
+ - 架构: LLM → command 工具 → stealth-* CLI → DrissionPage → 各网站
24
+
25
+ ---
26
+
2
27
  Task ID: [20260420-04]
3
28
  Agent: Main Agent
4
29
  Task: 发布 npm 包 myagent-ai v1.26.0