@napuketto/cli 0.6.24 → 0.6.27
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 +3 -2
- package/dist/index.mjs +721 -130
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.mjs
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import process from "node:process";
|
|
3
|
-
import { ConfigBase, ConfigError, EXIT_CONFIG_INVALID, configError, createLogger, errorMessage, hasNumberProp, hasStringProp, isRecord, kernelError, parseLogConfig, parseToml, resolveConfigPath, resolveDataRoot, stringifyToml } from "@napuketto/kernel";
|
|
3
|
+
import { CONFIG_FILE_MODE, ConfigBase, ConfigError, EXIT_CONFIG_INVALID, configError, createLogger, errorMessage, hasNumberProp, hasStringProp, isRecord, kernelError, parseLogConfig, parseToml, resolveConfigPath, resolveDataRoot, stringifyToml } from "@napuketto/kernel";
|
|
4
4
|
import { Command } from "commander";
|
|
5
|
-
import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
6
6
|
import { access, readFile, writeFile } from "node:fs/promises";
|
|
7
|
-
import
|
|
8
|
-
import { QR_LINE_PREFIX, checkInstanceLock, defaultStubDir, isNativeNoiseLine, launchSelfHost, removeStopSentinel, resolveQqFiles, watchStopSentinel, writeStopSentinel } from "@napuketto/loader";
|
|
7
|
+
import { basename, dirname, extname, isAbsolute, join, resolve, sep } from "node:path";
|
|
8
|
+
import { CMDLINE_PROBE_SUPPORTED, QR_LINE_PREFIX, checkInstanceLock, defaultStubDir, isNativeNoiseLine, launchSelfHost, normalizeCmdline, readCmdlineForPid, removeAccountStopSentinel, removeStopSentinel, resolveQqFiles, watchStopSentinel, writeAccountStopSentinel, writeStopSentinel } from "@napuketto/loader";
|
|
9
9
|
import { spawn } from "node:child_process";
|
|
10
|
-
import {
|
|
10
|
+
import { randomUUID } from "node:crypto";
|
|
11
11
|
import { fileURLToPath } from "node:url";
|
|
12
|
+
import { StringDecoder } from "node:string_decoder";
|
|
12
13
|
import { encode } from "uqr";
|
|
13
14
|
// src/config/schema.ts
|
|
14
15
|
/**
|
|
@@ -18,8 +19,8 @@ import { encode } from "uqr";
|
|
|
18
19
|
* 2026-08-08 结构拍板:**一个 QQ 账号一个 [[accounts]] 段,协议与通信配置嵌在
|
|
19
20
|
* 账号内**([accounts.onebot11] / [accounts.satori]);账号必填(至少一个)。
|
|
20
21
|
* 协议段为宽松对象,装配时由对应协议包的 zod schema 严格校验;
|
|
21
|
-
* `config validate` 例外(见 protocol-validate.ts
|
|
22
|
-
*
|
|
22
|
+
* `config validate` / `config apply` 例外(见 protocol-validate.ts:两条路径承诺与
|
|
23
|
+
* 装配同 schema,否则「校验/apply 通过但启动 78」,故仅在这两处懒加载 adapter 补校验)。
|
|
23
24
|
* 全部校验错误为 ConfigError(2026-10-25 嵌入式退出码契约:CLI exit 78 一族,
|
|
24
25
|
* 内联与文件两形态共用本校验器)。
|
|
25
26
|
*/
|
|
@@ -33,6 +34,21 @@ const DEFAULT_NATIVE_MEDIA_PATCH = true;
|
|
|
33
34
|
const DEFAULT_RESTART_DELAY_MS = 2e3;
|
|
34
35
|
/** QQ 号格式:纯数字 5-11 位(QQ 号合法范围,勿写死 11 位)。 */
|
|
35
36
|
const QQ_IN_FORMAT_RE = /^\d{5,11}$/;
|
|
37
|
+
/** 判定 QQ 号是否非法(undefined = 合法)。主配置校验与 CLI `-q` 入口共用。 */
|
|
38
|
+
function qqInvalidReason(qq) {
|
|
39
|
+
if (!QQ_IN_FORMAT_RE.test(qq)) return "format";
|
|
40
|
+
if (RESERVED_PLACEHOLDER_QINS.some((placeholder) => placeholder === qq)) return "placeholder";
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* CLI `-q/--qq` 入口校验(复用主配置 QQ 号规则):非法格式 / 模板占位值 /
|
|
44
|
+
* 路径穿越值一律 ConfigError(exit 78 一族)。返回原值便于链式使用。
|
|
45
|
+
*/
|
|
46
|
+
function parseCliQq(qq) {
|
|
47
|
+
const reason = qqInvalidReason(qq);
|
|
48
|
+
if (reason === "format") throw configError(`-q/--qq 参数 "${qq}" 非法:必须是 5-11 位纯数字 QQ 号`);
|
|
49
|
+
if (reason === "placeholder") throw configError(`-q/--qq 参数 "${qq}" 是模板占位值,请传入真实 QQ 号`);
|
|
50
|
+
return qq;
|
|
51
|
+
}
|
|
36
52
|
/** 解析账号内协议段(宽松对象,装配时由 zod schema 严格校验)。 */
|
|
37
53
|
function parseProtocolSection(raw, key) {
|
|
38
54
|
const section = raw[key];
|
|
@@ -73,7 +89,13 @@ function parseAccounts(raw) {
|
|
|
73
89
|
if (raw["accounts"] === void 0) throw configError("主配置缺少 accounts(必须至少一个账号);首次启动已生成模板,请编辑后重试");
|
|
74
90
|
if (!Array.isArray(raw["accounts"]) || raw["accounts"].length === 0) throw configError("主配置 accounts 必须是非空数组(至少一个 QQ 账号);首次启动已生成模板,请编辑后重试");
|
|
75
91
|
const accounts = [];
|
|
76
|
-
|
|
92
|
+
const seen = /* @__PURE__ */ new Set();
|
|
93
|
+
for (const item of raw["accounts"]) {
|
|
94
|
+
const account = parseAccount(item);
|
|
95
|
+
if (seen.has(account.qq)) throw configError(`主配置账号 qq 重复: "${account.qq}"(一个 QQ 号只允许一个 [[accounts]] 段)`);
|
|
96
|
+
seen.add(account.qq);
|
|
97
|
+
accounts.push(account);
|
|
98
|
+
}
|
|
77
99
|
return accounts;
|
|
78
100
|
}
|
|
79
101
|
/** 账号 qq 必填校验(非空字符串)。 */
|
|
@@ -85,8 +107,9 @@ function parseAccountQq(raw) {
|
|
|
85
107
|
}
|
|
86
108
|
/** qq 格式与占位值校验(5-11 位纯数字;模板占位号显式指路不静默)。 */
|
|
87
109
|
function assertValidQqFormat(qq) {
|
|
88
|
-
|
|
89
|
-
if (
|
|
110
|
+
const reason = qqInvalidReason(qq);
|
|
111
|
+
if (reason === "format") throw configError("主配置账号 qq 必须是 5-11 位纯数字 QQ 号");
|
|
112
|
+
if (reason === "placeholder") throw configError(`主配置账号 qq "${qq}" 是模板占位值,请编辑配置文件填入真实 QQ 号后再启动`);
|
|
90
113
|
}
|
|
91
114
|
/** 账号 enabled 可选校验(缺省 = 启用;显式给值必须是布尔)。 */
|
|
92
115
|
function applyAccountEnabled(out, enabled) {
|
|
@@ -185,9 +208,28 @@ const LEGACY_INLINE_CONFIG_ENV = "NAPKETTO_CONFIG_JSON";
|
|
|
185
208
|
* 回退文件形态)。
|
|
186
209
|
*/
|
|
187
210
|
function readInlineConfigText() {
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
211
|
+
return readInlineEnvEntry()?.text;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* 实际命中的内联配置 env 键名(新前缀优先、旧前缀回退;未生效 → undefined)。
|
|
215
|
+
* 来源日志据此输出真实键名,避免旧前缀兼容期日志写死新名误导排查。
|
|
216
|
+
*/
|
|
217
|
+
function inlineConfigEnvName() {
|
|
218
|
+
return readInlineEnvEntry()?.key;
|
|
219
|
+
}
|
|
220
|
+
/** 内联 env 决议(精确键读取;新前缀存在但为空时不回退旧前缀,与历史口径一致)。 */
|
|
221
|
+
function readInlineEnvEntry() {
|
|
222
|
+
const primary = process.env[INLINE_CONFIG_ENV];
|
|
223
|
+
if (primary !== void 0) return primary.trim() === "" ? void 0 : {
|
|
224
|
+
key: INLINE_CONFIG_ENV,
|
|
225
|
+
text: primary
|
|
226
|
+
};
|
|
227
|
+
const legacy = process.env[LEGACY_INLINE_CONFIG_ENV];
|
|
228
|
+
if (legacy === void 0 || legacy.trim() === "") return;
|
|
229
|
+
return {
|
|
230
|
+
key: LEGACY_INLINE_CONFIG_ENV,
|
|
231
|
+
text: legacy
|
|
232
|
+
};
|
|
191
233
|
}
|
|
192
234
|
/** 内联是否生效(boot/装配链决定「不碰文件」的判定口径,与 readInlineConfigText 同源)。 */
|
|
193
235
|
function isInlineConfigActive() {
|
|
@@ -237,14 +279,14 @@ function parseInlineConfig(text) {
|
|
|
237
279
|
}
|
|
238
280
|
// src/config/protocol-validate.ts
|
|
239
281
|
/**
|
|
240
|
-
* 协议段严格校验(`config validate`
|
|
282
|
+
* 协议段严格校验(`config validate` / `config apply` 共用)。
|
|
241
283
|
*
|
|
242
284
|
* 主配置解析(schema.ts)刻意保持协议段为宽松对象:普通启动路径不把协议包
|
|
243
285
|
* 拉进 CLI 进程,字段级校验由 loader 装配时用各协议自己的 zod schema 完成。
|
|
244
286
|
* 但 `config validate` 的承诺是「与运行时同一校验器落地」——只做 `isRecord`
|
|
245
287
|
* 浅校验会让 `httpServers = "not-an-array"` 报「配置合法」,真正启动却以 78
|
|
246
|
-
*
|
|
247
|
-
* adapter
|
|
288
|
+
* 退出;`config apply` 若跳过这层,则会把非法协议段写进主配置。因此两条路径
|
|
289
|
+
* 懒加载 adapter 补校验(普通 CLI 启动与 supervisor 不引入协议包)。
|
|
248
290
|
*
|
|
249
291
|
* 空段与 loader 装配语义一致:`{}` = 不启用该协议,跳过校验(kurobot 的
|
|
250
292
|
* url 必填只在段非空时生效)。
|
|
@@ -438,6 +480,8 @@ port = 3001
|
|
|
438
480
|
# # pingIntervalMs = 15000 # 可选:应用层心跳间隔(毫秒,须 < 30000)
|
|
439
481
|
# # chatTemplate = "[{player}] {content}" # 游戏聊天渲染模板
|
|
440
482
|
# # joinTemplate = "{player} 加入了服务器" # 玩家进服模板
|
|
483
|
+
# # leaveTemplate = "{player} 离开了服务器" # 玩家退服模板
|
|
484
|
+
# # deathTemplate = "{player} {message}" # 玩家死亡模板(空消息显示「死亡了」)
|
|
441
485
|
|
|
442
486
|
# ------------------------------------------------------------
|
|
443
487
|
# Milky 协议(P0)
|
|
@@ -452,8 +496,6 @@ port = 3001
|
|
|
452
496
|
# # eventModes = ["sse", "ws"] # /event 允许的连接形态
|
|
453
497
|
# # webhooks = [] # 可选:额外事件推送地址(WebHook POST)
|
|
454
498
|
# # cacheDir = "cache" # 可选:发送远程媒体 URI 的下载缓存目录
|
|
455
|
-
# # leaveTemplate = "{player} 离开了服务器" # 玩家退服模板
|
|
456
|
-
# # deathTemplate = "{player} {message}" # 玩家死亡模板(空消息显示「死亡了」)
|
|
457
499
|
`;
|
|
458
500
|
}
|
|
459
501
|
// src/config/store.ts
|
|
@@ -481,7 +523,10 @@ async function ensureConfigTemplate(path, onInfo) {
|
|
|
481
523
|
await access(path);
|
|
482
524
|
} catch {
|
|
483
525
|
mkdirSync(dirname(path), { recursive: true });
|
|
484
|
-
await writeFile(path, `${configTemplate()}\n`,
|
|
526
|
+
await writeFile(path, `${configTemplate()}\n`, {
|
|
527
|
+
encoding: "utf8",
|
|
528
|
+
...process.platform === "win32" ? {} : { mode: CONFIG_FILE_MODE }
|
|
529
|
+
});
|
|
485
530
|
onInfo?.({ path }, "配置文件不存在,已生成默认模板(请编辑 accounts 段填入 QQ 号)");
|
|
486
531
|
}
|
|
487
532
|
}
|
|
@@ -523,7 +568,7 @@ function resolveCliConfigSource(opts = {}) {
|
|
|
523
568
|
let sourceLogged = false;
|
|
524
569
|
/**
|
|
525
570
|
* 加载主配置(内联优先,2026-10-25 嵌入式契约):
|
|
526
|
-
*
|
|
571
|
+
* NAPUKETTO_CONFIG_JSON 非空 → 内存文档校验(不读 / 不写 / 不校验任何 toml
|
|
527
572
|
* 文件),打一行来源日志;否则现行文件链路(缺失自动落模板)。校验失败两形态
|
|
528
573
|
* 同为 ConfigError(exit 78),文案区别只在来源标注。
|
|
529
574
|
*/
|
|
@@ -533,7 +578,7 @@ async function loadCliConfigWithSource(opts = {}) {
|
|
|
533
578
|
const config = parseInlineConfig(resolved.text);
|
|
534
579
|
if (!sourceLogged) {
|
|
535
580
|
sourceLogged = true;
|
|
536
|
-
opts.onInfo?.(
|
|
581
|
+
opts.onInfo?.(`配置来源: inline(${inlineConfigEnvName() ?? "环境变量"})`);
|
|
537
582
|
}
|
|
538
583
|
return {
|
|
539
584
|
config,
|
|
@@ -559,15 +604,22 @@ async function loadCliConfigWithSource(opts = {}) {
|
|
|
559
604
|
* NAPUKETTO_LOG_FORMAT / NAPUKETTO_NO_BANNER / NAPUKETTO_LOG_COLORIZE,
|
|
560
605
|
* 兼容旧拼写 NAPKETTO_LOG_LEVEL。
|
|
561
606
|
*/
|
|
562
|
-
/**
|
|
607
|
+
/** 已解析日志配置缓存(同一数据根复用;显式传入不同数据根时重新解析)。 */
|
|
563
608
|
let cachedConfig = null;
|
|
564
|
-
/** 解析配置时用的数据根([log.file]
|
|
609
|
+
/** 解析配置时用的数据根([log.file] 相对路径展开基准,兼缓存键)。 */
|
|
565
610
|
let cachedDataRoot = resolveDataRoot();
|
|
566
611
|
/** 同步解析日志配置(内联 > toml 文件的 [log] 段 + env 覆盖)。损坏/缺失配置回退缺省
|
|
567
612
|
* (不阻塞启动:配置的严格校验由 loadCliConfig 主路径负责报错)。内联生效时不读
|
|
568
|
-
* 任何 toml 文件(嵌入式契约,2026-10-25)。
|
|
613
|
+
* 任何 toml 文件(嵌入式契约,2026-10-25)。
|
|
614
|
+
*
|
|
615
|
+
* 缓存口径(2026-11 修正):显式 `dataDir` 解析出的根与缓存不一致时重新解析,
|
|
616
|
+
* 避免早期无参调用(缺省数据根)把后续 `-d` 指定数据根的配置/日志路径锁死;
|
|
617
|
+
* 无参调用始终复用当前缓存(preAction 解析后,懒构造 logger 的 LazyCliLogger
|
|
618
|
+
* 不能再用缺省根把 `-d` 的结果覆盖掉)。 */
|
|
569
619
|
function resolveCliLogConfig(dataDir) {
|
|
570
|
-
if (cachedConfig !== null)
|
|
620
|
+
if (cachedConfig !== null) {
|
|
621
|
+
if (dataDir === void 0 || resolveDataRoot(dataDir) === cachedDataRoot) return cachedConfig;
|
|
622
|
+
}
|
|
571
623
|
cachedDataRoot = resolveDataRoot(dataDir);
|
|
572
624
|
let section;
|
|
573
625
|
if (isInlineConfigActive()) section = readInlineConfigSection("log");
|
|
@@ -668,6 +720,24 @@ function toRecord(config) {
|
|
|
668
720
|
...config.log === void 0 ? {} : { log: config.log }
|
|
669
721
|
};
|
|
670
722
|
}
|
|
723
|
+
/** stdout 敏感字段默认脱敏(协议段 token 等;`--show-secrets` 才输出明文)。 */
|
|
724
|
+
const SENSITIVE_KEY_RE = /^(?:token|access[_-]?token|secret|password)$/i;
|
|
725
|
+
/** 脱敏占位(保持 TOML 字符串类型,便于脚本继续 parse)。 */
|
|
726
|
+
const SECRET_MASK = "***";
|
|
727
|
+
/** 深度复制并脱敏敏感字段(空串 = 未配置凭据,保持原样)。 */
|
|
728
|
+
function maskSecrets(value) {
|
|
729
|
+
if (Array.isArray(value)) return value.map(maskSecrets);
|
|
730
|
+
if (!isRecord(value)) return value;
|
|
731
|
+
const out = {};
|
|
732
|
+
for (const [key, val] of Object.entries(value)) out[key] = SENSITIVE_KEY_RE.test(key) && typeof val === "string" && val !== "" ? SECRET_MASK : maskSecrets(val);
|
|
733
|
+
return out;
|
|
734
|
+
}
|
|
735
|
+
/** stdout 输出用配置对象(默认脱敏;写盘始终用未脱敏原对象)。 */
|
|
736
|
+
function toOutputRecord(config, showSecrets) {
|
|
737
|
+
const record = toRecord(config);
|
|
738
|
+
if (showSecrets === true) return record;
|
|
739
|
+
return maskSecrets(record);
|
|
740
|
+
}
|
|
671
741
|
/** config init:生成全局 TOML 配置文件(项目根)+ 数据根目录。
|
|
672
742
|
* 文件不存在 → 写带注释模板;已存在 → 跳过(不覆盖用户配置)。
|
|
673
743
|
* 输出原始模板内容(账号未填时解析会校验失败,init 只负责生成不校验)。 */
|
|
@@ -680,7 +750,10 @@ async function cmdConfigInit(opts) {
|
|
|
680
750
|
await access(store.path);
|
|
681
751
|
} catch {
|
|
682
752
|
mkdirSync(dirname(store.path), { recursive: true });
|
|
683
|
-
await writeFile(store.path, `${configTemplate()}\n`,
|
|
753
|
+
await writeFile(store.path, `${configTemplate()}\n`, {
|
|
754
|
+
encoding: "utf8",
|
|
755
|
+
...process.platform === "win32" ? {} : { mode: CONFIG_FILE_MODE }
|
|
756
|
+
});
|
|
684
757
|
created = true;
|
|
685
758
|
}
|
|
686
759
|
const raw = await readFile(store.path, "utf8");
|
|
@@ -689,14 +762,14 @@ async function cmdConfigInit(opts) {
|
|
|
689
762
|
else logger.info({ path: store.path }, "全局配置已存在(跳过生成,避免覆盖用户配置)");
|
|
690
763
|
process.stdout.write(raw);
|
|
691
764
|
}
|
|
692
|
-
/** config list
|
|
765
|
+
/** config list:列出全局配置与各账号目录(stdout 敏感字段默认脱敏)。 */
|
|
693
766
|
async function cmdConfigList(opts) {
|
|
694
767
|
const dataRoot = resolveDataRoot(opts.dataDir);
|
|
695
768
|
const store = new CliConfigStore(dataRoot);
|
|
696
769
|
const config = await store.load();
|
|
697
770
|
logger.info({ dataRoot }, "数据根");
|
|
698
771
|
logger.info({ path: store.path }, "全局配置");
|
|
699
|
-
process.stdout.write(`${stringifyToml(
|
|
772
|
+
process.stdout.write(`${stringifyToml(toOutputRecord(config, opts.showSecrets))}\n`);
|
|
700
773
|
let entries;
|
|
701
774
|
try {
|
|
702
775
|
entries = readdirSync(dataRoot, { withFileTypes: true });
|
|
@@ -721,16 +794,16 @@ function printAccountConfig(account, dataRoot) {
|
|
|
721
794
|
files: fileList
|
|
722
795
|
}, "账号配置");
|
|
723
796
|
}
|
|
724
|
-
/** 解析外部配置文本(按扩展名推断 TOML/JSON)。 */
|
|
797
|
+
/** 解析外部配置文本(按扩展名推断 TOML/JSON,语法错误统一 INVALID_PARAM)。 */
|
|
725
798
|
function parseExternalConfig(file, rawText) {
|
|
726
|
-
|
|
799
|
+
const format = extname(file).toLowerCase() === ".toml" ? "TOML" : "JSON";
|
|
727
800
|
try {
|
|
728
|
-
return JSON.parse(rawText);
|
|
729
|
-
} catch {
|
|
730
|
-
throw kernelError(`外部配置 ${file} 不是合法
|
|
801
|
+
return format === "TOML" ? parseToml(rawText) : JSON.parse(rawText);
|
|
802
|
+
} catch (err) {
|
|
803
|
+
throw kernelError(`外部配置 ${file} 不是合法 ${format}`, "INVALID_PARAM", { cause: err });
|
|
731
804
|
}
|
|
732
805
|
}
|
|
733
|
-
/** config apply
|
|
806
|
+
/** config apply:应用外部配置(顶层覆盖合并、主配置 + 协议段校验后写回全局配置)。 */
|
|
734
807
|
async function cmdConfigApply(file, opts) {
|
|
735
808
|
const store = new CliConfigStore(resolveDataRoot(opts.dataDir));
|
|
736
809
|
const existing = await store.load();
|
|
@@ -747,9 +820,10 @@ async function cmdConfigApply(file, opts) {
|
|
|
747
820
|
...existing,
|
|
748
821
|
...partial
|
|
749
822
|
});
|
|
823
|
+
await validateProtocolSections(next);
|
|
750
824
|
await store.save(next);
|
|
751
825
|
logger.info({ path: store.path }, "全局配置已更新");
|
|
752
|
-
process.stdout.write(`${stringifyToml(
|
|
826
|
+
process.stdout.write(`${stringifyToml(toOutputRecord(next, opts.showSecrets))}\n`);
|
|
753
827
|
}
|
|
754
828
|
/** 读取配置文件文本(validate 纯只读:ENOENT 不落模板,按「配置缺失」报 ConfigError)。 */
|
|
755
829
|
async function readConfigTextForValidate(path) {
|
|
@@ -813,23 +887,98 @@ async function cmdConfigValidate(opts) {
|
|
|
813
887
|
* `napuketto status/stop/restart` 读文件 + liveness 检测 + 树杀(win32
|
|
814
888
|
* taskkill /T /F,杀 boot 进程树连带 self-host 孙进程)+ detached 重启。
|
|
815
889
|
*/
|
|
890
|
+
/**
|
|
891
|
+
* supervisor 注入给受管子进程的托管标记 env。
|
|
892
|
+
*
|
|
893
|
+
* 托管模式下 supervisor 与 boot 共享同一份 runtime.json:supervisor 拥有
|
|
894
|
+
* `kind`/`restartCount`/启动时间与 boot pid,受管 boot 只补充 `selfHost*`。
|
|
895
|
+
* boot 读到该标记即走合并写入(`patchAccountRuntime`),不再整文件覆盖。
|
|
896
|
+
*/
|
|
897
|
+
const SUPERVISOR_CHILD_ENV = "NAPUTO_SUPERVISOR_CHILD";
|
|
898
|
+
/** POSIX 强杀升级宽限(毫秒):SIGTERM 后仍未退出则补 SIGKILL。 */
|
|
899
|
+
const FORCE_KILL_GRACE_MS = 1500;
|
|
816
900
|
/** runtime.json 文件名。 */
|
|
817
901
|
const RUNTIME_FILE = "runtime.json";
|
|
818
902
|
/** supervisor.json 文件名。 */
|
|
819
903
|
const SUPERVISOR_FILE = "supervisor.json";
|
|
820
|
-
/**
|
|
904
|
+
/**
|
|
905
|
+
* 账号数据目录(数据根路径边界防御):uin 必须是单一路径段,解析后必须落在
|
|
906
|
+
* dataRoot 内。CLI `-q` 入口已按 QQ 号格式校验,这里兜底任何直接调用方
|
|
907
|
+
* (`-q ../../x` / 绝对路径等不得逃出数据根)。非法值抛 ConfigError(exit 78)。
|
|
908
|
+
*/
|
|
909
|
+
function accountDir(dataRoot, uin) {
|
|
910
|
+
if (uin === "" || uin === "." || uin === ".." || isAbsolute(uin)) throw configError(`非法账号标识 "${uin}":必须是单个路径段(不允许绝对路径)`);
|
|
911
|
+
if (uin.includes("/") || uin.includes("\\")) throw configError(`非法账号标识 "${uin}":不允许包含路径分隔符`);
|
|
912
|
+
const root = resolve(dataRoot);
|
|
913
|
+
const resolved = resolve(root, uin);
|
|
914
|
+
if (resolved !== root && !resolved.startsWith(`${root}${sep}`)) throw configError(`账号数据目录越界: ${resolved} 不在数据根 ${root} 内`);
|
|
915
|
+
return join(dataRoot, uin);
|
|
916
|
+
}
|
|
917
|
+
/** 账号状态文件路径(经 accountDir 边界校验)。 */
|
|
821
918
|
function runtimeStatePath(dataRoot, uin) {
|
|
822
|
-
return join(dataRoot, uin, RUNTIME_FILE);
|
|
919
|
+
return join(accountDir(dataRoot, uin), RUNTIME_FILE);
|
|
823
920
|
}
|
|
824
921
|
/** supervisor 状态文件路径。 */
|
|
825
922
|
function supervisorStatePath(dataRoot) {
|
|
826
923
|
return join(dataRoot, SUPERVISOR_FILE);
|
|
827
924
|
}
|
|
925
|
+
/** 删除文件(不存在/删除失败不阻塞)。 */
|
|
926
|
+
function removeIfExists(path) {
|
|
927
|
+
try {
|
|
928
|
+
rmSync(path, { force: true });
|
|
929
|
+
} catch {}
|
|
930
|
+
}
|
|
931
|
+
/**
|
|
932
|
+
* 原子写 JSON:同目录唯一临时文件 → rename 覆盖目标。
|
|
933
|
+
*
|
|
934
|
+
* 直接 `writeFileSync` 在并发读取(status/stop 与其他进程)时可能读到截断 JSON;
|
|
935
|
+
* rename 在同一文件系统内是原子的。Windows 下 libuv 的 rename 走
|
|
936
|
+
* `MoveFileExW(MOVEFILE_REPLACE_EXISTING)`,目标已存在时直接替换,因此**不能**
|
|
937
|
+
* 先删目标再 rename(会留下「文件短暂不存在」的空窗)。临时文件名带 pid + UUID,
|
|
938
|
+
* 避免 supervisor / boot 并发写同一目录时互相踩临时文件;写入或替换失败时清理
|
|
939
|
+
* 临时文件后原样抛出。
|
|
940
|
+
*/
|
|
941
|
+
function writeJsonAtomic(path, value) {
|
|
942
|
+
const dir = dirname(path);
|
|
943
|
+
mkdirSync(dir, { recursive: true });
|
|
944
|
+
const tmpPath = join(dir, `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
|
|
945
|
+
try {
|
|
946
|
+
writeFileSync(tmpPath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
947
|
+
renameSync(tmpPath, path);
|
|
948
|
+
} catch (err) {
|
|
949
|
+
removeIfExists(tmpPath);
|
|
950
|
+
throw err;
|
|
951
|
+
}
|
|
952
|
+
}
|
|
828
953
|
/** 写账号运行时状态(原子覆盖)。 */
|
|
829
954
|
function writeAccountRuntime(dataRoot, state) {
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
955
|
+
writeJsonAtomic(runtimeStatePath(dataRoot, state.uin), state);
|
|
956
|
+
}
|
|
957
|
+
/** 过滤 undefined 的补丁字段(exactOptionalPropertyTypes:不显式写 undefined)。 */
|
|
958
|
+
function definedPatch(patch) {
|
|
959
|
+
const entries = Object.entries(patch).filter(([, value]) => value !== void 0);
|
|
960
|
+
return Object.fromEntries(entries);
|
|
961
|
+
}
|
|
962
|
+
/**
|
|
963
|
+
* 合并写入账号运行时状态(托管模式专用:supervisor 与受管 boot 共享 runtime.json)。
|
|
964
|
+
*
|
|
965
|
+
* 以磁盘现有合法状态为底应用 patch;现有文件缺失/损坏时用 fallback 完整状态兜底。
|
|
966
|
+
* `status` 切回 running 时丢弃上一次的 exitCode(新生命周期),避免 status 显示
|
|
967
|
+
* 「运行中 + 旧退出码」。
|
|
968
|
+
*/
|
|
969
|
+
function patchAccountRuntime(dataRoot, uin, patch, fallback) {
|
|
970
|
+
const base = readAccountRuntime(dataRoot, uin) ?? fallback;
|
|
971
|
+
const next = {
|
|
972
|
+
...base,
|
|
973
|
+
...definedPatch(patch),
|
|
974
|
+
uin
|
|
975
|
+
};
|
|
976
|
+
if (next.status === "running") delete next.exitCode;
|
|
977
|
+
else {
|
|
978
|
+
const exitCode = patch.exitCode === void 0 ? base.exitCode : patch.exitCode;
|
|
979
|
+
if (exitCode !== void 0) next.exitCode = exitCode;
|
|
980
|
+
}
|
|
981
|
+
writeJsonAtomic(runtimeStatePath(dataRoot, uin), next);
|
|
833
982
|
}
|
|
834
983
|
/** 账号运行形态判定。 */
|
|
835
984
|
function isAccountRuntimeKind(val) {
|
|
@@ -839,13 +988,17 @@ function isAccountRuntimeKind(val) {
|
|
|
839
988
|
function isAccountRuntimeStatus(val) {
|
|
840
989
|
return val === "running" || val === "exited";
|
|
841
990
|
}
|
|
991
|
+
/** 可选字符串字段判定(缺省合法)。 */
|
|
992
|
+
function isOptionalString(val) {
|
|
993
|
+
return val === void 0 || typeof val === "string";
|
|
994
|
+
}
|
|
842
995
|
/** runtime.json 形状守卫(损坏 / 旧格式 / 手工改错的文件一律判非法)。 */
|
|
843
996
|
function isAccountRuntime(val) {
|
|
844
|
-
return isRecord(val) && hasStringProp(val, "uin") && hasNumberProp(val, "pid") && Number.isInteger(val["pid"]) && val["pid"] > 0 && hasStringProp(val, "startedAt") && isAccountRuntimeKind(val["kind"]) && isAccountRuntimeStatus(val["status"]);
|
|
997
|
+
return isRecord(val) && hasStringProp(val, "uin") && hasNumberProp(val, "pid") && Number.isInteger(val["pid"]) && val["pid"] > 0 && hasStringProp(val, "startedAt") && isAccountRuntimeKind(val["kind"]) && isAccountRuntimeStatus(val["status"]) && isOptionalString(val["cmdline"]) && isOptionalString(val["selfHostCmdline"]);
|
|
845
998
|
}
|
|
846
999
|
/** supervisor.json 形状守卫。 */
|
|
847
1000
|
function isSupervisorRuntime(val) {
|
|
848
|
-
return isRecord(val) && hasNumberProp(val, "pid") && Number.isInteger(val["pid"]) && val["pid"] > 0 && hasStringProp(val, "startedAt") && Array.isArray(val["accounts"]) && val["accounts"].every((item) => typeof item === "string");
|
|
1001
|
+
return isRecord(val) && hasNumberProp(val, "pid") && Number.isInteger(val["pid"]) && val["pid"] > 0 && hasStringProp(val, "startedAt") && Array.isArray(val["accounts"]) && val["accounts"].every((item) => typeof item === "string") && isOptionalString(val["cmdline"]);
|
|
849
1002
|
}
|
|
850
1003
|
/** 读账号运行时状态(缺失/损坏返回 null)。 */
|
|
851
1004
|
function readAccountRuntime(dataRoot, uin) {
|
|
@@ -854,8 +1007,7 @@ function readAccountRuntime(dataRoot, uin) {
|
|
|
854
1007
|
}
|
|
855
1008
|
/** 写 supervisor 运行时状态(数据根缺省时自动创建——首次在新目录 start 不再 ENOENT)。 */
|
|
856
1009
|
function writeSupervisorRuntime(dataRoot, state) {
|
|
857
|
-
|
|
858
|
-
writeFileSync(supervisorStatePath(dataRoot), `${JSON.stringify(state, null, 2)}\n`, "utf8");
|
|
1010
|
+
writeJsonAtomic(supervisorStatePath(dataRoot), state);
|
|
859
1011
|
}
|
|
860
1012
|
/** 读 supervisor 运行时状态(缺失返回 null)。 */
|
|
861
1013
|
function readSupervisorRuntime(dataRoot) {
|
|
@@ -895,20 +1047,87 @@ function isPidAlive(pid) {
|
|
|
895
1047
|
return isRecord(err) && err["code"] === "EPERM";
|
|
896
1048
|
}
|
|
897
1049
|
}
|
|
898
|
-
/**
|
|
899
|
-
function
|
|
1050
|
+
/** 目标进程不存在(ESRCH):正常路径,不回调 onError。 */
|
|
1051
|
+
function isNoSuchProcess(err) {
|
|
1052
|
+
return isRecord(err) && err["code"] === "ESRCH";
|
|
1053
|
+
}
|
|
1054
|
+
/** 去重并过滤非法 pid(0/负数/非整数视为无效)。 */
|
|
1055
|
+
function uniquePids(pids) {
|
|
1056
|
+
return [...new Set(pids)].filter((pid) => Number.isInteger(pid) && pid > 0);
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* 树杀(超时兜底强杀):win32 走 `taskkill /T /F`;POSIX 先 SIGTERM,宽限后对
|
|
1060
|
+
* 仍存活目标补 SIGKILL。
|
|
1061
|
+
*
|
|
1062
|
+
* POSIX 覆盖范围:对每个目标同时尝试进程组(`-pid`,仅当目标恰为组长时生效,
|
|
1063
|
+
* 普通进程返回 ESRCH 静默)与单进程,并接受 `extraPids` 传入 selfHostPid——
|
|
1064
|
+
* 只发 SIGTERM 且只打 boot pid 会留下忽略信号的卡死进程与 self-host 孤儿。
|
|
1065
|
+
* Windows 必须监听 taskkill 的 `error` 事件:spawn 失败(PATH 缺 taskkill 等)
|
|
1066
|
+
* 是异步事件,不监听会静默失败。
|
|
1067
|
+
*/
|
|
1068
|
+
function killProcessTree(pid, options = {}) {
|
|
1069
|
+
const targets = uniquePids([pid, ...options.extraPids ?? []]);
|
|
1070
|
+
if (targets.length === 0) return;
|
|
900
1071
|
if (process.platform === "win32") {
|
|
901
|
-
spawn("taskkill", [
|
|
1072
|
+
for (const target of targets) spawn("taskkill", [
|
|
902
1073
|
"/PID",
|
|
903
|
-
String(
|
|
1074
|
+
String(target),
|
|
904
1075
|
"/T",
|
|
905
1076
|
"/F"
|
|
906
|
-
], {
|
|
1077
|
+
], {
|
|
1078
|
+
stdio: "ignore",
|
|
1079
|
+
windowsHide: true
|
|
1080
|
+
}).on("error", (err) => {
|
|
1081
|
+
options.onError?.(`taskkill 失败(pid ${target}):${errorMessage(err)}`);
|
|
1082
|
+
});
|
|
907
1083
|
return;
|
|
908
1084
|
}
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
1085
|
+
const send = (target, signal) => {
|
|
1086
|
+
try {
|
|
1087
|
+
process.kill(target, signal);
|
|
1088
|
+
} catch (err) {
|
|
1089
|
+
if (!isNoSuchProcess(err)) options.onError?.(`发送 ${signal} 失败(pid ${target}):${errorMessage(err)}`);
|
|
1090
|
+
}
|
|
1091
|
+
};
|
|
1092
|
+
const killTarget = (target, signal) => {
|
|
1093
|
+
send(-target, signal);
|
|
1094
|
+
send(target, signal);
|
|
1095
|
+
};
|
|
1096
|
+
for (const target of targets) killTarget(target, "SIGTERM");
|
|
1097
|
+
const escalate = () => {
|
|
1098
|
+
for (const target of targets) if (isPidAlive(target)) killTarget(target, "SIGKILL");
|
|
1099
|
+
};
|
|
1100
|
+
const graceMs = options.graceMs ?? FORCE_KILL_GRACE_MS;
|
|
1101
|
+
if (graceMs <= 0) {
|
|
1102
|
+
escalate();
|
|
1103
|
+
return;
|
|
1104
|
+
}
|
|
1105
|
+
setTimeout(escalate, graceMs).unref?.();
|
|
1106
|
+
}
|
|
1107
|
+
/**
|
|
1108
|
+
* 本进程命令行指纹(`argv[1..]`,不含可执行文件)。
|
|
1109
|
+
*
|
|
1110
|
+
* 不用 loader `selfCmdline()` 直接比对:它把 execArgv 排在 argv 前、且 argv[0]
|
|
1111
|
+
* 常是裸 `node`,与操作系统记录的完整命令行(可执行文件绝对路径 + execArgv +
|
|
1112
|
+
* 脚本 + 参数)顺序/前缀不一致,容易误判成「PID 已复用」而让 stop 失效。
|
|
1113
|
+
* 指纹只取脚本及其后的参数,校验时按规范化子串匹配。
|
|
1114
|
+
*/
|
|
1115
|
+
function selfArgvFingerprint() {
|
|
1116
|
+
const args = process.argv.slice(1);
|
|
1117
|
+
return args.length > 0 ? args.join(" ") : void 0;
|
|
1118
|
+
}
|
|
1119
|
+
/**
|
|
1120
|
+
* 树杀前 PID 身份校验(防 PID 复用误杀,口径同 loader `checkInstanceLock`):
|
|
1121
|
+
* 记录的「脚本 + 参数」指纹必须出现在目标进程当前命令行中(规范化后子串比对,
|
|
1122
|
+
* 对可执行文件绝对路径 / execArgv / 引号 / 路径分隔符差异免疫)。查不到(进程
|
|
1123
|
+
* 刚退 / 权限不足)→ mismatch;平台不支持探针或旧状态文件无指纹 → unverified
|
|
1124
|
+
* (调用方保守沿用旧行为,不因升级而让 stop 失效)。
|
|
1125
|
+
*/
|
|
1126
|
+
function checkProcessIdentity(pid, cmdline) {
|
|
1127
|
+
if (cmdline === void 0 || cmdline === "" || !CMDLINE_PROBE_SUPPORTED) return "unverified";
|
|
1128
|
+
const current = readCmdlineForPid(pid);
|
|
1129
|
+
if (current === null) return "mismatch";
|
|
1130
|
+
return normalizeCmdline(current).includes(normalizeCmdline(cmdline)) ? "match" : "mismatch";
|
|
912
1131
|
}
|
|
913
1132
|
/** detached 拉起 node 进程(restart 用;立即返回不等待)。 */
|
|
914
1133
|
function spawnDetached(args, cwd) {
|
|
@@ -925,6 +1144,7 @@ function aggregateStatus(runtimes, aliveFn = isPidAlive) {
|
|
|
925
1144
|
return runtimes.map((r) => ({
|
|
926
1145
|
uin: r.uin,
|
|
927
1146
|
pid: r.pid,
|
|
1147
|
+
...r.selfHostPid !== void 0 ? { selfHostPid: r.selfHostPid } : {},
|
|
928
1148
|
alive: r.status === "running" ? aliveFn(r.pid) : false,
|
|
929
1149
|
kind: r.kind,
|
|
930
1150
|
startedAt: r.startedAt,
|
|
@@ -948,6 +1168,13 @@ function aggregateStatus(runtimes, aliveFn = isPidAlive) {
|
|
|
948
1168
|
const GRACEFUL_STOP_WAIT_MS = 8e3;
|
|
949
1169
|
/** 存活轮询间隔(毫秒)。 */
|
|
950
1170
|
const LIVENESS_POLL_MS = 200;
|
|
1171
|
+
/**
|
|
1172
|
+
* 运维命令 `-q` 入口校验(复用主配置 QQ 规则):非法值抛 ConfigError(exit 78),
|
|
1173
|
+
* 避免 `-q all` 命中全局停止哨兵或 `-q ../..` 拼出数据根之外的路径。
|
|
1174
|
+
*/
|
|
1175
|
+
function assertOpsQq(opts) {
|
|
1176
|
+
if (opts.qq !== void 0) parseCliQq(opts.qq);
|
|
1177
|
+
}
|
|
951
1178
|
/** 等待 pid 列表全部退出(返回超时仍未退的 pid)。 */
|
|
952
1179
|
async function waitForPidsExit(pids) {
|
|
953
1180
|
const deadline = Date.now() + GRACEFUL_STOP_WAIT_MS;
|
|
@@ -960,6 +1187,7 @@ async function waitForPidsExit(pids) {
|
|
|
960
1187
|
}
|
|
961
1188
|
/** status:聚合输出各账号运行状态(含 supervisor 自身)。 */
|
|
962
1189
|
function cmdStatus(dataRoot, opts) {
|
|
1190
|
+
assertOpsQq(opts);
|
|
963
1191
|
const supervisor = readSupervisorRuntime(dataRoot);
|
|
964
1192
|
if (supervisor !== null) logger.info({
|
|
965
1193
|
pid: supervisor.pid,
|
|
@@ -977,18 +1205,70 @@ function cmdStatus(dataRoot, opts) {
|
|
|
977
1205
|
uin: row.uin,
|
|
978
1206
|
alive: row.alive,
|
|
979
1207
|
pid: row.pid,
|
|
1208
|
+
...row.selfHostPid !== void 0 ? { selfHostPid: row.selfHostPid } : {},
|
|
980
1209
|
kind: row.kind,
|
|
981
1210
|
startedAt: row.startedAt,
|
|
982
1211
|
restartCount: row.restartCount,
|
|
983
1212
|
...row.exitCode !== void 0 ? { exitCode: row.exitCode } : {}
|
|
984
1213
|
}, "账号状态");
|
|
985
1214
|
}
|
|
986
|
-
/**
|
|
987
|
-
|
|
988
|
-
|
|
1215
|
+
/**
|
|
1216
|
+
* 树杀前 PID 身份校验(防 PID 复用误杀,口径同 loader `checkInstanceLock`):
|
|
1217
|
+
* mismatch 直接跳过;unverified(旧状态无 cmdline 摘要 / 平台不支持探针)默认沿用
|
|
1218
|
+
* 旧行为并记 debug,`allowUnverified: false` 时拒绝(调用方无法证明 pid 身份)。
|
|
1219
|
+
*/
|
|
1220
|
+
function canKillProcess(pid, cmdline, fields, options = {}) {
|
|
1221
|
+
const identity = checkProcessIdentity(pid, cmdline);
|
|
1222
|
+
if (identity === "mismatch") {
|
|
1223
|
+
logger.warn({
|
|
1224
|
+
...fields,
|
|
1225
|
+
pid
|
|
1226
|
+
}, "PID 已被无关进程复用(命令行不匹配),跳过树杀以避免误杀");
|
|
1227
|
+
return false;
|
|
1228
|
+
}
|
|
1229
|
+
if (identity === "unverified") {
|
|
1230
|
+
if (options.allowUnverified === false) {
|
|
1231
|
+
logger.warn({
|
|
1232
|
+
...fields,
|
|
1233
|
+
pid
|
|
1234
|
+
}, "缺少命令行指纹且无同树存活进程可佐证,跳过树杀以避免误杀");
|
|
1235
|
+
return false;
|
|
1236
|
+
}
|
|
1237
|
+
logger.debug({
|
|
1238
|
+
...fields,
|
|
1239
|
+
pid
|
|
1240
|
+
}, "无命令行摘要,未做 PID 复用校验");
|
|
1241
|
+
}
|
|
1242
|
+
return true;
|
|
1243
|
+
}
|
|
1244
|
+
/** 树杀目标账号:boot pid + selfHostPid 分别做存活/身份校验后一并强杀。 */
|
|
1245
|
+
function killAccountTree(runtime) {
|
|
1246
|
+
const targets = [];
|
|
1247
|
+
const bootKillable = isPidAlive(runtime.pid) && canKillProcess(runtime.pid, runtime.cmdline, { uin: runtime.uin });
|
|
1248
|
+
if (bootKillable) targets.push(runtime.pid);
|
|
1249
|
+
const selfHostPid = runtime.selfHostPid;
|
|
1250
|
+
if (selfHostPid !== void 0 && isPidAlive(selfHostPid) && canKillProcess(selfHostPid, runtime.selfHostCmdline, {
|
|
1251
|
+
uin: runtime.uin,
|
|
1252
|
+
role: "self-host"
|
|
1253
|
+
}, { allowUnverified: bootKillable })) targets.push(selfHostPid);
|
|
1254
|
+
const [primary] = targets;
|
|
1255
|
+
if (primary === void 0) {
|
|
1256
|
+
logger.warn({
|
|
1257
|
+
uin: runtime.uin,
|
|
1258
|
+
pid: runtime.pid
|
|
1259
|
+
}, "无可安全结束的进程(已退出或 PID 已复用),跳过树杀");
|
|
1260
|
+
return;
|
|
1261
|
+
}
|
|
1262
|
+
killProcessTree(primary, {
|
|
1263
|
+
extraPids: targets.slice(1),
|
|
1264
|
+
onError: (message) => logger.warn({
|
|
1265
|
+
uin: runtime.uin,
|
|
1266
|
+
message
|
|
1267
|
+
}, "树杀失败")
|
|
1268
|
+
});
|
|
989
1269
|
logger.info({
|
|
990
1270
|
uin: runtime.uin,
|
|
991
|
-
|
|
1271
|
+
pids: targets
|
|
992
1272
|
}, "已发送停止(树杀)");
|
|
993
1273
|
}
|
|
994
1274
|
/** stop:-q 停单账号;无 -q 停 supervisor + 全部账号兜底。
|
|
@@ -997,26 +1277,56 @@ function stopAccount(runtime) {
|
|
|
997
1277
|
* (退出码 0)→ 超时残留树杀兜底 → 清理哨兵。单账号哨兵只命中对应 boot/self-host,
|
|
998
1278
|
* 不干扰同数据根的其他账号。
|
|
999
1279
|
*/
|
|
1000
|
-
/** stop -q
|
|
1280
|
+
/** stop -q:写单账号独立哨兵 → 等优雅退出 → 超时树杀兜底 → 清本账号哨兵。 */
|
|
1001
1281
|
async function stopSingleAccount(dataRoot, target) {
|
|
1002
1282
|
logger.info({
|
|
1003
1283
|
uin: target.uin,
|
|
1004
1284
|
pid: target.pid
|
|
1005
1285
|
}, "已发送停止请求(哨兵),等待退出");
|
|
1006
|
-
|
|
1007
|
-
const stragglers = await waitForPidsExit([target.pid]);
|
|
1008
|
-
|
|
1286
|
+
writeAccountStopSentinel(dataRoot, target.uin);
|
|
1287
|
+
const stragglers = await waitForPidsExit([target.pid, ...target.selfHostPid !== void 0 ? [target.selfHostPid] : []]);
|
|
1288
|
+
if (stragglers.length > 0) {
|
|
1009
1289
|
logger.warn({
|
|
1010
1290
|
uin: target.uin,
|
|
1011
|
-
|
|
1291
|
+
pids: stragglers
|
|
1012
1292
|
}, "限时内未退出,树杀兜底");
|
|
1013
|
-
|
|
1293
|
+
killAccountTree(target);
|
|
1014
1294
|
}
|
|
1015
|
-
|
|
1295
|
+
removeAccountStopSentinel(dataRoot, target.uin);
|
|
1016
1296
|
const supervisor = readSupervisorRuntime(dataRoot);
|
|
1017
1297
|
if (supervisor !== null) logger.warn({ supervisorPid: supervisor.pid }, "supervisor 仍在运行且 autoRestart 开启时会自动拉起该账号;如需彻底停止请执行 napuketto stop(停 supervisor)");
|
|
1018
1298
|
}
|
|
1299
|
+
/** 全量 stop:停 supervisor(all 哨兵 → 超时树杀,含 PID 复用校验)。 */
|
|
1300
|
+
async function stopSupervisor(dataRoot) {
|
|
1301
|
+
const supervisor = readSupervisorRuntime(dataRoot);
|
|
1302
|
+
if (supervisor === null) {
|
|
1303
|
+
logger.warn("supervisor 未运行(无状态文件)");
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
const supervisorPid = isPidAlive(supervisor.pid) ? supervisor.pid : 0;
|
|
1307
|
+
logger.info({ pid: supervisor.pid }, "已发送停止请求(哨兵),等待 supervisor 退出");
|
|
1308
|
+
writeStopSentinel(dataRoot, "all");
|
|
1309
|
+
const alive = await waitForPidsExit([supervisorPid]);
|
|
1310
|
+
for (const pid of alive) {
|
|
1311
|
+
if (!canKillProcess(pid, supervisor.cmdline, { role: "supervisor" })) continue;
|
|
1312
|
+
logger.warn({ pid }, "supervisor 限时内未退出,树杀兜底");
|
|
1313
|
+
killProcessTree(pid, { onError: (message) => logger.warn({
|
|
1314
|
+
pid,
|
|
1315
|
+
message
|
|
1316
|
+
}, "supervisor 树杀失败") });
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
/** 账号树杀涉及的全部 pid(boot pid + selfHostPid)。 */
|
|
1320
|
+
function runtimePids(runtime) {
|
|
1321
|
+
return [runtime.pid, ...runtime.selfHostPid !== void 0 ? [runtime.selfHostPid] : []];
|
|
1322
|
+
}
|
|
1323
|
+
/** 全量 stop 兜底:残留账号进程逐个树杀(all 哨兵转发失败场合)。 */
|
|
1324
|
+
async function stopStragglerAccounts(runtimes) {
|
|
1325
|
+
const stragglers = await waitForPidsExit(runtimes.flatMap(runtimePids));
|
|
1326
|
+
for (const runtime of runtimes) if (runtimePids(runtime).some((pid) => stragglers.includes(pid))) killAccountTree(runtime);
|
|
1327
|
+
}
|
|
1019
1328
|
async function cmdStop(dataRoot, opts) {
|
|
1329
|
+
assertOpsQq(opts);
|
|
1020
1330
|
const runtimes = listAccountRuntimes(dataRoot);
|
|
1021
1331
|
if (opts.qq !== void 0) {
|
|
1022
1332
|
const target = runtimes.find((r) => r.uin === opts.qq);
|
|
@@ -1028,26 +1338,25 @@ async function cmdStop(dataRoot, opts) {
|
|
|
1028
1338
|
await stopSingleAccount(dataRoot, target);
|
|
1029
1339
|
return;
|
|
1030
1340
|
}
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
if (supervisor !== null) {
|
|
1034
|
-
logger.info({ pid: supervisor.pid }, "已发送停止请求(哨兵),等待 supervisor 退出");
|
|
1035
|
-
writeStopSentinel(dataRoot, "all");
|
|
1036
|
-
const alive = await waitForPidsExit([supervisorPid]);
|
|
1037
|
-
for (const pid of alive) {
|
|
1038
|
-
logger.warn({ pid }, "supervisor 限时内未退出,树杀兜底");
|
|
1039
|
-
killProcessTree(pid);
|
|
1040
|
-
}
|
|
1041
|
-
} else logger.warn("supervisor 未运行(无状态文件)");
|
|
1042
|
-
const stragglers = await waitForPidsExit(runtimes.map((r) => r.pid));
|
|
1043
|
-
for (const runtime of runtimes) if (stragglers.includes(runtime.pid)) stopAccount(runtime);
|
|
1341
|
+
await stopSupervisor(dataRoot);
|
|
1342
|
+
await stopStragglerAccounts(runtimes);
|
|
1044
1343
|
removeStopSentinel(dataRoot);
|
|
1045
1344
|
}
|
|
1046
|
-
/** restart:stop 同目标 + detached
|
|
1345
|
+
/** restart:stop 同目标 + detached 拉起(停止失败/入口缺失时不得继续拉起)。 */
|
|
1047
1346
|
async function cmdRestart(dataRoot, opts) {
|
|
1347
|
+
assertOpsQq(opts);
|
|
1048
1348
|
await cmdStop(dataRoot, opts);
|
|
1349
|
+
if (process.exitCode !== void 0 && process.exitCode !== 0) {
|
|
1350
|
+
logger.error({ qq: opts.qq ?? "(supervisor 全量)" }, "停止失败(目标未运行等),跳过重新拉起");
|
|
1351
|
+
return;
|
|
1352
|
+
}
|
|
1353
|
+
const entry = process.argv[1];
|
|
1354
|
+
if (entry === void 0 || entry === "") {
|
|
1355
|
+
logger.error("无法确定 cli 入口(process.argv[1] 为空),拒绝拉起空 node 进程");
|
|
1356
|
+
process.exitCode = 1;
|
|
1357
|
+
return;
|
|
1358
|
+
}
|
|
1049
1359
|
await new Promise((resolve) => setTimeout(resolve, 1500));
|
|
1050
|
-
const entry = process.argv[1] ?? "";
|
|
1051
1360
|
const args = opts.qq !== void 0 ? [
|
|
1052
1361
|
entry,
|
|
1053
1362
|
"-q",
|
|
@@ -1065,6 +1374,77 @@ async function cmdRestart(dataRoot, opts) {
|
|
|
1065
1374
|
qq: opts.qq ?? "(supervisor 全量)"
|
|
1066
1375
|
}, "已 detached 拉起(日志不再接入当前终端,见数据目录 logs/)");
|
|
1067
1376
|
}
|
|
1377
|
+
// src/runtime/lines.ts
|
|
1378
|
+
/**
|
|
1379
|
+
* 子进程输出逐行切分(boot / supervisor 共用)。
|
|
1380
|
+
*
|
|
1381
|
+
* 为什么不用 `readline.createInterface`:readline 对「无换行符的超大输出」没有
|
|
1382
|
+
* 缓冲上限,原生层(QQ wrapper.node)异常刷屏或误写二进制时会把整块数据积在
|
|
1383
|
+
* 内存里,直到换行符出现才触发 line 事件。这里用轻量切分器保留逐行语义
|
|
1384
|
+
* (UTF-8 多字节跨 chunk 由 StringDecoder 拼接、\r\n 归一),同时给单行缓冲设
|
|
1385
|
+
* 上限:超过上限的部分直接丢弃,行结束时补 `…[truncated]` 标记。
|
|
1386
|
+
* 上限按字符计(UTF-16 code unit),64 KiB 对正常日志行足够宽松。
|
|
1387
|
+
*/
|
|
1388
|
+
/** 单行缓冲上限(字符):异常无换行输出在此截断,防止无界内存累积。 */
|
|
1389
|
+
const MAX_LINE_LENGTH = 65536;
|
|
1390
|
+
/** 截断行尾标记(保留 grep 可见性,避免静默丢数据)。 */
|
|
1391
|
+
const TRUNCATED_SUFFIX = "…[truncated]";
|
|
1392
|
+
/**
|
|
1393
|
+
* 监听 input 的 data/end,按换行切分后逐行回调(不含换行符,末行无换行也会回调)。
|
|
1394
|
+
* @param input 子进程 stdout/stderr(可读流)
|
|
1395
|
+
* @param onLine 行回调(空行也回调,与 readline 行为一致)
|
|
1396
|
+
* @param maxLineLength 单行缓冲上限(字符),超出部分丢弃并标记截断
|
|
1397
|
+
* @returns 解绑函数(流结束后无需调用;需要提前停止转发时用)
|
|
1398
|
+
*/
|
|
1399
|
+
function forwardLines(input, onLine, maxLineLength = MAX_LINE_LENGTH) {
|
|
1400
|
+
const decoder = new StringDecoder("utf8");
|
|
1401
|
+
let partial = "";
|
|
1402
|
+
let discarding = false;
|
|
1403
|
+
/** 当前行结束:输出(截断行补标记)并清空缓冲。 */
|
|
1404
|
+
const flushLine = () => {
|
|
1405
|
+
const line = partial.endsWith("\r") ? partial.slice(0, -1) : partial;
|
|
1406
|
+
partial = "";
|
|
1407
|
+
if (discarding) {
|
|
1408
|
+
discarding = false;
|
|
1409
|
+
onLine(`${line}${TRUNCATED_SUFFIX}`);
|
|
1410
|
+
return;
|
|
1411
|
+
}
|
|
1412
|
+
onLine(line);
|
|
1413
|
+
};
|
|
1414
|
+
/** 消费一段已解码文本:按 \n 切分,未完结部分留在 partial。 */
|
|
1415
|
+
const consume = (text) => {
|
|
1416
|
+
let cursor = 0;
|
|
1417
|
+
while (cursor < text.length) {
|
|
1418
|
+
const newline = text.indexOf("\n", cursor);
|
|
1419
|
+
const end = newline === -1 ? text.length : newline;
|
|
1420
|
+
if (!discarding) {
|
|
1421
|
+
const segment = text.slice(cursor, end);
|
|
1422
|
+
const remaining = maxLineLength - partial.length;
|
|
1423
|
+
if (segment.length <= remaining) partial += segment;
|
|
1424
|
+
else {
|
|
1425
|
+
partial += segment.slice(0, Math.max(remaining, 0));
|
|
1426
|
+
discarding = true;
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
if (newline === -1) return;
|
|
1430
|
+
flushLine();
|
|
1431
|
+
cursor = newline + 1;
|
|
1432
|
+
}
|
|
1433
|
+
};
|
|
1434
|
+
const onData = (chunk) => {
|
|
1435
|
+
consume(typeof chunk === "string" ? chunk : decoder.write(chunk));
|
|
1436
|
+
};
|
|
1437
|
+
const onEnd = () => {
|
|
1438
|
+
consume(decoder.end());
|
|
1439
|
+
if (partial !== "" || discarding) flushLine();
|
|
1440
|
+
};
|
|
1441
|
+
input.on("data", onData);
|
|
1442
|
+
input.on("end", onEnd);
|
|
1443
|
+
return () => {
|
|
1444
|
+
input.off("data", onData);
|
|
1445
|
+
input.off("end", onEnd);
|
|
1446
|
+
};
|
|
1447
|
+
}
|
|
1068
1448
|
// src/runtime/qr.ts
|
|
1069
1449
|
/**
|
|
1070
1450
|
* 终端二维码渲染(uqr 编码 + half-block ANSI,2026-11-03 替代 qrcode 包)
|
|
@@ -1134,7 +1514,7 @@ const GRACEFUL_STOP_TIMEOUT_MS = 1e4;
|
|
|
1134
1514
|
* 噪音判定走 loader 共享单一来源(isNativeNoiseLine,与 koishi IPC 路径同源)。
|
|
1135
1515
|
*/
|
|
1136
1516
|
function forwardFiltered(input, out) {
|
|
1137
|
-
|
|
1517
|
+
forwardLines(input, (line) => {
|
|
1138
1518
|
if (line.startsWith(QR_LINE_PREFIX)) {
|
|
1139
1519
|
renderTerminalQr(line.slice(QR_LINE_PREFIX.length));
|
|
1140
1520
|
return;
|
|
@@ -1264,29 +1644,81 @@ function forwardChildOutput(child) {
|
|
|
1264
1644
|
if (child.stdout !== null) forwardFiltered(child.stdout, process.stdout);
|
|
1265
1645
|
if (child.stderr !== null) forwardFiltered(child.stderr, process.stderr);
|
|
1266
1646
|
}
|
|
1267
|
-
/**
|
|
1268
|
-
|
|
1647
|
+
/** self-host 子进程命令行参数指纹(spawnargs 去掉可执行文件本身;不可得时 undefined)。 */
|
|
1648
|
+
function childCmdline$1(child) {
|
|
1649
|
+
const args = child.spawnargs;
|
|
1650
|
+
if (!Array.isArray(args)) return;
|
|
1651
|
+
const tail = args.slice(1).filter((arg) => typeof arg === "string").join(" ");
|
|
1652
|
+
return tail === "" ? void 0 : tail;
|
|
1653
|
+
}
|
|
1654
|
+
/** 是否由 supervisor 托管拉起(决定 runtime.json 的写入权责)。 */
|
|
1655
|
+
function isSupervisedChild() {
|
|
1656
|
+
return process.env[SUPERVISOR_CHILD_ENV] === "1";
|
|
1657
|
+
}
|
|
1658
|
+
/**
|
|
1659
|
+
* 单账号运行时状态落盘(napuketto status/stop 消费,2026-09-08 T8;
|
|
1660
|
+
* pid 记 boot 进程——树杀连带 self-host 孙进程)。
|
|
1661
|
+
*
|
|
1662
|
+
* 托管模式(supervisor 拉起)下 runtime.json 的所有权在 supervisor:`kind`、
|
|
1663
|
+
* `restartCount`、启动时间与 boot pid 由它写入,本函数只合并补充 selfHostPid /
|
|
1664
|
+
* selfHostCmdline / 生命周期状态。否则受管 boot 一启动就把 supervisor 写的
|
|
1665
|
+
* `supervisor-child` 覆写成 `single-boot` 并丢掉 restartCount(退出时再互相覆盖)。
|
|
1666
|
+
*/
|
|
1269
1667
|
function recordRuntimeState(dataRoot, account, child, status, exitCode) {
|
|
1668
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1669
|
+
const selfHostPid = child.pid;
|
|
1670
|
+
const selfHostCmdline = childCmdline$1(child);
|
|
1671
|
+
const cmdline = selfArgvFingerprint();
|
|
1672
|
+
const common = {
|
|
1673
|
+
pid: process.pid,
|
|
1674
|
+
...selfHostPid !== void 0 ? { selfHostPid } : {},
|
|
1675
|
+
...selfHostCmdline !== void 0 ? { selfHostCmdline } : {},
|
|
1676
|
+
status,
|
|
1677
|
+
...exitCode !== void 0 ? { exitCode } : {}
|
|
1678
|
+
};
|
|
1679
|
+
if (isSupervisedChild()) {
|
|
1680
|
+
patchAccountRuntime(dataRoot, account, common, {
|
|
1681
|
+
uin: account,
|
|
1682
|
+
pid: process.pid,
|
|
1683
|
+
startedAt,
|
|
1684
|
+
kind: "supervisor-child",
|
|
1685
|
+
status,
|
|
1686
|
+
restartCount: 0,
|
|
1687
|
+
...selfHostPid !== void 0 ? { selfHostPid } : {},
|
|
1688
|
+
...selfHostCmdline !== void 0 ? { selfHostCmdline } : {},
|
|
1689
|
+
...exitCode !== void 0 ? { exitCode } : {}
|
|
1690
|
+
});
|
|
1691
|
+
return;
|
|
1692
|
+
}
|
|
1270
1693
|
writeAccountRuntime(dataRoot, {
|
|
1271
1694
|
uin: account,
|
|
1272
1695
|
pid: process.pid,
|
|
1273
|
-
...
|
|
1274
|
-
|
|
1696
|
+
...selfHostPid !== void 0 ? { selfHostPid } : {},
|
|
1697
|
+
...selfHostCmdline !== void 0 ? { selfHostCmdline } : {},
|
|
1698
|
+
startedAt,
|
|
1275
1699
|
kind: "single-boot",
|
|
1276
1700
|
status,
|
|
1701
|
+
...cmdline !== void 0 ? { cmdline } : {},
|
|
1277
1702
|
...exitCode !== void 0 ? { exitCode } : {}
|
|
1278
1703
|
});
|
|
1279
1704
|
}
|
|
1280
1705
|
/** 优雅关停编排(2026-10-25 生命周期契约):触发后等 self-host 经自身哨兵/信号
|
|
1281
1706
|
* 处理自行退出(exit 0),10s 未退则 kill 兜底(Windows 下为硬杀)——
|
|
1282
1707
|
* boot 进程随后随 child 退出自然返回(退出码 0 = 请求式正常退出)。
|
|
1283
|
-
*
|
|
1708
|
+
* 返回句柄由 runSingleAccount 在 waitSelfHostExit 的 finally 中 dispose:
|
|
1709
|
+
* 常驻结束后不残留信号监听/哨兵定时器。 */
|
|
1284
1710
|
function installGracefulStop(child, dataRoot, account) {
|
|
1285
1711
|
let stopArmed = false;
|
|
1712
|
+
let fallback;
|
|
1286
1713
|
const killIfHung = () => {
|
|
1287
1714
|
if (child.exitCode !== null || child.killed) return;
|
|
1288
1715
|
logger.warn({ account }, "自建宿主未在限时内退出,强制结束");
|
|
1289
|
-
child.
|
|
1716
|
+
const pid = child.pid;
|
|
1717
|
+
if (pid === void 0) return;
|
|
1718
|
+
killProcessTree(pid, { onError: (message) => logger.warn({
|
|
1719
|
+
account,
|
|
1720
|
+
message
|
|
1721
|
+
}, "强制结束失败") });
|
|
1290
1722
|
};
|
|
1291
1723
|
const armGracefulStop = (reason) => {
|
|
1292
1724
|
if (stopArmed) return;
|
|
@@ -1295,21 +1727,41 @@ function installGracefulStop(child, dataRoot, account) {
|
|
|
1295
1727
|
account,
|
|
1296
1728
|
reason
|
|
1297
1729
|
}, "收到停止请求,等待自建宿主退出");
|
|
1298
|
-
setTimeout(killIfHung, GRACEFUL_STOP_TIMEOUT_MS)
|
|
1730
|
+
fallback = setTimeout(killIfHung, GRACEFUL_STOP_TIMEOUT_MS);
|
|
1731
|
+
fallback.unref?.();
|
|
1299
1732
|
};
|
|
1300
|
-
watchStopSentinel({
|
|
1733
|
+
const cancelSentinel = watchStopSentinel({
|
|
1301
1734
|
dataRoot,
|
|
1302
1735
|
account,
|
|
1303
1736
|
onTrigger: () => armGracefulStop("停止哨兵")
|
|
1304
1737
|
});
|
|
1305
1738
|
const onSignal = (signal) => {
|
|
1306
|
-
|
|
1739
|
+
writeAccountStopSentinel(dataRoot, account);
|
|
1307
1740
|
armGracefulStop(`信号 ${signal}`);
|
|
1308
1741
|
};
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1742
|
+
const signalHandlers = [
|
|
1743
|
+
{
|
|
1744
|
+
signal: "SIGINT",
|
|
1745
|
+
listener: () => onSignal("SIGINT")
|
|
1746
|
+
},
|
|
1747
|
+
{
|
|
1748
|
+
signal: "SIGTERM",
|
|
1749
|
+
listener: () => onSignal("SIGTERM")
|
|
1750
|
+
},
|
|
1751
|
+
{
|
|
1752
|
+
signal: "SIGBREAK",
|
|
1753
|
+
listener: () => onSignal("SIGBREAK")
|
|
1754
|
+
}
|
|
1755
|
+
];
|
|
1756
|
+
for (const { signal, listener } of signalHandlers) process.on(signal, listener);
|
|
1757
|
+
return {
|
|
1758
|
+
isStopping: () => stopArmed,
|
|
1759
|
+
dispose: () => {
|
|
1760
|
+
for (const { signal, listener } of signalHandlers) process.off(signal, listener);
|
|
1761
|
+
cancelSentinel();
|
|
1762
|
+
if (fallback !== void 0) clearTimeout(fallback);
|
|
1763
|
+
}
|
|
1764
|
+
};
|
|
1313
1765
|
}
|
|
1314
1766
|
/**
|
|
1315
1767
|
* 常驻:等待自建宿主进程退出(exit / error 两路径均 resolve,去留由 self-host 决定)。
|
|
@@ -1346,15 +1798,21 @@ async function waitSelfHostExit(child, dataRoot, account, isStopping) {
|
|
|
1346
1798
|
/** 启动单个账号(自建宿主 + 常驻)。 */
|
|
1347
1799
|
async function runSingleAccount(opts = {}) {
|
|
1348
1800
|
const dataRoot = resolveDataRoot(opts.dataDir);
|
|
1801
|
+
const account = opts.qq ?? "default";
|
|
1802
|
+
if (account === "all") throw configError("账号 \"all\" 是停止哨兵保留值,拒绝启动");
|
|
1803
|
+
const cfgDir = accountDir(dataRoot, account);
|
|
1349
1804
|
const qq = await locateQqFiles(dataRoot, opts);
|
|
1350
1805
|
if (qq === void 0) return;
|
|
1351
|
-
const account = opts.qq ?? "default";
|
|
1352
|
-
const cfgDir = path.join(dataRoot, account);
|
|
1353
1806
|
if (!ensureInstanceLockFree(cfgDir)) return;
|
|
1354
1807
|
const { child } = await startSelfHost(opts, qq, cfgDir, dataRoot);
|
|
1355
1808
|
forwardChildOutput(child);
|
|
1356
1809
|
recordRuntimeState(dataRoot, account, child, "running");
|
|
1357
|
-
|
|
1810
|
+
const stop = installGracefulStop(child, dataRoot, account);
|
|
1811
|
+
try {
|
|
1812
|
+
await waitSelfHostExit(child, dataRoot, account, stop.isStopping);
|
|
1813
|
+
} finally {
|
|
1814
|
+
stop.dispose();
|
|
1815
|
+
}
|
|
1358
1816
|
}
|
|
1359
1817
|
// src/runtime/supervisor.ts
|
|
1360
1818
|
/**
|
|
@@ -1388,9 +1846,21 @@ function computeRestartDelayMs(baseDelayMs, consecutiveFailures) {
|
|
|
1388
1846
|
const exponent = Math.max(consecutiveFailures - 1, 0);
|
|
1389
1847
|
return Math.min(baseDelayMs * 2 ** exponent, MAX_RESTART_DELAY_MS);
|
|
1390
1848
|
}
|
|
1391
|
-
/**
|
|
1849
|
+
/**
|
|
1850
|
+
* 解析账号列表(显式 -q 优先,否则主配置 accounts 过滤启用项)。
|
|
1851
|
+
* 显式 -q 在此再次校验格式并拒绝重复:重复 qq 会并发拉起同一账号,后一个
|
|
1852
|
+
* 子进程覆盖 ctx.children 的 Map 项,导致实例锁冲突与状态文件互相覆盖。
|
|
1853
|
+
*/
|
|
1392
1854
|
function resolveAccounts(opts, config) {
|
|
1393
|
-
if (opts.qqs !== void 0 && opts.qqs.length > 0)
|
|
1855
|
+
if (opts.qqs !== void 0 && opts.qqs.length > 0) {
|
|
1856
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1857
|
+
return opts.qqs.map((qq) => {
|
|
1858
|
+
parseCliQq(qq);
|
|
1859
|
+
if (seen.has(qq)) throw configError(`-q/--qq 重复指定账号: "${qq}"(每个账号只能出现一次)`);
|
|
1860
|
+
seen.add(qq);
|
|
1861
|
+
return { qq };
|
|
1862
|
+
});
|
|
1863
|
+
}
|
|
1394
1864
|
return config.accounts.filter((acct) => acct.enabled !== false);
|
|
1395
1865
|
}
|
|
1396
1866
|
/** 解析重启延迟(显式 -q 用默认,主配置场景用配置值)。 */
|
|
@@ -1405,21 +1875,47 @@ function resolveRestartDelay(opts, config) {
|
|
|
1405
1875
|
*/
|
|
1406
1876
|
function forwardPrefixed(stream, uin, prefixEnabled) {
|
|
1407
1877
|
if (stream === null) return;
|
|
1408
|
-
|
|
1878
|
+
forwardLines(stream, (line) => {
|
|
1409
1879
|
process.stdout.write(prefixEnabled ? `[${uin}] ${line}\n` : `${line}\n`);
|
|
1410
1880
|
});
|
|
1411
1881
|
}
|
|
1412
|
-
/**
|
|
1882
|
+
/** 子进程启动参数(spawn 与 runtime.json cmdline 共用,防两处漂移)。 */
|
|
1883
|
+
function childArgs(ctx, acct) {
|
|
1884
|
+
const args = [
|
|
1885
|
+
ctx.entry,
|
|
1886
|
+
"-q",
|
|
1887
|
+
acct.qq,
|
|
1888
|
+
"--data-dir",
|
|
1889
|
+
ctx.dataRoot
|
|
1890
|
+
];
|
|
1891
|
+
if (ctx.stubDir !== void 0) args.push("--stub-dir", ctx.stubDir);
|
|
1892
|
+
if (ctx.qqPath !== void 0) args.push("--qq-path", ctx.qqPath);
|
|
1893
|
+
return args;
|
|
1894
|
+
}
|
|
1895
|
+
/** 托管子进程(boot)命令行参数指纹:树杀前 PID 复用校验用(不含可执行文件)。 */
|
|
1896
|
+
function childCmdline(ctx, acct) {
|
|
1897
|
+
return childArgs(ctx, acct).join(" ");
|
|
1898
|
+
}
|
|
1899
|
+
/** 账号进程退出落 runtime exited(status/stop 消费)。
|
|
1900
|
+
* 合并写入:保留受管 boot 已记录的 selfHostPid / selfHostCmdline,不整文件覆盖。 */
|
|
1413
1901
|
function writeAccountExited(ctx, acct, child, exitCode, restartCount) {
|
|
1414
|
-
|
|
1902
|
+
const cmdline = childCmdline(ctx, acct);
|
|
1903
|
+
const fallback = {
|
|
1415
1904
|
uin: acct.qq,
|
|
1416
1905
|
pid: child.pid ?? 0,
|
|
1417
1906
|
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1418
1907
|
kind: "supervisor-child",
|
|
1419
1908
|
status: "exited",
|
|
1420
1909
|
exitCode,
|
|
1910
|
+
restartCount,
|
|
1911
|
+
cmdline
|
|
1912
|
+
};
|
|
1913
|
+
patchAccountRuntime(ctx.dataRoot, acct.qq, {
|
|
1914
|
+
...child.pid !== void 0 ? { pid: child.pid } : {},
|
|
1915
|
+
status: "exited",
|
|
1916
|
+
exitCode,
|
|
1421
1917
|
restartCount
|
|
1422
|
-
});
|
|
1918
|
+
}, fallback);
|
|
1423
1919
|
}
|
|
1424
1920
|
/**
|
|
1425
1921
|
* 守护重启编排(issue #144):短生命周期崩溃按指数退避,稳定运行超过阈值后
|
|
@@ -1442,12 +1938,15 @@ function scheduleRestart(ctx, acct, code, signal, startedAtMs, restartCount) {
|
|
|
1442
1938
|
if (shortLived) logger.warn(fields, "账号启动后短时间内退出,指数退避后重启");
|
|
1443
1939
|
else logger.info(fields, "账号退出,准备重启");
|
|
1444
1940
|
ctx.restartCounts.set(acct.qq, restartCount + 1);
|
|
1445
|
-
setTimeout(() => {
|
|
1941
|
+
const timer = setTimeout(() => {
|
|
1942
|
+
ctx.pendingRestarts.delete(acct.qq);
|
|
1446
1943
|
startAccount(ctx, acct);
|
|
1447
1944
|
}, delayMs);
|
|
1945
|
+
ctx.pendingRestarts.set(acct.qq, timer);
|
|
1448
1946
|
}
|
|
1449
1947
|
/** 账号子进程退出编排:配置失败免重启(78)/ 守护重启 / 落 runtime exited。 */
|
|
1450
1948
|
function handleAccountExit(ctx, acct, child, code, signal, startedAtMs, restartCount) {
|
|
1949
|
+
if (ctx.isFinished()) return;
|
|
1451
1950
|
ctx.children.delete(acct.qq);
|
|
1452
1951
|
logger.info({
|
|
1453
1952
|
qq: acct.qq,
|
|
@@ -1460,6 +1959,8 @@ function handleAccountExit(ctx, acct, child, code, signal, startedAtMs, restartC
|
|
|
1460
1959
|
code
|
|
1461
1960
|
}, "账号因配置校验失败退出(78),不自动重启");
|
|
1462
1961
|
writeAccountExited(ctx, acct, child, code, restartCount);
|
|
1962
|
+
ctx.exitedCodes.set(acct.qq, code);
|
|
1963
|
+
ctx.onSettled();
|
|
1463
1964
|
return;
|
|
1464
1965
|
}
|
|
1465
1966
|
if (!ctx.isStopping() && ctx.autoRestart) {
|
|
@@ -1467,24 +1968,20 @@ function handleAccountExit(ctx, acct, child, code, signal, startedAtMs, restartC
|
|
|
1467
1968
|
return;
|
|
1468
1969
|
}
|
|
1469
1970
|
writeAccountExited(ctx, acct, child, code, restartCount);
|
|
1971
|
+
ctx.exitedCodes.set(acct.qq, code);
|
|
1972
|
+
ctx.onSettled();
|
|
1470
1973
|
}
|
|
1471
1974
|
/** 启动一个账号子进程(exit 后按 autoRestart 守护重启)。 */
|
|
1472
1975
|
function startAccount(ctx, acct) {
|
|
1473
|
-
if (ctx.isStopping()) return;
|
|
1976
|
+
if (ctx.isStopping() || ctx.isFinished()) return;
|
|
1474
1977
|
const restartCount = ctx.restartCounts.get(acct.qq) ?? 0;
|
|
1978
|
+
ctx.exitedCodes.delete(acct.qq);
|
|
1475
1979
|
logger.debug({
|
|
1476
1980
|
qq: acct.qq,
|
|
1477
1981
|
pid: process.pid,
|
|
1478
1982
|
restartCount
|
|
1479
1983
|
}, "启动账号");
|
|
1480
|
-
const args =
|
|
1481
|
-
ctx.entry,
|
|
1482
|
-
"-q",
|
|
1483
|
-
acct.qq,
|
|
1484
|
-
"--data-dir",
|
|
1485
|
-
ctx.dataRoot
|
|
1486
|
-
];
|
|
1487
|
-
if (ctx.stubDir !== void 0) args.push("--stub-dir", ctx.stubDir);
|
|
1984
|
+
const args = childArgs(ctx, acct);
|
|
1488
1985
|
const child = spawn(process.execPath, args, {
|
|
1489
1986
|
stdio: [
|
|
1490
1987
|
"inherit",
|
|
@@ -1494,6 +1991,7 @@ function startAccount(ctx, acct) {
|
|
|
1494
1991
|
env: {
|
|
1495
1992
|
...process.env,
|
|
1496
1993
|
NAPUKETTO_NO_BANNER: "1",
|
|
1994
|
+
[SUPERVISOR_CHILD_ENV]: "1",
|
|
1497
1995
|
...ctx.childEnv
|
|
1498
1996
|
}
|
|
1499
1997
|
});
|
|
@@ -1507,18 +2005,22 @@ function startAccount(ctx, acct) {
|
|
|
1507
2005
|
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1508
2006
|
kind: "supervisor-child",
|
|
1509
2007
|
status: "running",
|
|
1510
|
-
restartCount
|
|
2008
|
+
restartCount,
|
|
2009
|
+
cmdline: childCmdline(ctx, acct)
|
|
1511
2010
|
});
|
|
1512
2011
|
child.on("exit", (code, signal) => {
|
|
1513
2012
|
handleAccountExit(ctx, acct, child, code, signal, startedAtMs, restartCount);
|
|
1514
2013
|
});
|
|
1515
2014
|
child.on("error", (err) => {
|
|
2015
|
+
if (ctx.isFinished()) return;
|
|
1516
2016
|
const { message } = err;
|
|
1517
2017
|
logger.error({
|
|
1518
2018
|
qq: acct.qq,
|
|
1519
2019
|
err
|
|
1520
2020
|
}, `账号启动失败: ${message}`);
|
|
1521
2021
|
ctx.children.delete(acct.qq);
|
|
2022
|
+
ctx.exitedCodes.set(acct.qq, 1);
|
|
2023
|
+
ctx.onSettled();
|
|
1522
2024
|
});
|
|
1523
2025
|
}
|
|
1524
2026
|
/** 停止全部子进程,全部退出后父进程退出(2026-10-25 优雅化)。
|
|
@@ -1530,9 +2032,22 @@ function startAccount(ctx, acct) {
|
|
|
1530
2032
|
*/
|
|
1531
2033
|
function stopAll(ctx) {
|
|
1532
2034
|
logger.info("收到退出信号,停止全部账号");
|
|
2035
|
+
for (const timer of ctx.pendingRestarts.values()) clearTimeout(timer);
|
|
2036
|
+
ctx.pendingRestarts.clear();
|
|
1533
2037
|
writeStopSentinel(ctx.dataRoot, "all");
|
|
1534
2038
|
const forceTimer = setTimeout(() => {
|
|
1535
|
-
for (const child of ctx.children
|
|
2039
|
+
for (const [uin, child] of ctx.children) {
|
|
2040
|
+
const pid = child.pid;
|
|
2041
|
+
if (pid === void 0) continue;
|
|
2042
|
+
const runtime = readAccountRuntime(ctx.dataRoot, uin);
|
|
2043
|
+
killProcessTree(pid, {
|
|
2044
|
+
...runtime?.selfHostPid !== void 0 ? { extraPids: [runtime.selfHostPid] } : {},
|
|
2045
|
+
onError: (message) => logger.warn({
|
|
2046
|
+
uin,
|
|
2047
|
+
message
|
|
2048
|
+
}, "强制停止失败")
|
|
2049
|
+
});
|
|
2050
|
+
}
|
|
1536
2051
|
process.exit(0);
|
|
1537
2052
|
}, FORCE_EXIT_MS);
|
|
1538
2053
|
forceTimer.unref?.();
|
|
@@ -1561,7 +2076,40 @@ async function runSupervisor(opts = {}) {
|
|
|
1561
2076
|
const children = /* @__PURE__ */ new Map();
|
|
1562
2077
|
const restartCounts = /* @__PURE__ */ new Map();
|
|
1563
2078
|
const crashCounts = /* @__PURE__ */ new Map();
|
|
2079
|
+
const pendingRestarts = /* @__PURE__ */ new Map();
|
|
2080
|
+
const exitedCodes = /* @__PURE__ */ new Map();
|
|
1564
2081
|
let stopping = false;
|
|
2082
|
+
let finished = false;
|
|
2083
|
+
let resolveResident;
|
|
2084
|
+
const resident = new Promise((resolve) => {
|
|
2085
|
+
resolveResident = resolve;
|
|
2086
|
+
});
|
|
2087
|
+
const signalHandlers = [];
|
|
2088
|
+
/** 结束常驻:清理定时器/信号监听 → 写退出码 → 释放 runSupervisor 的 await。 */
|
|
2089
|
+
const finish = (code) => {
|
|
2090
|
+
if (finished) return;
|
|
2091
|
+
finished = true;
|
|
2092
|
+
for (const timer of pendingRestarts.values()) clearTimeout(timer);
|
|
2093
|
+
pendingRestarts.clear();
|
|
2094
|
+
for (const { signal, listener } of signalHandlers) process.off(signal, listener);
|
|
2095
|
+
process.exitCode = code;
|
|
2096
|
+
resolveResident?.();
|
|
2097
|
+
};
|
|
2098
|
+
/**
|
|
2099
|
+
* 空闲收尾:既无存活子进程也无待重启定时器时不再常驻。
|
|
2100
|
+
* 典型场景:autoRestart=false 且全部子进程退出;全部账号因配置失败(78)退出
|
|
2101
|
+
* (不进重启队列)。没有这一步,supervisor 会被信号监听句柄永久挂起,即便
|
|
2102
|
+
* 早已没有任何账号在跑。
|
|
2103
|
+
*/
|
|
2104
|
+
const maybeFinish = () => {
|
|
2105
|
+
if (stopping || finished || children.size > 0 || pendingRestarts.size > 0) return;
|
|
2106
|
+
const codes = [...exitedCodes.values()];
|
|
2107
|
+
if (codes.length > 0 && codes.every((code) => code === EXIT_CONFIG_INVALID)) {
|
|
2108
|
+
finish(EXIT_CONFIG_INVALID);
|
|
2109
|
+
return;
|
|
2110
|
+
}
|
|
2111
|
+
finish(codes.some((code) => code !== 0) ? 1 : 0);
|
|
2112
|
+
};
|
|
1565
2113
|
const logCfg = resolveCliLogConfig(opts.dataDir);
|
|
1566
2114
|
const ctx = {
|
|
1567
2115
|
dataRoot,
|
|
@@ -1569,9 +2117,14 @@ async function runSupervisor(opts = {}) {
|
|
|
1569
2117
|
restartDelayMs,
|
|
1570
2118
|
autoRestart: config.autoRestart,
|
|
1571
2119
|
...opts.stubDir !== void 0 ? { stubDir: opts.stubDir } : {},
|
|
2120
|
+
...opts.qqPath !== void 0 ? { qqPath: opts.qqPath } : {},
|
|
1572
2121
|
children,
|
|
1573
2122
|
restartCounts,
|
|
1574
2123
|
crashCounts,
|
|
2124
|
+
pendingRestarts,
|
|
2125
|
+
exitedCodes,
|
|
2126
|
+
onSettled: maybeFinish,
|
|
2127
|
+
isFinished: () => finished,
|
|
1575
2128
|
childEnv: {
|
|
1576
2129
|
...effectiveConsoleEnv(logCfg),
|
|
1577
2130
|
...config.nativeMediaPatch === false ? { NAPUTO_DISABLE_MEDIA_PATCH: "1" } : {}
|
|
@@ -1579,25 +2132,35 @@ async function runSupervisor(opts = {}) {
|
|
|
1579
2132
|
prefixEnabled: effectiveConsoleFormat(logCfg) === "pretty",
|
|
1580
2133
|
isStopping: () => stopping
|
|
1581
2134
|
};
|
|
2135
|
+
const supervisorCmdline = selfArgvFingerprint();
|
|
1582
2136
|
writeSupervisorRuntime(dataRoot, {
|
|
1583
2137
|
pid: process.pid,
|
|
1584
2138
|
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1585
|
-
accounts: accounts.map((a) => a.qq)
|
|
2139
|
+
accounts: accounts.map((a) => a.qq),
|
|
2140
|
+
...supervisorCmdline !== void 0 ? { cmdline: supervisorCmdline } : {}
|
|
1586
2141
|
});
|
|
1587
2142
|
for (const acct of accounts) startAccount(ctx, acct);
|
|
1588
2143
|
const shutdown = () => {
|
|
1589
|
-
if (stopping) return;
|
|
2144
|
+
if (stopping || finished) return;
|
|
1590
2145
|
stopping = true;
|
|
1591
2146
|
stopAll(ctx);
|
|
1592
2147
|
};
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
2148
|
+
for (const signal of [
|
|
2149
|
+
"SIGINT",
|
|
2150
|
+
"SIGTERM",
|
|
2151
|
+
"SIGBREAK"
|
|
2152
|
+
]) {
|
|
2153
|
+
process.on(signal, shutdown);
|
|
2154
|
+
signalHandlers.push({
|
|
2155
|
+
signal,
|
|
2156
|
+
listener: shutdown
|
|
2157
|
+
});
|
|
2158
|
+
}
|
|
1596
2159
|
watchStopSentinel({
|
|
1597
2160
|
dataRoot,
|
|
1598
2161
|
onTrigger: shutdown
|
|
1599
2162
|
});
|
|
1600
|
-
await
|
|
2163
|
+
await resident;
|
|
1601
2164
|
}
|
|
1602
2165
|
// src/commands/start.ts
|
|
1603
2166
|
/**
|
|
@@ -1628,12 +2191,26 @@ async function autoStart(opts) {
|
|
|
1628
2191
|
if (config.accounts.length === 0) throw configError("主配置没有账号,请编辑 napuketto.toml 填写 [[accounts]] 段");
|
|
1629
2192
|
await runSupervisor({
|
|
1630
2193
|
...opts.dataDir === void 0 ? {} : { dataDir: opts.dataDir },
|
|
1631
|
-
...opts.stubDir === void 0 ? {} : { stubDir: opts.stubDir }
|
|
2194
|
+
...opts.stubDir === void 0 ? {} : { stubDir: opts.stubDir },
|
|
2195
|
+
...opts.qqPath === void 0 ? {} : { qqPath: opts.qqPath }
|
|
1632
2196
|
});
|
|
1633
2197
|
}
|
|
2198
|
+
/**
|
|
2199
|
+
* -q 列表入口校验(2026-11 安全加固):格式/占位值复用主配置规则,重复值直接报错。
|
|
2200
|
+
* ConfigError → exit 78;放在分发最前,非法值不会进入数据目录拼接或 supervisor。
|
|
2201
|
+
*/
|
|
2202
|
+
function parseQqList(qqs) {
|
|
2203
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2204
|
+
for (const qq of qqs) {
|
|
2205
|
+
parseCliQq(qq);
|
|
2206
|
+
if (seen.has(qq)) throw configError(`-q/--qq 重复指定账号: "${qq}"(每个账号只能出现一次)`);
|
|
2207
|
+
seen.add(qq);
|
|
2208
|
+
}
|
|
2209
|
+
return qqs;
|
|
2210
|
+
}
|
|
1634
2211
|
/** 主命令分发:无 -q 读配置 supervisor 拉起 / 单 -q 单账号 / 多 -q supervisor。 */
|
|
1635
2212
|
async function dispatchMainAction(opts) {
|
|
1636
|
-
const qqs = opts.qq ?? [];
|
|
2213
|
+
const qqs = parseQqList(opts.qq ?? []);
|
|
1637
2214
|
if (qqs.length === 0) {
|
|
1638
2215
|
await autoStart(opts);
|
|
1639
2216
|
return;
|
|
@@ -1645,12 +2222,16 @@ async function dispatchMainAction(opts) {
|
|
|
1645
2222
|
await runSupervisor({
|
|
1646
2223
|
qqs,
|
|
1647
2224
|
...opts.dataDir === void 0 ? {} : { dataDir: opts.dataDir },
|
|
1648
|
-
...opts.stubDir === void 0 ? {} : { stubDir: opts.stubDir }
|
|
2225
|
+
...opts.stubDir === void 0 ? {} : { stubDir: opts.stubDir },
|
|
2226
|
+
...opts.qqPath === void 0 ? {} : { qqPath: opts.qqPath }
|
|
1649
2227
|
});
|
|
1650
2228
|
}
|
|
1651
|
-
/** supervisor 子命令用例(读主配置 accounts 批量拉起;-d 复用主命令 option)。 */
|
|
2229
|
+
/** supervisor 子命令用例(读主配置 accounts 批量拉起;-d / --qq-path 复用主命令 option)。 */
|
|
1652
2230
|
async function runSupervisorCommand(opts) {
|
|
1653
|
-
await runSupervisor(
|
|
2231
|
+
await runSupervisor({
|
|
2232
|
+
...opts.dataDir === void 0 ? {} : { dataDir: opts.dataDir },
|
|
2233
|
+
...opts.qqPath === void 0 ? {} : { qqPath: opts.qqPath }
|
|
2234
|
+
});
|
|
1654
2235
|
}
|
|
1655
2236
|
// src/cli/error.ts
|
|
1656
2237
|
/**
|
|
@@ -1746,16 +2327,22 @@ function registerConfigCommands(program) {
|
|
|
1746
2327
|
handleActionError(err);
|
|
1747
2328
|
}
|
|
1748
2329
|
});
|
|
1749
|
-
configCmd.command("list").description("列出全局配置与账号配置").action(async () => {
|
|
2330
|
+
configCmd.command("list").description("列出全局配置与账号配置").option("--show-secrets", "输出明文敏感字段(协议 token 等;默认脱敏)").action(async (opts) => {
|
|
1750
2331
|
try {
|
|
1751
|
-
await cmdConfigList(
|
|
2332
|
+
await cmdConfigList({
|
|
2333
|
+
...rootDataDir(program),
|
|
2334
|
+
...opts.showSecrets === true ? { showSecrets: true } : {}
|
|
2335
|
+
});
|
|
1752
2336
|
} catch (err) {
|
|
1753
2337
|
handleActionError(err);
|
|
1754
2338
|
}
|
|
1755
2339
|
});
|
|
1756
|
-
configCmd.command("apply <file>").description("应用外部配置(TOML/JSON,校验后写回全局配置)").action(async (file) => {
|
|
2340
|
+
configCmd.command("apply <file>").description("应用外部配置(TOML/JSON,校验后写回全局配置)").option("--show-secrets", "输出明文敏感字段(协议 token 等;默认脱敏)").action(async (file, opts) => {
|
|
1757
2341
|
try {
|
|
1758
|
-
await cmdConfigApply(file,
|
|
2342
|
+
await cmdConfigApply(file, {
|
|
2343
|
+
...rootDataDir(program),
|
|
2344
|
+
...opts.showSecrets === true ? { showSecrets: true } : {}
|
|
2345
|
+
});
|
|
1759
2346
|
} catch (err) {
|
|
1760
2347
|
handleActionError(err);
|
|
1761
2348
|
}
|
|
@@ -1773,11 +2360,15 @@ function registerConfigCommands(program) {
|
|
|
1773
2360
|
}
|
|
1774
2361
|
});
|
|
1775
2362
|
}
|
|
1776
|
-
/** 注册 supervisor 子命令(读主配置 accounts 批量拉起,P6;-d 复用主命令 option)。 */
|
|
2363
|
+
/** 注册 supervisor 子命令(读主配置 accounts 批量拉起,P6;-d / --qq-path 复用主命令 option)。 */
|
|
1777
2364
|
function registerSupervisorCommand(program) {
|
|
1778
2365
|
program.command("supervisor").description("多账号编排(读全局配置 accounts 拉起子进程)").action(async () => {
|
|
1779
2366
|
try {
|
|
1780
|
-
|
|
2367
|
+
const { dataDir, qqPath } = program.opts();
|
|
2368
|
+
await runSupervisorCommand({
|
|
2369
|
+
...dataDir === void 0 ? {} : { dataDir },
|
|
2370
|
+
...qqPath === void 0 ? {} : { qqPath }
|
|
2371
|
+
});
|
|
1781
2372
|
} catch (err) {
|
|
1782
2373
|
handleActionError(err);
|
|
1783
2374
|
}
|