app_controller.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """
  2. agent67.tools.app_controller — 应用控制器 (macOS)
  3. Lambda: λ action_json. app_op(action)
  4. """
  5. import json
  6. import platform
  7. import subprocess
  8. from .safety import ask_user_confirm
  9. def control_app(input_json: str) -> str:
  10. """
  11. 应用程序控制。
  12. 支持: launch / quit / list / focus / notify
  13. """
  14. try:
  15. data = json.loads(input_json)
  16. except json.JSONDecodeError:
  17. data = {"action": "launch", "app": input_json.strip()}
  18. action = data.get("action", "launch")
  19. app_name = data.get("app", "")
  20. if platform.system() != "Darwin":
  21. return "⚠️ 应用控制目前仅支持 macOS"
  22. try:
  23. if action == "launch":
  24. subprocess.run(["open", "-a", app_name], check=True, timeout=10)
  25. return f"🚀 已启动: {app_name}"
  26. elif action == "quit":
  27. if not ask_user_confirm(f"关闭应用: {app_name}"):
  28. return "❌ 用户取消"
  29. script = f'tell application "{app_name}" to quit'
  30. subprocess.run(["osascript", "-e", script], timeout=10)
  31. return f"✅ 已关闭: {app_name}"
  32. elif action == "list":
  33. script = ('tell application "System Events" to get name of '
  34. 'every process whose background only is false')
  35. result = subprocess.run(
  36. ["osascript", "-e", script],
  37. capture_output=True, text=True, timeout=10,
  38. )
  39. return f"🖥️ 运行中的应用:\n{result.stdout.strip()}"
  40. elif action == "focus":
  41. script = f'tell application "{app_name}" to activate'
  42. subprocess.run(["osascript", "-e", script], timeout=10)
  43. return f"✅ 已切换到: {app_name}"
  44. elif action == "notify":
  45. title = data.get("title", "lambda 通知 🐂")
  46. message = data.get("message", "")
  47. script = f'display notification "{message}" with title "{title}"'
  48. subprocess.run(["osascript", "-e", script], timeout=10)
  49. return f"🔔 通知已发送: {title}"
  50. else:
  51. return f"❌ 未知操作: {action}. 支持: launch/quit/list/focus/notify"
  52. except subprocess.CalledProcessError as e:
  53. return f"❌ 应用操作失败: {e}"
  54. except Exception as e:
  55. return f"❌ 错误: {e}"