@leiyi-works/dsh-auto-restart 0.0.0-stage → 0.1.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/README.md +82 -2
- package/cordis.patch.yml +17 -0
- package/icon.svg +12 -0
- package/index.js +750 -0
- package/lib/launch-supervisor.ps1 +47 -0
- package/lib/restart-supervisor.ps1 +181 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +41 -3
package/README.md
CHANGED
|
@@ -1,3 +1,83 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-auto-restart · 自动重启
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
装完/更新完插件后,不用再自己关掉 DSH 再打开:它会发现插件文件变了,等所有会话空闲,然后把整个桌面应用重启一次,回到原来的会话。
|
|
4
|
+
|
|
5
|
+
只支持 **Windows 桌面端**(Electron 外壳 + Host 子进程的形态)。`dsh web` / headless 不会重启(插件会写日志说明不支持)。
|
|
6
|
+
|
|
7
|
+
## 它怎么判断"插件变了"
|
|
8
|
+
|
|
9
|
+
盯着当前 profile 的这几处,每 2 秒取一次指纹:
|
|
10
|
+
|
|
11
|
+
- `node_modules/` 顶层条目,以及 `@scope/` 下面的条目(时间、大小、增删)
|
|
12
|
+
- `node_modules-link/`(如果存在)
|
|
13
|
+
- `package.json` 里的 `dependencies` 与 `dsh.profile.bundles`(内容签名)
|
|
14
|
+
|
|
15
|
+
指纹变了并且**稳定 10 秒**没再变,才算一次安装/更新结束。这样 dshmarket、官方插件管理器、手动 `pnpm add`、改自己插件的文件都能覆盖到,而云同步恢复同样的内容(内容签名不变)不会误触发。
|
|
16
|
+
|
|
17
|
+
## 它怎么重启
|
|
18
|
+
|
|
19
|
+
1. 等所有会话空闲(`api-session/status` + `agent/status`),默认最多等 2 分钟;
|
|
20
|
+
2. 等插件管理器安静 3 秒(不打断进行中的安装/更新);
|
|
21
|
+
3. 由 WMI 起一个**脱离进程树、隐藏控制台**的 PowerShell 守护进程;
|
|
22
|
+
4. 守护进程等 `restartDelayMs`(默认 2 秒)→ **先杀 Electron 主进程**(否则 Host 先退出会让主进程弹「DeepSeek Harness 无法使用」并响一声)→ 清掉残留应用进程 → `Start-Process` 拉起应用 → 等主窗口出现 → 写回执。
|
|
23
|
+
|
|
24
|
+
会话记录在磁盘上,重启后回到同一个会话。
|
|
25
|
+
|
|
26
|
+
## 安装后第一次
|
|
27
|
+
|
|
28
|
+
第一次安装需要手动重启一次 DSH(托盘「退出」再打开),让 Host 半边的代码加载。之后就不用再管了。
|
|
29
|
+
|
|
30
|
+
**首次默认 `dryRun: true`**:只写日志、不真重启。确认日志里看到「检测到插件文件变化」和「[dry-run] 本应重启」之后,把配置文件里的 `dryRun` 改成 `false`(改完即时生效,不用重启):
|
|
31
|
+
|
|
32
|
+
```json
|
|
33
|
+
{ "dryRun": false }
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
配置文件:`%USERPROFILE%\.dsh\dsh-auto-restart\config.json`(也可以放 `~/...` 形式的可移植路径)。
|
|
37
|
+
|
|
38
|
+
## 配置
|
|
39
|
+
|
|
40
|
+
| 键 | 默认 | 说明 |
|
|
41
|
+
|---|---|---|
|
|
42
|
+
| `enabled` | `true` | 总开关 |
|
|
43
|
+
| `dryRun` | `true` | 只记日志不重启;验证后改 `false` |
|
|
44
|
+
| `stableMs` | `10000` | 文件停止变化多久算安装完成 |
|
|
45
|
+
| `pollIntervalMs` | `2000` | 轮询间隔 |
|
|
46
|
+
| `managerQuietMs` | `3000` | 插件管理器最后一次活动后至少安静多久 |
|
|
47
|
+
| `cooldownMs` | `60000` | 两次重启最小间隔(跨重启持久化) |
|
|
48
|
+
| `maxPerHour` | `6` | 每小时最多重启几次 |
|
|
49
|
+
| `waitForIdle` | `true` | 等会话空闲再重启 |
|
|
50
|
+
| `maxIdleWaitMs` | `120000` | 等空闲上限,超时放弃本次 |
|
|
51
|
+
| `forceWhenBusy` | `false` | 超时后是否强重启 |
|
|
52
|
+
| `restartDelayMs` | `2000` | 守护进程收到请求后等多久动手 |
|
|
53
|
+
| `exePath` | `''` | 应用可执行文件,留空自动推导 |
|
|
54
|
+
| `launchArgs` | `[]` | 拉起应用时的附加参数 |
|
|
55
|
+
| `supervisorScript` | `''` | 自定义守护脚本路径 |
|
|
56
|
+
| `powershellPath` | `''` | 自定义 powershell.exe |
|
|
57
|
+
| `profileDir` | `''` | 自定义 profile 目录 |
|
|
58
|
+
| `logMaxBytes` | `1048576` | 日志滚动阈值 |
|
|
59
|
+
|
|
60
|
+
## 急停
|
|
61
|
+
|
|
62
|
+
在 `%USERPROFILE%\.dsh\dsh-auto-restart\` 下新建一个空文件 `disabled`,它立刻什么都不做(每 2 秒检查一次)。删掉就恢复。
|
|
63
|
+
|
|
64
|
+
## 状态与日志
|
|
65
|
+
|
|
66
|
+
- 日志:`%USERPROFILE%\.dsh\dsh-auto-restart\auto-restart.log`
|
|
67
|
+
- 上次重启回执:`restart-result.json`;上次请求:`last-restart.json`
|
|
68
|
+
- 状态:`GET http://127.0.0.1:<Host 端口>/auto-restart/status`(只接受本机回环),返回 dryRun、忙闲、冷却、上次结果等
|
|
69
|
+
|
|
70
|
+
## 卸载
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
dsh plugin --profile desktop remove @leiyi-works/dsh-auto-restart
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`%USERPROFILE%\.dsh\dsh-auto-restart\` 里的日志和配置可以留也可以删。
|
|
77
|
+
|
|
78
|
+
## 边界
|
|
79
|
+
|
|
80
|
+
- 只重启应用,不动其它进程。
|
|
81
|
+
- 正在跑的任务会被重启打断——所以先等空闲;`maxIdleWaitMs` 超时默认放弃本次。
|
|
82
|
+
- 不碰 `app.asar`,DSH 升级不受影响。
|
|
83
|
+
- 桌面端正式构建没有可用重启入口(官方菜单项只在 development 构建出现),所以只能用外部守护进程的方式;这也是为什么需要一次引导重启。
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# dsh-auto-restart — 自动重启(bundle 补丁)
|
|
2
|
+
#
|
|
3
|
+
# 定位:装完/更新完插件(或改了自己插件的文件)之后,不必再手动退出再打开。
|
|
4
|
+
# 本 bundle 插入一行 Host 插件;它监听 profile 的插件文件变化,等所有会话空闲,
|
|
5
|
+
# 再由一个脱离 DSH 进程树的守护进程:先杀 Electron 主进程(避免官方「无法使用」
|
|
6
|
+
# 弹框),清掉残留进程,重新拉起应用。
|
|
7
|
+
#
|
|
8
|
+
# 为什么需要这一行:DSH 的插件管理器只在"需要重启"时提示,桌面端正式构建里
|
|
9
|
+
# 没有可用的重启入口(官方菜单里的「重启应用与 Host」只在 development 构建出现);
|
|
10
|
+
# 而 Host 是 Electron 主进程的子进程,Host 自己无法让父进程 relaunch。
|
|
11
|
+
#
|
|
12
|
+
# 运行参数默认从 <DSH_HOME>/dsh-auto-restart/config.json 读,改文件即时生效
|
|
13
|
+
# (不需要重启)。首次安装默认 dryRun=true:只写日志、不真重启,确认无误后把
|
|
14
|
+
# config.json 里的 dryRun 改成 false。
|
|
15
|
+
- insert:
|
|
16
|
+
- id: auto-restart
|
|
17
|
+
name: '@leiyi-works/dsh-auto-restart'
|
package/icon.svg
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" role="img" aria-label="Auto restart">
|
|
2
|
+
<defs>
|
|
3
|
+
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
|
|
4
|
+
<stop offset="0" stop-color="#4f7cff"/>
|
|
5
|
+
<stop offset="1" stop-color="#7b5cff"/>
|
|
6
|
+
</linearGradient>
|
|
7
|
+
</defs>
|
|
8
|
+
<rect x="2" y="2" width="60" height="60" rx="16" fill="url(#g)"/>
|
|
9
|
+
<path d="M44 32a12 12 0 1 1-4.2-9.2" fill="none" stroke="#ffffff" stroke-width="5" stroke-linecap="round"/>
|
|
10
|
+
<path d="M42 14v11H31" fill="none" stroke="#ffffff" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>
|
|
11
|
+
<circle cx="32" cy="32" r="3.2" fill="#ffffff" opacity="0.9"/>
|
|
12
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,750 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-auto-restart — Host half.
|
|
3
|
+
*
|
|
4
|
+
* 装/更插件之后不用再手动退出再打开:本插件盯着 desktop profile 的插件文件
|
|
5
|
+
* (node_modules 顶层条目、@scope 下的条目、node_modules-link、package.json 的
|
|
6
|
+
* dependencies 与 dsh.profile.bundles),发现变化并稳定下来后,等所有会话空闲,
|
|
7
|
+
* 派一个**脱离进程树**的 PowerShell 守护进程去重启整个桌面应用。
|
|
8
|
+
*
|
|
9
|
+
* 为什么必须这样重启(Windows 实测结论):
|
|
10
|
+
* 1. 桌面端 Host 是 Electron 主进程的子进程,Host 退出会被主进程当成崩溃,
|
|
11
|
+
* 弹出原生「DeepSeek Harness 无法使用」并响一声 —— 所以必须先杀主进程。
|
|
12
|
+
* 2. Host 进程没法调用父进程的 app.relaunch(),也没法在自己被拆掉后继续干活,
|
|
13
|
+
* 所以守护进程必须由 WMI 创建、跑在进程树之外。
|
|
14
|
+
* 3. 拉起 GUI 应用后要等主窗口出现,不能只等进程起来。
|
|
15
|
+
*
|
|
16
|
+
* 安全阀:默认 dryRun=true(只写日志不真重启);冷却 60s;每小时最多 6 次;
|
|
17
|
+
* 会话忙时等(默认最多 2 分钟,超时就放弃本次,等下次变化);`disabled` 文件
|
|
18
|
+
* 存在时完全不动;所有失败只写日志,绝不让插件加载失败拖垮 profile。
|
|
19
|
+
*
|
|
20
|
+
* 运行参数:<DSH_HOME>/dsh-auto-restart/config.json(改文件即时生效,无需重启),
|
|
21
|
+
* 见 README。诊断:<DSH_HOME>/dsh-auto-restart/auto-restart.log,
|
|
22
|
+
* 状态:GET /auto-restart/status(回环)。
|
|
23
|
+
*/
|
|
24
|
+
import { createHash } from 'node:crypto'
|
|
25
|
+
import { spawn } from 'node:child_process'
|
|
26
|
+
import {
|
|
27
|
+
appendFileSync,
|
|
28
|
+
existsSync,
|
|
29
|
+
mkdirSync,
|
|
30
|
+
readFileSync,
|
|
31
|
+
readdirSync,
|
|
32
|
+
renameSync,
|
|
33
|
+
rmSync,
|
|
34
|
+
statSync,
|
|
35
|
+
writeFileSync,
|
|
36
|
+
} from 'node:fs'
|
|
37
|
+
import { homedir } from 'node:os'
|
|
38
|
+
import { basename, dirname, join, resolve } from 'node:path'
|
|
39
|
+
import { fileURLToPath } from 'node:url'
|
|
40
|
+
|
|
41
|
+
/** Loader row id (the patch in cordis.patch.yml inserts this id). */
|
|
42
|
+
export const name = 'auto-restart'
|
|
43
|
+
|
|
44
|
+
const MARK = 'dsh-auto-restart'
|
|
45
|
+
const PKG_DIR = fileURLToPath(new URL('./', import.meta.url))
|
|
46
|
+
const STATE_KEY = Symbol.for('dsh-auto-restart.state')
|
|
47
|
+
|
|
48
|
+
/** Defaults; config.json overrides them field by field. */
|
|
49
|
+
const DEFAULTS = Object.freeze({
|
|
50
|
+
enabled: true,
|
|
51
|
+
/** 只写日志、不真的重启。首次安装默认开,验证后改 false。 */
|
|
52
|
+
dryRun: true,
|
|
53
|
+
/** 轮询插件文件的间隔(毫秒)。 */
|
|
54
|
+
pollIntervalMs: 2000,
|
|
55
|
+
/** 文件停止变化多久才算安装完成(毫秒)。 */
|
|
56
|
+
stableMs: 10000,
|
|
57
|
+
/** 插件管理器最后一次活动之后至少安静多久(毫秒)。 */
|
|
58
|
+
managerQuietMs: 3000,
|
|
59
|
+
/** 两次重启之间最小间隔(毫秒),跨重启持久化。 */
|
|
60
|
+
cooldownMs: 60000,
|
|
61
|
+
/** 每小时最多重启几次,防止死循环。 */
|
|
62
|
+
maxPerHour: 6,
|
|
63
|
+
/** 有会话在跑时先等它们空闲。 */
|
|
64
|
+
waitForIdle: true,
|
|
65
|
+
/** 等空闲的最长时间(毫秒),超时按下面 forceWhenBusy 处理。 */
|
|
66
|
+
maxIdleWaitMs: 120000,
|
|
67
|
+
/** 等空闲超时后是否仍然强重启;默认 false(放弃本次,等下次变化)。 */
|
|
68
|
+
forceWhenBusy: false,
|
|
69
|
+
/** 守护进程收到请求后等多久动手(毫秒),留时间给当前回合收尾。 */
|
|
70
|
+
restartDelayMs: 2000,
|
|
71
|
+
/** 覆盖应用可执行文件路径;留空 = 用 Host 的 process.execPath。 */
|
|
72
|
+
exePath: '',
|
|
73
|
+
/** 拉起应用时附加的参数(数组,通常为空)。 */
|
|
74
|
+
launchArgs: [],
|
|
75
|
+
/** 覆盖守护脚本路径;留空 = 用本包 lib/restart-supervisor.ps1。 */
|
|
76
|
+
supervisorScript: '',
|
|
77
|
+
/** 覆盖 powershell.exe 路径;留空 = 系统 Windows PowerShell。 */
|
|
78
|
+
powershellPath: '',
|
|
79
|
+
/** 覆盖 profile 目录;留空 = $DSH_PROFILE_DIR,再退到 Host 工作目录。 */
|
|
80
|
+
profileDir: '',
|
|
81
|
+
/** 日志超过这个大小就滚动一次。 */
|
|
82
|
+
logMaxBytes: 1048576,
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
/** Session ids that currently have a turn running. */
|
|
86
|
+
const ACTIVE_STATUSES = new Set(['running', 'busy', 'thinking', 'streaming', 'starting', 'working'])
|
|
87
|
+
|
|
88
|
+
let logger = () => {}
|
|
89
|
+
|
|
90
|
+
// ---------------------------------------------------------------------------
|
|
91
|
+
// paths
|
|
92
|
+
// ---------------------------------------------------------------------------
|
|
93
|
+
|
|
94
|
+
function dshHome() {
|
|
95
|
+
const env = process.env.DSH_HOME
|
|
96
|
+
return typeof env === 'string' && env.trim() !== '' ? env.trim() : join(homedir(), '.dsh')
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function dataDir() {
|
|
100
|
+
return join(dshHome(), 'dsh-auto-restart')
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function logPath() {
|
|
104
|
+
return join(dataDir(), 'auto-restart.log')
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function configPath() {
|
|
108
|
+
return join(dataDir(), 'config.json')
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function statePath() {
|
|
112
|
+
return join(dataDir(), 'state.json')
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function requestPath() {
|
|
116
|
+
return join(dataDir(), 'restart-request.json')
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function resultPath() {
|
|
120
|
+
return join(dataDir(), 'restart-result.json')
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function disabledPath() {
|
|
124
|
+
return join(dataDir(), 'disabled')
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Expand a leading `~` so a portable config can store the home shorthand. */
|
|
128
|
+
function expandHome(value) {
|
|
129
|
+
if (typeof value !== 'string' || value === '') return value
|
|
130
|
+
if (value === '~') return homedir()
|
|
131
|
+
if (value.startsWith('~/') || value.startsWith('~\\')) return join(homedir(), value.slice(2))
|
|
132
|
+
return value
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function profileDirOf(cfg) {
|
|
136
|
+
const configured = expandHome(cfg.profileDir)
|
|
137
|
+
if (typeof configured === 'string' && configured.trim() !== '') return resolve(configured.trim())
|
|
138
|
+
const env = process.env.DSH_PROFILE_DIR
|
|
139
|
+
if (typeof env === 'string' && env.trim() !== '') return resolve(env.trim())
|
|
140
|
+
return process.cwd()
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// ---------------------------------------------------------------------------
|
|
144
|
+
// logging
|
|
145
|
+
// ---------------------------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
function rotateLogIfNeeded(cfg) {
|
|
148
|
+
try {
|
|
149
|
+
const limit = Number(cfg.logMaxBytes) || DEFAULTS.logMaxBytes
|
|
150
|
+
if (statSync(logPath()).size <= limit) return
|
|
151
|
+
renameSync(logPath(), `${logPath()}.1`)
|
|
152
|
+
} catch {
|
|
153
|
+
// rotation is best effort
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function logLine(level, message) {
|
|
158
|
+
const line = `[${new Date().toISOString()}] [${level}] ${message}\n`
|
|
159
|
+
try {
|
|
160
|
+
mkdirSync(dataDir(), { recursive: true })
|
|
161
|
+
rotateLogIfNeeded(readConfigUncached())
|
|
162
|
+
appendFileSync(logPath(), line, 'utf8')
|
|
163
|
+
} catch {
|
|
164
|
+
// never fail the plugin because the log could not be written
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
logger(level, message)
|
|
168
|
+
} catch {
|
|
169
|
+
// ignore logger failures
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function readLastResult() {
|
|
174
|
+
try {
|
|
175
|
+
const parsed = JSON.parse(readFileSync(resultPath(), 'utf8'))
|
|
176
|
+
return parsed !== null && typeof parsed === 'object' ? parsed : null
|
|
177
|
+
} catch {
|
|
178
|
+
return null
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ---------------------------------------------------------------------------
|
|
183
|
+
// config / state
|
|
184
|
+
// ---------------------------------------------------------------------------
|
|
185
|
+
|
|
186
|
+
const configCache = { key: '', value: null }
|
|
187
|
+
|
|
188
|
+
function sanitizeConfig(raw) {
|
|
189
|
+
const cfg = { ...DEFAULTS }
|
|
190
|
+
if (raw === null || typeof raw !== 'object') return cfg
|
|
191
|
+
const bool = (value, fallback) => (typeof value === 'boolean' ? value : fallback)
|
|
192
|
+
const num = (value, fallback, min, max) => {
|
|
193
|
+
const parsed = Number(value)
|
|
194
|
+
if (!Number.isFinite(parsed)) return fallback
|
|
195
|
+
return Math.min(max, Math.max(min, Math.round(parsed)))
|
|
196
|
+
}
|
|
197
|
+
cfg.enabled = bool(raw.enabled, cfg.enabled)
|
|
198
|
+
cfg.dryRun = bool(raw.dryRun, cfg.dryRun)
|
|
199
|
+
cfg.waitForIdle = bool(raw.waitForIdle, cfg.waitForIdle)
|
|
200
|
+
cfg.forceWhenBusy = bool(raw.forceWhenBusy, cfg.forceWhenBusy)
|
|
201
|
+
cfg.pollIntervalMs = num(raw.pollIntervalMs, cfg.pollIntervalMs, 500, 60000)
|
|
202
|
+
cfg.stableMs = num(raw.stableMs, cfg.stableMs, 0, 600000)
|
|
203
|
+
cfg.managerQuietMs = num(raw.managerQuietMs, cfg.managerQuietMs, 0, 60000)
|
|
204
|
+
cfg.cooldownMs = num(raw.cooldownMs, cfg.cooldownMs, 0, 3600000)
|
|
205
|
+
cfg.maxPerHour = num(raw.maxPerHour, cfg.maxPerHour, 1, 100)
|
|
206
|
+
cfg.maxIdleWaitMs = num(raw.maxIdleWaitMs, cfg.maxIdleWaitMs, 0, 3600000)
|
|
207
|
+
cfg.restartDelayMs = num(raw.restartDelayMs, cfg.restartDelayMs, 0, 600000)
|
|
208
|
+
cfg.logMaxBytes = num(raw.logMaxBytes, cfg.logMaxBytes, 4096, 64 * 1024 * 1024)
|
|
209
|
+
for (const key of ['exePath', 'supervisorScript', 'powershellPath', 'profileDir']) {
|
|
210
|
+
if (typeof raw[key] === 'string') cfg[key] = raw[key].trim()
|
|
211
|
+
}
|
|
212
|
+
if (Array.isArray(raw.launchArgs)) {
|
|
213
|
+
cfg.launchArgs = raw.launchArgs.filter((item) => typeof item === 'string').slice(0, 8)
|
|
214
|
+
}
|
|
215
|
+
return cfg
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Read config.json, honouring a patch-provided base config; cached by file stamp. */
|
|
219
|
+
function readConfig(base) {
|
|
220
|
+
const file = configPath()
|
|
221
|
+
let key = ''
|
|
222
|
+
try {
|
|
223
|
+
const st = statSync(file)
|
|
224
|
+
key = `${st.mtimeMs}:${st.size}`
|
|
225
|
+
} catch {
|
|
226
|
+
return sanitizeConfig(base)
|
|
227
|
+
}
|
|
228
|
+
if (configCache.key === key && configCache.value !== null) {
|
|
229
|
+
return sanitizeConfig({ ...base, ...configCache.value })
|
|
230
|
+
}
|
|
231
|
+
try {
|
|
232
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8'))
|
|
233
|
+
configCache.key = key
|
|
234
|
+
configCache.value = parsed !== null && typeof parsed === 'object' ? parsed : {}
|
|
235
|
+
} catch {
|
|
236
|
+
configCache.key = key
|
|
237
|
+
configCache.value = {}
|
|
238
|
+
}
|
|
239
|
+
return sanitizeConfig({ ...base, ...configCache.value })
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function readConfigUncached() {
|
|
243
|
+
try {
|
|
244
|
+
return sanitizeConfig(JSON.parse(readFileSync(configPath(), 'utf8')))
|
|
245
|
+
} catch {
|
|
246
|
+
return sanitizeConfig(null)
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function writeJsonAtomic(file, value) {
|
|
251
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
252
|
+
const tmp = `${file}.tmp-${process.pid}`
|
|
253
|
+
writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, 'utf8')
|
|
254
|
+
renameSync(tmp, file)
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function readStateFile() {
|
|
258
|
+
try {
|
|
259
|
+
const parsed = JSON.parse(readFileSync(statePath(), 'utf8'))
|
|
260
|
+
if (parsed === null || typeof parsed !== 'object') return { lastRestartAt: 0, restarts: [] }
|
|
261
|
+
const restarts = Array.isArray(parsed.restarts)
|
|
262
|
+
? parsed.restarts.map(Number).filter((n) => Number.isFinite(n) && n > 0)
|
|
263
|
+
: []
|
|
264
|
+
return { lastRestartAt: Number(parsed.lastRestartAt) || 0, restarts }
|
|
265
|
+
} catch {
|
|
266
|
+
return { lastRestartAt: 0, restarts: [] }
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function saveState(state) {
|
|
271
|
+
try {
|
|
272
|
+
writeJsonAtomic(statePath(), {
|
|
273
|
+
lastRestartAt: state.lastRestartAt,
|
|
274
|
+
restarts: state.restarts.slice(-50),
|
|
275
|
+
updatedAt: new Date().toISOString(),
|
|
276
|
+
})
|
|
277
|
+
} catch {
|
|
278
|
+
// state persistence is best effort
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// ---------------------------------------------------------------------------
|
|
283
|
+
// fingerprint
|
|
284
|
+
// ---------------------------------------------------------------------------
|
|
285
|
+
|
|
286
|
+
/** List one directory level, plus scoped packages one level deeper. */
|
|
287
|
+
function listTree(root) {
|
|
288
|
+
const parts = []
|
|
289
|
+
let names
|
|
290
|
+
try {
|
|
291
|
+
names = readdirSync(root)
|
|
292
|
+
} catch {
|
|
293
|
+
return ''
|
|
294
|
+
}
|
|
295
|
+
names.sort()
|
|
296
|
+
for (const entry of names) {
|
|
297
|
+
if (entry === '.' || entry === '..') continue
|
|
298
|
+
const full = join(root, entry)
|
|
299
|
+
let st
|
|
300
|
+
try {
|
|
301
|
+
st = statSync(full)
|
|
302
|
+
} catch {
|
|
303
|
+
continue
|
|
304
|
+
}
|
|
305
|
+
const kind = st.isDirectory() ? 'd' : 'f'
|
|
306
|
+
parts.push(`${entry}|${Math.round(st.mtimeMs)}|${st.size}|${kind}`)
|
|
307
|
+
if (!st.isDirectory() || !entry.startsWith('@')) continue
|
|
308
|
+
let children
|
|
309
|
+
try {
|
|
310
|
+
children = readdirSync(full)
|
|
311
|
+
} catch {
|
|
312
|
+
continue
|
|
313
|
+
}
|
|
314
|
+
children.sort()
|
|
315
|
+
for (const child of children) {
|
|
316
|
+
let cst
|
|
317
|
+
try {
|
|
318
|
+
cst = statSync(join(full, child))
|
|
319
|
+
} catch {
|
|
320
|
+
continue
|
|
321
|
+
}
|
|
322
|
+
parts.push(`${entry}/${child}|${Math.round(cst.mtimeMs)}|${cst.size}`)
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return parts.join(';')
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** Content signature of the two manifest fields that decide which plugins load. */
|
|
329
|
+
function manifestSignature(profileDir) {
|
|
330
|
+
try {
|
|
331
|
+
const pkg = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8'))
|
|
332
|
+
const dependencies = pkg !== null && typeof pkg === 'object' && pkg.dependencies !== null && typeof pkg.dependencies === 'object' ? pkg.dependencies : {}
|
|
333
|
+
const bundles = pkg?.dsh?.profile?.bundles
|
|
334
|
+
const sortedDeps = {}
|
|
335
|
+
for (const key of Object.keys(dependencies).sort()) sortedDeps[key] = dependencies[key]
|
|
336
|
+
return createHash('sha1').update(JSON.stringify([sortedDeps, Array.isArray(bundles) ? bundles : []])).digest('hex')
|
|
337
|
+
} catch {
|
|
338
|
+
return 'unreadable'
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function fingerprint(profileDir) {
|
|
343
|
+
const parts = [
|
|
344
|
+
`nm:${listTree(join(profileDir, 'node_modules'))}`,
|
|
345
|
+
`link:${listTree(join(profileDir, 'node_modules-link'))}`,
|
|
346
|
+
`pkg:${manifestSignature(profileDir)}`,
|
|
347
|
+
]
|
|
348
|
+
return createHash('sha1').update(parts.join('\n')).digest('hex')
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// ---------------------------------------------------------------------------
|
|
352
|
+
// host facts
|
|
353
|
+
// ---------------------------------------------------------------------------
|
|
354
|
+
|
|
355
|
+
/** True only for the packaged desktop host (its entry point is dsh-desktop-host). */
|
|
356
|
+
function isDesktopHost() {
|
|
357
|
+
if (process.platform !== 'win32') return false
|
|
358
|
+
try {
|
|
359
|
+
return process.argv.some((arg) => typeof arg === 'string' && arg.includes('dsh-desktop-host'))
|
|
360
|
+
} catch {
|
|
361
|
+
return false
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function powershellPath(cfg) {
|
|
366
|
+
const configured = expandHome(cfg.powershellPath)
|
|
367
|
+
if (typeof configured === 'string' && configured.trim() !== '') return configured.trim()
|
|
368
|
+
const root = process.env.SystemRoot || 'C:\\Windows'
|
|
369
|
+
const candidate = join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
|
|
370
|
+
return existsSync(candidate) ? candidate : 'powershell.exe'
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function resolveExe(cfg) {
|
|
374
|
+
const configured = expandHome(cfg.exePath)
|
|
375
|
+
if (typeof configured === 'string' && configured.trim() !== '') return resolve(configured.trim())
|
|
376
|
+
return process.execPath
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// ---------------------------------------------------------------------------
|
|
380
|
+
// restart dispatch
|
|
381
|
+
// ---------------------------------------------------------------------------
|
|
382
|
+
|
|
383
|
+
function settled(state) {
|
|
384
|
+
state.baseline = state.lastFp
|
|
385
|
+
state.pendingSince = 0
|
|
386
|
+
state.waitingSince = 0
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function abortPending(state, reason) {
|
|
390
|
+
logLine('info', `放弃本次重启:${reason}`)
|
|
391
|
+
state.pendingSince = 0
|
|
392
|
+
state.waitingSince = 0
|
|
393
|
+
// Move the baseline so the same change does not immediately arm again.
|
|
394
|
+
state.baseline = state.lastFp
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function dispatchRestart(state, cfg, reason) {
|
|
398
|
+
const exe = resolveExe(cfg)
|
|
399
|
+
|
|
400
|
+
// Dry run is checked first so it works on any host and never touches anything.
|
|
401
|
+
if (cfg.dryRun) {
|
|
402
|
+
logLine('info', `[dry-run] 本应重启:${reason};desktop=${isDesktopHost()} exe=${exe} root=${process.ppid} delay=${cfg.restartDelayMs}ms(config.json 里把 dryRun 改成 false 才会真重启)`)
|
|
403
|
+
settled(state)
|
|
404
|
+
return false
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
if (!isDesktopHost()) {
|
|
408
|
+
abortPending(state, '当前宿主不是 Windows 桌面端(dsh web / headless 不支持)')
|
|
409
|
+
return false
|
|
410
|
+
}
|
|
411
|
+
if (!existsSync(exe)) {
|
|
412
|
+
abortPending(state, `应用可执行文件不存在:${exe}`)
|
|
413
|
+
return false
|
|
414
|
+
}
|
|
415
|
+
const delay = Math.max(0, Number(cfg.restartDelayMs) || 0)
|
|
416
|
+
const supervisor = expandHome(cfg.supervisorScript) || join(PKG_DIR, 'lib', 'restart-supervisor.ps1')
|
|
417
|
+
const launcher = join(PKG_DIR, 'lib', 'launch-supervisor.ps1')
|
|
418
|
+
if (!existsSync(supervisor)) {
|
|
419
|
+
abortPending(state, `守护脚本不存在:${supervisor}`)
|
|
420
|
+
return false
|
|
421
|
+
}
|
|
422
|
+
if (!existsSync(launcher)) {
|
|
423
|
+
abortPending(state, `启动脚本不存在:${launcher}`)
|
|
424
|
+
return false
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
const request = {
|
|
428
|
+
exe,
|
|
429
|
+
rootPid: process.ppid,
|
|
430
|
+
hostPid: process.pid,
|
|
431
|
+
delayMs: delay,
|
|
432
|
+
launchArgs: Array.isArray(cfg.launchArgs) ? cfg.launchArgs : [],
|
|
433
|
+
log: logPath(),
|
|
434
|
+
result: resultPath(),
|
|
435
|
+
reason,
|
|
436
|
+
requestedAt: new Date().toISOString(),
|
|
437
|
+
}
|
|
438
|
+
try {
|
|
439
|
+
writeJsonAtomic(requestPath(), request)
|
|
440
|
+
try {
|
|
441
|
+
rmSync(resultPath(), { force: true })
|
|
442
|
+
} catch {
|
|
443
|
+
// stale result is harmless; it is overwritten by the supervisor
|
|
444
|
+
}
|
|
445
|
+
const ps = powershellPath(cfg)
|
|
446
|
+
const child = spawn(
|
|
447
|
+
ps,
|
|
448
|
+
['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', launcher, '-Supervisor', supervisor, '-Request', requestPath(), '-Log', logPath()],
|
|
449
|
+
{ cwd: dataDir(), windowsHide: true, stdio: 'ignore' },
|
|
450
|
+
)
|
|
451
|
+
child.on('error', (error) => logLine('error', `启动守护脚本失败:${String(error?.message ?? error)}`))
|
|
452
|
+
child.unref?.()
|
|
453
|
+
} catch (error) {
|
|
454
|
+
logLine('error', `派发重启失败:${String(error?.message ?? error)}`)
|
|
455
|
+
abortPending(state, '守护进程未能启动')
|
|
456
|
+
return false
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const now = Date.now()
|
|
460
|
+
state.lastRestartAt = now
|
|
461
|
+
state.dispatchedAt = now
|
|
462
|
+
state.dispatchedDelay = delay
|
|
463
|
+
state.restarts = [...state.restarts.filter((t) => now - t < 3600000), now]
|
|
464
|
+
state.lastReason = reason
|
|
465
|
+
saveState(state)
|
|
466
|
+
settled(state)
|
|
467
|
+
logLine('warn', `已派发重启:${reason};exe=${exe} root=${process.ppid} delay=${delay}ms`)
|
|
468
|
+
try {
|
|
469
|
+
writeJsonAtomic(join(dataDir(), 'last-restart.json'), {
|
|
470
|
+
at: new Date(now).toISOString(),
|
|
471
|
+
reason,
|
|
472
|
+
reasonOf: 'plugin files changed',
|
|
473
|
+
exe,
|
|
474
|
+
rootPid: process.ppid,
|
|
475
|
+
hostPid: process.pid,
|
|
476
|
+
delayMs: delay,
|
|
477
|
+
})
|
|
478
|
+
} catch {
|
|
479
|
+
// informational only
|
|
480
|
+
}
|
|
481
|
+
return true
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// ---------------------------------------------------------------------------
|
|
485
|
+
// tick
|
|
486
|
+
// ---------------------------------------------------------------------------
|
|
487
|
+
|
|
488
|
+
function createState(profileDir) {
|
|
489
|
+
const persisted = readStateFile()
|
|
490
|
+
const now = Date.now()
|
|
491
|
+
return {
|
|
492
|
+
profileDir,
|
|
493
|
+
baseline: null,
|
|
494
|
+
lastFp: null,
|
|
495
|
+
lastChangeAt: 0,
|
|
496
|
+
pendingSince: 0,
|
|
497
|
+
waitingSince: 0,
|
|
498
|
+
lastRestartAt: persisted.lastRestartAt,
|
|
499
|
+
restarts: persisted.restarts.filter((t) => now - t < 3600000),
|
|
500
|
+
lastManagerAt: 0,
|
|
501
|
+
dispatchedAt: 0,
|
|
502
|
+
dispatchedDelay: 0,
|
|
503
|
+
busy: new Set(),
|
|
504
|
+
lastReason: '',
|
|
505
|
+
lastSkipLog: 0,
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function tick(ctx, baseConfig) {
|
|
510
|
+
const cfg = readConfig(baseConfig)
|
|
511
|
+
if (!cfg.enabled) return
|
|
512
|
+
if (existsSync(disabledPath())) return
|
|
513
|
+
|
|
514
|
+
const state = globalThis[STATE_KEY]
|
|
515
|
+
if (!state) return
|
|
516
|
+
const now = Date.now()
|
|
517
|
+
state.restarts = state.restarts.filter((t) => now - t < 3600000)
|
|
518
|
+
|
|
519
|
+
// A restart is already on its way; the process will disappear shortly.
|
|
520
|
+
if (state.dispatchedAt > 0 && now - state.dispatchedAt < 60000) return
|
|
521
|
+
|
|
522
|
+
// The supervisor never came back: report and let a later change retry.
|
|
523
|
+
if (state.dispatchedAt > 0) {
|
|
524
|
+
const result = readLastResult()
|
|
525
|
+
logLine('warn', `上次重启没有完成(result=${result?.phase ?? 'missing'} ${result?.detail ?? ''})`)
|
|
526
|
+
state.dispatchedAt = 0
|
|
527
|
+
state.pendingSince = now
|
|
528
|
+
state.baseline = null
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
const fp = fingerprint(state.profileDir)
|
|
532
|
+
if (fp !== state.lastFp) {
|
|
533
|
+
state.lastFp = fp
|
|
534
|
+
state.lastChangeAt = now
|
|
535
|
+
}
|
|
536
|
+
if (state.baseline === null) {
|
|
537
|
+
state.baseline = fp
|
|
538
|
+
logLine('info', `已记录插件文件基线(${fp.slice(0, 10)})`)
|
|
539
|
+
return
|
|
540
|
+
}
|
|
541
|
+
if (fp === state.baseline) {
|
|
542
|
+
state.pendingSince = 0
|
|
543
|
+
state.waitingSince = 0
|
|
544
|
+
return
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
const quietFor = now - state.lastChangeAt
|
|
548
|
+
if (state.pendingSince === 0) {
|
|
549
|
+
if (quietFor < cfg.stableMs) return
|
|
550
|
+
state.pendingSince = now
|
|
551
|
+
logLine('info', `检测到插件文件变化,已稳定 ${Math.round(quietFor / 1000)}s,准备重启(dryRun=${cfg.dryRun})`)
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
if (now - state.lastManagerAt < cfg.managerQuietMs) return
|
|
555
|
+
|
|
556
|
+
const sinceRestart = now - state.lastRestartAt
|
|
557
|
+
if (state.lastRestartAt > 0 && sinceRestart < cfg.cooldownMs) {
|
|
558
|
+
if (now - state.lastSkipLog > 15000) {
|
|
559
|
+
state.lastSkipLog = now
|
|
560
|
+
logLine('info', `冷却中:还剩 ${Math.ceil((cfg.cooldownMs - sinceRestart) / 1000)}s`)
|
|
561
|
+
}
|
|
562
|
+
return
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
if (state.restarts.length >= cfg.maxPerHour) {
|
|
566
|
+
if (now - state.lastSkipLog > 15000) {
|
|
567
|
+
state.lastSkipLog = now
|
|
568
|
+
logLine('warn', `本小时已重启 ${state.restarts.length} 次,达到上限 ${cfg.maxPerHour},本次不重启`)
|
|
569
|
+
}
|
|
570
|
+
abortPending(state, '本小时重启次数已达上限')
|
|
571
|
+
return
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
if (cfg.waitForIdle && state.busy.size > 0) {
|
|
575
|
+
if (state.waitingSince === 0) {
|
|
576
|
+
state.waitingSince = now
|
|
577
|
+
logLine('info', `有 ${state.busy.size} 个会话在跑,等它们空闲后再重启`)
|
|
578
|
+
return
|
|
579
|
+
}
|
|
580
|
+
if (now - state.waitingSince <= cfg.maxIdleWaitMs) return
|
|
581
|
+
if (!cfg.forceWhenBusy) {
|
|
582
|
+
abortPending(state, `会话忙了 ${Math.round(cfg.maxIdleWaitMs / 1000)}s 仍未空闲`)
|
|
583
|
+
return
|
|
584
|
+
}
|
|
585
|
+
logLine('warn', `会话忙了 ${Math.round(cfg.maxIdleWaitMs / 1000)}s,forceWhenBusy=true,按配置强重启`)
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
dispatchRestart(state, cfg, '插件文件变化(装/更/改插件)')
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// ---------------------------------------------------------------------------
|
|
592
|
+
// apply
|
|
593
|
+
// ---------------------------------------------------------------------------
|
|
594
|
+
|
|
595
|
+
function safeOn(ctx, event, handler, label) {
|
|
596
|
+
try {
|
|
597
|
+
ctx.effect(() => ctx.on(event, handler), label)
|
|
598
|
+
} catch (error) {
|
|
599
|
+
logLine('warn', `订阅 ${event} 失败:${String(error?.message ?? error)}`)
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/** Register the read-only status route (loopback only). */
|
|
604
|
+
function installRoutes(ctx, baseConfig) {
|
|
605
|
+
try {
|
|
606
|
+
ctx.inject(['webServer'], (scope) => {
|
|
607
|
+
scope.effect(() => scope.webServer.register({
|
|
608
|
+
kind: 'prefix',
|
|
609
|
+
path: '/auto-restart',
|
|
610
|
+
handler: (req, res) => {
|
|
611
|
+
try {
|
|
612
|
+
const address = String(req.socket?.remoteAddress ?? '')
|
|
613
|
+
const loopback = address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
|
|
614
|
+
if (!loopback) {
|
|
615
|
+
res.writeHead(403, { 'content-type': 'application/json; charset=utf-8' })
|
|
616
|
+
res.end(JSON.stringify({ ok: false, error: 'loopback only' }))
|
|
617
|
+
return
|
|
618
|
+
}
|
|
619
|
+
const url = String(req.url ?? '/')
|
|
620
|
+
const cfg = readConfig(baseConfig)
|
|
621
|
+
const state = globalThis[STATE_KEY]
|
|
622
|
+
if (url.startsWith('/auto-restart/status') && req.method === 'GET') {
|
|
623
|
+
const now = Date.now()
|
|
624
|
+
const body = {
|
|
625
|
+
ok: true,
|
|
626
|
+
version: 1,
|
|
627
|
+
desktopHost: isDesktopHost(),
|
|
628
|
+
profileDir: state?.profileDir ?? null,
|
|
629
|
+
enabled: cfg.enabled,
|
|
630
|
+
dryRun: cfg.dryRun,
|
|
631
|
+
busySessions: state ? [...state.busy] : [],
|
|
632
|
+
pending: state ? state.pendingSince > 0 : false,
|
|
633
|
+
baseline: state?.baseline?.slice(0, 10) ?? null,
|
|
634
|
+
current: state?.lastFp?.slice(0, 10) ?? null,
|
|
635
|
+
lastChangeAt: state?.lastChangeAt ? new Date(state.lastChangeAt).toISOString() : null,
|
|
636
|
+
lastRestartAt: state?.lastRestartAt ? new Date(state.lastRestartAt).toISOString() : null,
|
|
637
|
+
restartsInHour: state?.restarts.length ?? 0,
|
|
638
|
+
cooldownLeftMs: state?.lastRestartAt ? Math.max(0, cfg.cooldownMs - (now - state.lastRestartAt)) : 0,
|
|
639
|
+
lastResult: readLastResult(),
|
|
640
|
+
logPath: logPath(),
|
|
641
|
+
configPath: configPath(),
|
|
642
|
+
disabled: existsSync(disabledPath()),
|
|
643
|
+
}
|
|
644
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
645
|
+
res.end(JSON.stringify(body))
|
|
646
|
+
return
|
|
647
|
+
}
|
|
648
|
+
res.writeHead(404, { 'content-type': 'application/json; charset=utf-8' })
|
|
649
|
+
res.end(JSON.stringify({ ok: false, error: 'not found' }))
|
|
650
|
+
} catch (error) {
|
|
651
|
+
try {
|
|
652
|
+
res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
|
|
653
|
+
res.end(JSON.stringify({ ok: false, error: String(error?.message ?? error) }))
|
|
654
|
+
} catch {
|
|
655
|
+
// response already gone
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
},
|
|
659
|
+
}), 'auto-restart: status route')
|
|
660
|
+
try {
|
|
661
|
+
const origin = scope.webServer.getOrigin?.()
|
|
662
|
+
logLine('info', `状态接口:${origin ?? '?'}/auto-restart/status`)
|
|
663
|
+
} catch {
|
|
664
|
+
// informational
|
|
665
|
+
}
|
|
666
|
+
})
|
|
667
|
+
} catch (error) {
|
|
668
|
+
logLine('warn', `注册状态接口失败:${String(error?.message ?? error)}`)
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
export function apply(ctx, config) {
|
|
673
|
+
try {
|
|
674
|
+
try {
|
|
675
|
+
const scoped = typeof ctx.logger === 'function' ? ctx.logger(MARK) : ctx.logger
|
|
676
|
+
if (scoped && typeof scoped.info === 'function') logger = (level, message) => scoped[level]?.(message)
|
|
677
|
+
} catch {
|
|
678
|
+
logger = () => {}
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
const baseConfig = config !== null && config !== undefined && typeof config === 'object' ? config : {}
|
|
682
|
+
const cfg = readConfig(baseConfig)
|
|
683
|
+
const profileDir = profileDirOf(cfg)
|
|
684
|
+
|
|
685
|
+
if (globalThis[STATE_KEY] === undefined) globalThis[STATE_KEY] = createState(profileDir)
|
|
686
|
+
else globalThis[STATE_KEY].profileDir = profileDir
|
|
687
|
+
const state = globalThis[STATE_KEY]
|
|
688
|
+
|
|
689
|
+
// Report the outcome of the restart this process may have just survived.
|
|
690
|
+
const result = readLastResult()
|
|
691
|
+
if (result !== null) {
|
|
692
|
+
logLine(result.phase === 'relaunched' || result.phase === 'relaunched-no-window' ? 'info' : 'warn',
|
|
693
|
+
`上次重启结果:${result.phase ?? '?'} ${result.detail ?? ''}`)
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
logLine('info', `${MARK} 0.1.0 已加载:profile=${profileDir} dryRun=${cfg.dryRun} cap=${cfg.maxPerHour}/h cooldown=${cfg.cooldownMs}ms desktop=${isDesktopHost()}`)
|
|
697
|
+
|
|
698
|
+
// Track busy sessions so a restart never cuts an answer.
|
|
699
|
+
ctx.effect(() => ctx.on('api-session/status', (sessionId, running) => {
|
|
700
|
+
const id = String(sessionId)
|
|
701
|
+
if (running === false) state.busy.delete(id)
|
|
702
|
+
else state.busy.add(id)
|
|
703
|
+
}), 'auto-restart: session status')
|
|
704
|
+
|
|
705
|
+
ctx.effect(() => ctx.on('agent/status', (payload) => {
|
|
706
|
+
const id = payload?.agent?.id
|
|
707
|
+
if (id === undefined) return
|
|
708
|
+
const status = payload?.status
|
|
709
|
+
if (status === 'idle') state.busy.delete(String(id))
|
|
710
|
+
else if (ACTIVE_STATUSES.has(status)) state.busy.add(String(id))
|
|
711
|
+
}), 'auto-restart: agent status')
|
|
712
|
+
|
|
713
|
+
// Plugin-manager activity: do not restart in the middle of an operation.
|
|
714
|
+
for (const event of ['plugin-manager/operation', 'plugin-manager/install-state', 'plugin-manager/update-state', 'plugin-manager/changed']) {
|
|
715
|
+
safeOn(ctx, event, () => { state.lastManagerAt = Date.now() }, `auto-restart: ${event}`)
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
// One timer for the whole plugin; disposal clears it.
|
|
719
|
+
const interval = Math.max(500, Math.min(5000, cfg.pollIntervalMs))
|
|
720
|
+
ctx.effect(() => {
|
|
721
|
+
const timer = setInterval(() => {
|
|
722
|
+
try {
|
|
723
|
+
tick(ctx, baseConfig)
|
|
724
|
+
} catch (error) {
|
|
725
|
+
logLine('error', `tick 失败:${String(error?.message ?? error)}`)
|
|
726
|
+
}
|
|
727
|
+
}, interval)
|
|
728
|
+
timer.unref?.()
|
|
729
|
+
return () => clearInterval(timer)
|
|
730
|
+
}, 'auto-restart: watcher')
|
|
731
|
+
|
|
732
|
+
installRoutes(ctx, baseConfig)
|
|
733
|
+
} catch (error) {
|
|
734
|
+
try {
|
|
735
|
+
logLine('error', `插件加载失败(已忽略,不影响 Host):${String(error?.message ?? error)}`)
|
|
736
|
+
} catch {
|
|
737
|
+
// ignore
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/** Test-only surface: pure helpers, no side effects. */
|
|
743
|
+
export const _internals = {
|
|
744
|
+
DEFAULTS,
|
|
745
|
+
fingerprint,
|
|
746
|
+
listTree,
|
|
747
|
+
manifestSignature,
|
|
748
|
+
sanitizeConfig,
|
|
749
|
+
isDesktopHost,
|
|
750
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
param(
|
|
2
|
+
[Parameter(Mandatory=$true)][string]$Supervisor,
|
|
3
|
+
[Parameter(Mandatory=$true)][string]$Request,
|
|
4
|
+
[Parameter(Mandatory=$true)][string]$Log
|
|
5
|
+
)
|
|
6
|
+
|
|
7
|
+
# Creates the restart supervisor through WMI so it runs outside this Host's
|
|
8
|
+
# process tree (taskkill /T on the app cannot reach it) and with no visible
|
|
9
|
+
# console (Win32_ProcessStartup.ShowWindow = 0 is SW_HIDE at creation time).
|
|
10
|
+
# ASCII only: Windows PowerShell 5.1 would decode a BOM-less non-ASCII file as ANSI.
|
|
11
|
+
|
|
12
|
+
$ErrorActionPreference = 'Stop'
|
|
13
|
+
|
|
14
|
+
function Write-LaunchLog([string]$Message) {
|
|
15
|
+
try {
|
|
16
|
+
$line = (Get-Date).ToString('o') + ' [launcher] ' + $Message + [Environment]::NewLine
|
|
17
|
+
[System.IO.File]::AppendAllText($Log, $line, (New-Object System.Text.UTF8Encoding($false)))
|
|
18
|
+
} catch {}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
try {
|
|
22
|
+
if (-not (Test-Path -LiteralPath $Supervisor)) {
|
|
23
|
+
Write-LaunchLog 'supervisor script missing'
|
|
24
|
+
exit 2
|
|
25
|
+
}
|
|
26
|
+
if (-not (Test-Path -LiteralPath $Request)) {
|
|
27
|
+
Write-LaunchLog 'request file missing'
|
|
28
|
+
exit 3
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
$command = 'powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "' + $Supervisor + '" -Request "' + $Request + '"'
|
|
32
|
+
|
|
33
|
+
$startup = ([wmiclass]'Win32_ProcessStartup').CreateInstance()
|
|
34
|
+
$startup.ShowWindow = 0
|
|
35
|
+
|
|
36
|
+
$created = ([wmiclass]'Win32_Process').Create($command, (Split-Path -Parent $Supervisor), $startup)
|
|
37
|
+
if ($created.ReturnValue -ne 0) {
|
|
38
|
+
Write-LaunchLog ('WMI Win32_Process.Create failed with return value ' + $created.ReturnValue)
|
|
39
|
+
exit 4
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
Write-LaunchLog ('supervisor started, pid=' + $created.ProcessId)
|
|
43
|
+
exit 0
|
|
44
|
+
} catch {
|
|
45
|
+
Write-LaunchLog ('launcher error: ' + $_.Exception.Message)
|
|
46
|
+
exit 1
|
|
47
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
param(
|
|
2
|
+
[Parameter(Mandatory=$true)][string]$Request
|
|
3
|
+
)
|
|
4
|
+
|
|
5
|
+
# Restart supervisor: waits, kills the Electron MAIN process first (so the shell
|
|
6
|
+
# never sees its Host die and never shows the "DeepSeek Harness is unavailable"
|
|
7
|
+
# dialog), clears the remaining app processes, relaunches the app and waits for
|
|
8
|
+
# its window. Runs outside the app's process tree (see launch-supervisor.ps1).
|
|
9
|
+
# ASCII only: Windows PowerShell 5.1 would decode a BOM-less non-ASCII file as ANSI.
|
|
10
|
+
|
|
11
|
+
$ErrorActionPreference = 'Stop'
|
|
12
|
+
# NB: the parameter is [string]-constrained, so the parsed object MUST live in a
|
|
13
|
+
# differently named variable; reusing $Request would coerce it back to a string.
|
|
14
|
+
$spec = Get-Content -LiteralPath $Request -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
15
|
+
$Log = [string]$spec.log
|
|
16
|
+
$Result = [string]$spec.result
|
|
17
|
+
|
|
18
|
+
function Write-Log([string]$Message) {
|
|
19
|
+
try {
|
|
20
|
+
$line = (Get-Date).ToString('o') + ' [supervisor] ' + $Message + [Environment]::NewLine
|
|
21
|
+
[System.IO.File]::AppendAllText($Log, $line, (New-Object System.Text.UTF8Encoding($false)))
|
|
22
|
+
} catch {}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function Write-Result([string]$Phase, [string]$Detail) {
|
|
26
|
+
try {
|
|
27
|
+
$payload = '{"phase":"' + $Phase + '","detail":"' + ($Detail -replace '\\','\\\\' -replace '"','\"') + '","pid":' + $PID + ',"at":"' + (Get-Date).ToString('o') + '"}'
|
|
28
|
+
[System.IO.File]::WriteAllText($Result, $payload, (New-Object System.Text.UTF8Encoding($false)))
|
|
29
|
+
} catch {}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function Test-ProcessAlive([int]$ProcessId) {
|
|
33
|
+
return (Get-Process -Id $ProcessId -ErrorAction SilentlyContinue) -ne $null
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function Wait-ProcessGone([int]$ProcessId, [int]$TimeoutMs) {
|
|
37
|
+
$deadline = (Get-Date).AddMilliseconds($TimeoutMs)
|
|
38
|
+
while ((Get-Date) -lt $deadline) {
|
|
39
|
+
if (-not (Test-ProcessAlive $ProcessId)) { return $true }
|
|
40
|
+
Start-Sleep -Milliseconds 200
|
|
41
|
+
}
|
|
42
|
+
return $false
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function Get-ProcessById([int]$ProcessId) {
|
|
46
|
+
try {
|
|
47
|
+
return Get-CimInstance Win32_Process -Filter ('ProcessId=' + $ProcessId) -ErrorAction Stop
|
|
48
|
+
} catch {
|
|
49
|
+
return $null
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function Find-RootProcess([string]$Exe, [int]$RootPid, [int]$HostPid) {
|
|
54
|
+
$exeFull = [System.IO.Path]::GetFullPath($Exe)
|
|
55
|
+
$candidate = Get-ProcessById $RootPid
|
|
56
|
+
if ($candidate -ne $null) {
|
|
57
|
+
$image = [string]$candidate.ExecutablePath
|
|
58
|
+
if ($image -ne '') {
|
|
59
|
+
try {
|
|
60
|
+
if ([System.IO.Path]::GetFullPath($image).ToLowerInvariant() -eq $exeFull.ToLowerInvariant()) {
|
|
61
|
+
return $candidate
|
|
62
|
+
}
|
|
63
|
+
} catch {}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
# Fallback: walk up from the Host process while the parent is the same app.
|
|
68
|
+
$exeName = [System.IO.Path]::GetFileNameWithoutExtension($Exe)
|
|
69
|
+
$current = Get-ProcessById $HostPid
|
|
70
|
+
$guard = 0
|
|
71
|
+
while ($current -ne $null -and $guard -lt 10) {
|
|
72
|
+
$parentId = [int]$current.ParentProcessId
|
|
73
|
+
if ($parentId -le 0) { break }
|
|
74
|
+
$parent = Get-ProcessById $parentId
|
|
75
|
+
if ($parent -eq $null) { break }
|
|
76
|
+
if ([string]$parent.Name -ne ($exeName + '.exe')) { break }
|
|
77
|
+
$current = $parent
|
|
78
|
+
$guard = $guard + 1
|
|
79
|
+
}
|
|
80
|
+
if ($current -ne $null -and [string]$current.Name -eq ($exeName + '.exe')) {
|
|
81
|
+
return $current
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
# Last resort: the oldest running process with that image name (the main process starts first).
|
|
85
|
+
$all = @(Get-CimInstance Win32_Process -Filter ('Name="' + $exeName + '.exe"') -ErrorAction SilentlyContinue)
|
|
86
|
+
if ($all.Count -eq 0) { return $null }
|
|
87
|
+
$oldest = $all[0]
|
|
88
|
+
foreach ($item in $all) {
|
|
89
|
+
try {
|
|
90
|
+
if ($item.CreationDate -lt $oldest.CreationDate) { $oldest = $item }
|
|
91
|
+
} catch {}
|
|
92
|
+
}
|
|
93
|
+
return $oldest
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
try {
|
|
97
|
+
Write-Log ('request: exe=' + $spec.exe + ' root=' + $spec.rootPid + ' host=' + $spec.hostPid + ' delay=' + $spec.delayMs + 'ms reason=' + $spec.reason)
|
|
98
|
+
Start-Sleep -Milliseconds ([int]$spec.delayMs)
|
|
99
|
+
|
|
100
|
+
$exe = [string]$spec.exe
|
|
101
|
+
if (-not (Test-Path -LiteralPath $exe)) {
|
|
102
|
+
Write-Log 'aborting: application executable is missing'
|
|
103
|
+
Write-Result 'aborted' 'exe missing'
|
|
104
|
+
exit 2
|
|
105
|
+
}
|
|
106
|
+
$exeName = [System.IO.Path]::GetFileNameWithoutExtension($exe)
|
|
107
|
+
|
|
108
|
+
$root = Find-RootProcess $exe ([int]$spec.rootPid) ([int]$spec.hostPid)
|
|
109
|
+
if ($root -eq $null) {
|
|
110
|
+
$running = @(Get-Process -Name $exeName -ErrorAction SilentlyContinue)
|
|
111
|
+
if ($running.Count -eq 0) {
|
|
112
|
+
Write-Log 'aborting: app is not running'
|
|
113
|
+
Write-Result 'aborted' 'app not running'
|
|
114
|
+
exit 3
|
|
115
|
+
}
|
|
116
|
+
Write-Log 'root process not identified; refusing to kill blindly'
|
|
117
|
+
Write-Result 'aborted' 'root process not identified'
|
|
118
|
+
exit 4
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
Write-Log ('killing root process pid=' + $root.ProcessId + ' name=' + $root.Name)
|
|
122
|
+
Stop-Process -Id ([int]$root.ProcessId) -Force -ErrorAction SilentlyContinue
|
|
123
|
+
$gone = Wait-ProcessGone ([int]$root.ProcessId) 15000
|
|
124
|
+
Write-Log ('root gone=' + $gone)
|
|
125
|
+
|
|
126
|
+
$left = @(Get-Process -Name $exeName -ErrorAction SilentlyContinue)
|
|
127
|
+
if ($left.Count -gt 0) {
|
|
128
|
+
Write-Log ('stopping ' + $left.Count + ' remaining app process(es)')
|
|
129
|
+
foreach ($proc in $left) {
|
|
130
|
+
Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
$deadline = (Get-Date).AddSeconds(15)
|
|
134
|
+
while ((Get-Date) -lt $deadline) {
|
|
135
|
+
$still = @(Get-Process -Name $exeName -ErrorAction SilentlyContinue)
|
|
136
|
+
if ($still.Count -eq 0) { break }
|
|
137
|
+
Start-Sleep -Milliseconds 250
|
|
138
|
+
}
|
|
139
|
+
$remaining = @(Get-Process -Name $exeName -ErrorAction SilentlyContinue)
|
|
140
|
+
if ($remaining.Count -gt 0) {
|
|
141
|
+
Write-Log ('forcing image kill for ' + $remaining.Count + ' process(es)')
|
|
142
|
+
& taskkill.exe /F /IM ($exeName + '.exe') 2>$null | Out-Null
|
|
143
|
+
Start-Sleep -Milliseconds 800
|
|
144
|
+
}
|
|
145
|
+
Write-Result 'stopped' ''
|
|
146
|
+
Write-Log 'app stopped; relaunching'
|
|
147
|
+
|
|
148
|
+
$startArgs = @{
|
|
149
|
+
FilePath = $exe
|
|
150
|
+
WorkingDirectory = (Split-Path -Parent $exe)
|
|
151
|
+
PassThru = $true
|
|
152
|
+
}
|
|
153
|
+
$argsList = @($spec.launchArgs)
|
|
154
|
+
if ($argsList.Count -gt 0) {
|
|
155
|
+
$startArgs['ArgumentList'] = $argsList
|
|
156
|
+
}
|
|
157
|
+
$newProcess = Start-Process @startArgs
|
|
158
|
+
Write-Log ('relaunched pid=' + $newProcess.Id)
|
|
159
|
+
|
|
160
|
+
$windowDeadline = (Get-Date).AddSeconds(60)
|
|
161
|
+
$windowUp = $false
|
|
162
|
+
while ((Get-Date) -lt $windowDeadline) {
|
|
163
|
+
$alive = Get-Process -Id $newProcess.Id -ErrorAction SilentlyContinue
|
|
164
|
+
if ($alive -eq $null) { break }
|
|
165
|
+
if ($alive.MainWindowHandle -ne 0) { $windowUp = $true; break }
|
|
166
|
+
Start-Sleep -Milliseconds 500
|
|
167
|
+
}
|
|
168
|
+
if ($windowUp) {
|
|
169
|
+
Write-Result 'relaunched' ('window up, pid=' + $newProcess.Id)
|
|
170
|
+
Write-Log 'window is up'
|
|
171
|
+
} else {
|
|
172
|
+
Write-Result 'relaunched-no-window' ('pid=' + $newProcess.Id + ' no window within 60s')
|
|
173
|
+
Write-Log 'relaunched without a window within 60s'
|
|
174
|
+
}
|
|
175
|
+
exit 0
|
|
176
|
+
} catch {
|
|
177
|
+
Write-Log ('supervisor error: ' + $_.Exception.Message)
|
|
178
|
+
Write-Result 'failed' $_.Exception.Message
|
|
179
|
+
exit 1
|
|
180
|
+
}
|
|
181
|
+
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Auto restart",
|
|
4
|
+
"description": "Restart DSH automatically after a plugin is installed or updated, then come back to the same conversation: watch the profile's plugin files, wait for every session to be idle, and let a supervisor outside the app's process tree kill the main process first and relaunch it. Cooldown, hourly cap, dry-run and a status route included."
|
|
5
|
+
}
|
|
6
|
+
}
|
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@leiyi-works/dsh-auto-restart",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"title": "自动重启",
|
|
6
|
+
"description": "装/更插件后自动重启 DSH 并回到原会话:检测 profile 插件文件变化,等所有会话空闲,由脱离进程树的守护者先杀主进程再拉起,带冷却、频率上限、日志与状态接口。",
|
|
7
|
+
"main": "index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./index.js",
|
|
10
|
+
"./locale/*.json": "./locale/*.json",
|
|
11
|
+
"./icon": "./icon.svg",
|
|
12
|
+
"./package.json": "./package.json"
|
|
13
|
+
},
|
|
14
|
+
"icon": "icon.svg",
|
|
15
|
+
"files": [
|
|
16
|
+
"index.js",
|
|
17
|
+
"cordis.patch.yml",
|
|
18
|
+
"lib/*.ps1",
|
|
19
|
+
"locale/*.json",
|
|
20
|
+
"icon.svg",
|
|
21
|
+
"README.md"
|
|
22
|
+
],
|
|
23
|
+
"dsh": {
|
|
24
|
+
"bundle": {
|
|
25
|
+
"patch": "./cordis.patch.yml"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"engines": {
|
|
29
|
+
"node": ">=20"
|
|
30
|
+
},
|
|
31
|
+
"license": "MIT",
|
|
32
|
+
"author": "leiyi-works",
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
},
|
|
36
|
+
"keywords": [
|
|
37
|
+
"deepseek-harness",
|
|
38
|
+
"dsh",
|
|
39
|
+
"dsh-plugin",
|
|
40
|
+
"auto-restart",
|
|
41
|
+
"restart",
|
|
42
|
+
"windows"
|
|
43
|
+
]
|
|
6
44
|
}
|