dsh-snowbreak-heimdall 3.0.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 (68) hide show
  1. package/LICENSE +29 -0
  2. package/README.md +175 -0
  3. package/SHA256SUMS.txt +61 -0
  4. package/TEST-REPORT.md +96 -0
  5. package/assets/icons/app-512.png +0 -0
  6. package/assets/icons/app-light-512.png +0 -0
  7. package/assets/icons/app.ico +0 -0
  8. package/assets/icons/apple-touch-icon.png +0 -0
  9. package/assets/icons/favicon-dark.svg +5 -0
  10. package/assets/icons/favicon.svg +5 -0
  11. package/assets/icons/icon-192.png +0 -0
  12. package/assets/icons/icon-512.png +0 -0
  13. package/assets/icons/icon-maskable-512.png +0 -0
  14. package/assets/icons/icon.svg +5 -0
  15. package/assets/icons/res-icon.png +0 -0
  16. package/assets/icons/tray.ico +0 -0
  17. package/assets/previews/assets/hm-mark-blue.png +0 -0
  18. package/assets/previews/brand-fix.png +0 -0
  19. package/assets/previews/exe-icon-test.png +0 -0
  20. package/assets/previews/loading-dark.html +443 -0
  21. package/assets/previews/loading-dark.png +0 -0
  22. package/assets/previews/loading-fallback.html +443 -0
  23. package/assets/previews/loading-fallback.png +0 -0
  24. package/assets/previews/loading-handoff.html +457 -0
  25. package/assets/previews/loading-light.html +443 -0
  26. package/assets/previews/loading-light.png +0 -0
  27. package/assets/previews/mask-test.png +0 -0
  28. package/assets/previews/progress-winforms-complete.png +0 -0
  29. package/assets/previews/progress-winforms.png +0 -0
  30. package/assets/previews/ui-chrome.html +24 -0
  31. package/assets/previews/ui-chrome.png +0 -0
  32. package/assets/source/brand-client.js +95 -0
  33. package/assets/source/client-template.js +217 -0
  34. package/assets/source/hm-mark-blue.png +0 -0
  35. package/assets/source/hm-mark-ink.png +0 -0
  36. package/assets/source/hm-mark-light.png +0 -0
  37. package/assets/source/loading.css +373 -0
  38. package/assets/source/loading.html +58 -0
  39. package/assets/source/logo.webp +0 -0
  40. package/assets/source/mark-alpha.png +0 -0
  41. package/assets/source/mark-color.png +0 -0
  42. package/assets/source/progress.ps1 +312 -0
  43. package/assets/source/shell.css +475 -0
  44. package/assets/source/shell.js +293 -0
  45. package/assets/source/update.css +47 -0
  46. package/assets/source/watermark-soft.png +0 -0
  47. package/assets/source/welcome-brand.svg +18 -0
  48. package/assets/source/welcome-mark-ink.png +0 -0
  49. package/assets/source/welcome-mark-light.png +0 -0
  50. package/assets/source/welcome.css +121 -0
  51. package/cordis.patch.yml +4 -0
  52. package/icon.svg +5 -0
  53. package/lib/client.js +217 -0
  54. package/lib/index.js +239 -0
  55. package/locale/en.json +6 -0
  56. package/locale/zh.json +6 -0
  57. package/package.json +47 -0
  58. package/patch/asar.py +237 -0
  59. package/patch/patcher.py +1307 -0
  60. package/tools/build_assets.py +206 -0
  61. package/tools/build_client.py +21 -0
  62. package/tools/test_lock.py +28 -0
  63. package/tools/test_progress_launch.py +44 -0
  64. package/tools/test_progress_ps1.py +38 -0
  65. package/tools/test_progress_ps1_complete.py +38 -0
  66. package/vendor/rcedit/LICENSE +20 -0
  67. package/vendor/rcedit/README.md +51 -0
  68. package/vendor/rcedit/rcedit-x64.exe +0 -0
@@ -0,0 +1,1307 @@
1
+ #!/usr/bin/env python3
2
+ """Snowbreak / Heimdall Terminal source-layer installer for DSH 0.2.2-rc.1.
3
+
4
+ This is intentionally narrow: it patches the installed DSH resources, keeps a
5
+ verified backup inside the DSH installation, and restores only when the current
6
+ archive is provably one this tool wrote. A newer DSH archive is never
7
+ overwritten by an older backup.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import base64
13
+ import hashlib
14
+ import json
15
+ import os
16
+ import re
17
+ import shutil
18
+ import subprocess
19
+ import sys
20
+ import time
21
+
22
+ HERE = os.path.dirname(os.path.abspath(__file__))
23
+ ROOT = os.path.dirname(HERE)
24
+ ASSETS = os.path.join(ROOT, "assets")
25
+ SOURCE = os.path.join(ASSETS, "source")
26
+ ICONS = os.path.join(ASSETS, "icons")
27
+ sys.path.insert(0, HERE)
28
+ import asar # noqa: E402
29
+
30
+ FRONTEND = "dsh/node_modules/@deepseek-ai/dsh-web-frontend/dist"
31
+ BRAND = "dsh/node_modules/@deepseek-ai/dsh-client-ui-brand-official/lib/client.js"
32
+ MENU_FILES = ("lib/preload-app.cjs", "lib/main.js", "lib/preload-welcome.cjs")
33
+ STATE_JSON = "state.json"
34
+ LOG_NAME = "heimdall.log"
35
+ MARKER = "HEIMDALL-SOURCE-V1"
36
+
37
+ DEFAULT_TARGET = os.path.join(
38
+ os.environ.get("LOCALAPPDATA", ""), "Programs", "DeepSeek Harness",
39
+ "resources", "app.asar",
40
+ )
41
+
42
+ STATE_DIR = ""
43
+ LOG_FILE = ""
44
+ BACKUP_ROOT = ""
45
+ PROFILE_DIR = ""
46
+ TEST_MODE = False
47
+ PROGRESS_STARTED = False
48
+ PROGRESS_MODE = "apply"
49
+ APP_EXE = ""
50
+
51
+
52
+ def progress_file():
53
+ return os.path.join(STATE_DIR, "progress.txt")
54
+
55
+
56
+ def write_progress(pct, stage, text="", error=None, done=False):
57
+ try:
58
+ os.makedirs(STATE_DIR, exist_ok=True)
59
+ lines = [
60
+ "pct=" + str(max(0, min(100, int(pct)))),
61
+ "stage=" + str(stage or ""),
62
+ "text=" + str(text or ""),
63
+ "error=" + str(error or ""),
64
+ "done=" + ("1" if done and not error else "0"),
65
+ "mode=" + PROGRESS_MODE,
66
+ ]
67
+ tmp = progress_file() + ".tmp"
68
+ with open(tmp, "w", encoding="utf-16-le", newline="\n") as handle:
69
+ handle.write("\ufeff" + "\n".join(lines) + "\n")
70
+ os.replace(tmp, progress_file())
71
+ except OSError as exc:
72
+ log("progress write failed: %s" % exc)
73
+
74
+
75
+ def launch_progress(mode="apply"):
76
+ """Show a fixed, borderless WS_POPUP progress window after DSH has exited."""
77
+ global PROGRESS_STARTED, PROGRESS_MODE
78
+ if PROGRESS_STARTED:
79
+ return
80
+ PROGRESS_MODE = "restore" if mode == "restore" else "apply"
81
+ try:
82
+ template_path = os.path.join(SOURCE, "progress.ps1")
83
+ with open(template_path, encoding="utf-8") as handle:
84
+ template = handle.read()
85
+ progress_path = progress_file()
86
+ logo_path = os.path.join(SOURCE, "hm-mark-light.png")
87
+ script = (template.replace("__PROGRESS_PATH__", progress_path)
88
+ .replace("__LOGO_PATH__", logo_path)
89
+ .replace("__APP_EXE__", APP_EXE))
90
+ out = os.path.join(STATE_DIR, "progress.ps1")
91
+ with open(out, "w", encoding="utf-8-sig", newline="\n") as handle:
92
+ handle.write(script)
93
+ write_progress(1, "WAIT", "正在等待 DSH 完全退出…")
94
+ powershell = os.path.join(
95
+ os.environ.get("SystemRoot", r"C:\Windows"),
96
+ "System32", "WindowsPowerShell", "v1.0", "powershell.exe",
97
+ )
98
+ subprocess.Popen(
99
+ [powershell, "-NoProfile", "-NonInteractive", "-STA",
100
+ "-ExecutionPolicy", "Bypass", "-File", out],
101
+ close_fds=True, creationflags=0x08000000, # CREATE_NO_WINDOW
102
+ )
103
+ PROGRESS_STARTED = True
104
+ log("progress window launched")
105
+ except OSError as exc:
106
+ log("progress window failed: %s" % exc)
107
+
108
+
109
+ ZH_MAP = {
110
+ # Native menus / about / quit
111
+ "application": "终端",
112
+ "aboutMenu": "关于海姆达尔终端",
113
+ "aboutProduct": "海姆达尔终端",
114
+ "hideApplication": "隐藏海姆达尔终端",
115
+ "quitApplication": "终止接入",
116
+ "openApplication": "打开海姆达尔终端",
117
+ "quit": "终止接入",
118
+ "quitTitle": "终止海姆达尔终端接入?",
119
+ "quitActiveTasks": "当前接入链路将中断。",
120
+ "quitScheduledTasks": "终端关闭期间,定时序列不会运行。",
121
+ "quitActiveAndScheduledTasks": "当前接入链路将中断,且终端关闭期间定时序列不会运行。",
122
+ "backgroundNoticeBody": "任务仍在运行,可从系统托盘重新打开终端窗口",
123
+ "edit": "操作",
124
+ "menuBar": "终端菜单",
125
+ "delete": "清除",
126
+ "undo": "回退",
127
+ "redo": "重做",
128
+ "cut": "截取",
129
+ "copy": "复制",
130
+ "paste": "粘贴",
131
+ "selectAll": "全选",
132
+ "startupFailed": "海姆达尔终端无法使用",
133
+ "fatalSummary": "终端未能启动或已意外停止。",
134
+ "exitApplication": "终止接入",
135
+ "restartApplication": "重启终端",
136
+ "disableThirdPartyPlugins": "停用第三方模块、备份 profile patch 并重启",
137
+ "checkUpdatesMenu": "检查终端维护包…",
138
+ "reloadPageMenu": "刷新终端页面",
139
+ "toggleDevToolsMenu": "维护工具",
140
+ "restartAppHostMenu": "重启终端 Host",
141
+ "cliCommandMenu": "管理终端指令…",
142
+ "cliCommandTitle": "管理终端指令",
143
+ "cliCommandLocation": "终端指令位置:{path}",
144
+ "cliCommandSelected": "当前终端指令:{path}",
145
+ "cliCommandTarget": "当前接入目标:{path}",
146
+ "cliCommandShadowed": "检测到另一个终端接入点优先级更高。请调整安装顺序,或以完整路径运行终端指令。",
147
+ "cliCommandSelectionUnknown": "无法确认当前终端指令。别名或另一个接入点可能具有更高优先级。",
148
+ "cliCommandInstalled": "终端指令已接入。",
149
+ "cliCommandNotInstalled": "将终端指令接入当前终端。",
150
+ "cliCommandBroken": "终端指令需要校准。",
151
+ "cliCommandInstall": "接入",
152
+ "cliCommandRepair": "校准",
153
+ "cliCommandRemove": "解除",
154
+ "cliCommandClose": "关闭",
155
+ "cliCommandSwitch": "继续使用终端指令?",
156
+ "cliCommandPreserve": "现有指令会被保留,不会修改其他接入点或启动文件。",
157
+ "cliCommandContinue": "继续",
158
+ "cliCommandInstallApp": "请先将终端接入“应用程序”文件夹,再管理终端指令。",
159
+ "cliCommandUpdating": "正在安装维护包。请在完成后管理终端指令。",
160
+ "cliCommandNewTerminal": "打开新终端并运行 dsh --version。",
161
+ "cliCommandRemoved": "已解除终端指令注册。",
162
+ "cliCommandPreviousRestored": "已恢复之前的接入点。",
163
+ "cliCommandOtherKept": "其他接入点保持不变。",
164
+ "cliCommandBackupKept": "之前的接入点保留在:{path}",
165
+ "cliCommandChanged": "对话框打开期间终端指令或 PATH 已改变。请重新打开“管理终端指令”检查当前状态。",
166
+ "cliCommandOwnershipError": "终端指令注册或备份已改变,未解除无关指令。",
167
+ "cliCommandFailed": "无法更新终端指令。请检查应用是否已安装、目标位置是否可写,然后重试。",
168
+ # Welcome / sign-in shell
169
+ "welcomeTitle": "海姆达尔终端",
170
+ "welcomeBrand": "海姆达尔终端",
171
+ "welcomeTaglineBefore": "欢迎接入 ",
172
+ "welcomeTaglineBrand": "海姆达尔终端",
173
+ "welcomeDescription": "世界树公司 · 海姆达尔部队 · 零区战术终端",
174
+ "welcomeAuthStarting": "正在验证分析员身份…",
175
+ "welcomeAuthWaiting": "未自动打开身份验证页?",
176
+ "welcomeAuthWaitingDescription": "复制验证链接,在浏览器中完成世界树身份验证。",
177
+ "welcomeAuthExchanging": "正在建立接入链路…",
178
+ "welcomeAuthExpired": "身份验证已超时",
179
+ "welcomeAuthExpiredDescription": "请重新验证后继续",
180
+ "welcomeAuthFailed": "身份验证未完成,请重试。",
181
+ "welcomeAuthCopyLink": "复制验证链接",
182
+ "welcomeAuthCopied": "已复制",
183
+ "welcomeAuthCopyFailed": "复制失败,请重试",
184
+ "welcomeAuthCancel": "中止",
185
+ "welcomeAuthRetry": "重新验证",
186
+ "welcomeSignIn": "验证分析员身份",
187
+ "welcomeApiKey": "配置接入密钥",
188
+ "welcomeKeyTitle": "输入接入密钥",
189
+ "welcomeKeyDescription": "通过世界树认证链路接入海姆达尔终端",
190
+ "welcomeKeyPlaceholder": "输入接入密钥",
191
+ "welcomeKeySave": "验证并接入",
192
+ "welcomeKeyLater": "稍后配置",
193
+ "welcomeKeyBack": "返回身份验证",
194
+ "welcomeSessionExpired": "接入凭证已失效,请重新验证。",
195
+ "welcomeKeyBlank": "请输入接入密钥。",
196
+ "welcomeKeyInvalid": "请输入接入密钥本体,不要包含引号、空格或环境变量赋值。",
197
+ "welcomeKeyFailed": "无法保存接入密钥,请重试。",
198
+ "welcomeContinueFailed": "无法打开作业区,请重试。",
199
+ # Update shell
200
+ "updateCheckFailedTitle": "终端维护包检查失败",
201
+ "updateCheckFailed": "无法检查终端维护包,请稍后重试。",
202
+ "updateDownloadFailed": "维护包下载失败,请重试。",
203
+ "updateInstallFailed": "维护包安装失败,请稍后重试。",
204
+ "updateCheckNetworkFailed": "无法检查维护包,请检查网络后重试。",
205
+ "updateDownloadNetworkFailed": "维护包下载失败,请检查网络后重试。",
206
+ "updateInstallNetworkFailed": "维护包安装失败,请检查网络后重试。",
207
+ "updateCheckTitle": "检查终端维护包",
208
+ "updateCurrentDetail": "当前终端版本:{version}",
209
+ "updateCurrent": "终端已是最新版本",
210
+ "updateChecking": "正在检查维护包…",
211
+ "updateDownload": "下载维护包",
212
+ "updateDownloadedTitle": "维护包 {version} 已就绪",
213
+ "updateDownloadedDetail": "安装期间终端将暂时关闭,完成后自动重新接入。",
214
+ "updateDownloadedDetailWindows": "安装期间终端将暂时关闭,完成后自动重新接入。\n\n维护可能需要一些时间,请勿重复启动终端。",
215
+ "updateLater": "稍后维护",
216
+ "updateDownloading": "正在下载 {percent}%…",
217
+ "updateVerifying": "正在校验维护包…",
218
+ "updateInstalling": "正在准备重启…",
219
+ "updateRetry": "重新尝试维护",
220
+ "updateActiveTasks": "仍有进行中的任务",
221
+ "updateActiveTasksDetail": "维护将停止进行中的任务并重启终端,是否继续?",
222
+ "updateStopTasks": "停止任务并维护",
223
+ "updateTasksChanged": "有新的任务开始运行,请重新确认是否停止任务并维护。",
224
+ "updateTasksUnavailable": "无法确认任务状态,请在作业区就绪后重试维护。",
225
+ "updateFullscreenTimeout": "无法退出全屏,请退出全屏后重试维护",
226
+ "updateStopFailed": "未能安全停止任务,维护尚未安装,请稍后重试。",
227
+ "updateTechnicalDetails": "查看技术详情",
228
+ "updateTitle": "海姆达尔终端 · 维护更新",
229
+ "updateAvailable": "发现维护包 {version}",
230
+ "updateDetail": "下载完成后,可安装维护包并重启终端。",
231
+ "installAndRestart": "安装并重启",
232
+ "updateFailedTitle": "终端维护失败",
233
+ "mandatoryTitle": "请完成维护后继续接入",
234
+ "mandatoryDetail": "当前终端版本已停止支持。确认安装并重启前,进行中的任务会继续运行。",
235
+ "mandatoryUnavailable": "暂时无法检查维护要求,请稍后重试。",
236
+ "policyLoginTitle": "验证世界树身份",
237
+ "policyLoginRequired": "此测试终端需要先完成身份验证,才能检查维护要求。验证不会下载或安装维护包。",
238
+ "policyLogin": "验证世界树身份",
239
+ }
240
+
241
+ # Source-level UI strings that live in the shipped client bundles.
242
+ # Keep the actual model ids untouched; only display names and Chinese copy.
243
+ UI_TEXT = {
244
+ "dsh/node_modules/@deepseek-ai/dsh-client-ui-conversation/lib/client.js": [
245
+ ("探索未至之境", "接入零区"),
246
+ ("预览版", "战术预览"),
247
+ ("选择工作区", "选择作业区"),
248
+ ("新会话", "建立接入"),
249
+ ("新建会话", "建立接入"),
250
+ ("工作区", "作业区"),
251
+ ("会话", "接入"),
252
+ ],
253
+ "dsh/node_modules/@deepseek-ai/dsh-client-ui-workspace/lib/client.js": [
254
+ ("新会话", "建立接入"),
255
+ ("工作区", "作业区"),
256
+ ("会话", "接入"),
257
+ ],
258
+ "dsh/node_modules/@deepseek-ai/dsh-client-ui-agent-preset/lib/client.js": [
259
+ ("工作区", "作业区"),
260
+ ("会话", "接入"),
261
+ ],
262
+ "dsh/node_modules/@deepseek-ai/dsh-client-ui-permission-presets/lib/client.js": [
263
+ ("工作区内修改", "作业区内修改"),
264
+ ("新会话", "新接入"),
265
+ ("会话", "接入"),
266
+ ],
267
+ "dsh/node_modules/@deepseek-ai/dsh-llm-deepseek/lib/index.js": [
268
+ ('name: "DeepSeek-V4.1-Flash"', 'name: "世界树-V4.1-Flash"'),
269
+ ('name: "DeepSeek-V4-Pro"', 'name: "世界树-V4-Pro"'),
270
+ ],
271
+ }
272
+
273
+
274
+ def now():
275
+ return time.strftime("%Y-%m-%dT%H:%M:%S%z")
276
+
277
+
278
+ def configure(target, state_dir=None, profile_dir=None, test_mode=False):
279
+ global STATE_DIR, LOG_FILE, BACKUP_ROOT, PROFILE_DIR, TEST_MODE, APP_EXE
280
+ TEST_MODE = bool(test_mode)
281
+ resources = os.path.dirname(os.path.abspath(target))
282
+ APP_EXE = os.path.join(os.path.dirname(resources), "DeepSeek Harness.exe")
283
+ STATE_DIR = os.path.abspath(state_dir or os.environ.get("HEIMDALL_STATE_DIR")
284
+ or os.path.join(resources, "HeimdallTerminal"))
285
+ LOG_FILE = os.path.join(STATE_DIR, LOG_NAME)
286
+ BACKUP_ROOT = os.path.join(STATE_DIR, "backup")
287
+ PROFILE_DIR = os.path.abspath(profile_dir or os.environ.get("DSH_PROFILE_DIR") or "")
288
+ if not TEST_MODE:
289
+ if os.path.basename(target).lower() != "app.asar":
290
+ raise SystemExit("refusing target: not app.asar")
291
+ install = os.path.dirname(resources)
292
+ if not os.path.isfile(os.path.join(install, "DeepSeek Harness.exe")):
293
+ raise SystemExit("refusing target: not inside a DeepSeek Harness installation")
294
+ if os.path.commonpath([os.path.abspath(target), install]) != install:
295
+ raise SystemExit("refusing target: outside the installation")
296
+ if os.path.commonpath([STATE_DIR, resources]) != resources:
297
+ raise SystemExit("refusing state dir: outside resources")
298
+ os.makedirs(STATE_DIR, exist_ok=True)
299
+
300
+
301
+ def log(message):
302
+ line = "[%s] %s" % (now(), message)
303
+ try:
304
+ os.makedirs(STATE_DIR, exist_ok=True)
305
+ with open(LOG_FILE, "a", encoding="utf-8") as handle:
306
+ handle.write(line + "\n")
307
+ except OSError:
308
+ pass
309
+ print(line)
310
+
311
+
312
+ def state_path():
313
+ return os.path.join(STATE_DIR, STATE_JSON)
314
+
315
+
316
+ def load_state():
317
+ try:
318
+ with open(state_path(), encoding="utf-8-sig") as handle:
319
+ data = json.load(handle)
320
+ return data if isinstance(data, dict) else {}
321
+ except (OSError, ValueError):
322
+ return {}
323
+
324
+
325
+ def save_state(state):
326
+ os.makedirs(STATE_DIR, exist_ok=True)
327
+ tmp = state_path() + ".tmp"
328
+ with open(tmp, "w", encoding="utf-8", newline="\n") as handle:
329
+ json.dump(state, handle, ensure_ascii=False, indent=2)
330
+ handle.write("\n")
331
+ os.replace(tmp, state_path())
332
+
333
+
334
+ def sha256_file(path):
335
+ digest = hashlib.sha256()
336
+ with open(path, "rb") as handle:
337
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
338
+ digest.update(chunk)
339
+ return digest.hexdigest()
340
+
341
+
342
+ def sha256_bytes(data):
343
+ return hashlib.sha256(data).hexdigest()
344
+
345
+
346
+ def read_asset(*parts):
347
+ with open(os.path.join(*parts), "rb") as handle:
348
+ return handle.read()
349
+
350
+
351
+ def replace_retry(src, dst, tries=90, delay=1.0):
352
+ last = None
353
+ for _ in range(tries):
354
+ try:
355
+ os.replace(src, dst)
356
+ return
357
+ except PermissionError as exc:
358
+ last = exc
359
+ time.sleep(delay)
360
+ raise last or PermissionError("replace failed")
361
+
362
+
363
+ def wait_unlocked(path, timeout=180):
364
+ end = time.time() + timeout
365
+ while time.time() < end:
366
+ try:
367
+ fd = os.open(path, os.O_RDWR)
368
+ os.close(fd)
369
+ return True
370
+ except OSError:
371
+ time.sleep(1)
372
+ return False
373
+
374
+
375
+ def dsh_running():
376
+ try:
377
+ result = subprocess.run(
378
+ ["tasklist", "/FI", "IMAGENAME eq DeepSeek Harness.exe", "/NH"],
379
+ capture_output=True, text=True, creationflags=0x08000000,
380
+ )
381
+ return "DeepSeek Harness.exe" in (result.stdout or "")
382
+ except Exception:
383
+ return True
384
+
385
+
386
+ def pid_alive(pid):
387
+ """Ask tasklist instead of OpenProcess; OpenProcess can return a handle for a
388
+ just-dead PID on this host, which would leave a stale sync.lock forever."""
389
+ try:
390
+ result = subprocess.run(
391
+ ["tasklist", "/FI", "PID eq %d" % int(pid), "/FO", "CSV", "/NH"],
392
+ capture_output=True, text=True, creationflags=0x08000000,
393
+ )
394
+ output = (result.stdout or "").strip()
395
+ if not output or "No tasks" in output or "没有运行" in output:
396
+ return False
397
+ return ('","%d","' % int(pid)) in output
398
+ except Exception:
399
+ return True
400
+
401
+
402
+ def acquire_sync_lock():
403
+ """One helper at a time: two concurrent restores corrupt each other."""
404
+ lock = os.path.join(STATE_DIR, "sync.lock")
405
+ for _ in range(4):
406
+ try:
407
+ fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
408
+ os.write(fd, str(os.getpid()).encode("ascii"))
409
+ os.close(fd)
410
+ return True
411
+ except FileExistsError:
412
+ owner = 0
413
+ try:
414
+ with open(lock, encoding="ascii") as handle:
415
+ owner = int(handle.read().strip() or "0")
416
+ except (OSError, ValueError):
417
+ owner = 0
418
+ if owner and pid_alive(owner):
419
+ return False
420
+ try:
421
+ os.remove(lock)
422
+ except OSError:
423
+ return False
424
+ except OSError:
425
+ return False
426
+ return False
427
+
428
+
429
+ def wait_for_pid(pid):
430
+ """Block on the host process handle; zero CPU while DSH stays open."""
431
+ if os.name != "nt" or not pid:
432
+ return False
433
+ try:
434
+ import ctypes
435
+ synchronize = 0x00100000
436
+ handle = ctypes.windll.kernel32.OpenProcess(synchronize, False, int(pid))
437
+ if not handle:
438
+ return False
439
+ try:
440
+ ctypes.windll.kernel32.WaitForSingleObject(handle, 0xFFFFFFFF)
441
+ finally:
442
+ ctypes.windll.kernel32.CloseHandle(handle)
443
+ return True
444
+ except Exception:
445
+ return False
446
+
447
+
448
+ def archive_version(tree=None, target=None):
449
+ try:
450
+ with open(target, "rb") as handle:
451
+ if tree is None:
452
+ tree, hs = asar.read_header(handle)
453
+ else:
454
+ _, hs = asar.read_header(handle)
455
+ entry = asar.find(tree, "dsh/package.json")
456
+ data = asar.read_entry(handle, hs, entry)
457
+ return json.loads(data).get("version", "unknown")
458
+ except Exception:
459
+ return "unknown"
460
+
461
+
462
+ def plugin_present():
463
+ if not PROFILE_DIR:
464
+ return False
465
+ link = os.path.join(PROFILE_DIR, "node_modules", "@local", "snowbreak-heimdall")
466
+ return os.path.exists(link)
467
+
468
+
469
+ def plugin_enabled():
470
+ if not plugin_present():
471
+ return False
472
+ try:
473
+ with open(os.path.join(PROFILE_DIR, "package.json"), encoding="utf-8-sig") as handle:
474
+ pkg = json.load(handle)
475
+ except (OSError, ValueError):
476
+ return True
477
+ deps = pkg.get("dependencies") or {}
478
+ if "@local/snowbreak-heimdall" not in deps:
479
+ return False
480
+ bundles = ((pkg.get("dsh") or {}).get("profile") or {}).get("bundles") or []
481
+ if "@local/snowbreak-heimdall" not in bundles:
482
+ return False
483
+ # The Plugin Manager persists a per-row disable in the user's patch layer.
484
+ # That row wins over the bundle list, so the helper must read it too.
485
+ try:
486
+ with open(os.path.join(PROFILE_DIR, "cordis.patch.yml"), encoding="utf-8-sig") as handle:
487
+ lines = handle.read().splitlines()
488
+ except OSError:
489
+ return True
490
+ inside = False
491
+ for line in lines:
492
+ stripped = line.strip()
493
+ if stripped.startswith("- id:"):
494
+ value = stripped.split(":", 1)[1].strip().strip('"\'')
495
+ if inside:
496
+ break
497
+ inside = value == "snowbreak-heimdall"
498
+ continue
499
+ if not inside:
500
+ continue
501
+ if re.match(r"disabled\s*:\s*true\b", stripped, re.I) or \
502
+ re.match(r"enabled\s*:\s*false\b", stripped, re.I):
503
+ return False
504
+ return True
505
+
506
+
507
+ # --------------------------------------------------------------- asar patches
508
+ def replace_zh_block(text, mapping):
509
+ marker = "zh: {"
510
+ at = text.find(marker)
511
+ if at < 0:
512
+ return text, []
513
+ start = text.find("{", at + len("zh:"))
514
+ if start < 0:
515
+ return text, []
516
+ depth = 0
517
+ in_string = False
518
+ escaped = False
519
+ end = -1
520
+ for index in range(start, len(text)):
521
+ char = text[index]
522
+ if in_string:
523
+ if escaped:
524
+ escaped = False
525
+ elif char == "\\":
526
+ escaped = True
527
+ elif char == '"':
528
+ in_string = False
529
+ continue
530
+ if char == '"':
531
+ in_string = True
532
+ elif char == "{":
533
+ depth += 1
534
+ elif char == "}":
535
+ depth -= 1
536
+ if depth == 0:
537
+ end = index
538
+ break
539
+ if end < 0:
540
+ return text, []
541
+ block = text[start:end + 1]
542
+ changed = []
543
+ for key, value in mapping.items():
544
+ pattern = re.compile(
545
+ r"(?<![A-Za-z0-9_])(" + re.escape(key) + r")(\s*:\s*)\"((?:\\.|[^\"\\])*)\""
546
+ )
547
+ replacement = lambda match, v=value: match.group(1) + match.group(2) + json.dumps(v, ensure_ascii=False)
548
+ block, count = pattern.subn(replacement, block, count=1)
549
+ if count:
550
+ changed.append(key)
551
+ return text[:start] + block + text[end + 1:], changed
552
+
553
+
554
+ def compose_index(index_text):
555
+ if 'id="hm-boot"' in index_text:
556
+ return None
557
+ loading_css = read_asset(SOURCE, "loading.css").decode("utf-8")
558
+ loading_html = read_asset(SOURCE, "loading.html").decode("utf-8")
559
+ if "</style" in loading_css.lower():
560
+ raise RuntimeError("loading.css contains a closing style tag")
561
+ html = index_text
562
+ html = html.replace('<html lang="en">',
563
+ '<html lang="zh-CN" data-hm-shell="heimdall-terminal">', 1)
564
+ if "data-hm-shell" not in html:
565
+ html = re.sub(r"<html([^>]*)>", r'<html\1 data-hm-shell="heimdall-terminal">', html, count=1)
566
+ html, count = re.subn(r"<title>.*?</title>",
567
+ "<title>海姆达尔终端 // 世界树公司 · HEIMDALL</title>", html,
568
+ count=1, flags=re.DOTALL)
569
+ if count != 1:
570
+ raise RuntimeError("index title anchor missing")
571
+ meta = (
572
+ ' <meta name="theme-color" content="#070A0F" />\n'
573
+ ' <meta name="description" content="世界树公司 · 海姆达尔部队 · 零区战术终端 HM-04" />\n'
574
+ )
575
+ if '<link rel="manifest"' in html:
576
+ html = html.replace(' <link rel="manifest"', meta + ' <link rel="manifest"', 1)
577
+ else:
578
+ html = html.replace("</head>", meta + "</head>", 1)
579
+ critical = (
580
+ ' <style id="hm-boot-style">\n/* ' + MARKER + ' */\n' + loading_css + "\n </style>\n"
581
+ )
582
+ html = html.replace("</head>", critical + " </head>", 1)
583
+ body_open = re.search(r"<body([^>]*)>", html)
584
+ if body_open is None:
585
+ raise RuntimeError("index body anchor missing")
586
+ attrs = body_open.group(1)
587
+ if 'class="' in attrs:
588
+ attrs = attrs.replace('class="', 'class="hm-booting ', 1)
589
+ else:
590
+ attrs += ' class="hm-booting"'
591
+ html = html[:body_open.start()] + "<body" + attrs + ">\n" + loading_html + "\n" + html[body_open.end():]
592
+ if "</body>" not in html:
593
+ raise RuntimeError("index closing body anchor missing")
594
+ html = html.replace("</body>",
595
+ ' <script defer src="./assets/heimdall-shell.js"></script>\n </body>', 1)
596
+ if 'id="root"' not in html or "hm-boot-style" not in html:
597
+ raise RuntimeError("index composition failed")
598
+ return html
599
+
600
+
601
+ def brand_module():
602
+ template = read_asset(SOURCE, "brand-client.js").decode("utf-8")
603
+ mark = base64.b64encode(read_asset(SOURCE, "mark-alpha.png")).decode("ascii")
604
+ if "__MARK_B64__" not in template:
605
+ raise RuntimeError("brand template marker missing")
606
+ return template.replace("__MARK_B64__", mark).encode("utf-8")
607
+
608
+
609
+ def compose_tree(tree, target):
610
+ """Return (replacements, additions, warnings), or raise on incompatibility."""
611
+ with open(target, "rb") as handle:
612
+ _, hs = asar.read_header(handle)
613
+
614
+ def read(path):
615
+ entry = asar.find(tree, path)
616
+ return asar.read_entry(handle, hs, entry)
617
+
618
+ index_path = None
619
+ css_path = None
620
+ for path, entry in asar.walk(tree):
621
+ if path.startswith(FRONTEND + "/") and path.endswith("/index.html"):
622
+ index_path = path
623
+ elif path.startswith(FRONTEND + "/assets/") and path.endswith(".css") and \
624
+ path.rsplit("/", 1)[-1].startswith("index-"):
625
+ css_path = path
626
+ if index_path is None or css_path is None:
627
+ raise RuntimeError("frontend anchors missing")
628
+ if BRAND not in [p for p, _ in asar.walk(tree)]:
629
+ raise RuntimeError("brand module missing")
630
+
631
+ index_text = read(index_path).decode("utf-8")
632
+ new_index = compose_index(index_text)
633
+ if new_index is None:
634
+ raise RuntimeError("already patched")
635
+ css_text = read(css_path).decode("utf-8")
636
+ if MARKER in css_text:
637
+ raise RuntimeError("stylesheet already patched")
638
+ shell_css = read_asset(SOURCE, "shell.css").decode("utf-8")
639
+ new_css = css_text.rstrip() + "\n\n/* " + MARKER + " */\n" + shell_css
640
+
641
+ replacements = {
642
+ index_path: new_index.encode("utf-8"),
643
+ css_path: new_css.encode("utf-8"),
644
+ BRAND: brand_module(),
645
+ }
646
+ additions = {
647
+ FRONTEND + "/assets/heimdall-shell.js": read_asset(SOURCE, "shell.js"),
648
+ FRONTEND + "/assets/hm-mark-light.png": read_asset(SOURCE, "hm-mark-light.png"),
649
+ FRONTEND + "/assets/hm-mark-blue.png": read_asset(SOURCE, "hm-mark-blue.png"),
650
+ "renderer/assets/welcome-mark-light.png": read_asset(SOURCE, "welcome-mark-light.png"),
651
+ "renderer/assets/welcome-mark-ink.png": read_asset(SOURCE, "welcome-mark-ink.png"),
652
+ }
653
+ warnings = []
654
+
655
+ # Kernel boot strings (source-level; no runtime injection).
656
+ js_path = None
657
+ for path, _entry in asar.walk(tree):
658
+ if path.startswith(FRONTEND + "/assets/") and path.endswith(".js") and \
659
+ path.rsplit("/", 1)[-1].startswith("index-") and "langs/" not in path:
660
+ js_path = path
661
+ break
662
+ if js_path:
663
+ js_text = read(js_path).decode("utf-8")
664
+ boot_replacements = [
665
+ ('this.wordmark=cr(ar.wordmark,"HARNESS")',
666
+ 'this.wordmark=cr(ar.wordmark,"海姆达尔")'),
667
+ ('this.hint=cr(ar.hint,"Loading plugins…")',
668
+ 'this.hint=cr(ar.hint,"正在建立安全链路")'),
669
+ ('cr(ar.failedTitle,"Failed to load plugins")',
670
+ 'cr(ar.failedTitle,"接入失败")'),
671
+ ]
672
+ changed = 0
673
+ for old, new in boot_replacements:
674
+ if old in js_text:
675
+ js_text = js_text.replace(old, new, 1)
676
+ changed += 1
677
+ if changed:
678
+ replacements[js_path] = js_text.encode("utf-8")
679
+ else:
680
+ warnings.append("kernel boot strings unchanged")
681
+ else:
682
+ warnings.append("frontend js missing")
683
+
684
+ # Client UI dictionaries: hero, workspace/session vocabulary, model display names.
685
+ for path, pairs in UI_TEXT.items():
686
+ try:
687
+ raw = read(path)
688
+ except asar.AsarError:
689
+ warnings.append(path + ":missing-ui")
690
+ continue
691
+ text = raw.decode("utf-8")
692
+ changed = 0
693
+ for old, new in pairs:
694
+ if old in text:
695
+ text = text.replace(old, new)
696
+ changed += 1
697
+ if changed:
698
+ replacements[path] = text.encode("utf-8")
699
+ else:
700
+ warnings.append(path + ":ui-strings-unchanged")
701
+
702
+ # Native menu/welcome dictionaries.
703
+ dictionary_text = {}
704
+ for path in MENU_FILES:
705
+ try:
706
+ raw = read(path)
707
+ except asar.AsarError:
708
+ warnings.append(path + ":missing")
709
+ continue
710
+ text = raw.decode("utf-8")
711
+ new_text, changed = replace_zh_block(text, ZH_MAP)
712
+ if changed:
713
+ replacements[path] = new_text.encode("utf-8")
714
+ dictionary_text[path] = new_text
715
+ else:
716
+ warnings.append(path + ":no-zh-block")
717
+
718
+ # Welcome / update shells.
719
+ welcome_html = read("renderer/welcome.html").decode("utf-8")
720
+ welcome_html = welcome_html.replace('<html lang="en">', '<html lang="zh-CN">', 1)
721
+ welcome_html = re.sub(r"<title>.*?</title>", "<title>海姆达尔终端</title>", welcome_html,
722
+ count=1, flags=re.DOTALL)
723
+ replacements["renderer/welcome.html"] = welcome_html.encode("utf-8")
724
+ replacements["renderer/assets/welcome-brand.svg"] = read_asset(SOURCE, "welcome-brand.svg")
725
+ for path in ("renderer/welcome.css", "renderer/update-dialog.css", "renderer/mandatory-update.css"):
726
+ try:
727
+ base = read(path)
728
+ except asar.AsarError:
729
+ warnings.append(path + ":missing")
730
+ continue
731
+ extra = "welcome.css" if path.endswith("welcome.css") else "update.css"
732
+ replacements[path] = base.rstrip() + b"\n\n/* " + MARKER.encode() + b" */\n" + \
733
+ read_asset(SOURCE, extra)
734
+ for path in ("renderer/update-dialog.html", "renderer/mandatory-update.html"):
735
+ try:
736
+ html = read(path).decode("utf-8")
737
+ except asar.AsarError:
738
+ warnings.append(path + ":missing")
739
+ continue
740
+ html = html.replace('<html lang="en">', '<html lang="zh-CN">', 1)
741
+ html = re.sub(r"<title>.*?</title>", "<title>海姆达尔终端</title>", html,
742
+ count=1, flags=re.DOTALL)
743
+ replacements[path] = html.encode("utf-8")
744
+
745
+ # Front-end icon/manifest replacement.
746
+ icon_map = {
747
+ FRONTEND + "/favicon.svg": "favicon.svg",
748
+ FRONTEND + "/favicon-dark.svg": "favicon-dark.svg",
749
+ FRONTEND + "/apple-touch-icon.png": "apple-touch-icon.png",
750
+ FRONTEND + "/icon-192.png": "icon-192.png",
751
+ FRONTEND + "/icon-512.png": "icon-512.png",
752
+ FRONTEND + "/icon-maskable-512.png": "icon-maskable-512.png",
753
+ }
754
+ for path, name in icon_map.items():
755
+ if any(p == path for p, _ in asar.walk(tree)):
756
+ replacements[path] = read_asset(ICONS, name)
757
+ else:
758
+ warnings.append(path + ":missing")
759
+
760
+ manifest_path = FRONTEND + "/manifest.webmanifest"
761
+ try:
762
+ manifest = json.loads(read(manifest_path).decode("utf-8"))
763
+ except (asar.AsarError, ValueError):
764
+ warnings.append("manifest missing")
765
+ else:
766
+ manifest["name"] = "海姆达尔终端"
767
+ manifest["short_name"] = "海姆达尔"
768
+ manifest["description"] = "世界树公司 · 海姆达尔部队 · 零区战术终端"
769
+ manifest["theme_color"] = "#070A0F"
770
+ manifest["background_color"] = "#070A0F"
771
+ replacements[manifest_path] = (json.dumps(manifest, ensure_ascii=False,
772
+ separators=(",", ":")) + "\n").encode("utf-8")
773
+
774
+ # Source-level window chrome.
775
+ main_path = "lib/main.js"
776
+ try:
777
+ if main_path in dictionary_text:
778
+ main_text = dictionary_text[main_path]
779
+ else:
780
+ main_text = read(main_path).decode("utf-8")
781
+ except asar.AsarError:
782
+ warnings.append("main missing")
783
+ else:
784
+ old_fill = 'return nativeTheme.shouldUseDarkColors ? "#1b1b1c" : "#f9fafb";'
785
+ new_fill = 'return nativeTheme.shouldUseDarkColors ? "#070A0F" : "#EEF2F5";'
786
+ if old_fill in main_text:
787
+ main_text = main_text.replace(old_fill, new_fill, 1)
788
+ else:
789
+ warnings.append("titlebar fill anchor missing")
790
+ old_about = 'applicationName: "DeepSeek Harness",'
791
+ if old_about in main_text:
792
+ main_text = main_text.replace(old_about, 'applicationName: "海姆达尔终端",', 1)
793
+ else:
794
+ warnings.append("about name anchor missing")
795
+ old_show = '\t\tshow,\n\t\t...process.platform === "win32" && primary ? {'
796
+ if old_show in main_text:
797
+ main_text = main_text.replace(
798
+ old_show,
799
+ '\t\tshow,\n\t\tbackgroundColor: chromeFallbackFill(),\n'
800
+ '\t\t...process.platform === "win32" && primary ? {', 1)
801
+ else:
802
+ warnings.append("window background anchor missing")
803
+ replacements[main_path] = main_text.encode("utf-8")
804
+
805
+ return replacements, additions, warnings
806
+
807
+
808
+ def is_patched_tree(tree, handle):
809
+ index_path = None
810
+ for path, _entry in asar.walk(tree):
811
+ if path.startswith(FRONTEND + "/") and path.endswith("/index.html"):
812
+ index_path = path
813
+ break
814
+ if index_path is None:
815
+ return False
816
+ try:
817
+ entry = asar.find(tree, index_path)
818
+ data = asar.read_entry(handle, asar.read_header(handle)[1], entry)
819
+ return b'id="hm-boot"' in data and MARKER.encode() in data
820
+ except Exception:
821
+ return False
822
+
823
+
824
+ def check_target(target):
825
+ if not os.path.isfile(target):
826
+ return {"ok": False, "error": "target missing"}
827
+ if os.path.getsize(target) == 0:
828
+ return {"ok": False, "error": "target is 0 bytes"}
829
+ with open(target, "rb") as handle:
830
+ tree, _hs = asar.read_header(handle)
831
+ patched = is_patched_tree(tree, handle)
832
+ version = archive_version(tree, target)
833
+ return {
834
+ "ok": True,
835
+ "patched": patched,
836
+ "version": version,
837
+ "entries": asar.count_entries(tree),
838
+ "sha256": sha256_file(target),
839
+ "state": load_state(),
840
+ }
841
+
842
+
843
+ # ------------------------------------------------------------------ external
844
+ def external_paths(target):
845
+ resources = os.path.dirname(target)
846
+ return {
847
+ "icon": os.path.join(resources, "icon.png"),
848
+ "tray": os.path.join(resources, "tray.ico"),
849
+ "exe": os.path.join(os.path.dirname(resources), "DeepSeek Harness.exe"),
850
+ }
851
+
852
+
853
+ def backup_external(paths, backup_dir):
854
+ manifest = {}
855
+ for name, source in paths.items():
856
+ if not os.path.isfile(source):
857
+ continue
858
+ if os.path.getsize(source) == 0:
859
+ raise RuntimeError("refusing 0-byte backup source: " + name)
860
+ dst = os.path.join(backup_dir, os.path.basename(source) + ".orig")
861
+ shutil.copyfile(source, dst)
862
+ if os.path.getsize(dst) != os.path.getsize(source):
863
+ raise RuntimeError("external backup size mismatch: " + name)
864
+ digest = sha256_file(dst)
865
+ if digest != sha256_file(source):
866
+ raise RuntimeError("external backup hash mismatch: " + name)
867
+ manifest[name] = {"path": source, "sha256": digest, "size": os.path.getsize(dst)}
868
+ return manifest
869
+
870
+
871
+ def replace_file(src, dst, expected_sha=None):
872
+ if not os.path.isfile(src) or os.path.getsize(src) == 0:
873
+ raise RuntimeError("refusing 0-byte replacement: " + src)
874
+ if expected_sha and sha256_file(src) != expected_sha:
875
+ raise RuntimeError("replacement hash mismatch: " + src)
876
+ tmp = dst + ".heimdall.tmp"
877
+ shutil.copyfile(src, tmp)
878
+ if os.path.getsize(tmp) == 0:
879
+ raise RuntimeError("staged external file is 0 bytes")
880
+ replace_retry(tmp, dst)
881
+
882
+
883
+ def apply_external(target, backup_dir, warnings):
884
+ paths = external_paths(target)
885
+ applied = {}
886
+ for name in ("icon", "tray"):
887
+ if not os.path.isfile(paths[name]):
888
+ warnings.append(name + " target missing")
889
+ continue
890
+ replace_file(os.path.join(ICONS, "res-icon.png" if name == "icon" else "tray.ico"), paths[name])
891
+ applied[name] = sha256_file(paths[name])
892
+ log("external " + name + " replaced")
893
+ rcedit = os.path.join(ROOT, "vendor", "rcedit", "rcedit-x64.exe")
894
+ if os.path.isfile(paths["exe"]) and os.path.isfile(rcedit):
895
+ tmp = paths["exe"] + ".heimdall.tmp"
896
+ try:
897
+ shutil.copyfile(paths["exe"], tmp)
898
+ result = subprocess.run(
899
+ [rcedit, tmp, "--set-icon", os.path.join(ICONS, "app.ico")],
900
+ capture_output=True, text=True, timeout=120,
901
+ creationflags=0x08000000,
902
+ )
903
+ if result.returncode != 0:
904
+ raise RuntimeError((result.stderr or result.stdout or "rcedit failed").strip())
905
+ if not os.path.isfile(tmp) or os.path.getsize(tmp) == 0:
906
+ raise RuntimeError("rcedit produced an empty executable")
907
+ replace_retry(tmp, paths["exe"])
908
+ applied["exe"] = sha256_file(paths["exe"])
909
+ log("executable icon replaced (Authenticode signature is now invalid)")
910
+ except Exception as exc:
911
+ try:
912
+ if os.path.exists(tmp):
913
+ os.remove(tmp)
914
+ except OSError:
915
+ pass
916
+ warnings.append("exe icon: " + str(exc))
917
+ log("exe icon skipped: %s" % exc)
918
+ elif os.path.isfile(paths["exe"]):
919
+ warnings.append("rcedit missing; executable icon unchanged")
920
+ return applied
921
+
922
+
923
+ def restore_external(backup_dir, warnings):
924
+ manifest_path = os.path.join(backup_dir, "external.json")
925
+ if not os.path.isfile(manifest_path):
926
+ return
927
+ try:
928
+ with open(manifest_path, encoding="utf-8") as handle:
929
+ manifest = json.load(handle)
930
+ except (OSError, ValueError):
931
+ warnings.append("external backup manifest invalid")
932
+ return
933
+ for name, info in manifest.items():
934
+ src = os.path.join(backup_dir, os.path.basename(info["path"]) + ".orig")
935
+ dst = info["path"]
936
+ if not os.path.isfile(src):
937
+ warnings.append("external backup missing: " + name)
938
+ continue
939
+ if sha256_file(src) != info["sha256"]:
940
+ warnings.append("external backup hash mismatch: " + name)
941
+ continue
942
+ replace_file(src, dst, info["sha256"])
943
+ log("external " + name + " restored")
944
+
945
+
946
+ # -------------------------------------------------------------------- backup
947
+ def backup_dir_for(version, original_sha, create=False):
948
+ tag = "%s-%s" % (version.replace("/", "_"), original_sha[:12])
949
+ path = os.path.join(BACKUP_ROOT, tag)
950
+ if create:
951
+ os.makedirs(path, exist_ok=True)
952
+ return path
953
+
954
+
955
+ def ensure_backup(target, version, original_sha):
956
+ backup_dir = backup_dir_for(version, original_sha, create=True)
957
+ backup = os.path.join(backup_dir, "app.asar.orig")
958
+ if os.path.isfile(backup) and os.path.getsize(backup) > 0 and sha256_file(backup) == original_sha:
959
+ log("verified existing backup")
960
+ else:
961
+ if os.path.isfile(backup) and os.path.getsize(backup) == 0:
962
+ raise RuntimeError("existing backup is 0 bytes; refusing")
963
+ shutil.copyfile(target, backup)
964
+ if os.path.getsize(backup) == 0:
965
+ raise RuntimeError("backup is 0 bytes; refusing")
966
+ if sha256_file(backup) != original_sha:
967
+ raise RuntimeError("backup hash mismatch; refusing")
968
+ log("backup written: %s" % backup)
969
+ payload = backup_external(external_paths(target), backup_dir)
970
+ with open(os.path.join(backup_dir, "external.json"), "w", encoding="utf-8", newline="\n") as handle:
971
+ json.dump(payload, handle, ensure_ascii=False, indent=2)
972
+ handle.write("\n")
973
+ with open(os.path.join(backup_dir, "backup.json"), "w", encoding="utf-8", newline="\n") as handle:
974
+ json.dump({
975
+ "version": version,
976
+ "originalSha256": original_sha,
977
+ "target": target,
978
+ "when": now(),
979
+ }, handle, ensure_ascii=False, indent=2)
980
+ handle.write("\n")
981
+ return backup_dir, backup
982
+
983
+
984
+ def write_recovery(target):
985
+ python = sys.executable
986
+ patcher = os.path.join(HERE, "patcher.py")
987
+ base = [python, patcher, "--target", target, "--state-dir", STATE_DIR,
988
+ "--profile-dir", PROFILE_DIR]
989
+ if TEST_MODE:
990
+ base.append("--test-mode")
991
+ for mode, name in (("apply", "apply.vbs"), ("restore", "restore.vbs")):
992
+ command = " ".join('"' + part + '"' for part in base[:2] + ["--mode", mode] + base[2:])
993
+ body = (
994
+ 'Option Explicit\r\n'
995
+ 'Dim sh\r\n'
996
+ 'Set sh = CreateObject("WScript.Shell")\r\n'
997
+ 'sh.Run "' + command.replace('"', '""') + '", 0, False\r\n'
998
+ )
999
+ with open(os.path.join(STATE_DIR, name), "w", encoding="utf-8", newline="\n") as handle:
1000
+ handle.write(body)
1001
+ with open(os.path.join(STATE_DIR, "README.txt"), "w", encoding="utf-8", newline="\n") as handle:
1002
+ handle.write(
1003
+ "海姆达尔终端 · 源码层维护入口\n"
1004
+ "完全退出 DeepSeek Harness 后:\n"
1005
+ " apply.vbs 重新写入皮肤\n"
1006
+ " restore.vbs 还原官方文件\n"
1007
+ "备份与哈希:backup\\,状态:state.json\n"
1008
+ "仅位于 DSH 安装目录,无启动项、计划任务或注册表写入。\n"
1009
+ )
1010
+
1011
+
1012
+ # ---------------------------------------------------------------------- apply
1013
+ def apply_skin(target, dry_run=False, external=True):
1014
+ if not os.path.isfile(target):
1015
+ log("target missing")
1016
+ return 2
1017
+ if os.path.getsize(target) == 0:
1018
+ log("target is 0 bytes; refusing")
1019
+ return 2
1020
+ if not TEST_MODE and dsh_running():
1021
+ log("DSH is still running; apply refused")
1022
+ return 3
1023
+ if not dry_run:
1024
+ if not TEST_MODE:
1025
+ launch_progress("apply")
1026
+ write_progress(4, "CHECK", "正在校验官方归档…")
1027
+ try:
1028
+ with open(target, "rb") as handle:
1029
+ tree, _hs = asar.read_header(handle)
1030
+ size = os.path.getsize(target)
1031
+ if size < 16 * 1024 * 1024:
1032
+ log("target is suspiciously small; refusing")
1033
+ return 2
1034
+ original_sha = sha256_file(target)
1035
+ version = archive_version(tree, target)
1036
+ with open(target, "rb") as handle:
1037
+ patched = is_patched_tree(tree, handle)
1038
+ if patched:
1039
+ state = load_state()
1040
+ state.update({"status": "patched", "patchedSha256": original_sha,
1041
+ "version": version, "updatedAt": now()})
1042
+ save_state(state)
1043
+ log("already patched; no-op")
1044
+ write_progress(100, "READY", "源码层已是最新", done=True)
1045
+ return 0
1046
+ replacements, additions, warnings = compose_tree(tree, target)
1047
+ if dry_run:
1048
+ log("dry-run replacements=%d additions=%d warnings=%s"
1049
+ % (len(replacements), len(additions), warnings))
1050
+ return 0
1051
+ write_progress(10, "BACKUP", "正在创建可回滚备份…")
1052
+ exe_size = 0
1053
+ exe_path = external_paths(target)["exe"]
1054
+ if os.path.isfile(exe_path):
1055
+ exe_size = os.path.getsize(exe_path)
1056
+ disk = shutil.disk_usage(os.path.dirname(target)).free
1057
+ need = os.path.getsize(target) * 2 + exe_size * 2 + 64 * 1024 * 1024
1058
+ if disk < need:
1059
+ raise RuntimeError("not enough free space for backup + staged archive")
1060
+ backup_dir, backup_file = ensure_backup(target, version, original_sha)
1061
+ write_progress(24, "BACKUP", "官方归档与图标已备份")
1062
+ tmp = target + ".heimdall.tmp"
1063
+ if os.path.exists(tmp):
1064
+ os.remove(tmp)
1065
+ write_progress(32, "PACK", "正在重打包源码层…")
1066
+ log("composing archive")
1067
+ asar.rewrite(target, tmp, replacements, additions)
1068
+ write_progress(52, "PACK", "归档写入完成")
1069
+ write_progress(60, "VERIFY", "正在逐条目复核…")
1070
+ asar.verify(tmp, replacements, additions)
1071
+ if os.path.getsize(tmp) < 16 * 1024 * 1024:
1072
+ raise RuntimeError("staged archive is implausibly small")
1073
+ shutil.copystat(target, tmp)
1074
+ write_progress(68, "VERIFY", "逐条目校验通过")
1075
+ replace_retry(tmp, target)
1076
+ patched_sha = sha256_file(target)
1077
+ log("archive applied: %s -> %s" % (original_sha[:12], patched_sha[:12]))
1078
+ write_progress(76, "WRITE", "源码层已写入,正在处理图标…")
1079
+ except Exception as exc:
1080
+ log("apply failed: %s" % exc)
1081
+ write_progress(0, "FAILED", "源码层覆盖失败", error=str(exc))
1082
+ return 4
1083
+
1084
+ applied_external = {}
1085
+ # Persist the archive state before touching external icons. If the helper is
1086
+ # killed during the icon/EXE stage, restore can still verify and roll back
1087
+ # the archive from this record.
1088
+ state = load_state()
1089
+ state.update({
1090
+ "schema": 1,
1091
+ "status": "patched",
1092
+ "desired": state.get("desired", "on"),
1093
+ "version": version,
1094
+ "target": target,
1095
+ "originalSha256": original_sha,
1096
+ "patchedSha256": patched_sha,
1097
+ "backupDir": backup_dir,
1098
+ "backupFile": backup_file,
1099
+ "external": {},
1100
+ "warnings": warnings,
1101
+ "appliedAt": now(),
1102
+ "updatedAt": now(),
1103
+ })
1104
+ save_state(state)
1105
+ if external:
1106
+ write_progress(84, "WRITE", "正在写入应用/托盘/EXE 图标…")
1107
+ try:
1108
+ applied_external = apply_external(target, backup_dir, warnings)
1109
+ except Exception as exc:
1110
+ warnings.append("external: " + str(exc))
1111
+ log("external phase failed: %s" % exc)
1112
+ state = load_state()
1113
+ state.update({
1114
+ "external": applied_external,
1115
+ "warnings": warnings,
1116
+ "updatedAt": now(),
1117
+ })
1118
+ save_state(state)
1119
+ write_recovery(target)
1120
+ log("source layer ready")
1121
+ write_progress(100, "READY", "覆盖完成 · 可以重新打开 DSH", done=True)
1122
+ return 0
1123
+
1124
+
1125
+ def restore_skin(target, force=False, intermediate=False):
1126
+ if not os.path.isfile(target):
1127
+ log("target missing")
1128
+ return 2
1129
+ if not TEST_MODE and dsh_running():
1130
+ log("DSH is still running; restore refused")
1131
+ return 3
1132
+ if not TEST_MODE:
1133
+ launch_progress("restore")
1134
+ write_progress(5, "WAIT", "正在读取官方备份…")
1135
+ state = load_state()
1136
+ try:
1137
+ with open(target, "rb") as handle:
1138
+ tree, _hs = asar.read_header(handle)
1139
+ patched = is_patched_tree(tree, handle)
1140
+ if not patched:
1141
+ log("current archive is not skinned; leaving it untouched")
1142
+ state.update({"status": "original", "updatedAt": now()})
1143
+ save_state(state)
1144
+ write_progress(100, "READY",
1145
+ "旧层已还原,准备写入当前源码…" if intermediate else "当前已是官方源码层,无需还原",
1146
+ done=not intermediate)
1147
+ return 0
1148
+ if not force and state.get("patchedSha256") and state["patchedSha256"] != sha256_file(target):
1149
+ log("current skinned hash does not match state; refusing to overwrite")
1150
+ write_progress(0, "FAILED", "当前归档哈希与状态不一致", error="refusing to overwrite")
1151
+ return 5
1152
+ backup_dir = state.get("backupDir") or ""
1153
+ backup = state.get("backupFile") or os.path.join(backup_dir, "app.asar.orig")
1154
+ if not backup_dir or not os.path.isfile(backup) or os.path.getsize(backup) == 0:
1155
+ log("verified backup missing; refusing destructive restore")
1156
+ write_progress(0, "FAILED", "找不到可验证的官方备份", error="verified backup missing")
1157
+ return 4
1158
+ expected = state.get("originalSha256")
1159
+ if not expected or sha256_file(backup) != expected:
1160
+ log("backup hash mismatch; refusing")
1161
+ write_progress(0, "FAILED", "官方备份哈希校验失败", error="backup hash mismatch")
1162
+ return 4
1163
+ write_progress(32, "VERIFY", "正在校验官方备份哈希…")
1164
+ tmp = target + ".heimdall-restore.tmp"
1165
+ shutil.copyfile(backup, tmp)
1166
+ if os.path.getsize(tmp) == 0 or sha256_file(tmp) != expected:
1167
+ log("staged restore hash mismatch; refusing")
1168
+ write_progress(0, "FAILED", "还原暂存文件哈希校验失败", error="staged restore hash mismatch")
1169
+ return 4
1170
+ write_progress(62, "WRITE", "正在写回官方归档…")
1171
+ replace_retry(tmp, target)
1172
+ if sha256_file(target) != expected:
1173
+ log("restored archive hash mismatch")
1174
+ write_progress(0, "FAILED", "还原后归档哈希校验失败", error="restored archive hash mismatch")
1175
+ return 4
1176
+ warnings = []
1177
+ write_progress(84, "WRITE", "正在还原应用/托盘/EXE 图标…")
1178
+ restore_external(backup_dir, warnings)
1179
+ state.update({"status": "original", "warnings": warnings,
1180
+ "restoredAt": now(), "updatedAt": now()})
1181
+ save_state(state)
1182
+ log("RESTORED: " + expected[:12])
1183
+ if intermediate:
1184
+ write_progress(82, "WRITE", "旧层已还原,正在写入当前源码…", done=False)
1185
+ else:
1186
+ write_progress(100, "READY", "还原完成 · 可以重新打开 DSH", done=True)
1187
+ return 0
1188
+ except Exception as exc:
1189
+ log("restore failed: %s" % exc)
1190
+ write_progress(0, "FAILED", "源码层还原失败", error=str(exc))
1191
+ return 4
1192
+
1193
+
1194
+ def sync(target, skip_wait=False, wait_pid=0):
1195
+ if not os.path.isfile(target):
1196
+ log("target missing")
1197
+ return 2
1198
+ if not acquire_sync_lock():
1199
+ log("another sync helper is already running; exit")
1200
+ return 0
1201
+ if not skip_wait:
1202
+ log("waiting for DSH host pid %s" % (wait_pid or "unknown"))
1203
+ waited = wait_for_pid(wait_pid)
1204
+ if waited:
1205
+ time.sleep(3)
1206
+ absent = 0
1207
+ for _ in range(300):
1208
+ if dsh_running():
1209
+ absent = 0
1210
+ else:
1211
+ absent += 1
1212
+ if absent >= 2:
1213
+ break
1214
+ time.sleep(2)
1215
+ else:
1216
+ # Fallback for an old helper or a process handle we cannot open.
1217
+ absent = 0
1218
+ for _ in range(10800):
1219
+ if dsh_running():
1220
+ absent = 0
1221
+ else:
1222
+ absent += 1
1223
+ if absent >= 2:
1224
+ break
1225
+ time.sleep(2)
1226
+ else:
1227
+ log("wait timed out")
1228
+ return 1
1229
+ if not wait_unlocked(target, 180):
1230
+ log("archive stayed locked")
1231
+ return 3
1232
+ state = load_state()
1233
+ version = archive_version(target=target)
1234
+ original_sha = sha256_file(target)
1235
+ with open(target, "rb") as handle:
1236
+ tree, _hs = asar.read_header(handle)
1237
+ patched = is_patched_tree(tree, handle)
1238
+ desired = plugin_enabled()
1239
+ log("sync version=%s patched=%s desired=%s" % (version, patched, desired))
1240
+ if desired:
1241
+ if state.get("reapply"):
1242
+ log("reapply requested; restoring previous layer before applying current source")
1243
+ if not TEST_MODE:
1244
+ launch_progress("apply")
1245
+ write_progress(3, "WAIT", "正在准备重新覆盖源码层…")
1246
+ rc = restore_skin(target, force=False, intermediate=True)
1247
+ if rc != 0:
1248
+ return rc
1249
+ fresh = load_state()
1250
+ fresh["desired"] = "on"
1251
+ save_state(fresh)
1252
+ rc = apply_skin(target)
1253
+ if rc == 0:
1254
+ done = load_state()
1255
+ done["reapply"] = False
1256
+ save_state(done)
1257
+ return rc
1258
+ if patched:
1259
+ if state.get("patchedSha256") == original_sha:
1260
+ log("skin already current")
1261
+ state.update({"status": "patched", "updatedAt": now()})
1262
+ save_state(state)
1263
+ return 0
1264
+ log("skinned archive hash differs from state; not touching")
1265
+ return 5
1266
+ # A new DSH version (or a clean reinstall) is a fresh original: apply a
1267
+ # new patch and a new backup. Never restore an older backup over it.
1268
+ return apply_skin(target)
1269
+ if patched:
1270
+ return restore_skin(target, force=False)
1271
+ state.update({"status": "original", "updatedAt": now()})
1272
+ save_state(state)
1273
+ log("nothing to restore")
1274
+ return 0
1275
+
1276
+
1277
+ def main():
1278
+ parser = argparse.ArgumentParser()
1279
+ parser.add_argument("--mode", default="check",
1280
+ choices=("check", "apply", "restore", "sync", "status"))
1281
+ parser.add_argument("--target", default=DEFAULT_TARGET)
1282
+ parser.add_argument("--state-dir", default=None)
1283
+ parser.add_argument("--profile-dir", default=None)
1284
+ parser.add_argument("--no-external", action="store_true")
1285
+ parser.add_argument("--skip-wait", action="store_true")
1286
+ parser.add_argument("--dry-run", action="store_true")
1287
+ parser.add_argument("--test-mode", action="store_true")
1288
+ parser.add_argument("--wait-pid", type=int, default=0)
1289
+ args = parser.parse_args()
1290
+ configure(args.target, args.state_dir, args.profile_dir, args.test_mode)
1291
+ if args.mode == "check":
1292
+ print(json.dumps(check_target(args.target), ensure_ascii=False))
1293
+ return 0
1294
+ if args.mode == "status":
1295
+ print(json.dumps(load_state(), ensure_ascii=False, indent=2))
1296
+ return 0
1297
+ if args.mode == "apply":
1298
+ return apply_skin(args.target, args.dry_run, not args.no_external)
1299
+ if args.mode == "restore":
1300
+ return restore_skin(args.target)
1301
+ if args.mode == "sync":
1302
+ return sync(args.target, skip_wait=args.skip_wait, wait_pid=args.wait_pid)
1303
+ return 2
1304
+
1305
+
1306
+ if __name__ == "__main__":
1307
+ sys.exit(main())