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