@napuketto/cli 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,99 +1,436 @@
1
1
  #!/usr/bin/env node
2
2
  import process from "node:process";
3
- import { ConfigBase, createLogger, kernelError, parseLogConfig, parseToml, resolveConfigPath, resolveDataRoot, stringifyToml } from "@napuketto/kernel";
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
+ import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
5
6
  import path, { dirname, extname, isAbsolute, join } from "node:path";
6
7
  import { createInterface } from "node:readline";
7
8
  import { fileURLToPath } from "node:url";
8
9
  import { checkInstanceLock, defaultStubDir, isNativeNoiseLine, launchSelfHost, removeStopSentinel, resolveQqFiles, watchStopSentinel, writeStopSentinel } from "@napuketto/loader";
9
10
  import QRCode from "qrcode";
10
- import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
11
11
  import { spawn } from "node:child_process";
12
12
  import { access, readFile, writeFile } from "node:fs/promises";
13
- //#region src/logger.ts
13
+ //#region src/config-template.ts
14
14
  /**
15
- * cli 进程级 logger(ADR-007 日志规范,2026-08-07 统一改造;2026-10-25 日志可配置化)。
16
- *
17
- * 复用 kernel `createLogger`;输出格式/级别/时间戳/颜色由 napuketto.toml [log] 段 +
18
- * 环境变量决定(kernel parseLogConfig 单一解析源)。懒构造:commander preAction
19
- * 钩子先 resolveCliLogConfig(dataDir)(banner 决策 + 缓存),首个日志调用时按
20
- * 缓存配置构造;未初始化时兜底用缺省数据根解析(-d 生效前的极早期日志)。
15
+ * 配置模板(TOML 注释版,从 config-cmds.ts 拆分,2026-08-08 FTA 优化)。
16
+ * `config init` 与首次启动(loadCliConfig)缺失时生成。
21
17
  *
22
- * 环境变量(优先级高于 toml,见 kernel parseLogConfig):NAPUKETTO_LOG_LEVEL /
23
- * NAPUKETTO_LOG_FORMAT / NAPUKETTO_NO_BANNER / NAPUKETTO_LOG_COLORIZE,
24
- * 兼容旧拼写 NAPKETTO_LOG_LEVEL。
18
+ * 2026-08-08 结构拍板:**一个 QQ 账号一个 [[accounts]] 段,协议与通信配置嵌在
19
+ * 账号内**([accounts.onebot11] / [accounts.satori]);账号必填(至少一个)。
20
+ * dataDir 不再写死(缺省 = 项目根/.napuketto,跨平台),模板保持可移植。
25
21
  */
26
- /** 已解析日志配置缓存(preAction 首次解析后固定;-d 后续变化不影响已构造 logger)。 */
27
- let cachedConfig = null;
28
- /** 解析配置时用的数据根([log.file] 相对路径展开基准)。 */
29
- let cachedDataRoot = resolveDataRoot();
30
- /** 同步解析日志配置(toml [log] 段 + env 覆盖)。损坏/缺失配置回退缺省(不阻塞启动:
31
- * 配置的严格校验由 loadCliConfig 主路径负责报错)。 */
32
- function resolveCliLogConfig(dataDir) {
33
- if (cachedConfig !== null) return cachedConfig;
34
- cachedDataRoot = resolveDataRoot(dataDir);
35
- let section;
36
- try {
37
- const configPath = resolveConfigPath({ dataRoot: cachedDataRoot });
38
- section = parseToml(readFileSync(configPath, "utf8"))["log"];
39
- } catch {
40
- section = void 0;
41
- }
42
- try {
43
- cachedConfig = parseLogConfig(section, process.env);
44
- } catch {
45
- cachedConfig = parseLogConfig(void 0, process.env);
46
- }
47
- return cachedConfig;
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
+ `;
48
167
  }
168
+ //#endregion
169
+ //#region src/config-parse.ts
49
170
  /**
50
- * 顶层进程的最终控制台格式([log] format 显式优先,否则按 TTY 自动:
51
- * 终端 pretty / 管道 single-line)。supervisor 的前缀转发决策同源。
171
+ * 主配置类型与手写校验器(从 config-cmds.ts 拆分,2026-08-08 FTA 优化)
172
+ *
173
+ * 主配置 parse(不引入 zod):数据根 / 自动重启 / 重启延迟 / 账号列表。
174
+ * 2026-08-08 结构拍板:**一个 QQ 账号一个 [[accounts]] 段,协议与通信配置嵌在
175
+ * 账号内**([accounts.onebot11] / [accounts.satori]);账号必填(至少一个)。
176
+ * 协议段为宽松对象,装配时由对应协议包的 zod schema 严格校验。
177
+ * 全部校验错误为 ConfigError(2026-10-25 嵌入式退出码契约:CLI exit 78 一族,
178
+ * 内联与文件两形态共用本校验器)。
52
179
  */
53
- function effectiveConsoleFormat(cfg) {
54
- const isTty = process.stdout.isTTY === true;
55
- return cfg.format ?? (isTty ? "pretty" : "single-line");
180
+ /** 默认自动重启。 */
181
+ const DEFAULT_AUTO_RESTART = true;
182
+ /** 默认重启延迟(毫秒)。 */
183
+ const DEFAULT_RESTART_DELAY_MS$1 = 2e3;
184
+ /** QQ 号格式:纯数字 5-11 位(QQ 号合法范围,勿写死 11 位)。 */
185
+ const QQ_IN_FORMAT_RE = /^\d{5,11}$/;
186
+ /** 解析账号内协议段(宽松对象,装配时由 zod schema 严格校验)。 */
187
+ function parseProtocolSection(raw, key) {
188
+ const section = raw[key];
189
+ if (section === void 0) return;
190
+ if (typeof section !== "object" || section === null) throw configError(`主配置账号 ${key} 段必须是对象`);
191
+ return section;
56
192
  }
57
193
  /**
58
- * 顶层进程的有效控制台渲染决策(传播给子进程):
59
- * 子进程 stdout 恒为 pipe(TTY 判定失真),由本进程按最终控制台形态决定
60
- * format/colorize 并经 env 注入(NAPUKETTO_LOG_FORMAT/NAPUKETTO_LOG_COLORIZE)。
194
+ * 解析 dataDir(缺省用当前解析的数据根 = 项目根/.napuketto)。
195
+ * 支持绝对路径、"~/" 前缀(用户主目录)、相对路径(相对启动目录),
196
+ * 消费端 resolveDataRoot 统一展开为绝对路径。
61
197
  */
62
- function effectiveConsoleEnv(cfg) {
63
- const isTty = process.stdout.isTTY === true;
64
- const format = effectiveConsoleFormat(cfg);
65
- return {
66
- NAPUKETTO_LOG_FORMAT: format,
67
- NAPUKETTO_LOG_COLORIZE: cfg.colorize ?? (format === "pretty" && isTty) ? "1" : "0"
68
- };
198
+ function parseDataDir(raw) {
199
+ if (raw["dataDir"] === void 0) return resolveDataRoot();
200
+ if (typeof raw["dataDir"] !== "string" || raw["dataDir"] === "") throw configError("主配置 dataDir 必须是非空字符串");
201
+ return raw["dataDir"];
69
202
  }
70
- /** [log.file] 相对路径按数据根展开。 */
71
- function resolveLogFilePath(path) {
72
- return isAbsolute(path) ? path : join(cachedDataRoot, path);
203
+ /** 解析 autoRestart。 */
204
+ function parseAutoRestart(raw) {
205
+ if (raw["autoRestart"] === void 0) return DEFAULT_AUTO_RESTART;
206
+ if (typeof raw["autoRestart"] !== "boolean") throw configError("主配置 autoRestart 必须是布尔值");
207
+ return raw["autoRestart"];
73
208
  }
74
- /** cli logger 构造参数([log] 段折叠;file/fileLevel 成对生效,其余直传 undefined)。 */
75
- function cliLoggerOptions(cfg) {
76
- return {
77
- level: cfg.levels.cli ?? cfg.level,
78
- format: cfg.format,
79
- timestamp: cfg.timestamp,
80
- colorize: cfg.colorize,
81
- file: cfg.file !== void 0 ? resolveLogFilePath(cfg.file.path) : void 0,
82
- fileLevel: cfg.file?.level,
83
- base: {
84
- name: "cli",
85
- service: "cli"
86
- }
87
- };
209
+ /** 解析 restartDelayMs(毫秒)。 */
210
+ function parseRestartDelayMs(raw) {
211
+ if (raw["restartDelayMs"] === void 0) return DEFAULT_RESTART_DELAY_MS$1;
212
+ if (typeof raw["restartDelayMs"] !== "number" || !Number.isInteger(raw["restartDelayMs"]) || raw["restartDelayMs"] <= 0) throw configError("主配置 restartDelayMs 必须是正整数");
213
+ return raw["restartDelayMs"];
88
214
  }
89
- /** 懒构造 cli 进程日志(name 渲染为 (cli/pid) 元数据头,文件 JSON 保留 name 字段可过滤)。 */
90
- var LazyCliLogger = class {
91
- #inner = null;
92
- #ensure() {
93
- if (this.#inner === null) this.#inner = createLogger(cliLoggerOptions(resolveCliLogConfig()));
94
- return this.#inner;
95
- }
96
- info(obj, msg) {
215
+ /** 解析 accounts(必须至少一个账号,qq 必填)。 */
216
+ function parseAccounts(raw) {
217
+ if (raw["accounts"] === void 0) throw configError("主配置缺少 accounts(必须至少一个账号);首次启动已生成模板,请编辑后重试");
218
+ if (!Array.isArray(raw["accounts"]) || raw["accounts"].length === 0) throw configError("主配置 accounts 必须是非空数组(至少一个 QQ 账号);首次启动已生成模板,请编辑后重试");
219
+ const accounts = [];
220
+ for (const item of raw["accounts"]) accounts.push(parseAccount(item));
221
+ return accounts;
222
+ }
223
+ /** 账号 qq 必填校验(非空字符串)。 */
224
+ function parseAccountQq(raw) {
225
+ const qq = raw["qq"];
226
+ if (typeof qq !== "string" || qq === "") throw configError("主配置账号缺少非空 qq");
227
+ assertValidQqFormat(qq);
228
+ return qq;
229
+ }
230
+ /** qq 格式与占位值校验(5-11 位纯数字;模板占位号显式指路不静默)。 */
231
+ function assertValidQqFormat(qq) {
232
+ if (!QQ_IN_FORMAT_RE.test(qq)) throw configError("主配置账号 qq 必须是 5-11 位纯数字 QQ 号");
233
+ if (RESERVED_PLACEHOLDER_QINS.some((placeholder) => placeholder === qq)) throw configError(`主配置账号 qq "${qq}" 是模板占位值,请编辑配置文件填入真实 QQ 号后再启动`);
234
+ }
235
+ /** 账号 enabled 可选校验(缺省 = 启用;显式给值必须是布尔)。 */
236
+ function applyAccountEnabled(out, enabled) {
237
+ if (enabled === void 0) return;
238
+ if (typeof enabled !== "boolean") throw configError("主配置账号 enabled 必须是布尔值");
239
+ out.enabled = enabled;
240
+ }
241
+ /** 账号内协议段装配(onebot11/satori/kurobot 缺省 = 不启用该协议)。 */
242
+ function applyProtocolSections(raw, out) {
243
+ const onebot11 = parseProtocolSection(raw, "onebot11");
244
+ if (onebot11 !== void 0) out.onebot11 = onebot11;
245
+ const satori = parseProtocolSection(raw, "satori");
246
+ if (satori !== void 0) out.satori = satori;
247
+ const kurobot = parseProtocolSection(raw, "kurobot");
248
+ if (kurobot !== void 0) out.kurobot = kurobot;
249
+ }
250
+ /** 解析单个账号项(qq 必填;协议段缺省 = 不启用)。 */
251
+ function parseAccount(item) {
252
+ if (typeof item !== "object" || item === null) throw configError("主配置 accounts 元素必须是对象");
253
+ const raw = item;
254
+ const out = { qq: parseAccountQq(raw) };
255
+ applyAccountEnabled(out, raw["enabled"]);
256
+ applyProtocolSections(raw, out);
257
+ return out;
258
+ }
259
+ /**
260
+ * [log] 段落库净化:format 为 undefined(= 按 TTY 自动)时剔除该键,
261
+ * 避免 toml 回写(config list/apply 的 stringifyToml)遇到 undefined 值。
262
+ */
263
+ function stripUndefinedFormat(log) {
264
+ const { format, ...rest } = log;
265
+ return format === void 0 ? rest : {
266
+ ...rest,
267
+ format
268
+ };
269
+ }
270
+ /**
271
+ * [log] 段解析(kernel parseLogConfig 错误归一为 ConfigError):日志段非法同属
272
+ * 「配置未就绪」一族(exit 78);错误文案保持 kernel 原文(主配置 log.xxx ...)。
273
+ */
274
+ function parseLogSection(input) {
275
+ try {
276
+ return parseLogConfig(input);
277
+ } catch (err) {
278
+ const detail = err instanceof Error ? err.message : String(err);
279
+ throw configError(`主配置 [log] 段非法: ${detail}`, { cause: err });
280
+ }
281
+ }
282
+ /** 手写校验器:主配置 parse(不引入 zod)。全部校验错误为 ConfigError(exit 78 一族)。 */
283
+ function parseCliConfig(input) {
284
+ if (typeof input !== "object" || input === null) throw configError("主配置必须是对象");
285
+ const raw = input;
286
+ const dataDir = parseDataDir(raw);
287
+ const autoRestart = parseAutoRestart(raw);
288
+ const restartDelayMs = parseRestartDelayMs(raw);
289
+ const accounts = parseAccounts(raw);
290
+ const log = raw["log"] !== void 0 ? stripUndefinedFormat(parseLogSection(raw["log"])) : void 0;
291
+ return {
292
+ dataDir,
293
+ autoRestart,
294
+ restartDelayMs,
295
+ accounts,
296
+ ...log !== void 0 ? { log } : {}
297
+ };
298
+ }
299
+ //#endregion
300
+ //#region src/config-inline.ts
301
+ /**
302
+ * 内联配置(NAPKETTO_CONFIG_JSON,2026-10-25 嵌入式宿主契约)。
303
+ *
304
+ * KuroBridge 等嵌入式宿主每次拉起前整体生成配置,经环境变量喂 JSON 文本
305
+ * (与 napuketto.toml 同构:parseCliConfig 直接吃 JSON.parse 产物),消除托管
306
+ * toml 文件本体。优先级 NAPKETTO_CONFIG_JSON > NAPKETTO_CONFIG > 缺省模板生成;
307
+ * 内联生效时不读 / 不写 / 不校验任何 toml 文件。Windows 单环境变量上限 32767
308
+ * 字符(约 32KB),嵌入式配置形状远小于该限(超限宿主退回文件形态)。
309
+ *
310
+ * 错误一概 ConfigError(exit 78 一族),文案指明来源为「内联配置」且不含任何
311
+ * toml 文件路径。本模块不 import logger(logger.ts 反向依赖本模块判内联来源)。
312
+ */
313
+ /** 内联配置 env 键(读取为精确键访问;Windows 上 process.env 本身大小写不敏感)。 */
314
+ const INLINE_CONFIG_ENV = "NAPKETTO_CONFIG_JSON";
315
+ /**
316
+ * 读取内联配置文本(未设置 / 空串 / 纯空白 → undefined,回退文件形态)。
317
+ */
318
+ function readInlineConfigText() {
319
+ const raw = process.env[INLINE_CONFIG_ENV];
320
+ if (raw === void 0 || raw.trim() === "") return;
321
+ return raw;
322
+ }
323
+ /** 内联是否生效(boot/装配链决定「不碰文件」的判定口径,与 readInlineConfigText 同源)。 */
324
+ function isInlineConfigActive() {
325
+ return readInlineConfigText() !== void 0;
326
+ }
327
+ /**
328
+ * 内联 JSON 文本 → 校验后的主配置。JSON 解析失败 / 非对象 / 字段校验失败
329
+ * 均抛 ConfigError(宿主消费 exit 78,不重试)。
330
+ */
331
+ function parseInlineConfig(text) {
332
+ let doc;
333
+ try {
334
+ doc = JSON.parse(text);
335
+ } catch (err) {
336
+ const detail = err instanceof Error ? err.message : String(err);
337
+ throw configError(`内联配置 JSON 解析失败: ${detail}`, { cause: err });
338
+ }
339
+ if (typeof doc !== "object" || doc === null || Array.isArray(doc)) throw configError("内联配置必须是 JSON 对象(与 napuketto.toml 同构)");
340
+ return parseCliConfig(doc);
341
+ }
342
+ //#endregion
343
+ //#region src/logger.ts
344
+ /**
345
+ * cli 进程级 logger(ADR-007 日志规范,2026-08-07 统一改造;2026-10-25 日志可配置化)。
346
+ *
347
+ * 复用 kernel `createLogger`;输出格式/级别/时间戳/颜色由 napuketto.toml [log] 段 +
348
+ * 环境变量决定(kernel parseLogConfig 单一解析源)。懒构造:commander preAction
349
+ * 钩子先 resolveCliLogConfig(dataDir)(banner 决策 + 缓存),首个日志调用时按
350
+ * 缓存配置构造;未初始化时兜底用缺省数据根解析(-d 生效前的极早期日志)。
351
+ *
352
+ * 环境变量(优先级高于 toml,见 kernel parseLogConfig):NAPUKETTO_LOG_LEVEL /
353
+ * NAPUKETTO_LOG_FORMAT / NAPUKETTO_NO_BANNER / NAPUKETTO_LOG_COLORIZE,
354
+ * 兼容旧拼写 NAPKETTO_LOG_LEVEL。
355
+ */
356
+ /** 已解析日志配置缓存(preAction 首次解析后固定;-d 后续变化不影响已构造 logger)。 */
357
+ let cachedConfig = null;
358
+ /** 解析配置时用的数据根([log.file] 相对路径展开基准)。 */
359
+ let cachedDataRoot = resolveDataRoot();
360
+ /** 同步解析日志配置(内联 > toml 文件的 [log] 段 + env 覆盖)。损坏/缺失配置回退缺省
361
+ * (不阻塞启动:配置的严格校验由 loadCliConfig 主路径负责报错)。内联生效时不读
362
+ * 任何 toml 文件(嵌入式契约,2026-10-25)。 */
363
+ function resolveCliLogConfig(dataDir) {
364
+ if (cachedConfig !== null) return cachedConfig;
365
+ cachedDataRoot = resolveDataRoot(dataDir);
366
+ 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
+ }
373
+ else try {
374
+ const configPath = resolveConfigPath({ dataRoot: cachedDataRoot });
375
+ section = parseToml(readFileSync(configPath, "utf8"))["log"];
376
+ } catch {
377
+ section = void 0;
378
+ }
379
+ try {
380
+ cachedConfig = parseLogConfig(section, process.env);
381
+ } catch {
382
+ cachedConfig = parseLogConfig(void 0, process.env);
383
+ }
384
+ return cachedConfig;
385
+ }
386
+ /**
387
+ * 顶层进程的最终控制台格式([log] format 显式优先,否则按 TTY 自动:
388
+ * 终端 pretty / 管道 single-line)。supervisor 的前缀转发决策同源。
389
+ */
390
+ function effectiveConsoleFormat(cfg) {
391
+ const isTty = process.stdout.isTTY === true;
392
+ return cfg.format ?? (isTty ? "pretty" : "single-line");
393
+ }
394
+ /**
395
+ * 顶层进程的有效控制台渲染决策(传播给子进程):
396
+ * 子进程 stdout 恒为 pipe(TTY 判定失真),由本进程按最终控制台形态决定
397
+ * format/colorize 并经 env 注入(NAPUKETTO_LOG_FORMAT/NAPUKETTO_LOG_COLORIZE)。
398
+ */
399
+ function effectiveConsoleEnv(cfg) {
400
+ const isTty = process.stdout.isTTY === true;
401
+ const format = effectiveConsoleFormat(cfg);
402
+ return {
403
+ NAPUKETTO_LOG_FORMAT: format,
404
+ NAPUKETTO_LOG_COLORIZE: cfg.colorize ?? (format === "pretty" && isTty) ? "1" : "0"
405
+ };
406
+ }
407
+ /** [log.file] 相对路径按数据根展开。 */
408
+ function resolveLogFilePath(path) {
409
+ return isAbsolute(path) ? path : join(cachedDataRoot, path);
410
+ }
411
+ /** cli logger 构造参数([log] 段折叠;file/fileLevel 成对生效,其余直传 undefined)。 */
412
+ function cliLoggerOptions(cfg) {
413
+ return {
414
+ level: cfg.levels.cli ?? cfg.level,
415
+ format: cfg.format,
416
+ timestamp: cfg.timestamp,
417
+ colorize: cfg.colorize,
418
+ file: cfg.file !== void 0 ? resolveLogFilePath(cfg.file.path) : void 0,
419
+ fileLevel: cfg.file?.level,
420
+ base: {
421
+ name: "cli",
422
+ service: "cli"
423
+ }
424
+ };
425
+ }
426
+ /** 懒构造 cli 进程日志(name 渲染为 (cli/pid) 元数据头,文件 JSON 保留 name 字段可过滤)。 */
427
+ var LazyCliLogger = class {
428
+ #inner = null;
429
+ #ensure() {
430
+ if (this.#inner === null) this.#inner = createLogger(cliLoggerOptions(resolveCliLogConfig()));
431
+ return this.#inner;
432
+ }
433
+ info(obj, msg) {
97
434
  this.#ensure().info(obj, msg);
98
435
  }
99
436
  warn(obj, msg) {
@@ -115,6 +452,31 @@ var LazyCliLogger = class {
115
452
  /** cli 进程日志(懒构造,配置见 resolveCliLogConfig)。 */
116
453
  const logger = new LazyCliLogger();
117
454
  //#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
118
480
  //#region src/runtime-state.ts
119
481
  /**
120
482
  * runtime-state.ts:账号运行时状态文件 + 进程控制原语(2026-09-08 T8)。
@@ -228,22 +590,6 @@ function aggregateStatus(runtimes, aliveFn = isPidAlive) {
228
590
  }
229
591
  //#endregion
230
592
  //#region src/boot.ts
231
- /**
232
- * cli boot:单账号启动序列(2026-08-07 用户拍板:只保留自建宿主)
233
- *
234
- * resolveQqFiles(多级来源定位 QQ 原生文件)→ 解析各包 dist 入口 → launchSelfHost
235
- * (标准 node + stub QQNT.dll 直接 dlopen,不拉起 QQ / 不注入)→ 常驻。
236
- *
237
- * QQ 原生文件来源(本机未装 QQ 也能跑,2026-08-16 接入):
238
- * L0 NAPUTO_QQ_FILES 显式文件根 → L1 本机 QQ 安装(--qq-path / NAPUTO_QQ_PATH /
239
- * 注册表 / 常见路径)→ L2 数据根缓存 <数据根>/qq-files/<版本> → 全部缺失时
240
- * 自动下载官方安装包(sha256 校验 + 7z 解包 + 提取缓存,幂等)。
241
- * cached 来源下 qq.qqPath 为语义占位(缓存目录无 QQ.exe)——launchSelfHost 只消费
242
- * qq.wrapperPath / qq.version(NAPUTO_QQ_PATH 仅注入、self-host 未读取),占位安全。
243
- *
244
- * 不写业务逻辑:kernel 装配 + 登录 + 协议装配全部在 self-host.cjs → boot-bootstrap.js 完成。
245
- * 路线 B(拉起 QQ + 注入)已淘汰(launchQqWithLoader 已移除,cli 只走自建宿主)。
246
- */
247
593
  /** 解析 workspace 包的 dist 入口(ESM 解析:包是 ESM-only,exports 无 require 条件)。 */
248
594
  async function packageEntry(pkg) {
249
595
  const url = await import.meta.resolve(pkg);
@@ -252,417 +598,232 @@ async function packageEntry(pkg) {
252
598
  /** QR 透出标记行前缀(loader bootstrap-core 非 IPC 模式输出,cli 解析终端渲染)。 */
253
599
  const QR_LINE_PREFIX = "NAPUTO_QR ";
254
600
  /** 优雅停等待上限(毫秒):超时 kill 兜底(Windows 下为硬杀)。 */
255
- const GRACEFUL_STOP_TIMEOUT_MS = 1e4;
256
- /**
257
- * 逐行转发子进程输出到父进程,过滤原生噪音。
258
- * readline 按 UTF-8 解码 pipe 字节流,再经 process.stdout(TTY 路径,
259
- * WriteConsoleW UTF-16)输出——顺带修复 pino 中文在 cmd.exe/管道 936 转码
260
- * 链路下的乱码(原生 printf 字节流无法从 JS 侧改编码,转 pipe 后统一解码)。
261
- *
262
- * NAPUTO_QR 标记行(loader bootstrap-core 输出,QR 登录二维码数据)不转发,
263
- * 解析后用 qrcode 包渲染终端二维码;png 落盘与 URL 提示由 kernel 日志完成。
264
- * 噪音判定走 loader 共享单一来源(isNativeNoiseLine,与 koishi IPC 路径同源)。
265
- */
266
- function forwardFiltered(input, out) {
267
- createInterface({ input }).on("line", (line) => {
268
- if (line.startsWith(QR_LINE_PREFIX)) {
269
- renderTerminalQr(line.slice(10));
270
- return;
271
- }
272
- if (isNativeNoiseLine(line)) return;
273
- out.write(`${line}\n`);
274
- });
275
- }
276
- /**
277
- * 渲染终端二维码(qrcode 包 terminal 模式,half-block 字符)。
278
- * 解析失败/无 url 时静默丢弃——标记行是内部协议,坏行不影响登录。
279
- */
280
- function renderTerminalQr(raw) {
281
- try {
282
- const { qrcodeUrl } = JSON.parse(raw);
283
- if (qrcodeUrl === void 0 || qrcodeUrl === "") return;
284
- QRCode.toString(qrcodeUrl, {
285
- type: "terminal",
286
- small: true
287
- }).then((str) => {
288
- process.stdout.write(`${str}\n`);
289
- }).catch(() => {});
290
- } catch {}
291
- }
292
- /** 启动单个账号(自建宿主 + 常驻)。 */
293
- async function runSingleAccount(opts = {}) {
294
- const dataRoot = resolveDataRoot(opts.dataDir);
295
- let qq;
296
- try {
297
- qq = await resolveQqFiles({
298
- dataRoot,
299
- ...opts.qqPath !== void 0 ? { qqPath: opts.qqPath } : {}
300
- });
301
- } catch (err) {
302
- logger.error({ err }, `定位/下载 QQ 原生文件失败:${err instanceof Error ? err.message : String(err)}\n(本机未装 QQ 时自动下载官方安装包;若下载失败请检查网络,或手动安装 QQ、设置 NAPUTO_QQ_PATH 指定已有安装、NAPUTO_QQ_FILES 指定文件根、NAPUTO_QQ_URL 覆盖下载地址)`);
303
- process.exitCode = 1;
304
- return;
305
- }
306
- const cfgDir = path.join(dataRoot, opts.qq ?? "default");
307
- const { occupied, pid: holderPid } = checkInstanceLock(cfgDir);
308
- if (occupied) {
309
- logger.error({
310
- pid: holderPid,
311
- dataDir: cfgDir
312
- }, "数据目录已被其他实例占用,拒绝启动(同一账号数据目录仅允许一个实例;占用校验已含 pid 复用检测,如仍误报请删除该目录下的 instance.lock)");
313
- process.exitCode = 1;
314
- return;
315
- }
316
- const kernelEntry = await packageEntry("@napuketto/kernel");
317
- const adapterEntry = await packageEntry("@napuketto/adapter");
318
- const networkEntry = await packageEntry("@napuketto/network");
319
- const stubDir = opts.stubDir ?? process.env["NAPUTO_STUB_DIR"] ?? defaultStubDir();
320
- logger.debug({
321
- qqVersion: qq.version,
322
- qqPath: qq.qqPath,
323
- source: qq.source
324
- }, "QQ 文件来源");
325
- logger.debug({ dataDir: cfgDir }, "数据目录");
326
- logger.debug("自建宿主引导(标准 node + stub QQNT.dll)");
327
- const { child } = await launchSelfHost({
328
- qq,
329
- kernelEntry,
330
- adapterEntry,
331
- networkEntry,
332
- cfgDir,
333
- cwd: dataRoot,
334
- configPath: resolveConfigPath({ dataRoot }),
335
- selfHost: true,
336
- stdio: [
337
- "inherit",
338
- "pipe",
339
- "pipe"
340
- ],
341
- extraEnv: {
342
- ...effectiveConsoleEnv(resolveCliLogConfig(opts.dataDir)),
343
- NAPUTO_DATA_ROOT: dataRoot
344
- },
345
- ...opts.qq !== void 0 ? { quickUin: opts.qq } : {},
346
- ...stubDir !== void 0 ? { stubDir } : {}
347
- });
348
- if (child.stdout !== null) forwardFiltered(child.stdout, process.stdout);
349
- if (child.stderr !== null) forwardFiltered(child.stderr, process.stderr);
350
- writeAccountRuntime(dataRoot, {
351
- uin: opts.qq ?? "default",
352
- pid: process.pid,
353
- ...child.pid !== void 0 ? { selfHostPid: child.pid } : {},
354
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
355
- kind: "single-boot",
356
- status: "running"
357
- });
358
- const account = opts.qq ?? "default";
359
- let stopArmed = false;
360
- const armGracefulStop = (reason) => {
361
- if (stopArmed) return;
362
- stopArmed = true;
363
- logger.info({
364
- account,
365
- reason
366
- }, "收到停止请求,等待自建宿主退出");
367
- setTimeout(() => {
368
- if (child.exitCode === null && !child.killed) {
369
- logger.warn({ account }, "自建宿主未在限时内退出,强制结束");
370
- child.kill();
371
- }
372
- }, GRACEFUL_STOP_TIMEOUT_MS).unref?.();
373
- };
374
- watchStopSentinel({
375
- dataRoot,
376
- account,
377
- onTrigger: () => armGracefulStop("停止哨兵")
378
- });
379
- const onSignal = (signal) => {
380
- writeStopSentinel(dataRoot, account);
381
- armGracefulStop(`信号 ${signal}`);
382
- };
383
- process.on("SIGINT", () => onSignal("SIGINT"));
384
- process.on("SIGTERM", () => onSignal("SIGTERM"));
385
- process.on("SIGBREAK", () => onSignal("SIGBREAK"));
386
- await new Promise((resolve) => {
387
- child.on("exit", (code) => {
388
- logger.info({
389
- code,
390
- graceful: stopArmed
391
- }, "自建宿主进程退出");
392
- writeAccountRuntime(dataRoot, {
393
- uin: opts.qq ?? "default",
394
- pid: process.pid,
395
- ...child.pid !== void 0 ? { selfHostPid: child.pid } : {},
396
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
397
- kind: "single-boot",
398
- status: "exited",
399
- exitCode: code
400
- });
401
- resolve();
402
- });
403
- child.on("error", (err) => {
404
- logger.error({ err }, "自建宿主进程启动失败");
405
- resolve();
406
- });
407
- });
408
- }
409
- //#endregion
410
- //#region src/config-template.ts
411
- /**
412
- * 配置模板(TOML 注释版,从 config-cmds.ts 拆分,2026-08-08 FTA 优化)。
413
- * `config init` 与首次启动(loadCliConfig)缺失时生成。
414
- *
415
- * 2026-08-08 结构拍板:**一个 QQ 账号一个 [[accounts]] 段,协议与通信配置嵌在
416
- * 账号内**([accounts.onebot11] / [accounts.satori]);账号必填(至少一个)。
417
- * dataDir 不再写死(缺省 = 项目根/.napuketto,跨平台),模板保持可移植。
418
- */
419
- /** 保留占位 QQ 号(模板默认值):必须替换为真实 QQ 号,否则启动校验报错。 */
420
- const RESERVED_PLACEHOLDER_QINS = ["123456", "654321"];
421
- function configTemplate() {
422
- return `# ============================================================
423
- # NapukettoQQ 全局配置文件
424
- # ============================================================
425
- # 本文件由 \`napuketto config init\` 生成(或首次启动自动生成)。
426
- # 本机配置不入库(.gitignore);修改后重启生效。
427
- #
428
- # 配置组织:一个 QQ 账号一个 [[accounts]] 段,协议与通信配置嵌在账号内
429
- # ([accounts.onebot11] / [accounts.satori] / [accounts.kurobot])。账号没有写
430
- # 某协议段 = 该账号不启用该协议。账号必填(至少一个,qq 必填)。
431
-
432
- # ------------------------------------------------------------
433
- # 全局配置(跨账号)
434
- # ------------------------------------------------------------
435
-
436
- # 数据根目录:账号目录/日志/缓存/QQ 数据存放位置。
437
- # 缺省 = <项目根>/.napuketto(部署场景,跨平台,无需修改)。
438
- # 支持绝对路径、"~/" 前缀(用户主目录)、相对路径(相对启动目录)。
439
- # dataDir = ".napuketto"
440
-
441
- # 多账号(supervisor)模式下,账号进程崩溃是否自动重启
442
- autoRestart = true
443
-
444
- # 崩溃后自动重启的延迟(毫秒)
445
- restartDelayMs = 2000
446
-
447
- # ------------------------------------------------------------
448
- # 日志([log],可选——不配置即用缺省:终端 pretty 多行 / 管道 single-line)
449
- # ------------------------------------------------------------
450
- # 嵌入式宿主(把 napuketto 打进服务端等场景)推荐:
451
- # [log]
452
- # format = "single-line" # 或 "json"(NDJSON,宿主按 level/module 精确路由)
453
- # level = "warn" # 控制台只留警告以上,细节进文件(配 [log.file])
454
- # banner = false
455
- #
456
- # [log]
457
- # format = "pretty" # pretty | single-line | json(缺省按 TTY 自动)
458
- # level = "info" # trace|debug|info|warn|error|fatal(控制台级别)
459
- # banner = true # 启动字符画
460
- # timestamp = "local" # local | iso8601 | elapsed
461
- # unboundReceive = true # false = 未绑定频道的接收行不打(kurobot 握手后生效)
462
- # [log.levels] # 按模块覆盖级别:cli / kernel / loader / ob11
463
- # # loader = "debug" # 例:终端上看接收行(默认已降 debug)
464
- # # ob11 = "debug" # 例:协议校准数据(含原始 hex)
465
- # [log.file] # 独立文件 sink(可选;级别可低于控制台)
466
- # # path = "logs/napuketto-console.log"
467
- # # level = "debug"
468
- #
469
- # 环境变量覆盖(优先级高于本文件):NAPUKETTO_LOG_LEVEL / NAPUKETTO_LOG_FORMAT /
470
- # NAPUKETTO_NO_BANNER(兼容旧拼写 NAPKETTO_LOG_LEVEL)。
471
-
472
- # ------------------------------------------------------------
473
- # 账号(至少一个,qq 必填)
474
- # ------------------------------------------------------------
475
-
476
- [[accounts]]
477
- qq = "${RESERVED_PLACEHOLDER_QINS[0]}" # 占位值,必须替换为你的 QQ 号,否则启动报错
478
- enabled = true # 是否启用(可选,缺省 true)
479
-
480
- [accounts.onebot11] # 该账号的 OneBot 11 配置(无此段 = 不启用 OB11)
481
-
482
- # 鉴权 token(全局默认):HTTP/WS 连接必须携带。
483
- # 校验方式:Authorization: Bearer <token> / 裸 token / URL 参数 ?access_token=<token>
484
- # 每个网络实例可单独覆盖(见下文各实例的 token 字段)。
485
- # 留空 = 不鉴权(仅本机调试推荐)。
486
- # token = ""
487
-
488
- # 心跳 meta 事件间隔(毫秒);0 = 关闭心跳事件
489
- heartbeatInterval = 3000
490
-
491
- # 是否上报机器人自己发的消息(OB11 规范默认不上报)
492
- reportSelfMessage = false
493
-
494
- # 消息内容格式:array = 消息段数组(标准 OneBot 11),string = CQ 码字符串
495
- messagePostFormat = "array"
496
-
497
- # 群文件报形式:false(默认)= message 事件 + file 段(go-cqhttp 兼容);
498
- # true = 群文件消息改报 group_upload notice 事件(替代 message 事件)
499
- groupUploadAsNotice = false
500
-
501
- # ---- HTTP 反向服务器(接收第三方 POST 指令),可配置多个 ----
502
- [[accounts.onebot11.httpServers]]
503
- enabled = true
504
- host = "127.0.0.1" # 监听地址;0.0.0.0 = 监听所有网卡(局域网可连)
505
- port = 3000
506
- # token = "abc" # 可选:覆盖全局 token
507
-
508
- # ---- HTTP 正向上报(Webhook:把事件 POST 到第三方地址),可配置多个 ----
509
- # [[accounts.onebot11.httpPostUrls]]
510
- # enabled = true
511
- # url = "http://127.0.0.1:8080/onebot" # 第三方接收地址
512
- # token = "abc" # 可选:覆盖全局 token
513
- # timeoutMs = 5000 # 可选:上报超时(毫秒),缺省不超时
514
-
515
- # ---- WS 反向服务器(外部 WS 客户端主动连入),可配置多个 ----
516
- [[accounts.onebot11.wsServers]]
517
- enabled = true
518
- host = "127.0.0.1"
519
- port = 3001
520
- # token = "abc" # 可选:覆盖全局 token
521
- # heartbeatInterval = 30000 # 可选:WS ping 间隔(毫秒)
522
-
523
- # ---- WS 正向客户端(主动连接外部 WS,双向),可配置多个 ----
524
- # [[accounts.onebot11.wsReverseUrls]]
525
- # enabled = true
526
- # url = "ws://127.0.0.1:8081/ws" # 第三方 WS 地址(ws:// 或 wss://)
527
- # token = "abc" # 可选:覆盖全局 token
528
- # reconnectDelayMs = 5000 # 可选:断线重连延迟(毫秒)
529
- # maxReconnectAttempts = 10 # 可选:最大重连次数(缺省无限)
530
- # rejectUnauthorized = true # 可选:wss:// 是否校验证书(自签证书设 false)
531
- # heartbeatInterval = 30000 # 可选:WS ping 间隔(毫秒)
532
-
533
- # 第二个账号示例(只开 Satori):
534
- # [[accounts]]
535
- # qq = "${RESERVED_PLACEHOLDER_QINS[1]}"
536
- # [accounts.satori]
537
- # # token = "" # 可选:Satori 鉴权 token
538
- # [[accounts.satori.httpServers]] # HTTP RPC(POST /v1/{resource}.{method})
539
- # enabled = true
540
- # host = "127.0.0.1"
541
- # port = 5500
542
- # [[accounts.satori.wsServers]] # WS 事件服务(/v1/events)
543
- # enabled = true
544
- # host = "127.0.0.1"
545
- # port = 5501
546
-
547
- # ------------------------------------------------------------
548
- # KuroBot 群服互通(kurobridge-ws 客户端,MVP-3)
549
- # ------------------------------------------------------------
550
- # 账号内写 [accounts.kurobot] 段即启用;不写 = 不启用。作为 WS 客户端
551
- # 主动连入 KuroBot 服务端(Minecraft 服务器 kurobot 插件)。
552
- # QQ 群文字 ↔ 游戏聊天双向互通;群命令(前缀开头)→ 游戏命令。
553
- # [accounts.kurobot]
554
- # url = "ws://127.0.0.1:25580" # 必填:KuroBot 服务端地址(ws:// 或 wss://)
555
- # # token = "" # 可选:鉴权 token(服务端配了则必填,错 token 拒连)
556
- # # client = "napukettoqq" # 可选:自报身份(缺省 napukettoqq/<版本>)
557
- # # commandPrefix = "/" # 可选:群命令前缀
558
- # # pingIntervalMs = 15000 # 可选:应用层心跳间隔(毫秒,须 < 30000)
559
- # # chatTemplate = "[{player}] {content}" # 游戏聊天渲染模板
560
- # # joinTemplate = "{player} 加入了服务器" # 玩家进服模板
561
- # # leaveTemplate = "{player} 离开了服务器" # 玩家退服模板
562
- # # deathTemplate = "{player} {message}" # 玩家死亡模板(空消息显示「死亡了」)
563
- `;
564
- }
565
- //#endregion
566
- //#region src/config-parse.ts
601
+ const GRACEFUL_STOP_TIMEOUT_MS = 1e4;
567
602
  /**
568
- * 主配置类型与手写校验器(从 config-cmds.ts 拆分,2026-08-08 FTA 优化)
603
+ * 逐行转发子进程输出到父进程,过滤原生噪音。
604
+ * readline 按 UTF-8 解码 pipe 字节流,再经 process.stdout(TTY 路径,
605
+ * WriteConsoleW UTF-16)输出——顺带修复 pino 中文在 cmd.exe/管道 936 转码
606
+ * 链路下的乱码(原生 printf 字节流无法从 JS 侧改编码,转 pipe 后统一解码)。
569
607
  *
570
- * 主配置 parse(不引入 zod):数据根 / 自动重启 / 重启延迟 / 账号列表。
571
- * 2026-08-08 结构拍板:**一个 QQ 账号一个 [[accounts]] 段,协议与通信配置嵌在
572
- * 账号内**([accounts.onebot11] / [accounts.satori]);账号必填(至少一个)。
573
- * 协议段为宽松对象,装配时由对应协议包的 zod schema 严格校验。
608
+ * NAPUTO_QR 标记行(loader bootstrap-core 输出,QR 登录二维码数据)不转发,
609
+ * 解析后用 qrcode 包渲染终端二维码;png 落盘与 URL 提示由 kernel 日志完成。
610
+ * 噪音判定走 loader 共享单一来源(isNativeNoiseLine,与 koishi IPC 路径同源)。
574
611
  */
575
- /** 默认自动重启。 */
576
- const DEFAULT_AUTO_RESTART = true;
577
- /** 默认重启延迟(毫秒)。 */
578
- const DEFAULT_RESTART_DELAY_MS$1 = 2e3;
579
- /** QQ 号格式:纯数字 5-11 位(QQ 号合法范围,勿写死 11 位)。 */
580
- const QQ_IN_FORMAT_RE = /^\d{5,11}$/;
581
- /** 解析账号内协议段(宽松对象,装配时由 zod schema 严格校验)。 */
582
- function parseProtocolSection(raw, key) {
583
- const section = raw[key];
584
- if (section === void 0) return;
585
- if (typeof section !== "object" || section === null) throw kernelError(`主配置账号 ${key} 段必须是对象`, "INVALID_PARAM");
586
- return section;
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
+ });
587
621
  }
588
622
  /**
589
- * 解析 dataDir(缺省用当前解析的数据根 = 项目根/.napuketto)。
590
- * 支持绝对路径、"~/" 前缀(用户主目录)、相对路径(相对启动目录),
591
- * 消费端 resolveDataRoot 统一展开为绝对路径。
623
+ * 渲染终端二维码(qrcode 包 terminal 模式,half-block 字符)。
624
+ * 解析失败/无 url 时静默丢弃——标记行是内部协议,坏行不影响登录。
592
625
  */
593
- function parseDataDir(raw) {
594
- if (raw["dataDir"] === void 0) return resolveDataRoot();
595
- if (typeof raw["dataDir"] !== "string" || raw["dataDir"] === "") throw kernelError("主配置 dataDir 必须是非空字符串", "INVALID_PARAM");
596
- return raw["dataDir"];
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 {}
597
637
  }
598
- /** 解析 autoRestart。 */
599
- function parseAutoRestart(raw) {
600
- if (raw["autoRestart"] === void 0) return DEFAULT_AUTO_RESTART;
601
- if (typeof raw["autoRestart"] !== "boolean") throw kernelError("主配置 autoRestart 必须是布尔值", "INVALID_PARAM");
602
- return raw["autoRestart"];
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
+ };
603
645
  }
604
- /** 解析 restartDelayMs(毫秒)。 */
605
- function parseRestartDelayMs(raw) {
606
- if (raw["restartDelayMs"] === void 0) return DEFAULT_RESTART_DELAY_MS$1;
607
- if (typeof raw["restartDelayMs"] !== "number" || !Number.isInteger(raw["restartDelayMs"]) || raw["restartDelayMs"] <= 0) throw kernelError("主配置 restartDelayMs 必须是正整数", "INVALID_PARAM");
608
- return raw["restartDelayMs"];
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();
609
649
  }
610
- /** 解析 accounts(必须至少一个账号,qq 必填)。 */
611
- function parseAccounts(raw) {
612
- if (raw["accounts"] === void 0) throw kernelError("主配置缺少 accounts(必须至少一个账号);首次启动已生成模板,请编辑后重试", "INVALID_PARAM");
613
- if (!Array.isArray(raw["accounts"]) || raw["accounts"].length === 0) throw kernelError("主配置 accounts 必须是非空数组(至少一个 QQ 账号);首次启动已生成模板,请编辑后重试", "INVALID_PARAM");
614
- const accounts = [];
615
- for (const item of raw["accounts"]) accounts.push(parseAccount(item));
616
- return accounts;
650
+ /** 错误文案提取(Error 用 message,其余字符串化——保留旧日志文案语义)。 */
651
+ function errorMessage(err) {
652
+ return err instanceof Error ? err.message : String(err);
617
653
  }
618
- /** 解析单个账号项(qq 必填;协议段缺省 = 不启用)。 */
619
- function parseAccount(item) {
620
- if (typeof item !== "object" || item === null) throw kernelError("主配置 accounts 元素必须是对象", "INVALID_PARAM");
621
- const { qq, enabled } = item;
622
- if (typeof qq !== "string" || qq === "") throw kernelError("主配置账号缺少非空 qq", "INVALID_PARAM");
623
- if (!QQ_IN_FORMAT_RE.test(qq)) throw kernelError("主配置账号 qq 必须是 5-11 位纯数字 QQ 号", "INVALID_PARAM");
624
- if (RESERVED_PLACEHOLDER_QINS.some((placeholder) => placeholder === qq)) throw kernelError(`主配置账号 qq "${qq}" 是模板占位值,请编辑配置文件填入真实 QQ 号后再启动`, "INVALID_PARAM");
625
- const out = { qq };
626
- if (enabled !== void 0) {
627
- if (typeof enabled !== "boolean") throw kernelError("主配置账号 enabled 必须是布尔值", "INVALID_PARAM");
628
- out.enabled = enabled;
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;
629
666
  }
630
- const raw = item;
631
- const onebot11 = parseProtocolSection(raw, "onebot11");
632
- if (onebot11 !== void 0) out.onebot11 = onebot11;
633
- const satori = parseProtocolSection(raw, "satori");
634
- if (satori !== void 0) out.satori = satori;
635
- const kurobot = parseProtocolSection(raw, "kurobot");
636
- if (kurobot !== void 0) out.kurobot = kurobot;
637
- return out;
638
667
  }
639
668
  /**
640
- * [log] 段落库净化:format 为 undefined(= 按 TTY 自动)时剔除该键,
641
- * 避免 toml 回写(config list/apply 的 stringifyToml)遇到 undefined 值。
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
642
676
  */
643
- function stripUndefinedFormat(log) {
644
- const { format, ...rest } = log;
645
- return format === void 0 ? rest : {
646
- ...rest,
647
- format
648
- };
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;
649
686
  }
650
- /** 手写校验器:主配置 parse(不引入 zod)。 */
651
- function parseCliConfig(input) {
652
- if (typeof input !== "object" || input === null) throw kernelError("主配置必须是对象", "INVALID_PARAM");
653
- const raw = input;
654
- const dataDir = parseDataDir(raw);
655
- const autoRestart = parseAutoRestart(raw);
656
- const restartDelayMs = parseRestartDelayMs(raw);
657
- const accounts = parseAccounts(raw);
658
- const log = raw["log"] !== void 0 ? stripUndefinedFormat(parseLogConfig(raw["log"])) : void 0;
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;
659
709
  return {
660
- dataDir,
661
- autoRestart,
662
- restartDelayMs,
663
- accounts,
664
- ...log !== void 0 ? { log } : {}
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}`);
665
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));
666
827
  }
667
828
  //#endregion
668
829
  //#region src/config-cmds.ts
@@ -696,12 +857,41 @@ var CliConfigStore = class extends ConfigBase {
696
857
  });
697
858
  }
698
859
  };
699
- /** 读取主配置(缺失自动落模板)。 */
860
+ /** 读取主配置(缺失自动落模板;loadCliConfigWithSource 文件分支内部用)。 */
700
861
  async function loadCliConfig(dataRoot) {
701
862
  const store = new CliConfigStore(dataRoot);
702
863
  await ensureConfigTemplate(store.path);
703
864
  return await store.load();
704
865
  }
866
+ /** 「配置来源」日志每进程至多一行(autoStart 与 runSupervisor 各加载一次)。 */
867
+ let sourceLogged = false;
868
+ /**
869
+ * 加载主配置(内联优先,2026-10-25 嵌入式契约):
870
+ * NAPKETTO_CONFIG_JSON 非空 → 内存文档校验(不读 / 不写 / 不校验任何 toml
871
+ * 文件),打一行来源日志;否则现行文件链路(缺失自动落模板)。校验失败两形态
872
+ * 同为 ConfigError(exit 78),文案区别只在来源标注。
873
+ */
874
+ async function loadCliConfigWithSource(opts = {}) {
875
+ const inlineText = readInlineConfigText();
876
+ if (inlineText !== void 0) {
877
+ const config = parseInlineConfig(inlineText);
878
+ if (!sourceLogged) {
879
+ sourceLogged = true;
880
+ logger.info("配置来源: inline(NAPKETTO_CONFIG_JSON)");
881
+ }
882
+ return {
883
+ config,
884
+ source: "inline"
885
+ };
886
+ }
887
+ const dataRoot = resolveDataRoot(opts.dataDir);
888
+ const configPath = resolveConfigPath({ dataRoot });
889
+ return {
890
+ config: await loadCliConfig(dataRoot),
891
+ source: "file",
892
+ path: configPath
893
+ };
894
+ }
705
895
  /** CliConfig → 普通对象(smol-toml stringify 入参)。 */
706
896
  function toRecord(config) {
707
897
  return config;
@@ -794,6 +984,59 @@ async function cmdConfigApply(file, opts) {
794
984
  logger.info({ path: store.path }, "全局配置已更新");
795
985
  process.stdout.write(`${stringifyToml(toRecord(next))}\n`);
796
986
  }
987
+ /** 读取配置文件文本(validate 纯只读:ENOENT 不落模板,按「配置缺失」报 ConfigError)。 */
988
+ async function readConfigTextForValidate(path) {
989
+ try {
990
+ return await readFile(path, "utf8");
991
+ } catch (err) {
992
+ if (err.code === "ENOENT") throw configError(`配置文件不存在: ${path}`);
993
+ throw configError(`读取配置文件失败: ${path}`, { cause: err });
994
+ }
995
+ }
996
+ /**
997
+ * 校验配置文件(与运行时同构:ConfigBase.parseText 反序列化 + 校验,报错文案
998
+ * 含路径且与 loadCliConfig 主路径逐字一致;格式按扩展名推断,同 ConfigBase)。
999
+ */
1000
+ async function validateConfigFile(path, dataRoot) {
1001
+ const raw = await readConfigTextForValidate(path);
1002
+ new ConfigBase({
1003
+ path,
1004
+ schema: { parse: parseCliConfig },
1005
+ defaults: defaultCliConfig(dataRoot)
1006
+ }).parseText(raw);
1007
+ }
1008
+ /**
1009
+ * config validate:校验配置(exit 0 = 合法;exit 78 = 校验失败,ConfigError 一族;
1010
+ * --config 与 --config-json 同给 = 用法错误,exit 1)。纯只读——文件形态不落模板
1011
+ * (无参形态文件缺失按配置缺失报 78),不触碰数据目录。
1012
+ */
1013
+ async function cmdConfigValidate(opts) {
1014
+ const { configPath, configJson } = opts;
1015
+ if (configPath !== void 0 && configJson !== void 0) throw kernelError("config validate:--config 与 --config-json 只能二选一", "INVALID_PARAM");
1016
+ const dataRoot = resolveDataRoot(opts.dataDir);
1017
+ if (configJson !== void 0) {
1018
+ parseInlineConfig(configJson);
1019
+ return { source: "inline" };
1020
+ }
1021
+ if (configPath !== void 0) {
1022
+ await validateConfigFile(configPath, dataRoot);
1023
+ return {
1024
+ source: "file",
1025
+ path: configPath
1026
+ };
1027
+ }
1028
+ const inlineText = readInlineConfigText();
1029
+ if (inlineText !== void 0) {
1030
+ parseInlineConfig(inlineText);
1031
+ return { source: "inline" };
1032
+ }
1033
+ const path = resolveConfigPath({ dataRoot });
1034
+ await validateConfigFile(path, dataRoot);
1035
+ return {
1036
+ source: "file",
1037
+ path
1038
+ };
1039
+ }
797
1040
  //#endregion
798
1041
  //#region src/ops-commands.ts
799
1042
  /**
@@ -1014,6 +1257,22 @@ function startAccount(ctx, acct) {
1014
1257
  code,
1015
1258
  signal: signal ?? "none"
1016
1259
  }, "账号退出");
1260
+ if (code === EXIT_CONFIG_INVALID) {
1261
+ logger.error({
1262
+ qq: acct.qq,
1263
+ code
1264
+ }, "账号因配置校验失败退出(78),不自动重启");
1265
+ writeAccountRuntime(ctx.dataRoot, {
1266
+ uin: acct.qq,
1267
+ pid: child.pid ?? 0,
1268
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1269
+ kind: "supervisor-child",
1270
+ status: "exited",
1271
+ exitCode: code,
1272
+ restartCount
1273
+ });
1274
+ return;
1275
+ }
1017
1276
  if (!ctx.isStopping() && ctx.autoRestart) {
1018
1277
  ctx.restartCounts.set(acct.qq, restartCount + 1);
1019
1278
  setTimeout(() => {
@@ -1064,7 +1323,7 @@ function stopAll(ctx) {
1064
1323
  /** 运行 supervisor(多账号编排)。 */
1065
1324
  async function runSupervisor(opts = {}) {
1066
1325
  const dataRoot = resolveDataRoot(opts.dataDir);
1067
- const config = await loadCliConfig(dataRoot);
1326
+ const { config } = await loadCliConfigWithSource(opts.dataDir !== void 0 ? { dataDir: opts.dataDir } : {});
1068
1327
  const accounts = resolveAccounts(opts, config);
1069
1328
  if (accounts.length === 0) {
1070
1329
  logger.warn("supervisor:没有启用的账号(主配置 accounts 为空或全部禁用)");
@@ -1118,7 +1377,9 @@ async function runSupervisor(opts = {}) {
1118
1377
  * - 单账号:-q <uin> → runSingleAccount(自建宿主:标准 node + stub QQNT.dll,不拉起 QQ)
1119
1378
  * - 多账号:-q A -q B 或 supervisor 子命令 → runSupervisor(子进程编排)
1120
1379
  * - 无 -q:读全局配置 accounts(至少一个,账号必填)→ supervisor 拉起全部启用账号
1121
- * - config 子命令:init / list / apply(主配置管理)
1380
+ * - config 子命令:init / list / apply / validate(主配置管理)
1381
+ * - 退出码契约(2026-10-25):0 = 请求式优雅关停;78 = 配置校验失败(ConfigError
1382
+ * 一族,宿主消费,免重启);其余错误 = 1(handleActionError 统一出口)
1122
1383
  *
1123
1384
  * 路线 B(拉起 QQ + 注入)已淘汰(2026-08-07 用户拍板),相关入口已移除。
1124
1385
  */
@@ -1136,20 +1397,21 @@ const BANNER = [
1136
1397
  "/_/ |_/\\__,_/ .___/\\__,_/_/|_|\\___/\\__/\\__/\\____/\\___\\_\\___\\_\\ ",
1137
1398
  " /_/ "
1138
1399
  ].join("\n");
1139
- /** 统一错误输出(结构化日志,错误对象经 pino serializer 带堆栈)。 */
1140
- function reportError(err) {
1141
- let message = String(err);
1142
- if (err instanceof Error) {
1143
- const { message: errMessage } = err;
1144
- message = errMessage;
1145
- }
1146
- logger.error({ err }, message);
1147
- }
1148
1400
  /** 构造可选 dataDir 参数(exactOptionalPropertyTypes 不允许显式 undefined)。 */
1149
1401
  function withDataDir(dataDir) {
1150
1402
  if (dataDir === void 0) return {};
1151
1403
  return { dataDir };
1152
1404
  }
1405
+ /** 构造可选 stubDir 参数(同 withDataDir)。 */
1406
+ function withStubDir(stubDir) {
1407
+ if (stubDir === void 0) return {};
1408
+ return { stubDir };
1409
+ }
1410
+ /** 构造可选 qqPath 参数(同 withDataDir)。 */
1411
+ function withQqPath(qqPath) {
1412
+ if (qqPath === void 0) return {};
1413
+ return { qqPath };
1414
+ }
1153
1415
  /** 读主命令已解析的 data-dir(-d 定义在主命令,子命令经此共享)。 */
1154
1416
  function rootDataDir(program) {
1155
1417
  return withDataDir(program.opts().dataDir);
@@ -1161,24 +1423,33 @@ function registerConfigCommands(program) {
1161
1423
  try {
1162
1424
  await cmdConfigInit(rootDataDir(program));
1163
1425
  } catch (err) {
1164
- reportError(err);
1165
- process.exitCode = 1;
1426
+ handleActionError(err);
1166
1427
  }
1167
1428
  });
1168
1429
  configCmd.command("list").description("列出全局配置与账号配置").action(async () => {
1169
1430
  try {
1170
1431
  await cmdConfigList(rootDataDir(program));
1171
1432
  } catch (err) {
1172
- reportError(err);
1173
- process.exitCode = 1;
1433
+ handleActionError(err);
1174
1434
  }
1175
1435
  });
1176
1436
  configCmd.command("apply <file>").description("应用外部配置(TOML/JSON,校验后写回全局配置)").action(async (file) => {
1177
1437
  try {
1178
1438
  await cmdConfigApply(file, rootDataDir(program));
1179
1439
  } catch (err) {
1180
- reportError(err);
1181
- process.exitCode = 1;
1440
+ handleActionError(err);
1441
+ }
1442
+ });
1443
+ configCmd.command("validate").description("校验配置(--config <path> / --config-json <json> 二选一;无参 = 校验生效配置)").option("--config <path>", "待校验配置文件路径(.toml/.json 按扩展名解析)").option("--config-json <json>", "待校验内联配置 JSON 文本").action(async (opts) => {
1444
+ try {
1445
+ const result = await cmdConfigValidate({
1446
+ configPath: opts.config,
1447
+ configJson: opts.configJson,
1448
+ ...rootDataDir(program)
1449
+ });
1450
+ process.stdout.write(result.source === "inline" ? "配置校验通过(来源: inline)\n" : `配置校验通过(来源: file ${result.path})\n`);
1451
+ } catch (err) {
1452
+ handleActionError(err);
1182
1453
  }
1183
1454
  });
1184
1455
  }
@@ -1188,76 +1459,72 @@ function registerSupervisorCommand(program) {
1188
1459
  try {
1189
1460
  await runSupervisor(rootDataDir(program));
1190
1461
  } catch (err) {
1191
- reportError(err);
1192
- process.exitCode = 1;
1462
+ handleActionError(err);
1193
1463
  }
1194
1464
  });
1195
1465
  }
1196
- /** 注册运维子命令(status/stop/restart,2026-09-08 T8;-d 复用主命令 option)。 */
1197
- function registerOpsCommands(program) {
1198
- program.command("status").description("查看各账号运行状态(读 runtime.json + 进程存活检测)").option("-q, --qq <uin>", "只看指定账号").action(async (opts) => {
1199
- try {
1200
- cmdStatus(resolveDataRoot(rootDataDir(program).dataDir), { ...opts.qq !== void 0 ? { qq: opts.qq } : {} });
1201
- } catch (err) {
1202
- reportError(err);
1203
- process.exitCode = 1;
1204
- }
1205
- });
1206
- program.command("stop").description("停止账号进程树(无 -q 停 supervisor 全部;-q 停单账号,supervisor 守护时会自动拉起)").option("-q, --qq <uin>", "目标账号(缺省停 supervisor + 全部账号)").action(async (opts) => {
1207
- try {
1208
- await cmdStop(resolveDataRoot(rootDataDir(program).dataDir), { ...opts.qq !== void 0 ? { qq: opts.qq } : {} });
1209
- } catch (err) {
1210
- reportError(err);
1211
- process.exitCode = 1;
1212
- }
1213
- });
1214
- program.command("restart").description("重启账号(无 -q 重启 supervisor 全量;-q 重启单账号;detached 拉起)").option("-q, --qq <uin>", "目标账号(缺省重启 supervisor 全量)").action(async (opts) => {
1466
+ /** 运维子命令公共壳:解析数据根 + 可选 -q 参数,统一 handleActionError 出口。 */
1467
+ function opsAction(program, run) {
1468
+ return async (opts) => {
1215
1469
  try {
1216
- await cmdRestart(resolveDataRoot(rootDataDir(program).dataDir), { ...opts.qq !== void 0 ? { qq: opts.qq } : {} });
1470
+ await run(resolveDataRoot(rootDataDir(program).dataDir), opts.qq !== void 0 ? { qq: opts.qq } : {});
1217
1471
  } catch (err) {
1218
- reportError(err);
1219
- process.exitCode = 1;
1472
+ handleActionError(err);
1220
1473
  }
1221
- });
1474
+ };
1475
+ }
1476
+ /** 注册运维子命令(status/stop/restart,2026-09-08 T8;-q 复用主命令 option)。 */
1477
+ function registerOpsCommands(program) {
1478
+ program.command("status").description("查看各账号运行状态(读 runtime.json + 进程存活检测)").option("-q, --qq <uin>", "只看指定账号").action(opsAction(program, (dataRoot, arg) => cmdStatus(dataRoot, arg)));
1479
+ program.command("stop").description("停止账号进程树(无 -q 停 supervisor 全部;-q 停单账号,supervisor 守护时会自动拉起)").option("-q, --qq <uin>", "目标账号(缺省停 supervisor + 全部账号)").action(opsAction(program, (dataRoot, arg) => cmdStop(dataRoot, arg)));
1480
+ program.command("restart").description("重启账号(无 -q 重启 supervisor 全量;-q 重启单账号;detached 拉起)").option("-q, --qq <uin>", "目标账号(缺省重启 supervisor 全量)").action(opsAction(program, (dataRoot, arg) => cmdRestart(dataRoot, arg)));
1222
1481
  }
1223
1482
  /** 单账号启动分支(-q 单值;构造 bootOptions 后走 runSingleAccount)。 */
1224
1483
  async function runSingleAccountBranch(opts, qqs) {
1225
1484
  const [only] = qqs;
1226
1485
  if (only === void 0) return;
1227
- const bootOptions = { qq: only };
1228
- if (opts.dataDir !== void 0) bootOptions.dataDir = opts.dataDir;
1229
- if (opts.qqPath !== void 0) bootOptions.qqPath = opts.qqPath;
1230
- if (opts.stubDir !== void 0) bootOptions.stubDir = opts.stubDir;
1231
- await runSingleAccount(bootOptions);
1486
+ await runSingleAccount({
1487
+ qq: only,
1488
+ ...withDataDir(opts.dataDir),
1489
+ ...withQqPath(opts.qqPath),
1490
+ ...withStubDir(opts.stubDir)
1491
+ });
1232
1492
  }
1233
1493
  /** 无 -q 时:读全局配置 accounts(账号必填,2026-08-08 拍板),supervisor 拉起全部启用账号。
1234
- * 不再有「配置为空 → 交互式单账号登录」老路径:缺账号直接报错提示编辑模板。 */
1494
+ * 不再有「配置为空 → 交互式单账号登录」老路径:缺账号直接报错提示编辑模板。
1495
+ * 配置加载内联优先(NAPKETTO_CONFIG_JSON > 文件);校验失败 ConfigError → exit 78。 */
1235
1496
  async function autoStart(opts) {
1236
- if ((await loadCliConfig(resolveDataRoot(opts.dataDir))).accounts.length === 0) throw new Error("主配置没有账号,请编辑 napuketto.toml 填写 [[accounts]] 段");
1497
+ const { config } = await loadCliConfigWithSource(withDataDir(opts.dataDir));
1498
+ if (config.accounts.length === 0) throw new Error("主配置没有账号,请编辑 napuketto.toml 填写 [[accounts]] 段");
1237
1499
  await runSupervisor({
1238
- ...opts.dataDir !== void 0 ? { dataDir: opts.dataDir } : {},
1239
- ...opts.stubDir !== void 0 ? { stubDir: opts.stubDir } : {}
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)
1240
1519
  });
1241
1520
  }
1242
1521
  /** 注册主命令 action(-q 单账号 / 多 -q supervisor / 无 -q 读配置 supervisor 拉起)。 */
1243
1522
  function registerMainAction(program) {
1244
1523
  program.action(async (opts) => {
1245
1524
  try {
1246
- const qqs = opts.qq ?? [];
1247
- if (qqs.length === 0) {
1248
- await autoStart(opts);
1249
- return;
1250
- }
1251
- if (qqs.length === 1) await runSingleAccountBranch(opts, qqs);
1252
- else {
1253
- const supOpts = { qqs };
1254
- if (opts.dataDir !== void 0) supOpts.dataDir = opts.dataDir;
1255
- if (opts.stubDir !== void 0) supOpts.stubDir = opts.stubDir;
1256
- await runSupervisor(supOpts);
1257
- }
1525
+ await dispatchMainAction(opts);
1258
1526
  } catch (err) {
1259
- reportError(err);
1260
- process.exitCode = 1;
1527
+ handleActionError(err);
1261
1528
  }
1262
1529
  });
1263
1530
  }