@pkkkkh/dsh-restart 0.0.0-stage → 0.2.6
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/LICENSE +21 -0
- package/README.md +192 -2
- package/cordis.patch.yml +40 -0
- package/lib/announce.js +147 -0
- package/lib/args.js +90 -0
- package/lib/index.js +756 -0
- package/lib/timings.js +45 -0
- package/package.json +42 -3
- package/scripts/dsh-restart-tasks.ps1 +53 -0
- package/scripts/dsh-watchdog.cjs +61 -0
- package/scripts/restart-dsh-arm.ps1 +76 -0
- package/scripts/restart-dsh-arm2.ps1 +111 -0
- package/scripts/restart-dsh-start.ps1 +95 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,756 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-restart — model-facing tools that schedule a safe self-restart.
|
|
3
|
+
*
|
|
4
|
+
* Why a plugin: the restart itself is a desktop-side operation (kill this
|
|
5
|
+
* process and bring it back), but from IM or the Web GUI the agent cannot
|
|
6
|
+
* "press the button". This plugin lets the agent arm the restart on the
|
|
7
|
+
* user's behalf — with an explicit confirm, preflight checks, and a log
|
|
8
|
+
* readback so the caller can see the tasks were really registered.
|
|
9
|
+
*
|
|
10
|
+
* The kill/start work deliberately stays in the vetted scripts:
|
|
11
|
+
* scripts/restart-dsh-arm.ps1 start-first ordering + rollback (default)
|
|
12
|
+
* scripts/restart-dsh-arm2.ps1 same, plus -StartScript / -WatchAfterSeconds
|
|
13
|
+
* scripts/restart-dsh-fallback.cmd one retry if the app dies at startup
|
|
14
|
+
* scripts/restart-dsh-start.ps1 explorer launch + 20s "did it stay up" check
|
|
15
|
+
* scripts/dsh-restart-tasks.ps1 status / cancel of the armed tasks
|
|
16
|
+
* This module only wraps them; it does not re-implement Task Scheduler logic.
|
|
17
|
+
*
|
|
18
|
+
* 2026-11-10: tool results are plain strings on purpose. `output.schema` is an
|
|
19
|
+
* author-facing spec and a malformed one throws at defineTool() compile time,
|
|
20
|
+
* which kills the whole plugin (the first load attempt failed exactly that way).
|
|
21
|
+
*
|
|
22
|
+
* @module dsh-restart
|
|
23
|
+
*/
|
|
24
|
+
import { spawn } from "node:child_process";
|
|
25
|
+
import { appendFileSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
26
|
+
import { readFile } from "node:fs/promises";
|
|
27
|
+
import { dirname } from "node:path";
|
|
28
|
+
import z from "@deepseek-ai/schemastery";
|
|
29
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
30
|
+
import { fileURLToPath } from "node:url";
|
|
31
|
+
import { describeTimings, resolveTimings, DEFAULT_KILL_SECONDS } from "./timings.js";
|
|
32
|
+
|
|
33
|
+
// 2026-11-16:本机绝对路径的自动回退。配置里的路径不存在时(换电脑/换用户名),
|
|
34
|
+
// 按「插件自身位置」推导工作区根,再拼同名相对路径——旧机行为完全不变。
|
|
35
|
+
const WS_ROOT = (() => {
|
|
36
|
+
try { return fileURLToPath(new URL("../../../../", import.meta.url)).replace(/[\\/]+$/, ""); }
|
|
37
|
+
catch { return ""; }
|
|
38
|
+
})();
|
|
39
|
+
|
|
40
|
+
/** 配置文件类路径:父目录存在就用配置值,否则用回退值。 */
|
|
41
|
+
function resolveFile(configured, fallback) {
|
|
42
|
+
const value = String(configured ?? "").trim();
|
|
43
|
+
if (!value) return fallback;
|
|
44
|
+
try { if (existsSync(dirname(value))) return value; } catch { /* fall through */ }
|
|
45
|
+
return fallback || value;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// 插件自带一份脚本副本(2026-11-16 起入库),换机器时优先用它
|
|
49
|
+
const PLUGIN_ROOT = (() => {
|
|
50
|
+
try { return fileURLToPath(new URL("../", import.meta.url)).replace(/[\\/]+$/, ""); }
|
|
51
|
+
catch { return ""; }
|
|
52
|
+
})();
|
|
53
|
+
|
|
54
|
+
/** 脚本类路径:配置的必须真实存在才用,否则按「插件内 → 工作区」顺序找。 */
|
|
55
|
+
function resolveScript(configured, candidates) {
|
|
56
|
+
const value = String(configured ?? "").trim();
|
|
57
|
+
if (value && existsSync(value)) return value;
|
|
58
|
+
for (const candidate of candidates) {
|
|
59
|
+
if (candidate && existsSync(candidate)) return candidate;
|
|
60
|
+
}
|
|
61
|
+
return value || candidates.find(Boolean) || "";
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 目录类路径:本来就不存在的目录(如备份根)同样按父目录判断。 */
|
|
65
|
+
function resolveDir(configured, fallback) {
|
|
66
|
+
const value = String(configured ?? "").trim();
|
|
67
|
+
if (!value) return fallback;
|
|
68
|
+
try { if (existsSync(value) || existsSync(dirname(value))) return value; } catch { /* fall through */ }
|
|
69
|
+
return fallback || value;
|
|
70
|
+
}
|
|
71
|
+
import { buildArmArgs, needsExtendedScript, normalizeWatchSeconds, parseTaskStatus } from "./args.js";
|
|
72
|
+
// 公开版(由私有仓库导出):脚本用插件自带的 scripts/,日志与状态用 DSH_HOME 或插件目录下的 .state。
|
|
73
|
+
const pubStrip = (s) => { let r = String(s ?? ""); while (r.length && (r.endsWith("/") || r.charCodeAt(r.length - 1) === 92)) r = r.slice(0, -1); return r; };
|
|
74
|
+
const STATE_HOME = pubStrip(process.env.DSH_HOME ?? "") || PLUGIN_ROOT + "/.state";
|
|
75
|
+
const SCRIPT_ROOT = (() => { try { const local = fileURLToPath(new URL("../scripts", import.meta.url)); if (existsSync(local)) return pubStrip(local); } catch {} return PLUGIN_ROOT + "/scripts"; })();
|
|
76
|
+
const DEFAULT_ARM_SCRIPT = SCRIPT_ROOT + "/restart-dsh-arm.ps1";
|
|
77
|
+
const DEFAULT_MAINT_ARM_SCRIPT = SCRIPT_ROOT + "/restart-dsh-arm2.ps1";
|
|
78
|
+
const DEFAULT_TASKS_SCRIPT = SCRIPT_ROOT + "/dsh-restart-tasks.ps1";
|
|
79
|
+
const DEFAULT_LOG_FILE = STATE_HOME + "/logs/restart-dsh.log";
|
|
80
|
+
const DEFAULT_ANNOUNCE_FILE = STATE_HOME + "/logs/restart-announce.json";
|
|
81
|
+
// 本机 DSH home 也是私有路径,公开版改为「DSH_HOME → 用户主目录/dsh-home」推导。
|
|
82
|
+
const DSH_HOME_DEFAULT = pubStrip(process.env.DSH_HOME ?? "") || pubStrip(process.env.USERPROFILE ?? process.env.HOME ?? "") + "/dsh-home";
|
|
83
|
+
|
|
84
|
+
// Import-time breadcrumb: proves the loader reached this module at all.
|
|
85
|
+
// Without it we cannot tell "never imported" from "apply() failed".
|
|
86
|
+
// 公开版:import 面包屑已移除(原来写死日志路径)
|
|
87
|
+
import {
|
|
88
|
+
DEFAULT_ANNOUNCE_TEXT,
|
|
89
|
+
DEFAULT_MAX_AGE_MINUTES,
|
|
90
|
+
clearMarker,
|
|
91
|
+
isFresh,
|
|
92
|
+
readMarker,
|
|
93
|
+
resolveDelivery,
|
|
94
|
+
writeMarker,
|
|
95
|
+
} from "./announce.js";
|
|
96
|
+
|
|
97
|
+
export const name = "dsh-restart";
|
|
98
|
+
export const inject = ["tools", "commands"];
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
/** 进程身份:pid + startedAt(用 performance.timeOrigin 反推,避开系统时钟跳变)。
|
|
103
|
+
* 借鉴自 anweat/dsh-restart 的「pid + startedAt 双因子」思路(MIT)。 */
|
|
104
|
+
function processStartedAtISO() {
|
|
105
|
+
try {
|
|
106
|
+
return new Date(Date.now() - Math.round(performance.now())).toISOString();
|
|
107
|
+
} catch {
|
|
108
|
+
return new Date().toISOString();
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function readJsonSafe(path) {
|
|
113
|
+
try { return JSON.parse(readFileSync(path, "utf8")); } catch { return null; }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function writeJsonSafe(path, value) {
|
|
117
|
+
try { writeFileSync(path, JSON.stringify(value, null, 2), "utf8"); return true; } catch { return false; }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export const Config = z.object({
|
|
121
|
+
armScript: z.string().default(DEFAULT_ARM_SCRIPT),
|
|
122
|
+
maintArmScript: z.string().default(DEFAULT_MAINT_ARM_SCRIPT),
|
|
123
|
+
tasksScript: z.string().default(DEFAULT_TASKS_SCRIPT),
|
|
124
|
+
logFile: z.string().default(DEFAULT_LOG_FILE),
|
|
125
|
+
// 插件自己的日志:与脚本写的 logFile 分开,避免脚本独占锁导致 EBUSY
|
|
126
|
+
pluginLogFile: z.string().default(STATE_HOME + "/logs/restart-plugin.log"),
|
|
127
|
+
// ── 重启前备份 profile 的三个关键文件(改动前留一份,最便宜的回滚点)──
|
|
128
|
+
backupEnabled: z.boolean().default(true),
|
|
129
|
+
backupDir: z.string().default(STATE_HOME + "/logs/restart-backups"),
|
|
130
|
+
backupKeep: z.number().default(10),
|
|
131
|
+
profileDir: z.string().default(DSH_HOME_DEFAULT + "/profiles/desktop"),
|
|
132
|
+
powershell: z.string().default("powershell.exe"),
|
|
133
|
+
defaultKillSeconds: z.number().default(DEFAULT_KILL_SECONDS),
|
|
134
|
+
announce: z.boolean().default(true),
|
|
135
|
+
announceText: z.string().default(DEFAULT_ANNOUNCE_TEXT),
|
|
136
|
+
announceMaxAgeMinutes: z.number().default(DEFAULT_MAX_AGE_MINUTES),
|
|
137
|
+
announceFile: z.string().default(DEFAULT_ANNOUNCE_FILE),
|
|
138
|
+
// ── 常驻看门狗(默认关;心跳文件超时没更新就拉起 DSH)──
|
|
139
|
+
watchdogEnabled: z.boolean().default(false),
|
|
140
|
+
watchdogPollMs: z.number().default(2000),
|
|
141
|
+
watchdogStaleMs: z.number().default(15000),
|
|
142
|
+
watchdogCooldownMs: z.number().default(60000),
|
|
143
|
+
watchdogScript: z.string().default(SCRIPT_ROOT + "/dsh-watchdog.cjs"),
|
|
144
|
+
// 显式指定 node 可执行文件;留空则自动探测(Electron 里 process.execPath 是 exe,不能直接跑 .cjs)
|
|
145
|
+
watchdogNode: z.string().default(""),
|
|
146
|
+
announceBotId: z.string().default(""),
|
|
147
|
+
announceTargetId: z.string().default(""),
|
|
148
|
+
announceAutoTarget: z.boolean().default(true),
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
/** Run one process with pipes; resolves (never rejects) with {code, output}. */
|
|
152
|
+
function runProcess(file, args, timeoutMs) {
|
|
153
|
+
return new Promise((resolve) => {
|
|
154
|
+
let child;
|
|
155
|
+
const chunks = [];
|
|
156
|
+
try {
|
|
157
|
+
child = spawn(file, args, { windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
|
|
158
|
+
} catch (error) {
|
|
159
|
+
resolve({ code: -1, output: String(error?.message ?? error) });
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
const timer = setTimeout(() => {
|
|
163
|
+
try { child.kill("SIGKILL"); } catch { /* ignore */ }
|
|
164
|
+
resolve({ code: -1, output: chunks.join("") + "\ntimed out after " + timeoutMs + "ms" });
|
|
165
|
+
}, timeoutMs);
|
|
166
|
+
child.stdout?.on("data", (data) => chunks.push(String(data)));
|
|
167
|
+
child.stderr?.on("data", (data) => chunks.push(String(data)));
|
|
168
|
+
child.on("error", (error) => {
|
|
169
|
+
clearTimeout(timer);
|
|
170
|
+
resolve({ code: -1, output: String(error?.message ?? error) });
|
|
171
|
+
});
|
|
172
|
+
child.on("close", (code) => {
|
|
173
|
+
clearTimeout(timer);
|
|
174
|
+
resolve({ code: code ?? -1, output: chunks.join("") });
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function tailLines(text, count) {
|
|
180
|
+
return String(text ?? "").trimEnd().split(/\r?\n/).slice(-count).join("\n");
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Wait for the dshIm service. At boot the IM plugin registers its service
|
|
187
|
+
* asynchronously — at +3s it was still missing (2026-11-10 18:18), so poll.
|
|
188
|
+
*/
|
|
189
|
+
async function waitForIm(ctx, timeoutMs = 25000) {
|
|
190
|
+
const deadline = Date.now() + timeoutMs;
|
|
191
|
+
for (;;) {
|
|
192
|
+
const im = typeof ctx.get === "function" ? ctx.get("dshIm") : null;
|
|
193
|
+
if (im && typeof im.send === "function") return im;
|
|
194
|
+
if (Date.now() >= deadline) return null;
|
|
195
|
+
await sleep(1500);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Wait until a delivery route is resolvable. The bot list fills in after the
|
|
201
|
+
* channels connect, so an early "no-bot" is retried instead of giving up.
|
|
202
|
+
*/
|
|
203
|
+
async function waitForRoute(im, opts, timeoutMs = 20000) {
|
|
204
|
+
const deadline = Date.now() + timeoutMs;
|
|
205
|
+
let route = { error: "no-bot" };
|
|
206
|
+
for (;;) {
|
|
207
|
+
route = await resolveDelivery(im, { botId: opts.botId, targetId: opts.targetId, channel: opts.channel });
|
|
208
|
+
if (route.targetId) return route;
|
|
209
|
+
if (route.error === "no-target" || String(route.error).startsWith("list-targets-failed")) return route;
|
|
210
|
+
if (Date.now() >= deadline) return route;
|
|
211
|
+
await sleep(1500);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Post-restart greeting. Marker is cleared BEFORE sending (no crash-loop spam). */
|
|
216
|
+
async function announceIfPending(ctx, opts) {
|
|
217
|
+
const marker = readMarker(opts.file);
|
|
218
|
+
if (!marker) return;
|
|
219
|
+
if (!isFresh(marker, new Date(), opts.maxAgeMinutes)) {
|
|
220
|
+
clearMarker(opts.file);
|
|
221
|
+
opts.log("[announce] marker too old, dropped");
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
clearMarker(opts.file);
|
|
225
|
+
try {
|
|
226
|
+
const im = await waitForIm(ctx, opts.waitServiceMs ?? 25000);
|
|
227
|
+
if (!im) {
|
|
228
|
+
opts.log("[announce] IM service still unavailable after wait, greeting not delivered: " + marker.text);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
const route = await waitForRoute(im, { ...opts, channel: marker.channel }, opts.waitRouteMs ?? 60000);
|
|
232
|
+
if (!route.targetId) {
|
|
233
|
+
opts.log("[announce] " + route.error + " — configured target needed: 设置 → IM机器人 → 新建目标");
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
await im.send(route.botId, route.targetId, marker.text);
|
|
237
|
+
opts.log("[announce] sent after restart via " + route.botId + "/" + route.targetId + ": " + marker.text);
|
|
238
|
+
} catch (error) {
|
|
239
|
+
opts.log("[announce] failed: " + String(error?.message ?? error));
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* defineTool requires output.render (verified against the real host module:
|
|
245
|
+
* omitting output throws "Cannot read properties of undefined (reading 'render')").
|
|
246
|
+
* Our execute() returns plain strings, so render is a passthrough.
|
|
247
|
+
*/
|
|
248
|
+
function toolOutput() {
|
|
249
|
+
return {
|
|
250
|
+
schema: { type: "object", additionalProperties: true, properties: {} },
|
|
251
|
+
render: (_args, value) => [{ type: "text", text: String(value?.text ?? "") }],
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export function apply(ctx, config) {
|
|
256
|
+
const armScript = resolveScript(config?.armScript ?? DEFAULT_ARM_SCRIPT, [PLUGIN_ROOT + "/scripts/restart-dsh-arm.ps1", WS_ROOT + "/scripts/restart-dsh-arm.ps1"]);
|
|
257
|
+
const maintArmScript = resolveScript(config?.maintArmScript ?? DEFAULT_MAINT_ARM_SCRIPT, [PLUGIN_ROOT + "/scripts/restart-dsh-arm2.ps1", WS_ROOT + "/scripts/restart-dsh-arm2.ps1"]);
|
|
258
|
+
const tasksScript = resolveScript(config?.tasksScript ?? DEFAULT_TASKS_SCRIPT, [PLUGIN_ROOT + "/scripts/dsh-restart-tasks.ps1", WS_ROOT + "/scripts/dsh-restart-tasks.ps1"]);
|
|
259
|
+
const logFile = resolveFile(config?.logFile ?? DEFAULT_LOG_FILE, WS_ROOT + "/logs/restart-dsh.log");
|
|
260
|
+
const pluginLogFile = resolveFile(config?.pluginLogFile ?? STATE_HOME + "/logs/restart-plugin.log", WS_ROOT + "/logs/restart-plugin.log");
|
|
261
|
+
const powershell = String(config?.powershell ?? "powershell.exe").trim();
|
|
262
|
+
const defaultKillSeconds = Number(config?.defaultKillSeconds ?? DEFAULT_KILL_SECONDS);
|
|
263
|
+
const announce = config?.announce !== false;
|
|
264
|
+
const announceText = String(config?.announceText ?? DEFAULT_ANNOUNCE_TEXT).trim() || DEFAULT_ANNOUNCE_TEXT;
|
|
265
|
+
const announceFile = resolveFile(config?.announceFile ?? DEFAULT_ANNOUNCE_FILE, WS_ROOT + "/logs/restart-announce.json");
|
|
266
|
+
const announceMaxAgeMinutes = Number(config?.announceMaxAgeMinutes ?? DEFAULT_MAX_AGE_MINUTES);
|
|
267
|
+
|
|
268
|
+
const log = (msg) => {
|
|
269
|
+
const line = "[" + new Date().toISOString() + "] " + msg + "\n";
|
|
270
|
+
try {
|
|
271
|
+
appendFileSync(pluginLogFile, line, "utf8");
|
|
272
|
+
} catch (error) {
|
|
273
|
+
// 写不进去时留证据到 .fallback,别静默吞掉
|
|
274
|
+
try { appendFileSync(pluginLogFile + ".fallback", line + " (append failed: " + String(error?.message ?? error) + ")\n", "utf8"); } catch { /* give up */ }
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
log("[boot] dsh-restart loaded (announce=" + announce + ", marker=" + (existsSync(announceFile) ? "pending" : "none") + ")");
|
|
279
|
+
|
|
280
|
+
// ---------- 进程身份(pid + startedAt)----------
|
|
281
|
+
const stateDir = dirname(logFile);
|
|
282
|
+
const processFile = stateDir + "/dsh-process.json";
|
|
283
|
+
const armRecordFile = stateDir + "/dsh-arm-record.json";
|
|
284
|
+
const me = {
|
|
285
|
+
pid: process.pid,
|
|
286
|
+
startedAt: processStartedAtISO(),
|
|
287
|
+
cwd: process.cwd(),
|
|
288
|
+
recordedAt: new Date().toISOString(),
|
|
289
|
+
};
|
|
290
|
+
writeJsonSafe(processFile, me);
|
|
291
|
+
log("[boot] process identity pid=" + me.pid + " startedAt=" + me.startedAt);
|
|
292
|
+
|
|
293
|
+
// ---------- 重启前备份 + 停机时长 ----------
|
|
294
|
+
const killRecordFile = stateDir + "/dsh-kill-record.json";
|
|
295
|
+
const backupEnabled = config?.backupEnabled !== false;
|
|
296
|
+
const backupRoot = resolveDir(config?.backupDir ?? STATE_HOME + "/logs/restart-backups", WS_ROOT + "/logs/restart-backups");
|
|
297
|
+
const backupKeep = Math.max(1, Math.min(50, Number(config?.backupKeep ?? 10)));
|
|
298
|
+
const profileDir = resolveDir(config?.profileDir ?? DSH_HOME_DEFAULT + "/profiles/desktop", (process.env.DSH_HOME || DSH_HOME_DEFAULT + "").replace(/[\\/]+$/, "") + "/profiles/desktop");
|
|
299
|
+
|
|
300
|
+
const backupProfile = () => {
|
|
301
|
+
if (!backupEnabled) return { ok: false, reason: "已关闭" };
|
|
302
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
303
|
+
const dir = backupRoot + "/" + stamp;
|
|
304
|
+
try { mkdirSync(dir, { recursive: true }); }
|
|
305
|
+
catch (error) { return { ok: false, reason: "建目录失败:" + String(error?.message ?? error) }; }
|
|
306
|
+
const copied = [];
|
|
307
|
+
for (const name of ["package.json", "pnpm-lock.yaml", "cordis.patch.yml"]) {
|
|
308
|
+
try { copyFileSync(profileDir + "/" + name, dir + "/" + name); copied.push(name); } catch { /* 缺文件就跳过 */ }
|
|
309
|
+
}
|
|
310
|
+
try {
|
|
311
|
+
const all = readdirSync(backupRoot, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort();
|
|
312
|
+
for (const old of all.slice(0, Math.max(0, all.length - backupKeep))) {
|
|
313
|
+
try { rmSync(backupRoot + "/" + old, { recursive: true, force: true }); } catch { /* best effort */ }
|
|
314
|
+
}
|
|
315
|
+
} catch { /* prune 失败不影响备份 */ }
|
|
316
|
+
log("[backup] " + dir + " files=" + copied.length);
|
|
317
|
+
return { ok: true, dir, files: copied };
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
// 停机时长:排程时记下预计 kill 时刻,启动后算差(±1 秒,够用)
|
|
321
|
+
let downtimeSeconds = null;
|
|
322
|
+
{
|
|
323
|
+
const rec = readJsonSafe(killRecordFile);
|
|
324
|
+
if (rec && Number(rec.killAt)) {
|
|
325
|
+
const secs = Math.round((Date.now() - Number(rec.killAt)) / 1000);
|
|
326
|
+
if (secs >= 0 && secs < 3600) {
|
|
327
|
+
downtimeSeconds = secs;
|
|
328
|
+
me.downtimeSeconds = secs;
|
|
329
|
+
writeJsonSafe(processFile, me);
|
|
330
|
+
log("[boot] downtime ≈ " + secs + "s");
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// ---------- 心跳 + 常驻看门狗 ----------
|
|
336
|
+
const heartbeatFile = stateDir + "/dsh-heartbeat.json";
|
|
337
|
+
const restartFlagFile = stateDir + "/dsh-restarting.flag";
|
|
338
|
+
const stopFlagFile = stateDir + "/dsh-stop.flag";
|
|
339
|
+
const watchdogConfigFile = stateDir + "/dsh-watchdog.json";
|
|
340
|
+
const watchdogPidFile = stateDir + "/dsh-watchdog.pid";
|
|
341
|
+
const watchdogLog = stateDir + "/dsh-watchdog.log";
|
|
342
|
+
const watchdogEnabled = config?.watchdogEnabled === true;
|
|
343
|
+
const watchdogScript = resolveScript(config?.watchdogScript ?? SCRIPT_ROOT + "/dsh-watchdog.cjs", [PLUGIN_ROOT + "/scripts/dsh-watchdog.cjs", WS_ROOT + "/scripts/dsh-watchdog.cjs"]);
|
|
344
|
+
const watchdogPollMs = Math.max(500, Number(config?.watchdogPollMs ?? 2000));
|
|
345
|
+
const watchdogStaleMs = Math.max(5000, Number(config?.watchdogStaleMs ?? 15000));
|
|
346
|
+
const watchdogCooldownMs = Math.max(20000, Number(config?.watchdogCooldownMs ?? 60000));
|
|
347
|
+
|
|
348
|
+
const touchHeartbeat = () => writeJsonSafe(heartbeatFile, { pid: me.pid, startedAt: me.startedAt, ts: Date.now() });
|
|
349
|
+
touchHeartbeat();
|
|
350
|
+
const hbTimer = setInterval(touchHeartbeat, 5000);
|
|
351
|
+
if (typeof hbTimer.unref === "function") hbTimer.unref();
|
|
352
|
+
ctx.effect(() => () => clearInterval(hbTimer));
|
|
353
|
+
|
|
354
|
+
// 上一次重启留下的「重启中」标志:超过 3 分钟就是死的,清掉
|
|
355
|
+
try {
|
|
356
|
+
if (existsSync(restartFlagFile) && Date.now() - statSync(restartFlagFile).mtimeMs > 180000) unlinkSync(restartFlagFile);
|
|
357
|
+
} catch { /* best effort */ }
|
|
358
|
+
|
|
359
|
+
const watchdogPid = () => {
|
|
360
|
+
try {
|
|
361
|
+
const pid = Number(String(readFileSync(watchdogPidFile, "utf8")).trim());
|
|
362
|
+
if (!pid) return 0;
|
|
363
|
+
process.kill(pid, 0);
|
|
364
|
+
return pid;
|
|
365
|
+
} catch { return 0; }
|
|
366
|
+
};
|
|
367
|
+
// Electron 里 process.execPath 指向 "DeepSeek Harness.exe",拿它跑 .cjs 起不来,
|
|
368
|
+
// 所以按顺序探测真正的 node:配置 > 环境变量 > 运行时目录 > 已知安装路径。
|
|
369
|
+
const resolveNode = () => {
|
|
370
|
+
const configured = String(config?.watchdogNode ?? "").trim();
|
|
371
|
+
const candidates = [
|
|
372
|
+
configured,
|
|
373
|
+
process.env.DSH_NODE || "",
|
|
374
|
+
process.env.DSH_RUNTIME ? process.env.DSH_RUNTIME + "/dependencies/node/bin/node.exe" : "",
|
|
375
|
+
"D:/DSH/resources/runtime/primary-runtime/dependencies/node/bin/node.exe",
|
|
376
|
+
DSH_HOME_DEFAULT + "/dsh-runtimes/dsh-primary-runtime/dependencies/node/bin/node.exe",
|
|
377
|
+
].filter(Boolean);
|
|
378
|
+
for (const candidate of candidates) {
|
|
379
|
+
try { if (existsSync(candidate)) return { path: candidate, electron: false }; } catch { /* next */ }
|
|
380
|
+
}
|
|
381
|
+
// 兜底:让 Electron 以 node 模式运行自己
|
|
382
|
+
return { path: process.execPath, electron: true };
|
|
383
|
+
};
|
|
384
|
+
const startWatchdog = () => {
|
|
385
|
+
if (!existsSync(watchdogScript)) return { ok: false, error: "找不到看门狗脚本 " + watchdogScript };
|
|
386
|
+
writeJsonSafe(watchdogConfigFile, {
|
|
387
|
+
heartbeat: heartbeatFile,
|
|
388
|
+
stopFlag: stopFlagFile,
|
|
389
|
+
restartFlag: restartFlagFile,
|
|
390
|
+
pidFile: watchdogPidFile,
|
|
391
|
+
startScript: resolveScript(SCRIPT_ROOT + "/restart-dsh-start.ps1", [PLUGIN_ROOT + "/scripts/restart-dsh-start.ps1", WS_ROOT + "/scripts/restart-dsh-start.ps1"]),
|
|
392
|
+
logFile: watchdogLog,
|
|
393
|
+
pollMs: watchdogPollMs,
|
|
394
|
+
staleMs: watchdogStaleMs,
|
|
395
|
+
cooldownMs: watchdogCooldownMs,
|
|
396
|
+
});
|
|
397
|
+
try { if (existsSync(stopFlagFile)) unlinkSync(stopFlagFile); } catch { /* best effort */ }
|
|
398
|
+
const node = resolveNode();
|
|
399
|
+
const env = node.electron ? { ...process.env, ELECTRON_RUN_AS_NODE: "1" } : process.env;
|
|
400
|
+
const child = spawn(node.path, [watchdogScript, watchdogConfigFile], { detached: true, stdio: "ignore", windowsHide: true, env });
|
|
401
|
+
child.on("error", (e) => {
|
|
402
|
+
log("[watchdog] spawn error: " + String(e));
|
|
403
|
+
try { appendFileSync(watchdogLog, "[" + new Date().toISOString() + "] spawn error: " + String(e) + "\n", "utf8"); } catch { /* best effort */ }
|
|
404
|
+
});
|
|
405
|
+
child.unref();
|
|
406
|
+
log("[watchdog] started pid=" + child.pid + " via " + node.path + (node.electron ? " (ELECTRON_RUN_AS_NODE)" : ""));
|
|
407
|
+
try {
|
|
408
|
+
appendFileSync(watchdogLog, "[" + new Date().toISOString() + "] spawn requested pid=" + child.pid + " via " + node.path + "\n", "utf8");
|
|
409
|
+
} catch { /* best effort */ }
|
|
410
|
+
return { ok: true, pid: child.pid, node: node.path };
|
|
411
|
+
};
|
|
412
|
+
const stopWatchdog = () => {
|
|
413
|
+
try { writeFileSync(stopFlagFile, new Date().toISOString(), "utf8"); } catch { /* best effort */ }
|
|
414
|
+
const pid = watchdogPid();
|
|
415
|
+
if (pid) { try { process.kill(pid); } catch { /* best effort */ } }
|
|
416
|
+
log("[watchdog] stop requested (pid=" + (pid || "none") + ")");
|
|
417
|
+
return pid;
|
|
418
|
+
};
|
|
419
|
+
if (watchdogEnabled && !watchdogPid()) {
|
|
420
|
+
const started = startWatchdog();
|
|
421
|
+
log("[boot] watchdog " + (started.ok ? "spawned pid=" + started.pid : "failed: " + started.error));
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// ---------- restart_dsh ----------
|
|
425
|
+
try {
|
|
426
|
+
ctx.tools.register(defineTool({
|
|
427
|
+
name: "restart_dsh",
|
|
428
|
+
description:
|
|
429
|
+
"Restart DeepSeek Harness safely. Arms a scheduled kill + start pair: DSH is killed after " +
|
|
430
|
+
"delay_seconds (20-600, default 45) and started again ~11s later if it is still down. The whole " +
|
|
431
|
+
"app — including this conversation — goes down and comes back in 60-90 seconds; the next session " +
|
|
432
|
+
"can continue. Optional start_script replaces the start half (e.g. run pnpm install before the " +
|
|
433
|
+
"app comes back); optional watch_seconds adds a third watchdog task. " +
|
|
434
|
+
"Requires confirm:true. Never call this unless the user explicitly asked to restart DSH.",
|
|
435
|
+
parameters: {
|
|
436
|
+
confirm: { type: "boolean", required: true, description: "Must be true. A restart kills the whole app." },
|
|
437
|
+
delay_seconds: { type: "integer", description: "Seconds until DSH is killed (20-600, default 45)." },
|
|
438
|
+
start_script: {
|
|
439
|
+
type: "string",
|
|
440
|
+
description:
|
|
441
|
+
"Optional absolute path of a .cmd/.ps1 used as the start half. It runs after the kill in its " +
|
|
442
|
+
"own scheduled task and must bring DSH back (call restart-dsh-start.ps1 at the end).",
|
|
443
|
+
},
|
|
444
|
+
watch_seconds: {
|
|
445
|
+
type: "integer",
|
|
446
|
+
description: "Optional watchdog delay (0/omitted = off). Starts DSH if it is still down then.",
|
|
447
|
+
},
|
|
448
|
+
reason: { type: "string", description: "Optional one-line reason, echoed in the result." },
|
|
449
|
+
announce_channel: {
|
|
450
|
+
type: "string",
|
|
451
|
+
description:
|
|
452
|
+
"Which IM channel should receive the post-restart greeting: weixin | qq. Pass the channel this conversation lives on; omit = auto pick.",
|
|
453
|
+
},
|
|
454
|
+
},
|
|
455
|
+
output: toolOutput(),
|
|
456
|
+
async execute(args) {
|
|
457
|
+
// The host validates tool results against output.schema: a bare string
|
|
458
|
+
// is rejected as `"value" must be an object`. Always return { ok, text }.
|
|
459
|
+
if (args?.confirm !== true) {
|
|
460
|
+
return { ok: false, text: "重启没有排上 ❌\n原因:缺少 confirm:true\n提示:重启会杀掉整个 DSH 并打断本对话;先向用户确认,再带 confirm:true 调用。" };
|
|
461
|
+
}
|
|
462
|
+
const timings = resolveTimings(args?.delay_seconds, { defaultKillSeconds });
|
|
463
|
+
const startScript = String(args?.start_script ?? "").trim();
|
|
464
|
+
const extended = needsExtendedScript({ startScript, watchSeconds: args?.watch_seconds });
|
|
465
|
+
const watchSeconds = extended
|
|
466
|
+
? normalizeWatchSeconds(args?.watch_seconds, { startSeconds: timings.startSeconds })
|
|
467
|
+
: 0;
|
|
468
|
+
const script = extended ? maintArmScript : armScript;
|
|
469
|
+
|
|
470
|
+
if (!existsSync(script)) {
|
|
471
|
+
return { ok: false, text: "重启没有排上 ❌\n原因:找不到重启脚本 " + script + "\n提示:检查 armScript / maintArmScript 配置。" };
|
|
472
|
+
}
|
|
473
|
+
if (startScript && !existsSync(startScript)) {
|
|
474
|
+
return { ok: false, text: "重启没有排上 ❌\n原因:找不到启动半段脚本 " + startScript };
|
|
475
|
+
}
|
|
476
|
+
if (!existsSync(dirname(logFile))) {
|
|
477
|
+
return { ok: false, text: "重启没有排上 ❌\n原因:找不到日志目录 " + dirname(logFile) };
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const result = await runProcess(powershell,
|
|
481
|
+
buildArmArgs({ script, killSeconds: timings.killSeconds, startSeconds: timings.startSeconds, startScript, watchSeconds }),
|
|
482
|
+
20000);
|
|
483
|
+
|
|
484
|
+
if (result.code !== 0) {
|
|
485
|
+
return { ok: false, text: "重启没有排上 ❌\n原因:arm 脚本失败(exit " + result.code + ")\n输出:\n" + tailLines(result.output, 8) };
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
if (announce) {
|
|
489
|
+
const marked = writeMarker(announceFile, announceText, new Date(), String(args?.announce_channel ?? ""));
|
|
490
|
+
if (!marked.ok) log("[announce] marker write failed: " + marked.error);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
writeJsonSafe(armRecordFile, {
|
|
494
|
+
pid: me.pid,
|
|
495
|
+
startedAt: me.startedAt,
|
|
496
|
+
armedAt: new Date().toISOString(),
|
|
497
|
+
delaySeconds: timings.killSeconds,
|
|
498
|
+
startSeconds: timings.startSeconds,
|
|
499
|
+
startScript,
|
|
500
|
+
watchSeconds,
|
|
501
|
+
reason: String(args?.reason ?? ""),
|
|
502
|
+
source: "tool",
|
|
503
|
+
});
|
|
504
|
+
writeJsonSafe(restartFlagFile, { at: new Date().toISOString(), by: "tool", pid: me.pid, delaySeconds: timings.killSeconds });
|
|
505
|
+
const backup = backupProfile();
|
|
506
|
+
writeJsonSafe(killRecordFile, { killAt: Date.now() + timings.killSeconds * 1000, armedAt: Date.now(), by: "tool" });
|
|
507
|
+
|
|
508
|
+
let logTail = "";
|
|
509
|
+
try { logTail = tailLines(await readFile(logFile, "utf8"), 6); } catch { /* best effort */ }
|
|
510
|
+
|
|
511
|
+
return {
|
|
512
|
+
ok: true,
|
|
513
|
+
text: [
|
|
514
|
+
"重启已排程 ✅",
|
|
515
|
+
"计划:" + describeTimings(timings),
|
|
516
|
+
startScript ? "启动半段:" + startScript : "",
|
|
517
|
+
watchSeconds > 0 ? "看门狗:+" + watchSeconds + "s 后补拉" : "",
|
|
518
|
+
"原因:" + (String(args?.reason ?? "").trim() || "(未填)"),
|
|
519
|
+
announce ? "回来后会发一句:「" + announceText + "」" : "",
|
|
520
|
+
logTail ? "日志:" + logTail : "",
|
|
521
|
+
"本对话会中断,重启后新会话可继续。",
|
|
522
|
+
].filter(Boolean).join("\n"),
|
|
523
|
+
};
|
|
524
|
+
},
|
|
525
|
+
}));
|
|
526
|
+
} catch (error) {
|
|
527
|
+
log("[boot] register restart_dsh failed: " + String(error?.message ?? error));
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// ---------- restart_watchdog ----------
|
|
531
|
+
try {
|
|
532
|
+
ctx.tools.register(defineTool({
|
|
533
|
+
name: "restart_watchdog",
|
|
534
|
+
description:
|
|
535
|
+
"常驻看门狗:盯心跳文件,DSH 心跳超过阈值没更新就用 vetted 的 start 脚本把 DSH 拉起来。" +
|
|
536
|
+
"action = status / start / stop。",
|
|
537
|
+
parameters: { action: { type: "string", required: true, description: "status | start | stop" } },
|
|
538
|
+
output: toolOutput(),
|
|
539
|
+
async execute(args) {
|
|
540
|
+
const action = String(args?.action ?? "status").trim().toLowerCase();
|
|
541
|
+
if (action === "stop") {
|
|
542
|
+
const pid = stopWatchdog();
|
|
543
|
+
return { ok: true, text: "已请求停止看门狗" + (pid ? "(pid=" + pid + ")" : "(原本没在跑)") };
|
|
544
|
+
}
|
|
545
|
+
if (action === "start") {
|
|
546
|
+
const running = watchdogPid();
|
|
547
|
+
if (running) return { ok: true, text: "看门狗已在运行,pid=" + running };
|
|
548
|
+
const started = startWatchdog();
|
|
549
|
+
return started.ok
|
|
550
|
+
? { ok: true, text: "看门狗已启动,pid=" + started.pid + "\n脚本:" + watchdogScript }
|
|
551
|
+
: { ok: false, text: "启动失败 ❌\n原因:" + started.error };
|
|
552
|
+
}
|
|
553
|
+
const pid = watchdogPid();
|
|
554
|
+
let hb = "无";
|
|
555
|
+
try { hb = Math.round((Date.now() - statSync(heartbeatFile).mtimeMs) / 1000) + "s 前"; } catch { /* best effort */ }
|
|
556
|
+
return {
|
|
557
|
+
ok: true,
|
|
558
|
+
text: [
|
|
559
|
+
"看门狗:" + (pid ? "运行中 pid=" + pid : "未运行"),
|
|
560
|
+
"配置开关:watchdogEnabled=" + watchdogEnabled,
|
|
561
|
+
"心跳:" + hb,
|
|
562
|
+
"阈值:stale=" + watchdogStaleMs + "ms / poll=" + watchdogPollMs + "ms / cooldown=" + watchdogCooldownMs + "ms",
|
|
563
|
+
"脚本:" + watchdogScript,
|
|
564
|
+
"日志:" + watchdogLog,
|
|
565
|
+
].join("\n"),
|
|
566
|
+
};
|
|
567
|
+
},
|
|
568
|
+
}));
|
|
569
|
+
} catch (error) {
|
|
570
|
+
log("[boot] register restart_watchdog failed: " + String(error?.message ?? error));
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// ---------- restart_status ----------
|
|
574
|
+
try {
|
|
575
|
+
ctx.tools.register(defineTool({
|
|
576
|
+
name: "restart_status",
|
|
577
|
+
description:
|
|
578
|
+
"Show the restart-related scheduled tasks (DSH-Restart-*) and the tail of the restart log. " +
|
|
579
|
+
"Use it to check whether a restart was really armed or why the last one failed.",
|
|
580
|
+
parameters: {},
|
|
581
|
+
output: toolOutput(),
|
|
582
|
+
async execute() {
|
|
583
|
+
if (!existsSync(tasksScript)) return { ok: false, text: "查询失败 ❌\n原因:找不到任务查询脚本 " + tasksScript };
|
|
584
|
+
const result = await runProcess(powershell, ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", tasksScript, "-Action", "status"], 15000);
|
|
585
|
+
if (result.code !== 0) return { ok: false, text: "查询失败 ❌\n原因:查询脚本失败(exit " + result.code + ")\n" + tailLines(result.output, 6) };
|
|
586
|
+
let logTail = "";
|
|
587
|
+
try { logTail = tailLines(await readFile(logFile, "utf8"), 12); } catch { /* best effort */ }
|
|
588
|
+
const rows = parseTaskStatus(result.output).map(
|
|
589
|
+
(t) => "- " + t.name + ":" + (t.state || "未注册") + (t.next ? "(下次 " + t.next + ")" : ""),
|
|
590
|
+
);
|
|
591
|
+
const armed = readJsonSafe(armRecordFile);
|
|
592
|
+
const identity = ["当前进程:pid=" + me.pid + ",startedAt=" + me.startedAt];
|
|
593
|
+
if (downtimeSeconds !== null) identity.push("上次停机:约 " + downtimeSeconds + " 秒");
|
|
594
|
+
if (backupEnabled) {
|
|
595
|
+
try {
|
|
596
|
+
const dirs = readdirSync(backupRoot, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort();
|
|
597
|
+
identity.push("重启前备份:" + dirs.length + " 份" + (dirs.length ? ",最新 " + dirs[dirs.length - 1] : "(还没有)") + " → " + backupRoot);
|
|
598
|
+
} catch {
|
|
599
|
+
identity.push("重启前备份:目录还没建 → " + backupRoot);
|
|
600
|
+
}
|
|
601
|
+
} else {
|
|
602
|
+
identity.push("重启前备份:已关闭");
|
|
603
|
+
}
|
|
604
|
+
if (armed && armed.pid) {
|
|
605
|
+
const same = Number(armed.pid) === Number(me.pid) && String(armed.startedAt) === String(me.startedAt);
|
|
606
|
+
identity.push("上次排程时的进程:pid=" + armed.pid + ",startedAt=" + armed.startedAt);
|
|
607
|
+
identity.push(same ? "判定:仍是同一进程(重启可能没发生 / 或还没到点)" : "判定:进程已更替 ✅(重启确实发生过)");
|
|
608
|
+
} else {
|
|
609
|
+
identity.push("上次排程记录:无");
|
|
610
|
+
}
|
|
611
|
+
return { ok: true, text: [...identity, "", "重启任务:", ...(rows.length ? rows : ["- (无)"]), "", "日志尾部:", logTail || "(空)"].join("\n") };
|
|
612
|
+
},
|
|
613
|
+
}));
|
|
614
|
+
} catch (error) {
|
|
615
|
+
log("[boot] register restart_status failed: " + String(error?.message ?? error));
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// ---------- restart_announce_test ----------
|
|
619
|
+
try {
|
|
620
|
+
ctx.tools.register(defineTool({
|
|
621
|
+
name: "restart_announce_test",
|
|
622
|
+
description:
|
|
623
|
+
"Send the post-restart greeting right now, without restarting. Verifies that IM proactive " +
|
|
624
|
+
"delivery actually works and reports which bot/target was used, or the exact reason it failed.",
|
|
625
|
+
parameters: { channel: { type: "string", description: "Which IM channel to greet: weixin | qq (omit = auto)." } },
|
|
626
|
+
output: toolOutput(),
|
|
627
|
+
async execute(args) {
|
|
628
|
+
const im = await waitForIm(ctx, 8000);
|
|
629
|
+
if (!im) return { ok: false, text: "发送失败 ❌\n原因:IM 服务不可用(等了 8 秒)" };
|
|
630
|
+
const route = await waitForRoute(im, { botId: config?.announceBotId, targetId: config?.announceTargetId, channel: String(args?.channel ?? "") }, 6000);
|
|
631
|
+
if (!route.targetId) {
|
|
632
|
+
return {
|
|
633
|
+
ok: false,
|
|
634
|
+
text: "发送失败 ❌\n原因:" + route.error +
|
|
635
|
+
"\n修法:设置 → IM机器人 → 对应机器人卡片 → 新建目标 → 「从已聊会话选择」→ 测试 → 保存。",
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
try {
|
|
639
|
+
await im.send(route.botId, route.targetId, announceText);
|
|
640
|
+
log("[announce] test sent via " + route.botId + "/" + route.targetId);
|
|
641
|
+
let botsInfo = "";
|
|
642
|
+
try { const bs = typeof im.listBots === "function" ? await im.listBots() : []; botsInfo = "\n可用机器人:" + (Array.isArray(bs) ? bs.map((b) => String(b?.botId) + "(" + String(b?.channel) + ")").join(" ") : "?"); } catch { botsInfo = "\n可用机器人:读不到"; }
|
|
643
|
+
return { ok: true, text: "已发送 ✅\n机器人:" + route.botId + "\n目标:" + route.targetId + "\n内容:" + announceText + botsInfo };
|
|
644
|
+
} catch (error) {
|
|
645
|
+
return { ok: false, text: "发送失败 ❌\n原因:" + String(error?.message ?? error) };
|
|
646
|
+
}
|
|
647
|
+
},
|
|
648
|
+
}));
|
|
649
|
+
} catch (error) {
|
|
650
|
+
log("[boot] register restart_announce_test failed: " + String(error?.message ?? error));
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// ---------- restart_cancel ----------
|
|
654
|
+
try {
|
|
655
|
+
ctx.tools.register(defineTool({
|
|
656
|
+
name: "restart_cancel",
|
|
657
|
+
description:
|
|
658
|
+
"Cancel an armed restart: unregister every DSH-Restart-* scheduled task. Only useful before the " +
|
|
659
|
+
"kill task fires.",
|
|
660
|
+
parameters: {},
|
|
661
|
+
output: toolOutput(),
|
|
662
|
+
async execute() {
|
|
663
|
+
if (!existsSync(tasksScript)) return { ok: false, text: "取消失败 ❌\n原因:找不到任务查询脚本 " + tasksScript };
|
|
664
|
+
const result = await runProcess(powershell, ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", tasksScript, "-Action", "cancel"], 15000);
|
|
665
|
+
if (result.code !== 0) return { ok: false, text: "取消失败 ❌\n原因:取消脚本失败(exit " + result.code + ")\n" + tailLines(result.output, 6) };
|
|
666
|
+
return { ok: true, text: "已取消重启任务:\n" + (tailLines(result.output, 10) || "(没有可取消的任务)") };
|
|
667
|
+
},
|
|
668
|
+
}));
|
|
669
|
+
} catch (error) {
|
|
670
|
+
log("[boot] register restart_cancel failed: " + String(error?.message ?? error));
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// ---------- /restart 斜杠命令(人敲,确定性执行,不花推理 token)----------
|
|
674
|
+
// 设计借鉴 anweat/dsh-restart 的 /restart 命令(MIT):命令行只做排程,不改配置。
|
|
675
|
+
try {
|
|
676
|
+
const commands = ctx.commands;
|
|
677
|
+
if (commands && typeof commands.register === "function") {
|
|
678
|
+
commands.register({
|
|
679
|
+
definitionId: "dsh-restart",
|
|
680
|
+
name: "restart",
|
|
681
|
+
description: "重启 DSH(默认 45 秒后杀进程、约 11 秒后拉起)",
|
|
682
|
+
input: { hint: "[秒数 20-600] [--watch 看门狗秒数]" },
|
|
683
|
+
handler: async (invocation) => {
|
|
684
|
+
const raw = String(invocation?.rawInput ?? "").trim();
|
|
685
|
+
const parts = raw.split(/\s+/).filter(Boolean);
|
|
686
|
+
let delay = defaultKillSeconds;
|
|
687
|
+
let watch = 0;
|
|
688
|
+
for (let i = 0; i < parts.length; i++) {
|
|
689
|
+
const p = parts[i];
|
|
690
|
+
if (p === "--watch") { watch = Number(parts[++i] ?? 0); continue; }
|
|
691
|
+
const n = Number(p);
|
|
692
|
+
if (Number.isFinite(n) && n > 0) delay = n;
|
|
693
|
+
}
|
|
694
|
+
const timings = resolveTimings(delay, { defaultKillSeconds });
|
|
695
|
+
const watchSeconds = watch > 0
|
|
696
|
+
? normalizeWatchSeconds(watch, { startSeconds: timings.startSeconds })
|
|
697
|
+
: 0;
|
|
698
|
+
const script = watchSeconds > 0 ? maintArmScript : armScript;
|
|
699
|
+
if (!existsSync(script)) {
|
|
700
|
+
return { kind: "error", text: "重启没有排上 ❌ 找不到重启脚本 " + script };
|
|
701
|
+
}
|
|
702
|
+
const result = await runProcess(
|
|
703
|
+
powershell,
|
|
704
|
+
buildArmArgs({ script, killSeconds: timings.killSeconds, startSeconds: timings.startSeconds, startScript: "", watchSeconds }),
|
|
705
|
+
20000,
|
|
706
|
+
);
|
|
707
|
+
if (result.code !== 0) {
|
|
708
|
+
return { kind: "error", text: "重启没有排上 ❌ arm 脚本失败(exit " + result.code + ")\n" + tailLines(result.output, 6) };
|
|
709
|
+
}
|
|
710
|
+
if (announce) writeMarker(announceFile, announceText);
|
|
711
|
+
writeJsonSafe(armRecordFile, {
|
|
712
|
+
pid: me.pid,
|
|
713
|
+
startedAt: me.startedAt,
|
|
714
|
+
armedAt: new Date().toISOString(),
|
|
715
|
+
delaySeconds: timings.killSeconds,
|
|
716
|
+
startSeconds: timings.startSeconds,
|
|
717
|
+
startScript: "",
|
|
718
|
+
watchSeconds,
|
|
719
|
+
reason: "/restart",
|
|
720
|
+
source: "command",
|
|
721
|
+
});
|
|
722
|
+
writeJsonSafe(restartFlagFile, { at: new Date().toISOString(), by: "command", pid: me.pid, delaySeconds: timings.killSeconds });
|
|
723
|
+
backupProfile();
|
|
724
|
+
writeJsonSafe(killRecordFile, { killAt: Date.now() + timings.killSeconds * 1000, armedAt: Date.now(), by: "command" });
|
|
725
|
+
log("[/restart] armed by command: " + describeTimings(timings));
|
|
726
|
+
return {
|
|
727
|
+
kind: "success",
|
|
728
|
+
text: "重启已排程 ✅\n计划:" + describeTimings(timings) +
|
|
729
|
+
(watchSeconds > 0 ? "\n看门狗:+" + watchSeconds + "s 后补拉" : "") +
|
|
730
|
+
"\n约 60-90 秒后回来;本对话会中断。",
|
|
731
|
+
};
|
|
732
|
+
},
|
|
733
|
+
});
|
|
734
|
+
log("[boot] /restart command registered");
|
|
735
|
+
} else {
|
|
736
|
+
log("[boot] /restart skipped: commands service unavailable");
|
|
737
|
+
}
|
|
738
|
+
} catch (error) {
|
|
739
|
+
log("[boot] register /restart failed: " + String(error?.message ?? error));
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
// ---------- boot hook: "我回来啦" ----------
|
|
743
|
+
if (announce) {
|
|
744
|
+
const timer = setTimeout(() => {
|
|
745
|
+
void announceIfPending(ctx, {
|
|
746
|
+
file: announceFile,
|
|
747
|
+
maxAgeMinutes: announceMaxAgeMinutes,
|
|
748
|
+
botId: config?.announceBotId,
|
|
749
|
+
targetId: config?.announceTargetId,
|
|
750
|
+
autoTarget: config?.announceAutoTarget !== false,
|
|
751
|
+
log,
|
|
752
|
+
}).catch((error) => log("[announce] unexpected failure: " + String(error?.message ?? error)));
|
|
753
|
+
}, 3000);
|
|
754
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
755
|
+
}
|
|
756
|
+
}
|