@hfyjq/crannia 1.1.1 → 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 -7523
  39. package/core/allowlist.py +2 -3
  40. package/core/approval.py +36 -26
  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 +15 -15
  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 +3 -3
  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 +37 -28
  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 +369 -77
  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 -1762
  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 +32 -7
  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
@@ -1,381 +1,563 @@
1
- r"""接管会话状态 —— 全进程只有一份。
2
-
3
- ## 为什么是单例,不是"每会话一份"
4
-
5
- Windows 一个登录会话只有一个输入桌面(`Winsta0\Default`),`SendInput`
6
- 也没有目标窗口参数 —— 两个 agent 同时接管,事件会交织。同一时刻
7
- 只允许一条会话持有接管;第二个人来要,拒绝并说清,不是排队。
8
-
9
- ## 三条判据
10
-
11
- 1. `/clear` 有意不清(同 `mode`):一次启用整个会话有效,
12
- 除非关闭软件或再次点击接管按钮 —— `/clear` 不在那两条里。
13
- 登记在 `state_registry` 的 `SESSION_SCOPED_BY_OTHER`,
14
- purge=None,理由写在那一格。
15
- 2. 观察快照存"路径"不存 COM 指针 —— 动作时重新解析(`uia.resolve`),
16
- 窗口变了就失败,这正是"一次观察 → 一个动作"要的失败方向。
17
- 3. 窗口 id / 观察 id 单调递增、永不重用 —— 重用一个 id 会让一条
18
- 迟到的点击打到另一个窗口上(比报错坏得多)。
19
-
20
- ## 与"物理输入即退出"的接口
21
-
22
- `watch.py` 检测到物理输入后调 `disable("physical_input")`;
23
- `subscribe()` 的监听者在锁外被调用(监听者可能 emit 事件 / 碰 IO)。
24
- """
25
-
26
- from __future__ import annotations
27
-
28
- import sys
29
- import threading
30
- import time
31
- from dataclasses import dataclass, field
32
- from typing import Callable
33
-
34
- from . import win32
35
-
36
-
37
- class TakeoverError(RuntimeError):
38
- pass
39
-
40
-
41
- @dataclass
42
- class Observation:
43
- obs_id: str
44
- window_id: str
45
- hwnd: int
46
- exe: str
47
- rect: tuple[int, int, int, int] # 窗口外框(物理像素)—— 过期检测用
48
- elements: list = field(default_factory=list) # list[uia.UIElement]
49
- created: float = 0.0
50
- consumed: bool = False
51
- #: 这一张图对应的物理矩形。
52
- #: 全窗截图 = `rect`;局部放大 = 裁剪出来的那一块。模型的 `x`/`y`
53
- #: 是 0–1000 比例,永远相对它看到的那张图,这里就是映射的底。
54
- coord_rect: tuple[int, int, int, int] | None = None
55
-
56
-
57
- @dataclass
58
- class Takeover:
59
- owner: str
60
- started: float = field(default_factory=time.time)
61
- authorized: set[str] = field(default_factory=set) # exe 小写 basename
62
- windows: dict[str, win32.WindowInfo] = field(default_factory=dict)
63
- observations: dict[str, Observation] = field(default_factory=dict)
64
- latest_by_window: dict[str, str] = field(default_factory=dict)
65
- #: 每个窗口最近一次点击的物理点(下一张截图用来画红十字;取一次就清)。
66
- last_click: dict[str, tuple[int, int]] = field(default_factory=dict)
67
- seq: int = 0
68
- stop_reason: str = ""
69
- #: 「接管」与「正在对抗检测」是两态。
70
- #: 启用之后用户还要打字下指令 / 去打开目标应用——那些输入不该算干预。
71
- #:模型第一次动电脑那一刻(`tools.computer()` 被调)才 `armed=True`;
72
- #: 一轮结束(`PostProcess` 收尾)自动 `armed=False`。
73
- #: `Esc` 不受这一格影响 —— 它是显式急停,启用期间永远有效。
74
- armed: bool = False
75
- armed_at: float = 0.0
76
- #: 启用那一刻算好的"我们自己"的 pid(Crannia 后端 + 桌面壳)。
77
- #: 用途:`list_windows` 把它们剔出去,`window_decision` 也据此拒绝 ——
78
- #: 用户绝不该把"控制 Crannia 自己"授权出去(那等于把急停按钮交出去)。
79
- our_pids: set[int] = field(default_factory=set)
80
-
81
-
82
- _lock = threading.RLock()
83
- _state: Takeover | None = None
84
- _listeners: list[Callable[[str, str], None]] = [] # (owner, reason)
85
- #: 最近一次为什么关的 —— 界面要能说一句人话("检测到你的键盘输入")。
86
- #: 它是进程级的史(同 `_recent_commands`),`/clear` 不清。
87
- _last_stop: dict = {"owner": "", "reason": "", "at": 0.0}
88
-
89
-
90
- # 生命周期
91
- _enable_lock = threading.Lock()
92
-
93
-
94
- def enable(owner: str) -> tuple[bool, str]:
95
- """开启接管。模式校验在调用方(这里不 import `core.modes`,避免循环)。"""
96
- global _state
97
- if not win32.IS_WINDOWS:
98
- return False, "接管模式只支持 Windows 桌面(当前系统 %s)" % sys.platform
99
- if not owner:
100
- return False, "拿不到当前会话"
101
- if win32.is_locked():
102
- return False, "桌面已锁屏 —— 先解锁再启用接管"
103
- # 整段串行:两个通道同时按「启用」不能装出两套钩子 / 两半状态。
104
- with _enable_lock:
105
- with _lock:
106
- if _state is not None:
107
- if _state.owner == owner:
108
- return True, "接管已经开着"
109
- return False, "另一个对话正在接管这台电脑 —— 先在那里退出再启用"
110
- # 急停钩子是启用的一部分,不是可选项:装不起来就不许启用
111
- # (否则"用户一碰键鼠就退出"这条承诺是空的)。
112
- # 在发布状态之前装 —— 不能出现"已经算开着、但钩子还没起来"的窗口。
113
- try:
114
- from . import watch
115
- ours = win32.our_pids()
116
- ok, why = watch.start(ours)
117
- if not ok:
118
- return False, why
119
- except Exception as exc: # noqa: BLE001
120
- return False, "急停钩子装不起来(%s: %s)—— 拒绝启用接管" % (
121
- type(exc).__name__, exc)
122
- with _lock:
123
- _state = Takeover(owner=owner, our_pids=set(ours))
124
- return True, ""
125
-
126
-
127
- def disable(reason: str = "") -> str:
128
- """关闭接管,返回之前的所有者(没有就返回空串)。"""
129
- global _state
130
- with _lock:
131
- if _state is None:
132
- return ""
133
- owner = _state.owner
134
- _state.stop_reason = reason or ""
135
- _state = None
136
- _last_stop.update({"owner": owner, "reason": reason or "",
137
- "at": time.time()})
138
- listeners = list(_listeners)
139
- try:
140
- from . import watch
141
- watch.stop()
142
- except Exception as exc: # noqa: BLE001
143
- print("[computer] 摘急停钩子失败:%s: %s" % (type(exc).__name__, exc))
144
- for fn in listeners:
145
- try:
146
- fn(owner, reason or "")
147
- except Exception as exc: # noqa: BLE001 - 监听者坏了不能反噬
148
- print("[computer] stop listener failed: %s: %s" % (type(exc).__name__, exc))
149
- return owner
150
-
151
-
152
- def disable_for_session(session_id: str, reason: str = "") -> bool:
153
- """只有这条会话是持有者时才关(模式切走 / 会话清理)。返回是否真的关了。"""
154
- with _lock:
155
- if _state is None or not session_id or _state.owner != session_id:
156
- return False
157
- disable(reason)
158
- return True
159
-
160
-
161
- def subscribe(fn: Callable[[str, str], None]) -> None:
162
- """注册一个"接管被关掉了"的监听者(锁外调用)。"""
163
- with _lock:
164
- if fn not in _listeners:
165
- _listeners.append(fn)
166
-
167
-
168
- def arm() -> None:
169
- """模型开始动电脑了,打开对抗检测。"""
170
- with _lock:
171
- if _state is not None and not _state.armed:
172
- _state.armed = True
173
- _state.armed_at = time.time()
174
- print("[computer] 已进入操作检测(模型开始动作;物理输入将退出接管)")
175
-
176
-
177
- def disarm_for(session_id: str, reason: str = "") -> None:
178
- """一轮结束,关掉对抗检测(只关持有者的那一轮,六个通道并行)。
179
-
180
- 不传 `session_id` 的调用会关掉任何人的 —— 只给 `disable()` 用。
181
- """
182
- with _lock:
183
- if _state is None:
184
- return
185
- if session_id and _state.owner != session_id:
186
- return
187
- if _state.armed:
188
- _state.armed = False
189
- print("[computer] 操作检测结束(%s)" % (reason or "turn_end"))
190
-
191
-
192
- def is_armed() -> bool:
193
- """只有这一格为真时,物理键鼠才算"干预"(`Esc` 例外)。"""
194
- with _lock:
195
- return bool(_state is not None and _state.armed)
196
-
197
-
198
- def last_stop() -> dict:
199
- """最近一次"为什么退出接管"(进程级的史,与哪条会话无关)。
200
-
201
- 模型侧要用它区分两种长得一样的状态:
202
- 「用户从没启用」 vs 「刚刚因为用户干预被退出」。
203
- """
204
- with _lock:
205
- return dict(_last_stop)
206
-
207
-
208
- def our_pids() -> set[int]:
209
- """启用时算好的"我们自己"(后端 + 桌面壳)。没启用,空集。"""
210
- with _lock:
211
- return set(_state.our_pids) if _state else set()
212
-
213
-
214
- def is_enabled() -> bool:
215
- with _lock:
216
- return _state is not None
217
-
218
-
219
- def enabled_for(session_id: str) -> bool:
220
- """这条会话自己是不是接管者 —— `tools=` 只给它的持有者发 `computer`。"""
221
- with _lock:
222
- return bool(_state is not None and session_id and _state.owner == session_id)
223
-
224
-
225
- def status() -> dict:
226
- with _lock:
227
- if _state is None:
228
- return {"enabled": False, "owner": "", "started_at": 0,
229
- "authorized": [], "stop_reason": "", "armed": False,
230
- "last_stop": dict(_last_stop)}
231
- return {"enabled": True, "owner": _state.owner,
232
- "started_at": _state.started, "authorized": sorted(_state.authorized),
233
- "stop_reason": _state.stop_reason, "armed": bool(_state.armed),
234
- "armed_at": _state.armed_at, "last_stop": dict(_last_stop)}
235
-
236
-
237
- def _require(session_id: str) -> Takeover:
238
- with _lock:
239
- if _state is None:
240
- raise TakeoverError("接管模式没有启用 —— 请让用户点击输入框右侧的「接管」按钮")
241
- if session_id and _state.owner != session_id:
242
- raise TakeoverError("接管由另一个对话持有 —— 这里不能操作")
243
- return _state
244
-
245
-
246
- # 应用授权(逐应用 · 每会话一次)
247
- def authorize(exe: str) -> None:
248
- exe = (exe or "").lower()
249
- if not exe:
250
- return
251
- with _lock:
252
- if _state is None:
253
- raise TakeoverError("接管模式没有启用")
254
- _state.authorized.add(exe)
255
-
256
-
257
- def is_authorized(exe: str) -> bool:
258
- """这个应用现在能不能操作。
259
-
260
- 两层:永久白名单(`data/allowlist.json` 的
261
- `computer_app` 格,设置页可加可删)或 本会话的临时授权。
262
- 文件那条每轮现读(`core/allowlist.py` 判据 ①:文件即真相)——
263
- 用户在设置页删掉一条,下一轮就该重新问。
264
- """
265
- exe = (exe or "").lower()
266
- if not exe:
267
- return False
268
- try:
269
- from core import allowlist as _al
270
- if _al.matches_any(_al.list_for("computer_app"), exe):
271
- return True
272
- except Exception as exc: # noqa: BLE001 - 读不到就按"没批准"
273
- print("[computer] 读永久应用白名单失败(按未批准处理):%s: %s"
274
- % (type(exc).__name__, exc))
275
- with _lock:
276
- return bool(_state is not None and exe in _state.authorized)
277
-
278
-
279
- def authorized() -> set[str]:
280
- with _lock:
281
- return set(_state.authorized) if _state else set()
282
-
283
-
284
- # 窗口登记
285
- def set_windows(infos: list[win32.WindowInfo]) -> dict[str, win32.WindowInfo]:
286
- """给这一批窗口发新的 id(`w12` 这种),返回 id → info。
287
-
288
- 每次 `list_windows` 都发新 id,旧 id 作废(不是复用)——
289
- 见模块 docstring 判据 3。
290
- """
291
- with _lock:
292
- st = _state
293
- if st is None:
294
- raise TakeoverError("接管模式没有启用")
295
- out: dict[str, win32.WindowInfo] = {}
296
- for info in infos:
297
- st.seq += 1
298
- wid = "w%d" % st.seq
299
- st.windows[wid] = info
300
- out[wid] = info
301
- # 只保留最近 200 个窗口登记(长会话不无限涨)
302
- if len(st.windows) > 200:
303
- for wid in list(st.windows)[:-200]:
304
- st.windows.pop(wid, None)
305
- return out
306
-
307
-
308
- def get_window(window_id: str) -> win32.WindowInfo | None:
309
- with _lock:
310
- return _state.windows.get(window_id) if _state else None
311
-
312
-
313
- # 观察快照
314
- def record_observation(window_id: str, info: win32.WindowInfo,
315
- elements: list, rect: tuple[int, int, int, int],
316
- coord_rect: tuple[int, int, int, int] | None = None) -> str:
317
- with _lock:
318
- st = _state
319
- if st is None:
320
- raise TakeoverError("接管模式没有启用")
321
- st.seq += 1
322
- oid = "obs%d" % st.seq
323
- st.observations[oid] = Observation(
324
- obs_id=oid, window_id=window_id, hwnd=info.hwnd,
325
- exe=info.exe, rect=rect, elements=list(elements or []),
326
- created=time.time(), coord_rect=coord_rect or rect)
327
- st.latest_by_window[window_id] = oid
328
- # 每个窗口只留最近 5 次观察
329
- olds = [k for k, v in st.observations.items() if v.window_id == window_id]
330
- for k in olds[:-5]:
331
- st.observations.pop(k, None)
332
- return oid
333
-
334
-
335
- def usable_observation(obs_id: str) -> Observation:
336
- """取一个还能用的观察:存在、没被消费、且是那个窗口最新的一次。"""
337
- with _lock:
338
- st = _state
339
- if st is None:
340
- raise TakeoverError("接管模式没有启用")
341
- obs = st.observations.get(obs_id)
342
- if obs is None:
343
- raise TakeoverError("观察快照不存在(或已过期)—— 重新 `get_window_state`")
344
- if obs.consumed:
345
- raise TakeoverError("这次观察已经用过了 —— 重新 `get_window_state` 再看一眼")
346
- if st.latest_by_window.get(obs.window_id) != obs_id:
347
- raise TakeoverError("这不是该窗口最新的一次观察 —— 重新 `get_window_state`")
348
- return obs
349
-
350
-
351
- def consume(obs_id: str) -> None:
352
- with _lock:
353
- if _state and obs_id in _state.observations:
354
- _state.observations[obs_id].consumed = True
355
-
356
-
357
- def note_click(window_id: str, x: int, y: int) -> None:
358
- """记下实际点到的物理点(下一张截图在它上面画红十字)。"""
359
- with _lock:
360
- if _state is not None:
361
- _state.last_click[window_id] = (int(x), int(y))
362
-
363
-
364
- def take_last_click(window_id: str) -> tuple[int, int] | None:
365
- """取走那个点(只标一次,免得每张图都糊一个旧红十字)。"""
366
- with _lock:
367
- if _state is None:
368
- return None
369
- return _state.last_click.pop(window_id, None)
370
-
371
-
372
- def reset_for_tests() -> None:
373
- """只给测试用(`purge` 不走它 —— `/clear` 有意不清)。
374
-
375
- 连 `_last_stop` 一起清:否则上一条用例的"刚刚因键盘退出"会漏进下一条,
376
- 让「从没启用」那条用例拿到一句"接管刚刚退出了"(两种状态又塌回一种)。
377
- """
378
- global _state
379
- with _lock:
380
- _state = None
381
- _last_stop.update({"owner": "", "reason": "", "at": 0.0})
1
+ r"""接管会话状态 —— 全进程只有一份。
2
+
3
+ ## 为什么是单例,不是"每会话一份"
4
+
5
+ Windows 一个登录会话只有一个输入桌面(`Winsta0\Default`),`SendInput`
6
+ 也没有目标窗口参数 —— 两个 agent 同时接管,事件会交织。同一时刻
7
+ 只允许一条会话持有接管;第二个人来要,拒绝并说清,不是排队。
8
+
9
+ ## 三条判据
10
+
11
+ 1. `/clear` 有意不清(同 `mode`):一次启用整个会话有效,
12
+ 除非关闭软件或再次点击接管按钮 —— `/clear` 不在那两条里。
13
+ 登记在 `state_registry` 的 `SESSION_SCOPED_BY_OTHER`,
14
+ purge=None,理由写在那一格。
15
+ 2. 观察快照存"路径"不存 COM 指针 —— 动作时重新解析(`uia.resolve`),
16
+ 窗口变了就失败,这正是"一次观察 → 一个动作"要的失败方向。
17
+ 3. 窗口 id / 观察 id 单调递增、永不重用 —— 重用一个 id 会让一条
18
+ 迟到的点击打到另一个窗口上(比报错坏得多)。
19
+ 2026-11-27 订正:同一个 `(hwnd, pid)` 复用原 id —— "永不重用"
20
+ 指的是"一个 id 不给两个窗口",同一个窗口重新列举不换 id。真机代价:
21
+ PS 主窗从 `w6` 变成 `w279`,模型手里的 `w6` 直接报"不认识的窗口 id",
22
+ 白跑两轮。(原实现每次 `list_windows` 全发新 id + 200 条上限按插入
23
+ 顺序清理,常用窗口最先被清。)
24
+
25
+ ## 与"物理输入即退出"的接口
26
+
27
+ `watch.py` 检测到物理输入后调 `disable("physical_input")`;
28
+ `subscribe()` 的监听者在锁外被调用(监听者可能 emit 事件 / 碰 IO)。
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import sys
34
+ import threading
35
+ import time
36
+ from dataclasses import dataclass, field
37
+ from typing import Callable
38
+
39
+ from . import win32
40
+
41
+
42
+ class TakeoverError(RuntimeError):
43
+ pass
44
+
45
+
46
+ @dataclass
47
+ class Observation:
48
+ obs_id: str
49
+ window_id: str
50
+ hwnd: int
51
+ exe: str
52
+ rect: tuple[int, int, int, int] # 窗口外框(物理像素)—— 过期检测用
53
+ elements: list = field(default_factory=list) # list[uia.UIElement]
54
+ created: float = 0.0
55
+ consumed: bool = False
56
+ #: 这一张图对应的物理矩形。
57
+ #: 全窗截图 = `rect`;局部放大 = 裁剪出来的那一块。模型的 `x`/`y`
58
+ #: 是 0–1000 比例,永远相对它看到的那张图,这里就是映射的底。
59
+ coord_rect: tuple[int, int, int, int] | None = None
60
+ #: 弹出菜单的元素 → 菜单命令 id(`win32.menu_items` 配上的那些)。
61
+ #: 有它 → 这次观察的菜单项坐标取自菜单自己的表,不是 UIA 的估计。
62
+ #: 点击时按 id 重取一次当下的矩形 —— 菜单滚动/换层都跟得上。
63
+ menu_ids: dict[int, int] = field(default_factory=dict)
64
+ #: 窗口相对观察那一刻的位移(像素)。窗口被拖动时,比例坐标仍然
65
+ #: 相对"你看到的那张图",所以换算时把这段位移补上 —— 不必因为
66
+ #: 窗口挪了一下就让观察作废。由 `tools._ensure_same_rect` 填。
67
+ drift: tuple[int, int] = (0, 0)
68
+
69
+
70
+ @dataclass
71
+ class Takeover:
72
+ owner: str
73
+ started: float = field(default_factory=time.time)
74
+ authorized: set[str] = field(default_factory=set) # exe 小写 basename
75
+ windows: dict[str, win32.WindowInfo] = field(default_factory=dict)
76
+ observations: dict[str, Observation] = field(default_factory=dict)
77
+ latest_by_window: dict[str, str] = field(default_factory=dict)
78
+ #: 每个窗口最近一次点击的实际物理点(下一张截图用来画红十字;取一次就清)。
79
+ last_click: dict[str, tuple[int, int]] = field(default_factory=dict)
80
+ #: 每个窗口上一次点击的时刻(`time.monotonic`)—— 算"距上次点击多少 ms"。
81
+ #: 两次单点落在同一个点上、间隔小于系统双击阈值时,会被合成一次双击;
82
+ #: 回执把间隔报出来,模型才知道自己是不是在"点两下"。
83
+ last_click_at: dict[str, float] = field(default_factory=dict)
84
+ #: 上次 `cursor_position` 报数那一刻的光标物理点(只留给下一张图标一次)。
85
+ #: 与 `last_click` 分开存:一个是"点落在哪",一个是"我读到它在哪"。
86
+ last_cursor: dict[str, tuple[int, int]] = field(default_factory=dict)
87
+ #: 最近一次点击"实际落点 − 请求落点"的差值(取一次就清)。
88
+ #: 存在它是为了把"点偏了多少"变成可读的反馈,而不是让模型自己猜图有没有对。
89
+ click_miss: dict[str, tuple[int, int]] = field(default_factory=dict)
90
+ #: 下一次观察要自动开网格的窗口(点偏超阈值时置,取一次就清)。
91
+ grid_hint: set[str] = field(default_factory=set)
92
+ #: 最近一次观察 / 激活的窗口 —— `get_window_state` / `cursor_position`
93
+ #: 不给 window 时沿用。它只是默认值,回执里会写明"沿用 wX"。
94
+ last_window: str = ""
95
+ #: 每个窗口上一次观察的原始截图指纹(sha256 前 12 位)。
96
+ #: 截图按内容命名附件,所以"同一张图"既可能是界面没变、也可能是
97
+ #: 目标程序没重绘;指纹把这件事变成回执里的事实,让模型有依据判断。
98
+ last_frame: dict[str, str] = field(default_factory=dict)
99
+ #: 每个窗口上一次观察的元素树摘要(类型 / id / 名字 / 矩形)。
100
+ #: 与 `last_frame` 配对使用:图与树各自独立,两个都相同才说明界面
101
+ #: 真的没动;只有图相同而树变了,说明拿到的是旧帧。
102
+ last_tree: dict[str, str] = field(default_factory=dict)
103
+ seq: int = 0
104
+ stop_reason: str = ""
105
+ #: 「接管」与「正在对抗检测」是两态。
106
+ #: 启用之后用户还要打字下指令 / 去打开目标应用——那些输入不该算干预。
107
+ #:模型第一次动电脑那一刻(`tools.computer()` 被调)才 `armed=True`;
108
+ #: 一轮结束(`PostProcess` 收尾)自动 `armed=False`。
109
+ #: `Esc` 不受这一格影响 —— 它是显式急停,启用期间永远有效。
110
+ armed: bool = False
111
+ armed_at: float = 0.0
112
+ #: 启用那一刻算好的"我们自己"的 pid(Crannia 后端 + 桌面壳)。
113
+ #: 用途:`list_windows` 把它们剔出去,`window_decision` 也据此拒绝 ——
114
+ #: 用户绝不该把"控制 Crannia 自己"授权出去(那等于把急停按钮交出去)。
115
+ our_pids: set[int] = field(default_factory=set)
116
+
117
+
118
+ _lock = threading.RLock()
119
+ _state: Takeover | None = None
120
+ _listeners: list[Callable[[str, str], None]] = [] # (owner, reason)
121
+ #: 最近一次为什么关的 —— 界面要能说一句人话("检测到你的键盘输入")。
122
+ #: 它是进程级的史(同 `_recent_commands`),`/clear` 不清。
123
+ _last_stop: dict = {"owner": "", "reason": "", "at": 0.0}
124
+
125
+
126
+ # 生命周期
127
+ _enable_lock = threading.Lock()
128
+
129
+
130
+ def enable(owner: str) -> tuple[bool, str]:
131
+ """开启接管。模式校验在调用方(这里不 import `core.modes`,避免循环)。"""
132
+ global _state
133
+ if not win32.IS_WINDOWS:
134
+ #: 这条会出现在按钮旁的提示里 —— 跟着界面语言走,与别的消息同一处取。
135
+ from core import i18n
136
+ return False, i18n.t("接管模式只支持 Windows 桌面(当前系统 %s)") % sys.platform
137
+ if not owner:
138
+ return False, "拿不到当前会话"
139
+ if win32.is_locked():
140
+ return False, "桌面已锁屏 —— 先解锁再启用接管"
141
+ # 整段串行:两个通道同时按「启用」不能装出两套钩子 / 两半状态。
142
+ with _enable_lock:
143
+ with _lock:
144
+ if _state is not None:
145
+ if _state.owner == owner:
146
+ return True, "接管已经开着"
147
+ return False, "另一个对话正在接管这台电脑 —— 先在那里退出再启用"
148
+ # 急停钩子是启用的一部分,不是可选项:装不起来就不许启用
149
+ # (否则"用户一碰键鼠就退出"这条承诺是空的)。
150
+ # 在发布状态之前装 —— 不能出现"已经算开着、但钩子还没起来"的窗口。
151
+ try:
152
+ from . import watch
153
+ ours = win32.our_pids()
154
+ ok, why = watch.start(ours)
155
+ if not ok:
156
+ return False, why
157
+ except Exception as exc: # noqa: BLE001
158
+ return False, "急停钩子装不起来(%s: %s)—— 拒绝启用接管" % (
159
+ type(exc).__name__, exc)
160
+ with _lock:
161
+ _state = Takeover(owner=owner, our_pids=set(ours))
162
+ return True, ""
163
+
164
+
165
+ def disable(reason: str = "") -> str:
166
+ """关闭接管,返回之前的所有者(没有就返回空串)。"""
167
+ global _state
168
+ with _lock:
169
+ if _state is None:
170
+ return ""
171
+ owner = _state.owner
172
+ _state.stop_reason = reason or ""
173
+ _state = None
174
+ _last_stop.update({"owner": owner, "reason": reason or "",
175
+ "at": time.time()})
176
+ listeners = list(_listeners)
177
+ try:
178
+ from . import watch
179
+ watch.stop()
180
+ except Exception as exc: # noqa: BLE001
181
+ print("[computer] failed to detach emergency-stop hook: %s: %s" % (type(exc).__name__, exc))
182
+ for fn in listeners:
183
+ try:
184
+ fn(owner, reason or "")
185
+ except Exception as exc: # noqa: BLE001 - 监听者坏了不能反噬
186
+ print("[computer] stop listener failed: %s: %s" % (type(exc).__name__, exc))
187
+ return owner
188
+
189
+
190
+ def disable_for_session(session_id: str, reason: str = "") -> bool:
191
+ """只有这条会话是持有者时才关(模式切走 / 会话清理)。返回是否真的关了。"""
192
+ with _lock:
193
+ if _state is None or not session_id or _state.owner != session_id:
194
+ return False
195
+ disable(reason)
196
+ return True
197
+
198
+
199
+ def subscribe(fn: Callable[[str, str], None]) -> None:
200
+ """注册一个"接管被关掉了"的监听者(锁外调用)。"""
201
+ with _lock:
202
+ if fn not in _listeners:
203
+ _listeners.append(fn)
204
+
205
+
206
+ def arm() -> None:
207
+ """模型开始动电脑了,打开对抗检测。"""
208
+ with _lock:
209
+ if _state is not None and not _state.armed:
210
+ _state.armed = True
211
+ _state.armed_at = time.time()
212
+ print("[computer] operation detection entered (model starting actions; physical input will exit takeover)")
213
+
214
+
215
+ def disarm_for(session_id: str, reason: str = "") -> None:
216
+ """一轮结束,关掉对抗检测(只关持有者的那一轮,六个通道并行)。
217
+
218
+ 不传 `session_id` 的调用会关掉任何人的 —— 只给 `disable()` 用。
219
+ """
220
+ with _lock:
221
+ if _state is None:
222
+ return
223
+ if session_id and _state.owner != session_id:
224
+ return
225
+ if _state.armed:
226
+ _state.armed = False
227
+ print("[computer] operation detection ended (%s)" % (reason or "turn_end"))
228
+
229
+
230
+ def is_armed() -> bool:
231
+ """只有这一格为真时,物理键鼠才算"干预"(`Esc` 例外)。"""
232
+ with _lock:
233
+ return bool(_state is not None and _state.armed)
234
+
235
+
236
+ def last_stop() -> dict:
237
+ """最近一次"为什么退出接管"(进程级的史,与哪条会话无关)。
238
+
239
+ 模型侧要用它区分两种长得一样的状态:
240
+ 「用户从没启用」 vs 「刚刚因为用户干预被退出」。
241
+ """
242
+ with _lock:
243
+ return dict(_last_stop)
244
+
245
+
246
+ def our_pids() -> set[int]:
247
+ """启用时算好的"我们自己"(后端 + 桌面壳)。没启用,空集。"""
248
+ with _lock:
249
+ return set(_state.our_pids) if _state else set()
250
+
251
+
252
+ def is_enabled() -> bool:
253
+ with _lock:
254
+ return _state is not None
255
+
256
+
257
+ def enabled_for(session_id: str) -> bool:
258
+ """这条会话自己是不是接管者 —— `tools=` 只给它的持有者发 `computer`。"""
259
+ with _lock:
260
+ return bool(_state is not None and session_id and _state.owner == session_id)
261
+
262
+
263
+ def status() -> dict:
264
+ with _lock:
265
+ if _state is None:
266
+ return {"enabled": False, "owner": "", "started_at": 0,
267
+ "authorized": [], "stop_reason": "", "armed": False,
268
+ "last_stop": dict(_last_stop)}
269
+ return {"enabled": True, "owner": _state.owner,
270
+ "started_at": _state.started, "authorized": sorted(_state.authorized),
271
+ "stop_reason": _state.stop_reason, "armed": bool(_state.armed),
272
+ "armed_at": _state.armed_at, "last_stop": dict(_last_stop)}
273
+
274
+
275
+ def _require(session_id: str) -> Takeover:
276
+ with _lock:
277
+ if _state is None:
278
+ raise TakeoverError("接管模式没有启用 —— 请让用户点击输入框右侧的「接管」按钮")
279
+ if session_id and _state.owner != session_id:
280
+ raise TakeoverError("接管由另一个对话持有 —— 这里不能操作")
281
+ return _state
282
+
283
+
284
+ # 应用授权(逐应用 · 每会话一次)
285
+ def authorize(exe: str) -> None:
286
+ exe = (exe or "").lower()
287
+ if not exe:
288
+ return
289
+ with _lock:
290
+ if _state is None:
291
+ raise TakeoverError("接管模式没有启用")
292
+ _state.authorized.add(exe)
293
+
294
+
295
+ def is_authorized(exe: str) -> bool:
296
+ """这个应用现在能不能操作。
297
+
298
+ 两层:永久白名单(`data/allowlist.json` 的
299
+ `computer_app` 格,设置页可加可删)或 本会话的临时授权。
300
+ 文件那条每轮现读(`core/allowlist.py` 判据 ①:文件即真相)——
301
+ 用户在设置页删掉一条,下一轮就该重新问。
302
+ """
303
+ exe = (exe or "").lower()
304
+ if not exe:
305
+ return False
306
+ try:
307
+ from core import allowlist as _al
308
+ if _al.matches_any(_al.list_for("computer_app"), exe):
309
+ return True
310
+ except Exception as exc: # noqa: BLE001 - 读不到就按"没批准"
311
+ print("[computer] reading permanent app allowlist failed (treating as not approved): %s: %s"
312
+ % (type(exc).__name__, exc))
313
+ with _lock:
314
+ return bool(_state is not None and exe in _state.authorized)
315
+
316
+
317
+ def authorized() -> set[str]:
318
+ with _lock:
319
+ return set(_state.authorized) if _state else set()
320
+
321
+
322
+ # 窗口登记
323
+ def set_windows(infos: list[win32.WindowInfo]) -> dict[str, win32.WindowInfo]:
324
+ """给这一批窗口发 id(`w12` 这种),返回 id → info。
325
+
326
+ 同一个 `(hwnd, pid)` 复用原来的 id —— 模型手里的 id 不该因为
327
+ "又列了一次窗口"就作废(真机:PS 主窗从 w6 变 w279,w6 直接报错)。
328
+ 判据 3 是"一个 id 不给两个窗口",同一个窗口复用不违反它;
329
+ hwnd 被系统回收给新窗口时 pid 会变 → 发新 id。
330
+ 清理按"最久没用"(这一批出现的移到末尾),不再按"最早登记"。
331
+ """
332
+ with _lock:
333
+ st = _state
334
+ if st is None:
335
+ raise TakeoverError("接管模式没有启用")
336
+ by_key = {(info.hwnd, info.pid): wid
337
+ for wid, info in st.windows.items()}
338
+ out: dict[str, win32.WindowInfo] = {}
339
+ for info in infos:
340
+ key = (info.hwnd, info.pid)
341
+ wid = by_key.get(key)
342
+ if wid is None:
343
+ st.seq += 1
344
+ wid = "w%d" % st.seq
345
+ by_key[key] = wid
346
+ # 移到最后 = 最近使用;200 条上限按这个顺序清最老的。
347
+ if wid in st.windows:
348
+ st.windows.pop(wid)
349
+ st.windows[wid] = info
350
+ out[wid] = info
351
+ if len(st.windows) > 200:
352
+ for wid in list(st.windows)[:-200]:
353
+ st.windows.pop(wid, None)
354
+ return out
355
+
356
+
357
+ def get_window(window_id: str) -> win32.WindowInfo | None:
358
+ with _lock:
359
+ return _state.windows.get(window_id) if _state else None
360
+
361
+
362
+ def window_id_for(hwnd: int) -> str:
363
+ """某个顶层窗口已登记的 id(没有就空串)。"""
364
+ with _lock:
365
+ if _state is None:
366
+ return ""
367
+ for wid, info in _state.windows.items():
368
+ if int(info.hwnd) == int(hwnd):
369
+ return wid
370
+ return ""
371
+
372
+
373
+ def last_window() -> str:
374
+ """最近一次观察 / 激活的窗口 id(没有就空串)。"""
375
+ with _lock:
376
+ return _state.last_window if _state else ""
377
+
378
+
379
+ def set_last_window(window_id: str) -> None:
380
+ with _lock:
381
+ if _state is not None and window_id:
382
+ _state.last_window = window_id
383
+
384
+
385
+ # 观察快照
386
+ def record_observation(window_id: str, info: win32.WindowInfo,
387
+ elements: list, rect: tuple[int, int, int, int],
388
+ coord_rect: tuple[int, int, int, int] | None = None,
389
+ menu_ids: dict[int, int] | None = None) -> str:
390
+ with _lock:
391
+ st = _state
392
+ if st is None:
393
+ raise TakeoverError("接管模式没有启用")
394
+ st.seq += 1
395
+ oid = "obs%d" % st.seq
396
+ st.observations[oid] = Observation(
397
+ obs_id=oid, window_id=window_id, hwnd=info.hwnd,
398
+ exe=info.exe, rect=rect, elements=list(elements or []),
399
+ created=time.time(), coord_rect=coord_rect or rect,
400
+ menu_ids=dict(menu_ids or {}))
401
+ st.latest_by_window[window_id] = oid
402
+ st.last_window = window_id
403
+ # 每个窗口只留最近 5 次观察
404
+ olds = [k for k, v in st.observations.items() if v.window_id == window_id]
405
+ for k in olds[:-5]:
406
+ st.observations.pop(k, None)
407
+ return oid
408
+
409
+
410
+ def usable_observation(obs_id: str) -> Observation:
411
+ """取一个还能用的观察:存在、没被消费、且是那个窗口最新的一次。"""
412
+ with _lock:
413
+ st = _state
414
+ if st is None:
415
+ raise TakeoverError("接管模式没有启用")
416
+ obs = st.observations.get(obs_id)
417
+ if obs is None:
418
+ raise TakeoverError("[STALE_OBSERVATION] 观察快照不存在(或已过期)—— "
419
+ "重新 `get_window_state`")
420
+ if obs.consumed:
421
+ raise TakeoverError("[STALE_OBSERVATION] 这次观察已经用过了 —— "
422
+ "重新 `get_window_state` 再看一眼")
423
+ if st.latest_by_window.get(obs.window_id) != obs_id:
424
+ raise TakeoverError("[STALE_OBSERVATION] 这不是该窗口最新的一次观察 —— "
425
+ "重新 `get_window_state`")
426
+ return obs
427
+
428
+
429
+ def consume(obs_id: str) -> None:
430
+ with _lock:
431
+ if _state and obs_id in _state.observations:
432
+ _state.observations[obs_id].consumed = True
433
+
434
+
435
+ def note_frame(window_id: str, digest: str) -> str | None:
436
+ """记下这一帧的指纹,返回该窗口上一帧的指纹(第一次为 `None`)。
437
+
438
+ `digest` 取的是原始窗口截图的哈希,与观察参数(网格 / 放大 /
439
+ 标记)无关 —— 它回答的是"窗口内容有没有变",不是"这张图长什么样"。
440
+ """
441
+ with _lock:
442
+ st = _state
443
+ if st is None:
444
+ return None
445
+ prev = st.last_frame.get(window_id)
446
+ st.last_frame[window_id] = digest
447
+ return prev
448
+
449
+
450
+ def note_tree(window_id: str, digest: str) -> str | None:
451
+ """记下这一份元素树的摘要,返回上一份(第一次为 `None`)。"""
452
+ with _lock:
453
+ st = _state
454
+ if st is None:
455
+ return None
456
+ prev = st.last_tree.get(window_id)
457
+ st.last_tree[window_id] = digest
458
+ return prev
459
+
460
+
461
+ def note_click(window_id: str, x: int, y: int, *,
462
+ requested: tuple[int, int] | None = None,
463
+ miss_limit: int = 0) -> float | None:
464
+ """记下实际点到的物理点,并顺手算出它偏离请求点多少。
465
+
466
+ `requested` 是"我们让它去的点",`x`/`y` 是回读到的实际点。两者不一样时,
467
+ 偏了多少必须留给下一张图/下一句回执 —— 只画一个红十字而不说差值,
468
+ 模型得自己从图上量,那又变成一次目测。
469
+
470
+ `miss_limit` 是"算不算偏"的阈值(调用方按窗口尺寸算)。超过就置一次
471
+ 网格提示:点偏之后最缺的是位置依据,网格正好补它。
472
+
473
+ 返回距上一次点击的秒数(没有上一次则 None)—— 两次单点贴得太近
474
+ 会被系统合成双击,回执要能说清这件事。
475
+ """
476
+ with _lock:
477
+ if _state is None:
478
+ return None
479
+ now = time.monotonic()
480
+ prev = _state.last_click_at.get(window_id)
481
+ _state.last_click_at[window_id] = now
482
+ gap = (now - prev) if prev is not None else None
483
+ _state.last_click[window_id] = (int(x), int(y))
484
+ if requested is not None:
485
+ dx = int(x) - int(requested[0])
486
+ dy = int(y) - int(requested[1])
487
+ _state.click_miss[window_id] = (dx, dy)
488
+ if miss_limit > 0 and max(abs(dx), abs(dy)) > miss_limit:
489
+ _state.grid_hint.add(window_id)
490
+ return gap
491
+
492
+
493
+ def take_last_click(window_id: str) -> tuple[int, int] | None:
494
+ """取走那个点(只标一次,免得每张图都糊一个旧红十字)。"""
495
+ with _lock:
496
+ if _state is None:
497
+ return None
498
+ return _state.last_click.pop(window_id, None)
499
+
500
+
501
+ def note_cursor(window_id: str, x: int, y: int) -> None:
502
+ """记下 `cursor_position` 报数那一刻的光标物理点,留给下一张图标出来。
503
+
504
+ 为什么不在读数当下就截图:`cursor_position` 是一条轻量读数(模型会连问
505
+ 几次确认),每次都 PrintWindow 太贵。留给下一张 `get_window_state` 标 ——
506
+ 但回执必须说清"这是读数那一刻的位置",中间的移动归用户。
507
+ """
508
+ with _lock:
509
+ if _state is None:
510
+ return
511
+ _state.last_cursor[window_id] = (int(x), int(y))
512
+
513
+
514
+ def take_cursor(window_id: str) -> tuple[int, int] | None:
515
+ """取走那个点(只标一次,同 `take_last_click`)。"""
516
+ with _lock:
517
+ if _state is None:
518
+ return None
519
+ return _state.last_cursor.pop(window_id, None)
520
+
521
+
522
+ def take_click_miss(window_id: str) -> tuple[int, int] | None:
523
+ """取走"上次点偏了多少"(同上,只报一次)。"""
524
+ with _lock:
525
+ if _state is None:
526
+ return None
527
+ return _state.click_miss.pop(window_id, None)
528
+
529
+
530
+ def take_grid_hint(window_id: str) -> bool:
531
+ """上一次点偏了没有(取了就清,只影响紧接的那一张图)。"""
532
+ with _lock:
533
+ if _state is None:
534
+ return False
535
+ if window_id in _state.grid_hint:
536
+ _state.grid_hint.discard(window_id)
537
+ return True
538
+ return False
539
+
540
+
541
+ def enable_for_tests(owner: str = "test") -> "Takeover":
542
+ """测试专用:跳过平台闸装一个接管态,不装系统钩子。
543
+
544
+ 真机上的平台闸在 `enable()` 里(非 Windows 明确拒绝);但这组测试注入的
545
+ 全是假窗口 / 假输入,验的是落点回读、编号、盲模型降级那套纯逻辑 ——
546
+ 在 Linux CI 上跳过它们等于放弃一半判据。
547
+ """
548
+ global _state
549
+ with _lock:
550
+ _state = Takeover(owner=owner)
551
+ return _state
552
+
553
+
554
+ def reset_for_tests() -> None:
555
+ """只给测试用(`purge` 不走它 —— `/clear` 有意不清)。
556
+
557
+ 连 `_last_stop` 一起清:否则上一条用例的"刚刚因键盘退出"会漏进下一条,
558
+ 让「从没启用」那条用例拿到一句"接管刚刚退出了"(两种状态又塌回一种)。
559
+ """
560
+ global _state
561
+ with _lock:
562
+ _state = None
563
+ _last_stop.update({"owner": "", "reason": "", "at": 0.0})