dsh-cloud-backup 0.0.0-stage → 0.1.139

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.
@@ -0,0 +1,328 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+ import zlib from "node:zlib";
5
+ import crypto from "node:crypto";
6
+ import { runCmd } from "../util/proc.js";
7
+ import { logInfo, logWarn } from "../util/log.js";
8
+
9
+ const INBOX = new Set([
10
+ "@deepseek-ai/dsh-base",
11
+ "@deepseek-ai/dsh-web-app",
12
+ "@deepseek-ai/dsh-headless",
13
+ ]);
14
+
15
+ const LINK_PREFIX = "link:";
16
+ const FILE_PREFIX = "file:";
17
+ const NON_REGISTRY = /^(github:|gitlab:|bitbucket:|git\+|file:|link:|workspace:|https?:)/i;
18
+
19
+ export function classifySpec(spec) {
20
+ if (typeof spec !== "string") return "registry";
21
+ const s = spec.trim();
22
+ if (s === "") return "registry";
23
+ const lower = s.toLowerCase();
24
+ if (lower.startsWith(LINK_PREFIX)) return "link";
25
+ if (lower.startsWith(FILE_PREFIX)) return "file";
26
+ if (/^https?:\/\//i.test(s)) return "https";
27
+ if (/^(github:|gitlab:|bitbucket:|git\+)/i.test(s)) return "github";
28
+ return "registry";
29
+ }
30
+
31
+ export function isInbox(name) {
32
+ return INBOX.has(String(name || ""));
33
+ }
34
+
35
+ function readJsonSafe(file) {
36
+ try {
37
+ return JSON.parse(fs.readFileSync(file, "utf8"));
38
+ } catch {
39
+ return null;
40
+ }
41
+ }
42
+
43
+ function listDirs(dir) {
44
+ try {
45
+ return fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
46
+ } catch {
47
+ return [];
48
+ }
49
+ }
50
+
51
+ function realDirOrNull(p) {
52
+ try {
53
+ return fs.realpathSync(p);
54
+ } catch {
55
+ return fs.existsSync(p) ? p : null;
56
+ }
57
+ }
58
+
59
+ /** 判定一个已解包目录是不是 DSH 插件:package.json 带 dsh 字段,或带 cordis.patch.yml。 */
60
+ function looksLikePlugin(dir) {
61
+ const pkg = readJsonSafe(path.join(dir, "package.json"));
62
+ if (!pkg) return null;
63
+ const name = String(pkg.name || "");
64
+ if (!name || isInbox(name) || /^@deepseek-ai\//.test(name)) return null;
65
+ if (!pkg.dsh && !fs.existsSync(path.join(dir, "cordis.patch.yml"))) return null;
66
+ return { name, version: String(pkg.version || ""), dir };
67
+ }
68
+
69
+ /** 扫 profile 已解包的插件,用于清单被宿主重写后的归属兜底。
70
+ * 只看 node_modules 顶层:`.pnpm` 会留下卸载后没人清理的旧副本,扫它就会把早已移除的包当成已安装。
71
+ */
72
+ function scanInstalledPlugins(profileDir) {
73
+ const found = [];
74
+ const seen = new Set();
75
+ const take = (dir) => {
76
+ const info = looksLikePlugin(dir);
77
+ if (!info || seen.has(info.name)) return;
78
+ seen.add(info.name);
79
+ found.push(info);
80
+ };
81
+ const scanContainer = (root) => {
82
+ for (const e of listDirs(root)) {
83
+ if (e === ".bin" || e === ".pnpm") continue;
84
+ if (e.startsWith("@")) {
85
+ for (const s of listDirs(path.join(root, e))) take(path.join(root, e, s));
86
+ } else {
87
+ take(path.join(root, e));
88
+ }
89
+ }
90
+ };
91
+ const top = path.join(profileDir, "node_modules");
92
+ scanContainer(top);
93
+ return found;
94
+ }
95
+
96
+ export function listProfilePlugins({ dshHome } = {}) {
97
+ const out = [];
98
+ if (!dshHome) return out;
99
+ for (const profile of listDirs(path.join(dshHome, "profiles"))) {
100
+ const profileDir = path.join(dshHome, "profiles", profile);
101
+ const pkg = readJsonSafe(path.join(profileDir, "package.json"));
102
+ const deps = (pkg && pkg.dependencies) || {};
103
+ for (const name of Object.keys(deps)) {
104
+ if (isInbox(name)) continue;
105
+ // 运行时随宿主分发的包(@deepseek-ai/*)属于应用本体,不随用户备份打包;它们会随桌面版一起装回
106
+ if (/^@deepseek-ai\//.test(name)) continue;
107
+ const spec = String(deps[name] || "");
108
+ const kind = classifySpec(spec);
109
+ const installedDir = realDirOrNull(path.join(profileDir, "node_modules", name));
110
+ const installedPkg = installedDir ? readJsonSafe(path.join(installedDir, "package.json")) : null;
111
+ const version = (installedPkg && installedPkg.version) || (/^[~^]?\d+\.\d+\.\d+/.test(spec) ? spec.replace(/^[~^]/, "") : "");
112
+ out.push({ profile, name, spec, kind, version, dir: installedDir, hasScripts: !!installedPkg, declared: true });
113
+ }
114
+ // 兜底:宿主会重写 profiles/<p>/package.json,已解包的插件可能不再出现在 dependencies 里。
115
+ // 插件自带的多包结构(如 dsh-mnemon-*)也在 node_modules 顶层,它们是被依赖的子包而不是用户装的插件,
116
+ // 用「别的插件依赖了它」把这类子包排除掉,否则清单里的插件数会被虚高。
117
+ const candidates = scanInstalledPlugins(profileDir).filter(function (it) {
118
+ return !Object.prototype.hasOwnProperty.call(deps, it.name);
119
+ });
120
+ const subPackages = new Set();
121
+ for (const name of Object.keys(deps)) {
122
+ const dir = realDirOrNull(path.join(profileDir, "node_modules", name));
123
+ if (!dir) continue;
124
+ const pj = readJsonSafe(path.join(dir, "package.json")) || {};
125
+ for (const field of ["dependencies", "peerDependencies", "optionalDependencies"]) {
126
+ for (const dep of Object.keys(pj[field] || {})) subPackages.add(dep);
127
+ }
128
+ }
129
+ for (const it of candidates) {
130
+ if (subPackages.has(it.name)) continue;
131
+ out.push({ profile, name: it.name, spec: "", kind: "installed", version: it.version, dir: it.dir, hasScripts: true, declared: false });
132
+ }
133
+ }
134
+ return out;
135
+ }
136
+
137
+ /** 打包前把包复制成普通副本:pnpm 硬链接(link count > 1)会让 npm pack 直接崩、不产出文件。
138
+ * node_modules 默认不进 tarball,复制时跳过;包声明 bundledDependencies 时保留。
139
+ */
140
+ function stagePlainCopy(dir, stagingRoot) {
141
+ const staged = path.join(stagingRoot, "package");
142
+ const pkg = readJsonSafe(path.join(dir, "package.json")) || {};
143
+ const bundled = Array.isArray(pkg.bundledDependencies) ? pkg.bundledDependencies : Array.isArray(pkg.bundleDependencies) ? pkg.bundleDependencies : [];
144
+ const skipModules = bundled.length === 0;
145
+ const topModules = path.resolve(path.join(dir, "node_modules"));
146
+ fs.cpSync(dir, staged, { recursive: true, filter: (src) => !(skipModules && path.resolve(src) === topModules) });
147
+ return staged;
148
+ }
149
+
150
+ function packOnce(dir, outDir, timeoutMs) {
151
+ return new Promise((resolve) => {
152
+ let stagingRoot = null;
153
+ let staged = null;
154
+ try {
155
+ stagingRoot = fs.mkdtempSync(path.join(os.tmpdir(), "dshcb-stage-"));
156
+ staged = stagePlainCopy(dir, stagingRoot);
157
+ } catch (e) {
158
+ if (stagingRoot) {
159
+ try { fs.rmSync(stagingRoot, { recursive: true, force: true }); } catch {}
160
+ }
161
+ resolve({ ok: false, file: null, error: "复制打包暂存目录失败:" + String((e && e.message) || e) });
162
+ return;
163
+ }
164
+ const cleanup = () => {
165
+ try { fs.rmSync(stagingRoot, { recursive: true, force: true }); } catch {}
166
+ };
167
+ // 参数数组直传:暂存目录与输出目录只作为独立参数,不参与命令行拼接
168
+ runCmd("npm", ["pack", "--ignore-scripts", "--pack-destination", outDir, staged], { cwd: path.dirname(staged), timeoutMs })
169
+ .then((r) => {
170
+ if (!r.ok) {
171
+ const detail = String((r.stderr || "").trim() || (r.error || "")).split("\n").slice(0, 3).join(" ");
172
+ cleanup();
173
+ resolve({ ok: false, file: null, error: "npm pack 失败:" + detail });
174
+ return;
175
+ }
176
+ const lines = String(r.stdout || "").trim().split("\n");
177
+ const tail = lines[lines.length - 1] || "";
178
+ const file = path.isAbsolute(tail) ? tail : path.join(outDir, tail.trim());
179
+ const ok = fs.existsSync(file);
180
+ cleanup();
181
+ resolve({ ok, file: ok ? file : null, error: ok ? null : "npm pack 未产出 tarball" });
182
+ });
183
+ });
184
+ }
185
+
186
+ /** 打包一次并给出可诊断的原因;失败通常是确定的(源目录属性所致),不做无意义的重试。 */
187
+ export async function runNpmPack(dir, outDir, timeoutMs) {
188
+ return await packOnce(dir, outDir, timeoutMs);
189
+ }
190
+
191
+ function tarEntries(tgzPath, limit = 4096) {
192
+ const names = [];
193
+ try {
194
+ const buf = zlib.gunzipSync(fs.readFileSync(tgzPath));
195
+ let off = 0;
196
+ while (off + 512 <= buf.length && names.length < limit) {
197
+ const header = buf.subarray(off, off + 512);
198
+ if (header.every((b) => b === 0)) break;
199
+ const rawName = header.subarray(0, 100).toString("utf8").replace(/\0.*$/, "");
200
+ const prefix = header.subarray(345, 500).toString("utf8").replace(/\0.*$/, "");
201
+ const name = prefix ? prefix + "/" + rawName : rawName;
202
+ const sizeOctal = header.subarray(124, 136).toString("utf8").replace(/\0.*$/, "").trim();
203
+ const size = parseInt(sizeOctal, 8) || 0;
204
+ if (name) names.push(name);
205
+ off += 512 + Math.ceil(size / 512) * 512;
206
+ }
207
+ } catch {
208
+ return null;
209
+ }
210
+ return names;
211
+ }
212
+
213
+ export function selfCheck({ srcDir, tgzPath }) {
214
+ const names = tarEntries(tgzPath);
215
+ if (!names) return { ok: false, warning: "tarball-unreadable" };
216
+ const has = (suffix) => names.some((n) => n === "package/" + suffix || n.endsWith("/" + suffix) || n.startsWith("package/" + suffix + "/") || n.indexOf("/" + suffix + "/") >= 0);
217
+ const deps = [];
218
+ let hasScripts = [];
219
+ const srcPkg = readJsonSafe(path.join(srcDir, "package.json")) || {};
220
+ for (const d of Object.keys(srcPkg.dependencies || {})) deps.push(d);
221
+ for (const s of Object.keys(srcPkg.scripts || {})) {
222
+ if (["preinstall", "install", "postinstall", "prepare", "prepack"].includes(s)) hasScripts.push(s);
223
+ }
224
+ let nestedDeps = false;
225
+ try {
226
+ for (const entry of fs.readdirSync(srcDir, { withFileTypes: true })) {
227
+ if (entry.isDirectory() && fs.existsSync(path.join(srcDir, entry.name, "node_modules"))) { nestedDeps = true; break; }
228
+ }
229
+ if (!nestedDeps && fs.existsSync(path.join(srcDir, "node_modules"))) nestedDeps = true;
230
+ } catch {
231
+ nestedDeps = false;
232
+ }
233
+ const warnings = [];
234
+ if (!has("package.json")) warnings.push("missing-package-json");
235
+ for (const must of ["client.js", "cordis.patch.yml", "lib"]) {
236
+ if (fs.existsSync(path.join(srcDir, must)) && !has(must)) warnings.push("missing-" + must);
237
+ }
238
+ return { ok: warnings.length === 0, warning: warnings.join(",") || null, deps, has_scripts: hasScripts, nested_deps: nestedDeps, files: names.length };
239
+ }
240
+
241
+ const cache = new Map();
242
+
243
+ function cacheKey(item) {
244
+ try {
245
+ const st = fs.statSync(path.join(item.dir, "package.json"));
246
+ return item.name + "@" + item.version + ":" + st.mtimeMs + ":" + st.size;
247
+ } catch {
248
+ return item.name + "@" + item.version;
249
+ }
250
+ }
251
+
252
+ export async function collectPluginPacks({ dshHome, maxBytes = 20 * 1024 * 1024, maxCount = 40, timeoutMs = 120000, onPack = null } = {}) {
253
+ const items = listProfilePlugins({ dshHome });
254
+ const seen = new Map();
255
+ const plugins = [];
256
+ const stats = { candidates: items.length, packed: 0, specOnly: 0, skipped: 0, bytes: 0, runtimeBundles: 0 };
257
+ let taken = 0;
258
+ for (const item of items) {
259
+ if (!item.dir) { stats.skipped++; continue; }
260
+ const prev = seen.get(item.name);
261
+ if (prev) {
262
+ if (prev.profiles.indexOf(item.profile) < 0) prev.profiles.push(item.profile);
263
+ continue;
264
+ }
265
+ const slot = { profiles: [item.profile] };
266
+ seen.set(item.name, slot);
267
+ const cacheHit = cache.get(cacheKey(item));
268
+ if (item.kind === "registry" && !cacheHit) {
269
+ plugins.push({
270
+ name: item.name, version: item.version, spec: item.spec, source_kind: "registry", profiles: slot.profiles,
271
+ resolved_ref: null, blob: null, size: 0, files: 0, state: "spec-only",
272
+ nested_deps: false, deps: [], has_scripts: [], warning: null, packed_at: new Date().toISOString(),
273
+ });
274
+ stats.specOnly++;
275
+ continue;
276
+ }
277
+ if (taken >= maxCount) {
278
+ logWarn("plugin.pack.skipped", { name: item.name, reason: "too-many" });
279
+ stats.skipped++;
280
+ continue;
281
+ }
282
+ taken++;
283
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "dshcb-pack-"));
284
+ const t0 = Date.now();
285
+ logInfo("plugin.pack.start", { name: item.name, version: item.version, kind: item.kind, dir: item.dir });
286
+ const packed = await runNpmPack(item.dir, tmp, timeoutMs);
287
+ let entry = null;
288
+ if (packed.ok && packed.file) {
289
+ const bytes = fs.statSync(packed.file).size;
290
+ if (bytes > maxBytes) {
291
+ logWarn("plugin.pack.skipped", { name: item.name, reason: "too-large", bytes });
292
+ stats.skipped++;
293
+ } else {
294
+ const check = selfCheck({ srcDir: item.dir, tgzPath: packed.file });
295
+ const sha = crypto.createHash("sha256").update(fs.readFileSync(packed.file)).digest("hex");
296
+ entry = {
297
+ name: item.name, version: item.version, spec: item.spec, source_kind: item.kind, profiles: slot.profiles,
298
+ resolved_ref: null, blob: sha, size: bytes, files: check.files || 0,
299
+ state: check.ok ? "packed" : "spec-only", nested_deps: !!check.nested_deps,
300
+ deps: check.deps || [], has_scripts: check.has_scripts || [], warning: check.warning || null,
301
+ packed_at: new Date().toISOString(), tgzPath: packed.file,
302
+ };
303
+ if (!check.ok) stats.specOnly++; else { stats.packed++; stats.bytes += bytes; }
304
+ logInfo(check.ok ? "plugin.pack.done" : "plugin.pack.failed", {
305
+ name: item.name, version: item.version, bytes, seconds: ((Date.now() - t0) / 1000).toFixed(1), warning: check.warning || "",
306
+ });
307
+ }
308
+ } else {
309
+ logWarn("plugin.pack.failed", { name: item.name, error: packed.error });
310
+ stats.skipped++;
311
+ }
312
+ if (!entry) {
313
+ entry = {
314
+ name: item.name, version: item.version, spec: item.spec, source_kind: item.kind, profiles: slot.profiles,
315
+ resolved_ref: null, blob: null, size: 0, files: 0, state: "spec-only",
316
+ nested_deps: false, deps: [], has_scripts: [], warning: packed.error || "pack-failed",
317
+ packed_at: new Date().toISOString(),
318
+ };
319
+ }
320
+ if (entry.blob && entry.tgzPath) cache.set(cacheKey(item), { blob: entry.blob, size: entry.size, files: entry.files });
321
+ plugins.push(entry);
322
+ if (typeof onPack === "function" && entry.tgzPath) {
323
+ try { await onPack(entry); } catch (e) { logWarn("plugin.pack.upload-failed", { name: entry.name, error: String((e && e.message) || e) }); }
324
+ }
325
+ try { fs.rmSync(tmp, { recursive: true, force: true }); } catch { /* 临时目录残留不影响结果 */ }
326
+ }
327
+ return { plugins, stats };
328
+ }
@@ -0,0 +1,102 @@
1
+ // lib/engine/prune.js —— 清理本地旧快照(省本地磁盘),云端留底
2
+
3
+ import fs from "node:fs";
4
+ import { storeDir as storeDirOf } from "../store/paths.js";
5
+ import { listSnapshots, readManifest, snapshotDir, rebuildIndex } from "./manifest.js";
6
+ import { listBlobs } from "./blob.js";
7
+ import { listRemoteSnapshots, loadRemoteState } from "../providers/aliyun.js";
8
+ import { acquireLock, releaseLock, busyResult } from "./lock.js";
9
+
10
+ export function keepCount(raw, fallback) {
11
+ const n = Number(raw);
12
+ if (!Number.isFinite(n)) return fallback;
13
+ return Math.max(0, Math.floor(n));
14
+ }
15
+
16
+ export async function pruneLocalSnapshots(o = {}) {
17
+ const storeDir = o.storeDir || storeDirOf();
18
+ const keepRecent = keepCount(o.keepRecent, 5);
19
+ const stamps = Array.isArray(o.stamps) && o.stamps.length ? o.stamps : null;
20
+ const dryRun = o.dryRun !== false;
21
+ const requireCloud = o.requireCloud !== false;
22
+ const reclaim = o.reclaim !== false;
23
+ const logger = o.logger || (() => {});
24
+
25
+ const snaps = listSnapshots(storeDir); // 新的在前
26
+ const keep = stamps ? snaps.filter((s) => !stamps.includes(s.stamp)) : snaps.slice(0, keepRecent);
27
+ const targets = stamps ? snaps.filter((s) => stamps.includes(s.stamp)) : snaps.slice(keepRecent);
28
+
29
+ let cloud = null, cloudError = null;
30
+ try {
31
+ const ls = await listRemoteSnapshots({ storeDir });
32
+ if (ls && ls.ok) cloud = new Map((ls.snapshots || []).map((x) => [x.stamp, !!x.hasManifest]));
33
+ else cloudError = (ls && ls.error) || "云端列举失败";
34
+ } catch (e) { cloudError = (e && e.message) || String(e); }
35
+
36
+ // 删除本地快照并回收数据块,必须与备份写入互斥(见 lib/engine/lock.js)。
37
+ // dryRun 只读,不取锁,否则面板里的「预览」会在备份期间被拒。
38
+ const lock = dryRun ? { ok: true, lockFile: null } : acquireLock(storeDir);
39
+ if (!lock.ok) return busyResult(lock);
40
+ try {
41
+ const plan = [];
42
+ let deleted = 0, freedSnapshotBytes = 0;
43
+ for (const s of targets) {
44
+ const man = readManifest(s.file);
45
+ const files = man && man.files ? man.files.length : 0;
46
+ const bytes = man && man.stats ? man.stats.bytes || 0 : 0;
47
+ const hasCloud = cloud ? cloud.get(s.stamp) === true : false;
48
+ let action = "delete", reason = "";
49
+ if (requireCloud && !cloud) { action = "skip"; reason = "云端不可达,不敢删(" + cloudError + ")"; }
50
+ else if (requireCloud && !hasCloud) { action = "skip"; reason = "云端没有这份快照的清单"; }
51
+ plan.push({ stamp: s.stamp, files, bytes, cloudHasManifest: cloud ? hasCloud : null, action, reason });
52
+ if (action !== "delete" || dryRun) continue;
53
+ try {
54
+ fs.rmSync(snapshotDir(storeDir, s.stamp), { recursive: true, force: true });
55
+ deleted++;
56
+ freedSnapshotBytes += bytes;
57
+ logger("prune-local removed " + s.stamp);
58
+ } catch (e) {
59
+ plan[plan.length - 1].action = "failed";
60
+ plan[plan.length - 1].reason = "删除失败: " + ((e && e.message) || e);
61
+ logger("prune-local " + s.stamp + " failed: " + ((e && e.message) || e));
62
+ }
63
+ }
64
+
65
+ const gc = { candidates: 0, deleted: 0, freedBytes: 0, keptLocalOnly: 0, skipped: false };
66
+ if (reclaim && (dryRun || deleted > 0)) {
67
+ let refs;
68
+ try {
69
+ if (dryRun) {
70
+ // 演练模式:本地还没删,必须按「删完剩下的快照」算引用集,否则「回收数据块」永远显示 0
71
+ refs = new Set();
72
+ for (const s of keep) {
73
+ const m = readManifest(s.file);
74
+ for (const f of m && m.files ? m.files : []) refs.add(f.hash);
75
+ }
76
+ } else {
77
+ refs = rebuildIndex(storeDir, { provider: "aliyun" }).refs;
78
+ }
79
+ } catch (e) { gc.skipped = true; gc.error = String((e && e.message) || e); }
80
+ if (refs) {
81
+ const remote = (loadRemoteState(storeDir) || {}).blobs || {};
82
+ for (const b of listBlobs(storeDir)) {
83
+ if (refs.has(b.hash)) continue;
84
+ if (!remote[b.hash] || !remote[b.hash].file_id) { gc.keptLocalOnly++; continue; }
85
+ gc.candidates++;
86
+ gc.freedBytes += b.size;
87
+ if (dryRun) { gc.deleted++; continue; }
88
+ try { fs.unlinkSync(b.path); gc.deleted++; } catch {}
89
+ }
90
+ }
91
+ }
92
+
93
+ return {
94
+ ok: true, dryRun, storeDir,
95
+ localSnapshots: snaps.length,
96
+ keep: keep.map((s) => s.stamp),
97
+ targets: targets.map((s) => s.stamp),
98
+ cloud: { ok: !!cloud, error: cloudError, snapshots: cloud ? cloud.size : 0 },
99
+ plan, deleted, freedSnapshotBytes, gc,
100
+ };
101
+ } finally { releaseLock(lock); }
102
+ }
@@ -0,0 +1,172 @@
1
+ // 自重启:交给脱离进程的助手脚本先等端口释放、再拉起新宿主并确认应答;Windows 需 -WindowStyle Hidden 包一层。
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { spawn } from "node:child_process";
5
+
6
+ const INSPECT_FLAG = /^--inspect(-brk|-port|-wait)?(=|$)/;
7
+ const HELPER_NAME = "restart-helper.mjs";
8
+
9
+ // 助手源码:避免模板插值,全部用字符串拼接
10
+ const HELPER_SOURCE = [
11
+ 'import fs from "node:fs";',
12
+ 'import net from "node:net";',
13
+ 'import http from "node:http";',
14
+ 'import { spawn } from "node:child_process";',
15
+ "",
16
+ "const cfg = JSON.parse(fs.readFileSync(process.argv[2], \"utf8\"));",
17
+ "const sleep = (ms) => new Promise((r) => setTimeout(r, ms));",
18
+ "function note(line) {",
19
+ " try { fs.appendFileSync(cfg.logFile, new Date().toISOString() + \" \" + line + \"\\n\"); } catch (e) { /* 日志写不进去不影响重启 */ }",
20
+ "}",
21
+ "function portBusy(port) {",
22
+ " return new Promise((resolve) => {",
23
+ " const s = net.connect({ host: \"127.0.0.1\", port: port });",
24
+ " let done = false;",
25
+ " const fin = (v) => { if (done) return; done = true; try { s.destroy(); } catch (e) {} resolve(v); };",
26
+ " s.once(\"connect\", () => fin(true));",
27
+ " s.once(\"error\", () => fin(false));",
28
+ " s.setTimeout(500, () => fin(false));",
29
+ " });",
30
+ "}",
31
+ "function ready(port) {",
32
+ " return new Promise((resolve) => {",
33
+ " const req = http.get({ host: \"127.0.0.1\", port: port, path: \"/\", timeout: 1500 }, (res) => { res.resume(); resolve(res.statusCode >= 200 && res.statusCode < 500); });",
34
+ " req.on(\"error\", () => resolve(false));",
35
+ " req.on(\"timeout\", () => { req.destroy(); resolve(false); });",
36
+ " });",
37
+ "}",
38
+ "(async function () {",
39
+ " let freed = false;",
40
+ " for (let i = 0; i < 160; i++) { if (!(await portBusy(cfg.port))) { freed = true; break; } await sleep(250); }",
41
+ " note(\"old host released port=\" + cfg.port + \" freed=\" + String(freed));",
42
+ " const child = spawn(cfg.spawn.file, cfg.spawn.args, { cwd: cfg.cwd || undefined, env: process.env, detached: !!cfg.spawn.detached, windowsHide: true, stdio: \"ignore\", shell: false });",
43
+ " child.on(\"error\", (e) => note(\"spawn failed: \" + ((e && e.message) || String(e))));",
44
+ " note(\"spawned pid=\" + String(child.pid) + \" file=\" + cfg.spawn.file);",
45
+ " let up = false;",
46
+ " for (let i = 0; i < 120; i++) { if (await ready(cfg.port)) { up = true; break; } await sleep(500); }",
47
+ " note(up ? \"host is serving again on port=\" + cfg.port : \"host did not answer on port=\" + cfg.port);",
48
+ " process.exit(up ? 0 : 1);",
49
+ "})().catch((e) => { note(\"helper failed: \" + ((e && e.message) || String(e))); });",
50
+ "",
51
+ ].join("\n");
52
+
53
+ /** 运行本进程的 node:argv0 是绝对路径且存在时就用它,否则退回 execPath。 */
54
+ export function nodeExecutable(argv0 = process.argv0, execPath = process.execPath) {
55
+ if (typeof argv0 === "string" && argv0 && path.isAbsolute(argv0) && fs.existsSync(argv0)) return argv0;
56
+ return execPath;
57
+ }
58
+
59
+ /** 自重启的前置否决:返回原因字符串即拒绝,返回 null 表示可以重启。 */
60
+ export function restartRefusal(env = process.env, execArgv = process.execArgv, argv = process.argv) {
61
+ if (String((env && env.DSH_CLOUD_BACKUP_NO_RESTART) || "") === "1") return "已用 DSH_CLOUD_BACKUP_NO_RESTART=1 关闭自重启";
62
+ const all = (execArgv || []).concat(argv || []);
63
+ for (const a of all) if (INSPECT_FLAG.test(String(a))) return "宿主处于调试模式(--inspect),自重启被拒绝";
64
+ return null;
65
+ }
66
+
67
+ /** 复现宿主的启动方式:入口是 CLI 时用 node 把同一入口拉起;入口不认识时退回 PATH 上的 dsh(Windows 上是 .cmd,只能交给 shell)。 */
68
+ export function launchSpec(argv1 = process.argv[1], execArgv = process.execArgv, extraArgs = process.argv.slice(2), platform = process.platform) {
69
+ const asString = typeof argv1 === "string" ? argv1 : "";
70
+ const desktopCli = /[\\/]node_modules[\\/]@deepseek-ai[\\/]dsh-desktop-host[\\/]lib[\\/]cli\.js$/.test(asString);
71
+ if (asString && (desktopCli || /[\\/](?:bin\.(?:js|ts)|dsh)$/.test(asString))) {
72
+ const abs = path.resolve(asString);
73
+ // 源码启动会传相对入口,子进程按自己的 cwd 解析会 MODULE_NOT_FOUND,所以一律用绝对路径;
74
+ // 入口在 app.asar 里时 Electron 能读、操作系统不能 chdir,故桌面形态不给 cwd。
75
+ return { kind: "cli", file: nodeExecutable(), args: [...(execArgv || []), abs, ...(extraArgs || [])], cwd: desktopCli ? undefined : path.dirname(abs), viaShell: false };
76
+ }
77
+ return { kind: "path", file: "dsh", args: [...(extraArgs || [])], cwd: undefined, viaShell: platform === "win32" };
78
+ }
79
+
80
+ /** 把启动方案整理成可判定的计划:能不能找到入口,先看清楚再决定要不要杀进程。 */
81
+ export function describeLaunch(spec, platform = process.platform, env = process.env) {
82
+ if (!spec) return null;
83
+ let resolvable = false;
84
+ if (!spec.viaShell) {
85
+ try { resolvable = fs.existsSync(spec.file); } catch { resolvable = false; }
86
+ } else {
87
+ const names = platform === "win32" ? ["dsh.cmd", "dsh.bat", "dsh.exe"] : ["dsh"];
88
+ const dirs = String((env && env.PATH) || "").split(path.delimiter).filter(Boolean);
89
+ resolvable = dirs.some((d) => names.some((n) => { try { return fs.existsSync(path.join(d, n)); } catch { return false; } }));
90
+ }
91
+ return { kind: spec.kind, file: spec.file, args: spec.args, cwd: spec.cwd || null, viaShell: !!spec.viaShell, resolvable };
92
+ }
93
+
94
+ /** 平台正确的拉起方式(Windows 包一层隐藏 PowerShell)。 */
95
+ export function respawnInvocation(spec, platform = process.platform) {
96
+ if (!spec) return null;
97
+ if (platform !== "win32") return { file: spec.file, args: spec.args, detached: true, viaShell: !!spec.viaShell };
98
+ // PowerShell 单引号只需转义内层单引号;显式点名 .cmd,避免被优先选中的 .ps1 撞上执行策略
99
+ const quote = (part) => "'" + String(part).replace(/'/g, "''") + "'";
100
+ const file = spec.viaShell && !/\.(?:cmd|bat)$/iu.test(spec.file) ? spec.file + ".cmd" : spec.file;
101
+ return {
102
+ file: "powershell.exe",
103
+ args: ["-NoProfile", "-WindowStyle", "Hidden", "-Command", ["& " + quote(file)].concat((spec.args || []).map(quote)).join(" ")],
104
+ detached: false,
105
+ viaShell: false,
106
+ };
107
+ }
108
+
109
+ /** 当前服务的端口:优先取连接本端端口,其次解析 Host 头。 */
110
+ export function servingPort(req) {
111
+ try {
112
+ const local = req && req.socket && req.socket.localPort;
113
+ if (Number.isFinite(local) && local > 0) return Number(local);
114
+ } catch { /* 落到 Host 头 */ }
115
+ const host = String((req && req.headers && (req.headers.host || req.headers.HOST)) || "");
116
+ const m = /:(\d{2,5})\s*$/.exec(host);
117
+ return m ? Number(m[1]) : null;
118
+ }
119
+
120
+ /** Electron 里的 execPath 是应用本身,助手要当纯 node 跑,必须显式降级。 */
121
+ function helperEnv(env = process.env, versions = process.versions) {
122
+ const out = { ...env };
123
+ if (versions && versions.electron) out.ELECTRON_RUN_AS_NODE = "1";
124
+ return out;
125
+ }
126
+
127
+ export function helperPath(logDir) {
128
+ return path.join(logDir, HELPER_NAME);
129
+ }
130
+
131
+ /** 写出助手脚本;内容随源码更新,文件已存在且一致时不再写盘。 */
132
+ export function ensureHelper(logDir) {
133
+ const file = helperPath(logDir);
134
+ try {
135
+ if (!fs.existsSync(logDir)) fs.mkdirSync(logDir, { recursive: true });
136
+ let current = null;
137
+ try { current = fs.readFileSync(file, "utf8"); } catch { current = null; }
138
+ if (current !== HELPER_SOURCE) fs.writeFileSync(file, HELPER_SOURCE, "utf8");
139
+ return file;
140
+ } catch { return null; }
141
+ }
142
+
143
+ /** 交给助手重启,并在延迟后结束本进程;计划先落盘,拉起失败也能从日志看出它尝试了什么。 */
144
+ export function scheduleRestart({ spec, port, logDir, delayMs = 600, platform = process.platform, logFile = null }) {
145
+ const helper = ensureHelper(logDir);
146
+ if (!helper) return { ok: false, error: "助手脚本写不出去:" + String(logDir) };
147
+ const spawnSpec = respawnInvocation(spec, platform);
148
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
149
+ const log = logFile || path.join(logDir, "restart-" + stamp + ".log");
150
+ const configPath = path.join(logDir, "restart-" + stamp + ".json");
151
+ const config = {
152
+ port: port || null,
153
+ spawn: spawnSpec,
154
+ cwd: spec && spec.cwd ? spec.cwd : null,
155
+ logFile: log,
156
+ startedAt: new Date().toISOString(),
157
+ atPid: process.pid,
158
+ };
159
+ try { fs.writeFileSync(configPath, JSON.stringify(config, null, 2), "utf8"); } catch (e) {
160
+ return { ok: false, error: "重启配置写不出去:" + String((e && e.message) || e) };
161
+ }
162
+ let child = null;
163
+ try {
164
+ child = spawn(nodeExecutable(), [helper, configPath], { detached: true, stdio: "ignore", env: helperEnv(), windowsHide: true });
165
+ child.unref();
166
+ } catch (e) {
167
+ return { ok: false, error: "助手启动失败:" + String((e && e.message) || e), configPath, logFile: log };
168
+ }
169
+ const timer = setTimeout(() => { try { process.kill(process.pid, "SIGTERM"); } catch { /* 退出失败只能人工关掉宿主 */ } }, delayMs);
170
+ if (timer.unref) timer.unref();
171
+ return { ok: true, helperPid: child.pid, configPath, logFile: log, spawn: spawnSpec, delayMs };
172
+ }