@hfyjq/crannia 1.1.2 → 1.2.0

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.
Files changed (306) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +48 -45
  3. package/README.md +1 -1
  4. package/THIRD-PARTY-FRONTEND.md +5266 -5266
  5. package/THIRD-PARTY-PYTHON-linux.md +174 -0
  6. package/THIRD-PARTY-PYTHON.md +176 -162
  7. package/THIRD-PARTY.md +323 -316
  8. package/apps/desktop/quotes.txt +56 -56
  9. package/bus/core.py +677 -671
  10. package/bus/loaders/channel_loader.py +64 -64
  11. package/bus/loaders/provider_loader.py +4 -7
  12. package/bus/loaders/skill_loader.py +46 -27
  13. package/bus/loaders/skill_md.py +9 -9
  14. package/bus/mcp_disabled.py +4 -6
  15. package/bus/quarantine.py +10 -13
  16. package/bus/registry.py +2315 -2284
  17. package/bus/skill_state.py +124 -124
  18. package/channels/cli_channel/handler.py +3 -3
  19. package/channels/cli_channel/manifest.yaml +5 -5
  20. package/channels/dingtalk_channel/handler.py +32 -32
  21. package/channels/dingtalk_channel/manifest.yaml +12 -12
  22. package/channels/feishu_channel/handler.py +33 -33
  23. package/channels/feishu_channel/manifest.yaml +12 -12
  24. package/channels/qq_bot_channel/__init__.py +1 -1
  25. package/channels/qq_bot_channel/handler.py +24 -24
  26. package/channels/qq_bot_channel/manifest.yaml +4 -4
  27. package/channels/telegram_channel/__init__.py +1 -1
  28. package/channels/telegram_channel/handler.py +21 -21
  29. package/channels/telegram_channel/manifest.yaml +4 -4
  30. package/channels/telegram_channel/media.py +231 -231
  31. package/channels/textfmt.py +58 -58
  32. package/channels/wechat_channel/__init__.py +1 -1
  33. package/channels/wechat_channel/converter.py +1 -1
  34. package/channels/wechat_channel/handler.py +8 -8
  35. package/channels/wechat_channel/manifest.yaml +5 -5
  36. package/channels/wechat_channel/media.py +178 -178
  37. package/core/activity.py +753 -709
  38. package/core/agent_loop.py +7673 -7522
  39. package/core/allowlist.py +2 -3
  40. package/core/approval.py +34 -24
  41. package/core/approval_timeout.py +256 -228
  42. package/core/artifacts.py +3 -3
  43. package/core/attachment_gc.py +21 -0
  44. package/core/auto_review.py +2 -2
  45. package/core/browser/cdp.py +5 -2
  46. package/core/browser/discover.py +55 -19
  47. package/core/browser/session.py +4 -4
  48. package/core/cache_break_detector.py +97 -0
  49. package/core/cache_breakpoints.py +103 -0
  50. package/core/cache_policies.py +255 -0
  51. package/core/cancellation.py +3 -3
  52. package/core/channel_configs.py +3 -3
  53. package/core/channel_turns.py +13 -13
  54. package/core/child_approval.py +2 -3
  55. package/core/code_intel.py +11 -11
  56. package/core/command_policy.py +13 -7
  57. package/core/computer/annotate.py +231 -11
  58. package/core/computer/capture.py +140 -1
  59. package/core/computer/guard.py +7 -4
  60. package/core/computer/input.py +452 -26
  61. package/core/computer/session.py +563 -381
  62. package/core/computer/tools.py +2170 -928
  63. package/core/computer/uia.py +100 -1
  64. package/core/computer/watch.py +1 -1
  65. package/core/computer/win32.py +302 -7
  66. package/core/config_requirements.py +205 -205
  67. package/core/cron/runner.py +4 -4
  68. package/core/daily_log.py +2 -2
  69. package/core/dedup.py +2 -2
  70. package/core/egress_channels.py +326 -0
  71. package/core/egress_gate.py +96 -8
  72. package/core/egress_preapproved.py +59 -3
  73. package/core/endpoint.py +141 -141
  74. package/core/events.py +17 -8
  75. package/core/extension.py +2 -2
  76. package/core/file_history.py +10 -10
  77. package/core/file_tools.py +3 -3
  78. package/core/github_config.py +1 -1
  79. package/core/group_digest.py +3 -4
  80. package/core/group_minutes.py +5 -5
  81. package/core/group_reply.py +24 -0
  82. package/core/groups.py +5 -9
  83. package/core/hooks.py +15 -15
  84. package/core/i18n.py +2 -2
  85. package/core/ice/canary.py +3 -3
  86. package/core/ice/net_heuristics.py +2 -2
  87. package/core/im_routing.py +2 -2
  88. package/core/image_input.py +183 -43
  89. package/core/inbound.py +3 -3
  90. package/core/jobs.py +6 -6
  91. package/core/last_good.py +150 -150
  92. package/core/leaf_md.py +3 -3
  93. package/core/llm_errors.py +36 -27
  94. package/core/mail_config.py +2 -2
  95. package/core/memory/compressor.py +8 -8
  96. package/core/memory/manager.py +30 -45
  97. package/core/memory/session_memory.py +1 -2
  98. package/core/memory/short_term.py +4 -4
  99. package/core/memory_extract.py +1 -1
  100. package/core/memory_organize.py +8 -8
  101. package/core/memory_store.py +7 -9
  102. package/core/memory_transfer.py +2 -2
  103. package/core/model_capabilities.py +2 -2
  104. package/core/model_configs.py +219 -68
  105. package/core/model_profiles.py +333 -0
  106. package/core/modes.py +12 -11
  107. package/core/net_proxy.py +3 -3
  108. package/core/pipeline/scheduler.py +48 -43
  109. package/core/pipeline/stage.py +3 -0
  110. package/core/pipeline/stages/agent_loop.py +36 -15
  111. package/core/pipeline/stages/group_reply.py +22 -20
  112. package/core/pipeline/stages/post_process.py +7 -7
  113. package/core/pipeline/stages/pre_process.py +360 -68
  114. package/core/prompt_assembler.py +13 -4
  115. package/core/recycle.py +227 -16
  116. package/core/response_language.py +1 -1
  117. package/core/retention.py +2 -2
  118. package/core/rg.py +4 -3
  119. package/core/security.py +26 -8
  120. package/core/services.py +8 -8
  121. package/core/session_model.py +3 -5
  122. package/core/session_pool.py +35 -5
  123. package/core/session_recap.py +40 -3
  124. package/core/session_workspace.py +2 -3
  125. package/core/settings_baseline.py +2 -2
  126. package/core/settings_transfer.py +25 -1
  127. package/core/shell.py +52 -20
  128. package/core/side_call.py +3 -3
  129. package/core/skill_config.py +164 -0
  130. package/core/skill_factory.py +2 -2
  131. package/core/skill_guidance.py +2 -4
  132. package/core/skill_index.py +3 -4
  133. package/core/skill_settings.py +1 -1
  134. package/core/skill_sources.py +7 -7
  135. package/core/ssh_config.py +129 -0
  136. package/core/state_registry.py +67 -5
  137. package/core/subagent.py +28 -5
  138. package/core/subagent_defs.py +3 -3
  139. package/core/summarizer.py +4 -5
  140. package/core/tasks_notify.py +6 -6
  141. package/core/tiers.py +2 -2
  142. package/core/todos.py +1 -1
  143. package/core/token_calibrator.py +1 -4
  144. package/core/tool_outcome.py +108 -108
  145. package/core/touched_files.py +1 -1
  146. package/core/trace.py +12 -3
  147. package/core/unlock.py +4 -4
  148. package/core/update_tui.py +184 -158
  149. package/core/updater.py +5 -3
  150. package/core/version.py +14 -14
  151. package/core/vision_budget.py +235 -0
  152. package/core/web_cache.py +152 -152
  153. package/core/web_request.py +474 -0
  154. package/core/window_estimate.py +1 -1
  155. package/core/workspace.py +56 -26
  156. package/crannia_tray.py +278 -278
  157. package/licenses/GPL-3.0.txt +619 -619
  158. package/licenses/LGPL-2.1.txt +502 -502
  159. package/licenses/LGPL-3.0.txt +165 -165
  160. package/licenses/MIT-chat-on-wechat.txt +18 -18
  161. package/licenses/MIT-deepseek-harness.txt +21 -21
  162. package/licenses/Molio-LICENSE.txt +44 -44
  163. package/locales/en.json +1876 -1755
  164. package/main.py +154 -154
  165. package/mcpx/client.py +12 -1
  166. package/mcpx/manager.py +530 -522
  167. package/mcpx/servers/web_search.py +5 -13
  168. package/package.json +15 -23
  169. package/providers/anthropic/client.py +35 -33
  170. package/providers/base.py +13 -13
  171. package/providers/cache_policies.json +294 -0
  172. package/providers/cost_table.json +3779 -3779
  173. package/providers/lmstudio/client.py +2 -2
  174. package/providers/model_capabilities.json +6665 -6665
  175. package/providers/model_profiles.json +629 -0
  176. package/providers/ollama/client.py +2 -2
  177. package/providers/openai_compat.py +37 -16
  178. package/providers/openrouter/client.py +2 -2
  179. package/providers/qwen/__init__.py +1 -1
  180. package/providers/qwen/client.py +2 -2
  181. package/providers/qwen/manifest.yaml +16 -16
  182. package/providers/rate_limiter.py +2 -2
  183. package/providers/siliconflow/client.py +2 -2
  184. package/providers/validation.py +171 -171
  185. package/providers/vision_profiles.json +89 -0
  186. package/providers/window_table.json +8909 -8909
  187. package/requirements.txt +59 -51
  188. package/sbom-linux-x64.json +4580 -0
  189. package/sbom.json +4600 -4413
  190. package/skills/diagram/SKILL.md +47 -0
  191. package/skills/diagram/__init__.py +1 -0
  192. package/skills/diagram/handler.py +294 -0
  193. package/skills/diagram/layout.py +174 -0
  194. package/skills/diagram/manifest.yaml +106 -0
  195. package/skills/diagram/mermaid.py +170 -0
  196. package/skills/diagram/svg.py +223 -0
  197. package/skills/entertainment/SKILL.md +35 -35
  198. package/skills/entertainment/__init__.py +1 -1
  199. package/skills/entertainment/handler.py +91 -91
  200. package/skills/entertainment/manifest.yaml +26 -26
  201. package/skills/file_parser/GUIDANCE.md +10 -10
  202. package/skills/file_parser/handler.py +33 -11
  203. package/skills/github/SKILL.md +32 -32
  204. package/skills/github/__init__.py +1 -1
  205. package/skills/mail_parser/SKILL.md +68 -68
  206. package/skills/mail_parser/__init__.py +1 -1
  207. package/skills/mail_parser/handler.py +1 -1
  208. package/skills/media_gen/GUIDANCE.md +19 -19
  209. package/skills/media_gen/SKILL.md +43 -43
  210. package/skills/media_gen/__init__.py +1 -1
  211. package/skills/media_gen/handler.py +1 -1
  212. package/skills/media_gen/manifest.yaml +93 -93
  213. package/skills/netops/SKILL.md +45 -0
  214. package/skills/netops/__init__.py +1 -0
  215. package/skills/netops/handler.py +418 -0
  216. package/skills/netops/manifest.yaml +118 -0
  217. package/skills/office_parser/_excel_io.py +3 -3
  218. package/skills/office_parser/handler.py +2 -2
  219. package/skills/office_parser/ppt_tools.py +1 -1
  220. package/skills/office_parser/pptx_export/console_encoding.py +27 -27
  221. package/skills/office_parser/pptx_export/resource_paths.py +88 -88
  222. package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
  223. package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
  224. package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
  225. package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
  226. package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
  227. package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
  228. package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
  229. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
  230. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
  231. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
  232. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
  233. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/utils.py +40 -21
  234. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
  235. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
  236. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
  237. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
  238. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
  239. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
  240. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
  241. package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
  242. package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
  243. package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
  244. package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
  245. package/skills/office_parser/references/layout_library.md +816 -816
  246. package/skills/office_parser/references/ppt-master/LICENSE +21 -21
  247. package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
  248. package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
  249. package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
  250. package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
  251. package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
  252. package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
  253. package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
  254. package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
  255. package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
  256. package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
  257. package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
  258. package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
  259. package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
  260. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
  261. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
  262. package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
  263. package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
  264. package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
  265. package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
  266. package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
  267. package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
  268. package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
  269. package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
  270. package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
  271. package/skills/office_parser/references/spec_lock.md +235 -235
  272. package/skills/office_parser/soffice.py +68 -68
  273. package/skills/office_parser/word_tools.py +3 -3
  274. package/skills/ssh/SKILL.md +81 -0
  275. package/skills/ssh/__init__.py +1 -0
  276. package/skills/ssh/handler.py +609 -0
  277. package/skills/ssh/manifest.yaml +182 -0
  278. package/tui/crannia.cmd +134 -134
  279. package/tui/crannia.sh +82 -0
  280. package/tui/crannia_tui/__init__.py +1 -1
  281. package/tui/crannia_tui/app.py +240 -17
  282. package/tui/crannia_tui/app.tcss +21 -0
  283. package/tui/crannia_tui/clipboard.py +78 -10
  284. package/tui/crannia_tui/commands.py +37 -0
  285. package/tui/crannia_tui/events.py +6 -0
  286. package/tui/crannia_tui/i18n.py +164 -164
  287. package/tui/crannia_tui/locales/en.json +31 -6
  288. package/tui/crannia_tui/paths.py +4 -1
  289. package/tui/crannia_tui/profile.py +178 -169
  290. package/tui/crannia_tui/settings.py +134 -134
  291. package/tui/crannia_tui/setup.py +44 -5
  292. package/tui/crannia_tui/ui.py +156 -16
  293. package/tui/crannia_tui/update.py +393 -389
  294. package/vendor/ripgrep/COPYING.txt +3 -3
  295. package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
  296. package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
  297. package/vendor/ripgrep/README.md +30 -14
  298. package/vendor/ripgrep/UNLICENSE.txt +24 -24
  299. package/vendor/ripgrep/linux-x64/rg +0 -0
  300. package/vendor/ripgrep/package-source.json +15 -16
  301. package/web/__main__.py +12 -15
  302. package/web/server.py +8481 -8594
  303. package/web/static/img/channel-telegram.svg +1 -1
  304. package/web/static/img/channel-wechat.svg +1 -1
  305. package/web/templates/logs.html +49 -49
  306. package/web/templates/models.html +46 -46
@@ -17,6 +17,7 @@ from __future__ import annotations
17
17
  import ctypes
18
18
  import sys
19
19
  import time
20
+ from contextlib import contextmanager
20
21
  from ctypes import wintypes
21
22
 
22
23
  from . import win32
@@ -176,6 +177,18 @@ def parse_combo(combo: str) -> list[str]:
176
177
  return out
177
178
 
178
179
 
180
+ #: 单字符标点 -> 虚拟键码。快捷键里写 `ctrl+'` 比 `ctrl+quote` 自然,
181
+ #: 而 `parse_combo` 不会替它查英文名 —— 没有这张表就只有英文名能用。
182
+ #: 实测留档(2026-11-27 订正):Photoshop 的 `Ctrl+'`(视图 > 显示 > 网格)
183
+ #: 这条快捷键人手动也按不出来(用户实测),所以"发不进去"不是注入的问题;
184
+ #: 同一条路发 `Ctrl+Shift+;` 是生效的,标点键本身没问题。这类快捷键请走菜单,
185
+ #: 别在按键上花时间。
186
+ _SYMBOL_VK: dict[str, int] = {
187
+ "'": 0xDE, ",": 0xBC, "-": 0xBD, ".": 0xBE, "/": 0xBF, ";": 0xBA,
188
+ "=": 0xBB, "`": 0xC0, "[": 0xDB, "\\": 0xDC, "]": 0xDD,
189
+ }
190
+
191
+
179
192
  def _vk_of(token: str) -> tuple[int, bool]:
180
193
  """返回 `(虚拟键码, 是否扩展键)`。"""
181
194
  if token in _VK:
@@ -184,6 +197,8 @@ def _vk_of(token: str) -> tuple[int, bool]:
184
197
  ch = token.upper()
185
198
  if "A" <= ch <= "Z" or "0" <= ch <= "9":
186
199
  return ord(ch), False
200
+ if token in _SYMBOL_VK:
201
+ return _SYMBOL_VK[token], False
187
202
  if token.startswith("vk_"):
188
203
  try:
189
204
  return int(token[3:], 0), False
@@ -193,9 +208,32 @@ def _vk_of(token: str) -> tuple[int, bool]:
193
208
 
194
209
 
195
210
  # 事件构造
211
+ #: 虚拟键 -> scan code 的缓存。
212
+ #:
213
+ #: 只发 `wVk` 而不发 `wScan` 时,事件能到窗口,但接收方拿不到"是哪个键"
214
+ #: (文本控件收到的键名是空的);修饰键状态仍然对 —— 那是按 VK 读的。
215
+ #: 所以坏的那一半只表现为"普通按键不起作用",看起来像键盘根本没发出去。
216
+ _SCAN_CACHE: dict[int, int] = {}
217
+
218
+
219
+ def _scan_of(vk: int) -> int:
220
+ """虚拟键码 -> scan code。查不到回 0(那时退回只发 VK)。"""
221
+ try:
222
+ got = _SCAN_CACHE.get(int(vk))
223
+ if got is None:
224
+ got = int(win32.user32.MapVirtualKeyW(int(vk), 0)) # MAPVK_VK_TO_VSC
225
+ _SCAN_CACHE[int(vk)] = got
226
+ return got
227
+ except Exception: # noqa: BLE001
228
+ return 0
229
+
230
+
196
231
  def _key_event(vk: int, flags: int, scan: int = 0) -> "INPUT":
197
232
  ev = INPUT()
198
233
  ev.type = INPUT_KEYBOARD
234
+ #: `KEYEVENTF_UNICODE` 那一支的 scan 是字符本身,`wVk` 必须是 0 —— 不许改写。
235
+ if scan == 0 and vk and not (flags & KEYEVENTF_UNICODE):
236
+ scan = _scan_of(vk)
199
237
  ev.u.ki = KEYBDINPUT(wVk=vk, wScan=scan, dwFlags=flags, time=0, dwExtraInfo=0)
200
238
  return ev
201
239
 
@@ -241,13 +279,78 @@ def move_to(x: int, y: int) -> None:
241
279
  time.sleep(0.02)
242
280
 
243
281
 
244
- def _button_flags(button: str) -> tuple[int, int]:
282
+ def _button_flags(button: str) -> tuple[int, int, int]:
283
+ """返回 `(down_flag, up_flag, mouseData)`。
284
+
285
+ 侧键不用(不是所有鼠标都有),但保留 mouseData 位是为了让
286
+ left/right/middle 与 XDOWN/XUP 共用一条发送路径,将来要扩也只改这张表。
287
+ """
245
288
  button = (button or "left").lower()
246
289
  return {
247
- "left": (MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP),
248
- "right": (MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP),
249
- "middle": (MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP),
250
- }.get(button, (MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP))
290
+ "left": (MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, 0),
291
+ "right": (MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP, 0),
292
+ "middle": (MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP, 0),
293
+ }.get(button, (MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, 0))
294
+
295
+
296
+ def button_down(button: str) -> None:
297
+ """只按下鼠标键,不松开。供脚本的 down/up 与多键拖用。"""
298
+ down, _up, data = _button_flags(button)
299
+ _send([_mouse_event(down, data=data)])
300
+
301
+
302
+ def button_up(button: str) -> None:
303
+ _down, up, data = _button_flags(button)
304
+ _send([_mouse_event(up, data=data)])
305
+
306
+
307
+ #: 修饰键按下后、与松开前的静置时间(秒)。
308
+ #:
309
+ #: 为什么必须有:`SendInput` 是一串独立调用,`held_keys` 的按下、
310
+ #: 动作里的鼠标事件、`finally` 里的松开之间只隔几微秒。消息循环快的
311
+ #: 程序当场就处理完;但重绘重、循环慢的程序常把鼠标事件压到下一帧
312
+ #: 再读键盘状态 —— 那时修饰键已经抬了,表现为"动作生效了,但修饰键
313
+ #: 没生效"(选中态没跟着变,只有指针挪过去)。人手按住修饰键时会保持
314
+ #: 几百毫秒,所以人工操作从不复现这一档。
315
+ KEY_SETTLE = 0.04
316
+ KEY_RELEASE_SETTLE = 0.06
317
+
318
+ #: 连按同一个键时,两次完整按下之间的距离。取值按人手连按的节奏,
319
+ #: 让重绘慢的程序有机会处理完上一次按下/松开。
320
+ #: 它不是"防丢键"的开关:实测有程序对连按次数本身有阈值,把间隔拉到
321
+ #: 300 ms 照样整批失效 —— 那不是时序能解决的,只能分成几次按。
322
+ REPEAT_GAP = 0.06
323
+
324
+
325
+ @contextmanager
326
+ def held_keys(combo: str, *, settle: float = KEY_SETTLE,
327
+ release_settle: float = KEY_RELEASE_SETTLE):
328
+ """按住修饰键执行一段动作,退出时逆序释放——异常也走 finally。
329
+
330
+ 修饰键跟随单次动作(不跨轮持有):调用者把 click/drag/scroll 包在
331
+ `with held_keys("ctrl+shift")` 里,就不会出现"模型忘了松开"的卡键。
332
+ 护栏在 tools 层过 guard.combo_decision,这里只管按下与释放。
333
+
334
+ `settle` / `release_settle` 见上面那两个常量的注释:它们是给目标应用
335
+ 读键盘状态用的,不是给我们自己。脚本里每一步都带修饰键时可以传小一点
336
+ (`_run_script` 就这么做——那里一次脚本最多 64 步,全按默认会白等几秒)。
337
+ """
338
+ tokens = parse_combo(combo)
339
+ if not tokens:
340
+ yield []
341
+ return
342
+ vks = [(_vk_of(t)) for t in tokens]
343
+ for vk, ext in vks:
344
+ _send([_key_event(vk, KEYEVENTF_EXTENDEDKEY if ext else 0)])
345
+ if settle > 0:
346
+ time.sleep(settle)
347
+ try:
348
+ yield tokens
349
+ finally:
350
+ if release_settle > 0:
351
+ time.sleep(release_settle)
352
+ for vk, ext in reversed(vks):
353
+ _send([_key_event(vk, KEYEVENTF_KEYUP | (KEYEVENTF_EXTENDEDKEY if ext else 0))])
251
354
 
252
355
 
253
356
  @win32.dpi_wrapped
@@ -271,13 +374,13 @@ def _legacy_click(x: int, y: int, *, button: str = "left", count: int = 1) -> No
271
374
  """`SetCursorPos` + `mouse_event` —— 与 SendInput 并存的那条路。"""
272
375
  if not win32.IS_WINDOWS:
273
376
  raise InputError("接管模式只支持 Windows 桌面(当前系统 %s)" % sys.platform)
274
- down, up = _button_flags(button)
377
+ down, up, data = _button_flags(button)
275
378
  n = max(1, min(3, int(count or 1)))
276
379
  _legacy_move_to(int(x), int(y))
277
380
  for i in range(n):
278
- win32.user32.mouse_event(down, 0, 0, 0, 0)
381
+ win32.user32.mouse_event(down, 0, 0, data, 0)
279
382
  time.sleep(0.01)
280
- win32.user32.mouse_event(up, 0, 0, 0, 0)
383
+ win32.user32.mouse_event(up, 0, 0, data, 0)
281
384
  if i + 1 < n:
282
385
  time.sleep(0.05)
283
386
 
@@ -304,18 +407,18 @@ def click(x: int, y: int, *, button: str = "left", count: int = 1,
304
407
  if req == "legacy":
305
408
  _legacy_click(x, y, button=button, count=n)
306
409
  return "legacy"
307
- down, up = _button_flags(button)
410
+ down, up, data = _button_flags(button)
308
411
  try:
309
412
  move_to(x, y)
310
413
  for i in range(n):
311
- _send([_mouse_event(down), _mouse_event(up)])
414
+ _send([_mouse_event(down, data=data), _mouse_event(up, data=data)])
312
415
  if i + 1 < n:
313
416
  time.sleep(0.05)
314
417
  return "sendinput"
315
418
  except InputError:
316
419
  if req not in ("", "auto"):
317
420
  raise
318
- print("[input] SendInput 点击失败,退到 legacy 真实鼠标")
421
+ print("[input] SendInput click failed, falling back to legacy real mouse")
319
422
  _legacy_click(x, y, button=button, count=n)
320
423
  return "legacy"
321
424
 
@@ -335,15 +438,21 @@ def scroll(x: int, y: int, *, vertical: int = 0, horizontal: int = 0) -> None:
335
438
 
336
439
 
337
440
  @win32.dpi_wrapped
338
- def drag(x1: int, y1: int, x2: int, y2: int, *, duration: float = 0.3) -> None:
441
+ def drag(x1: int, y1: int, x2: int, y2: int, *, duration: float = 0.3,
442
+ button: str = "left") -> None:
443
+ """两点间拖拽。button 换成中键/右键就是 3D 软件的平移/旋转导航。"""
444
+ down, up, data = _button_flags(button)
339
445
  move_to(x1, y1)
340
- _send([_mouse_event(MOUSEEVENTF_LEFTDOWN)])
341
- steps = max(2, min(30, int(duration / 0.02)))
342
- for i in range(1, steps + 1):
343
- t = i / steps
344
- move_to(int(x1 + (x2 - x1) * t), int(y1 + (y2 - y1) * t))
345
- time.sleep(max(0.0, duration / steps - 0.02))
346
- _send([_mouse_event(MOUSEEVENTF_LEFTUP)])
446
+ _send([_mouse_event(down, data=data)])
447
+ try:
448
+ steps = max(2, min(30, int(duration / 0.02)))
449
+ for i in range(1, steps + 1):
450
+ t = i / steps
451
+ move_to(int(x1 + (x2 - x1) * t), int(y1 + (y2 - y1) * t))
452
+ time.sleep(max(0.0, duration / steps - 0.02))
453
+ finally:
454
+ # 中途异常也要松开,否则目标软件会一直以为键还按着。
455
+ _send([_mouse_event(up, data=data)])
347
456
 
348
457
 
349
458
  def type_text(text: str) -> None:
@@ -466,21 +575,338 @@ def press_key(combo: str, *, backend: str = "auto") -> list[str]:
466
575
  _legacy_press_key(tokens)
467
576
  return tokens
468
577
  vks = [(_vk_of(t)) for t in tokens]
469
- events: list["INPUT"] = []
470
- for vk, ext in vks: # 按下:从左到右
471
- events.append(_key_event(vk, KEYEVENTF_EXTENDEDKEY if ext else 0))
472
- for vk, ext in reversed(vks): # 松开:从右到左
473
- events.append(_key_event(vk, KEYEVENTF_KEYUP | (KEYEVENTF_EXTENDEDKEY if ext else 0)))
578
+ down = [_key_event(vk, KEYEVENTF_EXTENDEDKEY if ext else 0)
579
+ for vk, ext in vks] # 按下:从左到右
580
+ up = [_key_event(vk, KEYEVENTF_KEYUP | (KEYEVENTF_EXTENDEDKEY if ext else 0))
581
+ for vk, ext in reversed(vks)] # 松开:从右到左
474
582
  try:
475
- _send(events)
583
+ #: 按下与松开分两次发,中间留一段时间。挤在同一次调用里时,
584
+ #: 重绘重的程序处理到 keydown 时 keyup 已经躺在队列里 —— 快捷键
585
+ #: 常常因此不触发(人手按键天然有几十毫秒的持续)。
586
+ _send(down)
587
+ if KEY_SETTLE > 0:
588
+ time.sleep(KEY_SETTLE)
589
+ _send(up)
476
590
  except InputError:
591
+ #: 部分发送时可能有 down 已经进队列、up 被拦 —— 键会卡住。
592
+ #: 先补一次 up(对没按下的键松开无害),再决定要不要退 legacy。
593
+ try:
594
+ _send(up)
595
+ except InputError:
596
+ pass
477
597
  if req not in ("", "auto"):
478
598
  raise
479
- print("[input] SendInput 按键失败,退到 legacy keybd_event")
599
+ print("[input] SendInput key failed, falling back to legacy keybd_event")
480
600
  _legacy_press_key(tokens)
481
601
  return tokens
482
602
 
483
603
 
604
+ VK_CAPITAL = 0x14
605
+
606
+ #: 中文输入法的 LANGID(简/繁/香港/新加坡)。这些布局下字母键可能被 IME
607
+ #: 截获成候选框;英文布局不会,所以不必碰大写锁定。
608
+ _CJK_LANGIDS = frozenset({0x0804, 0x0404, 0x0C04, 0x1004})
609
+ #: 英语(美国)—— 临时切换的目标布局,只认已安装的那份。
610
+ EN_US_LANGID = 0x0409
611
+
612
+
613
+ def caps_lock_on() -> bool | None:
614
+ """大写锁定现在开着吗?读不到返回 `None`(不猜)。
615
+
616
+ 低 bit 是开关态(caps / num / scroll),这是 `GetKeyState` 的文档语义;
617
+ `GetAsyncKeyState` 的低 bit 是"上次查询之后按过",两者不是一件事,
618
+ 别替换。代价是它按线程的消息队列取值 —— 后台线程可能读到旧值,所以
619
+ 读数里拿不准时一律写"读不到",不猜成"关"。
620
+ """
621
+ if not win32.IS_WINDOWS:
622
+ return None
623
+ try:
624
+ return bool(int(win32.user32.GetKeyState(VK_CAPITAL)) & 0x0001)
625
+ except Exception: # noqa: BLE001
626
+ return None
627
+
628
+
629
+ def needs_ime_bypass(tokens: list[str]) -> bool:
630
+ """这个组合键会不会被输入法截获(=值不值得为它临时开大写锁定)。
631
+
632
+ 只认"没有修饰键的单字母"。实测:`Ctrl+1` / `Ctrl+0` / `Alt+F` 都原样
633
+ 到达目标窗口,`Tab` / `F10` 也一样 —— 输入法截获的是裸字母(拿去拼
634
+ 候选框)。给别的键也开大写锁定,只会让用户的指示灯闪一下、外加两次
635
+ 多余的注入。
636
+ """
637
+ if len(tokens) != 1:
638
+ return False
639
+ tok = tokens[0]
640
+ return len(tok) == 1 and "a" <= tok <= "z"
641
+
642
+
643
+ #: 常见键盘布局的 LANGID -> 给人看的名字。只列会进"读数"的那几类;
644
+ #: 其余按 `0xXXXX` 原样报出 —— 不猜语言。
645
+ _LANG_NAMES = {
646
+ 0x0409: "英语(美国)",
647
+ 0x0804: "中文(简体)",
648
+ 0x0404: "中文(繁体)",
649
+ 0x0C04: "中文(香港)",
650
+ 0x1004: "中文(新加坡)",
651
+ 0x0411: "日语",
652
+ 0x0412: "韩语",
653
+ }
654
+
655
+
656
+ def keyboard_layout(hwnd: int | None = None) -> tuple[int, str] | None:
657
+ """目标窗口线程的键盘布局 `(langid, 名字)`;读不到返回 None。
658
+
659
+ 必须按目标窗口的线程取。`GetKeyboardLayout(0)` 问的是调用线程,
660
+ 而框架跑在后台工作线程里 —— 那个线程的布局可能一直停在进程启动时,
661
+ 与用户此刻在目标应用里用的输入法无关(症状:中文输入法在吃键,框架
662
+ 却判成英文布局,大写锁定旁路因此从不触发)。
663
+ """
664
+ if not win32.IS_WINDOWS:
665
+ return None
666
+ hkl = None
667
+ try:
668
+ if hwnd:
669
+ hkl = win32.keyboard_layout_of(hwnd)
670
+ else:
671
+ hkl = int(win32.user32.GetKeyboardLayout(0) or 0)
672
+ except Exception: # noqa: BLE001
673
+ return None
674
+ langid = int(hkl or 0) & 0xFFFF
675
+ if not langid:
676
+ return None
677
+ return langid, _LANG_NAMES.get(langid, "0x%04X" % langid)
678
+
679
+
680
+ def ime_may_intercept(hwnd: int | None = None) -> bool:
681
+ """目标窗口的布局是不是中文(IME 可能把字母键转成候选框)。
682
+
683
+ *hwnd* 不给时退回调用线程的布局 —— 只为兼容旧调用点与测试;
684
+ 真实动作一律传目标窗口。
685
+ """
686
+ lay = keyboard_layout(hwnd)
687
+ return bool(lay and lay[0] in _CJK_LANGIDS)
688
+
689
+
690
+ def ime_open(hwnd: int) -> bool | None:
691
+ """目标窗口的输入法此刻开着吗?读不到返回 None(不猜)。
692
+
693
+ TSF 系输入法(如搜狗)不归 IMM32 管:`ImmGetContext` 可能拿不到
694
+ 上下文,或拿得到但开关状态与用户看到的候选框无关 —— 那种情况如实
695
+ 报"读不到",不拿它当"输入法是关的"。
696
+ """
697
+ if not win32.IS_WINDOWS:
698
+ return None
699
+ himc = None
700
+ try:
701
+ imm = ctypes.windll.imm32
702
+ himc = imm.ImmGetContext(int(hwnd))
703
+ if not himc:
704
+ return None
705
+ return bool(imm.ImmGetOpenStatus(himc))
706
+ except Exception: # noqa: BLE001
707
+ return None
708
+ finally:
709
+ if himc:
710
+ try:
711
+ ctypes.windll.imm32.ImmReleaseContext(int(hwnd), himc)
712
+ except Exception: # noqa: BLE001
713
+ pass
714
+
715
+
716
+ #: 会"卡住"的修饰键 / 鼠标键 —— 读数里报出来,让模型知道有没有残留的
717
+ #: 按下状态(框架自己的 finally 会松,但崩溃 / 外部注入可能留下)。
718
+ _HELD_VKS = ((0x11, "ctrl"), (0x10, "shift"), (0x12, "alt"),
719
+ (0x5B, "win"), (0x5C, "win"), (0x01, "鼠标左键"),
720
+ (0x02, "鼠标右键"), (0x04, "鼠标中键"))
721
+
722
+
723
+ def pressed_keys() -> list[str] | None:
724
+ """此刻还按着的修饰键 / 鼠标键;读不到返回 None(不猜成"没有")。"""
725
+ if not win32.IS_WINDOWS:
726
+ return None
727
+ try:
728
+ out: list[str] = []
729
+ for vk, name in _HELD_VKS:
730
+ down = win32.key_is_down(vk)
731
+ if down is None: # 读不到 ≠ 没按着
732
+ return None
733
+ if down and name not in out:
734
+ out.append(name)
735
+ return out
736
+ except Exception: # noqa: BLE001
737
+ return None
738
+
739
+
740
+ def keyboard_focus(hwnd: int) -> dict | None:
741
+ """目标线程此刻的键盘焦点是不是"在目标窗口里"。
742
+
743
+ 返回 `{"active": "类名「标题」", "within": bool}`;读不到返回 None。
744
+ 判据是活动窗口的根窗口 == 目标窗口。活动窗口是另一个顶层窗口
745
+ (例如 Photoshop 的浮动操作栏 `OS_ViewContainer`)时,键盘事件不会到
746
+ 目标窗口 —— 而"前台"仍可能是目标窗口,两者不是一件事。
747
+ """
748
+ if not win32.IS_WINDOWS:
749
+ return None
750
+ tid = win32.thread_id_of(hwnd)
751
+ active, _focus = win32.thread_focus(tid)
752
+ if not active:
753
+ return None
754
+ try:
755
+ within = win32.root_of(active) == int(hwnd)
756
+ except Exception: # noqa: BLE001
757
+ return None
758
+ return {"active": win32.window_brief(active),
759
+ "class": win32.class_name_of(active),
760
+ "within": bool(within)}
761
+
762
+
763
+ def input_context(hwnd: int) -> dict:
764
+ """按目标窗口读一组事实(回执的「框架读数」段用它;从不抛)。
765
+
766
+ 五个格:`layout` / `ime_open` / `caps` / `held` / `focus`。读不到的格
767
+ 是 None —— 调用方必须把 None 渲染成"读不到",不许当成 False。
768
+ """
769
+ return {
770
+ "layout": keyboard_layout(hwnd),
771
+ "ime_open": ime_open(hwnd),
772
+ "caps": caps_lock_on(),
773
+ "held": pressed_keys(),
774
+ "focus": keyboard_focus(hwnd),
775
+ }
776
+
777
+
778
+ @contextmanager
779
+ def caps_lock_guard(active: bool):
780
+ """必要时临时打开大写锁定,退出时按原状态还原。
781
+
782
+ 为什么有用:中文输入法在大写模式下不把字母键转成候选框,而目标程序的
783
+ 快捷键不区分大小写 —— 这是"不用换输入法"的一条旁路。
784
+
785
+ 什么时候动它:调用方说需要(中文布局)且现在确实关着。读不到状态
786
+ (`None`)时不动 —— 不知道用户原本什么状态,就不该改。
787
+ """
788
+ if not active:
789
+ yield False
790
+ return
791
+ was = caps_lock_on()
792
+ if was is None or was:
793
+ yield False
794
+ return
795
+ try:
796
+ press_key("capslock")
797
+ yield True
798
+ finally:
799
+ try:
800
+ press_key("capslock")
801
+ except Exception: # noqa: BLE001
802
+ pass
803
+
804
+
805
+ @contextmanager
806
+ def ime_muted(hwnd: int):
807
+ """注入按键期间临时关掉目标窗口的输入法;退出时按原状态恢复。
808
+
809
+ 中文输入法会截获字母键、转成候选框,目标程序收不到原始按键 ——
810
+ 症状是"键盘完全没反应,而鼠标一切正常",且换到英文输入法就恢复。
811
+ 这里只动这个窗口的 IME 上下文,不改用户全局的输入法。
812
+
813
+ 产物是"这次有没有真的关过"(True/False):没关成也不报错 ——
814
+ TSF 系的输入法不归 IMM32 管,那种情况只能如实告诉调用方。
815
+ """
816
+ if not win32.IS_WINDOWS:
817
+ yield False
818
+ return
819
+ himc = None
820
+ imm = None
821
+ was_open = False
822
+ try:
823
+ imm = ctypes.windll.imm32
824
+ himc = imm.ImmGetContext(int(hwnd))
825
+ if himc:
826
+ was_open = bool(imm.ImmGetOpenStatus(himc))
827
+ if was_open:
828
+ imm.ImmSetOpenStatus(himc, False)
829
+ except Exception: # noqa: BLE001
830
+ himc = None
831
+ try:
832
+ yield was_open
833
+ finally:
834
+ if himc is not None:
835
+ try:
836
+ if was_open:
837
+ imm.ImmSetOpenStatus(himc, True)
838
+ imm.ImmReleaseContext(int(hwnd), himc)
839
+ except Exception: # noqa: BLE001
840
+ pass
841
+
842
+
843
+ def _pick_english_layout(installed) -> int | None:
844
+ """从 `[(HKL, langid)]` 里挑英语(美国);没有返回 None(不替用户装)。"""
845
+ for hkl, langid in installed or ():
846
+ if langid == EN_US_LANGID:
847
+ return int(hkl)
848
+ return None
849
+
850
+
851
+ def english_layout_hkl() -> int | None:
852
+ """已安装的英语(美国)布局 HKL;没装返回 None。"""
853
+ return _pick_english_layout(win32.installed_layouts())
854
+
855
+
856
+ def _wait_layout(hwnd: int, langid: int, timeout: float = 0.4) -> bool:
857
+ """等目标线程的布局变成 *langid*;超时返回 False。"""
858
+ deadline = time.monotonic() + timeout
859
+ while time.monotonic() < deadline:
860
+ now = keyboard_layout(hwnd)
861
+ if now and now[0] == langid:
862
+ return True
863
+ time.sleep(0.02)
864
+ return False
865
+
866
+
867
+ @contextmanager
868
+ def english_layout_guard(hwnd: int, active: bool):
869
+ """为这次注入临时把目标窗口切到英语布局,退出时还原。
870
+
871
+ 为什么用 `WM_INPUTLANGCHANGEREQUEST`:它是系统给"窗口级输入语言切换"
872
+ 的官方消息,作用在目标线程上;注入 Win+Space 既被护栏禁止(Win 键),
873
+ 真机也按不出来。实测中文 0x0804 <-> 英语 0x0409 都切得动、读得回。
874
+
875
+ 只在"中文布局 + 这个键会被 IME 吃掉"时动(判据与 caps_lock_guard
876
+ 同源)。产物是 `{"switched": bool, "restored": bool}`:没切成功就
877
+ 如实报 swapped=False;切成功但还原失败时 restored=False —— 调用方
878
+ 必须把这件事告诉模型(用户的状态被留在英语了)。
879
+ """
880
+ res = {"switched": False, "restored": True}
881
+ if not active:
882
+ yield res
883
+ return
884
+ lay = keyboard_layout(hwnd)
885
+ if not lay or lay[0] not in _CJK_LANGIDS:
886
+ yield res
887
+ return
888
+ hkl = english_layout_hkl()
889
+ if hkl is None:
890
+ yield res
891
+ return
892
+ before = win32.keyboard_layout_of(hwnd)
893
+ if not before or not win32.post_input_language_change(hwnd, hkl):
894
+ yield res
895
+ return
896
+ if not _wait_layout(hwnd, EN_US_LANGID):
897
+ # 消息可能晚到:走之前先试着还原,不能把用户留在英语。
898
+ win32.post_input_language_change(hwnd, before)
899
+ _wait_layout(hwnd, lay[0], timeout=0.2)
900
+ yield res
901
+ return
902
+ res["switched"] = True
903
+ try:
904
+ yield res
905
+ finally:
906
+ win32.post_input_language_change(hwnd, before)
907
+ res["restored"] = _wait_layout(hwnd, lay[0])
908
+
909
+
484
910
  def paste_text(text: str, *, backend: str = "auto") -> None:
485
911
  """写剪贴板 + Ctrl+V(中文 / 输入法场景)。"""
486
912
  if not text: