@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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pkkkkh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,193 @@
1
- # Temporary Holding Version
1
+ # dsh-restart
2
+
3
+ 让 agent 能从 IM / Web 会话里**安全地把整个 DSH 重启**,并在重启成功后自动说一句「我回来啦」。
4
+
5
+ ## 为什么做成插件
6
+
7
+ 重启是桌面端的事(杀进程 + 拉起),但人在微信 / Web 里时,agent 没有「点那个按钮」的能力。
8
+ 本插件给模型四个工具,把这件事变得可验证、可撤销、可播报。
9
+
10
+ ## 四个工具
11
+
12
+ | 工具 | 参数 | 作用 |
13
+ | --- | --- | --- |
14
+ | `restart_dsh` | `confirm`(必填 true)、`delay_seconds`、`start_script`、`watch_seconds`、`reason` | 排一次重启:先杀后起,可选维护半段和看门狗 |
15
+ | `restart_status` | 无 | 查 `DSH-Restart-*` 任务状态 + 日志尾部 |
16
+ | `restart_cancel` | 无 | 撤销还没触发的重启任务 |
17
+ | `restart_announce_test` | 无 | 立刻发一次问候,**不重启**,用来验证 IM 投递是否通 |
18
+
19
+ 工具返回值统一是对象 `{ ok, text }`(宿主会按 `output.schema` 校验,返回字符串会报
20
+ `"value" must be an object`)。
21
+
22
+ ## 0.2.0 新增(2026-11-16)
23
+
24
+ - **进程身份双因子**:插件启动时把 `{pid, startedAt}` 写进 `logs/dsh-process.json`,每次排程写 `logs/dsh-arm-record.json`;`restart_status` 会对比两者并给出「仍是同一进程 / 进程已更替 ✅」的判定(只看 pid 会被系统复用骗)。
25
+ - **`/restart` 斜杠命令**:`/restart [秒数] [--watch 120]`,人敲即可排程,不花推理 token;走的还是同一套 vetted 脚本(先注册 start、再注册 kill,带回滚)。
26
+ - 设计参考 [anweat/dsh-restart](https://github.com/anweat/dsh-restart)(MIT):「pid + startedAt 双因子」与「/restart 命令」的思路来自它;**重启机制仍是我们自己的 PowerShell 计划任务链**(它是 Node 原生 relaunch)。
27
+ - 下一版计划:**client 半端**(设置卡片 + 重启后自动刷新页面)。需要单独的 client bundle(`dsh.client` + 构建产物),不能只改 host 半。
28
+
29
+ ## 0.2.1 新增:常驻看门狗(2026-11-16)
30
+
31
+ - 插件每 **5 秒**写一次心跳 `logs/dsh-heartbeat.json`。
32
+ - `scripts/dsh-watchdog.cjs` 常驻监督:心跳超过 `watchdogStaleMs`(默认 15s)没更新,且没有 `dsh-restarting.flag`(重启中)时,用 vetted 的 `restart-dsh-start.ps1` 把 DSH 拉起来;`watchdogCooldownMs`(默认 60s)内不重复拉,避免重启风暴。
33
+ - 启停:`restart_watchdog(action:"status"|"start"|"stop")`;强制停也可以建 `logs/dsh-stop.flag`。
34
+ - 默认开关在 `cordis.patch.yml` 里(`watchdogEnabled: true`);配置改了要重启才生效。
35
+ - 设计参考 [anweat/dsh-restart](https://github.com/anweat/dsh-restart)(MIT)的看门狗思路;实现是「心跳文件 + vetted start 脚本」,不重写启动逻辑。
36
+
37
+ ## 一次重启会发生什么
38
+
39
+ ```
40
+ T+0 restart_dsh 被调用
41
+ → 校验脚本 / 日志目录 / start_script
42
+ → 写 marker(问候语 + 时间戳,30 分钟有效)
43
+ T+45 计划任务 Kill 触发:restart-dsh-kill.cmd(只做 taskkill)
44
+ T+56 计划任务 Start 触发:restart-dsh-fallback.cmd
45
+ 没在跑就 restart-dsh-start.ps1(explorer 启动 + 20 秒复查,失败重试一次)
46
+ T+56+ DSH 起来 → 插件 apply() → 3 秒后读 marker
47
+ 轮询等 IM 服务(最多 25 秒)、遍历所有机器人找投递目标(最多 20 秒)
48
+ → dshIm.send(botId, targetId, "咕噜~本鱼回来啦…")
49
+ ```
50
+
51
+ **先删 marker 再发**:崩溃循环不会刷屏;marker 过期(默认 30 分钟)自动丢弃;非计划启动没有 marker,不会打扰。
52
+
53
+ ## 维护重启(先跑 pnpm 再拉起)
54
+
55
+ ```
56
+ restart_dsh({
57
+ confirm: true,
58
+ delay_seconds: 120,
59
+ start_script: "<IM 工作区>/scripts/restart-dsh-maint-start.cmd",
60
+ watch_seconds: 600,
61
+ reason: "装了新插件"
62
+ })
63
+ ```
64
+
65
+ (本机的 `<IM 工作区>` 是 `C:\Users\YOURNAME\.dsh\im`。)
66
+
67
+ `restart-dsh-maint-start.cmd` 做四件事:
68
+ `pnpm install` → 验 `@dsh-ops` 还在(不在就从 C 旧 profile robocopy)→ 写问候 marker → 拉起 DSH。
69
+
70
+ > 安全阀:如果 DSH 还在跑,**跳过 pnpm**——运行中的 pnpm 曾把 `@dsh-ops` 删掉(2026-11-09 14:08)。
71
+
72
+ ## 它不重新实现调度
73
+
74
+ 杀/起仍然走工作区里那套踩过坑的脚本:
75
+
76
+ | 脚本 | 作用 |
77
+ | --- | --- |
78
+ | `restart-dsh-arm.ps1` | 先注册 Start、再注册 Kill,失败自动回滚(默认路径) |
79
+ | `restart-dsh-arm2.ps1` | 严格超集:多 `-StartScript` / `-WatchAfterSeconds`,回滚逻辑相同 |
80
+ | `restart-dsh-kill.cmd` | 只 taskkill(火绒会在 kill 后连带杀掉本进程,所以「杀」和「起」必须拆开) |
81
+ | `restart-dsh-fallback.cmd` | 没在跑就拉起,失败重试一次 |
82
+ | `restart-dsh-start.ps1` | explorer 启动 + 20 秒存活确认 |
83
+ | `restart-dsh-watchdog.cmd` | 第三任务:还在 down 就补拉,然后清任务 |
84
+ | `dsh-restart-tasks.ps1` | status / cancel 的实现 |
85
+ | `write-announce-marker.ps1` | 供脚本侧写 marker(问候文本在 `logs/announce-text.txt`) |
86
+
87
+ ## 配置(`cordis.patch.yml`)
88
+
89
+ | 键 | 默认 | 说明 |
90
+ | --- | --- | --- |
91
+ | `armScript` | `scripts/restart-dsh-arm.ps1` | 默认排程脚本 |
92
+ | `maintArmScript` | `scripts/restart-dsh-arm2.ps1` | 带 `start_script`/`watch_seconds` 时用 |
93
+ | `tasksScript` | `scripts/dsh-restart-tasks.ps1` | status / cancel 实现 |
94
+ | `logFile` | `logs/restart-dsh.log` | 插件与脚本共用的日志 |
95
+ | `powershell` | `powershell.exe` | 调用器 |
96
+ | `defaultKillSeconds` | 45 | 默认延迟,夹在 20–600 |
97
+ | `announce` | true | 是否播报 |
98
+ | `announceText` | 咕噜~本鱼回来啦… | 问候语(脚本侧读 `announce-text.txt`) |
99
+ | `announceMaxAgeMinutes` | 30 | marker 有效期 |
100
+ | `announceFile` | `logs/restart-announce.json` | marker 路径 |
101
+ | `announceBotId` / `announceTargetId` | 空 | 留空 = 自动挑第一个有目标的机器人 |
102
+
103
+ > 路径约定:表里的 `scripts/` 与 `logs/` 都相对于 **IM 工作区**(本机 `C:\Users\YOURNAME\.dsh\im`)。
104
+ > 换机器/换目录时改 `cordis.patch.yml` 里的 `armScript` / `maintArmScript` / `tasksScript` / `logFile` / `announceFile`,
105
+ > 脚本里的绝对路径也要跟着改(脚本按 ASCII + 绝对路径写死,是为了避免工作目录漂移)。
106
+
107
+ ## 日志
108
+
109
+ | 文件 | 内容 |
110
+ | --- | --- |
111
+ | `logs/restart-dsh.log` | 插件 `[boot]` / `[announce]` + 脚本的排程/杀/起记录 |
112
+ | `logs/restart-maint.log` | 维护半段(pnpm / robocopy / 启动) |
113
+ | `logs/restart-import.log` | 模块被 import 一次写一行,排查「插件到底加载没加载」 |
114
+ | `logs/announce-text.txt` | 问候语文本(UTF-8,改完不用动代码) |
115
+
116
+ ## 安全边界
117
+
118
+ - **只在 Windows 有效**(Task Scheduler + `powershell.exe`)。
119
+ - 必须 `confirm: true`;工具描述写死「除非用户明确要求,否则不要调用」。
120
+ - `delay_seconds` 下限 20 秒,留出返回结果的窗口。
121
+ - 不会删用户数据;排程失败会回滚已注册的任务。
122
+ - 问候只走 IM 主动投递;**Web GUI 没有推送通道**,没人说话时不会自己冒出一句。
123
+
124
+ ## 测试
125
+
126
+ ```powershell
127
+ cd dsh-restart
128
+ node --test test/args.test.mjs test/announce.test.mjs test/timings.test.mjs
129
+ ```
130
+
131
+ 覆盖:默认值/边界夹紧、arm 参数拼装、任务状态解析、marker 读写与过期、投递目标解析(多机器人扫描、失败跳过)。
132
+
133
+ 真实宿主模块下的冒烟(用 app.asar 里的 `defineTool`):
134
+
135
+ ```powershell
136
+ ELECTRON_RUN_AS_NODE=1 "<DSH 安装目录>/DeepSeek Harness.exe" --expose-internals run.mjs
137
+ ```
138
+
139
+ ## 安装(需要停 DSH 再 pnpm)
140
+
141
+ ```
142
+ # 1. 把本目录放到 <插件安装目录>(建议 junction 到仓库,改源码即生效)
143
+ profiles/<profile>/node_modules/dsh-restart → <仓库目录>/dsh-restart
144
+
145
+ # 2. profiles/<profile>/package.json
146
+ dependencies 加 "dsh-restart": "link:<仓库目录>/dsh-restart"
147
+ dsh.profile.bundles 加 "dsh-restart"
148
+
149
+ # 3. 重启 DSH
150
+ ```
151
+
152
+ **`peerDependencies` 必须声明** `@deepseek-ai/cordis`、`dsh-tools`、`schemastery`,否则 link 安装的插件
153
+ 拿不到宿主包,会以 `ERR_MODULE_NOT_FOUND` 被静默跳过(桌面端看不到这个错误,只有 `dsh --profile <临时> --no-open` 才看得到)。
154
+
155
+ ## 已知限制
156
+
157
+ - 播报需要 IM 投递目标(设置 → IM机器人 → 新建目标),服务没有「自动建目标」的 API。
158
+ - 只能按「从现在起 N 秒」排程;按绝对时间排要用 `scripts/arm-maint-at.ps1`。
159
+
160
+ ## 0.2.2 / 0.2.3 修复(2026-11-16,均已实测)
161
+
162
+ 看门狗第一版有三个 bug,全在「拉不起来」上,写在这里免得以后重踩:
163
+
164
+ | bug | 现象 | 修法 |
165
+ | --- | --- | --- |
166
+ | **Electron 的 process.execPath 指向 DeepSeek Harness.exe** | spawn .cjs 起不来(等于再开一个 Electron) | resolveNode() 按序探测:配置 watchdogNode → DSH_NODE → DSH_RUNTIME → 两个已知路径 → 兜底 ELECTRON_RUN_AS_NODE=1 |
167
+ | **配置路径对不上** | 脚本只读 __dirname/dsh-watchdog.json,插件却写在 logs/ | 脚本改读 process.argv[2];插件 spawn 时把配置路径传进去 |
168
+ | **timer.unref()** | 唯一的定时器被解引用 → 进程「起完就退」,日志里有 watchdog up 但 pid 立刻失效 | 删掉 unref,定时器必须保活 |
169
+
170
+ **0.2.3 还查清了一个长期异常**:插件启动时写 restart-dsh.log 一律报
171
+ EBUSY: resource busy or locked —— 是**启动脚本那一侧独占了该文件**(writeFileSync 写心跳/进程文件不受影响,所以只有日志缺)。
172
+ 于是插件日志改写到独立的 logs/restart-plugin.log(配置项 pluginLogFile),restart-dsh.log 留给脚本;append 失败仍会落 .fallback 留证据。
173
+
174
+ 实测结果(2026-11-16 18:40 重启):
175
+
176
+ - [watchdog] started pid=3048 via D:/DSH/resources/runtime/primary-runtime/dependencies/node/bin/node.exe
177
+ - [boot] /restart command registered
178
+ - restart_status:当前进程 pid=10688 vs 上次排程 pid=26456 → 判定:进程已更替 ✅
179
+ - 心跳每 5 秒刷新;重启播报正常发出
180
+
181
+ ## 0.2.4 新增(2026-11-16,低风险增强)
182
+
183
+ - **重启前自动备份 profile**:排程时把 `package.json` / `pnpm-lock.yaml` / `cordis.patch.yml`
184
+ 复制到 `logs/restart-backups/<时间戳>/`,保留最近 `backupKeep`(默认 10)份、自动清旧的。
185
+ 配置:`backupEnabled`(默认 true)、`backupDir`、`backupKeep`、`profileDir`。
186
+ 备份失败**不阻塞重启**(只记日志)。
187
+ - **停机时长**:排程时记下预计 kill 时刻到 `logs/dsh-kill-record.json`,启动后算差,
188
+ `restart_status` 显示「上次停机:约 N 秒」。
189
+ - `restart_status` 同时显示「重启前备份:N 份,最新 <时间戳>」。
190
+
191
+ 为什么要备份:2026-11-16 一次 `pnpm add` 把三条 `link:` 软链重建到不存在的路径,
192
+ 三个插件静默失效——有备份就能秒回滚。
2
193
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
@@ -0,0 +1,40 @@
1
+ # dsh-restart — bundle patch.
2
+ # This row is what gets inserted into the profile tree. Override any field in
3
+ # profiles/desktop/cordis.patch.yml (later layers win).
4
+ - insert:
5
+ - id: dsh-restart
6
+ name: 'dsh-restart'
7
+ config:
8
+ # The vetted restart scripts live in the IM workspace (ASCII only,
9
+ # start-task-first ordering, rollback on partial registration).
10
+ armScript: 'C:/Users/YOURNAME/.dsh/im/scripts/restart-dsh-arm.ps1'
11
+ # Strict superset used only when a caller passes start_script and/or
12
+ # watch_seconds (maintenance runs: pnpm install inside the start half).
13
+ maintArmScript: 'C:/Users/YOURNAME/.dsh/im/scripts/restart-dsh-arm2.ps1'
14
+ # Status / cancel helper for the DSH-Restart-* tasks.
15
+ tasksScript: 'C:/Users/YOURNAME/.dsh/im/scripts/dsh-restart-tasks.ps1'
16
+ logFile: 'C:/Users/YOURNAME/.dsh/im/logs/restart-dsh.log'
17
+ powershell: 'powershell.exe'
18
+ # Default delay before DSH is killed; the start task fires 11s later.
19
+ defaultKillSeconds: 45
20
+ # ── 「我回来啦」播报 ──────────────────────────────────────────────
21
+ # 计划重启时写一个 marker;下次 DSH 起来后插件读 marker,用 IM 主动投递
22
+ # 发一句问候,然后删 marker。非计划启动(没有 marker)不会说话。
23
+ announce: true
24
+ announceText: '咕噜~本鱼回来啦,尾巴甩甩,满血复活!'
25
+ announceMaxAgeMinutes: 30
26
+ announceFile: 'C:/Users/YOURNAME/.dsh/im/logs/restart-announce.json'
27
+ # 留空 = 自动挑第一个在线机器人 / 它的第一个投递目标;
28
+ # 一个目标都没有时,自动把「最近聊过的会话」提升成 restart-hello 目标。
29
+ announceBotId: ''
30
+ announceTargetId: ''
31
+ announceAutoTarget: true
32
+ # ── 常驻看门狗(2026-11-16 加)──────────────────────────────
33
+ # 心跳文件每 5s 更新一次;超过 watchdogStaleMs 没更新且没有「重启中」标志,
34
+ # 就用 restart-dsh-start.ps1 把 DSH 拉起来(冷却期内不重复拉)。
35
+ # 要停:调 restart_watchdog(action:"stop"),或删 logs/dsh-stop.flag 后重启。
36
+ watchdogEnabled: true
37
+ watchdogPollMs: 2000
38
+ watchdogStaleMs: 15000
39
+ watchdogCooldownMs: 60000
40
+ watchdogScript: 'C:/Users/YOURNAME/.dsh/im/scripts/dsh-watchdog.cjs'
@@ -0,0 +1,147 @@
1
+ /**
2
+ * "我回来啦" announcement support for dsh-restart.
3
+ *
4
+ * Flow:
5
+ * 1. `restart_dsh` arms a restart → writeMarker() drops a JSON marker
6
+ * 2. DSH goes down, the start task brings it back
7
+ * 3. the plugin loads again → announceIfPending() sees the fresh
8
+ * marker and pushes the greeting once
9
+ *
10
+ * The marker is what makes this safe: a normal (unplanned) app start finds no
11
+ * marker and stays silent, and the marker is deleted before the push so a
12
+ * crash-loop cannot spam the chat.
13
+ *
14
+ * Kept free of @deepseek-ai imports so `node --test` can run standalone.
15
+ */
16
+ import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync } from "node:fs";
17
+ import { dirname } from "node:path";
18
+
19
+ export const DEFAULT_ANNOUNCE_TEXT = "咕噜~本鱼回来啦,尾巴甩甩,满血复活!";
20
+ export const DEFAULT_MAX_AGE_MINUTES = 30;
21
+
22
+ /**
23
+ * Persist the pending-announce marker. Never throws.
24
+ *
25
+ * @param {string} file absolute path
26
+ * @param {string} text greeting to send after the restart
27
+ * @param {Date} [now]
28
+ * @returns {{ ok: boolean, error?: string }}
29
+ */
30
+ export function writeMarker(file, text, now = new Date(), channel = "") {
31
+ try {
32
+ mkdirSync(dirname(file), { recursive: true });
33
+ const payload = {
34
+ version: 1,
35
+ at: now.toISOString(),
36
+ text: String(text ?? "").trim() || DEFAULT_ANNOUNCE_TEXT,
37
+ channel: String(channel ?? "").trim(),
38
+ };
39
+ writeFileSync(file, JSON.stringify(payload, null, 2) + "\n", "utf8");
40
+ return { ok: true };
41
+ } catch (error) {
42
+ return { ok: false, error: String(error?.message ?? error) };
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Read the marker, returning null when missing or unparseable.
48
+ * @param {string} file
49
+ */
50
+ export function readMarker(file) {
51
+ try {
52
+ if (!existsSync(file)) return null;
53
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
54
+ if (!parsed || typeof parsed.text !== "string" || !parsed.text.trim()) return null;
55
+ const at = Date.parse(parsed.at);
56
+ if (!Number.isFinite(at)) return null;
57
+ return { at, text: parsed.text.trim(), channel: String(parsed.channel ?? "").trim() };
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Is this marker still from the restart we just did?
65
+ *
66
+ * @param {{ at: number } | null} marker epoch ms
67
+ * @param {Date} [now]
68
+ * @param {number} [maxAgeMinutes]
69
+ */
70
+ export function isFresh(marker, now = new Date(), maxAgeMinutes = DEFAULT_MAX_AGE_MINUTES) {
71
+ if (!marker) return false;
72
+ const ttl = Math.max(1, Number(maxAgeMinutes) || DEFAULT_MAX_AGE_MINUTES) * 60 * 1000;
73
+ const age = now.getTime() - marker.at;
74
+ return age >= 0 && age <= ttl;
75
+ }
76
+
77
+ /** Delete the marker. Never throws; returns true when something was removed. */
78
+ export function clearMarker(file) {
79
+ try {
80
+ if (!existsSync(file)) return false;
81
+ unlinkSync(file);
82
+ return true;
83
+ } catch {
84
+ return false;
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Work out where the greeting should go, using the REAL dshIm service surface.
90
+ *
91
+ * The service (contractVersion 1) exposes only:
92
+ * listBots(): [{ botId, channel }]
93
+ * listTargets(botId): [{ targetId, ... }] (an ARRAY, not { targets })
94
+ * send(botId, targetId, text, opts)
95
+ * There is no listSuggestions / createTarget, so a target must already exist —
96
+ * it is created by the user in 设置 → IM机器人 → 新建目标.
97
+ *
98
+ * @param {{ listBots?: Function, listTargets?: Function }} im
99
+ * @param {{ botId?: string, targetId?: string }} [configured]
100
+ * @returns {Promise<{ botId: string, targetId: string } | { error: string, botId?: string }>}
101
+ */
102
+ export async function resolveDelivery(im, configured = {}) {
103
+ const forcedBot = String(configured?.botId ?? "").trim();
104
+ const forced = String(configured?.targetId ?? "").trim();
105
+ const wantChannel = String(configured?.channel ?? "").trim().toLowerCase();
106
+ // 指定渠道时,渠道优先于「配置好的机器人/目标」——否则 QQ 叫重启会被硬拽回微信。
107
+ if (forcedBot && forced && !wantChannel) return { botId: forcedBot, targetId: forced };
108
+
109
+ let bots = [];
110
+ try {
111
+ if (typeof im?.listBots === "function") bots = await im.listBots();
112
+ } catch { bots = []; }
113
+ const channelBot = wantChannel && Array.isArray(bots)
114
+ ? String((bots.find((b) => String(b?.channel ?? "").toLowerCase().includes(wantChannel)) || {}).botId ?? "")
115
+ : "";
116
+ // 指定渠道但该渠道没有机器人时,才退回配置好的那个,避免静默发错人。
117
+ if (wantChannel && !channelBot) {
118
+ // 指定了渠道,就绝不把问候发到别的渠道去;让调用方继续等这个渠道上线。
119
+ return { error: "channel-bot-not-ready:" + wantChannel };
120
+ }
121
+ const botIds = channelBot
122
+ ? [channelBot]
123
+ : forcedBot
124
+ ? [forcedBot]
125
+ : (Array.isArray(bots) ? bots.map((b) => String(b?.botId ?? "")).filter(Boolean) : []);
126
+ if (botIds.length === 0) return { error: "no-bot" };
127
+
128
+ if (forced && !wantChannel) return { botId: botIds[0], targetId: forced };
129
+ if (typeof im?.listTargets !== "function") return { error: "no-target", botId: botIds[0] };
130
+
131
+ // Scan every connected bot: the target may be saved under a different
132
+ // channel than the one that happens to be listed first.
133
+ let lastError = "";
134
+ for (const botId of botIds) {
135
+ let targets;
136
+ try {
137
+ targets = await im.listTargets(botId);
138
+ } catch (error) {
139
+ lastError = "list-targets-failed: " + String(error?.message ?? error);
140
+ continue;
141
+ }
142
+ if (targets && !Array.isArray(targets) && Array.isArray(targets.targets)) targets = targets.targets;
143
+ const first = Array.isArray(targets) ? String(targets[0]?.targetId ?? "") : "";
144
+ if (first) return { botId, targetId: first };
145
+ }
146
+ return lastError ? { error: lastError, botId: botIds[0] } : { error: "no-target", botId: botIds[0] };
147
+ }
package/lib/args.js ADDED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Pure argument/timing helpers for dsh-restart.
3
+ *
4
+ * Kept free of @deepseek-ai imports so `node --test` runs without the host
5
+ * profile (index.js does import the host modules).
6
+ *
7
+ * @module dsh-restart/args
8
+ */
9
+
10
+ /** Watchdog must be at least this many seconds after the start half. */
11
+ export const WATCH_GAP_SECONDS = 60;
12
+ export const MAX_WATCH_SECONDS = 1800;
13
+
14
+ /**
15
+ * Clamp a watchdog delay.
16
+ *
17
+ * 0 / missing / non-numeric / negative → 0 (no watchdog).
18
+ * Otherwise: at least startSeconds + WATCH_GAP_SECONDS, at most 1800.
19
+ *
20
+ * @param {unknown} requested
21
+ * @param {{ startSeconds?: number }} [timings]
22
+ * @returns {number} 0 = disabled
23
+ */
24
+ export function normalizeWatchSeconds(requested, timings = {}) {
25
+ const raw = Number(requested);
26
+ if (!Number.isFinite(raw) || raw <= 0) return 0;
27
+ const start = Number(timings?.startSeconds) || 0;
28
+ const floor = start + WATCH_GAP_SECONDS;
29
+ return Math.min(MAX_WATCH_SECONDS, Math.max(floor, Math.round(raw)));
30
+ }
31
+
32
+ /**
33
+ * Parse the "NAME=STATE;next=TIME" lines produced by scripts/dsh-restart-tasks.ps1.
34
+ * A missing task prints "NAME=-" and becomes {state:"", next:""}.
35
+ *
36
+ * @param {unknown} output
37
+ * @returns {{ name: string, state: string, next: string }[]}
38
+ */
39
+ export function parseTaskStatus(output) {
40
+ const rows = [];
41
+ for (const line of String(output ?? "").split(/\r?\n/)) {
42
+ const text = line.trim();
43
+ const eq = text.indexOf("=");
44
+ if (!text || eq <= 0) continue;
45
+ const name = text.slice(0, eq);
46
+ const rest = text.slice(eq + 1);
47
+ const parts = rest.split(";");
48
+ const rawState = (parts[0] ?? "-").trim();
49
+ const nextPart = parts.find((p) => p.startsWith("next=")) ?? "next=-";
50
+ const next = nextPart.slice("next=".length).trim();
51
+ rows.push({
52
+ name: name.trim(),
53
+ state: rawState === "-" ? "" : rawState,
54
+ next: next === "-" ? "" : next,
55
+ });
56
+ }
57
+ return rows;
58
+ }
59
+
60
+ /**
61
+ * Does this call need the extended arm script (custom start half / watchdog)?
62
+ *
63
+ * The plain arm script is the long-verified path; everything that only needs
64
+ * "kill + default start" must keep using it.
65
+ */
66
+ export function needsExtendedScript({ startScript, watchSeconds } = {}) {
67
+ return String(startScript ?? "").trim().length > 0 || Number(watchSeconds) > 0;
68
+ }
69
+
70
+ /**
71
+ * Build the PowerShell argument list for an arm script.
72
+ *
73
+ * @param {{ script: string, killSeconds: number, startSeconds: number,
74
+ * startScript?: string, watchSeconds?: number }} options
75
+ * @returns {string[]}
76
+ */
77
+ export function buildArmArgs({ script, killSeconds, startSeconds, startScript, watchSeconds }) {
78
+ const args = [
79
+ "-NoProfile",
80
+ "-ExecutionPolicy", "Bypass",
81
+ "-File", String(script),
82
+ "-KillAfterSeconds", String(killSeconds),
83
+ "-StartAfterSeconds", String(startSeconds),
84
+ ];
85
+ const start = String(startScript ?? "").trim();
86
+ if (start) args.push("-StartScript", start);
87
+ const watch = Number(watchSeconds) || 0;
88
+ if (watch > 0) args.push("-WatchAfterSeconds", String(watch));
89
+ return args;
90
+ }