@napuketto/cli 0.6.25 → 0.6.28

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/dist/index.mjs CHANGED
@@ -1,14 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import process from "node:process";
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";
3
+ import { CONFIG_FILE_MODE, ConfigBase, ConfigError, EXIT_CONFIG_INVALID, configError, createLogger, errorMessage, hasNumberProp, hasStringProp, isKernelError, 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 { dirname, extname, isAbsolute, join, resolve, sep } from "node:path";
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 { createInterface } from "node:readline";
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
  /**
@@ -207,9 +208,28 @@ const LEGACY_INLINE_CONFIG_ENV = "NAPKETTO_CONFIG_JSON";
207
208
  * 回退文件形态)。
208
209
  */
209
210
  function readInlineConfigText() {
210
- const raw = process.env[INLINE_CONFIG_ENV] ?? process.env[LEGACY_INLINE_CONFIG_ENV];
211
- if (raw === void 0 || raw.trim() === "") return;
212
- return raw;
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
+ };
213
233
  }
214
234
  /** 内联是否生效(boot/装配链决定「不碰文件」的判定口径,与 readInlineConfigText 同源)。 */
215
235
  function isInlineConfigActive() {
@@ -460,6 +480,8 @@ port = 3001
460
480
  # # pingIntervalMs = 15000 # 可选:应用层心跳间隔(毫秒,须 < 30000)
461
481
  # # chatTemplate = "[{player}] {content}" # 游戏聊天渲染模板
462
482
  # # joinTemplate = "{player} 加入了服务器" # 玩家进服模板
483
+ # # leaveTemplate = "{player} 离开了服务器" # 玩家退服模板
484
+ # # deathTemplate = "{player} {message}" # 玩家死亡模板(空消息显示「死亡了」)
463
485
 
464
486
  # ------------------------------------------------------------
465
487
  # Milky 协议(P0)
@@ -474,8 +496,6 @@ port = 3001
474
496
  # # eventModes = ["sse", "ws"] # /event 允许的连接形态
475
497
  # # webhooks = [] # 可选:额外事件推送地址(WebHook POST)
476
498
  # # cacheDir = "cache" # 可选:发送远程媒体 URI 的下载缓存目录
477
- # # leaveTemplate = "{player} 离开了服务器" # 玩家退服模板
478
- # # deathTemplate = "{player} {message}" # 玩家死亡模板(空消息显示「死亡了」)
479
499
  `;
480
500
  }
481
501
  // src/config/store.ts
@@ -548,7 +568,7 @@ function resolveCliConfigSource(opts = {}) {
548
568
  let sourceLogged = false;
549
569
  /**
550
570
  * 加载主配置(内联优先,2026-10-25 嵌入式契约):
551
- * NAPKETTO_CONFIG_JSON 非空 → 内存文档校验(不读 / 不写 / 不校验任何 toml
571
+ * NAPUKETTO_CONFIG_JSON 非空 → 内存文档校验(不读 / 不写 / 不校验任何 toml
552
572
  * 文件),打一行来源日志;否则现行文件链路(缺失自动落模板)。校验失败两形态
553
573
  * 同为 ConfigError(exit 78),文案区别只在来源标注。
554
574
  */
@@ -558,7 +578,7 @@ async function loadCliConfigWithSource(opts = {}) {
558
578
  const config = parseInlineConfig(resolved.text);
559
579
  if (!sourceLogged) {
560
580
  sourceLogged = true;
561
- opts.onInfo?.("配置来源: inline(NAPKETTO_CONFIG_JSON)");
581
+ opts.onInfo?.(`配置来源: inline(${inlineConfigEnvName() ?? "环境变量"})`);
562
582
  }
563
583
  return {
564
584
  config,
@@ -584,15 +604,22 @@ async function loadCliConfigWithSource(opts = {}) {
584
604
  * NAPUKETTO_LOG_FORMAT / NAPUKETTO_NO_BANNER / NAPUKETTO_LOG_COLORIZE,
585
605
  * 兼容旧拼写 NAPKETTO_LOG_LEVEL。
586
606
  */
587
- /** 已解析日志配置缓存(preAction 首次解析后固定;-d 后续变化不影响已构造 logger)。 */
607
+ /** 已解析日志配置缓存(同一数据根复用;显式传入不同数据根时重新解析)。 */
588
608
  let cachedConfig = null;
589
- /** 解析配置时用的数据根([log.file] 相对路径展开基准)。 */
609
+ /** 解析配置时用的数据根([log.file] 相对路径展开基准,兼缓存键)。 */
590
610
  let cachedDataRoot = resolveDataRoot();
591
611
  /** 同步解析日志配置(内联 > toml 文件的 [log] 段 + env 覆盖)。损坏/缺失配置回退缺省
592
612
  * (不阻塞启动:配置的严格校验由 loadCliConfig 主路径负责报错)。内联生效时不读
593
- * 任何 toml 文件(嵌入式契约,2026-10-25)。 */
613
+ * 任何 toml 文件(嵌入式契约,2026-10-25)。
614
+ *
615
+ * 缓存口径(2026-11 修正):显式 `dataDir` 解析出的根与缓存不一致时重新解析,
616
+ * 避免早期无参调用(缺省数据根)把后续 `-d` 指定数据根的配置/日志路径锁死;
617
+ * 无参调用始终复用当前缓存(preAction 解析后,懒构造 logger 的 LazyCliLogger
618
+ * 不能再用缺省根把 `-d` 的结果覆盖掉)。 */
594
619
  function resolveCliLogConfig(dataDir) {
595
- if (cachedConfig !== null) return cachedConfig;
620
+ if (cachedConfig !== null) {
621
+ if (dataDir === void 0 || resolveDataRoot(dataDir) === cachedDataRoot) return cachedConfig;
622
+ }
596
623
  cachedDataRoot = resolveDataRoot(dataDir);
597
624
  let section;
598
625
  if (isInlineConfigActive()) section = readInlineConfigSection("log");
@@ -860,6 +887,16 @@ async function cmdConfigValidate(opts) {
860
887
  * `napuketto status/stop/restart` 读文件 + liveness 检测 + 树杀(win32
861
888
  * taskkill /T /F,杀 boot 进程树连带 self-host 孙进程)+ detached 重启。
862
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;
863
900
  /** runtime.json 文件名。 */
864
901
  const RUNTIME_FILE = "runtime.json";
865
902
  /** supervisor.json 文件名。 */
@@ -885,11 +922,63 @@ function runtimeStatePath(dataRoot, uin) {
885
922
  function supervisorStatePath(dataRoot) {
886
923
  return join(dataRoot, SUPERVISOR_FILE);
887
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
+ }
888
953
  /** 写账号运行时状态(原子覆盖)。 */
889
954
  function writeAccountRuntime(dataRoot, state) {
890
- const path = runtimeStatePath(dataRoot, state.uin);
891
- mkdirSync(join(path, ".."), { recursive: true });
892
- writeFileSync(path, `${JSON.stringify(state, null, 2)}\n`, "utf8");
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);
893
982
  }
894
983
  /** 账号运行形态判定。 */
895
984
  function isAccountRuntimeKind(val) {
@@ -899,13 +988,17 @@ function isAccountRuntimeKind(val) {
899
988
  function isAccountRuntimeStatus(val) {
900
989
  return val === "running" || val === "exited";
901
990
  }
991
+ /** 可选字符串字段判定(缺省合法)。 */
992
+ function isOptionalString(val) {
993
+ return val === void 0 || typeof val === "string";
994
+ }
902
995
  /** runtime.json 形状守卫(损坏 / 旧格式 / 手工改错的文件一律判非法)。 */
903
996
  function isAccountRuntime(val) {
904
- 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"]);
905
998
  }
906
999
  /** supervisor.json 形状守卫。 */
907
1000
  function isSupervisorRuntime(val) {
908
- 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"]);
909
1002
  }
910
1003
  /** 读账号运行时状态(缺失/损坏返回 null)。 */
911
1004
  function readAccountRuntime(dataRoot, uin) {
@@ -914,8 +1007,7 @@ function readAccountRuntime(dataRoot, uin) {
914
1007
  }
915
1008
  /** 写 supervisor 运行时状态(数据根缺省时自动创建——首次在新目录 start 不再 ENOENT)。 */
916
1009
  function writeSupervisorRuntime(dataRoot, state) {
917
- mkdirSync(dataRoot, { recursive: true });
918
- writeFileSync(supervisorStatePath(dataRoot), `${JSON.stringify(state, null, 2)}\n`, "utf8");
1010
+ writeJsonAtomic(supervisorStatePath(dataRoot), state);
919
1011
  }
920
1012
  /** 读 supervisor 运行时状态(缺失返回 null)。 */
921
1013
  function readSupervisorRuntime(dataRoot) {
@@ -955,20 +1047,87 @@ function isPidAlive(pid) {
955
1047
  return isRecord(err) && err["code"] === "EPERM";
956
1048
  }
957
1049
  }
958
- /** 树杀命令构造(win32:taskkill /T /F 连孙进程;posix:kill 信号)。 */
959
- function killProcessTree(pid) {
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;
960
1071
  if (process.platform === "win32") {
961
- spawn("taskkill", [
1072
+ for (const target of targets) spawn("taskkill", [
962
1073
  "/PID",
963
- String(pid),
1074
+ String(target),
964
1075
  "/T",
965
1076
  "/F"
966
- ], { stdio: "ignore" });
1077
+ ], {
1078
+ stdio: "ignore",
1079
+ windowsHide: true
1080
+ }).on("error", (err) => {
1081
+ options.onError?.(`taskkill 失败(pid ${target}):${errorMessage(err)}`);
1082
+ });
967
1083
  return;
968
1084
  }
969
- try {
970
- process.kill(pid, "SIGTERM");
971
- } catch {}
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";
972
1131
  }
973
1132
  /** detached 拉起 node 进程(restart 用;立即返回不等待)。 */
974
1133
  function spawnDetached(args, cwd) {
@@ -985,6 +1144,7 @@ function aggregateStatus(runtimes, aliveFn = isPidAlive) {
985
1144
  return runtimes.map((r) => ({
986
1145
  uin: r.uin,
987
1146
  pid: r.pid,
1147
+ ...r.selfHostPid !== void 0 ? { selfHostPid: r.selfHostPid } : {},
988
1148
  alive: r.status === "running" ? aliveFn(r.pid) : false,
989
1149
  kind: r.kind,
990
1150
  startedAt: r.startedAt,
@@ -1045,18 +1205,70 @@ function cmdStatus(dataRoot, opts) {
1045
1205
  uin: row.uin,
1046
1206
  alive: row.alive,
1047
1207
  pid: row.pid,
1208
+ ...row.selfHostPid !== void 0 ? { selfHostPid: row.selfHostPid } : {},
1048
1209
  kind: row.kind,
1049
1210
  startedAt: row.startedAt,
1050
1211
  restartCount: row.restartCount,
1051
1212
  ...row.exitCode !== void 0 ? { exitCode: row.exitCode } : {}
1052
1213
  }, "账号状态");
1053
1214
  }
1054
- /** 树杀目标账号(按 runtime pid)。 */
1055
- function stopAccount(runtime) {
1056
- killProcessTree(runtime.pid);
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
+ });
1057
1269
  logger.info({
1058
1270
  uin: runtime.uin,
1059
- pid: runtime.pid
1271
+ pids: targets
1060
1272
  }, "已发送停止(树杀)");
1061
1273
  }
1062
1274
  /** stop:-q 停单账号;无 -q 停 supervisor + 全部账号兜底。
@@ -1065,25 +1277,54 @@ function stopAccount(runtime) {
1065
1277
  * (退出码 0)→ 超时残留树杀兜底 → 清理哨兵。单账号哨兵只命中对应 boot/self-host,
1066
1278
  * 不干扰同数据根的其他账号。
1067
1279
  */
1068
- /** stop -q:写单账号哨兵 → 等优雅退出 → 超时树杀兜底 → 清哨兵。 */
1280
+ /** stop -q:写单账号独立哨兵 → 等优雅退出 → 超时树杀兜底 → 清本账号哨兵。 */
1069
1281
  async function stopSingleAccount(dataRoot, target) {
1070
1282
  logger.info({
1071
1283
  uin: target.uin,
1072
1284
  pid: target.pid
1073
1285
  }, "已发送停止请求(哨兵),等待退出");
1074
- writeStopSentinel(dataRoot, target.uin);
1075
- const stragglers = await waitForPidsExit([target.pid]);
1076
- for (const pid of stragglers) {
1286
+ writeAccountStopSentinel(dataRoot, target.uin);
1287
+ const stragglers = await waitForPidsExit([target.pid, ...target.selfHostPid !== void 0 ? [target.selfHostPid] : []]);
1288
+ if (stragglers.length > 0) {
1077
1289
  logger.warn({
1078
1290
  uin: target.uin,
1079
- pid
1291
+ pids: stragglers
1080
1292
  }, "限时内未退出,树杀兜底");
1081
- killProcessTree(pid);
1293
+ killAccountTree(target);
1082
1294
  }
1083
- removeStopSentinel(dataRoot);
1295
+ removeAccountStopSentinel(dataRoot, target.uin);
1084
1296
  const supervisor = readSupervisorRuntime(dataRoot);
1085
1297
  if (supervisor !== null) logger.warn({ supervisorPid: supervisor.pid }, "supervisor 仍在运行且 autoRestart 开启时会自动拉起该账号;如需彻底停止请执行 napuketto stop(停 supervisor)");
1086
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
+ }
1087
1328
  async function cmdStop(dataRoot, opts) {
1088
1329
  assertOpsQq(opts);
1089
1330
  const runtimes = listAccountRuntimes(dataRoot);
@@ -1097,27 +1338,25 @@ async function cmdStop(dataRoot, opts) {
1097
1338
  await stopSingleAccount(dataRoot, target);
1098
1339
  return;
1099
1340
  }
1100
- const supervisor = readSupervisorRuntime(dataRoot);
1101
- const supervisorPid = supervisor !== null && isPidAlive(supervisor.pid) ? supervisor.pid : 0;
1102
- if (supervisor !== null) {
1103
- logger.info({ pid: supervisor.pid }, "已发送停止请求(哨兵),等待 supervisor 退出");
1104
- writeStopSentinel(dataRoot, "all");
1105
- const alive = await waitForPidsExit([supervisorPid]);
1106
- for (const pid of alive) {
1107
- logger.warn({ pid }, "supervisor 限时内未退出,树杀兜底");
1108
- killProcessTree(pid);
1109
- }
1110
- } else logger.warn("supervisor 未运行(无状态文件)");
1111
- const stragglers = await waitForPidsExit(runtimes.map((r) => r.pid));
1112
- for (const runtime of runtimes) if (stragglers.includes(runtime.pid)) stopAccount(runtime);
1341
+ await stopSupervisor(dataRoot);
1342
+ await stopStragglerAccounts(runtimes);
1113
1343
  removeStopSentinel(dataRoot);
1114
1344
  }
1115
- /** restart:stop 同目标 + detached 拉起。 */
1345
+ /** restart:stop 同目标 + detached 拉起(停止失败/入口缺失时不得继续拉起)。 */
1116
1346
  async function cmdRestart(dataRoot, opts) {
1117
1347
  assertOpsQq(opts);
1118
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
+ }
1119
1359
  await new Promise((resolve) => setTimeout(resolve, 1500));
1120
- const entry = process.argv[1] ?? "";
1121
1360
  const args = opts.qq !== void 0 ? [
1122
1361
  entry,
1123
1362
  "-q",
@@ -1135,6 +1374,77 @@ async function cmdRestart(dataRoot, opts) {
1135
1374
  qq: opts.qq ?? "(supervisor 全量)"
1136
1375
  }, "已 detached 拉起(日志不再接入当前终端,见数据目录 logs/)");
1137
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
+ }
1138
1448
  // src/runtime/qr.ts
1139
1449
  /**
1140
1450
  * 终端二维码渲染(uqr 编码 + half-block ANSI,2026-11-03 替代 qrcode 包)
@@ -1204,7 +1514,7 @@ const GRACEFUL_STOP_TIMEOUT_MS = 1e4;
1204
1514
  * 噪音判定走 loader 共享单一来源(isNativeNoiseLine,与 koishi IPC 路径同源)。
1205
1515
  */
1206
1516
  function forwardFiltered(input, out) {
1207
- createInterface({ input }).on("line", (line) => {
1517
+ forwardLines(input, (line) => {
1208
1518
  if (line.startsWith(QR_LINE_PREFIX)) {
1209
1519
  renderTerminalQr(line.slice(QR_LINE_PREFIX.length));
1210
1520
  return;
@@ -1334,29 +1644,81 @@ function forwardChildOutput(child) {
1334
1644
  if (child.stdout !== null) forwardFiltered(child.stdout, process.stdout);
1335
1645
  if (child.stderr !== null) forwardFiltered(child.stderr, process.stderr);
1336
1646
  }
1337
- /** 单账号运行时状态落盘(napuketto status/stop 消费,2026-09-08 T8;
1338
- * pid 记 boot 进程——树杀连带 self-host 孙进程)。 */
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
+ */
1339
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
+ }
1340
1693
  writeAccountRuntime(dataRoot, {
1341
1694
  uin: account,
1342
1695
  pid: process.pid,
1343
- ...child.pid !== void 0 ? { selfHostPid: child.pid } : {},
1344
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1696
+ ...selfHostPid !== void 0 ? { selfHostPid } : {},
1697
+ ...selfHostCmdline !== void 0 ? { selfHostCmdline } : {},
1698
+ startedAt,
1345
1699
  kind: "single-boot",
1346
1700
  status,
1701
+ ...cmdline !== void 0 ? { cmdline } : {},
1347
1702
  ...exitCode !== void 0 ? { exitCode } : {}
1348
1703
  });
1349
1704
  }
1350
1705
  /** 优雅关停编排(2026-10-25 生命周期契约):触发后等 self-host 经自身哨兵/信号
1351
1706
  * 处理自行退出(exit 0),10s 未退则 kill 兜底(Windows 下为硬杀)——
1352
1707
  * boot 进程随后随 child 退出自然返回(退出码 0 = 请求式正常退出)。
1353
- * @returns 「是否已收到停止请求」查询(退出日志 graceful 标注) */
1708
+ * 返回句柄由 runSingleAccount 在 waitSelfHostExit 的 finally 中 dispose:
1709
+ * 常驻结束后不残留信号监听/哨兵定时器。 */
1354
1710
  function installGracefulStop(child, dataRoot, account) {
1355
1711
  let stopArmed = false;
1712
+ let fallback;
1356
1713
  const killIfHung = () => {
1357
1714
  if (child.exitCode !== null || child.killed) return;
1358
1715
  logger.warn({ account }, "自建宿主未在限时内退出,强制结束");
1359
- child.kill();
1716
+ const pid = child.pid;
1717
+ if (pid === void 0) return;
1718
+ killProcessTree(pid, { onError: (message) => logger.warn({
1719
+ account,
1720
+ message
1721
+ }, "强制结束失败") });
1360
1722
  };
1361
1723
  const armGracefulStop = (reason) => {
1362
1724
  if (stopArmed) return;
@@ -1365,21 +1727,41 @@ function installGracefulStop(child, dataRoot, account) {
1365
1727
  account,
1366
1728
  reason
1367
1729
  }, "收到停止请求,等待自建宿主退出");
1368
- setTimeout(killIfHung, GRACEFUL_STOP_TIMEOUT_MS).unref?.();
1730
+ fallback = setTimeout(killIfHung, GRACEFUL_STOP_TIMEOUT_MS);
1731
+ fallback.unref?.();
1369
1732
  };
1370
- watchStopSentinel({
1733
+ const cancelSentinel = watchStopSentinel({
1371
1734
  dataRoot,
1372
1735
  account,
1373
1736
  onTrigger: () => armGracefulStop("停止哨兵")
1374
1737
  });
1375
1738
  const onSignal = (signal) => {
1376
- writeStopSentinel(dataRoot, account);
1739
+ writeAccountStopSentinel(dataRoot, account);
1377
1740
  armGracefulStop(`信号 ${signal}`);
1378
1741
  };
1379
- process.on("SIGINT", () => onSignal("SIGINT"));
1380
- process.on("SIGTERM", () => onSignal("SIGTERM"));
1381
- process.on("SIGBREAK", () => onSignal("SIGBREAK"));
1382
- return () => stopArmed;
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
+ };
1383
1765
  }
1384
1766
  /**
1385
1767
  * 常驻:等待自建宿主进程退出(exit / error 两路径均 resolve,去留由 self-host 决定)。
@@ -1425,7 +1807,12 @@ async function runSingleAccount(opts = {}) {
1425
1807
  const { child } = await startSelfHost(opts, qq, cfgDir, dataRoot);
1426
1808
  forwardChildOutput(child);
1427
1809
  recordRuntimeState(dataRoot, account, child, "running");
1428
- await waitSelfHostExit(child, dataRoot, account, installGracefulStop(child, dataRoot, account));
1810
+ const stop = installGracefulStop(child, dataRoot, account);
1811
+ try {
1812
+ await waitSelfHostExit(child, dataRoot, account, stop.isStopping);
1813
+ } finally {
1814
+ stop.dispose();
1815
+ }
1429
1816
  }
1430
1817
  // src/runtime/supervisor.ts
1431
1818
  /**
@@ -1488,21 +1875,47 @@ function resolveRestartDelay(opts, config) {
1488
1875
  */
1489
1876
  function forwardPrefixed(stream, uin, prefixEnabled) {
1490
1877
  if (stream === null) return;
1491
- createInterface({ input: stream }).on("line", (line) => {
1878
+ forwardLines(stream, (line) => {
1492
1879
  process.stdout.write(prefixEnabled ? `[${uin}] ${line}\n` : `${line}\n`);
1493
1880
  });
1494
1881
  }
1495
- /** 账号进程退出落 runtime exited(status/stop 消费)。 */
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,不整文件覆盖。 */
1496
1901
  function writeAccountExited(ctx, acct, child, exitCode, restartCount) {
1497
- writeAccountRuntime(ctx.dataRoot, {
1902
+ const cmdline = childCmdline(ctx, acct);
1903
+ const fallback = {
1498
1904
  uin: acct.qq,
1499
1905
  pid: child.pid ?? 0,
1500
1906
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1501
1907
  kind: "supervisor-child",
1502
1908
  status: "exited",
1503
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,
1504
1917
  restartCount
1505
- });
1918
+ }, fallback);
1506
1919
  }
1507
1920
  /**
1508
1921
  * 守护重启编排(issue #144):短生命周期崩溃按指数退避,稳定运行超过阈值后
@@ -1525,12 +1938,15 @@ function scheduleRestart(ctx, acct, code, signal, startedAtMs, restartCount) {
1525
1938
  if (shortLived) logger.warn(fields, "账号启动后短时间内退出,指数退避后重启");
1526
1939
  else logger.info(fields, "账号退出,准备重启");
1527
1940
  ctx.restartCounts.set(acct.qq, restartCount + 1);
1528
- setTimeout(() => {
1941
+ const timer = setTimeout(() => {
1942
+ ctx.pendingRestarts.delete(acct.qq);
1529
1943
  startAccount(ctx, acct);
1530
1944
  }, delayMs);
1945
+ ctx.pendingRestarts.set(acct.qq, timer);
1531
1946
  }
1532
1947
  /** 账号子进程退出编排:配置失败免重启(78)/ 守护重启 / 落 runtime exited。 */
1533
1948
  function handleAccountExit(ctx, acct, child, code, signal, startedAtMs, restartCount) {
1949
+ if (ctx.isFinished()) return;
1534
1950
  ctx.children.delete(acct.qq);
1535
1951
  logger.info({
1536
1952
  qq: acct.qq,
@@ -1543,6 +1959,8 @@ function handleAccountExit(ctx, acct, child, code, signal, startedAtMs, restartC
1543
1959
  code
1544
1960
  }, "账号因配置校验失败退出(78),不自动重启");
1545
1961
  writeAccountExited(ctx, acct, child, code, restartCount);
1962
+ ctx.exitedCodes.set(acct.qq, code);
1963
+ ctx.onSettled();
1546
1964
  return;
1547
1965
  }
1548
1966
  if (!ctx.isStopping() && ctx.autoRestart) {
@@ -1550,24 +1968,20 @@ function handleAccountExit(ctx, acct, child, code, signal, startedAtMs, restartC
1550
1968
  return;
1551
1969
  }
1552
1970
  writeAccountExited(ctx, acct, child, code, restartCount);
1971
+ ctx.exitedCodes.set(acct.qq, code);
1972
+ ctx.onSettled();
1553
1973
  }
1554
1974
  /** 启动一个账号子进程(exit 后按 autoRestart 守护重启)。 */
1555
1975
  function startAccount(ctx, acct) {
1556
- if (ctx.isStopping()) return;
1976
+ if (ctx.isStopping() || ctx.isFinished()) return;
1557
1977
  const restartCount = ctx.restartCounts.get(acct.qq) ?? 0;
1978
+ ctx.exitedCodes.delete(acct.qq);
1558
1979
  logger.debug({
1559
1980
  qq: acct.qq,
1560
1981
  pid: process.pid,
1561
1982
  restartCount
1562
1983
  }, "启动账号");
1563
- const args = [
1564
- ctx.entry,
1565
- "-q",
1566
- acct.qq,
1567
- "--data-dir",
1568
- ctx.dataRoot
1569
- ];
1570
- if (ctx.stubDir !== void 0) args.push("--stub-dir", ctx.stubDir);
1984
+ const args = childArgs(ctx, acct);
1571
1985
  const child = spawn(process.execPath, args, {
1572
1986
  stdio: [
1573
1987
  "inherit",
@@ -1577,6 +1991,7 @@ function startAccount(ctx, acct) {
1577
1991
  env: {
1578
1992
  ...process.env,
1579
1993
  NAPUKETTO_NO_BANNER: "1",
1994
+ [SUPERVISOR_CHILD_ENV]: "1",
1580
1995
  ...ctx.childEnv
1581
1996
  }
1582
1997
  });
@@ -1590,18 +2005,22 @@ function startAccount(ctx, acct) {
1590
2005
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1591
2006
  kind: "supervisor-child",
1592
2007
  status: "running",
1593
- restartCount
2008
+ restartCount,
2009
+ cmdline: childCmdline(ctx, acct)
1594
2010
  });
1595
2011
  child.on("exit", (code, signal) => {
1596
2012
  handleAccountExit(ctx, acct, child, code, signal, startedAtMs, restartCount);
1597
2013
  });
1598
2014
  child.on("error", (err) => {
2015
+ if (ctx.isFinished()) return;
1599
2016
  const { message } = err;
1600
2017
  logger.error({
1601
2018
  qq: acct.qq,
1602
2019
  err
1603
2020
  }, `账号启动失败: ${message}`);
1604
2021
  ctx.children.delete(acct.qq);
2022
+ ctx.exitedCodes.set(acct.qq, 1);
2023
+ ctx.onSettled();
1605
2024
  });
1606
2025
  }
1607
2026
  /** 停止全部子进程,全部退出后父进程退出(2026-10-25 优雅化)。
@@ -1613,9 +2032,22 @@ function startAccount(ctx, acct) {
1613
2032
  */
1614
2033
  function stopAll(ctx) {
1615
2034
  logger.info("收到退出信号,停止全部账号");
2035
+ for (const timer of ctx.pendingRestarts.values()) clearTimeout(timer);
2036
+ ctx.pendingRestarts.clear();
1616
2037
  writeStopSentinel(ctx.dataRoot, "all");
1617
2038
  const forceTimer = setTimeout(() => {
1618
- for (const child of ctx.children.values()) child.kill();
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
+ }
1619
2051
  process.exit(0);
1620
2052
  }, FORCE_EXIT_MS);
1621
2053
  forceTimer.unref?.();
@@ -1644,7 +2076,40 @@ async function runSupervisor(opts = {}) {
1644
2076
  const children = /* @__PURE__ */ new Map();
1645
2077
  const restartCounts = /* @__PURE__ */ new Map();
1646
2078
  const crashCounts = /* @__PURE__ */ new Map();
2079
+ const pendingRestarts = /* @__PURE__ */ new Map();
2080
+ const exitedCodes = /* @__PURE__ */ new Map();
1647
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
+ };
1648
2113
  const logCfg = resolveCliLogConfig(opts.dataDir);
1649
2114
  const ctx = {
1650
2115
  dataRoot,
@@ -1652,9 +2117,14 @@ async function runSupervisor(opts = {}) {
1652
2117
  restartDelayMs,
1653
2118
  autoRestart: config.autoRestart,
1654
2119
  ...opts.stubDir !== void 0 ? { stubDir: opts.stubDir } : {},
2120
+ ...opts.qqPath !== void 0 ? { qqPath: opts.qqPath } : {},
1655
2121
  children,
1656
2122
  restartCounts,
1657
2123
  crashCounts,
2124
+ pendingRestarts,
2125
+ exitedCodes,
2126
+ onSettled: maybeFinish,
2127
+ isFinished: () => finished,
1658
2128
  childEnv: {
1659
2129
  ...effectiveConsoleEnv(logCfg),
1660
2130
  ...config.nativeMediaPatch === false ? { NAPUTO_DISABLE_MEDIA_PATCH: "1" } : {}
@@ -1662,25 +2132,35 @@ async function runSupervisor(opts = {}) {
1662
2132
  prefixEnabled: effectiveConsoleFormat(logCfg) === "pretty",
1663
2133
  isStopping: () => stopping
1664
2134
  };
2135
+ const supervisorCmdline = selfArgvFingerprint();
1665
2136
  writeSupervisorRuntime(dataRoot, {
1666
2137
  pid: process.pid,
1667
2138
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1668
- accounts: accounts.map((a) => a.qq)
2139
+ accounts: accounts.map((a) => a.qq),
2140
+ ...supervisorCmdline !== void 0 ? { cmdline: supervisorCmdline } : {}
1669
2141
  });
1670
2142
  for (const acct of accounts) startAccount(ctx, acct);
1671
2143
  const shutdown = () => {
1672
- if (stopping) return;
2144
+ if (stopping || finished) return;
1673
2145
  stopping = true;
1674
2146
  stopAll(ctx);
1675
2147
  };
1676
- process.on("SIGINT", shutdown);
1677
- process.on("SIGTERM", shutdown);
1678
- process.on("SIGBREAK", shutdown);
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
+ }
1679
2159
  watchStopSentinel({
1680
2160
  dataRoot,
1681
2161
  onTrigger: shutdown
1682
2162
  });
1683
- await new Promise(() => {});
2163
+ await resident;
1684
2164
  }
1685
2165
  // src/commands/start.ts
1686
2166
  /**
@@ -1711,7 +2191,8 @@ async function autoStart(opts) {
1711
2191
  if (config.accounts.length === 0) throw configError("主配置没有账号,请编辑 napuketto.toml 填写 [[accounts]] 段");
1712
2192
  await runSupervisor({
1713
2193
  ...opts.dataDir === void 0 ? {} : { dataDir: opts.dataDir },
1714
- ...opts.stubDir === void 0 ? {} : { stubDir: opts.stubDir }
2194
+ ...opts.stubDir === void 0 ? {} : { stubDir: opts.stubDir },
2195
+ ...opts.qqPath === void 0 ? {} : { qqPath: opts.qqPath }
1715
2196
  });
1716
2197
  }
1717
2198
  /**
@@ -1741,25 +2222,71 @@ async function dispatchMainAction(opts) {
1741
2222
  await runSupervisor({
1742
2223
  qqs,
1743
2224
  ...opts.dataDir === void 0 ? {} : { dataDir: opts.dataDir },
1744
- ...opts.stubDir === void 0 ? {} : { stubDir: opts.stubDir }
2225
+ ...opts.stubDir === void 0 ? {} : { stubDir: opts.stubDir },
2226
+ ...opts.qqPath === void 0 ? {} : { qqPath: opts.qqPath }
1745
2227
  });
1746
2228
  }
1747
- /** supervisor 子命令用例(读主配置 accounts 批量拉起;-d 复用主命令 option)。 */
2229
+ /** supervisor 子命令用例(读主配置 accounts 批量拉起;-d / --qq-path 复用主命令 option)。 */
1748
2230
  async function runSupervisorCommand(opts) {
1749
- await runSupervisor(opts.dataDir === void 0 ? {} : { dataDir: opts.dataDir });
2231
+ await runSupervisor({
2232
+ ...opts.dataDir === void 0 ? {} : { dataDir: opts.dataDir },
2233
+ ...opts.qqPath === void 0 ? {} : { qqPath: opts.qqPath }
2234
+ });
1750
2235
  }
1751
2236
  // src/cli/error.ts
1752
2237
  /**
1753
- * CLI 动作错误出口(2026-10-25 退出码契约):
2238
+ * CLI 动作错误出口(2026-10-25 退出码契约;2026-11 预期错误去堆栈):
1754
2239
  * 0 = 请求式优雅关停(0.2.0 已有,不经此路径);78 = 配置校验失败
1755
2240
  * (ConfigError 一族,宿主据此区分「配置未就绪」与运行时崩溃,免重启);
1756
2241
  * 其余 = 1(运行时崩溃,现状不变)。
1757
2242
  *
1758
2243
  * 退出码只认错误类型(instanceof ConfigError),与日志文案完全解耦——
1759
2244
  * 文案是人读的,退出码是宿主消费的机器契约。
2245
+ *
2246
+ * 日志分两档:
2247
+ * - 预期内用户错误(ConfigError / KernelError INVALID_PARAM):消息链拼成单行,
2248
+ * 只带 errorType/code 轻量字段,不在默认级别打印堆栈;
2249
+ * - 预期外错误:保持 { err } 结构化输出(pino serializer 展开堆栈)。
2250
+ * 两档都保留 logger.debug({ err }) 的完整堆栈,排障不降级。
2251
+ */
2252
+ /** 消息链最大深度(防御异常 cause 环与超长链)。 */
2253
+ const MAX_CAUSE_DEPTH = 8;
2254
+ /**
2255
+ * 预期内用户错误:配置未就绪(ConfigError)或参数非法(INVALID_PARAM)。
2256
+ * ConfigError 本身就是 code=INVALID_PARAM 的 KernelError 子型,这里显式分开写,
2257
+ * 让「配置失败」与「参数非法」两类预期语义在分类处可见。
1760
2258
  */
1761
- /** 统一错误输出(结构化日志,错误对象经 pino serializer 带堆栈)。 */
2259
+ function isExpectedUserError(err) {
2260
+ return err instanceof ConfigError || isKernelError(err) && err.code === "INVALID_PARAM";
2261
+ }
2262
+ /**
2263
+ * 把 `err.message → cause.message → ...` 拼成单行提示:预期错误的文案本身就是
2264
+ * 结论(哪份配置、哪个字段、怎么改),比默认级别的堆栈更直接。换行折叠为空格
2265
+ * 保证单行;cause 环按已见对象截断。
2266
+ */
2267
+ function errorChainText(err) {
2268
+ const parts = [];
2269
+ const seen = /* @__PURE__ */ new Set();
2270
+ let current = err;
2271
+ while (current !== void 0 && current !== null && parts.length < MAX_CAUSE_DEPTH) {
2272
+ if (seen.has(current)) break;
2273
+ seen.add(current);
2274
+ const text = errorMessage(current).replace(/\s+/g, " ").trim();
2275
+ if (text !== "") parts.push(text);
2276
+ current = current instanceof Error ? current.cause : void 0;
2277
+ }
2278
+ return parts.join(" — ");
2279
+ }
2280
+ /** 统一错误输出(预期错误单行 + debug 堆栈;预期外错误保持结构化 err)。 */
1762
2281
  function reportError(err) {
2282
+ if (isExpectedUserError(err)) {
2283
+ logger.error({
2284
+ errorType: err.name,
2285
+ code: err.code
2286
+ }, errorChainText(err));
2287
+ logger.debug({ err }, "详细错误堆栈");
2288
+ return;
2289
+ }
1763
2290
  let message = String(err);
1764
2291
  if (err instanceof Error) {
1765
2292
  const { message: errMessage } = err;
@@ -1875,11 +2402,15 @@ function registerConfigCommands(program) {
1875
2402
  }
1876
2403
  });
1877
2404
  }
1878
- /** 注册 supervisor 子命令(读主配置 accounts 批量拉起,P6;-d 复用主命令 option)。 */
2405
+ /** 注册 supervisor 子命令(读主配置 accounts 批量拉起,P6;-d / --qq-path 复用主命令 option)。 */
1879
2406
  function registerSupervisorCommand(program) {
1880
2407
  program.command("supervisor").description("多账号编排(读全局配置 accounts 拉起子进程)").action(async () => {
1881
2408
  try {
1882
- await runSupervisorCommand(rootDataDir(program));
2409
+ const { dataDir, qqPath } = program.opts();
2410
+ await runSupervisorCommand({
2411
+ ...dataDir === void 0 ? {} : { dataDir },
2412
+ ...qqPath === void 0 ? {} : { qqPath }
2413
+ });
1883
2414
  } catch (err) {
1884
2415
  handleActionError(err);
1885
2416
  }