ErisPulse 2.1.14.dev2__py3-none-any.whl → 2.1.15.dev3__py3-none-any.whl

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.
ErisPulse/__main__.py CHANGED
@@ -95,7 +95,7 @@ class PackageManager:
95
95
  """
96
96
  REMOTE_SOURCES = [
97
97
  "https://erisdev.com/packages.json",
98
- "https://raw.githubusercontent.com/ErisPulse/ErisPulse-ModuleRepo/main/packages.json"
98
+ "https://raw.githubusercontent.com/ErisPulse/ErisPulse/main/packages.json"
99
99
  ]
100
100
 
101
101
  CACHE_EXPIRY = 3600 # 1小时缓存
@@ -256,13 +256,76 @@ class PackageManager:
256
256
  except Exception:
257
257
  return False
258
258
 
259
- def _run_pip_command(self, args: List[str], description: str) -> bool:
259
+ def _normalize_name(self, name: str) -> str:
260
260
  """
261
- 执行pip命令
261
+ 标准化包名,统一转为小写以实现大小写不敏感比较
262
+
263
+ :param name: 原始名称
264
+ :return: 标准化后的名称
265
+ """
266
+ return name.lower().strip()
267
+
268
+ async def _find_package_by_alias(self, alias: str) -> Optional[str]:
269
+ """
270
+ 通过别名查找实际包名(大小写不敏感)
271
+
272
+ :param alias: 包别名
273
+ :return: 实际包名,未找到返回None
274
+ """
275
+ normalized_alias = self._normalize_name(alias)
276
+ remote_packages = await self.get_remote_packages()
277
+
278
+ # 检查模块
279
+ for name, info in remote_packages["modules"].items():
280
+ if self._normalize_name(name) == normalized_alias:
281
+ return info["package"]
282
+
283
+ # 检查适配器
284
+ for name, info in remote_packages["adapters"].items():
285
+ if self._normalize_name(name) == normalized_alias:
286
+ return info["package"]
287
+
288
+ # 检查CLI扩展
289
+ for name, info in remote_packages.get("cli_extensions", {}).items():
290
+ if self._normalize_name(name) == normalized_alias:
291
+ return info["package"]
292
+
293
+ return None
294
+
295
+ def _find_installed_package_by_name(self, name: str) -> Optional[str]:
296
+ """
297
+ 在已安装包中查找实际包名(大小写不敏感)
298
+
299
+ :param name: 包名或别名
300
+ :return: 实际包名,未找到返回None
301
+ """
302
+ normalized_name = self._normalize_name(name)
303
+ installed = self.get_installed_packages()
304
+
305
+ # 在已安装的模块中查找
306
+ for module_info in installed["modules"].values():
307
+ if self._normalize_name(module_info["package"]) == normalized_name:
308
+ return module_info["package"]
309
+
310
+ # 在已安装的适配器中查找
311
+ for adapter_info in installed["adapters"].values():
312
+ if self._normalize_name(adapter_info["package"]) == normalized_name:
313
+ return adapter_info["package"]
314
+
315
+ # 在已安装的CLI扩展中查找
316
+ for cli_info in installed["cli_extensions"].values():
317
+ if self._normalize_name(cli_info["package"]) == normalized_name:
318
+ return cli_info["package"]
319
+
320
+ return None
321
+
322
+ def _run_pip_command_with_output(self, args: List[str], description: str) -> Tuple[bool, str, str]:
323
+ """
324
+ 执行pip命令并捕获输出
262
325
 
263
326
  :param args: pip命令参数列表
264
327
  :param description: 进度条描述
265
- :return: 命令是否成功执行
328
+ :return: (是否成功, 标准输出, 标准错误)
266
329
  """
267
330
  with Progress(
268
331
  TextColumn(f"[progress.description]{description}"),
@@ -279,58 +342,245 @@ class PackageManager:
279
342
  universal_newlines=True
280
343
  )
281
344
 
345
+ stdout_lines = []
346
+ stderr_lines = []
347
+
348
+ # 实时读取输出
282
349
  while True:
283
- output = process.stdout.readline()
284
- if output == '' and process.poll() is not None:
285
- break
286
- if output:
350
+ stdout_line = process.stdout.readline()
351
+ stderr_line = process.stderr.readline()
352
+
353
+ if stdout_line:
354
+ stdout_lines.append(stdout_line)
355
+ progress.update(task, advance=1)
356
+
357
+ if stderr_line:
358
+ stderr_lines.append(stderr_line)
287
359
  progress.update(task, advance=1)
288
360
 
289
- return process.returncode == 0
361
+ if stdout_line == '' and stderr_line == '' and process.poll() is not None:
362
+ break
363
+
364
+ stdout = ''.join(stdout_lines)
365
+ stderr = ''.join(stderr_lines)
366
+
367
+ return process.returncode == 0, stdout, stderr
290
368
  except subprocess.CalledProcessError as e:
291
369
  console.print(f"[error]命令执行失败: {e}[/]")
292
- return False
370
+ return False, "", str(e)
293
371
 
294
- def install_package(self, package_name: str, upgrade: bool = False) -> bool:
372
+
373
+ def _compare_versions(self, version1: str, version2: str) -> int:
295
374
  """
296
- 安装指定包
375
+ 比较两个版本号
297
376
 
298
- :param package_name: 要安装的包名
377
+ :param version1: 版本号1
378
+ :param version2: 版本号2
379
+ :return: 1 if version1 > version2, -1 if version1 < version2, 0 if equal
380
+ """
381
+ from packaging import version as comparison
382
+ try:
383
+ v1 = comparison.parse(version1)
384
+ v2 = comparison.parse(version2)
385
+ if v1 > v2:
386
+ return 1
387
+ elif v1 < v2:
388
+ return -1
389
+ else:
390
+ return 0
391
+ except comparison.InvalidVersion:
392
+ # 如果无法解析,使用字符串比较作为后备
393
+ if version1 > version2:
394
+ return 1
395
+ elif version1 < version2:
396
+ return -1
397
+ else:
398
+ return 0
399
+
400
+ def _check_sdk_compatibility(self, min_sdk_version: str) -> Tuple[bool, str]:
401
+ """
402
+ 检查SDK版本兼容性
403
+
404
+ :param min_sdk_version: 所需的最小SDK版本
405
+ :return: (是否兼容, 当前版本信息)
406
+ """
407
+ try:
408
+ from ErisPulse import __version__
409
+ current_version = __version__
410
+ except ImportError:
411
+ current_version = "unknown"
412
+
413
+ if current_version == "unknown":
414
+ return True, "无法确定当前SDK版本"
415
+
416
+ try:
417
+ compatibility = self._compare_versions(current_version, min_sdk_version)
418
+ if compatibility >= 0:
419
+ return True, f"当前SDK版本 {current_version} 满足最低要求 {min_sdk_version}"
420
+ else:
421
+ return False, f"当前SDK版本 {current_version} 低于最低要求 {min_sdk_version}"
422
+ except Exception:
423
+ return True, "无法验证SDK版本兼容性"
424
+
425
+ async def _get_package_info(self, package_name: str) -> Optional[Dict[str, Any]]:
426
+ """
427
+ 获取包的详细信息(包括min_sdk_version等)
428
+
429
+ :param package_name: 包名或别名
430
+ :return: 包信息字典
431
+ """
432
+ # 首先尝试通过别名查找
433
+ normalized_name = self._normalize_name(package_name)
434
+ remote_packages = await self.get_remote_packages()
435
+
436
+ # 检查模块
437
+ for name, info in remote_packages["modules"].items():
438
+ if self._normalize_name(name) == normalized_name:
439
+ return info
440
+
441
+ # 检查适配器
442
+ for name, info in remote_packages["adapters"].items():
443
+ if self._normalize_name(name) == normalized_name:
444
+ return info
445
+
446
+ # 检查CLI扩展
447
+ for name, info in remote_packages.get("cli_extensions", {}).items():
448
+ if self._normalize_name(name) == normalized_name:
449
+ return info
450
+
451
+ return None
452
+
453
+ def install_package(self, package_names: List[str], upgrade: bool = False, pre: bool = False) -> bool:
454
+ """
455
+ 安装指定包(支持多个包)
456
+
457
+ :param package_names: 要安装的包名或别名列表
299
458
  :param upgrade: 是否升级已安装的包
459
+ :param pre: 是否包含预发布版本
300
460
  :return: 安装是否成功
301
461
  """
302
- cmd = ["install"]
303
- if upgrade:
304
- cmd.append("--upgrade")
305
- cmd.append(package_name)
462
+ all_success = True
306
463
 
307
- success = self._run_pip_command(cmd, f"安装 {package_name}")
308
-
309
- if success:
310
- console.print(f"[success]包 {package_name} 安装成功[/]")
311
- else:
312
- console.print(f"[error]包 {package_name} 安装失败[/]")
464
+ for package_name in package_names:
465
+ # 首先尝试通过别名查找实际包名
466
+ actual_package = asyncio.run(self._find_package_by_alias(package_name))
313
467
 
314
- return success
468
+ if actual_package:
469
+ console.print(f"[info]找到别名映射: [bold]{package_name}[/] → [package]{actual_package}[/][/]")
470
+ current_package_name = actual_package
471
+ else:
472
+ console.print(f"[info]未找到别名,将直接安装: [package]{package_name}[/][/]")
473
+ current_package_name = package_name
474
+
475
+ # 检查SDK版本兼容性
476
+ package_info = asyncio.run(self._get_package_info(package_name))
477
+ if package_info and "min_sdk_version" in package_info:
478
+ is_compatible, message = self._check_sdk_compatibility(package_info["min_sdk_version"])
479
+ if not is_compatible:
480
+ console.print(Panel(
481
+ f"[warning]SDK版本兼容性警告[/]\n"
482
+ f"包 [package]{current_package_name}[/] 需要最低SDK版本 {package_info['min_sdk_version']}\n"
483
+ f"{message}\n\n"
484
+ f"继续安装可能会导致问题。",
485
+ title="兼容性警告",
486
+ border_style="warning"
487
+ ))
488
+ if not Confirm.ask("是否继续安装?", default=False):
489
+ console.print("[info]已取消安装[/]")
490
+ all_success = False
491
+ continue
492
+ else:
493
+ console.print(f"[success]{message}[/]")
494
+
495
+ # 构建pip命令
496
+ cmd = ["install"]
497
+ if upgrade:
498
+ cmd.append("--upgrade")
499
+ if pre:
500
+ cmd.append("--pre")
501
+ cmd.append(current_package_name)
502
+
503
+ # 执行安装命令
504
+ success, stdout, stderr = self._run_pip_command_with_output(cmd, f"安装 {current_package_name}")
505
+
506
+ if success:
507
+ console.print(Panel(
508
+ f"[success]包 {current_package_name} 安装成功[/]\n\n"
509
+ f"[dim]{stdout}[/]",
510
+ title="安装完成",
511
+ border_style="success"
512
+ ))
513
+ else:
514
+ console.print(Panel(
515
+ f"[error]包 {current_package_name} 安装失败[/]\n\n"
516
+ f"[dim]{stderr}[/]",
517
+ title="安装失败",
518
+ border_style="error"
519
+ ))
520
+ all_success = False
521
+
522
+ return all_success
315
523
 
316
- def uninstall_package(self, package_name: str) -> bool:
524
+ def uninstall_package(self, package_names: List[str]) -> bool:
317
525
  """
318
- 卸载指定包
526
+ 卸载指定包(支持多个包,支持别名)
319
527
 
320
- :param package_name: 要卸载的包名
528
+ :param package_names: 要卸载的包名或别名列表
321
529
  :return: 卸载是否成功
322
530
  """
323
- success = self._run_pip_command(
324
- ["uninstall", "-y", package_name],
325
- f"卸载 {package_name}"
326
- )
531
+ all_success = True
327
532
 
328
- if success:
329
- console.print(f"[success]包 {package_name} 卸载成功[/]")
330
- else:
331
- console.print(f"[error]包 {package_name} 卸载失败[/]")
533
+ packages_to_uninstall = []
534
+
535
+ # 首先处理所有包名,查找实际包名
536
+ for package_name in package_names:
537
+ # 首先尝试通过别名查找实际包名
538
+ actual_package = asyncio.run(self._find_package_by_alias(package_name))
332
539
 
333
- return success
540
+ if actual_package:
541
+ console.print(f"[info]找到别名映射: [bold]{package_name}[/] → [package]{actual_package}[/][/]")
542
+ packages_to_uninstall.append(actual_package)
543
+ else:
544
+ # 如果找不到别名映射,检查是否是已安装的包
545
+ installed_package = self._find_installed_package_by_name(package_name)
546
+ if installed_package:
547
+ package_name = installed_package
548
+ console.print(f"[info]找到已安装包: [bold]{package_name}[/][/]")
549
+ packages_to_uninstall.append(package_name)
550
+ else:
551
+ console.print(f"[warning]未找到别名映射,将尝试直接卸载: [package]{package_name}[/][/]")
552
+ packages_to_uninstall.append(package_name)
553
+
554
+ # 确认卸载操作
555
+ package_list = "\n".join([f" - [package]{pkg}[/]" for pkg in packages_to_uninstall])
556
+ if not Confirm.ask(f"确认卸载以下包吗?\n{package_list}", default=False):
557
+ console.print("[info]操作已取消[/]")
558
+ return False
559
+
560
+ # 执行卸载命令
561
+ for package_name in packages_to_uninstall:
562
+ success, stdout, stderr = self._run_pip_command_with_output(
563
+ ["uninstall", "-y", package_name],
564
+ f"卸载 {package_name}"
565
+ )
566
+
567
+ if success:
568
+ console.print(Panel(
569
+ f"[success]包 {package_name} 卸载成功[/]\n\n"
570
+ f"[dim]{stdout}[/]",
571
+ title="卸载完成",
572
+ border_style="success"
573
+ ))
574
+ else:
575
+ console.print(Panel(
576
+ f"[error]包 {package_name} 卸载失败[/]\n\n"
577
+ f"[dim]{stderr}[/]",
578
+ title="卸载失败",
579
+ border_style="error"
580
+ ))
581
+ all_success = False
582
+
583
+ return all_success
334
584
 
335
585
  def upgrade_all(self) -> bool:
336
586
  """
@@ -362,7 +612,7 @@ class PackageManager:
362
612
 
363
613
  results = {}
364
614
  for pkg in sorted(all_packages):
365
- results[pkg] = self.install_package(pkg, upgrade=True)
615
+ results[pkg] = self.install_package([pkg], upgrade=True)
366
616
 
367
617
  failed = [pkg for pkg, success in results.items() if not success]
368
618
  if failed:
@@ -375,6 +625,223 @@ class PackageManager:
375
625
 
376
626
  return True
377
627
 
628
+ def upgrade_package(self, package_names: List[str], pre: bool = False) -> bool:
629
+ """
630
+ 升级指定包(支持多个包)
631
+
632
+ :param package_names: 要升级的包名或别名列表
633
+ :param pre: 是否包含预发布版本
634
+ :return: 升级是否成功
635
+ """
636
+ all_success = True
637
+
638
+ for package_name in package_names:
639
+ # 首先尝试通过别名查找实际包名
640
+ actual_package = asyncio.run(self._find_package_by_alias(package_name))
641
+
642
+ if actual_package:
643
+ console.print(f"[info]找到别名映射: [bold]{package_name}[/] → [package]{actual_package}[/][/]")
644
+ current_package_name = actual_package
645
+ else:
646
+ current_package_name = package_name
647
+
648
+ # 检查SDK版本兼容性
649
+ package_info = asyncio.run(self._get_package_info(package_name))
650
+ if package_info and "min_sdk_version" in package_info:
651
+ is_compatible, message = self._check_sdk_compatibility(package_info["min_sdk_version"])
652
+ if not is_compatible:
653
+ console.print(Panel(
654
+ f"[warning]SDK版本兼容性警告[/]\n"
655
+ f"包 [package]{current_package_name}[/] 需要最低SDK版本 {package_info['min_sdk_version']}\n"
656
+ f"{message}\n\n"
657
+ f"继续升级可能会导致问题。",
658
+ title="兼容性警告",
659
+ border_style="warning"
660
+ ))
661
+ if not Confirm.ask("是否继续升级?", default=False):
662
+ console.print("[info]已取消升级[/]")
663
+ all_success = False
664
+ continue
665
+ else:
666
+ console.print(f"[success]{message}[/]")
667
+
668
+ # 构建pip命令
669
+ cmd = ["install", "--upgrade"]
670
+ if pre:
671
+ cmd.append("--pre")
672
+ cmd.append(current_package_name)
673
+
674
+ # 执行升级命令
675
+ success, stdout, stderr = self._run_pip_command_with_output(cmd, f"升级 {current_package_name}")
676
+
677
+ if success:
678
+ console.print(Panel(
679
+ f"[success]包 {current_package_name} 升级成功[/]\n\n"
680
+ f"[dim]{stdout}[/]",
681
+ title="升级完成",
682
+ border_style="success"
683
+ ))
684
+ else:
685
+ console.print(Panel(
686
+ f"[error]包 {current_package_name} 升级失败[/]\n\n"
687
+ f"[dim]{stderr}[/]",
688
+ title="升级失败",
689
+ border_style="error"
690
+ ))
691
+ all_success = False
692
+
693
+ return all_success
694
+
695
+ def search_package(self, query: str) -> Dict[str, List[Dict[str, str]]]:
696
+ """
697
+ 搜索包(本地和远程)
698
+
699
+ :param query: 搜索关键词
700
+ :return: 匹配的包信息
701
+ """
702
+ normalized_query = self._normalize_name(query)
703
+ results = {"installed": [], "remote": []}
704
+
705
+ # 搜索已安装的包
706
+ installed = self.get_installed_packages()
707
+ for pkg_type in ["modules", "adapters", "cli_extensions"]:
708
+ for name, info in installed[pkg_type].items():
709
+ if (normalized_query in self._normalize_name(name) or
710
+ normalized_query in self._normalize_name(info["package"]) or
711
+ normalized_query in self._normalize_name(info["summary"])):
712
+ results["installed"].append({
713
+ "type": pkg_type[:-1] if pkg_type.endswith("s") else pkg_type, # 移除复数s
714
+ "name": name,
715
+ "package": info["package"],
716
+ "version": info["version"],
717
+ "summary": info["summary"]
718
+ })
719
+
720
+ # 搜索远程包
721
+ remote = asyncio.run(self.get_remote_packages())
722
+ for pkg_type in ["modules", "adapters", "cli_extensions"]:
723
+ for name, info in remote[pkg_type].items():
724
+ if (normalized_query in self._normalize_name(name) or
725
+ normalized_query in self._normalize_name(info["package"]) or
726
+ normalized_query in self._normalize_name(info.get("description", "")) or
727
+ normalized_query in self._normalize_name(info.get("summary", ""))):
728
+ results["remote"].append({
729
+ "type": pkg_type[:-1] if pkg_type.endswith("s") else pkg_type, # 移除复数s
730
+ "name": name,
731
+ "package": info["package"],
732
+ "version": info["version"],
733
+ "summary": info.get("description", info.get("summary", ""))
734
+ })
735
+
736
+ return results
737
+
738
+ def get_installed_version(self) -> str:
739
+ """
740
+ 获取当前安装的ErisPulse版本
741
+
742
+ :return: 当前版本号
743
+ """
744
+ try:
745
+ from ErisPulse import __version__
746
+ return __version__
747
+ except ImportError:
748
+ return "unknown"
749
+
750
+ async def get_pypi_versions(self) -> List[Dict[str, Any]]:
751
+ """
752
+ 从PyPI获取ErisPulse的所有可用版本
753
+
754
+ :return: 版本信息列表
755
+ """
756
+ import aiohttp
757
+ from aiohttp import ClientError, ClientTimeout
758
+ from packaging import version as comparison
759
+
760
+ timeout = ClientTimeout(total=10)
761
+ url = "https://pypi.org/pypi/ErisPulse/json"
762
+
763
+ try:
764
+ async with aiohttp.ClientSession(timeout=timeout) as session:
765
+ async with session.get(url) as response:
766
+ if response.status == 200:
767
+ data = await response.json()
768
+ versions = []
769
+ for version_str, releases in data["releases"].items():
770
+ if releases: # 只包含有文件的版本
771
+ release_info = {
772
+ "version": version_str,
773
+ "uploaded": releases[0].get("upload_time_iso_8601", ""),
774
+ "pre_release": self._is_pre_release(version_str)
775
+ }
776
+ versions.append(release_info)
777
+
778
+ # 使用版本比较函数正确排序版本
779
+ versions.sort(key=lambda x: comparison.parse(x["version"]), reverse=True)
780
+ return versions
781
+ except (ClientError, asyncio.TimeoutError, json.JSONDecodeError, KeyError, Exception) as e:
782
+ console.print(f"[error]获取PyPI版本信息失败: {e}[/]")
783
+ return []
784
+
785
+ def _is_pre_release(self, version: str) -> bool:
786
+ """
787
+ 判断版本是否为预发布版本
788
+
789
+ :param version: 版本号
790
+ :return: 是否为预发布版本
791
+ """
792
+ import re
793
+ # 检查是否包含预发布标识符 (alpha, beta, rc, dev等)
794
+ pre_release_pattern = re.compile(r'(a|b|rc|dev|alpha|beta)\d*', re.IGNORECASE)
795
+ return bool(pre_release_pattern.search(version))
796
+
797
+ def update_self(self, target_version: str = None, force: bool = False) -> bool:
798
+ """
799
+ 更新ErisPulse SDK本身
800
+
801
+ :param target_version: 目标版本号,None表示更新到最新版本
802
+ :param force: 是否强制更新
803
+ :return: 更新是否成功
804
+ """
805
+ current_version = self.get_installed_version()
806
+
807
+ if target_version and target_version == current_version and not force:
808
+ console.print(f"[info]当前已是目标版本 [bold]{current_version}[/][/]")
809
+ return True
810
+
811
+ # 确定要安装的版本
812
+ package_spec = "ErisPulse"
813
+ if target_version:
814
+ package_spec += f"=={target_version}"
815
+
816
+ # 执行更新命令
817
+ success, stdout, stderr = self._run_pip_command_with_output(
818
+ ["install", "--upgrade", package_spec],
819
+ f"更新 ErisPulse SDK {f'到 {target_version}' if target_version else '到最新版本'}"
820
+ )
821
+
822
+ if success:
823
+ new_version = target_version or "最新版本"
824
+ console.print(Panel(
825
+ f"[success]ErisPulse SDK 更新成功[/]\n"
826
+ f" 当前版本: [bold]{current_version}[/]\n"
827
+ f" 更新版本: [bold]{new_version}[/]\n\n"
828
+ f"[dim]{stdout}[/]",
829
+ title="更新完成",
830
+ border_style="success"
831
+ ))
832
+
833
+ if not target_version:
834
+ console.print("[info]请重新启动CLI以使用新版本[/]")
835
+ else:
836
+ console.print(Panel(
837
+ f"[error]ErisPulse SDK 更新失败[/]\n\n"
838
+ f"[dim]{stderr}[/]",
839
+ title="更新失败",
840
+ border_style="error"
841
+ ))
842
+
843
+ return success
844
+
378
845
  class ReloadHandler(FileSystemEventHandler):
379
846
  """
380
847
  文件系统事件处理器
@@ -454,12 +921,44 @@ class ReloadHandler(FileSystemEventHandler):
454
921
 
455
922
  def _handle_reload(self, event, reason: str):
456
923
  """
457
- 处理重载逻辑
458
-
924
+ 处理热重载逻辑
459
925
  :param event: 文件系统事件
460
- :param reason: 重载原因描述
926
+ :param reason: 重载原因
461
927
  """
462
- console.print(f"\n[reload]{reason}: [path]{event.src_path}[/][/]")
928
+ from ErisPulse.Core import adapter, logger
929
+ # 在重载前确保所有适配器正确停止
930
+ try:
931
+ # 检查适配器是否正在运行
932
+ if hasattr(adapter, '_started_instances') and adapter._started_instances:
933
+ logger.info("正在停止适配器...")
934
+ # 创建新的事件循环来运行异步停止操作
935
+ import asyncio
936
+ import threading
937
+
938
+ # 如果在主线程中
939
+ if threading.current_thread() is threading.main_thread():
940
+ try:
941
+ # 尝试获取当前事件循环
942
+ loop = asyncio.get_running_loop()
943
+ # 在新线程中运行适配器停止
944
+ stop_thread = threading.Thread(target=lambda: asyncio.run(adapter.shutdown()))
945
+ stop_thread.start()
946
+ stop_thread.join(timeout=10) # 最多等待10秒
947
+ except RuntimeError:
948
+ # 没有运行中的事件循环
949
+ asyncio.run(adapter.shutdown())
950
+ else:
951
+ # 在非主线程中,创建新的事件循环
952
+ new_loop = asyncio.new_event_loop()
953
+ asyncio.set_event_loop(new_loop)
954
+ new_loop.run_until_complete(adapter.shutdown())
955
+
956
+ logger.info("适配器已停止")
957
+ except Exception as e:
958
+ logger.warning(f"停止适配器时出错: {e}")
959
+
960
+ # 原有的重载逻辑
961
+ logger.info(f"检测到文件变更 ({reason}),正在重启...")
463
962
  self._terminate_process()
464
963
  self.start_process()
465
964
 
@@ -519,11 +1018,12 @@ class CLI:
519
1018
  # 安装命令
520
1019
  install_parser = subparsers.add_parser(
521
1020
  'install',
522
- help='安装模块/适配器包'
1021
+ help='安装模块/适配器包(支持多个,用空格分隔)'
523
1022
  )
524
1023
  install_parser.add_argument(
525
1024
  'package',
526
- help='要安装的包名或模块/适配器简称'
1025
+ nargs='+', # 改为接受多个参数
1026
+ help='要安装的包名或模块/适配器简称(可指定多个)'
527
1027
  )
528
1028
  install_parser.add_argument(
529
1029
  '--upgrade', '-U',
@@ -539,11 +1039,12 @@ class CLI:
539
1039
  # 卸载命令
540
1040
  uninstall_parser = subparsers.add_parser(
541
1041
  'uninstall',
542
- help='卸载模块/适配器包'
1042
+ help='卸载模块/适配器包(支持多个,用空格分隔)'
543
1043
  )
544
1044
  uninstall_parser.add_argument(
545
1045
  'package',
546
- help='要卸载的包名'
1046
+ nargs='+', # 改为接受多个参数
1047
+ help='要卸载的包名(可指定多个)'
547
1048
  )
548
1049
 
549
1050
  # 模块管理命令
@@ -613,11 +1114,11 @@ class CLI:
613
1114
  # 升级命令
614
1115
  upgrade_parser = subparsers.add_parser(
615
1116
  'upgrade',
616
- help='升级组件'
1117
+ help='升级组件(支持多个,用空格分隔)'
617
1118
  )
618
1119
  upgrade_parser.add_argument(
619
1120
  'package',
620
- nargs='?',
1121
+ nargs='*', # 改为接受可选的多个参数
621
1122
  help='要升级的包名 (可选,不指定则升级所有)'
622
1123
  )
623
1124
  upgrade_parser.add_argument(
@@ -625,6 +1126,52 @@ class CLI:
625
1126
  action='store_true',
626
1127
  help='跳过确认直接升级'
627
1128
  )
1129
+ upgrade_parser.add_argument(
1130
+ '--pre',
1131
+ action='store_true',
1132
+ help='包含预发布版本'
1133
+ )
1134
+
1135
+ # 搜索命令
1136
+ search_parser = subparsers.add_parser(
1137
+ 'search',
1138
+ help='搜索模块/适配器包'
1139
+ )
1140
+ search_parser.add_argument(
1141
+ 'query',
1142
+ help='搜索关键词'
1143
+ )
1144
+ search_parser.add_argument(
1145
+ '--installed', '-i',
1146
+ action='store_true',
1147
+ help='仅搜索已安装的包'
1148
+ )
1149
+ search_parser.add_argument(
1150
+ '--remote', '-r',
1151
+ action='store_true',
1152
+ help='仅搜索远程包'
1153
+ )
1154
+
1155
+ # 自更新命令
1156
+ self_update_parser = subparsers.add_parser(
1157
+ 'self-update',
1158
+ help='更新ErisPulse SDK本身'
1159
+ )
1160
+ self_update_parser.add_argument(
1161
+ 'version',
1162
+ nargs='?',
1163
+ help='要更新到的版本号 (可选,默认为最新版本)'
1164
+ )
1165
+ self_update_parser.add_argument(
1166
+ '--pre',
1167
+ action='store_true',
1168
+ help='包含预发布版本'
1169
+ )
1170
+ self_update_parser.add_argument(
1171
+ '--force', '-f',
1172
+ action='store_true',
1173
+ help='强制更新,即使版本相同'
1174
+ )
628
1175
 
629
1176
  # 运行命令
630
1177
  run_parser = subparsers.add_parser(
@@ -899,23 +1446,133 @@ class CLI:
899
1446
 
900
1447
  def _resolve_package_name(self, short_name: str) -> Optional[str]:
901
1448
  """
902
- 解析简称到完整包名
1449
+ 解析简称到完整包名(大小写不敏感)
903
1450
 
904
1451
  :param short_name: 模块/适配器简称
905
1452
  :return: 完整包名,未找到返回None
906
1453
  """
1454
+ normalized_name = self.package_manager._normalize_name(short_name)
907
1455
  remote_packages = asyncio.run(self.package_manager.get_remote_packages())
908
1456
 
909
1457
  # 检查模块
910
- if short_name in remote_packages["modules"]:
911
- return remote_packages["modules"][short_name]["package"]
912
-
1458
+ for name, info in remote_packages["modules"].items():
1459
+ if self.package_manager._normalize_name(name) == normalized_name:
1460
+ return info["package"]
1461
+
913
1462
  # 检查适配器
914
- if short_name in remote_packages["adapters"]:
915
- return remote_packages["adapters"][short_name]["package"]
916
-
1463
+ for name, info in remote_packages["adapters"].items():
1464
+ if self.package_manager._normalize_name(name) == normalized_name:
1465
+ return info["package"]
1466
+
917
1467
  return None
918
1468
 
1469
+ def _print_search_results(self, query: str, results: Dict[str, List[Dict[str, str]]]):
1470
+ """
1471
+ 打印搜索结果
1472
+
1473
+ :param query: 搜索关键词
1474
+ :param results: 搜索结果
1475
+ """
1476
+ if not results["installed"] and not results["remote"]:
1477
+ console.print(f"[info]未找到与 '[bold]{query}[/]' 匹配的包[/]")
1478
+ return
1479
+
1480
+ # 打印已安装的包
1481
+ if results["installed"]:
1482
+ table = Table(
1483
+ title="已安装的包",
1484
+ box=SIMPLE,
1485
+ header_style="info"
1486
+ )
1487
+ table.add_column("类型")
1488
+ table.add_column("名称")
1489
+ table.add_column("包名")
1490
+ table.add_column("版本")
1491
+ table.add_column("描述")
1492
+
1493
+ for item in results["installed"]:
1494
+ table.add_row(
1495
+ item["type"],
1496
+ item["name"],
1497
+ item["package"],
1498
+ item["version"],
1499
+ item["summary"]
1500
+ )
1501
+
1502
+ console.print(table)
1503
+
1504
+ # 打印远程包
1505
+ if results["remote"]:
1506
+ table = Table(
1507
+ title="远程包",
1508
+ box=SIMPLE,
1509
+ header_style="info"
1510
+ )
1511
+ table.add_column("类型")
1512
+ table.add_column("名称")
1513
+ table.add_column("包名")
1514
+ table.add_column("版本")
1515
+ table.add_column("描述")
1516
+
1517
+ for item in results["remote"]:
1518
+ table.add_row(
1519
+ item["type"],
1520
+ item["name"],
1521
+ item["package"],
1522
+ item["version"],
1523
+ item["summary"]
1524
+ )
1525
+
1526
+ console.print(table)
1527
+
1528
+ def _print_version_list(self, versions: List[Dict[str, Any]], include_pre: bool = False):
1529
+ """
1530
+ 打印版本列表
1531
+
1532
+ :param versions: 版本信息列表
1533
+ :param include_pre: 是否包含预发布版本
1534
+ """
1535
+ if not versions:
1536
+ console.print("[info]未找到可用版本[/]")
1537
+ return
1538
+
1539
+ table = Table(
1540
+ title="可用版本",
1541
+ box=SIMPLE,
1542
+ header_style="info"
1543
+ )
1544
+ table.add_column("序号")
1545
+ table.add_column("版本")
1546
+ table.add_column("类型")
1547
+ table.add_column("上传时间")
1548
+
1549
+ displayed = 0
1550
+ version_list = []
1551
+ for version_info in versions:
1552
+ # 如果不包含预发布版本,则跳过预发布版本
1553
+ if not include_pre and version_info["pre_release"]:
1554
+ continue
1555
+
1556
+ version_list.append(version_info)
1557
+ version_type = "[yellow]预发布[/]" if version_info["pre_release"] else "[green]稳定版[/]"
1558
+ table.add_row(
1559
+ str(displayed + 1),
1560
+ version_info["version"],
1561
+ version_type,
1562
+ version_info["uploaded"][:10] if version_info["uploaded"] else "未知"
1563
+ )
1564
+ displayed += 1
1565
+
1566
+ # 只显示前10个版本
1567
+ if displayed >= 10:
1568
+ break
1569
+
1570
+ if displayed == 0:
1571
+ console.print("[info]没有找到符合条件的版本[/]")
1572
+ else:
1573
+ console.print(table)
1574
+ return version_list
1575
+
919
1576
  def _setup_watchdog(self, script_path: str, reload_mode: bool):
920
1577
  """
921
1578
  设置文件监控
@@ -980,16 +1637,19 @@ class CLI:
980
1637
 
981
1638
  try:
982
1639
  if args.command == "install":
983
- full_package = self._resolve_package_name(args.package)
984
- if full_package:
985
- console.print(f"[info]找到远程包: [bold]{args.package}[/] → [package]{full_package}[/][/]")
986
- self.package_manager.install_package(full_package, args.upgrade)
987
- else:
988
- self.package_manager.install_package(args.package, args.upgrade)
1640
+ success = self.package_manager.install_package(
1641
+ args.package, # 现在是列表
1642
+ upgrade=args.upgrade,
1643
+ pre=args.pre
1644
+ )
1645
+ if not success:
1646
+ sys.exit(1)
989
1647
 
990
1648
  elif args.command == "uninstall":
991
- self.package_manager.uninstall_package(args.package)
992
-
1649
+ success = self.package_manager.uninstall_package(args.package) # 现在是列表
1650
+ if not success:
1651
+ sys.exit(1)
1652
+
993
1653
  elif args.command == "module":
994
1654
  from ErisPulse.Core import mods
995
1655
  installed = self.package_manager.get_installed_packages()
@@ -1030,11 +1690,165 @@ class CLI:
1030
1690
 
1031
1691
  elif args.command == "upgrade":
1032
1692
  if args.package:
1033
- self.package_manager.install_package(args.package, upgrade=True)
1693
+ success = self.package_manager.upgrade_package(
1694
+ args.package, # 现在是列表
1695
+ pre=args.pre
1696
+ )
1697
+ if not success:
1698
+ sys.exit(1)
1034
1699
  else:
1035
- if args.force or Confirm.ask("确定要升级所有ErisPulse组件吗?"):
1036
- self.package_manager.upgrade_all()
1700
+ if args.force or Confirm.ask("确定要升级所有ErisPulse组件吗?", default=False):
1701
+ success = self.package_manager.upgrade_all()
1702
+ if not success:
1703
+ sys.exit(1)
1704
+
1705
+ elif args.command == "search":
1706
+ results = self.package_manager.search_package(args.query)
1707
+
1708
+ # 根据选项过滤结果
1709
+ if args.installed:
1710
+ results["remote"] = []
1711
+ elif args.remote:
1712
+ results["installed"] = []
1713
+
1714
+ self._print_search_results(args.query, results)
1715
+
1716
+ elif args.command == "self-update":
1717
+ current_version = self.package_manager.get_installed_version()
1718
+ console.print(Panel(
1719
+ f"[title]ErisPulse SDK 自更新[/]\n"
1720
+ f"当前版本: [bold]{current_version}[/]",
1721
+ title_align="left"
1722
+ ))
1723
+
1724
+ # 获取可用版本
1725
+ with console.status("[bold green]正在获取版本信息...", spinner="dots"):
1726
+ versions = asyncio.run(self.package_manager.get_pypi_versions())
1727
+
1728
+ if not versions:
1729
+ console.print("[error]无法获取版本信息[/]")
1730
+ sys.exit(1)
1731
+
1732
+ # 交互式选择更新选项
1733
+ if not args.version:
1734
+ # 显示最新版本
1735
+ stable_versions = [v for v in versions if not v["pre_release"]]
1736
+ pre_versions = [v for v in versions if v["pre_release"]]
1737
+
1738
+ latest_stable = stable_versions[0] if stable_versions else None
1739
+ latest_pre = pre_versions[0] if pre_versions and args.pre else None
1740
+
1741
+ choices = []
1742
+ choice_versions = {}
1743
+ choice_index = {}
1744
+
1745
+ if latest_stable:
1746
+ choice = f"最新稳定版 ({latest_stable['version']})"
1747
+ choices.append(choice)
1748
+ choice_versions[choice] = latest_stable['version']
1749
+ choice_index[len(choices)] = choice
1750
+
1751
+ if args.pre and latest_pre:
1752
+ choice = f"最新预发布版 ({latest_pre['version']})"
1753
+ choices.append(choice)
1754
+ choice_versions[choice] = latest_pre['version']
1755
+ choice_index[len(choices)] = choice
1037
1756
 
1757
+ # 添加其他选项
1758
+ choices.append("查看所有版本")
1759
+ choices.append("手动指定版本")
1760
+ choices.append("取消")
1761
+
1762
+ # 创建数字索引映射
1763
+ for i, choice in enumerate(choices, 1):
1764
+ choice_index[i] = choice
1765
+
1766
+ # 显示选项
1767
+ console.print("\n[info]请选择更新选项:[/]")
1768
+ for i, choice in enumerate(choices, 1):
1769
+ console.print(f" {i}. {choice}")
1770
+
1771
+ while True:
1772
+ try:
1773
+ selected_input = Prompt.ask(
1774
+ "请输入选项编号",
1775
+ default="1"
1776
+ )
1777
+
1778
+ if selected_input.isdigit():
1779
+ selected_index = int(selected_input)
1780
+ if selected_index in choice_index:
1781
+ selected = choice_index[selected_index]
1782
+ break
1783
+ else:
1784
+ console.print("[warning]请输入有效的选项编号[/]")
1785
+ else:
1786
+ # 检查是否是选项文本
1787
+ if selected_input in choices:
1788
+ selected = selected_input
1789
+ break
1790
+ else:
1791
+ console.print("[warning]请输入有效的选项编号或选项名称[/]")
1792
+ except KeyboardInterrupt:
1793
+ console.print("\n[info]操作已取消[/]")
1794
+ sys.exit(0)
1795
+
1796
+ if selected == "取消":
1797
+ console.print("[info]操作已取消[/]")
1798
+ sys.exit(0)
1799
+ elif selected == "手动指定版本":
1800
+ target_version = Prompt.ask("请输入要更新到的版本号")
1801
+ if not any(v['version'] == target_version for v in versions):
1802
+ console.print(f"[warning]版本 {target_version} 可能不存在[/]")
1803
+ if not Confirm.ask("是否继续?", default=False):
1804
+ sys.exit(0)
1805
+ elif selected == "查看所有版本":
1806
+ version_list = self._print_version_list(versions, include_pre=args.pre)
1807
+ if not version_list:
1808
+ console.print("[info]没有可用版本[/]")
1809
+ sys.exit(0)
1810
+
1811
+ # 显示版本选择
1812
+ console.print("\n[info]请选择要更新到的版本:[/]")
1813
+ while True:
1814
+ try:
1815
+ version_input = Prompt.ask("请输入版本序号或版本号")
1816
+ if version_input.isdigit():
1817
+ version_index = int(version_input)
1818
+ if 1 <= version_index <= len(version_list):
1819
+ target_version = version_list[version_index - 1]['version']
1820
+ break
1821
+ else:
1822
+ console.print("[warning]请输入有效的版本序号[/]")
1823
+ else:
1824
+ # 检查是否是有效的版本号
1825
+ if any(v['version'] == version_input for v in version_list):
1826
+ target_version = version_input
1827
+ break
1828
+ else:
1829
+ console.print("[warning]请输入有效的版本序号或版本号[/]")
1830
+ except KeyboardInterrupt:
1831
+ console.print("\n[info]操作已取消[/]")
1832
+ sys.exit(0)
1833
+ else:
1834
+ target_version = choice_versions[selected]
1835
+ else:
1836
+ target_version = args.version
1837
+
1838
+ # 确认更新
1839
+ if target_version == current_version and not args.force:
1840
+ console.print(f"[info]当前已是目标版本 [bold]{current_version}[/][/]")
1841
+ sys.exit(0)
1842
+ elif not args.force:
1843
+ if not Confirm.ask(f"确认将ErisPulse SDK从 [bold]{current_version}[/] 更新到 [bold]{target_version}[/] 吗?", default=False):
1844
+ console.print("[info]操作已取消[/]")
1845
+ sys.exit(0)
1846
+
1847
+ # 执行更新
1848
+ success = self.package_manager.update_self(target_version, args.force)
1849
+ if not success:
1850
+ sys.exit(1)
1851
+
1038
1852
  elif args.command == "run":
1039
1853
  script = args.script or "main.py"
1040
1854
  if not os.path.exists(script):
@@ -1046,9 +1860,10 @@ class CLI:
1046
1860
 
1047
1861
  try:
1048
1862
  while True:
1049
- time.sleep(1)
1863
+ time.sleep(0.5)
1050
1864
  except KeyboardInterrupt:
1051
1865
  console.print("\n[info]正在安全关闭...[/]")
1866
+ self._cleanup_adapters()
1052
1867
  self._cleanup()
1053
1868
  console.print("[success]已安全退出[/]")
1054
1869
 
@@ -1087,6 +1902,44 @@ class CLI:
1087
1902
  console.print(traceback.format_exc())
1088
1903
  self._cleanup()
1089
1904
  sys.exit(1)
1905
+
1906
+ def _cleanup_adapters(self):
1907
+ """
1908
+ 清理适配器资源
1909
+ """
1910
+ from ErisPulse import adapter, logger
1911
+ try:
1912
+ import asyncio
1913
+ import threading
1914
+
1915
+ # 检查是否有正在运行的适配器
1916
+ if (hasattr(adapter, '_started_instances') and
1917
+ adapter._started_instances):
1918
+
1919
+ logger.info("正在停止所有适配器...")
1920
+
1921
+ if threading.current_thread() is threading.main_thread():
1922
+ try:
1923
+ loop = asyncio.get_running_loop()
1924
+ if loop.is_running():
1925
+ # 在新线程中运行
1926
+ stop_thread = threading.Thread(
1927
+ target=lambda: asyncio.run(adapter.shutdown())
1928
+ )
1929
+ stop_thread.start()
1930
+ stop_thread.join(timeout=5)
1931
+ else:
1932
+ asyncio.run(adapter.shutdown())
1933
+ except RuntimeError:
1934
+ asyncio.run(adapter.shutdown())
1935
+ else:
1936
+ new_loop = asyncio.new_event_loop()
1937
+ asyncio.set_event_loop(new_loop)
1938
+ new_loop.run_until_complete(adapter.shutdown())
1939
+
1940
+ logger.info("适配器已全部停止")
1941
+ except Exception as e:
1942
+ logger.error(f"清理适配器资源时出错: {e}")
1090
1943
 
1091
1944
  def main():
1092
1945
  """