ai-os-desktop 0.1.0__tar.gz

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.
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.4
2
+ Name: ai-os-desktop
3
+ Version: 0.1.0
4
+ Summary: Voice-first Windows desktop control: a voice assistant and an MCP server for DeepSeek Harness and other agents
5
+ License-Expression: MIT
6
+ Keywords: deepseek,dsh-plugin,mcp,voice,computer-use,windows,uiautomation
7
+ Classifier: Operating System :: Microsoft :: Windows
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ Requires-Dist: openai>=1.40
11
+ Requires-Dist: python-dotenv>=1.0
12
+ Requires-Dist: numpy>=1.26
13
+ Requires-Dist: sounddevice>=0.4.6
14
+ Requires-Dist: pyautogui>=0.9.54
15
+ Requires-Dist: pyperclip>=1.8
16
+ Requires-Dist: uiautomation>=2.0.18
17
+ Requires-Dist: pyttsx3>=2.90
18
+ Requires-Dist: pillow>=10.0
19
+ Requires-Dist: httpx>=0.27
20
+ Requires-Dist: mcp>=2.3
21
+ Provides-Extra: wake
22
+ Requires-Dist: sherpa-onnx>=1.10; extra == "wake"
23
+ Requires-Dist: pypinyin>=0.50; extra == "wake"
24
+
25
+ # AI OS
26
+
27
+ 用语音代替鼠标和键盘来操作 Windows 电脑。基于 DeepSeek(大模型、语音识别、语音合成),一个 API Key 即可运行。
28
+
29
+ 两种用法:
30
+
31
+ - **独立语音助手** `ai-os`:说“小爱,打开记事本写一首诗”,它会读取屏幕控件、点击、输入,并用语音汇报结果。
32
+ - **DeepSeek Harness 插件** `dsh-ai-os`:把桌面控制能力以 MCP 工具的形式提供给 DeepSeek Harness(也适用于 Claude Code、Cursor 等任何 MCP 客户端)。
33
+
34
+ ## 安装
35
+
36
+ ```sh
37
+ pip install ai-os-desktop
38
+ ```
39
+
40
+ ## 独立语音助手
41
+
42
+ 在任意目录创建 `.env`(参考 [.env.example](.env.example)),至少填写 `DEEPSEEK_API_KEY`,然后:
43
+
44
+ ```sh
45
+ ai-os # 语音模式
46
+ ai-os --text # 键盘输入指令,调试用
47
+ ai-os --once "打开设置调高亮度"
48
+ ```
49
+
50
+ 语音模式下屏幕顶部会显示一个状态条(待命 / 聆听 / 识别 / 思考 / 执行 / 说话),它不抢焦点、鼠标可以点穿;不需要时加 `--no-overlay`。
51
+
52
+ 唤醒词默认在本地离线识别,说出唤醒词之前的声音不会上传:
53
+
54
+ ```sh
55
+ pip install "ai-os-desktop[wake]"
56
+ python -m ai_os.wake # 下载唤醒模型(约 33 MB)
57
+ ```
58
+
59
+ 听到“嘀”一声后说指令;也可以一口气说“小爱,打开计算器”。没装本地模型时自动退回云端识别唤醒词。
60
+
61
+ ## 接入 DeepSeek Harness
62
+
63
+ ```sh
64
+ dsh plugin add dsh-ai-os
65
+ ```
66
+
67
+ 其他 MCP 客户端可直接把 `ai-os-mcp` 配置为 stdio 服务器。
68
+
69
+ 插件还在输入框旁加了一个语音对话按钮:按 **F8**(或点按钮)开始说话,说完自动发送;任务完成后朗读回复,随后几秒内可以直接接着说。朗读时按 F8 打断,Esc 取消。
70
+
71
+ 在别的程序里按 **Ctrl+Alt+Space** 也能用:它会把 DeepSeek Harness 拉到前台并开始听。这个热键由 `ai-os-mcp` 进程注册,所以依赖 Python 端正常运行。
72
+
73
+ `ai-os-mcp` 通过 MCP 提供 13 个桌面工具(读控件、点击、输入、按键、滚动、开应用/网址/文件、列窗口、切窗口、截图问视觉模型、等待)。它没有暴露命令执行工具,需要跑命令时由 DeepSeek Harness 自己的终端工具处理,走它自己的审批。
74
+
75
+ 如果 agent 还是去写 PowerShell 而不是用这些工具,在工作区放一个 `AGENTS.md` 说明优先用 `ai-os` 工具即可(本仓库根目录有一份可以直接参考),或重启 DeepSeek Harness 让工具列表和指令重新加载。
76
+
77
+ 语音识别复用 DeepSeek Harness 官方的**语音输入**插件(实验功能),无需另外配置 API Key:在侧栏**插件**中打开它,并按提示完成一次模型准备即可。插件页的「运行检查」会实地读取 MCP 状态:桌面工具连不上时这一行会变红并给出具体原因,不会假装正常。
78
+
79
+ ## 实测效果
80
+
81
+ 同一台 Windows 11 电脑、同样的 6 个桌面任务(计算器输入、计算器切换模式、系统设置切换深色模式、浏览器填写表单、资源管理器新建文件夹、记事本写入并保存),在 DeepSeek Harness 中分别关闭和开启 `dsh-ai-os` 运行,模型均为 `deepseek-flash`:
82
+
83
+ | | 仅 DeepSeek Harness | + dsh-ai-os |
84
+ |---|---|---|
85
+ | 成功率 | 6/6 | 6/6 |
86
+ | 耗时中位数 | 166 秒 | 26 秒 |
87
+ | 平均工具调用 | 12.3 次 | 9.2 次 |
88
+ | 平均 token 用量 | 648K | 326K |
89
+
90
+ 不装插件时,DeepSeek Harness 需要现写 PowerShell 脚本模拟按键、截图看图、再修改脚本;装上后直接按控件编号点击,每步只回传界面变化。每个任务各运行一次,测试于 2026-11-16。复现方法见 [benchmark](benchmark/__main__.py):`python -m benchmark run --mode off|on`。
91
+
92
+ 真实会话里差距更大。同一个「列出当前所有窗口」的请求:桌面工具不可用时用时 **17 分 10 秒、27 步**,因为它去写 `EnumWindows` 的 PowerShell,每步都撞上 `danger-full-access` 审批;桌面工具可用后 **3 秒**完成,且没有任何审批弹窗。「用记事本写下“你好,AI OS”并保存到桌面」这类带写入的任务,全程 14 步、无审批,落盘内容正确。
93
+
94
+ 另有 3 个更难的任务(确认弹窗、多标签页表单、300 项长列表中打开指定项并在详情窗口操作),用 `--only hard` 运行,结果通过测试程序自身的事件上报核验,无法靠改文件或注册表“作弊”。
95
+
96
+ ## 工作原理
97
+
98
+ 1. 本地模型(sherpa-onnx)持续监听唤醒词;唤醒后按音量切分语句,发送到 DeepSeek ASR 转成文字。
99
+ 2. 通过 Windows UI Automation 读取前台窗口的控件,编号后连同指令一起交给 `deepseek-flash`。
100
+ 3. 模型通过工具调用点击控件、输入文字、按快捷键、切换窗口;每步之后读取新的屏幕状态再决定下一步。
101
+ 4. 结果通过 DeepSeek TTS 朗读;网络不可用时退回 Windows 本地语音。
102
+
103
+ ## 安全
104
+
105
+ - 执行 PowerShell 命令前必须语音确认;删除、发送、付款等不可逆操作会先询问。
106
+ - 鼠标移到屏幕左上角立即中止当前操作。
107
+ - MCP 模式下不提供命令执行工具,交给宿主自己的审批流程。
108
+
109
+ ## 开发
110
+
111
+ ```sh
112
+ pip install -e .
113
+ python -m ai_os --text
114
+ python -m ai_os.mcp_server
115
+ ```
@@ -0,0 +1,91 @@
1
+ # AI OS
2
+
3
+ 用语音代替鼠标和键盘来操作 Windows 电脑。基于 DeepSeek(大模型、语音识别、语音合成),一个 API Key 即可运行。
4
+
5
+ 两种用法:
6
+
7
+ - **独立语音助手** `ai-os`:说“小爱,打开记事本写一首诗”,它会读取屏幕控件、点击、输入,并用语音汇报结果。
8
+ - **DeepSeek Harness 插件** `dsh-ai-os`:把桌面控制能力以 MCP 工具的形式提供给 DeepSeek Harness(也适用于 Claude Code、Cursor 等任何 MCP 客户端)。
9
+
10
+ ## 安装
11
+
12
+ ```sh
13
+ pip install ai-os-desktop
14
+ ```
15
+
16
+ ## 独立语音助手
17
+
18
+ 在任意目录创建 `.env`(参考 [.env.example](.env.example)),至少填写 `DEEPSEEK_API_KEY`,然后:
19
+
20
+ ```sh
21
+ ai-os # 语音模式
22
+ ai-os --text # 键盘输入指令,调试用
23
+ ai-os --once "打开设置调高亮度"
24
+ ```
25
+
26
+ 语音模式下屏幕顶部会显示一个状态条(待命 / 聆听 / 识别 / 思考 / 执行 / 说话),它不抢焦点、鼠标可以点穿;不需要时加 `--no-overlay`。
27
+
28
+ 唤醒词默认在本地离线识别,说出唤醒词之前的声音不会上传:
29
+
30
+ ```sh
31
+ pip install "ai-os-desktop[wake]"
32
+ python -m ai_os.wake # 下载唤醒模型(约 33 MB)
33
+ ```
34
+
35
+ 听到“嘀”一声后说指令;也可以一口气说“小爱,打开计算器”。没装本地模型时自动退回云端识别唤醒词。
36
+
37
+ ## 接入 DeepSeek Harness
38
+
39
+ ```sh
40
+ dsh plugin add dsh-ai-os
41
+ ```
42
+
43
+ 其他 MCP 客户端可直接把 `ai-os-mcp` 配置为 stdio 服务器。
44
+
45
+ 插件还在输入框旁加了一个语音对话按钮:按 **F8**(或点按钮)开始说话,说完自动发送;任务完成后朗读回复,随后几秒内可以直接接着说。朗读时按 F8 打断,Esc 取消。
46
+
47
+ 在别的程序里按 **Ctrl+Alt+Space** 也能用:它会把 DeepSeek Harness 拉到前台并开始听。这个热键由 `ai-os-mcp` 进程注册,所以依赖 Python 端正常运行。
48
+
49
+ `ai-os-mcp` 通过 MCP 提供 13 个桌面工具(读控件、点击、输入、按键、滚动、开应用/网址/文件、列窗口、切窗口、截图问视觉模型、等待)。它没有暴露命令执行工具,需要跑命令时由 DeepSeek Harness 自己的终端工具处理,走它自己的审批。
50
+
51
+ 如果 agent 还是去写 PowerShell 而不是用这些工具,在工作区放一个 `AGENTS.md` 说明优先用 `ai-os` 工具即可(本仓库根目录有一份可以直接参考),或重启 DeepSeek Harness 让工具列表和指令重新加载。
52
+
53
+ 语音识别复用 DeepSeek Harness 官方的**语音输入**插件(实验功能),无需另外配置 API Key:在侧栏**插件**中打开它,并按提示完成一次模型准备即可。插件页的「运行检查」会实地读取 MCP 状态:桌面工具连不上时这一行会变红并给出具体原因,不会假装正常。
54
+
55
+ ## 实测效果
56
+
57
+ 同一台 Windows 11 电脑、同样的 6 个桌面任务(计算器输入、计算器切换模式、系统设置切换深色模式、浏览器填写表单、资源管理器新建文件夹、记事本写入并保存),在 DeepSeek Harness 中分别关闭和开启 `dsh-ai-os` 运行,模型均为 `deepseek-flash`:
58
+
59
+ | | 仅 DeepSeek Harness | + dsh-ai-os |
60
+ |---|---|---|
61
+ | 成功率 | 6/6 | 6/6 |
62
+ | 耗时中位数 | 166 秒 | 26 秒 |
63
+ | 平均工具调用 | 12.3 次 | 9.2 次 |
64
+ | 平均 token 用量 | 648K | 326K |
65
+
66
+ 不装插件时,DeepSeek Harness 需要现写 PowerShell 脚本模拟按键、截图看图、再修改脚本;装上后直接按控件编号点击,每步只回传界面变化。每个任务各运行一次,测试于 2026-11-16。复现方法见 [benchmark](benchmark/__main__.py):`python -m benchmark run --mode off|on`。
67
+
68
+ 真实会话里差距更大。同一个「列出当前所有窗口」的请求:桌面工具不可用时用时 **17 分 10 秒、27 步**,因为它去写 `EnumWindows` 的 PowerShell,每步都撞上 `danger-full-access` 审批;桌面工具可用后 **3 秒**完成,且没有任何审批弹窗。「用记事本写下“你好,AI OS”并保存到桌面」这类带写入的任务,全程 14 步、无审批,落盘内容正确。
69
+
70
+ 另有 3 个更难的任务(确认弹窗、多标签页表单、300 项长列表中打开指定项并在详情窗口操作),用 `--only hard` 运行,结果通过测试程序自身的事件上报核验,无法靠改文件或注册表“作弊”。
71
+
72
+ ## 工作原理
73
+
74
+ 1. 本地模型(sherpa-onnx)持续监听唤醒词;唤醒后按音量切分语句,发送到 DeepSeek ASR 转成文字。
75
+ 2. 通过 Windows UI Automation 读取前台窗口的控件,编号后连同指令一起交给 `deepseek-flash`。
76
+ 3. 模型通过工具调用点击控件、输入文字、按快捷键、切换窗口;每步之后读取新的屏幕状态再决定下一步。
77
+ 4. 结果通过 DeepSeek TTS 朗读;网络不可用时退回 Windows 本地语音。
78
+
79
+ ## 安全
80
+
81
+ - 执行 PowerShell 命令前必须语音确认;删除、发送、付款等不可逆操作会先询问。
82
+ - 鼠标移到屏幕左上角立即中止当前操作。
83
+ - MCP 模式下不提供命令执行工具,交给宿主自己的审批流程。
84
+
85
+ ## 开发
86
+
87
+ ```sh
88
+ pip install -e .
89
+ python -m ai_os --text
90
+ python -m ai_os.mcp_server
91
+ ```
File without changes
@@ -0,0 +1,3 @@
1
+ from .cli import voice
2
+
3
+ voice()
@@ -0,0 +1,290 @@
1
+ import os
2
+ import subprocess
3
+ import time
4
+ import webbrowser
5
+ from typing import Callable
6
+
7
+ import pyautogui
8
+ import pyperclip
9
+ import uiautomation as auto
10
+ from openai import OpenAI
11
+
12
+ from .config import Config
13
+ from .screen import ScreenReader, screenshot_base64
14
+
15
+ pyautogui.PAUSE = 0.05
16
+ # Moving the mouse to the top-left corner aborts any running action.
17
+ pyautogui.FAILSAFE = True
18
+
19
+ APP_ALIASES = {
20
+ "记事本": "notepad", "notepad": "notepad",
21
+ "计算器": "calc", "calculator": "calc",
22
+ "画图": "mspaint",
23
+ "命令提示符": "cmd", "cmd": "cmd",
24
+ "终端": "wt", "terminal": "wt", "powershell": "powershell",
25
+ "资源管理器": "explorer", "文件管理器": "explorer", "此电脑": "explorer",
26
+ "设置": "ms-settings:", "系统设置": "ms-settings:",
27
+ "任务管理器": "taskmgr", "控制面板": "control",
28
+ }
29
+ KEY_ALIASES = {
30
+ "回车": "enter", "return": "enter", "escape": "esc", "退出键": "esc",
31
+ "control": "ctrl", "windows": "win", "空格": "space", "删除": "delete",
32
+ "退格": "backspace", "上": "up", "下": "down", "左": "left", "右": "right",
33
+ }
34
+ APP_WAIT_S = 8.0
35
+ SHELL_PROCESSES = {"searchhost", "startmenuexperiencehost", "shellexperiencehost", "textinputhost"}
36
+ YES_WORDS = ("确认", "确定", "是", "好", "可以", "执行", "对", "没问题", "yes", "ok")
37
+
38
+ ConfirmFn = Callable[[str], bool]
39
+ AskFn = Callable[[str], str]
40
+
41
+
42
+ def _fn(name: str, description: str, properties: dict | None = None, required: list[str] | None = None) -> dict:
43
+ return {
44
+ "type": "function",
45
+ "function": {
46
+ "name": name,
47
+ "description": description,
48
+ "parameters": {"type": "object", "properties": properties or {}, "required": required or []},
49
+ },
50
+ }
51
+
52
+
53
+ TOOLS = [
54
+ _fn("get_screen_elements", "重新读取前台窗口的可交互控件列表(带编号和坐标)。"),
55
+ _fn("click_element", "点击屏幕控件列表中编号为 id 的控件。",
56
+ {"id": {"type": "integer"},
57
+ "double": {"type": "boolean", "description": "是否双击"},
58
+ "right": {"type": "boolean", "description": "是否右键"}},
59
+ ["id"]),
60
+ _fn("click_xy", "按 look_at_screen 截图中的像素坐标点击。仅在控件列表里找不到目标时使用。",
61
+ {"x": {"type": "integer"}, "y": {"type": "integer"},
62
+ "double": {"type": "boolean"}, "right": {"type": "boolean"}},
63
+ ["x", "y"]),
64
+ _fn("type_text", "在当前焦点处输入文字(支持中文)。输入前确保已点击目标输入框。",
65
+ {"text": {"type": "string"},
66
+ "press_enter": {"type": "boolean", "description": "输入后是否按回车"}},
67
+ ["text"]),
68
+ _fn("press_keys", "按下快捷键或单个按键,例如 'ctrl+s'、'alt+tab'、'enter'、'win+d'。",
69
+ {"keys": {"type": "string"}, "times": {"type": "integer", "description": "重复次数,默认 1"}},
70
+ ["keys"]),
71
+ _fn("scroll", "在鼠标当前位置或指定控件上滚动。",
72
+ {"direction": {"type": "string", "enum": ["up", "down"]},
73
+ "amount": {"type": "integer", "description": "滚动格数,默认 5"},
74
+ "element_id": {"type": "integer", "description": "可选,滚动包含该控件的列表或区域"}},
75
+ ["direction"]),
76
+ _fn("open_app", "打开应用程序,例如 '记事本'、'微信'、'Chrome'、'设置'。",
77
+ {"name": {"type": "string"}}, ["name"]),
78
+ _fn("open_url", "用默认浏览器打开网址。搜索时可构造搜索引擎网址。",
79
+ {"url": {"type": "string"}}, ["url"]),
80
+ _fn("open_path", "用默认程序打开本地文件或文件夹。",
81
+ {"path": {"type": "string"}}, ["path"]),
82
+ _fn("list_windows", "列出所有已打开的窗口标题和所属进程。这就是完整的窗口清单,无需补充。"),
83
+ _fn("focus_window", "切换到标题包含关键字的窗口。",
84
+ {"keyword": {"type": "string"}}, ["keyword"]),
85
+ _fn("look_at_screen", "截图并让视觉模型回答关于屏幕内容的问题,可要求返回目标的像素坐标供 click_xy 使用。",
86
+ {"question": {"type": "string"}}, ["question"]),
87
+ _fn("run_powershell", "执行 PowerShell 命令并返回输出。会先向用户语音确认。",
88
+ {"command": {"type": "string"}, "reason": {"type": "string", "description": "用一句话向用户说明要做什么"}},
89
+ ["command", "reason"]),
90
+ _fn("wait", "等待界面加载。", {"seconds": {"type": "number"}}, ["seconds"]),
91
+ _fn("ask_user", "当指令有歧义或缺少信息时,语音询问用户并获得回答。",
92
+ {"question": {"type": "string"}}, ["question"]),
93
+ _fn("finish", "任务完成或无法继续时调用,summary 会被朗读给用户,应简短口语化。",
94
+ {"summary": {"type": "string"}}, ["summary"]),
95
+ ]
96
+
97
+ READ_ONLY_TOOLS = {"get_screen_elements", "list_windows", "look_at_screen", "ask_user", "finish", "wait"}
98
+
99
+
100
+ class Actions:
101
+ def __init__(self, cfg: Config, screen: ScreenReader, confirm: ConfirmFn, ask: AskFn):
102
+ self.screen = screen
103
+ self.confirm = confirm
104
+ self.ask = ask
105
+ self.vision_model = cfg.vision_model
106
+ self.vision_client = (OpenAI(api_key=cfg.vision_api_key, base_url=cfg.vision_base_url)
107
+ if cfg.vision_model else None)
108
+ self.screenshot_scale = 1.0
109
+
110
+ def dispatch(self, name: str, args: dict) -> str:
111
+ handler = getattr(self, f"do_{name}", None)
112
+ if handler is None:
113
+ return f"错误:未知工具 {name}"
114
+ try:
115
+ return handler(**args)
116
+ except pyautogui.FailSafeException:
117
+ raise
118
+ except Exception as e:
119
+ return f"错误:{type(e).__name__}: {e}"
120
+
121
+ def do_get_screen_elements(self) -> str:
122
+ return self.screen.snapshot()
123
+
124
+ def do_click_element(self, id: int, double: bool = False, right: bool = False) -> str:
125
+ element = self.screen.elements.get(id)
126
+ if element is None:
127
+ return f"错误:控件 {id} 不存在,请先调用 get_screen_elements 刷新。"
128
+ self._click(element.x, element.y, double, right)
129
+ return f"已点击 [{id}] {element.kind} \"{element.name}\""
130
+
131
+ def do_click_xy(self, x: int, y: int, double: bool = False, right: bool = False) -> str:
132
+ sx, sy = int(x / self.screenshot_scale), int(y / self.screenshot_scale)
133
+ self._click(sx, sy, double, right)
134
+ return f"已点击屏幕坐标 ({sx},{sy})"
135
+
136
+ @staticmethod
137
+ def _click(x: int, y: int, double: bool, right: bool) -> None:
138
+ pyautogui.click(x, y, clicks=2 if double else 1, interval=0.08,
139
+ button="right" if right else "left")
140
+
141
+ def do_type_text(self, text: str, press_enter: bool = False) -> str:
142
+ try:
143
+ previous = pyperclip.paste()
144
+ except Exception:
145
+ previous = None
146
+ pyperclip.copy(text)
147
+ time.sleep(0.05)
148
+ pyautogui.hotkey("ctrl", "v")
149
+ time.sleep(0.15)
150
+ if previous is not None:
151
+ pyperclip.copy(previous)
152
+ if press_enter:
153
+ pyautogui.press("enter")
154
+ return f"已输入:{text[:50]}"
155
+
156
+ def do_press_keys(self, keys: str, times: int = 1) -> str:
157
+ parts = [KEY_ALIASES.get(k.strip().lower(), k.strip().lower()) for k in keys.split("+")]
158
+ unknown = [k for k in parts if k not in pyautogui.KEYBOARD_KEYS]
159
+ if unknown:
160
+ return f"错误:无法识别的按键 {unknown}"
161
+ for _ in range(max(1, times)):
162
+ pyautogui.hotkey(*parts)
163
+ time.sleep(0.05)
164
+ return f"已按下 {'+'.join(parts)}" + (f" ×{times}" if times > 1 else "")
165
+
166
+ def do_scroll(self, direction: str, amount: int = 5, element_id: int | None = None) -> str:
167
+ label = f"已向{'上' if direction == 'up' else '下'}滚动 {amount} 格"
168
+ if element_id is not None and element_id in self.screen.elements:
169
+ element = self.screen.elements[element_id]
170
+ if _uia_scroll(element.x, element.y, direction, amount):
171
+ return label
172
+ pyautogui.moveTo(element.x, element.y)
173
+ pyautogui.scroll(120 * amount * (1 if direction == "up" else -1))
174
+ return label
175
+
176
+ def do_open_app(self, name: str) -> str:
177
+ existing = {w.handle for w in self.screen.list_windows()}
178
+ target = APP_ALIASES.get(name.strip()) or APP_ALIASES.get(name.strip().lower())
179
+ if target:
180
+ os.startfile(target)
181
+ how = "已启动"
182
+ else:
183
+ pyautogui.press("win")
184
+ time.sleep(0.8)
185
+ pyperclip.copy(name)
186
+ pyautogui.hotkey("ctrl", "v")
187
+ time.sleep(1.2)
188
+ pyautogui.press("enter")
189
+ how = "已通过开始菜单搜索并启动"
190
+
191
+ window = self._wait_for_new_window(existing)
192
+ if window:
193
+ self.screen.focus(window)
194
+ time.sleep(0.5)
195
+ return f"{how} {name},已切换到窗口:{window.title}"
196
+ # Single-instance apps (e.g. Notepad adding a tab) reuse their existing window.
197
+ focused = self.do_focus_window(name)
198
+ if not focused.startswith("错误"):
199
+ return f"{how} {name},{focused}"
200
+ return f"{how} {name},但 {APP_WAIT_S:.0f} 秒内没有出现新窗口,请用 list_windows 检查是否打开成功。"
201
+
202
+ def _wait_for_new_window(self, existing: set[int]):
203
+ deadline = time.monotonic() + APP_WAIT_S
204
+ while time.monotonic() < deadline:
205
+ time.sleep(0.5)
206
+ for window in self.screen.list_windows():
207
+ if window.handle not in existing and window.process not in SHELL_PROCESSES:
208
+ return window
209
+ return None
210
+
211
+ def do_open_url(self, url: str) -> str:
212
+ if not url.startswith(("http://", "https://")):
213
+ url = "https://" + url
214
+ webbrowser.open(url)
215
+ time.sleep(2.0)
216
+ return f"已打开 {url}"
217
+
218
+ def do_open_path(self, path: str) -> str:
219
+ path = os.path.expandvars(os.path.expanduser(path))
220
+ if not os.path.exists(path):
221
+ return f"错误:路径不存在 {path}"
222
+ os.startfile(path)
223
+ time.sleep(1.0)
224
+ return f"已打开 {path}"
225
+
226
+ def do_list_windows(self) -> str:
227
+ windows = self.screen.list_windows()
228
+ return "\n".join(f"- {w.title} ({w.process})" for w in windows) or "没有找到窗口"
229
+
230
+ def do_focus_window(self, keyword: str) -> str:
231
+ keyword_lower = keyword.strip().lower()
232
+ process = APP_ALIASES.get(keyword.strip(), keyword_lower)
233
+ for window in self.screen.list_windows():
234
+ if keyword_lower in window.title.lower() or process == window.process:
235
+ self.screen.focus(window)
236
+ time.sleep(0.5)
237
+ return f"已切换到窗口:{window.title}"
238
+ return f"错误:没有标题包含“{keyword}”的窗口,可调用 list_windows 查看。"
239
+
240
+ def do_look_at_screen(self, question: str) -> str:
241
+ if self.vision_client is None:
242
+ return "错误:未配置视觉模型(VISION_MODEL),请改用 get_screen_elements。"
243
+ image_b64, self.screenshot_scale, (w, h) = screenshot_base64()
244
+ prompt = (f"这是用户电脑的屏幕截图,尺寸 {w}x{h} 像素。{question}\n"
245
+ "如果涉及要点击的目标,请给出其中心点在这张图片中的像素坐标 (x, y)。")
246
+ response = self.vision_client.chat.completions.create(
247
+ model=self.vision_model,
248
+ messages=[{"role": "user", "content": [
249
+ {"type": "text", "text": prompt},
250
+ {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_b64}"}},
251
+ ]}],
252
+ )
253
+ return response.choices[0].message.content or "(视觉模型无返回)"
254
+
255
+ def do_run_powershell(self, command: str, reason: str) -> str:
256
+ if not self.confirm(f"我需要执行一条系统命令:{reason}。确认执行吗?"):
257
+ return "用户拒绝执行该命令。"
258
+ script = "[Console]::OutputEncoding=[Text.Encoding]::UTF8;" + command
259
+ result = subprocess.run(["powershell", "-NoProfile", "-Command", script],
260
+ capture_output=True, timeout=60)
261
+ output = (result.stdout + result.stderr).decode("utf-8", errors="replace").strip()
262
+ return f"退出码 {result.returncode}\n{output[:3000]}"
263
+
264
+ def do_wait(self, seconds: float) -> str:
265
+ time.sleep(min(max(seconds, 0), 10))
266
+ return f"已等待 {seconds} 秒"
267
+
268
+ def do_ask_user(self, question: str) -> str:
269
+ answer = self.ask(question)
270
+ return f"用户回答:{answer}" if answer else "用户没有回答。"
271
+
272
+
273
+ def _uia_scroll(x: int, y: int, direction: str, amount: int) -> bool:
274
+ """Scroll the nearest scrollable ancestor of the control at (x, y) without relying on mouse focus."""
275
+ control = auto.ControlFromPoint(x, y)
276
+ while control:
277
+ pattern = control.GetPattern(auto.PatternId.ScrollPattern)
278
+ if pattern and pattern.VerticallyScrollable:
279
+ step = auto.ScrollAmount.SmallDecrement if direction == "up" else auto.ScrollAmount.SmallIncrement
280
+ # One wheel notch scrolls three lines.
281
+ for _ in range(3 * amount):
282
+ pattern.Scroll(auto.ScrollAmount.NoAmount, step, waitTime=0)
283
+ return True
284
+ control = control.GetParentControl()
285
+ return False
286
+
287
+
288
+ def is_yes(answer: str) -> bool:
289
+ answer = answer.lower()
290
+ return any(word in answer for word in YES_WORDS) and not any(n in answer for n in ("不", "别", "取消", "no"))
@@ -0,0 +1,146 @@
1
+ import json
2
+ import time
3
+
4
+ import pyautogui
5
+ from openai import OpenAI
6
+
7
+ from .actions import READ_ONLY_TOOLS, TOOLS, Actions
8
+ from .config import Config
9
+ from .deepseek import is_deepseek
10
+ from .overlay import StatusFn, no_status
11
+ from .screen import ScreenReader
12
+ from .voice import Speaker
13
+
14
+ SCREEN_MARK = "\n\n=== 当前屏幕 ===\n"
15
+ TOOL_LABELS = {
16
+ "get_screen_elements": "读取屏幕", "click_element": "点击", "click_xy": "点击坐标",
17
+ "type_text": "输入", "press_keys": "按键", "scroll": "滚动", "open_app": "打开",
18
+ "open_url": "打开网址", "open_path": "打开", "list_windows": "查看窗口", "focus_window": "切换到",
19
+ "look_at_screen": "看屏幕", "run_powershell": "运行命令", "wait": "等待", "ask_user": "询问",
20
+ }
21
+ STALE_SCREEN = "\n\n(旧的屏幕状态已省略)"
22
+
23
+ SYSTEM_PROMPT = """你是一个运行在 Windows 电脑上的语音操作助手,用户完全通过语音控制电脑,不使用鼠标和键盘。
24
+ 你的任务是把用户的口语指令转化为一系列电脑操作并执行完成。
25
+
26
+ 工作方式:
27
+ - 每次操作后你会收到最新的屏幕控件列表,格式为 [编号] 类型 名称。
28
+ - 优先使用 click_element 按编号点击;控件列表里找不到目标时,再用 look_at_screen + click_xy。
29
+ - 善用快捷键(press_keys)和 open_app / open_url / focus_window,它们比逐个点击更可靠。
30
+ - 输入文字前先点击或聚焦目标输入框。
31
+ - 每一步后检查屏幕状态是否符合预期,不符合就调整策略,不要盲目重复同一个动作。
32
+ - 用户口述可能有同音错别字,请结合语境理解。
33
+ - 指令有歧义或缺少关键信息(如收件人、文件名)时,用 ask_user 询问。
34
+ - 删除文件、发送消息、付款、关机等不可逆操作,执行前先用 ask_user 确认。
35
+ - 完成后调用 finish,summary 用一两句口语化中文告诉用户结果。纯问答类问题(不需要操作电脑)也直接用 finish 回答。
36
+ """
37
+
38
+
39
+ class Agent:
40
+ def __init__(self, cfg: Config, speaker: Speaker, actions: Actions, screen: ScreenReader,
41
+ status: StatusFn = no_status):
42
+ self.client = OpenAI(api_key=cfg.llm_api_key, base_url=cfg.llm_base_url)
43
+ self.model = cfg.llm_model
44
+ self.extra_body = ({"thinking": {"type": cfg.llm_thinking}}
45
+ if is_deepseek(cfg.llm_base_url) and cfg.llm_thinking else None)
46
+ self.max_steps = cfg.max_steps
47
+ self.speaker = speaker
48
+ self.actions = actions
49
+ self.screen = screen
50
+ self.status = status
51
+
52
+ def run(self, command: str) -> None:
53
+ print(f"[用户] {command}")
54
+ self.command = command
55
+ messages: list[dict] = [
56
+ {"role": "system", "content": SYSTEM_PROMPT},
57
+ {"role": "user", "content": command + SCREEN_MARK + self.screen.snapshot()},
58
+ ]
59
+ try:
60
+ for _ in range(self.max_steps):
61
+ if self._step(messages):
62
+ return
63
+ self.speaker.say("步骤太多了,我先停下来。你可以换个说法再试一次。")
64
+ except pyautogui.FailSafeException:
65
+ self.speaker.say("已紧急停止。")
66
+ except Exception as e:
67
+ print(f"[错误] {type(e).__name__}: {e}")
68
+ self.speaker.say("出错了,请稍后再试。")
69
+
70
+ def _step(self, messages: list[dict]) -> bool:
71
+ """Runs one model turn; returns True when the task is finished."""
72
+ self.status("thinking", self.command)
73
+ response = self.client.chat.completions.create(
74
+ model=self.model, messages=messages, tools=TOOLS, tool_choice="auto", temperature=0.2,
75
+ extra_body=self.extra_body)
76
+ message = response.choices[0].message
77
+ tool_calls = message.tool_calls or []
78
+
79
+ entry: dict = {"role": "assistant", "content": message.content or ""}
80
+ # DeepSeek thinking mode requires the reasoning to be echoed back while tool calls are in flight.
81
+ reasoning = getattr(message, "reasoning_content", None)
82
+ if reasoning:
83
+ entry["reasoning_content"] = reasoning
84
+ if tool_calls:
85
+ entry["tool_calls"] = [
86
+ {"id": tc.id, "type": "function",
87
+ "function": {"name": tc.function.name, "arguments": tc.function.arguments}}
88
+ for tc in tool_calls
89
+ ]
90
+ messages.append(entry)
91
+
92
+ if not tool_calls:
93
+ self.speaker.say(message.content or "好的。")
94
+ return True
95
+
96
+ screen_changed = False
97
+ for tc in tool_calls:
98
+ name = tc.function.name
99
+ try:
100
+ args = json.loads(tc.function.arguments or "{}")
101
+ except json.JSONDecodeError:
102
+ args = {}
103
+
104
+ if name == "finish":
105
+ messages.append({"role": "tool", "tool_call_id": tc.id, "content": "ok"})
106
+ self.speaker.say(args.get("summary", "完成了。"))
107
+ return True
108
+
109
+ print(f" -> {name}({json.dumps(args, ensure_ascii=False)})")
110
+ self.status("acting", self._describe(name, args))
111
+ result = self.actions.dispatch(name, args)
112
+ print(f" {result.splitlines()[0] if result else ''}")
113
+ if name == "get_screen_elements":
114
+ result = SCREEN_MARK.lstrip() + result
115
+ screen_changed |= name not in READ_ONLY_TOOLS
116
+ messages.append({"role": "tool", "tool_call_id": tc.id, "content": result})
117
+
118
+ if screen_changed:
119
+ time.sleep(0.6)
120
+ messages[-1]["content"] += SCREEN_MARK + self.screen.snapshot()
121
+ _drop_stale_screens(messages)
122
+ return False
123
+
124
+ def _describe(self, name: str, args: dict) -> str:
125
+ verb = TOOL_LABELS.get(name, name)
126
+ if name == "click_element":
127
+ element = self.screen.elements.get(args.get("id"))
128
+ target = element.name or element.kind if element else ""
129
+ else:
130
+ target = next((str(args[k]) for k in ("name", "keyword", "text", "keys", "url", "path", "command")
131
+ if args.get(k)), "")
132
+ return f"{verb} {target}".strip()
133
+
134
+
135
+ def _drop_stale_screens(messages: list[dict]) -> None:
136
+ """Keeps only the latest screen snapshot in context to bound token usage."""
137
+ marker = SCREEN_MARK.strip()
138
+ seen_latest = False
139
+ for msg in reversed(messages):
140
+ content = msg.get("content")
141
+ if not isinstance(content, str) or marker not in content:
142
+ continue
143
+ if not seen_latest:
144
+ seen_latest = True
145
+ continue
146
+ msg["content"] = content.split(marker)[0].rstrip() + STALE_SCREEN
@@ -0,0 +1,13 @@
1
+ from .dpi import enable_dpi_awareness
2
+
3
+
4
+ def voice() -> None:
5
+ enable_dpi_awareness()
6
+ from .main import main
7
+ main()
8
+
9
+
10
+ def mcp() -> None:
11
+ enable_dpi_awareness()
12
+ from .mcp_server import main
13
+ main()