@hfyjq/crannia 1.0.0 → 1.1.1

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 (222) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +45 -45
  3. package/THIRD-PARTY-FRONTEND.md +5266 -5266
  4. package/THIRD-PARTY-PYTHON.md +162 -153
  5. package/THIRD-PARTY.md +316 -316
  6. package/apps/desktop/quotes.txt +56 -56
  7. package/bus/core.py +671 -671
  8. package/bus/loaders/channel_loader.py +64 -64
  9. package/bus/loaders/skill_md.py +676 -676
  10. package/bus/skill_state.py +124 -124
  11. package/channels/cli_channel/manifest.yaml +5 -5
  12. package/channels/dingtalk_channel/manifest.yaml +12 -12
  13. package/channels/feishu_channel/manifest.yaml +12 -12
  14. package/channels/qq_bot_channel/__init__.py +1 -1
  15. package/channels/qq_bot_channel/handler.py +881 -881
  16. package/channels/qq_bot_channel/manifest.yaml +4 -4
  17. package/channels/telegram_channel/__init__.py +1 -1
  18. package/channels/telegram_channel/handler.py +813 -813
  19. package/channels/telegram_channel/manifest.yaml +4 -4
  20. package/channels/telegram_channel/media.py +231 -231
  21. package/channels/textfmt.py +58 -58
  22. package/channels/wechat_channel/__init__.py +1 -1
  23. package/channels/wechat_channel/auth.py +23 -5
  24. package/channels/wechat_channel/manifest.yaml +5 -5
  25. package/channels/wechat_channel/media.py +178 -178
  26. package/config.yaml +2 -2
  27. package/core/activity.py +3 -0
  28. package/core/agent_loop.py +390 -55
  29. package/core/approval.py +17 -6
  30. package/core/artifacts.py +7 -0
  31. package/core/auto_review.py +23 -5
  32. package/core/channel_configs.py +34 -2
  33. package/core/channel_turns.py +759 -759
  34. package/core/child_approval.py +150 -0
  35. package/core/config_requirements.py +205 -0
  36. package/core/cron/runner.py +118 -6
  37. package/core/cron/store.py +14 -5
  38. package/core/cron/tools.py +17 -5
  39. package/core/endpoint.py +141 -0
  40. package/core/events.py +23 -0
  41. package/core/i18n.py +329 -329
  42. package/core/ice/store.py +191 -191
  43. package/core/inbound.py +193 -193
  44. package/core/jobs.py +19 -3
  45. package/core/last_good.py +150 -150
  46. package/core/llm_errors.py +227 -227
  47. package/core/llm_retry.py +230 -230
  48. package/core/memory/compressor.py +1214 -1214
  49. package/core/memory/manager.py +14 -0
  50. package/core/model_configs.py +80 -0
  51. package/core/pipeline/scheduler.py +2 -2
  52. package/core/pipeline/stages/agent_loop.py +24 -4
  53. package/core/pipeline/stages/pre_process.py +58 -7
  54. package/core/prompt_assembler.py +680 -680
  55. package/core/rg.py +255 -255
  56. package/core/security.py +1544 -1544
  57. package/core/settings_baseline.py +70 -1
  58. package/core/shell.py +5 -17
  59. package/core/skill_settings.py +7 -2
  60. package/core/state_registry.py +19 -0
  61. package/core/subagent.py +64 -3
  62. package/core/task_tool.py +1 -1
  63. package/core/tasks_notify.py +69 -4
  64. package/core/tiers.py +9 -3
  65. package/core/tool_outcome.py +108 -0
  66. package/core/update_tui.py +158 -0
  67. package/core/updater.py +229 -40
  68. package/core/version.py +2 -2
  69. package/core/web_cache.py +152 -0
  70. package/crannia_tray.py +278 -278
  71. package/creators/models.json +4 -4
  72. package/data/settings.example.json +67 -0
  73. package/licenses/GPL-3.0.txt +619 -619
  74. package/licenses/LGPL-2.1.txt +502 -502
  75. package/licenses/LGPL-3.0.txt +165 -165
  76. package/licenses/MIT-chat-on-wechat.txt +18 -18
  77. package/licenses/MIT-deepseek-harness.txt +21 -21
  78. package/licenses/Molio-LICENSE.txt +44 -44
  79. package/locales/en.json +9 -4
  80. package/main.py +154 -154
  81. package/mcpx/manager.py +522 -522
  82. package/mcpx/servers/__init__.py +22 -22
  83. package/mcpx/servers/web_search.py +321 -33
  84. package/package.json +24 -10
  85. package/providers/anthropic/client.py +772 -772
  86. package/providers/cost_table.json +3779 -3779
  87. package/providers/deepseek/client.py +20 -20
  88. package/providers/deepseek/manifest.yaml +2 -2
  89. package/providers/factory.py +136 -136
  90. package/providers/lmstudio/client.py +2 -2
  91. package/providers/metadata.py +80 -80
  92. package/providers/model_capabilities.json +6665 -6665
  93. package/providers/moonshot/client.py +12 -12
  94. package/providers/ollama/client.py +2 -2
  95. package/providers/openai/client.py +13 -13
  96. package/providers/openrouter/client.py +2 -2
  97. package/providers/qwen/__init__.py +1 -1
  98. package/providers/qwen/client.py +2 -2
  99. package/providers/qwen/manifest.yaml +16 -16
  100. package/providers/rate_limiter.py +144 -144
  101. package/providers/siliconflow/client.py +2 -2
  102. package/providers/validation.py +171 -171
  103. package/providers/window_table.json +8909 -8909
  104. package/sbom.json +4413 -4296
  105. package/skills/entertainment/SKILL.md +35 -35
  106. package/skills/entertainment/__init__.py +1 -1
  107. package/skills/entertainment/handler.py +91 -91
  108. package/skills/entertainment/manifest.yaml +26 -26
  109. package/skills/file_parser/GUIDANCE.md +10 -10
  110. package/skills/file_parser/handler.py +177 -4
  111. package/skills/file_parser/manifest.yaml +22 -1
  112. package/skills/github/SKILL.md +32 -32
  113. package/skills/github/__init__.py +1 -1
  114. package/skills/github/manifest.yaml +5 -0
  115. package/skills/mail_parser/SKILL.md +68 -68
  116. package/skills/mail_parser/__init__.py +1 -1
  117. package/skills/mail_parser/handler.py +806 -806
  118. package/skills/mail_parser/manifest.yaml +5 -0
  119. package/skills/media_gen/GUIDANCE.md +19 -19
  120. package/skills/media_gen/SKILL.md +43 -43
  121. package/skills/media_gen/__init__.py +1 -1
  122. package/skills/media_gen/handler.py +430 -430
  123. package/skills/media_gen/manifest.yaml +93 -88
  124. package/skills/office_parser/cell_validation.py +127 -127
  125. package/skills/office_parser/excel_transform.py +936 -936
  126. package/skills/office_parser/layout_spec.py +243 -243
  127. package/skills/office_parser/pptx_export/console_encoding.py +27 -27
  128. package/skills/office_parser/pptx_export/resource_paths.py +88 -88
  129. package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
  130. package/skills/office_parser/pptx_export/svg_finalize/align_embed_images.py +575 -575
  131. package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
  132. package/skills/office_parser/pptx_export/svg_finalize/embed_icons.py +498 -498
  133. package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
  134. package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
  135. package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
  136. package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
  137. package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
  138. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
  139. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
  140. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
  141. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/elements.py +2490 -2490
  142. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
  143. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/styles.py +656 -656
  144. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
  145. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
  146. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
  147. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
  148. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/media.py +141 -141
  149. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
  150. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
  151. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
  152. package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
  153. package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
  154. package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
  155. package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
  156. package/skills/office_parser/references/layout_library.md +816 -816
  157. package/skills/office_parser/references/ppt-master/LICENSE +21 -21
  158. package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
  159. package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
  160. package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
  161. package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
  162. package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
  163. package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
  164. package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
  165. package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
  166. package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
  167. package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
  168. package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
  169. package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
  170. package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
  171. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
  172. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
  173. package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
  174. package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
  175. package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
  176. package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
  177. package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
  178. package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
  179. package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
  180. package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
  181. package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
  182. package/skills/office_parser/references/spec_lock.md +235 -235
  183. package/skills/office_parser/soffice.py +68 -68
  184. package/skills/office_parser/word_tools.py +2909 -2909
  185. package/tui/crannia.cmd +134 -0
  186. package/tui/crannia_tui/__init__.py +1 -0
  187. package/tui/crannia_tui/__main__.py +223 -0
  188. package/tui/crannia_tui/app.py +1318 -0
  189. package/tui/crannia_tui/app.tcss +153 -0
  190. package/tui/crannia_tui/approval.py +85 -0
  191. package/tui/crannia_tui/backend.py +279 -0
  192. package/tui/crannia_tui/channel.py +472 -0
  193. package/tui/crannia_tui/client.py +125 -0
  194. package/tui/crannia_tui/clipboard.py +62 -0
  195. package/tui/crannia_tui/commands.py +65 -0
  196. package/tui/crannia_tui/doctor.py +304 -0
  197. package/tui/crannia_tui/events.py +84 -0
  198. package/tui/crannia_tui/headless.py +152 -0
  199. package/tui/crannia_tui/i18n.py +164 -0
  200. package/tui/crannia_tui/locales/en.json +263 -0
  201. package/tui/crannia_tui/outcome.py +62 -0
  202. package/tui/crannia_tui/paths.py +181 -0
  203. package/tui/crannia_tui/probe.py +53 -0
  204. package/tui/crannia_tui/profile.py +169 -0
  205. package/tui/crannia_tui/render.py +209 -0
  206. package/tui/crannia_tui/settings.py +134 -0
  207. package/tui/crannia_tui/setup.py +380 -0
  208. package/tui/crannia_tui/term.py +116 -0
  209. package/tui/crannia_tui/ui.py +1236 -0
  210. package/tui/crannia_tui/update.py +389 -0
  211. package/vendor/ripgrep/COPYING.txt +3 -3
  212. package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
  213. package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
  214. package/vendor/ripgrep/README.md +51 -51
  215. package/vendor/ripgrep/UNLICENSE.txt +24 -24
  216. package/vendor/ripgrep/package-source.json +19 -19
  217. package/web/__main__.py +15 -0
  218. package/web/server.py +178 -20
  219. package/web/static/img/channel-telegram.svg +1 -1
  220. package/web/static/img/channel-wechat.svg +1 -1
  221. package/web/templates/logs.html +49 -49
  222. package/web/templates/models.html +46 -46
@@ -0,0 +1,158 @@
1
+ """TUI 的更新检查:读同一份清单里的 `artifacts.tui`,下代码包。
2
+
3
+ python -m core.update_tui --dest <目录> [--channel stable|beta]
4
+
5
+ ## 它为什么在 core 里
6
+
7
+ 清单的读取(两条静态地址 + npm 源适配)只有一份实现(`core.updater`)。
8
+ TUI 的命令行不 import core(那是它的既有约定:动账本、读清单都走子进程),
9
+ 所以这里做成一个能单独跑的子进程入口,TUI 那一侧只解析这道 JSON:
10
+
11
+ {"ok": true, "version": "1.1.0", "path": "...", "sha256": "..."}
12
+ {"ok": true, "up_to_date": true, "version": "1.1.0"}
13
+ {"ok": false, "error": "..."}
14
+
15
+ ## 只认 `artifacts.tui`
16
+
17
+ GUI 的清单里 `artifacts.windows-exe` 是安装包、`artifacts.codepack` 是
18
+ GUI 的代码包;TUI 的代码包是第三件。没有这一件就说清「这一版还没有 TUI
19
+ 包」,不回退去下那个几百兆的安装包 —— 那些字节对 TUI 没用。
20
+
21
+ ## 版本比较
22
+
23
+ 与客户端同一套(`core.updater._parse_version`):正式版补位次 1、预发布
24
+ 补位次 0,所以 `1.1.1-beta < 1.1.1 < 1.1.2-alpha`。渠道默认由当前版本推
25
+ (预发布查 beta,其余查 stable)。
26
+
27
+ ASCII-only 输出(Windows 控制台默认 GBK)。
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import hashlib
34
+ import json
35
+ import sys
36
+ from pathlib import Path
37
+
38
+ from .updater import (UpdateChecker, _parse_version, channel_for_version,
39
+ log_update)
40
+ from .version import __version__
41
+
42
+ _TIMEOUT = 60
43
+
44
+
45
+ def _artifacts_tui(data: dict) -> dict | None:
46
+ latest = data.get("latest") if isinstance(data, dict) else None
47
+ if not isinstance(latest, dict):
48
+ latest = data if isinstance(data, dict) else {}
49
+ art = (latest.get("artifacts") or {}).get("tui")
50
+ if not isinstance(art, dict):
51
+ return None
52
+ urls = art.get("urls")
53
+ url_list = ([str(u).strip() for u in urls if str(u).strip()]
54
+ if isinstance(urls, (list, tuple)) else [])
55
+ if not url_list and str(art.get("url") or "").strip():
56
+ url_list = [str(art["url"]).strip()]
57
+ if not url_list:
58
+ return None
59
+ return {
60
+ "version": str(latest.get("version") or "").strip(),
61
+ "urls": url_list,
62
+ "sha256": str(art.get("sha256") or "").strip(),
63
+ "size_bytes": int(art.get("size_bytes") or 0),
64
+ }
65
+
66
+
67
+ def plan(channel: str | None = None, *, checker=None) -> dict:
68
+ """问一次清单。返回给 CLI 的那份字典(不抛网络异常)。
69
+
70
+ `checker` 只给测试用:默认按渠道造一个 `UpdateChecker`。
71
+ """
72
+ ch = channel or channel_for_version(__version__)
73
+ checker = checker or UpdateChecker(channel=ch)
74
+ problems: list = []
75
+ for source in checker.manifest_urls:
76
+ try:
77
+ data = checker._fetch_manifest(source)
78
+ except Exception as exc: # noqa: BLE001 - 一条源坏了就试下一条
79
+ problems.append("%s: %s" % (source, exc))
80
+ continue
81
+ tui = _artifacts_tui(data)
82
+ if tui is None:
83
+ problems.append("%s: 清单里没有 artifacts.tui" % source)
84
+ continue
85
+ remote = tui["version"]
86
+ if not remote:
87
+ problems.append("%s: 清单没有 version" % source)
88
+ continue
89
+ if _parse_version(remote) <= _parse_version(__version__):
90
+ return {"ok": True, "up_to_date": True, "version": remote}
91
+ return {"ok": True, "up_to_date": False, "version": remote,
92
+ "urls": tui["urls"], "sha256": tui["sha256"],
93
+ "size_bytes": tui["size_bytes"]}
94
+ return {"ok": False,
95
+ "error": ";".join(problems) or "没有可用的清单地址"}
96
+
97
+
98
+ def _download(urls: list, dest: Path, sha256: str) -> tuple[bool, str]:
99
+ """按顺序试每一条地址;下完核哈希。回 `(成功, 说明)`。"""
100
+ import requests
101
+
102
+ from core import net_proxy as _np
103
+
104
+ dest.parent.mkdir(parents=True, exist_ok=True)
105
+ part = dest.with_suffix(dest.suffix + ".part")
106
+ last: Exception | None = None
107
+ for url in urls:
108
+ try:
109
+ with requests.get(url, timeout=_TIMEOUT, stream=True,
110
+ headers={"User-Agent": f"Crannia/{__version__} "
111
+ "(Windows)"},
112
+ proxies=_np.requests_proxies()) as r:
113
+ r.raise_for_status()
114
+ h = hashlib.sha256()
115
+ with part.open("wb") as f:
116
+ for chunk in r.iter_content(chunk_size=1 << 20):
117
+ if not chunk:
118
+ continue
119
+ f.write(chunk)
120
+ h.update(chunk)
121
+ got = h.hexdigest()
122
+ if sha256 and got.lower() != sha256.lower():
123
+ part.unlink(missing_ok=True)
124
+ return False, "sha256 对不上(清单 %s,实际 %s)" % (sha256[:16], got[:16])
125
+ part.replace(dest)
126
+ return True, ""
127
+ except Exception as exc: # noqa: BLE001 - 换下一个地址
128
+ last = exc
129
+ part.unlink(missing_ok=True)
130
+ return False, "下载失败:%s" % last
131
+
132
+
133
+ def main(argv=None) -> int:
134
+ ap = argparse.ArgumentParser(description="TUI 更新检查与下载")
135
+ ap.add_argument("--dest", default="", help="下载到哪个目录(不给则只检查)")
136
+ ap.add_argument("--channel", default="", choices=("", "stable", "beta"))
137
+ args = ap.parse_args(argv)
138
+
139
+ result = plan(args.channel or None)
140
+ if not result.get("ok") or result.get("up_to_date") or not args.dest:
141
+ print(json.dumps(result, ensure_ascii=False))
142
+ return 0 if result.get("ok") else 1
143
+
144
+ dest = Path(args.dest).expanduser()
145
+ target = dest / ("crannia-tui-%s-code.zip" % result["version"])
146
+ ok, why = _download(result["urls"], target, result.get("sha256", ""))
147
+ if not ok:
148
+ print(json.dumps({"ok": False, "error": why}, ensure_ascii=False))
149
+ return 1
150
+ log_update("tui: downloaded %s from manifest v%s" % (target.name, result["version"]))
151
+ print(json.dumps({"ok": True, "version": result["version"],
152
+ "path": str(target),
153
+ "sha256": result.get("sha256", "")}, ensure_ascii=False))
154
+ return 0
155
+
156
+
157
+ if __name__ == "__main__":
158
+ sys.exit(main())
package/core/updater.py CHANGED
@@ -20,6 +20,7 @@ import json
20
20
  import os
21
21
  import re
22
22
  import shutil
23
+ import struct
23
24
  import subprocess
24
25
  import sys
25
26
  import tarfile
@@ -65,6 +66,8 @@ _update_state: dict = {
65
66
  "latest_version": None, # str | None
66
67
  "latest_manifest": None, # dict | None (raw manifest JSON)
67
68
  "downloaded_path": None, # str | None
69
+ #: 当前这一段(downloading / verifying)从什么时候开始 —— 前端给校验阶段计时用。
70
+ "phase_started": 0.0,
68
71
  #: 这一轮下的是哪一级:`codepack`(几 MB,下次启动换目录)或 `full`(安装包)。
69
72
  "kind": None,
70
73
  #: 更新源还是占位域名,根本没发请求(与"查过了、没新版本"必须分开)。
@@ -252,6 +255,59 @@ def read_update_log(max_chars: int = 20000) -> str:
252
255
  return text[-max_chars:] if max_chars else text
253
256
 
254
257
 
258
+ def _mark_phase(status: str) -> None:
259
+ """改状态的同时记下"这一段从什么时候开始"(界面给校验阶段计时)。"""
260
+ _update_state["status"] = status
261
+ _update_state["phase_started"] = time.time()
262
+
263
+
264
+ def _replace_with_retry(src: Path, dst: Path) -> None:
265
+ """`Path.replace` 带重试 —— Windows 上杀软会短暂占住刚下好的文件。
266
+
267
+ 现场形状(2026-11-22 报障):状态已经是 `verifying`,`replace` 抛
268
+ `PermissionError`(WinError 32/5),下载线程直接死掉,界面就永远停在
269
+ 「正在校验安装包…」,日志里一个字都没有。重试三次,每次失败都写日志。
270
+ """
271
+ delays = (0.5, 2.0, 5.0)
272
+ for i in range(len(delays) + 1):
273
+ try:
274
+ src.replace(dst)
275
+ return
276
+ except PermissionError as exc:
277
+ log_update("replace attempt %d/%d failed: %s"
278
+ % (i + 1, len(delays) + 1, exc))
279
+ if i >= len(delays):
280
+ raise
281
+ time.sleep(delays[i])
282
+
283
+
284
+ #: 同一时刻只许一个下载:两个线程写同一个 `.part` 会互相抢文件
285
+ #: (WinError 32 的一种来源),也会让进度与状态互相覆盖。
286
+ _DOWNLOAD_LOCK = threading.Lock()
287
+
288
+
289
+ def download_thread_entry(manifest, checker=None) -> None:
290
+ """后台下载线程的唯一入口:任何异常都落成 `error`。
291
+
292
+ 此前 `web/server.py` 的线程体是裸调用 —— 校验/落地那一抛,线程死掉,
293
+ `_update_state["status"]` 永远停在 `verifying`,而界面只看这个状态。
294
+ 自动检查与手动下载都可能起线程,所以这里还要串行化。
295
+ """
296
+ checker = checker or UpdateChecker()
297
+ if not _DOWNLOAD_LOCK.acquire(blocking=False):
298
+ log_update("download already running; this request is skipped")
299
+ return
300
+ try:
301
+ checker.download_best(manifest)
302
+ except Exception as exc: # noqa: BLE001
303
+ _update_state["status"] = "error"
304
+ _update_state["error"] = "下载线程异常:%s" % exc
305
+ log_update("download thread crashed: %s: %s"
306
+ % (type(exc).__name__, exc))
307
+ finally:
308
+ _DOWNLOAD_LOCK.release()
309
+
310
+
255
311
  def _read_config() -> dict:
256
312
  """Read config.yaml (lightweight)."""
257
313
  import yaml
@@ -553,10 +609,12 @@ def local_runtime_digest() -> str:
553
609
 
554
610
 
555
611
  def local_shell_sha256() -> str:
556
- """本地壳(`app.asar`)的哈希。
612
+ """本地壳(`app.asar`)的整包哈希。
557
613
 
558
- 代码包不包含壳与前端产物(它们在 asar 里,不是 `resources/app` 那棵树)。
559
- 所以"壳变了"必须走全量;只换 Python 树时 asar 必须逐字节一致。
614
+ 这一格不能用来判"壳变没变":asar 里的 `package.json` 带着 `version`,
615
+ 每发一版都变,整包哈希对任何跨版本更新必然不同,代码包永远用不上
616
+ (2026-11-22 现场)。新清单用 `shell_sig`,这一格只留给老客户端与
617
+ 老清单。
560
618
  """
561
619
  res = install_resources_dir()
562
620
  if res is None:
@@ -564,6 +622,97 @@ def local_shell_sha256() -> str:
564
622
  return _sha256_file(res / "app.asar")
565
623
 
566
624
 
625
+ def _asar_layout(blob: bytes) -> tuple[dict, int]:
626
+ """解析 asar 头,回 `(header, 数据区起点)`;解不开抛 `ValueError`。
627
+
628
+ 格式(`@electron/asar`):u32@4 = pickle 大小,u32@12 = header JSON 长度,
629
+ JSON 从 16 开始,文件内容从 `8 + pickle 大小` 开始。
630
+ """
631
+ if len(blob) < 16:
632
+ raise ValueError("asar too short")
633
+ pickle_size = struct.unpack("<I", blob[4:8])[0]
634
+ json_len = struct.unpack("<I", blob[12:16])[0]
635
+ if (pickle_size < json_len or 16 + json_len > len(blob)
636
+ or 8 + pickle_size > len(blob)):
637
+ raise ValueError("asar header sizes out of range")
638
+ header = json.loads(blob[16:16 + json_len].decode("utf-8"))
639
+ if not isinstance(header, dict):
640
+ raise ValueError("asar header is not an object")
641
+ return header, 8 + pickle_size
642
+
643
+
644
+ def _package_json_without_version(raw: bytes) -> bytes:
645
+ """`package.json` 去掉 `version` 再规范化 —— 别让版本号进壳签名。
646
+
647
+ 其余字段照算:依赖或入口变了,代码包仍然要回退全量。
648
+ """
649
+ try:
650
+ obj = json.loads(raw.decode("utf-8"))
651
+ except (UnicodeDecodeError, ValueError):
652
+ return raw
653
+ if not isinstance(obj, dict):
654
+ return raw
655
+ obj.pop("version", None)
656
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"),
657
+ ensure_ascii=False).encode("utf-8")
658
+
659
+
660
+ def shell_signature(asar_path) -> str:
661
+ """壳的「内容签名」—— 与版本号无关的那一半。
662
+
663
+ 为什么不能用整包 sha256:asar 里装着壳自己的 `package.json`,而它带着
664
+ `version`,每发一版都变,整包哈希对任何跨版本更新必然不同,代码包
665
+ 永远用不上,用户每次都退回 268 MB 全量
666
+ (实测 1.0.0 / 1.0.3 / 1.1.0 三个哈希互不相同)。
667
+
668
+ 判据:除 `package.json` 外,每个文件的 `(路径, 内容)` 都进哈希;
669
+ `package.json` 去掉 `version` 之后再进。`unpacked` 条目只记名字
670
+ (它们的字节不在 asar 里)。读不到 / 解不开回空串 —— 调用方 fail-closed。
671
+ """
672
+ try:
673
+ blob = Path(asar_path).read_bytes()
674
+ header, data_off = _asar_layout(blob)
675
+ except (OSError, ValueError):
676
+ return ""
677
+ entries: list[tuple[str, dict]] = []
678
+
679
+ def walk(node: dict, prefix: str) -> None:
680
+ for name, ent in (node or {}).items():
681
+ if not isinstance(ent, dict):
682
+ continue
683
+ full = prefix + name
684
+ children = ent.get("files")
685
+ if isinstance(children, dict):
686
+ walk(children, full + "/")
687
+ else:
688
+ entries.append((full, ent))
689
+
690
+ walk(header.get("files") or {}, "")
691
+ h = hashlib.sha256()
692
+ for full, ent in sorted(entries, key=lambda kv: kv[0]):
693
+ h.update(full.encode("utf-8"))
694
+ h.update(b"\0")
695
+ if ent.get("unpacked"):
696
+ h.update(b"<unpacked>")
697
+ h.update(b"\0")
698
+ continue
699
+ start = data_off + int(ent.get("offset") or 0)
700
+ payload = blob[start:start + int(ent.get("size") or 0)]
701
+ if full == "package.json":
702
+ payload = _package_json_without_version(payload)
703
+ h.update(payload)
704
+ h.update(b"\0")
705
+ return h.hexdigest()
706
+
707
+
708
+ def local_shell_sig() -> str:
709
+ """本地壳的内容签名(判据同 `shell_signature`)。"""
710
+ res = install_resources_dir()
711
+ if res is None:
712
+ return ""
713
+ return shell_signature(res / "app.asar")
714
+
715
+
567
716
  def codepack_applicable(manifest) -> bool:
568
717
  """这一版能不能只下代码包。
569
718
 
@@ -586,6 +735,11 @@ def codepack_applicable(manifest) -> bool:
586
735
  runtime = local_runtime_digest()
587
736
  if not runtime or str(cp.get("runtime") or "") != runtime:
588
737
  return False
738
+ #: 新清单带 `shell_sig`(与版本号无关的内容签名);老清单只有整包
739
+ #: `shell_sha256` —— 那个对任何跨版本更新都必然不同,只留给老客户端。
740
+ sig = str(cp.get("shell_sig") or "")
741
+ if sig:
742
+ return sig == local_shell_sig()
589
743
  shell = str(cp.get("shell_sha256") or "")
590
744
  if not shell:
591
745
  return False
@@ -940,7 +1094,7 @@ class UpdateChecker:
940
1094
  renamed to its final name. This prevents orphaned partial downloads.
941
1095
  """
942
1096
  global _update_state
943
- _update_state["status"] = "downloading"
1097
+ _mark_phase("downloading")
944
1098
  _update_state["progress"] = 0.0
945
1099
  _update_state["error"] = None
946
1100
  _update_state["kind"] = "full"
@@ -966,6 +1120,7 @@ class UpdateChecker:
966
1120
  urls = list(manifest.download_urls or []) or [manifest.download_url]
967
1121
  attempts = len(self.DOWNLOAD_RETRY_DELAYS) + 1
968
1122
  last_error: Exception | None = None
1123
+ download_started = time.time()
969
1124
  for attempt in range(1, attempts + 1):
970
1125
  for url in urls:
971
1126
  try:
@@ -973,7 +1128,12 @@ class UpdateChecker:
973
1128
  progress_callback)
974
1129
  last_error = None
975
1130
  break
976
- except requests.RequestException as exc:
1131
+ except (requests.RequestException, OSError) as exc:
1132
+ #: `OSError` 也要接:`.part` 被别的进程占着时 `open()` 抛
1133
+ #: `PermissionError: [WinError 32]`(杀软 / 并发下载),
1134
+ #: 原来它越过这条重试直接冲进线程体 —— 2026-11-22 真机
1135
+ #: 日志里那一行就是它。放过这一支等于"重试机制本身会被
1136
+ #: 一次瞬时占用打断"。
977
1137
  last_error = exc
978
1138
  log_update("download attempt %d/%d failed (%s): %s"
979
1139
  % (attempt, attempts, url, exc))
@@ -997,26 +1157,41 @@ class UpdateChecker:
997
1157
  # 「要不要校验」这个开关落在了 manifest 的提供方手上 —— 不给就跳过,
998
1158
  # 下载来的 exe 直接进安装器(`-ExecutionPolicy Bypass` + `/S` 静默)。
999
1159
  # 宁可不更新,也不装一个不知道是什么的东西。
1000
- _update_state["status"] = "verifying"
1001
- if not manifest.sha256:
1002
- dest_part.unlink(missing_ok=True)
1003
- _update_state["status"] = "error"
1004
- _update_state["error"] = ("manifest 没给 sha256 —— 拒绝投放"
1005
- "(没有校验和就无法确认这个包是什么)")
1006
- log_update("refused: manifest has no sha256")
1007
- return None
1008
- if not self.verify_checksum(dest_part, manifest.sha256):
1009
- dest_part.unlink(missing_ok=True)
1160
+ try:
1161
+ size = dest_part.stat().st_size
1162
+ except OSError:
1163
+ size = 0
1164
+ log_update("download complete: %s (%d bytes) in %.1fs -> verifying"
1165
+ % (dest_part.name, size, time.time() - download_started))
1166
+ _mark_phase("verifying")
1167
+ try:
1168
+ if not manifest.sha256:
1169
+ dest_part.unlink(missing_ok=True)
1170
+ _update_state["status"] = "error"
1171
+ _update_state["error"] = ("manifest 没给 sha256 —— 拒绝投放"
1172
+ "(没有校验和就无法确认这个包是什么)")
1173
+ log_update("refused: manifest has no sha256")
1174
+ return None
1175
+ if not self.verify_checksum(dest_part, manifest.sha256):
1176
+ dest_part.unlink(missing_ok=True)
1177
+ _update_state["status"] = "error"
1178
+ _update_state["error"] = "SHA256 checksum mismatch — download discarded"
1179
+ log_update("refused: sha256 mismatch")
1180
+ return None
1181
+ log_update("verify ok: %s" % dest_part.name)
1182
+
1183
+ # 收口用 replace,不用 rename。Windows 上 os.rename 碰到已存在的目标会抛
1184
+ # FileExistsError,于是同一个版本下第二次下载(装失败后点重试,或者上次
1185
+ # 下到一半断了)必然失败,而那句错误看起来像磁盘坏了。走到这里时哈希
1186
+ # 已经验过,覆盖是事先想清楚的事,不是巧合。
1187
+ # 杀软可能正扫着这个刚下好的 exe,重试在 `_replace_with_retry`。
1188
+ _replace_with_retry(dest_part, dest_final)
1189
+ except OSError as exc:
1010
1190
  _update_state["status"] = "error"
1011
- _update_state["error"] = "SHA256 checksum mismatch — download discarded"
1012
- log_update("refused: sha256 mismatch")
1191
+ _update_state["error"] = ("安装包落地失败(文件可能被杀毒软件占用):%s"
1192
+ % exc)
1193
+ log_update("finalize failed: %s" % exc)
1013
1194
  return None
1014
-
1015
- # 收口用 replace,不用 rename。Windows 上 os.rename 碰到已存在的目标会抛
1016
- # FileExistsError,于是同一个版本下第二次下载(装失败后点重试,或者上次
1017
- # 下到一半断了)必然失败,而那句错误看起来像磁盘坏了。走到这里时哈希
1018
- # 已经验过,覆盖是事先想清楚的事,不是巧合。
1019
- dest_part.replace(dest_final)
1020
1195
  _update_state["status"] = "ready"
1021
1196
  _update_state["downloaded_path"] = str(dest_final)
1022
1197
  mark_pending(manifest, dest_final)
@@ -1055,7 +1230,7 @@ class UpdateChecker:
1055
1230
  #: 才是权威。两种哈希认一种即可,两样都没有就拒绝。
1056
1231
  integrity = str(cp.get("integrity") or "")
1057
1232
  _update_state["kind"] = "codepack"
1058
- _update_state["status"] = "downloading"
1233
+ _mark_phase("downloading")
1059
1234
  _update_state["progress"] = 0.0
1060
1235
  _update_state["error"] = None
1061
1236
 
@@ -1087,7 +1262,7 @@ class UpdateChecker:
1087
1262
  progress_callback)
1088
1263
  last_error = None
1089
1264
  break
1090
- except requests.RequestException as exc:
1265
+ except (requests.RequestException, OSError) as exc:
1091
1266
  last_error = exc
1092
1267
  log_update("codepack attempt %d/%d failed (%s): %s"
1093
1268
  % (attempt, attempts, candidate, exc))
@@ -1102,18 +1277,32 @@ class UpdateChecker:
1102
1277
  _update_state["error"] = "Code pack download error: %s" % last_error
1103
1278
  return None
1104
1279
 
1105
- _update_state["status"] = "verifying"
1106
- verified = (_sha256_file(dest_part) == expected) if expected \
1107
- else (_sha512_integrity(dest_part) == integrity)
1108
- if not verified:
1109
- dest_part.unlink(missing_ok=True)
1280
+ try:
1281
+ size = dest_part.stat().st_size
1282
+ except OSError:
1283
+ size = 0
1284
+ log_update("code pack download complete: %s (%d bytes) -> verifying"
1285
+ % (dest_part.name, size))
1286
+ _mark_phase("verifying")
1287
+ try:
1288
+ verified = (_sha256_file(dest_part) == expected) if expected \
1289
+ else (_sha512_integrity(dest_part) == integrity)
1290
+ if not verified:
1291
+ dest_part.unlink(missing_ok=True)
1292
+ _update_state["status"] = "error"
1293
+ _update_state["error"] = ("Code pack %s mismatch — discarded"
1294
+ % ("sha256" if expected else "integrity"))
1295
+ log_update("code pack refused: %s mismatch"
1296
+ % ("sha256" if expected else "integrity"))
1297
+ return None
1298
+ log_update("code pack verify ok: %s" % dest_part.name)
1299
+ _replace_with_retry(dest_part, dest_final)
1300
+ except OSError as exc:
1110
1301
  _update_state["status"] = "error"
1111
- _update_state["error"] = ("Code pack %s mismatch — discarded"
1112
- % ("sha256" if expected else "integrity"))
1113
- log_update("code pack refused: %s mismatch"
1114
- % ("sha256" if expected else "integrity"))
1302
+ _update_state["error"] = ("代码包落地失败(文件可能被杀毒软件占用):%s"
1303
+ % exc)
1304
+ log_update("code pack finalize failed: %s" % exc)
1115
1305
  return None
1116
- dest_part.replace(dest_final)
1117
1306
 
1118
1307
  try:
1119
1308
  new_dir = _extract_codepack(dest_final, res)
@@ -1441,11 +1630,11 @@ def background_startup_check() -> None:
1441
1630
  if installed:
1442
1631
  already = pending_install()
1443
1632
  if not (already and already.get("version") == manifest.version):
1444
- try:
1445
- checker.download_best(manifest)
1446
- except Exception as exc: # noqa: BLE001
1447
- log_update("download crashed: %s: %s"
1448
- % (type(exc).__name__, exc))
1633
+ #: 走同一条入口:任何异常都落成 `error`。此前这里是
1634
+ #: 裸调用 + 只记日志 —— 状态停在 `downloading`,
1635
+ #: 界面一直转,而下面那格还照样写 24h 时间戳
1636
+ #: (2026-11-22 报障日志的现场)。
1637
+ download_thread_entry(manifest, checker)
1449
1638
  if _update_state.get("status") == "error":
1450
1639
  #: 下载失败:不写时间戳 —— 下次启动从 `.part` 续传。
1451
1640
  log_update("download failed: %s"
package/core/version.py CHANGED
@@ -9,6 +9,6 @@ canonical source. Keep pyproject.toml `version` field in sync manually
9
9
  or use [tool.hatch.version] path = "core/version.py".
10
10
  """
11
11
 
12
- __version__ = "1.0.0"
13
- __version_tuple__ = (1, 0, 0)
12
+ __version__ = "1.1.1"
13
+ __version_tuple__ = (1, 1, 1)
14
14
  __build__ = ""