@andy.ian/dsh-homing 2.0.3 → 2.1.1
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/bin/restart-daemon.mjs +3 -0
- package/bin/restart.mjs +3 -0
- package/index.js +714 -21
- package/lib/devices.mjs +0 -1
- package/lib/files-page.mjs +0 -18
- package/lib/files.mjs +39 -27
- package/package.json +7 -9
- package/restart/client.mjs +184 -0
- package/restart/config.mjs +187 -0
- package/restart/daemon/README.md +102 -0
- package/restart/daemon/cli.mjs +366 -0
- package/restart/daemon/lib/detach.mjs +126 -0
- package/restart/daemon/lib/process-tree.mjs +69 -0
- package/restart/daemon/lib/restart-flow.mjs +111 -0
- package/restart/daemon/lib/update-state.mjs +72 -0
- package/restart/daemon/main.mjs +691 -0
- package/restart/engine.mjs +93 -0
- package/restart/face.mjs +62 -0
- package/restart/runner.mjs +184 -0
- package/restart/service.mjs +91 -0
- package/bin/supervisor.mjs +0 -488
- package/bin/watchdog.mjs +0 -144
- package/lib/vendor/node_modules/ssh2/examples/server-chat.js +0 -238
- package/lib/vendor/node_modules/ssh2/examples/sftp-server-download-only.js +0 -134
- package/lib/vendor/node_modules/ssh2/test/common.js +0 -316
- package/lib/vendor/node_modules/ssh2/test/fixtures/bad_rsa_private_key +0 -26
- package/lib/vendor/node_modules/ssh2/test/fixtures/https_cert.pem +0 -33
- package/lib/vendor/node_modules/ssh2/test/fixtures/https_key.pem +0 -52
- package/lib/vendor/node_modules/ssh2/test/fixtures/id_dsa +0 -12
- package/lib/vendor/node_modules/ssh2/test/fixtures/id_ecdsa +0 -5
- package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa +0 -15
- package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa.ppk +0 -26
- package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa_enc +0 -30
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa +0 -21
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc +0 -22
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm +0 -23
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa +0 -9
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc +0 -10
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub.result +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm +0 -10
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub.result +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519 +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa +0 -27
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc +0 -28
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub.result +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm +0 -29
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub.result +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa +0 -12
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc +0 -15
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub.result +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa +0 -5
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub.result +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa +0 -27
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc +0 -30
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub.result +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256 +0 -54
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub.result +0 -6
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.result +0 -6
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc +0 -17
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa +0 -26
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc +0 -18
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub +0 -9
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub +0 -10
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub +0 -11
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub +0 -11
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub +0 -13
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/openssh_new_rsa +0 -27
- package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_dsa_key +0 -12
- package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_ecdsa_key +0 -5
- package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_rsa_key +0 -15
- package/lib/vendor/node_modules/ssh2/test/test-exec.js +0 -578
- package/lib/vendor/node_modules/ssh2/test/test-integration-openssh.js +0 -486
- package/lib/vendor/node_modules/ssh2/test/test-keygen.js +0 -60
- package/lib/vendor/node_modules/ssh2/test/test-misc-client-server.js +0 -1460
- package/lib/vendor/node_modules/ssh2/test/test-openssh.js +0 -261
- package/lib/vendor/node_modules/ssh2/test/test-protocol-crypto.js +0 -631
- package/lib/vendor/node_modules/ssh2/test/test-protocol-keyparser.js +0 -177
- package/lib/vendor/node_modules/ssh2/test/test-server-hostkeys.js +0 -138
- package/lib/vendor/node_modules/ssh2/test/test-sftp.js +0 -842
- package/lib/vendor/node_modules/ssh2/test/test-shell.js +0 -109
- package/lib/vendor/node_modules/ssh2/test/test-userauth-agent-openssh.js +0 -110
- package/lib/vendor/node_modules/ssh2/test/test-userauth-agent.js +0 -171
- package/lib/vendor/node_modules/ssh2/test/test-userauth.js +0 -611
- package/lib/vendor/node_modules/ssh2/test/test-worker-imports.js +0 -25
- package/lib/vendor/node_modules/ssh2/test/test.js +0 -20
|
@@ -0,0 +1,691 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* DSH 常驻守护进程(模型 B)
|
|
4
|
+
*
|
|
5
|
+
* 为什么要独立进程:插件跑在 DSH 里,不能重启 DSH(会把自己杀掉)。
|
|
6
|
+
* 相比「系统定时任务每 5 分钟轮询」,常驻进程的优势:
|
|
7
|
+
* - 自己拉起的子进程:child.on('exit') 瞬时感知
|
|
8
|
+
* - 外部拉起的进程:2 秒轻量轮询(进程列表 + 端口),开销 < 0.05% CPU
|
|
9
|
+
* - 纯 Node,一份代码跨平台;只有「怎么开机启动它」分平台
|
|
10
|
+
* - 无控制台窗口,不存在闪黑窗
|
|
11
|
+
*
|
|
12
|
+
* 已修的关键缺陷:
|
|
13
|
+
* ① 单实例:控制端口被占用即退出,避免两个守护互相抢着拉起
|
|
14
|
+
* ② 重启互斥:并发请求只执行一次,避免双实例
|
|
15
|
+
* ③ 主动退出(退出码 0)不自动拉起,否则用户关不掉程序
|
|
16
|
+
* ④ default 模式等待空闲超时 → 放弃本次重启,不再硬打断用户
|
|
17
|
+
* ⑤ 稳定运行 60 秒后把退避计数归零
|
|
18
|
+
* ⑥ 找不到 exe 时只记一次日志并停止自动拉起
|
|
19
|
+
* ⑦ 用代际号忽略旧子进程的迟到 exit 事件
|
|
20
|
+
* ⑫ 空闲判定同时看 activity.json 与 sessions/*.json
|
|
21
|
+
*
|
|
22
|
+
* 用法:
|
|
23
|
+
* node bin/restart-daemon.mjs 前台运行(调试)
|
|
24
|
+
* node bin/restart-daemon.mjs --detach 后台常驻(配合启动项)
|
|
25
|
+
* node bin/restart-daemon.mjs --status 查看状态后退出
|
|
26
|
+
* node bin/restart-daemon.mjs --restart [--immediate] 请求重启
|
|
27
|
+
*
|
|
28
|
+
* 控制接口:
|
|
29
|
+
* GET http://127.0.0.1:8790/status
|
|
30
|
+
* POST http://127.0.0.1:8790/restart?mode=immediate|default
|
|
31
|
+
*/
|
|
32
|
+
import fs from 'node:fs'
|
|
33
|
+
import net from 'node:net'
|
|
34
|
+
import crypto from 'node:crypto'
|
|
35
|
+
import os from 'node:os'
|
|
36
|
+
import path from 'node:path'
|
|
37
|
+
import http from 'node:http'
|
|
38
|
+
import { spawn, spawnSync } from 'node:child_process'
|
|
39
|
+
import { rootOf, authorizeRestart } from './lib/process-tree.mjs'
|
|
40
|
+
import { decideUpgrade } from './lib/update-state.mjs'
|
|
41
|
+
import { startHidden, ancestorMatches, chainNames } from './lib/detach.mjs'
|
|
42
|
+
import { createRestartFlow, computeBackoff, planAfterExit } from './lib/restart-flow.mjs'
|
|
43
|
+
|
|
44
|
+
// ---------- 参数 ----------
|
|
45
|
+
function arg(name, fallback = '') {
|
|
46
|
+
const index = process.argv.indexOf('--' + name)
|
|
47
|
+
if (index < 0) return fallback
|
|
48
|
+
const next = process.argv[index + 1]
|
|
49
|
+
return next && !next.startsWith('--') ? next : 'true'
|
|
50
|
+
}
|
|
51
|
+
const has = (name) => process.argv.includes('--' + name)
|
|
52
|
+
|
|
53
|
+
const dshHome = process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh')
|
|
54
|
+
const stateDir = arg('state', path.join(dshHome, 'restart-daemon'))
|
|
55
|
+
const controlPort = Number(arg('control', '8790'))
|
|
56
|
+
const bridgePort = Number(arg('bridge', '8787'))
|
|
57
|
+
const pollMs = Number(arg('poll', '2000'))
|
|
58
|
+
const logFile = path.join(stateDir, 'restart-daemon.log')
|
|
59
|
+
const stateFile = path.join(stateDir, 'restart-daemon.json')
|
|
60
|
+
const pidFile = path.join(stateDir, 'restart-daemon.pid')
|
|
61
|
+
const MAX_PAUSE_MINUTES = 24 * 60
|
|
62
|
+
|
|
63
|
+
// 根据"客户端本地端口"反查发起连接的进程 PID。
|
|
64
|
+
// 用于确认重启指令确实来自 DSH 进程内部(我们的策略模块),
|
|
65
|
+
// 而不是同机其他进程——令牌文件同用户可读,PID 校验才是硬约束。
|
|
66
|
+
// 监听某端口的进程 PID(用于识别"插件宿主")
|
|
67
|
+
function listeningPid(port) {
|
|
68
|
+
const target = String(port);
|
|
69
|
+
try {
|
|
70
|
+
if (process.platform === 'win32') {
|
|
71
|
+
const out = spawnSync('netstat', ['-ano', '-p', 'tcp'], { encoding: 'utf8', timeout: 5000, windowsHide: true });
|
|
72
|
+
if (out.status !== 0 || !out.stdout) return null;
|
|
73
|
+
for (const line of out.stdout.split('\n')) {
|
|
74
|
+
const cols = line.trim().split(/\s+/u);
|
|
75
|
+
if (cols.length < 5) continue;
|
|
76
|
+
if (cols[3] !== 'LISTENING') continue;
|
|
77
|
+
if (!cols[1].endsWith(':' + target)) continue;
|
|
78
|
+
const pid = Number(cols[4]);
|
|
79
|
+
if (Number.isFinite(pid) && pid > 0) return pid;
|
|
80
|
+
}
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
const out = spawnSync('ss', ['-tlnp'], { encoding: 'utf8', timeout: 5000 });
|
|
84
|
+
if (out.status === 0 && out.stdout) {
|
|
85
|
+
for (const line of out.stdout.split('\n')) {
|
|
86
|
+
if (!line.includes(':' + target)) continue;
|
|
87
|
+
const m = /pid=(\d+)/u.exec(line);
|
|
88
|
+
if (m) return Number(m[1]);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return null;
|
|
92
|
+
} catch {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// 列出所有进程名(tasklist,无需 wmic)
|
|
98
|
+
function listProcessNames() {
|
|
99
|
+
try {
|
|
100
|
+
if (process.platform !== 'win32') {
|
|
101
|
+
const out = spawnSync('ps', ['-eo', 'comm='], { encoding: 'utf8', timeout: 5000 })
|
|
102
|
+
return String(out.stdout ?? '').split(/\n/u).map((x) => x.trim()).filter(Boolean)
|
|
103
|
+
}
|
|
104
|
+
const out = spawnSync('tasklist', ['/FO', 'CSV', '/NH'], { encoding: 'utf8', windowsHide: true, timeout: 8000 })
|
|
105
|
+
return String(out.stdout ?? '')
|
|
106
|
+
.split(/\r?\n/u)
|
|
107
|
+
.map((line) => line.match(/^"([^"]+)"/u)?.[1])
|
|
108
|
+
.filter(Boolean)
|
|
109
|
+
} catch {
|
|
110
|
+
return []
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function peerPidForPort(remotePort, controlPortNumber) {
|
|
115
|
+
const rport = String(remotePort);
|
|
116
|
+
const cport = String(controlPortNumber);
|
|
117
|
+
try {
|
|
118
|
+
if (process.platform === 'win32') {
|
|
119
|
+
const out = spawnSync('netstat', ['-ano', '-p', 'tcp'], { encoding: 'utf8', timeout: 5000, windowsHide: true });
|
|
120
|
+
if (out.status !== 0 || !out.stdout) return null;
|
|
121
|
+
for (const line of out.stdout.split('\n')) {
|
|
122
|
+
const cols = line.trim().split(/\s+/u);
|
|
123
|
+
if (cols.length < 5) continue;
|
|
124
|
+
if (cols[3] !== 'ESTABLISHED') continue;
|
|
125
|
+
// 客户端那一行:Local 是临时端口,Foreign 是 127.0.0.1:控制口
|
|
126
|
+
if (!cols[1].endsWith(':' + rport)) continue;
|
|
127
|
+
if (!cols[2].endsWith(':' + cport)) continue;
|
|
128
|
+
const pid = Number(cols[4]);
|
|
129
|
+
if (Number.isFinite(pid) && pid > 0) return pid;
|
|
130
|
+
}
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
const out = spawnSync('ss', ['-tnp'], { encoding: 'utf8', timeout: 5000 });
|
|
134
|
+
if (out.status === 0 && out.stdout) {
|
|
135
|
+
for (const line of out.stdout.split('\n')) {
|
|
136
|
+
if (!line.includes(':' + rport)) continue;
|
|
137
|
+
if (!line.includes(':' + cport)) continue;
|
|
138
|
+
const m = /pid=(\d+)/u.exec(line);
|
|
139
|
+
if (m) return Number(m[1]);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return null;
|
|
143
|
+
} catch {
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** netstat 有时抓不到刚建立/已复用的连接,重试三次降低误 403 */
|
|
149
|
+
async function peerPidForPortRetry(remotePort, controlPortNumber, attempts = 3, delayMs = 80) {
|
|
150
|
+
for (let i = 0; i < attempts; i += 1) {
|
|
151
|
+
const pid = peerPidForPort(remotePort, controlPortNumber)
|
|
152
|
+
if (pid) return pid
|
|
153
|
+
if (i < attempts - 1) await new Promise((resolve) => setTimeout(resolve, delayMs))
|
|
154
|
+
}
|
|
155
|
+
return null
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
fs.mkdirSync(stateDir, { recursive: true })
|
|
159
|
+
|
|
160
|
+
/** 本地时间 + 时区偏移,例如 2026-11-05T21:36:42+08:00 */
|
|
161
|
+
function localIso(date = new Date()) {
|
|
162
|
+
const pad = (n) => String(n).padStart(2, '0')
|
|
163
|
+
const offsetMinutes = -date.getTimezoneOffset()
|
|
164
|
+
const sign = offsetMinutes >= 0 ? '+' : '-'
|
|
165
|
+
const abs = Math.abs(offsetMinutes)
|
|
166
|
+
return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate())
|
|
167
|
+
+ 'T' + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds())
|
|
168
|
+
+ sign + pad(Math.floor(abs / 60)) + ':' + pad(abs % 60)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function log(message) {
|
|
172
|
+
const line = `${new Date().toISOString()} ${message}\n`
|
|
173
|
+
try { fs.appendFileSync(logFile, line) } catch { /* 日志写不了不影响主流程 */ }
|
|
174
|
+
if (!has('detach')) process.stdout.write(line)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ---------- 找 DSH 可执行文件(唯一真正分平台的部分) ----------
|
|
178
|
+
function findDshExe() {
|
|
179
|
+
const fromArg = arg('exe')
|
|
180
|
+
if (fromArg && fromArg !== 'true' && fs.existsSync(fromArg)) return fromArg
|
|
181
|
+
if (process.platform === 'win32') {
|
|
182
|
+
const candidates = [
|
|
183
|
+
path.join(process.env.LOCALAPPDATA ?? '', 'Programs', 'DeepSeek Harness', 'DeepSeek Harness.exe'),
|
|
184
|
+
path.join(process.env.ProgramFiles ?? '', 'DeepSeek Harness', 'DeepSeek Harness.exe'),
|
|
185
|
+
path.join(process.env['ProgramFiles(x86)'] ?? '', 'DeepSeek Harness', 'DeepSeek Harness.exe'),
|
|
186
|
+
path.join(process.env.ProgramData ?? '', 'DeepSeek Harness', 'DeepSeek Harness.exe'),
|
|
187
|
+
]
|
|
188
|
+
return candidates.find((item) => item && fs.existsSync(item)) ?? null
|
|
189
|
+
}
|
|
190
|
+
const candidates = process.platform === 'darwin'
|
|
191
|
+
? ['/Applications/DeepSeek Harness.app/Contents/MacOS/DeepSeek Harness']
|
|
192
|
+
: ['/usr/local/bin/deepseek-harness', '/usr/bin/deepseek-harness']
|
|
193
|
+
return candidates.find((item) => fs.existsSync(item)) ?? null
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const exePath = findDshExe()
|
|
197
|
+
const exeName = exePath ? path.basename(exePath) : 'DeepSeek Harness.exe'
|
|
198
|
+
const procName = path.basename(exeName, path.extname(exeName))
|
|
199
|
+
|
|
200
|
+
// ---------- 进程发现与探测 ----------
|
|
201
|
+
function listDshPids() {
|
|
202
|
+
try {
|
|
203
|
+
if (process.platform === 'win32') {
|
|
204
|
+
const out = spawnSync('tasklist', ['/FI', `IMAGENAME eq ${exeName}`, '/FO', 'CSV', '/NH'], {
|
|
205
|
+
encoding: 'utf8', windowsHide: true, timeout: 5000,
|
|
206
|
+
})
|
|
207
|
+
return String(out.stdout ?? '')
|
|
208
|
+
.split(/\r?\n/u)
|
|
209
|
+
.map((line) => line.match(/^"([^"]+)","(\d+)"/u))
|
|
210
|
+
.filter(Boolean)
|
|
211
|
+
.map((match) => Number(match[2]))
|
|
212
|
+
}
|
|
213
|
+
const out = spawnSync('ps', ['-eo', 'pid=,comm='], { encoding: 'utf8', timeout: 5000 })
|
|
214
|
+
return String(out.stdout ?? '')
|
|
215
|
+
.split(/\n/u)
|
|
216
|
+
.map((line) => line.trim().split(/\s+/u))
|
|
217
|
+
.filter((parts) => parts.length >= 2 && parts.slice(1).join(' ').includes(procName))
|
|
218
|
+
.map((parts) => Number(parts[0]))
|
|
219
|
+
} catch {
|
|
220
|
+
return []
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function portOpen(port) {
|
|
225
|
+
return new Promise((resolve) => {
|
|
226
|
+
const socket = net.connect({ host: '127.0.0.1', port, timeout: 800 })
|
|
227
|
+
socket.once('connect', () => { socket.destroy(); resolve(true) })
|
|
228
|
+
socket.once('timeout', () => { socket.destroy(); resolve(false) })
|
|
229
|
+
socket.once('error', () => resolve(false))
|
|
230
|
+
})
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function probe() {
|
|
234
|
+
const pids = listDshPids()
|
|
235
|
+
return { pids, bridge: await portOpen(bridgePort), running: pids.length > 0 }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// ---------- 运行状态 ----------
|
|
239
|
+
// 进程探测快照:轮询时刷新,GET /status 直接读它(避免每次请求都 spawn tasklist)
|
|
240
|
+
let lastProbe = { at: 0, value: null }
|
|
241
|
+
|
|
242
|
+
async function refreshProbe() {
|
|
243
|
+
try {
|
|
244
|
+
lastProbe = { at: Date.now(), value: await probe() }
|
|
245
|
+
} catch (error) {
|
|
246
|
+
// 探测失败时故意不更新时间戳,让 probeAgeSeconds 持续变大以暴露故障
|
|
247
|
+
log('探测失败:' + (error?.message ?? String(error)))
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
let child = null
|
|
252
|
+
let childGeneration = 0
|
|
253
|
+
let restarts = 0
|
|
254
|
+
let stoppingForRestart = false
|
|
255
|
+
let restarting = false
|
|
256
|
+
let launchFailed = false
|
|
257
|
+
const startedAt = new Date()
|
|
258
|
+
|
|
259
|
+
function persist(extra = {}) {
|
|
260
|
+
try {
|
|
261
|
+
fs.writeFileSync(stateFile, JSON.stringify({
|
|
262
|
+
pid: process.pid,
|
|
263
|
+
exe: exePath,
|
|
264
|
+
controlPort,
|
|
265
|
+
bridgePort,
|
|
266
|
+
restarts,
|
|
267
|
+
childPid: child?.pid ?? null,
|
|
268
|
+
platform: process.platform,
|
|
269
|
+
startedAt: startedAt.toISOString(),
|
|
270
|
+
updatedAt: new Date().toISOString(),
|
|
271
|
+
...extra,
|
|
272
|
+
}, null, 2))
|
|
273
|
+
} catch { /* 忽略 */ }
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// ---------- 升级检测 ----------
|
|
277
|
+
// ---------- 升级检测(依据 electron-updater 的真实行为) ----------
|
|
278
|
+
// 1) 安装器进程的可执行路径位于 updater 缓存目录 → 正在安装(最可靠)
|
|
279
|
+
// 2) pending 里的版本高于已安装版本 → 确实有待装更新
|
|
280
|
+
// 3) 仅"pending 存在"不可信:可能是安装完的残留(本机实测就有一个 10/31 的残留)
|
|
281
|
+
|
|
282
|
+
function updaterCacheDir() {
|
|
283
|
+
const exeDir = exePath ? path.dirname(exePath) : ''
|
|
284
|
+
let cacheName = ''
|
|
285
|
+
try {
|
|
286
|
+
const yml = fs.readFileSync(path.join(exeDir, 'resources', 'app-update.yml'), 'utf8')
|
|
287
|
+
cacheName = (/updaterCacheDirName:\s*['"]?([^'"\n]+)/u.exec(yml)?.[1] ?? '').trim()
|
|
288
|
+
} catch { /* 没有配置就放弃 */ }
|
|
289
|
+
if (!cacheName) return null
|
|
290
|
+
const base = process.platform === 'win32' ? process.env.LOCALAPPDATA : path.join(os.homedir(), '.cache')
|
|
291
|
+
return base ? path.join(base, cacheName) : null
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function installerProcessRunning(cacheDir) {
|
|
295
|
+
// wmic 已不可用:退化为"进程名像安装包"的判断
|
|
296
|
+
// 安装器文件名形如 deepseek-harness-0.2.1-rc.5-win-x64.exe
|
|
297
|
+
try {
|
|
298
|
+
return listProcessNames().some((name) => /^deepseek[-_]?harness.*\.exe$/iu.test(name) && !/^DeepSeek Harness\.exe$/iu.test(name))
|
|
299
|
+
} catch {
|
|
300
|
+
return false
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
function pendingPackage(cacheDir) {
|
|
306
|
+
try {
|
|
307
|
+
const info = JSON.parse(fs.readFileSync(path.join(cacheDir, 'pending', 'update-info.json'), 'utf8'))
|
|
308
|
+
const file = path.join(cacheDir, 'pending', String(info.fileName ?? ''))
|
|
309
|
+
const stat = fs.statSync(file)
|
|
310
|
+
return { fileName: String(info.fileName ?? ''), ageSeconds: Math.round((Date.now() - stat.mtimeMs) / 1000) }
|
|
311
|
+
} catch {
|
|
312
|
+
return null
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
let installedVersionCache = null
|
|
317
|
+
function installedVersion() {
|
|
318
|
+
if (installedVersionCache !== null) return installedVersionCache
|
|
319
|
+
// 纯 Node 读取:app.asar 头部的 package.json(含 rc 后缀,如 0.2.1-rc.5)
|
|
320
|
+
try {
|
|
321
|
+
const asar = path.join(exePath ? path.dirname(exePath) : '', 'resources', 'app.asar')
|
|
322
|
+
const fd = fs.openSync(asar, 'r')
|
|
323
|
+
try {
|
|
324
|
+
const head = Buffer.alloc(16)
|
|
325
|
+
fs.readSync(fd, head, 0, 16, 0)
|
|
326
|
+
const headerSize = head.readUInt32LE(12)
|
|
327
|
+
const headerBuf = Buffer.alloc(headerSize)
|
|
328
|
+
fs.readSync(fd, headerBuf, 0, headerSize, 16)
|
|
329
|
+
const header = JSON.parse(headerBuf.toString('utf8'))
|
|
330
|
+
const entry = header?.files?.['package.json']
|
|
331
|
+
if (entry && entry.size > 0) {
|
|
332
|
+
const buf = Buffer.alloc(entry.size)
|
|
333
|
+
fs.readSync(fd, buf, 0, entry.size, 16 + headerSize + Number(entry.offset))
|
|
334
|
+
const json = JSON.parse(buf.toString('utf8'))
|
|
335
|
+
if (json.version) installedVersionCache = String(json.version).trim()
|
|
336
|
+
}
|
|
337
|
+
} finally {
|
|
338
|
+
fs.closeSync(fd)
|
|
339
|
+
}
|
|
340
|
+
} catch {
|
|
341
|
+
installedVersionCache = null
|
|
342
|
+
}
|
|
343
|
+
// 兜底:注册表里的 DisplayVersion(reg.exe,不是 PowerShell)
|
|
344
|
+
if (!installedVersionCache) {
|
|
345
|
+
try {
|
|
346
|
+
const out = spawnSync('reg', ['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall', '/s', '/f', 'DeepSeek Harness', '/v', 'DisplayVersion'], { encoding: 'utf8', timeout: 5000, windowsHide: true })
|
|
347
|
+
installedVersionCache = (/DisplayVersion\s+REG_SZ\s+(\S+)/u.exec(out.stdout ?? '')?.[1] ?? '').trim() || null
|
|
348
|
+
} catch {
|
|
349
|
+
installedVersionCache = null
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
return installedVersionCache
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async function waitForUpgrade() {
|
|
356
|
+
const cacheDir = updaterCacheDir()
|
|
357
|
+
let announced = false
|
|
358
|
+
for (let i = 0; i < 900; i += 1) {
|
|
359
|
+
const exeMissing = exePath ? !fs.existsSync(exePath) : false
|
|
360
|
+
const pending = cacheDir ? pendingPackage(cacheDir) : null
|
|
361
|
+
const verdict = decideUpgrade({
|
|
362
|
+
installerRunning: cacheDir ? installerProcessRunning(cacheDir) : false,
|
|
363
|
+
pendingFileName: pending?.fileName ?? null,
|
|
364
|
+
installedVersion: installedVersion(),
|
|
365
|
+
pendingAgeSeconds: pending?.ageSeconds ?? null,
|
|
366
|
+
})
|
|
367
|
+
if (!verdict.upgrading && !exeMissing) {
|
|
368
|
+
if (announced) log('升级结束(' + verdict.reason + '),继续拉起流程')
|
|
369
|
+
return { upgrading: announced, reason: verdict.reason }
|
|
370
|
+
}
|
|
371
|
+
if (!announced) {
|
|
372
|
+
announced = true
|
|
373
|
+
log('检测到升级中(' + (exeMissing ? 'exe-missing' : verdict.reason) + '),先等待安装完成')
|
|
374
|
+
}
|
|
375
|
+
await new Promise((resolve) => setTimeout(resolve, 2000))
|
|
376
|
+
}
|
|
377
|
+
log('升级检测超时(30 分钟),按未升级处理')
|
|
378
|
+
return { upgrading: true, reason: 'timeout' }
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function launch() {
|
|
382
|
+
if (!exePath) {
|
|
383
|
+
if (!launchFailed) {
|
|
384
|
+
launchFailed = true
|
|
385
|
+
log('找不到 DSH 可执行文件,停止自动拉起(用 --exe 指定或检查安装位置)')
|
|
386
|
+
}
|
|
387
|
+
return null
|
|
388
|
+
}
|
|
389
|
+
launchFailed = false
|
|
390
|
+
log(`启动 DSH:${exePath}`)
|
|
391
|
+
const generation = ++childGeneration
|
|
392
|
+
// POSIX:detached = setsid,让 DSH 拥有独立会话/进程组,
|
|
393
|
+
// 这样"杀 DSH 所在组"不会连带杀掉守护进程;Windows 保持原样(避免多弹控制台)
|
|
394
|
+
const spawned = spawn(exePath, [], {
|
|
395
|
+
stdio: 'ignore',
|
|
396
|
+
windowsHide: false,
|
|
397
|
+
detached: process.platform !== 'win32',
|
|
398
|
+
})
|
|
399
|
+
spawned.on('error', (error) => {
|
|
400
|
+
log(`启动失败:${error.code ?? error.message}`)
|
|
401
|
+
launchFailed = true
|
|
402
|
+
})
|
|
403
|
+
spawned.on('exit', (code, signal) => {
|
|
404
|
+
if (generation !== childGeneration) return // 旧子进程的迟到事件,忽略
|
|
405
|
+
log(`DSH 退出:code=${code} signal=${signal}${stoppingForRestart ? '(主动重启)' : ''}`)
|
|
406
|
+
child = null
|
|
407
|
+
const stopping = stoppingForRestart
|
|
408
|
+
if (!stopping) restarts += 1
|
|
409
|
+
const plan = planAfterExit({ stopping, pausedUntil, restarts: Math.max(1, restarts) })
|
|
410
|
+
if (plan.action === 'skip') {
|
|
411
|
+
log('不重新拉起:' + plan.reason)
|
|
412
|
+
return
|
|
413
|
+
}
|
|
414
|
+
const delay = plan.delayMs
|
|
415
|
+
log(`${delay}ms 后重新拉起(第 ${restarts} 次)`)
|
|
416
|
+
setTimeout(async () => {
|
|
417
|
+
if (child) return
|
|
418
|
+
await waitForUpgrade()
|
|
419
|
+
if (pausedUntil > Date.now()) { log('暂停中,不拉起 DSH'); return }
|
|
420
|
+
if (!child) { child = launch(); persist() }
|
|
421
|
+
}, delay)
|
|
422
|
+
})
|
|
423
|
+
// 稳定运行 60 秒后把退避计数归零,避免一次崩溃永久 30 秒退避
|
|
424
|
+
const timer = setTimeout(() => {
|
|
425
|
+
if (generation === childGeneration && child) restarts = 0
|
|
426
|
+
}, 60_000)
|
|
427
|
+
timer.unref?.()
|
|
428
|
+
return spawned
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
async function killDsh() {
|
|
432
|
+
const pids = listDshPids()
|
|
433
|
+
if (pids.length === 0) return
|
|
434
|
+
log('终止 DSH 进程:' + pids.join(','))
|
|
435
|
+
for (const pid of pids) {
|
|
436
|
+
try { process.kill(pid) } catch { /* 已退出 */ }
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
const deadline = Date.now() + 10_000
|
|
440
|
+
while (Date.now() < deadline && listDshPids().length > 0) {
|
|
441
|
+
await new Promise((resolve) => setTimeout(resolve, 300))
|
|
442
|
+
}
|
|
443
|
+
for (const pid of listDshPids()) {
|
|
444
|
+
try {
|
|
445
|
+
if (process.platform === 'win32') spawnSync('taskkill', ['/F', '/PID', String(pid)], { windowsHide: true })
|
|
446
|
+
else process.kill(pid, 'SIGKILL')
|
|
447
|
+
} catch { /* 已退出 */ }
|
|
448
|
+
}
|
|
449
|
+
const portDeadline = Date.now() + 60_000
|
|
450
|
+
while (Date.now() < portDeadline && await portOpen(bridgePort)) {
|
|
451
|
+
await new Promise((resolve) => setTimeout(resolve, 500))
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* 是否已经「全空闲」:
|
|
457
|
+
* - 活动信标(键盘/指针上报)静默 ≥ 3 秒 → 没人在输入
|
|
458
|
+
* - 最近被改动的会话文件静默 ≥ 3 秒 → 没有会话在产出(agent 干活时会持续写会话)
|
|
459
|
+
* 两个条件同时满足才算空闲。
|
|
460
|
+
*/
|
|
461
|
+
// ---------- 控制接口 ----------
|
|
462
|
+
// pausedUntil > 0 时暂停自动拉起(给用户关机/维护用)
|
|
463
|
+
let pausedUntil = 0
|
|
464
|
+
|
|
465
|
+
/** 暂停到期后:若 DSH 不在运行且没有新的暂停,就拉起它 */
|
|
466
|
+
function schedulePauseExpiry(minutes) {
|
|
467
|
+
const timer = setTimeout(async () => {
|
|
468
|
+
if (pausedUntil > Date.now()) return // 期间又被延长了
|
|
469
|
+
const info = await probe()
|
|
470
|
+
if (info.running) { log('暂停到期,DSH 仍在运行'); return }
|
|
471
|
+
log('暂停到期,拉起 DSH')
|
|
472
|
+
if (!child) { child = launch(); persist() }
|
|
473
|
+
}, minutes * 60_000)
|
|
474
|
+
timer.unref?.()
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function cors(res) {
|
|
478
|
+
// 客户端插件运行在 DSH 页面里(http://127.0.0.1:<随机端口>),需要允许跨端口调用
|
|
479
|
+
res.setHeader('access-control-allow-origin', '*')
|
|
480
|
+
res.setHeader('access-control-allow-methods', 'GET, POST, OPTIONS')
|
|
481
|
+
res.setHeader('access-control-allow-headers', 'content-type')
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// 重启流程(顺序/超时/并发/异常复位都在 lib/restart-flow.mjs,可单测)
|
|
485
|
+
const restartFlow = createRestartFlow({
|
|
486
|
+
probe,
|
|
487
|
+
killDsh,
|
|
488
|
+
launch,
|
|
489
|
+
waitForUpgrade,
|
|
490
|
+
setRestarting: (value) => { restarting = value },
|
|
491
|
+
setStopping: (value) => { stoppingForRestart = value },
|
|
492
|
+
setChild: (value) => { child = value },
|
|
493
|
+
persist,
|
|
494
|
+
log,
|
|
495
|
+
});
|
|
496
|
+
const restart = () => {
|
|
497
|
+
// 并发请求交给流程层返回 busy,不重复累加计数
|
|
498
|
+
if (restartFlow.inFlight) return restartFlow.restart();
|
|
499
|
+
restarts += 1;
|
|
500
|
+
return restartFlow.restart();
|
|
501
|
+
};
|
|
502
|
+
|
|
503
|
+
function startControl() {
|
|
504
|
+
const server = http.createServer(async (req, res) => {
|
|
505
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
506
|
+
cors(res)
|
|
507
|
+
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
|
|
508
|
+
const paused = pausedUntil > Date.now()
|
|
509
|
+
// 授权模型:调用者必须是插件宿主进程本身;并断言目标进程树包含该宿主
|
|
510
|
+
if (req.method === 'POST') {
|
|
511
|
+
const hostPid = listeningPid(bridgePort)
|
|
512
|
+
const srcPid = await peerPidForPortRetry(req.socket?.remotePort ?? 0, controlPort)
|
|
513
|
+
const info = await probe()
|
|
514
|
+
const verdict = authorizeRestart({ srcPid, hostPid, pids: info.pids ?? [] })
|
|
515
|
+
if (!verdict.ok) {
|
|
516
|
+
log('拒绝变更操作:原因=' + verdict.reason + ' 来源PID=' + (srcPid ?? '未知') + ' 插件宿主=' + (hostPid ?? '未发现') + ' 目标根=' + (verdict.rootPid ?? '未知') + ' 树内进程数=' + (verdict.treeSize ?? (info.pids ?? []).length))
|
|
517
|
+
res.writeHead(403, { 'content-type': 'application/json; charset=utf-8' })
|
|
518
|
+
res.end(JSON.stringify({ error: '拒绝:' + verdict.reason }))
|
|
519
|
+
return
|
|
520
|
+
}
|
|
521
|
+
log('授权通过:来源PID=' + srcPid + ' 插件宿主=' + hostPid + ' 目标根=' + verdict.rootPid + ' 树内进程数=' + verdict.treeSize)
|
|
522
|
+
}
|
|
523
|
+
if (url.pathname === '/health') {
|
|
524
|
+
// 轻量探活:不 spawn 任何进程、不读文件
|
|
525
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
|
|
526
|
+
res.end(JSON.stringify({ ok: true, pid: process.pid, uptimeSeconds: Math.round(process.uptime()) }))
|
|
527
|
+
return
|
|
528
|
+
}
|
|
529
|
+
if (url.pathname === '/status') {
|
|
530
|
+
// 读缓存快照(轮询每 2 秒刷新);首次请求若还没有快照,补一次实时探测
|
|
531
|
+
if (!lastProbe.value) await refreshProbe()
|
|
532
|
+
const age = lastProbe.at ? Math.round((Date.now() - lastProbe.at) / 1000) : null
|
|
533
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
|
|
534
|
+
res.end(JSON.stringify({
|
|
535
|
+
daemon: { pid: process.pid, restarts, restarting, exe: exePath },
|
|
536
|
+
...(lastProbe.value ?? { pids: [], bridge: false, running: false }),
|
|
537
|
+
probeAgeSeconds: age,
|
|
538
|
+
lastProbeAt: lastProbe.at ? localIso(new Date(lastProbe.at)) : null,
|
|
539
|
+
probeStale: age === null || age > 10,
|
|
540
|
+
paused,
|
|
541
|
+
pausedSecondsLeft: paused ? Math.round((pausedUntil - Date.now()) / 1000) : 0,
|
|
542
|
+
}, null, 2))
|
|
543
|
+
return
|
|
544
|
+
}
|
|
545
|
+
if (url.pathname === '/pause') {
|
|
546
|
+
const minutes = Number(url.searchParams.get('minutes'))
|
|
547
|
+
if (!Number.isFinite(minutes) || minutes <= 0 || minutes > MAX_PAUSE_MINUTES) {
|
|
548
|
+
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' });
|
|
549
|
+
res.end(JSON.stringify({ error: 'minutes 必须是 1..' + MAX_PAUSE_MINUTES + ' 的正整数,不支持永久暂停' }));
|
|
550
|
+
return
|
|
551
|
+
}
|
|
552
|
+
pausedUntil = Date.now() + minutes * 60_000
|
|
553
|
+
log(`暂停自动拉起 ${minutes} 分钟;到期后会检查 DSH 是否还在`)
|
|
554
|
+
schedulePauseExpiry(minutes)
|
|
555
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
|
|
556
|
+
res.end(JSON.stringify({ paused: true, minutes }))
|
|
557
|
+
return
|
|
558
|
+
}
|
|
559
|
+
if (url.pathname === '/resume') {
|
|
560
|
+
pausedUntil = 0
|
|
561
|
+
log('恢复自动拉起')
|
|
562
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
|
|
563
|
+
res.end(JSON.stringify({ paused: false }))
|
|
564
|
+
return
|
|
565
|
+
}
|
|
566
|
+
if (url.pathname === '/stop') {
|
|
567
|
+
log('收到停止指令:守护进程退出,不再拉起 DSH')
|
|
568
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
|
|
569
|
+
res.end(JSON.stringify({ stopped: true }))
|
|
570
|
+
setTimeout(() => process.exit(0), 300)
|
|
571
|
+
return
|
|
572
|
+
}
|
|
573
|
+
if (url.pathname === '/restart-now') {
|
|
574
|
+
// 只做"杀+起",是否该重启由插件策略层判断
|
|
575
|
+
res.writeHead(202, { 'content-type': 'application/json; charset=utf-8' })
|
|
576
|
+
res.end(JSON.stringify({ accepted: true }))
|
|
577
|
+
void restart().catch((error) => log('重启异常:' + error.message))
|
|
578
|
+
return
|
|
579
|
+
}
|
|
580
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
|
|
581
|
+
res.end('not found\n')
|
|
582
|
+
})
|
|
583
|
+
server.on('error', (error) => {
|
|
584
|
+
if (error.code === 'EADDRINUSE') {
|
|
585
|
+
log('控制端口已被占用,说明已有守护进程在运行;本实例退出(单实例保护)')
|
|
586
|
+
process.exit(0)
|
|
587
|
+
}
|
|
588
|
+
log(`控制端口错误:${error.code}`)
|
|
589
|
+
process.exit(1)
|
|
590
|
+
})
|
|
591
|
+
server.listen(controlPort, '127.0.0.1', () => log(`控制接口:http://127.0.0.1:${controlPort}/status`))
|
|
592
|
+
return server
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// 进程级兜底:崩溃必须留痕,否则排障时看不到任何线索
|
|
596
|
+
process.on('uncaughtException', (error) => {
|
|
597
|
+
log('未捕获异常:' + (error && error.stack ? error.stack : String(error)))
|
|
598
|
+
process.exit(1)
|
|
599
|
+
})
|
|
600
|
+
process.on('unhandledRejection', (reason) => {
|
|
601
|
+
log('未处理的 Promise 拒绝:' + (reason && reason.stack ? reason.stack : String(reason)))
|
|
602
|
+
})
|
|
603
|
+
|
|
604
|
+
/** 查某个 PID 的映像名(tasklist,无需 PowerShell) */
|
|
605
|
+
function processNameOf(pid) {
|
|
606
|
+
try {
|
|
607
|
+
if (process.platform === 'win32') {
|
|
608
|
+
const out = spawnSync('tasklist', ['/FI', 'PID eq ' + pid, '/FO', 'CSV', '/NH'], {
|
|
609
|
+
encoding: 'utf8', windowsHide: true, timeout: 5000,
|
|
610
|
+
})
|
|
611
|
+
return String(out.stdout ?? '').match(/^"([^"]+)"/u)?.[1] ?? null
|
|
612
|
+
}
|
|
613
|
+
const out = spawnSync('ps', ['-p', String(pid), '-o', 'comm='], { encoding: 'utf8', timeout: 5000 })
|
|
614
|
+
return String(out.stdout ?? '').trim() || null
|
|
615
|
+
} catch {
|
|
616
|
+
return null
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
// 启动自检:如果自己落在 DSH 的进程树里(会被 taskkill /T 连带杀掉),
|
|
621
|
+
// 用 WMI(Windows)或 detached(Unix)重新拉起一份,然后退出。
|
|
622
|
+
function detachSelfIfNeeded() {
|
|
623
|
+
if (has('detached-once')) return false
|
|
624
|
+
const dshPids = listDshPids()
|
|
625
|
+
const parentName = processNameOf(process.ppid)
|
|
626
|
+
// 直接父进程是 DSH,或父进程是 shell(说明可能是 DSH → shell → 本进程的多级链)
|
|
627
|
+
const shellLike = parentName ? /^(cmd|powershell|pwsh|conhost|wscript|bash|sh|zsh)$/iu.test(parentName.replace(/\.exe$/iu, '')) : false
|
|
628
|
+
const insideDsh = dshPids.includes(process.ppid) || shellLike
|
|
629
|
+
if (!insideDsh) return false
|
|
630
|
+
log('检测到父进程 ' + process.ppid + '(' + (parentName ?? '未知') + ')属于 DSH 或 shell,自我脱离')
|
|
631
|
+
const scriptPath = process.argv[1]
|
|
632
|
+
const result = startHidden({ command: process.execPath, args: [scriptPath, '--detached-once'], stateDir })
|
|
633
|
+
if (result.ok) {
|
|
634
|
+
log('已用 ' + result.how + ' 方式重新拉起(PID ' + (result.pid ?? '未知') + '),本实例退出')
|
|
635
|
+
process.exit(0)
|
|
636
|
+
}
|
|
637
|
+
log('自我脱离失败(' + (result.error ?? '未知原因') + '),继续在当前树内运行')
|
|
638
|
+
return false
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
// ---------- 主流程 ----------
|
|
642
|
+
if (has('status')) {
|
|
643
|
+
const info = await probe()
|
|
644
|
+
console.log(JSON.stringify({
|
|
645
|
+
exe: exePath,
|
|
646
|
+
...info,
|
|
647
|
+
probeAgeSeconds: 0,
|
|
648
|
+
lastProbeAt: localIso(),
|
|
649
|
+
stateFile,
|
|
650
|
+
logFile,
|
|
651
|
+
}, null, 2))
|
|
652
|
+
process.exit(0)
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
detachSelfIfNeeded()
|
|
656
|
+
|
|
657
|
+
if (has('restart')) {
|
|
658
|
+
console.error('命令行不能直接重启:守护进程只接受插件宿主进程(策略层)的指令。')
|
|
659
|
+
console.error('请在重启页面操作,或调用插件的 /dsh_homing/restart/queue。')
|
|
660
|
+
process.exit(1)
|
|
661
|
+
}
|
|
662
|
+
else {
|
|
663
|
+
fs.writeFileSync(pidFile, String(process.pid))
|
|
664
|
+
log('守护进程启动:pid=' + process.pid + ' 平台=' + process.platform + ' exe=' + (exePath ?? '未找到'))
|
|
665
|
+
const cleanup = () => { try { fs.rmSync(pidFile, { force: true }) } catch { /* 忽略 */ } }
|
|
666
|
+
process.on('SIGINT', () => { log('收到 SIGINT,退出'); cleanup(); process.exit(0) })
|
|
667
|
+
process.on('SIGTERM', () => { log('收到 SIGTERM,退出'); cleanup(); process.exit(0) })
|
|
668
|
+
process.on('exit', cleanup)
|
|
669
|
+
|
|
670
|
+
startControl()
|
|
671
|
+
const info = await probe()
|
|
672
|
+
if (info.running) {
|
|
673
|
+
log('DSH 已在运行(PID ' + info.pids.join(',') + '),接管监视(' + pollMs / 1000 + ' 秒轮询)')
|
|
674
|
+
setInterval(async () => {
|
|
675
|
+
await refreshProbe()
|
|
676
|
+
if (stoppingForRestart || restarting || launchFailed) return
|
|
677
|
+
const current = await probe()
|
|
678
|
+
if (!current.running) {
|
|
679
|
+
restarts += 1
|
|
680
|
+
log('检测到 DSH 已退出(外部拉起),准备拉起')
|
|
681
|
+
await waitForUpgrade()
|
|
682
|
+
if (pausedUntil > Date.now()) { log('暂停中,不拉起 DSH'); return }
|
|
683
|
+
if (!child) { child = launch(); persist() }
|
|
684
|
+
}
|
|
685
|
+
}, pollMs)
|
|
686
|
+
} else {
|
|
687
|
+
log('未发现运行中的 DSH,等待(可能是升级中)后拉起')
|
|
688
|
+
await waitForUpgrade()
|
|
689
|
+
if (pausedUntil > Date.now()) { log('暂停中,不拉起 DSH') } else { child = launch(); persist() }
|
|
690
|
+
}
|
|
691
|
+
}
|