@napuketto/cli 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -3,172 +3,16 @@ import process from "node:process";
3
3
  import { ConfigBase, ConfigError, EXIT_CONFIG_INVALID, configError, createLogger, kernelError, parseLogConfig, parseToml, resolveConfigPath, resolveDataRoot, stringifyToml } from "@napuketto/kernel";
4
4
  import { Command } from "commander";
5
5
  import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
6
+ import { access, readFile, writeFile } from "node:fs/promises";
6
7
  import path, { dirname, extname, isAbsolute, join } from "node:path";
8
+ import { checkInstanceLock, defaultStubDir, isNativeNoiseLine, launchSelfHost, removeStopSentinel, resolveQqFiles, watchStopSentinel, writeStopSentinel } from "@napuketto/loader";
9
+ import { spawn } from "node:child_process";
7
10
  import { createInterface } from "node:readline";
8
11
  import { fileURLToPath } from "node:url";
9
- import { checkInstanceLock, defaultStubDir, isNativeNoiseLine, launchSelfHost, removeStopSentinel, resolveQqFiles, watchStopSentinel, writeStopSentinel } from "@napuketto/loader";
10
12
  import QRCode from "qrcode";
11
- import { spawn } from "node:child_process";
12
- import { access, readFile, writeFile } from "node:fs/promises";
13
- //#region src/config-template.ts
14
- /**
15
- * 配置模板(TOML 注释版,从 config-cmds.ts 拆分,2026-08-08 FTA 优化)。
16
- * `config init` 与首次启动(loadCliConfig)缺失时生成。
17
- *
18
- * 2026-08-08 结构拍板:**一个 QQ 账号一个 [[accounts]] 段,协议与通信配置嵌在
19
- * 账号内**([accounts.onebot11] / [accounts.satori]);账号必填(至少一个)。
20
- * dataDir 不再写死(缺省 = 项目根/.napuketto,跨平台),模板保持可移植。
21
- */
22
- /** 保留占位 QQ 号(模板默认值):必须替换为真实 QQ 号,否则启动校验报错。 */
23
- const RESERVED_PLACEHOLDER_QINS = ["123456", "654321"];
24
- function configTemplate() {
25
- return `# ============================================================
26
- # NapukettoQQ 全局配置文件
27
- # ============================================================
28
- # 本文件由 \`napuketto config init\` 生成(或首次启动自动生成)。
29
- # 本机配置不入库(.gitignore);修改后重启生效。
30
- #
31
- # 配置组织:一个 QQ 账号一个 [[accounts]] 段,协议与通信配置嵌在账号内
32
- # ([accounts.onebot11] / [accounts.satori] / [accounts.kurobot])。账号没有写
33
- # 某协议段 = 该账号不启用该协议。账号必填(至少一个,qq 必填)。
34
-
35
- # ------------------------------------------------------------
36
- # 全局配置(跨账号)
37
- # ------------------------------------------------------------
38
-
39
- # 数据根目录:账号目录/日志/缓存/QQ 数据存放位置。
40
- # 缺省 = <项目根>/.napuketto(部署场景,跨平台,无需修改)。
41
- # 支持绝对路径、"~/" 前缀(用户主目录)、相对路径(相对启动目录)。
42
- # dataDir = ".napuketto"
43
-
44
- # 多账号(supervisor)模式下,账号进程崩溃是否自动重启
45
- autoRestart = true
46
-
47
- # 崩溃后自动重启的延迟(毫秒)
48
- restartDelayMs = 2000
49
-
50
- # ------------------------------------------------------------
51
- # 日志([log],可选——不配置即用缺省:终端 pretty 多行 / 管道 single-line)
52
- # ------------------------------------------------------------
53
- # 嵌入式宿主(把 napuketto 打进服务端等场景)推荐:
54
- # [log]
55
- # format = "single-line" # 或 "json"(NDJSON,宿主按 level/module 精确路由)
56
- # level = "warn" # 控制台只留警告以上,细节进文件(配 [log.file])
57
- # banner = false
58
- #
59
- # [log]
60
- # format = "pretty" # pretty | single-line | json(缺省按 TTY 自动)
61
- # level = "info" # trace|debug|info|warn|error|fatal(控制台级别)
62
- # banner = true # 启动字符画
63
- # timestamp = "local" # local | iso8601 | elapsed
64
- # unboundReceive = true # false = 未绑定频道的接收行不打(kurobot 握手后生效)
65
- # [log.levels] # 按模块覆盖级别:cli / kernel / loader / ob11
66
- # # loader = "debug" # 例:终端上看接收行(默认已降 debug)
67
- # # ob11 = "debug" # 例:协议校准数据(含原始 hex)
68
- # [log.file] # 独立文件 sink(可选;级别可低于控制台)
69
- # # path = "logs/napuketto-console.log"
70
- # # level = "debug"
71
- #
72
- # 环境变量覆盖(优先级高于本文件):NAPUKETTO_LOG_LEVEL / NAPUKETTO_LOG_FORMAT /
73
- # NAPUKETTO_NO_BANNER(兼容旧拼写 NAPKETTO_LOG_LEVEL)。
74
-
75
- # ------------------------------------------------------------
76
- # 账号(至少一个,qq 必填)
77
- # ------------------------------------------------------------
78
-
79
- [[accounts]]
80
- qq = "${RESERVED_PLACEHOLDER_QINS[0]}" # 占位值,必须替换为你的 QQ 号,否则启动报错
81
- enabled = true # 是否启用(可选,缺省 true)
82
-
83
- [accounts.onebot11] # 该账号的 OneBot 11 配置(无此段 = 不启用 OB11)
84
-
85
- # 鉴权 token(全局默认):HTTP/WS 连接必须携带。
86
- # 校验方式:Authorization: Bearer <token> / 裸 token / URL 参数 ?access_token=<token>
87
- # 每个网络实例可单独覆盖(见下文各实例的 token 字段)。
88
- # 留空 = 不鉴权(仅本机调试推荐)。
89
- # token = ""
90
-
91
- # 心跳 meta 事件间隔(毫秒);0 = 关闭心跳事件
92
- heartbeatInterval = 3000
93
-
94
- # 是否上报机器人自己发的消息(OB11 规范默认不上报)
95
- reportSelfMessage = false
96
-
97
- # 消息内容格式:array = 消息段数组(标准 OneBot 11),string = CQ 码字符串
98
- messagePostFormat = "array"
99
-
100
- # 群文件报形式:false(默认)= message 事件 + file 段(go-cqhttp 兼容);
101
- # true = 群文件消息改报 group_upload notice 事件(替代 message 事件)
102
- groupUploadAsNotice = false
103
-
104
- # ---- HTTP 反向服务器(接收第三方 POST 指令),可配置多个 ----
105
- [[accounts.onebot11.httpServers]]
106
- enabled = true
107
- host = "127.0.0.1" # 监听地址;0.0.0.0 = 监听所有网卡(局域网可连)
108
- port = 3000
109
- # token = "abc" # 可选:覆盖全局 token
110
-
111
- # ---- HTTP 正向上报(Webhook:把事件 POST 到第三方地址),可配置多个 ----
112
- # [[accounts.onebot11.httpPostUrls]]
113
- # enabled = true
114
- # url = "http://127.0.0.1:8080/onebot" # 第三方接收地址
115
- # token = "abc" # 可选:覆盖全局 token
116
- # timeoutMs = 5000 # 可选:上报超时(毫秒),缺省不超时
117
-
118
- # ---- WS 反向服务器(外部 WS 客户端主动连入),可配置多个 ----
119
- [[accounts.onebot11.wsServers]]
120
- enabled = true
121
- host = "127.0.0.1"
122
- port = 3001
123
- # token = "abc" # 可选:覆盖全局 token
124
- # heartbeatInterval = 30000 # 可选:WS ping 间隔(毫秒)
125
-
126
- # ---- WS 正向客户端(主动连接外部 WS,双向),可配置多个 ----
127
- # [[accounts.onebot11.wsReverseUrls]]
128
- # enabled = true
129
- # url = "ws://127.0.0.1:8081/ws" # 第三方 WS 地址(ws:// 或 wss://)
130
- # token = "abc" # 可选:覆盖全局 token
131
- # reconnectDelayMs = 5000 # 可选:断线重连延迟(毫秒)
132
- # maxReconnectAttempts = 10 # 可选:最大重连次数(缺省无限)
133
- # rejectUnauthorized = true # 可选:wss:// 是否校验证书(自签证书设 false)
134
- # heartbeatInterval = 30000 # 可选:WS ping 间隔(毫秒)
135
-
136
- # 第二个账号示例(只开 Satori):
137
- # [[accounts]]
138
- # qq = "${RESERVED_PLACEHOLDER_QINS[1]}"
139
- # [accounts.satori]
140
- # # token = "" # 可选:Satori 鉴权 token
141
- # [[accounts.satori.httpServers]] # HTTP RPC(POST /v1/{resource}.{method})
142
- # enabled = true
143
- # host = "127.0.0.1"
144
- # port = 5500
145
- # [[accounts.satori.wsServers]] # WS 事件服务(/v1/events)
146
- # enabled = true
147
- # host = "127.0.0.1"
148
- # port = 5501
149
-
150
- # ------------------------------------------------------------
151
- # KuroBot 群服互通(kurobridge-ws 客户端,MVP-3)
152
- # ------------------------------------------------------------
153
- # 账号内写 [accounts.kurobot] 段即启用;不写 = 不启用。作为 WS 客户端
154
- # 主动连入 KuroBot 服务端(Minecraft 服务器 kurobot 插件)。
155
- # QQ 群文字 ↔ 游戏聊天双向互通;群命令(前缀开头)→ 游戏命令。
156
- # [accounts.kurobot]
157
- # url = "ws://127.0.0.1:25580" # 必填:KuroBot 服务端地址(ws:// 或 wss://)
158
- # # token = "" # 可选:鉴权 token(服务端配了则必填,错 token 拒连)
159
- # # client = "napukettoqq" # 可选:自报身份(缺省 napukettoqq/<版本>)
160
- # # commandPrefix = "/" # 可选:群命令前缀
161
- # # pingIntervalMs = 15000 # 可选:应用层心跳间隔(毫秒,须 < 30000)
162
- # # chatTemplate = "[{player}] {content}" # 游戏聊天渲染模板
163
- # # joinTemplate = "{player} 加入了服务器" # 玩家进服模板
164
- # # leaveTemplate = "{player} 离开了服务器" # 玩家退服模板
165
- # # deathTemplate = "{player} {message}" # 玩家死亡模板(空消息显示「死亡了」)
166
- `;
167
- }
168
- //#endregion
169
- //#region src/config-parse.ts
13
+ //#region src/config/schema.ts
170
14
  /**
171
- * 主配置类型与手写校验器(从 config-cmds.ts 拆分,2026-08-08 FTA 优化)
15
+ * 主配置类型与手写校验器(原 config-cmds.ts 拆分,2026-08-08 FTA 优化)
172
16
  *
173
17
  * 主配置 parse(不引入 zod):数据根 / 自动重启 / 重启延迟 / 账号列表。
174
18
  * 2026-08-08 结构拍板:**一个 QQ 账号一个 [[accounts]] 段,协议与通信配置嵌在
@@ -177,10 +21,12 @@ port = 3001
177
21
  * 全部校验错误为 ConfigError(2026-10-25 嵌入式退出码契约:CLI exit 78 一族,
178
22
  * 内联与文件两形态共用本校验器)。
179
23
  */
24
+ /** 保留占位 QQ 号(模板默认值):必须替换为真实 QQ 号,否则启动校验报错。 */
25
+ const RESERVED_PLACEHOLDER_QINS = ["123456", "654321"];
180
26
  /** 默认自动重启。 */
181
27
  const DEFAULT_AUTO_RESTART = true;
182
- /** 默认重启延迟(毫秒)。 */
183
- const DEFAULT_RESTART_DELAY_MS$1 = 2e3;
28
+ /** 默认重启延迟(毫秒;supervisor 显式 -q 场景复用,避免两处常量漂移)。 */
29
+ const DEFAULT_RESTART_DELAY_MS = 2e3;
184
30
  /** QQ 号格式:纯数字 5-11 位(QQ 号合法范围,勿写死 11 位)。 */
185
31
  const QQ_IN_FORMAT_RE = /^\d{5,11}$/;
186
32
  /** 解析账号内协议段(宽松对象,装配时由 zod schema 严格校验)。 */
@@ -208,7 +54,7 @@ function parseAutoRestart(raw) {
208
54
  }
209
55
  /** 解析 restartDelayMs(毫秒)。 */
210
56
  function parseRestartDelayMs(raw) {
211
- if (raw["restartDelayMs"] === void 0) return DEFAULT_RESTART_DELAY_MS$1;
57
+ if (raw["restartDelayMs"] === void 0) return DEFAULT_RESTART_DELAY_MS;
212
58
  if (typeof raw["restartDelayMs"] !== "number" || !Number.isInteger(raw["restartDelayMs"]) || raw["restartDelayMs"] <= 0) throw configError("主配置 restartDelayMs 必须是正整数");
213
59
  return raw["restartDelayMs"];
214
60
  }
@@ -297,7 +143,7 @@ function parseCliConfig(input) {
297
143
  };
298
144
  }
299
145
  //#endregion
300
- //#region src/config-inline.ts
146
+ //#region src/config/inline.ts
301
147
  /**
302
148
  * 内联配置(NAPKETTO_CONFIG_JSON,2026-10-25 嵌入式宿主契约)。
303
149
  *
@@ -307,8 +153,15 @@ function parseCliConfig(input) {
307
153
  * 内联生效时不读 / 不写 / 不校验任何 toml 文件。Windows 单环境变量上限 32767
308
154
  * 字符(约 32KB),嵌入式配置形状远小于该限(超限宿主退回文件形态)。
309
155
  *
310
- * 错误一概 ConfigError(exit 78 一族),文案指明来源为「内联配置」且不含任何
311
- * toml 文件路径。本模块不 import logger(logger.ts 反向依赖本模块判内联来源)。
156
+ * 读取口径分两档(有意为之):
157
+ * - parseInlineConfig:严格,主配置加载 / config validate 用;JSON 解析失败、
158
+ * 非对象、字段校验失败一律 ConfigError(exit 78 一族)。
159
+ * - readInlineConfigDoc / readInlineConfigSection:宽松,logger 读 [log] 段用;
160
+ * 坏文档返回 undefined(日志配置损坏不阻塞启动,严格校验由主配置路径负责)。
161
+ * loader 引导进程另有自己的宽松读取(编译期不静态依赖 kernel),两套不合并。
162
+ *
163
+ * 错误文案指明来源为「内联配置」且不含任何 toml 文件路径。本模块不 import
164
+ * logger(logger.ts 反向依赖本模块判内联来源)。
312
165
  */
313
166
  /** 内联配置 env 键(读取为精确键访问;Windows 上 process.env 本身大小写不敏感)。 */
314
167
  const INLINE_CONFIG_ENV = "NAPKETTO_CONFIG_JSON";
@@ -324,11 +177,31 @@ function readInlineConfigText() {
324
177
  function isInlineConfigActive() {
325
178
  return readInlineConfigText() !== void 0;
326
179
  }
180
+ /** JSON.parse 产物 → 配置对象(数组 / null / 原始值 → undefined)。 */
181
+ function asConfigObject(value) {
182
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return;
183
+ return value;
184
+ }
327
185
  /**
328
- * 内联 JSON 文本 → 校验后的主配置。JSON 解析失败 / 非对象 / 字段校验失败
329
- * 均抛 ConfigError(宿主消费 exit 78,不重试)。
186
+ * 读内联配置文档(宽松口径:未设置 / 空串 / JSON 解析失败 / 非对象 → undefined)。
187
+ * 供日志段等「坏配置不阻塞启动」的消费方使用。
330
188
  */
331
- function parseInlineConfig(text) {
189
+ function readInlineConfigDoc() {
190
+ const text = readInlineConfigText();
191
+ if (text === void 0) return;
192
+ try {
193
+ return asConfigObject(JSON.parse(text));
194
+ } catch {
195
+ return;
196
+ }
197
+ }
198
+ /** 读内联配置的单个顶层段(坏文档 → undefined;logger 读 [log] 用)。 */
199
+ function readInlineConfigSection(key) {
200
+ const doc = readInlineConfigDoc();
201
+ return doc === void 0 ? void 0 : doc[key];
202
+ }
203
+ /** 严格解析内联 JSON 对象(主配置校验入口;错误一概 ConfigError)。 */
204
+ function parseJsonObject(text) {
332
205
  let doc;
333
206
  try {
334
207
  doc = JSON.parse(text);
@@ -336,8 +209,16 @@ function parseInlineConfig(text) {
336
209
  const detail = err instanceof Error ? err.message : String(err);
337
210
  throw configError(`内联配置 JSON 解析失败: ${detail}`, { cause: err });
338
211
  }
339
- if (typeof doc !== "object" || doc === null || Array.isArray(doc)) throw configError("内联配置必须是 JSON 对象(与 napuketto.toml 同构)");
340
- return parseCliConfig(doc);
212
+ const object = asConfigObject(doc);
213
+ if (object === void 0) throw configError("内联配置必须是 JSON 对象(与 napuketto.toml 同构)");
214
+ return object;
215
+ }
216
+ /**
217
+ * 内联 JSON 文本 → 校验后的主配置。JSON 解析失败 / 非对象 / 字段校验失败
218
+ * 均抛 ConfigError(宿主消费 exit 78,不重试)。
219
+ */
220
+ function parseInlineConfig(text) {
221
+ return parseCliConfig(parseJsonObject(text));
341
222
  }
342
223
  //#endregion
343
224
  //#region src/logger.ts
@@ -364,12 +245,7 @@ function resolveCliLogConfig(dataDir) {
364
245
  if (cachedConfig !== null) return cachedConfig;
365
246
  cachedDataRoot = resolveDataRoot(dataDir);
366
247
  let section;
367
- const inlineText = readInlineConfigText();
368
- if (inlineText !== void 0) try {
369
- section = JSON.parse(inlineText)["log"];
370
- } catch {
371
- section = void 0;
372
- }
248
+ if (isInlineConfigActive()) section = readInlineConfigSection("log");
373
249
  else try {
374
250
  const configPath = resolveConfigPath({ dataRoot: cachedDataRoot });
375
251
  section = parseToml(readFileSync(configPath, "utf8"))["log"];
@@ -452,381 +328,169 @@ var LazyCliLogger = class {
452
328
  /** cli 进程日志(懒构造,配置见 resolveCliLogConfig)。 */
453
329
  const logger = new LazyCliLogger();
454
330
  //#endregion
455
- //#region src/action-error.ts
456
- /**
457
- * CLI 动作错误出口(2026-10-25 退出码契约):
458
- * 0 = 请求式优雅关停(0.2.0 已有,不经此路径);78 = 配置校验失败
459
- * (ConfigError 一族,宿主据此区分「配置未就绪」与运行时崩溃,免重启);
460
- * 其余 = 1(运行时崩溃,现状不变)。
461
- *
462
- * 退出码只认错误类型(instanceof ConfigError),与日志文案完全解耦——
463
- * 文案是人读的,退出码是宿主消费的机器契约。
464
- */
465
- /** 统一错误输出(结构化日志,错误对象经 pino serializer 带堆栈)。 */
466
- function reportError(err) {
467
- let message = String(err);
468
- if (err instanceof Error) {
469
- const { message: errMessage } = err;
470
- message = errMessage;
471
- }
472
- logger.error({ err }, message);
473
- }
474
- /** 统一 catch 出口:打印错误并按类型设置进程退出码(78 = 配置校验失败)。 */
475
- function handleActionError(err) {
476
- reportError(err);
477
- process.exitCode = err instanceof ConfigError ? EXIT_CONFIG_INVALID : 1;
478
- }
479
- //#endregion
480
- //#region src/runtime-state.ts
331
+ //#region src/config/template.ts
481
332
  /**
482
- * runtime-state.ts:账号运行时状态文件 + 进程控制原语(2026-09-08 T8)。
333
+ * 配置模板(TOML 注释版,原 config-cmds.ts 拆分,2026-08-08 FTA 优化)。
334
+ * `config init` 与首次启动(loadCliConfig)缺失时生成。
483
335
  *
484
- * 跨进程通信选型(决策记录):现有 IPC 为 stdio JSON 行协议(NAPUTO_IPC=1,
485
- * koishi 插件专用),supervisor 子进程不在此模式;引入独立通道(socket/pipe)
486
- * 复杂度高。采用 **PID 状态文件**:supervisor/单账号 boot 启动时把进程信息写
487
- * `<数据根>/<uin>/runtime.json`,supervisor 自身写 `<数据根>/supervisor.json`;
488
- * `napuketto status/stop/restart` 读文件 + liveness 检测 + 树杀(win32
489
- * taskkill /T /F,杀 boot 进程树连带 self-host 孙进程)+ detached 重启。
336
+ * 2026-08-08 结构拍板:**一个 QQ 账号一个 [[accounts]] 段,协议与通信配置嵌在
337
+ * 账号内**([accounts.onebot11] / [accounts.satori]);账号必填(至少一个)。
338
+ * dataDir 不再写死(缺省 = 项目根/.napuketto,跨平台),模板保持可移植。
490
339
  */
491
- /** runtime.json 文件名。 */
492
- const RUNTIME_FILE = "runtime.json";
493
- /** supervisor.json 文件名。 */
494
- const SUPERVISOR_FILE = "supervisor.json";
495
- /** 账号状态文件路径。 */
496
- function runtimeStatePath(dataRoot, uin) {
497
- return join(dataRoot, uin, RUNTIME_FILE);
498
- }
499
- /** supervisor 状态文件路径。 */
500
- function supervisorStatePath(dataRoot) {
501
- return join(dataRoot, SUPERVISOR_FILE);
502
- }
503
- /** 写账号运行时状态(原子覆盖)。 */
504
- function writeAccountRuntime(dataRoot, state) {
505
- const path = runtimeStatePath(dataRoot, state.uin);
506
- mkdirSync(join(path, ".."), { recursive: true });
507
- writeFileSync(path, `${JSON.stringify(state, null, 2)}\n`, "utf8");
508
- }
509
- /** 读账号运行时状态(缺失/损坏返回 null)。 */
510
- function readAccountRuntime(dataRoot, uin) {
511
- return readJson(runtimeStatePath(dataRoot, uin));
512
- }
513
- /** 写 supervisor 运行时状态。 */
514
- function writeSupervisorRuntime(dataRoot, state) {
515
- writeFileSync(supervisorStatePath(dataRoot), `${JSON.stringify(state, null, 2)}\n`, "utf8");
516
- }
517
- /** 读 supervisor 运行时状态(缺失返回 null)。 */
518
- function readSupervisorRuntime(dataRoot) {
519
- return readJson(supervisorStatePath(dataRoot));
520
- }
521
- /** 读 JSON 文件(缺失/解析失败返回 null)。 */
522
- function readJson(path) {
523
- try {
524
- return JSON.parse(readFileSync(path, "utf8"));
525
- } catch {
526
- return null;
527
- }
528
- }
529
- /** 列出数据根下全部账号运行时状态(扫一级目录 runtime.json)。 */
530
- function listAccountRuntimes(dataRoot) {
531
- let entries = [];
532
- try {
533
- entries = readdirSync(dataRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
534
- } catch {
535
- return [];
536
- }
537
- const out = [];
538
- for (const uin of entries) {
539
- const state = readAccountRuntime(dataRoot, uin);
540
- if (state !== null) out.push(state);
541
- }
542
- return out;
543
- }
544
- /** pid 存活检测(signal 0;EPERM 视为存活——进程存在但无权限)。 */
545
- function isPidAlive(pid) {
546
- if (!Number.isInteger(pid) || pid <= 0) return false;
547
- try {
548
- process.kill(pid, 0);
549
- return true;
550
- } catch (err) {
551
- return err.code === "EPERM";
552
- }
553
- }
554
- /** 树杀命令构造(win32:taskkill /T /F 连孙进程;posix:kill 信号)。 */
555
- function killProcessTree(pid) {
556
- if (process.platform === "win32") {
557
- spawn("taskkill", [
558
- "/PID",
559
- String(pid),
560
- "/T",
561
- "/F"
562
- ], { stdio: "ignore" });
563
- return;
564
- }
565
- try {
566
- process.kill(pid, "SIGTERM");
567
- } catch {}
568
- }
569
- /** detached 拉起 node 进程(restart 用;立即返回不等待)。 */
570
- function spawnDetached(args, cwd) {
571
- const child = spawn(process.execPath, args, {
572
- detached: true,
573
- stdio: "ignore",
574
- ...cwd !== void 0 ? { cwd } : {}
575
- });
576
- child.unref();
577
- return child;
578
- }
579
- /** 聚合各账号状态(liveness 修正:文件 running 但 pid 已死 → not running)。 */
580
- function aggregateStatus(runtimes, aliveFn = isPidAlive) {
581
- return runtimes.map((r) => ({
582
- uin: r.uin,
583
- pid: r.pid,
584
- alive: r.status === "running" ? aliveFn(r.pid) : false,
585
- kind: r.kind,
586
- startedAt: r.startedAt,
587
- restartCount: r.restartCount ?? 0,
588
- exitCode: r.exitCode
589
- }));
590
- }
591
- //#endregion
592
- //#region src/boot.ts
593
- /** 解析 workspace 包的 dist 入口(ESM 解析:包是 ESM-only,exports 无 require 条件)。 */
594
- async function packageEntry(pkg) {
595
- const url = await import.meta.resolve(pkg);
596
- return fileURLToPath(url);
597
- }
598
- /** QR 透出标记行前缀(loader bootstrap-core 非 IPC 模式输出,cli 解析终端渲染)。 */
599
- const QR_LINE_PREFIX = "NAPUTO_QR ";
600
- /** 优雅停等待上限(毫秒):超时 kill 兜底(Windows 下为硬杀)。 */
601
- const GRACEFUL_STOP_TIMEOUT_MS = 1e4;
602
- /**
603
- * 逐行转发子进程输出到父进程,过滤原生噪音。
604
- * readline 按 UTF-8 解码 pipe 字节流,再经 process.stdout(TTY 路径,
605
- * WriteConsoleW UTF-16)输出——顺带修复 pino 中文在 cmd.exe/管道 936 转码
606
- * 链路下的乱码(原生 printf 字节流无法从 JS 侧改编码,转 pipe 后统一解码)。
607
- *
608
- * NAPUTO_QR 标记行(loader bootstrap-core 输出,QR 登录二维码数据)不转发,
609
- * 解析后用 qrcode 包渲染终端二维码;png 落盘与 URL 提示由 kernel 日志完成。
610
- * 噪音判定走 loader 共享单一来源(isNativeNoiseLine,与 koishi IPC 路径同源)。
611
- */
612
- function forwardFiltered(input, out) {
613
- createInterface({ input }).on("line", (line) => {
614
- if (line.startsWith(QR_LINE_PREFIX)) {
615
- renderTerminalQr(line.slice(10));
616
- return;
617
- }
618
- if (isNativeNoiseLine(line)) return;
619
- out.write(`${line}\n`);
620
- });
621
- }
622
- /**
623
- * 渲染终端二维码(qrcode 包 terminal 模式,half-block 字符)。
624
- * 解析失败/无 url 时静默丢弃——标记行是内部协议,坏行不影响登录。
625
- */
626
- function renderTerminalQr(raw) {
627
- try {
628
- const { qrcodeUrl } = JSON.parse(raw);
629
- if (qrcodeUrl === void 0 || qrcodeUrl === "") return;
630
- QRCode.toString(qrcodeUrl, {
631
- type: "terminal",
632
- small: true
633
- }).then((str) => {
634
- process.stdout.write(`${str}\n`);
635
- }).catch(() => {});
636
- } catch {}
637
- }
638
- /** 解析自建宿主装配面的三个包入口(ESM 解析,顺序同旧实现)。 */
639
- async function resolvePackageEntries() {
640
- return {
641
- kernelEntry: await packageEntry("@napuketto/kernel"),
642
- adapterEntry: await packageEntry("@napuketto/adapter"),
643
- networkEntry: await packageEntry("@napuketto/network")
644
- };
645
- }
646
- /** stub QQNT.dll 目录(--stub-dir > NAPUTO_STUB_DIR > loader 包内闭源 submodule 默认)。 */
647
- function resolveStubDir(opts) {
648
- return opts.stubDir ?? process.env["NAPUTO_STUB_DIR"] ?? defaultStubDir();
649
- }
650
- /** 错误文案提取(Error 用 message,其余字符串化——保留旧日志文案语义)。 */
651
- function errorMessage(err) {
652
- return err instanceof Error ? err.message : String(err);
653
- }
654
- /** QQ 原生文件多级来源 + 自动下载(本机未装 QQ 时走下载管线)。
655
- * 失败记录可操作提示并置 exitCode 1,返回 undefined(调用方提前返回)。 */
656
- async function locateQqFiles(dataRoot, opts) {
657
- try {
658
- return await resolveQqFiles({
659
- dataRoot,
660
- ...opts.qqPath !== void 0 ? { qqPath: opts.qqPath } : {}
661
- });
662
- } catch (err) {
663
- logger.error({ err }, `定位/下载 QQ 原生文件失败:${errorMessage(err)}\n(本机未装 QQ 时自动下载官方安装包;若下载失败请检查网络,或手动安装 QQ、设置 NAPUTO_QQ_PATH 指定已有安装、NAPUTO_QQ_FILES 指定文件根、NAPUTO_QQ_URL 覆盖下载地址)`);
664
- process.exitCode = 1;
665
- return;
666
- }
667
- }
668
- /**
669
- * 单实例锁预检(2026-08-07 根治「多实例抢数据目录锁挂起」):同一账号数据
670
- * 目录只允许一个实例(QQ 原生层 MMKV/登录单例有锁,第二个实例抢不到锁会卡死)。
671
- * 占用 → 快速失败并提示占用 PID;残留(PID 已死 / PID 被复用,2026-09-10
672
- * cmdline 校验根治)→ self-host 会自动接管。真正的锁由 self-host 子进程
673
- * 获取/释放(它才是数据目录的实际持有者),cli 这里只做 spawn 前预检,
674
- * 给用户友好提示(supervisor 等批量拉起同用)。
675
- * @returns 可用 true;占用时记录错误并置 exitCode 1 返回 false
676
- */
677
- function ensureInstanceLockFree(cfgDir) {
678
- const { occupied, pid: holderPid } = checkInstanceLock(cfgDir);
679
- if (!occupied) return true;
680
- logger.error({
681
- pid: holderPid,
682
- dataDir: cfgDir
683
- }, "数据目录已被其他实例占用,拒绝启动(同一账号数据目录仅允许一个实例;占用校验已含 pid 复用检测,如仍误报请删除该目录下的 instance.lock)");
684
- process.exitCode = 1;
685
- return false;
686
- }
687
- /** 启动信息走结构化日志(时间戳 + 级别 + pid + 元数据,与 kernel 子进程格式一致)。
688
- * 2026-10-25 级别重分配:引导细节降 debug(banner 之外的定位/路径细节对运行
689
- * 状态无信息量),致命错误与登录/退出生命周期保持 info 及以上。 */
690
- function logBootInfo(qq, cfgDir) {
691
- logger.debug({
692
- qqVersion: qq.version,
693
- qqPath: qq.qqPath,
694
- source: qq.source
695
- }, "QQ 文件来源");
696
- logger.debug({ dataDir: cfgDir }, "数据目录");
697
- logger.debug("自建宿主引导(标准 node + stub QQNT.dll)");
698
- }
699
- /** launchSelfHost 调用参数构造(唯一启动路径:自建宿主,2026-08-07 用户拍板)。
700
- * configPath:全局配置文件(项目根 napuketto.toml),注入 NAPKETTO_CONFIG 供装配链读取;
701
- * 内联配置生效(NAPKETTO_CONFIG_JSON)时不解析、不注入——子进程经 env 继承
702
- * 内联文本,装配链按同一优先级读取;避免项目根探测出无关路径注入孙进程。
703
- * extraEnv:传播有效控制台渲染决策(子进程 stdout 恒 pipe,TTY 判定失真)+
704
- * 数据根(NAPUTO_DATA_ROOT,self-host 停止哨兵目录)。
705
- * cwd:子进程 cwd 指向数据根——QQ 原生层 fallback 落盘(guild1.db 等)落在专门
706
- * 的数据目录,不污染项目根(实测 08-07)。 */
707
- function buildLaunchOptions(ctx) {
708
- const { opts, qq, cfgDir, dataRoot, entries, stubDir } = ctx;
709
- return {
710
- qq,
711
- kernelEntry: entries.kernelEntry,
712
- adapterEntry: entries.adapterEntry,
713
- networkEntry: entries.networkEntry,
714
- cfgDir,
715
- cwd: dataRoot,
716
- ...isInlineConfigActive() ? {} : { configPath: resolveConfigPath({ dataRoot }) },
717
- selfHost: true,
718
- stdio: [
719
- "inherit",
720
- "pipe",
721
- "pipe"
722
- ],
723
- extraEnv: {
724
- ...effectiveConsoleEnv(resolveCliLogConfig(opts.dataDir)),
725
- NAPUTO_DATA_ROOT: dataRoot
726
- },
727
- ...opts.qq !== void 0 ? { quickUin: opts.qq } : {},
728
- stubDir
729
- };
730
- }
731
- /** 启动自建宿主子进程(包入口解析 → stub 目录 → 启动信息 → launchSelfHost)。
732
- * ⚠️ P2(2026-08-12):launchSelfHost 变 async(linux 场景需下载 win-node)。 */
733
- async function startSelfHost(opts, qq, cfgDir, dataRoot) {
734
- const entries = await resolvePackageEntries();
735
- const stubDir = resolveStubDir(opts);
736
- logBootInfo(qq, cfgDir);
737
- return await launchSelfHost(buildLaunchOptions({
738
- opts,
739
- qq,
740
- cfgDir,
741
- dataRoot,
742
- entries,
743
- stubDir
744
- }));
745
- }
746
- /** 接管子进程 stdout/stderr:过滤 MMKV / 符号查找失败等原生噪音,其余转发。 */
747
- function forwardChildOutput(child) {
748
- if (child.stdout !== null) forwardFiltered(child.stdout, process.stdout);
749
- if (child.stderr !== null) forwardFiltered(child.stderr, process.stderr);
750
- }
751
- /** 单账号运行时状态落盘(napuketto status/stop 消费,2026-09-08 T8;
752
- * pid 记 boot 进程——树杀连带 self-host 孙进程)。 */
753
- function recordRuntimeState(dataRoot, account, child, status, exitCode) {
754
- writeAccountRuntime(dataRoot, {
755
- uin: account,
756
- pid: process.pid,
757
- ...child.pid !== void 0 ? { selfHostPid: child.pid } : {},
758
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
759
- kind: "single-boot",
760
- status,
761
- ...exitCode !== void 0 ? { exitCode } : {}
762
- });
763
- }
764
- /** 优雅关停编排(2026-10-25 生命周期契约):触发后等 self-host 经自身哨兵/信号
765
- * 处理自行退出(exit 0),10s 未退则 kill 兜底(Windows 下为硬杀)——
766
- * boot 进程随后随 child 退出自然返回(退出码 0 = 请求式正常退出)。
767
- * @returns 「是否已收到停止请求」查询(退出日志 graceful 标注) */
768
- function installGracefulStop(child, dataRoot, account) {
769
- let stopArmed = false;
770
- const killIfHung = () => {
771
- if (child.exitCode !== null || child.killed) return;
772
- logger.warn({ account }, "自建宿主未在限时内退出,强制结束");
773
- child.kill();
774
- };
775
- const armGracefulStop = (reason) => {
776
- if (stopArmed) return;
777
- stopArmed = true;
778
- logger.info({
779
- account,
780
- reason
781
- }, "收到停止请求,等待自建宿主退出");
782
- setTimeout(killIfHung, GRACEFUL_STOP_TIMEOUT_MS).unref?.();
783
- };
784
- watchStopSentinel({
785
- dataRoot,
786
- account,
787
- onTrigger: () => armGracefulStop("停止哨兵")
788
- });
789
- const onSignal = (signal) => {
790
- writeStopSentinel(dataRoot, account);
791
- armGracefulStop(`信号 ${signal}`);
792
- };
793
- process.on("SIGINT", () => onSignal("SIGINT"));
794
- process.on("SIGTERM", () => onSignal("SIGTERM"));
795
- process.on("SIGBREAK", () => onSignal("SIGBREAK"));
796
- return () => stopArmed;
797
- }
798
- /** 常驻:等待自建宿主进程退出(exit / error 两路径均 resolve,去留由 self-host 决定)。 */
799
- async function waitSelfHostExit(child, dataRoot, account, isStopping) {
800
- await new Promise((resolve) => {
801
- child.on("exit", (code) => {
802
- logger.info({
803
- code,
804
- graceful: isStopping()
805
- }, "自建宿主进程退出");
806
- recordRuntimeState(dataRoot, account, child, "exited", code);
807
- resolve();
808
- });
809
- child.on("error", (err) => {
810
- logger.error({ err }, "自建宿主进程启动失败");
811
- resolve();
812
- });
813
- });
814
- }
815
- /** 启动单个账号(自建宿主 + 常驻)。 */
816
- async function runSingleAccount(opts = {}) {
817
- const dataRoot = resolveDataRoot(opts.dataDir);
818
- const qq = await locateQqFiles(dataRoot, opts);
819
- if (qq === void 0) return;
820
- const account = opts.qq ?? "default";
821
- const cfgDir = path.join(dataRoot, account);
822
- if (!ensureInstanceLockFree(cfgDir)) return;
823
- const { child } = await startSelfHost(opts, qq, cfgDir, dataRoot);
824
- forwardChildOutput(child);
825
- recordRuntimeState(dataRoot, account, child, "running");
826
- await waitSelfHostExit(child, dataRoot, account, installGracefulStop(child, dataRoot, account));
340
+ function configTemplate() {
341
+ return `# ============================================================
342
+ # NapukettoQQ 全局配置文件
343
+ # ============================================================
344
+ # 本文件由 \`napuketto config init\` 生成(或首次启动自动生成)。
345
+ # 本机配置不入库(.gitignore);修改后重启生效。
346
+ #
347
+ # 配置组织:一个 QQ 账号一个 [[accounts]] 段,协议与通信配置嵌在账号内
348
+ # ([accounts.onebot11] / [accounts.satori] / [accounts.kurobot])。账号没有写
349
+ # 某协议段 = 该账号不启用该协议。账号必填(至少一个,qq 必填)。
350
+
351
+ # ------------------------------------------------------------
352
+ # 全局配置(跨账号)
353
+ # ------------------------------------------------------------
354
+
355
+ # 数据根目录:账号目录/日志/缓存/QQ 数据存放位置。
356
+ # 缺省 = <项目根>/.napuketto(部署场景,跨平台,无需修改)。
357
+ # 支持绝对路径、"~/" 前缀(用户主目录)、相对路径(相对启动目录)。
358
+ # dataDir = ".napuketto"
359
+
360
+ # 多账号(supervisor)模式下,账号进程崩溃是否自动重启
361
+ autoRestart = true
362
+
363
+ # 崩溃后自动重启的延迟(毫秒)
364
+ restartDelayMs = 2000
365
+
366
+ # ------------------------------------------------------------
367
+ # 日志([log],可选——不配置即用缺省:终端 pretty 多行 / 管道 single-line)
368
+ # ------------------------------------------------------------
369
+ # 嵌入式宿主(把 napuketto 打进服务端等场景)推荐:
370
+ # [log]
371
+ # format = "single-line" # 或 "json"(NDJSON,宿主按 level/module 精确路由)
372
+ # level = "warn" # 控制台只留警告以上,细节进文件(配 [log.file])
373
+ # banner = false
374
+ #
375
+ # [log]
376
+ # format = "pretty" # pretty | single-line | json(缺省按 TTY 自动)
377
+ # level = "info" # trace|debug|info|warn|error|fatal(控制台级别)
378
+ # banner = true # 启动字符画
379
+ # timestamp = "local" # local | iso8601 | elapsed
380
+ # unboundReceive = true # false = 未绑定频道的接收行不打(kurobot 握手后生效)
381
+ # [log.levels] # 按模块覆盖级别:cli / kernel / loader / ob11
382
+ # # loader = "debug" # 例:终端上看接收行(默认已降 debug)
383
+ # # ob11 = "debug" # 例:协议校准数据(含原始 hex)
384
+ # [log.file] # 独立文件 sink(可选;级别可低于控制台)
385
+ # # path = "logs/napuketto-console.log"
386
+ # # level = "debug"
387
+ #
388
+ # 环境变量覆盖(优先级高于本文件):NAPUKETTO_LOG_LEVEL / NAPUKETTO_LOG_FORMAT /
389
+ # NAPUKETTO_NO_BANNER(兼容旧拼写 NAPKETTO_LOG_LEVEL)。
390
+
391
+ # ------------------------------------------------------------
392
+ # 账号(至少一个,qq 必填)
393
+ # ------------------------------------------------------------
394
+
395
+ [[accounts]]
396
+ qq = "${RESERVED_PLACEHOLDER_QINS[0]}" # 占位值,必须替换为你的 QQ 号,否则启动报错
397
+ enabled = true # 是否启用(可选,缺省 true)
398
+
399
+ [accounts.onebot11] # 该账号的 OneBot 11 配置(无此段 = 不启用 OB11)
400
+
401
+ # 鉴权 token(全局默认):HTTP/WS 连接必须携带。
402
+ # 校验方式:Authorization: Bearer <token> / 裸 token / URL 参数 ?access_token=<token>
403
+ # 每个网络实例可单独覆盖(见下文各实例的 token 字段)。
404
+ # 留空 = 不鉴权(仅本机调试推荐)。
405
+ # token = ""
406
+
407
+ # 心跳 meta 事件间隔(毫秒);0 = 关闭心跳事件
408
+ heartbeatInterval = 3000
409
+
410
+ # 是否上报机器人自己发的消息(OB11 规范默认不上报)
411
+ reportSelfMessage = false
412
+
413
+ # 消息内容格式:array = 消息段数组(标准 OneBot 11),string = CQ 码字符串
414
+ messagePostFormat = "array"
415
+
416
+ # 群文件报形式:false(默认)= message 事件 + file 段(go-cqhttp 兼容);
417
+ # true = 群文件消息改报 group_upload notice 事件(替代 message 事件)
418
+ groupUploadAsNotice = false
419
+
420
+ # ---- HTTP 反向服务器(接收第三方 POST 指令),可配置多个 ----
421
+ [[accounts.onebot11.httpServers]]
422
+ enabled = true
423
+ host = "127.0.0.1" # 监听地址;0.0.0.0 = 监听所有网卡(局域网可连)
424
+ port = 3000
425
+ # token = "abc" # 可选:覆盖全局 token
426
+
427
+ # ---- HTTP 正向上报(Webhook:把事件 POST 到第三方地址),可配置多个 ----
428
+ # [[accounts.onebot11.httpPostUrls]]
429
+ # enabled = true
430
+ # url = "http://127.0.0.1:8080/onebot" # 第三方接收地址
431
+ # token = "abc" # 可选:覆盖全局 token
432
+ # timeoutMs = 5000 # 可选:上报超时(毫秒),缺省不超时
433
+
434
+ # ---- WS 反向服务器(外部 WS 客户端主动连入),可配置多个 ----
435
+ [[accounts.onebot11.wsServers]]
436
+ enabled = true
437
+ host = "127.0.0.1"
438
+ port = 3001
439
+ # token = "abc" # 可选:覆盖全局 token
440
+ # heartbeatInterval = 30000 # 可选:WS ping 间隔(毫秒)
441
+
442
+ # ---- WS 正向客户端(主动连接外部 WS,双向),可配置多个 ----
443
+ # [[accounts.onebot11.wsReverseUrls]]
444
+ # enabled = true
445
+ # url = "ws://127.0.0.1:8081/ws" # 第三方 WS 地址(ws:// 或 wss://)
446
+ # token = "abc" # 可选:覆盖全局 token
447
+ # reconnectDelayMs = 5000 # 可选:断线重连延迟(毫秒)
448
+ # maxReconnectAttempts = 10 # 可选:最大重连次数(缺省无限)
449
+ # rejectUnauthorized = true # 可选:wss:// 是否校验证书(自签证书设 false)
450
+ # heartbeatInterval = 30000 # 可选:WS ping 间隔(毫秒)
451
+
452
+ # 第二个账号示例(只开 Satori):
453
+ # [[accounts]]
454
+ # qq = "${RESERVED_PLACEHOLDER_QINS[1]}"
455
+ # [accounts.satori]
456
+ # # token = "" # 可选:Satori 鉴权 token
457
+ # [[accounts.satori.httpServers]] # HTTP RPC(POST /v1/{resource}.{method})
458
+ # enabled = true
459
+ # host = "127.0.0.1"
460
+ # port = 5500
461
+ # [[accounts.satori.wsServers]] # WS 事件服务(/v1/events)
462
+ # enabled = true
463
+ # host = "127.0.0.1"
464
+ # port = 5501
465
+
466
+ # ------------------------------------------------------------
467
+ # KuroBot 群服互通(kurobridge-ws 客户端,MVP-3)
468
+ # ------------------------------------------------------------
469
+ # 账号内写 [accounts.kurobot] 段即启用;不写 = 不启用。作为 WS 客户端
470
+ # 主动连入 KuroBot 服务端(Minecraft 服务器 kurobot 插件)。
471
+ # QQ 群文字 ↔ 游戏聊天双向互通;群命令(前缀开头)→ 游戏命令。
472
+ # [accounts.kurobot]
473
+ # url = "ws://127.0.0.1:25580" # 必填:KuroBot 服务端地址(ws:// 或 wss://)
474
+ # # token = "" # 可选:鉴权 token(服务端配了则必填,错 token 拒连)
475
+ # # client = "napukettoqq" # 可选:自报身份(缺省 napukettoqq/<版本>)
476
+ # # commandPrefix = "/" # 可选:群命令前缀
477
+ # # pingIntervalMs = 15000 # 可选:应用层心跳间隔(毫秒,须 < 30000)
478
+ # # chatTemplate = "[{player}] {content}" # 游戏聊天渲染模板
479
+ # # joinTemplate = "{player} 加入了服务器" # 玩家进服模板
480
+ # # leaveTemplate = "{player} 离开了服务器" # 玩家退服模板
481
+ # # deathTemplate = "{player} {message}" # 玩家死亡模板(空消息显示「死亡了」)
482
+ `;
827
483
  }
828
484
  //#endregion
829
- //#region src/config-cmds.ts
485
+ //#region src/config/store.ts
486
+ /**
487
+ * 主配置 store:默认值、ConfigBase 子类、模板落盘、内联/文件来源加载。
488
+ *
489
+ * 从 config-cmds.ts 拆出(2026-10-25 模块收拢):
490
+ * - `CliConfigStore` 只负责 napuketto.toml 的读写/校验(kernel ConfigBase);
491
+ * - `loadCliConfigWithSource` 负责来源决议(NAPKETTO_CONFIG_JSON 优先)与来源日志;
492
+ * - 4 个 config 子命令留在 commands/config.ts,不反向依赖本文件的私有实现。
493
+ */
830
494
  /** 主配置默认值(dataRoot 为当前解析的数据根 = 项目根/.napuketto)。 */
831
495
  function defaultCliConfig(dataRoot) {
832
496
  return {
@@ -863,6 +527,23 @@ async function loadCliConfig(dataRoot) {
863
527
  await ensureConfigTemplate(store.path);
864
528
  return await store.load();
865
529
  }
530
+ /**
531
+ * 解析生效配置来源(loadCliConfigWithSource 与 config validate 无参分支共用):
532
+ * 内联非空 → inline;否则按 kernel resolveConfigPath 解析文件路径,并带回数据根。
533
+ */
534
+ function resolveCliConfigSource(opts = {}) {
535
+ const inlineText = readInlineConfigText();
536
+ if (inlineText !== void 0) return {
537
+ source: "inline",
538
+ text: inlineText
539
+ };
540
+ const dataRoot = resolveDataRoot(opts.dataDir);
541
+ return {
542
+ source: "file",
543
+ path: resolveConfigPath({ dataRoot }),
544
+ dataRoot
545
+ };
546
+ }
866
547
  /** 「配置来源」日志每进程至多一行(autoStart 与 runSupervisor 各加载一次)。 */
867
548
  let sourceLogged = false;
868
549
  /**
@@ -872,9 +553,9 @@ let sourceLogged = false;
872
553
  * 同为 ConfigError(exit 78),文案区别只在来源标注。
873
554
  */
874
555
  async function loadCliConfigWithSource(opts = {}) {
875
- const inlineText = readInlineConfigText();
876
- if (inlineText !== void 0) {
877
- const config = parseInlineConfig(inlineText);
556
+ const resolved = resolveCliConfigSource(opts);
557
+ if (resolved.source === "inline") {
558
+ const config = parseInlineConfig(resolved.text);
878
559
  if (!sourceLogged) {
879
560
  sourceLogged = true;
880
561
  logger.info("配置来源: inline(NAPKETTO_CONFIG_JSON)");
@@ -884,14 +565,14 @@ async function loadCliConfigWithSource(opts = {}) {
884
565
  source: "inline"
885
566
  };
886
567
  }
887
- const dataRoot = resolveDataRoot(opts.dataDir);
888
- const configPath = resolveConfigPath({ dataRoot });
889
568
  return {
890
- config: await loadCliConfig(dataRoot),
569
+ config: await loadCliConfig(resolved.dataRoot),
891
570
  source: "file",
892
- path: configPath
571
+ path: resolved.path
893
572
  };
894
573
  }
574
+ //#endregion
575
+ //#region src/commands/config.ts
895
576
  /** CliConfig → 普通对象(smol-toml stringify 入参)。 */
896
577
  function toRecord(config) {
897
578
  return config;
@@ -1013,36 +694,146 @@ async function validateConfigFile(path, dataRoot) {
1013
694
  async function cmdConfigValidate(opts) {
1014
695
  const { configPath, configJson } = opts;
1015
696
  if (configPath !== void 0 && configJson !== void 0) throw kernelError("config validate:--config 与 --config-json 只能二选一", "INVALID_PARAM");
1016
- const dataRoot = resolveDataRoot(opts.dataDir);
1017
697
  if (configJson !== void 0) {
1018
698
  parseInlineConfig(configJson);
1019
699
  return { source: "inline" };
1020
700
  }
1021
701
  if (configPath !== void 0) {
1022
- await validateConfigFile(configPath, dataRoot);
702
+ await validateConfigFile(configPath, resolveDataRoot(opts.dataDir));
1023
703
  return {
1024
704
  source: "file",
1025
705
  path: configPath
1026
706
  };
1027
707
  }
1028
- const inlineText = readInlineConfigText();
1029
- if (inlineText !== void 0) {
1030
- parseInlineConfig(inlineText);
708
+ const resolved = resolveCliConfigSource(opts);
709
+ if (resolved.source === "inline") {
710
+ parseInlineConfig(resolved.text);
1031
711
  return { source: "inline" };
1032
712
  }
1033
- const path = resolveConfigPath({ dataRoot });
1034
- await validateConfigFile(path, dataRoot);
713
+ await validateConfigFile(resolved.path, resolved.dataRoot);
1035
714
  return {
1036
715
  source: "file",
1037
- path
716
+ path: resolved.path
1038
717
  };
1039
718
  }
1040
719
  //#endregion
1041
- //#region src/ops-commands.ts
720
+ //#region src/runtime/state.ts
721
+ /**
722
+ * state.ts:账号运行时状态文件 + 进程控制原语(2026-09-08 T8)。
723
+ *
724
+ * 跨进程通信选型(决策记录):现有 IPC 为 stdio JSON 行协议(NAPUTO_IPC=1,
725
+ * koishi 插件专用),supervisor 子进程不在此模式;引入独立通道(socket/pipe)
726
+ * 复杂度高。采用 **PID 状态文件**:supervisor/单账号 boot 启动时把进程信息写
727
+ * `<数据根>/<uin>/runtime.json`,supervisor 自身写 `<数据根>/supervisor.json`;
728
+ * `napuketto status/stop/restart` 读文件 + liveness 检测 + 树杀(win32
729
+ * taskkill /T /F,杀 boot 进程树连带 self-host 孙进程)+ detached 重启。
730
+ */
731
+ /** runtime.json 文件名。 */
732
+ const RUNTIME_FILE = "runtime.json";
733
+ /** supervisor.json 文件名。 */
734
+ const SUPERVISOR_FILE = "supervisor.json";
735
+ /** 账号状态文件路径。 */
736
+ function runtimeStatePath(dataRoot, uin) {
737
+ return join(dataRoot, uin, RUNTIME_FILE);
738
+ }
739
+ /** supervisor 状态文件路径。 */
740
+ function supervisorStatePath(dataRoot) {
741
+ return join(dataRoot, SUPERVISOR_FILE);
742
+ }
743
+ /** 写账号运行时状态(原子覆盖)。 */
744
+ function writeAccountRuntime(dataRoot, state) {
745
+ const path = runtimeStatePath(dataRoot, state.uin);
746
+ mkdirSync(join(path, ".."), { recursive: true });
747
+ writeFileSync(path, `${JSON.stringify(state, null, 2)}\n`, "utf8");
748
+ }
749
+ /** 读账号运行时状态(缺失/损坏返回 null)。 */
750
+ function readAccountRuntime(dataRoot, uin) {
751
+ return readJson(runtimeStatePath(dataRoot, uin));
752
+ }
753
+ /** 写 supervisor 运行时状态。 */
754
+ function writeSupervisorRuntime(dataRoot, state) {
755
+ writeFileSync(supervisorStatePath(dataRoot), `${JSON.stringify(state, null, 2)}\n`, "utf8");
756
+ }
757
+ /** 读 supervisor 运行时状态(缺失返回 null)。 */
758
+ function readSupervisorRuntime(dataRoot) {
759
+ return readJson(supervisorStatePath(dataRoot));
760
+ }
761
+ /** 读 JSON 文件(缺失/解析失败返回 null)。 */
762
+ function readJson(path) {
763
+ try {
764
+ return JSON.parse(readFileSync(path, "utf8"));
765
+ } catch {
766
+ return null;
767
+ }
768
+ }
769
+ /** 列出数据根下全部账号运行时状态(扫一级目录 runtime.json)。 */
770
+ function listAccountRuntimes(dataRoot) {
771
+ let entries = [];
772
+ try {
773
+ entries = readdirSync(dataRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
774
+ } catch {
775
+ return [];
776
+ }
777
+ const out = [];
778
+ for (const uin of entries) {
779
+ const state = readAccountRuntime(dataRoot, uin);
780
+ if (state !== null) out.push(state);
781
+ }
782
+ return out;
783
+ }
784
+ /** pid 存活检测(signal 0;EPERM 视为存活——进程存在但无权限)。 */
785
+ function isPidAlive(pid) {
786
+ if (!Number.isInteger(pid) || pid <= 0) return false;
787
+ try {
788
+ process.kill(pid, 0);
789
+ return true;
790
+ } catch (err) {
791
+ return err.code === "EPERM";
792
+ }
793
+ }
794
+ /** 树杀命令构造(win32:taskkill /T /F 连孙进程;posix:kill 信号)。 */
795
+ function killProcessTree(pid) {
796
+ if (process.platform === "win32") {
797
+ spawn("taskkill", [
798
+ "/PID",
799
+ String(pid),
800
+ "/T",
801
+ "/F"
802
+ ], { stdio: "ignore" });
803
+ return;
804
+ }
805
+ try {
806
+ process.kill(pid, "SIGTERM");
807
+ } catch {}
808
+ }
809
+ /** detached 拉起 node 进程(restart 用;立即返回不等待)。 */
810
+ function spawnDetached(args, cwd) {
811
+ const child = spawn(process.execPath, args, {
812
+ detached: true,
813
+ stdio: "ignore",
814
+ ...cwd !== void 0 ? { cwd } : {}
815
+ });
816
+ child.unref();
817
+ return child;
818
+ }
819
+ /** 聚合各账号状态(liveness 修正:文件 running 但 pid 已死 → not running)。 */
820
+ function aggregateStatus(runtimes, aliveFn = isPidAlive) {
821
+ return runtimes.map((r) => ({
822
+ uin: r.uin,
823
+ pid: r.pid,
824
+ alive: r.status === "running" ? aliveFn(r.pid) : false,
825
+ kind: r.kind,
826
+ startedAt: r.startedAt,
827
+ restartCount: r.restartCount ?? 0,
828
+ exitCode: r.exitCode
829
+ }));
830
+ }
831
+ //#endregion
832
+ //#region src/commands/ops.ts
1042
833
  /**
1043
- * ops-commands.ts:status / stop / restart 运维命令实现(2026-09-08 T8)。
834
+ * ops.ts:status / stop / restart 运维命令实现(2026-09-08 T8)。
1044
835
  *
1045
- * 数据源:runtime-state 状态文件(supervisor/单账号 boot 写入)+ liveness 检测。
836
+ * 数据源:runtime/state 状态文件(supervisor/单账号 boot 写入)+ liveness 检测。
1046
837
  * stop/restart 语义(2026-10-25 优雅化):
1047
838
  * - stop -q <uin>:写单账号停止哨兵 → 等该账号进程链优雅退出 → 超时树杀兜底。
1048
839
  * ⚠️ supervisor 在跑且 autoRestart 时账号会被自动拉起——提示用户先 `napuketto stop`。
@@ -1122,57 +913,294 @@ async function stopSingleAccount(dataRoot, target) {
1122
913
  const supervisor = readSupervisorRuntime(dataRoot);
1123
914
  if (supervisor !== null) logger.warn({ supervisorPid: supervisor.pid }, "supervisor 仍在运行且 autoRestart 开启时会自动拉起该账号;如需彻底停止请执行 napuketto stop(停 supervisor)");
1124
915
  }
1125
- async function cmdStop(dataRoot, opts) {
1126
- const runtimes = listAccountRuntimes(dataRoot);
1127
- if (opts.qq !== void 0) {
1128
- const target = runtimes.find((r) => r.uin === opts.qq);
1129
- if (target === void 0) {
1130
- logger.error({ uin: opts.qq }, "账号无运行时状态(未启动过)");
1131
- process.exitCode = 1;
1132
- return;
1133
- }
1134
- await stopSingleAccount(dataRoot, target);
1135
- return;
1136
- }
1137
- const supervisor = readSupervisorRuntime(dataRoot);
1138
- const supervisorPid = supervisor !== null && isPidAlive(supervisor.pid) ? supervisor.pid : 0;
1139
- if (supervisor !== null) {
1140
- logger.info({ pid: supervisor.pid }, "已发送停止请求(哨兵),等待 supervisor 退出");
1141
- writeStopSentinel(dataRoot, "all");
1142
- const alive = await waitForPidsExit([supervisorPid]);
1143
- for (const pid of alive) {
1144
- logger.warn({ pid }, "supervisor 限时内未退出,树杀兜底");
1145
- killProcessTree(pid);
1146
- }
1147
- } else logger.warn("supervisor 未运行(无状态文件)");
1148
- const stragglers = await waitForPidsExit(runtimes.map((r) => r.pid));
1149
- for (const runtime of runtimes) if (stragglers.includes(runtime.pid)) stopAccount(runtime);
1150
- removeStopSentinel(dataRoot);
916
+ async function cmdStop(dataRoot, opts) {
917
+ const runtimes = listAccountRuntimes(dataRoot);
918
+ if (opts.qq !== void 0) {
919
+ const target = runtimes.find((r) => r.uin === opts.qq);
920
+ if (target === void 0) {
921
+ logger.error({ uin: opts.qq }, "账号无运行时状态(未启动过)");
922
+ process.exitCode = 1;
923
+ return;
924
+ }
925
+ await stopSingleAccount(dataRoot, target);
926
+ return;
927
+ }
928
+ const supervisor = readSupervisorRuntime(dataRoot);
929
+ const supervisorPid = supervisor !== null && isPidAlive(supervisor.pid) ? supervisor.pid : 0;
930
+ if (supervisor !== null) {
931
+ logger.info({ pid: supervisor.pid }, "已发送停止请求(哨兵),等待 supervisor 退出");
932
+ writeStopSentinel(dataRoot, "all");
933
+ const alive = await waitForPidsExit([supervisorPid]);
934
+ for (const pid of alive) {
935
+ logger.warn({ pid }, "supervisor 限时内未退出,树杀兜底");
936
+ killProcessTree(pid);
937
+ }
938
+ } else logger.warn("supervisor 未运行(无状态文件)");
939
+ const stragglers = await waitForPidsExit(runtimes.map((r) => r.pid));
940
+ for (const runtime of runtimes) if (stragglers.includes(runtime.pid)) stopAccount(runtime);
941
+ removeStopSentinel(dataRoot);
942
+ }
943
+ /** restart:stop 同目标 + detached 拉起。 */
944
+ async function cmdRestart(dataRoot, opts) {
945
+ await cmdStop(dataRoot, opts);
946
+ await new Promise((resolve) => setTimeout(resolve, 1500));
947
+ const entry = process.argv[1] ?? "";
948
+ const args = opts.qq !== void 0 ? [
949
+ entry,
950
+ "-q",
951
+ opts.qq,
952
+ "--data-dir",
953
+ dataRoot
954
+ ] : [
955
+ entry,
956
+ "--data-dir",
957
+ dataRoot
958
+ ];
959
+ spawnDetached(args);
960
+ logger.info({
961
+ args: args.slice(1),
962
+ qq: opts.qq ?? "(supervisor 全量)"
963
+ }, "已 detached 拉起(日志不再接入当前终端,见数据目录 logs/)");
964
+ }
965
+ //#endregion
966
+ //#region src/runtime/boot.ts
967
+ /** 解析 workspace 包的 dist 入口(ESM 解析:包是 ESM-only,exports 无 require 条件)。 */
968
+ async function packageEntry(pkg) {
969
+ const url = await import.meta.resolve(pkg);
970
+ return fileURLToPath(url);
971
+ }
972
+ /** QR 透出标记行前缀(loader bootstrap-core 非 IPC 模式输出,cli 解析终端渲染)。 */
973
+ const QR_LINE_PREFIX = "NAPUTO_QR ";
974
+ /** 优雅停等待上限(毫秒):超时 kill 兜底(Windows 下为硬杀)。 */
975
+ const GRACEFUL_STOP_TIMEOUT_MS = 1e4;
976
+ /**
977
+ * 逐行转发子进程输出到父进程,过滤原生噪音。
978
+ * readline 按 UTF-8 解码 pipe 字节流,再经 process.stdout(TTY 路径,
979
+ * WriteConsoleW UTF-16)输出——顺带修复 pino 中文在 cmd.exe/管道 936 转码
980
+ * 链路下的乱码(原生 printf 字节流无法从 JS 侧改编码,转 pipe 后统一解码)。
981
+ *
982
+ * NAPUTO_QR 标记行(loader bootstrap-core 输出,QR 登录二维码数据)不转发,
983
+ * 解析后用 qrcode 包渲染终端二维码;png 落盘与 URL 提示由 kernel 日志完成。
984
+ * 噪音判定走 loader 共享单一来源(isNativeNoiseLine,与 koishi IPC 路径同源)。
985
+ */
986
+ function forwardFiltered(input, out) {
987
+ createInterface({ input }).on("line", (line) => {
988
+ if (line.startsWith(QR_LINE_PREFIX)) {
989
+ renderTerminalQr(line.slice(10));
990
+ return;
991
+ }
992
+ if (isNativeNoiseLine(line)) return;
993
+ out.write(`${line}\n`);
994
+ });
995
+ }
996
+ /**
997
+ * 渲染终端二维码(qrcode 包 terminal 模式,half-block 字符)。
998
+ * 解析失败/无 url 时静默丢弃——标记行是内部协议,坏行不影响登录。
999
+ */
1000
+ function renderTerminalQr(raw) {
1001
+ try {
1002
+ const { qrcodeUrl } = JSON.parse(raw);
1003
+ if (qrcodeUrl === void 0 || qrcodeUrl === "") return;
1004
+ QRCode.toString(qrcodeUrl, {
1005
+ type: "terminal",
1006
+ small: true
1007
+ }).then((str) => {
1008
+ process.stdout.write(`${str}\n`);
1009
+ }).catch(() => {});
1010
+ } catch {}
1011
+ }
1012
+ /** 解析自建宿主装配面的三个包入口(ESM 解析,顺序同旧实现)。 */
1013
+ async function resolvePackageEntries() {
1014
+ return {
1015
+ kernelEntry: await packageEntry("@napuketto/kernel"),
1016
+ adapterEntry: await packageEntry("@napuketto/adapter"),
1017
+ networkEntry: await packageEntry("@napuketto/network")
1018
+ };
1019
+ }
1020
+ /** stub QQNT.dll 目录(--stub-dir > NAPUTO_STUB_DIR > loader 包内闭源 submodule 默认)。 */
1021
+ function resolveStubDir(opts) {
1022
+ return opts.stubDir ?? process.env["NAPUTO_STUB_DIR"] ?? defaultStubDir();
1023
+ }
1024
+ /** 错误文案提取(Error 用 message,其余字符串化——保留旧日志文案语义)。 */
1025
+ function errorMessage(err) {
1026
+ return err instanceof Error ? err.message : String(err);
1027
+ }
1028
+ /** QQ 原生文件多级来源 + 自动下载(本机未装 QQ 时走下载管线)。
1029
+ * 失败记录可操作提示并置 exitCode 1,返回 undefined(调用方提前返回)。 */
1030
+ async function locateQqFiles(dataRoot, opts) {
1031
+ try {
1032
+ return await resolveQqFiles({
1033
+ dataRoot,
1034
+ ...opts.qqPath !== void 0 ? { qqPath: opts.qqPath } : {}
1035
+ });
1036
+ } catch (err) {
1037
+ logger.error({ err }, `定位/下载 QQ 原生文件失败:${errorMessage(err)}\n(本机未装 QQ 时自动下载官方安装包;若下载失败请检查网络,或手动安装 QQ、设置 NAPUTO_QQ_PATH 指定已有安装、NAPUTO_QQ_FILES 指定文件根、NAPUTO_QQ_URL 覆盖下载地址)`);
1038
+ process.exitCode = 1;
1039
+ return;
1040
+ }
1041
+ }
1042
+ /**
1043
+ * 单实例锁预检(2026-08-07 根治「多实例抢数据目录锁挂起」):同一账号数据
1044
+ * 目录只允许一个实例(QQ 原生层 MMKV/登录单例有锁,第二个实例抢不到锁会卡死)。
1045
+ * 占用 → 快速失败并提示占用 PID;残留(PID 已死 / PID 被复用,2026-09-10
1046
+ * cmdline 校验根治)→ self-host 会自动接管。真正的锁由 self-host 子进程
1047
+ * 获取/释放(它才是数据目录的实际持有者),cli 这里只做 spawn 前预检,
1048
+ * 给用户友好提示(supervisor 等批量拉起同用)。
1049
+ * @returns 可用 true;占用时记录错误并置 exitCode 1 返回 false
1050
+ */
1051
+ function ensureInstanceLockFree(cfgDir) {
1052
+ const { occupied, pid: holderPid } = checkInstanceLock(cfgDir);
1053
+ if (!occupied) return true;
1054
+ logger.error({
1055
+ pid: holderPid,
1056
+ dataDir: cfgDir
1057
+ }, "数据目录已被其他实例占用,拒绝启动(同一账号数据目录仅允许一个实例;占用校验已含 pid 复用检测,如仍误报请删除该目录下的 instance.lock)");
1058
+ process.exitCode = 1;
1059
+ return false;
1060
+ }
1061
+ /** 启动信息走结构化日志(时间戳 + 级别 + pid + 元数据,与 kernel 子进程格式一致)。
1062
+ * 2026-10-25 级别重分配:引导细节降 debug(banner 之外的定位/路径细节对运行
1063
+ * 状态无信息量),致命错误与登录/退出生命周期保持 info 及以上。 */
1064
+ function logBootInfo(qq, cfgDir) {
1065
+ logger.debug({
1066
+ qqVersion: qq.version,
1067
+ qqPath: qq.qqPath,
1068
+ source: qq.source
1069
+ }, "QQ 文件来源");
1070
+ logger.debug({ dataDir: cfgDir }, "数据目录");
1071
+ logger.debug("自建宿主引导(标准 node + stub QQNT.dll)");
1072
+ }
1073
+ /** launchSelfHost 调用参数构造(唯一启动路径:自建宿主,2026-08-07 用户拍板)。
1074
+ * configPath:全局配置文件(项目根 napuketto.toml),注入 NAPKETTO_CONFIG 供装配链读取;
1075
+ * 内联配置生效(NAPKETTO_CONFIG_JSON)时不解析、不注入——子进程经 env 继承
1076
+ * 内联文本,装配链按同一优先级读取;避免项目根探测出无关路径注入孙进程。
1077
+ * extraEnv:传播有效控制台渲染决策(子进程 stdout 恒 pipe,TTY 判定失真)+
1078
+ * 数据根(NAPUTO_DATA_ROOT,self-host 停止哨兵目录)。
1079
+ * cwd:子进程 cwd 指向数据根——QQ 原生层 fallback 落盘(guild1.db 等)落在专门
1080
+ * 的数据目录,不污染项目根(实测 08-07)。 */
1081
+ function buildLaunchOptions(ctx) {
1082
+ const { opts, qq, cfgDir, dataRoot, entries, stubDir } = ctx;
1083
+ return {
1084
+ qq,
1085
+ kernelEntry: entries.kernelEntry,
1086
+ adapterEntry: entries.adapterEntry,
1087
+ networkEntry: entries.networkEntry,
1088
+ cfgDir,
1089
+ cwd: dataRoot,
1090
+ ...isInlineConfigActive() ? {} : { configPath: resolveConfigPath({ dataRoot }) },
1091
+ selfHost: true,
1092
+ stdio: [
1093
+ "inherit",
1094
+ "pipe",
1095
+ "pipe"
1096
+ ],
1097
+ extraEnv: {
1098
+ ...effectiveConsoleEnv(resolveCliLogConfig(opts.dataDir)),
1099
+ NAPUTO_DATA_ROOT: dataRoot
1100
+ },
1101
+ ...opts.qq !== void 0 ? { quickUin: opts.qq } : {},
1102
+ stubDir
1103
+ };
1104
+ }
1105
+ /** 启动自建宿主子进程(包入口解析 → stub 目录 → 启动信息 → launchSelfHost)。
1106
+ * ⚠️ P2(2026-08-12):launchSelfHost 变 async(linux 场景需下载 win-node)。 */
1107
+ async function startSelfHost(opts, qq, cfgDir, dataRoot) {
1108
+ const entries = await resolvePackageEntries();
1109
+ const stubDir = resolveStubDir(opts);
1110
+ logBootInfo(qq, cfgDir);
1111
+ return await launchSelfHost(buildLaunchOptions({
1112
+ opts,
1113
+ qq,
1114
+ cfgDir,
1115
+ dataRoot,
1116
+ entries,
1117
+ stubDir
1118
+ }));
1119
+ }
1120
+ /** 接管子进程 stdout/stderr:过滤 MMKV / 符号查找失败等原生噪音,其余转发。 */
1121
+ function forwardChildOutput(child) {
1122
+ if (child.stdout !== null) forwardFiltered(child.stdout, process.stdout);
1123
+ if (child.stderr !== null) forwardFiltered(child.stderr, process.stderr);
1124
+ }
1125
+ /** 单账号运行时状态落盘(napuketto status/stop 消费,2026-09-08 T8;
1126
+ * pid 记 boot 进程——树杀连带 self-host 孙进程)。 */
1127
+ function recordRuntimeState(dataRoot, account, child, status, exitCode) {
1128
+ writeAccountRuntime(dataRoot, {
1129
+ uin: account,
1130
+ pid: process.pid,
1131
+ ...child.pid !== void 0 ? { selfHostPid: child.pid } : {},
1132
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1133
+ kind: "single-boot",
1134
+ status,
1135
+ ...exitCode !== void 0 ? { exitCode } : {}
1136
+ });
1137
+ }
1138
+ /** 优雅关停编排(2026-10-25 生命周期契约):触发后等 self-host 经自身哨兵/信号
1139
+ * 处理自行退出(exit 0),10s 未退则 kill 兜底(Windows 下为硬杀)——
1140
+ * boot 进程随后随 child 退出自然返回(退出码 0 = 请求式正常退出)。
1141
+ * @returns 「是否已收到停止请求」查询(退出日志 graceful 标注) */
1142
+ function installGracefulStop(child, dataRoot, account) {
1143
+ let stopArmed = false;
1144
+ const killIfHung = () => {
1145
+ if (child.exitCode !== null || child.killed) return;
1146
+ logger.warn({ account }, "自建宿主未在限时内退出,强制结束");
1147
+ child.kill();
1148
+ };
1149
+ const armGracefulStop = (reason) => {
1150
+ if (stopArmed) return;
1151
+ stopArmed = true;
1152
+ logger.info({
1153
+ account,
1154
+ reason
1155
+ }, "收到停止请求,等待自建宿主退出");
1156
+ setTimeout(killIfHung, GRACEFUL_STOP_TIMEOUT_MS).unref?.();
1157
+ };
1158
+ watchStopSentinel({
1159
+ dataRoot,
1160
+ account,
1161
+ onTrigger: () => armGracefulStop("停止哨兵")
1162
+ });
1163
+ const onSignal = (signal) => {
1164
+ writeStopSentinel(dataRoot, account);
1165
+ armGracefulStop(`信号 ${signal}`);
1166
+ };
1167
+ process.on("SIGINT", () => onSignal("SIGINT"));
1168
+ process.on("SIGTERM", () => onSignal("SIGTERM"));
1169
+ process.on("SIGBREAK", () => onSignal("SIGBREAK"));
1170
+ return () => stopArmed;
1171
+ }
1172
+ /** 常驻:等待自建宿主进程退出(exit / error 两路径均 resolve,去留由 self-host 决定)。 */
1173
+ async function waitSelfHostExit(child, dataRoot, account, isStopping) {
1174
+ await new Promise((resolve) => {
1175
+ child.on("exit", (code) => {
1176
+ logger.info({
1177
+ code,
1178
+ graceful: isStopping()
1179
+ }, "自建宿主进程退出");
1180
+ recordRuntimeState(dataRoot, account, child, "exited", code);
1181
+ resolve();
1182
+ });
1183
+ child.on("error", (err) => {
1184
+ logger.error({ err }, "自建宿主进程启动失败");
1185
+ resolve();
1186
+ });
1187
+ });
1151
1188
  }
1152
- /** restart:stop 同目标 + detached 拉起。 */
1153
- async function cmdRestart(dataRoot, opts) {
1154
- await cmdStop(dataRoot, opts);
1155
- await new Promise((resolve) => setTimeout(resolve, 1500));
1156
- const entry = process.argv[1] ?? "";
1157
- const args = opts.qq !== void 0 ? [
1158
- entry,
1159
- "-q",
1160
- opts.qq,
1161
- "--data-dir",
1162
- dataRoot
1163
- ] : [
1164
- entry,
1165
- "--data-dir",
1166
- dataRoot
1167
- ];
1168
- spawnDetached(args);
1169
- logger.info({
1170
- args: args.slice(1),
1171
- qq: opts.qq ?? "(supervisor 全量)"
1172
- }, "已 detached 拉起(日志不再接入当前终端,见数据目录 logs/)");
1189
+ /** 启动单个账号(自建宿主 + 常驻)。 */
1190
+ async function runSingleAccount(opts = {}) {
1191
+ const dataRoot = resolveDataRoot(opts.dataDir);
1192
+ const qq = await locateQqFiles(dataRoot, opts);
1193
+ if (qq === void 0) return;
1194
+ const account = opts.qq ?? "default";
1195
+ const cfgDir = path.join(dataRoot, account);
1196
+ if (!ensureInstanceLockFree(cfgDir)) return;
1197
+ const { child } = await startSelfHost(opts, qq, cfgDir, dataRoot);
1198
+ forwardChildOutput(child);
1199
+ recordRuntimeState(dataRoot, account, child, "running");
1200
+ await waitSelfHostExit(child, dataRoot, account, installGracefulStop(child, dataRoot, account));
1173
1201
  }
1174
1202
  //#endregion
1175
- //#region src/supervisor.ts
1203
+ //#region src/runtime/supervisor.ts
1176
1204
  /**
1177
1205
  * supervisor:多账号子进程编排(P6,2026-08-05;2026-08-07 自建宿主唯一)
1178
1206
  *
@@ -1183,8 +1211,6 @@ async function cmdRestart(dataRoot, opts) {
1183
1211
  * - 守护:账号异常退出且 autoRestart → 延迟重启
1184
1212
  * - 信号转发:SIGINT/SIGTERM → 停止全部子进程 → 父进程退出
1185
1213
  */
1186
- /** 默认重启延迟(毫秒)。 */
1187
- const DEFAULT_RESTART_DELAY_MS = 2e3;
1188
1214
  /** 退出轮询间隔(毫秒)。 */
1189
1215
  const EXIT_POLL_MS = 100;
1190
1216
  /** 子进程优雅退出时限(毫秒):哨兵/信号后子进程自行停止,超时强杀兜底。 */
@@ -1368,35 +1394,13 @@ async function runSupervisor(opts = {}) {
1368
1394
  await new Promise(() => {});
1369
1395
  }
1370
1396
  //#endregion
1371
- //#region src/index.ts
1397
+ //#region src/commands/start.ts
1372
1398
  /**
1373
- * @napuketto/cli 入口(P2-6 + P6,2026-08-05;2026-08-07 用户拍板:只保留自建宿主;
1374
- * 2026-08-08 配置结构拍板:账号必填,协议配置嵌在账号内)
1375
- *
1376
- * commander 参数解析:
1377
- * - 单账号:-q <uin> → runSingleAccount(自建宿主:标准 node + stub QQNT.dll,不拉起 QQ)
1378
- * - 多账号:-q A -q B 或 supervisor 子命令 → runSupervisor(子进程编排)
1379
- * - 无 -q:读全局配置 accounts(至少一个,账号必填)→ supervisor 拉起全部启用账号
1380
- * - config 子命令:init / list / apply / validate(主配置管理)
1381
- * - 退出码契约(2026-10-25):0 = 请求式优雅关停;78 = 配置校验失败(ConfigError
1382
- * 一族,宿主消费,免重启);其余错误 = 1(handleActionError 统一出口)
1399
+ * 默认动作(无子命令)用例:-q 单账号 / 多 -q supervisor / 无 -q 读配置拉起全部账号。
1383
1400
  *
1384
- * 路线 B(拉起 QQ + 注入)已淘汰(2026-08-07 用户拍板),相关入口已移除。
1401
+ * 从 index.ts 拆出(2026-10-25 模块收拢):这里只做编排,不 import commander;
1402
+ * 参数解析、帮助文案与退出码收敛在 cli/program.ts。
1385
1403
  */
1386
- /** commander collect:累积 -q 多值。 */
1387
- function collectQq(value, prev) {
1388
- prev.push(value);
1389
- return prev;
1390
- }
1391
- /** 启动字符画(NapukettoQQ 品牌标识,内嵌;art 含反引号/反斜杠,用数组逐行转义)。 */
1392
- const BANNER = [
1393
- " _ __ __ __ __ ____ ____ ",
1394
- " / | / /___ _____ __ __/ /_____ / /_/ /_____ / __ \\/ __ \\",
1395
- " / |/ / __ `/ __ \\/ / / / //_/ _ \\/ __/ __/ __ \\/ / / / / / /",
1396
- " / /| / /_/ / /_/ / /_/ / ,< / __/ /_/ /_/ /_/ / /_/ / /_/ / ",
1397
- "/_/ |_/\\__,_/ .___/\\__,_/_/|_|\\___/\\__/\\__/\\____/\\___\\_\\___\\_\\ ",
1398
- " /_/ "
1399
- ].join("\n");
1400
1404
  /** 构造可选 dataDir 参数(exactOptionalPropertyTypes 不允许显式 undefined)。 */
1401
1405
  function withDataDir(dataDir) {
1402
1406
  if (dataDir === void 0) return {};
@@ -1412,9 +1416,100 @@ function withQqPath(qqPath) {
1412
1416
  if (qqPath === void 0) return {};
1413
1417
  return { qqPath };
1414
1418
  }
1419
+ /** 单账号启动分支(-q 单值;构造 bootOptions 后走 runSingleAccount)。 */
1420
+ async function runSingleAccountBranch(opts, qqs) {
1421
+ const [only] = qqs;
1422
+ if (only === void 0) return;
1423
+ await runSingleAccount({
1424
+ qq: only,
1425
+ ...withDataDir(opts.dataDir),
1426
+ ...withQqPath(opts.qqPath),
1427
+ ...withStubDir(opts.stubDir)
1428
+ });
1429
+ }
1430
+ /** 无 -q 时:读全局配置 accounts(账号必填,2026-08-08 拍板),supervisor 拉起全部启用账号。
1431
+ * 不再有「配置为空 → 交互式单账号登录」老路径:缺账号直接报错提示编辑模板。
1432
+ * 配置加载内联优先(NAPKETTO_CONFIG_JSON > 文件);校验失败 ConfigError → exit 78。 */
1433
+ async function autoStart(opts) {
1434
+ const { config } = await loadCliConfigWithSource(withDataDir(opts.dataDir));
1435
+ if (config.accounts.length === 0) throw new Error("主配置没有账号,请编辑 napuketto.toml 填写 [[accounts]] 段");
1436
+ await runSupervisor({
1437
+ ...withDataDir(opts.dataDir),
1438
+ ...withStubDir(opts.stubDir)
1439
+ });
1440
+ }
1441
+ /** 主命令分发:无 -q 读配置 supervisor 拉起 / 单 -q 单账号 / 多 -q supervisor。 */
1442
+ async function dispatchMainAction(opts) {
1443
+ const qqs = opts.qq ?? [];
1444
+ if (qqs.length === 0) {
1445
+ await autoStart(opts);
1446
+ return;
1447
+ }
1448
+ if (qqs.length === 1) {
1449
+ await runSingleAccountBranch(opts, qqs);
1450
+ return;
1451
+ }
1452
+ await runSupervisor({
1453
+ qqs,
1454
+ ...withDataDir(opts.dataDir),
1455
+ ...withStubDir(opts.stubDir)
1456
+ });
1457
+ }
1458
+ /** supervisor 子命令用例(读主配置 accounts 批量拉起;-d 复用主命令 option)。 */
1459
+ async function runSupervisorCommand(opts) {
1460
+ await runSupervisor(withDataDir(opts.dataDir));
1461
+ }
1462
+ //#endregion
1463
+ //#region src/cli/error.ts
1464
+ /**
1465
+ * CLI 动作错误出口(2026-10-25 退出码契约):
1466
+ * 0 = 请求式优雅关停(0.2.0 已有,不经此路径);78 = 配置校验失败
1467
+ * (ConfigError 一族,宿主据此区分「配置未就绪」与运行时崩溃,免重启);
1468
+ * 其余 = 1(运行时崩溃,现状不变)。
1469
+ *
1470
+ * 退出码只认错误类型(instanceof ConfigError),与日志文案完全解耦——
1471
+ * 文案是人读的,退出码是宿主消费的机器契约。
1472
+ */
1473
+ /** 统一错误输出(结构化日志,错误对象经 pino serializer 带堆栈)。 */
1474
+ function reportError(err) {
1475
+ let message = String(err);
1476
+ if (err instanceof Error) {
1477
+ const { message: errMessage } = err;
1478
+ message = errMessage;
1479
+ }
1480
+ logger.error({ err }, message);
1481
+ }
1482
+ /** 统一 catch 出口:打印错误并按类型设置进程退出码(78 = 配置校验失败)。 */
1483
+ function handleActionError(err) {
1484
+ reportError(err);
1485
+ process.exitCode = err instanceof ConfigError ? EXIT_CONFIG_INVALID : 1;
1486
+ }
1487
+ //#endregion
1488
+ //#region src/cli/program.ts
1489
+ /**
1490
+ * commander 装配层:全局选项、banner、子命令注册、默认动作分发。
1491
+ *
1492
+ * 从 index.ts 拆出(2026-10-25 模块收拢):只做 CLI 契约适配(参数/帮助/输出/
1493
+ * 退出码),用例实现见 commands/。禁止在此写业务逻辑。
1494
+ */
1495
+ /** commander collect:累积 -q 多值。 */
1496
+ function collectQq(value, prev) {
1497
+ prev.push(value);
1498
+ return prev;
1499
+ }
1500
+ /** 启动字符画(NapukettoQQ 品牌标识,内嵌;art 含反引号/反斜杠,用数组逐行转义)。 */
1501
+ const BANNER = [
1502
+ " _ __ __ __ __ ____ ____ ",
1503
+ " / | / /___ _____ __ __/ /_____ / /_/ /_____ / __ \\/ __ \\",
1504
+ " / |/ / __ `/ __ \\/ / / / //_/ _ \\/ __/ __/ __ \\/ / / / / / /",
1505
+ " / /| / /_/ / /_/ / /_/ / ,< / __/ /_/ /_/ /_/ / /_/ / /_/ / ",
1506
+ "/_/ |_/\\__,_/ .___/\\__,_/_/|_|\\___/\\__/\\__/\\____/\\___\\_\\___\\_\\ ",
1507
+ " /_/ "
1508
+ ].join("\n");
1415
1509
  /** 读主命令已解析的 data-dir(-d 定义在主命令,子命令经此共享)。 */
1416
1510
  function rootDataDir(program) {
1417
- return withDataDir(program.opts().dataDir);
1511
+ const { dataDir } = program.opts();
1512
+ return dataDir === void 0 ? {} : { dataDir };
1418
1513
  }
1419
1514
  /** 注册 config 子命令(init/list/apply,P6;-d 复用主命令 option)。 */
1420
1515
  function registerConfigCommands(program) {
@@ -1457,7 +1552,7 @@ function registerConfigCommands(program) {
1457
1552
  function registerSupervisorCommand(program) {
1458
1553
  program.command("supervisor").description("多账号编排(读全局配置 accounts 拉起子进程)").action(async () => {
1459
1554
  try {
1460
- await runSupervisor(rootDataDir(program));
1555
+ await runSupervisorCommand(rootDataDir(program));
1461
1556
  } catch (err) {
1462
1557
  handleActionError(err);
1463
1558
  }
@@ -1479,45 +1574,6 @@ function registerOpsCommands(program) {
1479
1574
  program.command("stop").description("停止账号进程树(无 -q 停 supervisor 全部;-q 停单账号,supervisor 守护时会自动拉起)").option("-q, --qq <uin>", "目标账号(缺省停 supervisor + 全部账号)").action(opsAction(program, (dataRoot, arg) => cmdStop(dataRoot, arg)));
1480
1575
  program.command("restart").description("重启账号(无 -q 重启 supervisor 全量;-q 重启单账号;detached 拉起)").option("-q, --qq <uin>", "目标账号(缺省重启 supervisor 全量)").action(opsAction(program, (dataRoot, arg) => cmdRestart(dataRoot, arg)));
1481
1576
  }
1482
- /** 单账号启动分支(-q 单值;构造 bootOptions 后走 runSingleAccount)。 */
1483
- async function runSingleAccountBranch(opts, qqs) {
1484
- const [only] = qqs;
1485
- if (only === void 0) return;
1486
- await runSingleAccount({
1487
- qq: only,
1488
- ...withDataDir(opts.dataDir),
1489
- ...withQqPath(opts.qqPath),
1490
- ...withStubDir(opts.stubDir)
1491
- });
1492
- }
1493
- /** 无 -q 时:读全局配置 accounts(账号必填,2026-08-08 拍板),supervisor 拉起全部启用账号。
1494
- * 不再有「配置为空 → 交互式单账号登录」老路径:缺账号直接报错提示编辑模板。
1495
- * 配置加载内联优先(NAPKETTO_CONFIG_JSON > 文件);校验失败 ConfigError → exit 78。 */
1496
- async function autoStart(opts) {
1497
- const { config } = await loadCliConfigWithSource(withDataDir(opts.dataDir));
1498
- if (config.accounts.length === 0) throw new Error("主配置没有账号,请编辑 napuketto.toml 填写 [[accounts]] 段");
1499
- await runSupervisor({
1500
- ...withDataDir(opts.dataDir),
1501
- ...withStubDir(opts.stubDir)
1502
- });
1503
- }
1504
- /** 主命令分发:无 -q 读配置 supervisor 拉起 / 单 -q 单账号 / 多 -q supervisor。 */
1505
- async function dispatchMainAction(opts) {
1506
- const qqs = opts.qq ?? [];
1507
- if (qqs.length === 0) {
1508
- await autoStart(opts);
1509
- return;
1510
- }
1511
- if (qqs.length === 1) {
1512
- await runSingleAccountBranch(opts, qqs);
1513
- return;
1514
- }
1515
- await runSupervisor({
1516
- qqs,
1517
- ...withDataDir(opts.dataDir),
1518
- ...withStubDir(opts.stubDir)
1519
- });
1520
- }
1521
1577
  /** 注册主命令 action(-q 单账号 / 多 -q supervisor / 无 -q 读配置 supervisor 拉起)。 */
1522
1578
  function registerMainAction(program) {
1523
1579
  program.action(async (opts) => {
@@ -1542,6 +1598,25 @@ function main() {
1542
1598
  registerMainAction(program);
1543
1599
  program.parse(process.argv);
1544
1600
  }
1601
+ //#endregion
1602
+ //#region src/index.ts
1603
+ /**
1604
+ * @napuketto/cli 入口(P2-6 + P6,2026-08-05;2026-08-07 用户拍板:只保留自建宿主;
1605
+ * 2026-08-08 配置结构拍板:账号必填,协议配置嵌在账号内)
1606
+ *
1607
+ * commander 参数解析:
1608
+ * - 单账号:-q <uin> → runSingleAccount(自建宿主:标准 node + stub QQNT.dll,不拉起 QQ)
1609
+ * - 多账号:-q A -q B 或 supervisor 子命令 → runSupervisor(子进程编排)
1610
+ * - 无 -q:读全局配置 accounts(至少一个,账号必填)→ supervisor 拉起全部启用账号
1611
+ * - config 子命令:init / list / apply / validate(主配置管理)
1612
+ * - 退出码契约(2026-10-25):0 = 请求式优雅关停;78 = 配置校验失败(ConfigError
1613
+ * 一族,宿主消费,免重启);其余错误 = 1(handleActionError 统一出口)
1614
+ *
1615
+ * 路线 B(拉起 QQ + 注入)已淘汰(2026-08-07 用户拍板),相关入口已移除。
1616
+ *
1617
+ * 2026-10-25 模块收拢:本文件只保留进程入口;commander 装配在 cli/program.ts,
1618
+ * 用例在 commands/,配置领域在 config/,运行期在 runtime/。
1619
+ */
1545
1620
  main();
1546
1621
  //#endregion
1547
1622
  export {};