@napuketto/cli 0.2.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 +904 -562
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.mjs
CHANGED
|
@@ -1,15 +1,226 @@
|
|
|
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";
|
|
6
|
+
import { access, readFile, writeFile } from "node:fs/promises";
|
|
5
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";
|
|
6
10
|
import { createInterface } from "node:readline";
|
|
7
11
|
import { fileURLToPath } from "node:url";
|
|
8
|
-
import { checkInstanceLock, defaultStubDir, isNativeNoiseLine, launchSelfHost, removeStopSentinel, resolveQqFiles, watchStopSentinel, writeStopSentinel } from "@napuketto/loader";
|
|
9
12
|
import QRCode from "qrcode";
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
+
//#region src/config/schema.ts
|
|
14
|
+
/**
|
|
15
|
+
* 主配置类型与手写校验器(原 config-cmds.ts 拆分,2026-08-08 FTA 优化)
|
|
16
|
+
*
|
|
17
|
+
* 主配置 parse(不引入 zod):数据根 / 自动重启 / 重启延迟 / 账号列表。
|
|
18
|
+
* 2026-08-08 结构拍板:**一个 QQ 账号一个 [[accounts]] 段,协议与通信配置嵌在
|
|
19
|
+
* 账号内**([accounts.onebot11] / [accounts.satori]);账号必填(至少一个)。
|
|
20
|
+
* 协议段为宽松对象,装配时由对应协议包的 zod schema 严格校验。
|
|
21
|
+
* 全部校验错误为 ConfigError(2026-10-25 嵌入式退出码契约:CLI exit 78 一族,
|
|
22
|
+
* 内联与文件两形态共用本校验器)。
|
|
23
|
+
*/
|
|
24
|
+
/** 保留占位 QQ 号(模板默认值):必须替换为真实 QQ 号,否则启动校验报错。 */
|
|
25
|
+
const RESERVED_PLACEHOLDER_QINS = ["123456", "654321"];
|
|
26
|
+
/** 默认自动重启。 */
|
|
27
|
+
const DEFAULT_AUTO_RESTART = true;
|
|
28
|
+
/** 默认重启延迟(毫秒;supervisor 显式 -q 场景复用,避免两处常量漂移)。 */
|
|
29
|
+
const DEFAULT_RESTART_DELAY_MS = 2e3;
|
|
30
|
+
/** QQ 号格式:纯数字 5-11 位(QQ 号合法范围,勿写死 11 位)。 */
|
|
31
|
+
const QQ_IN_FORMAT_RE = /^\d{5,11}$/;
|
|
32
|
+
/** 解析账号内协议段(宽松对象,装配时由 zod schema 严格校验)。 */
|
|
33
|
+
function parseProtocolSection(raw, key) {
|
|
34
|
+
const section = raw[key];
|
|
35
|
+
if (section === void 0) return;
|
|
36
|
+
if (typeof section !== "object" || section === null) throw configError(`主配置账号 ${key} 段必须是对象`);
|
|
37
|
+
return section;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* 解析 dataDir(缺省用当前解析的数据根 = 项目根/.napuketto)。
|
|
41
|
+
* 支持绝对路径、"~/" 前缀(用户主目录)、相对路径(相对启动目录),
|
|
42
|
+
* 消费端 resolveDataRoot 统一展开为绝对路径。
|
|
43
|
+
*/
|
|
44
|
+
function parseDataDir(raw) {
|
|
45
|
+
if (raw["dataDir"] === void 0) return resolveDataRoot();
|
|
46
|
+
if (typeof raw["dataDir"] !== "string" || raw["dataDir"] === "") throw configError("主配置 dataDir 必须是非空字符串");
|
|
47
|
+
return raw["dataDir"];
|
|
48
|
+
}
|
|
49
|
+
/** 解析 autoRestart。 */
|
|
50
|
+
function parseAutoRestart(raw) {
|
|
51
|
+
if (raw["autoRestart"] === void 0) return DEFAULT_AUTO_RESTART;
|
|
52
|
+
if (typeof raw["autoRestart"] !== "boolean") throw configError("主配置 autoRestart 必须是布尔值");
|
|
53
|
+
return raw["autoRestart"];
|
|
54
|
+
}
|
|
55
|
+
/** 解析 restartDelayMs(毫秒)。 */
|
|
56
|
+
function parseRestartDelayMs(raw) {
|
|
57
|
+
if (raw["restartDelayMs"] === void 0) return DEFAULT_RESTART_DELAY_MS;
|
|
58
|
+
if (typeof raw["restartDelayMs"] !== "number" || !Number.isInteger(raw["restartDelayMs"]) || raw["restartDelayMs"] <= 0) throw configError("主配置 restartDelayMs 必须是正整数");
|
|
59
|
+
return raw["restartDelayMs"];
|
|
60
|
+
}
|
|
61
|
+
/** 解析 accounts(必须至少一个账号,qq 必填)。 */
|
|
62
|
+
function parseAccounts(raw) {
|
|
63
|
+
if (raw["accounts"] === void 0) throw configError("主配置缺少 accounts(必须至少一个账号);首次启动已生成模板,请编辑后重试");
|
|
64
|
+
if (!Array.isArray(raw["accounts"]) || raw["accounts"].length === 0) throw configError("主配置 accounts 必须是非空数组(至少一个 QQ 账号);首次启动已生成模板,请编辑后重试");
|
|
65
|
+
const accounts = [];
|
|
66
|
+
for (const item of raw["accounts"]) accounts.push(parseAccount(item));
|
|
67
|
+
return accounts;
|
|
68
|
+
}
|
|
69
|
+
/** 账号 qq 必填校验(非空字符串)。 */
|
|
70
|
+
function parseAccountQq(raw) {
|
|
71
|
+
const qq = raw["qq"];
|
|
72
|
+
if (typeof qq !== "string" || qq === "") throw configError("主配置账号缺少非空 qq");
|
|
73
|
+
assertValidQqFormat(qq);
|
|
74
|
+
return qq;
|
|
75
|
+
}
|
|
76
|
+
/** qq 格式与占位值校验(5-11 位纯数字;模板占位号显式指路不静默)。 */
|
|
77
|
+
function assertValidQqFormat(qq) {
|
|
78
|
+
if (!QQ_IN_FORMAT_RE.test(qq)) throw configError("主配置账号 qq 必须是 5-11 位纯数字 QQ 号");
|
|
79
|
+
if (RESERVED_PLACEHOLDER_QINS.some((placeholder) => placeholder === qq)) throw configError(`主配置账号 qq "${qq}" 是模板占位值,请编辑配置文件填入真实 QQ 号后再启动`);
|
|
80
|
+
}
|
|
81
|
+
/** 账号 enabled 可选校验(缺省 = 启用;显式给值必须是布尔)。 */
|
|
82
|
+
function applyAccountEnabled(out, enabled) {
|
|
83
|
+
if (enabled === void 0) return;
|
|
84
|
+
if (typeof enabled !== "boolean") throw configError("主配置账号 enabled 必须是布尔值");
|
|
85
|
+
out.enabled = enabled;
|
|
86
|
+
}
|
|
87
|
+
/** 账号内协议段装配(onebot11/satori/kurobot 缺省 = 不启用该协议)。 */
|
|
88
|
+
function applyProtocolSections(raw, out) {
|
|
89
|
+
const onebot11 = parseProtocolSection(raw, "onebot11");
|
|
90
|
+
if (onebot11 !== void 0) out.onebot11 = onebot11;
|
|
91
|
+
const satori = parseProtocolSection(raw, "satori");
|
|
92
|
+
if (satori !== void 0) out.satori = satori;
|
|
93
|
+
const kurobot = parseProtocolSection(raw, "kurobot");
|
|
94
|
+
if (kurobot !== void 0) out.kurobot = kurobot;
|
|
95
|
+
}
|
|
96
|
+
/** 解析单个账号项(qq 必填;协议段缺省 = 不启用)。 */
|
|
97
|
+
function parseAccount(item) {
|
|
98
|
+
if (typeof item !== "object" || item === null) throw configError("主配置 accounts 元素必须是对象");
|
|
99
|
+
const raw = item;
|
|
100
|
+
const out = { qq: parseAccountQq(raw) };
|
|
101
|
+
applyAccountEnabled(out, raw["enabled"]);
|
|
102
|
+
applyProtocolSections(raw, out);
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* [log] 段落库净化:format 为 undefined(= 按 TTY 自动)时剔除该键,
|
|
107
|
+
* 避免 toml 回写(config list/apply 的 stringifyToml)遇到 undefined 值。
|
|
108
|
+
*/
|
|
109
|
+
function stripUndefinedFormat(log) {
|
|
110
|
+
const { format, ...rest } = log;
|
|
111
|
+
return format === void 0 ? rest : {
|
|
112
|
+
...rest,
|
|
113
|
+
format
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* [log] 段解析(kernel parseLogConfig 错误归一为 ConfigError):日志段非法同属
|
|
118
|
+
* 「配置未就绪」一族(exit 78);错误文案保持 kernel 原文(主配置 log.xxx ...)。
|
|
119
|
+
*/
|
|
120
|
+
function parseLogSection(input) {
|
|
121
|
+
try {
|
|
122
|
+
return parseLogConfig(input);
|
|
123
|
+
} catch (err) {
|
|
124
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
125
|
+
throw configError(`主配置 [log] 段非法: ${detail}`, { cause: err });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** 手写校验器:主配置 parse(不引入 zod)。全部校验错误为 ConfigError(exit 78 一族)。 */
|
|
129
|
+
function parseCliConfig(input) {
|
|
130
|
+
if (typeof input !== "object" || input === null) throw configError("主配置必须是对象");
|
|
131
|
+
const raw = input;
|
|
132
|
+
const dataDir = parseDataDir(raw);
|
|
133
|
+
const autoRestart = parseAutoRestart(raw);
|
|
134
|
+
const restartDelayMs = parseRestartDelayMs(raw);
|
|
135
|
+
const accounts = parseAccounts(raw);
|
|
136
|
+
const log = raw["log"] !== void 0 ? stripUndefinedFormat(parseLogSection(raw["log"])) : void 0;
|
|
137
|
+
return {
|
|
138
|
+
dataDir,
|
|
139
|
+
autoRestart,
|
|
140
|
+
restartDelayMs,
|
|
141
|
+
accounts,
|
|
142
|
+
...log !== void 0 ? { log } : {}
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
//#endregion
|
|
146
|
+
//#region src/config/inline.ts
|
|
147
|
+
/**
|
|
148
|
+
* 内联配置(NAPKETTO_CONFIG_JSON,2026-10-25 嵌入式宿主契约)。
|
|
149
|
+
*
|
|
150
|
+
* KuroBridge 等嵌入式宿主每次拉起前整体生成配置,经环境变量喂 JSON 文本
|
|
151
|
+
* (与 napuketto.toml 同构:parseCliConfig 直接吃 JSON.parse 产物),消除托管
|
|
152
|
+
* toml 文件本体。优先级 NAPKETTO_CONFIG_JSON > NAPKETTO_CONFIG > 缺省模板生成;
|
|
153
|
+
* 内联生效时不读 / 不写 / 不校验任何 toml 文件。Windows 单环境变量上限 32767
|
|
154
|
+
* 字符(约 32KB),嵌入式配置形状远小于该限(超限宿主退回文件形态)。
|
|
155
|
+
*
|
|
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 反向依赖本模块判内联来源)。
|
|
165
|
+
*/
|
|
166
|
+
/** 内联配置 env 键(读取为精确键访问;Windows 上 process.env 本身大小写不敏感)。 */
|
|
167
|
+
const INLINE_CONFIG_ENV = "NAPKETTO_CONFIG_JSON";
|
|
168
|
+
/**
|
|
169
|
+
* 读取内联配置文本(未设置 / 空串 / 纯空白 → undefined,回退文件形态)。
|
|
170
|
+
*/
|
|
171
|
+
function readInlineConfigText() {
|
|
172
|
+
const raw = process.env[INLINE_CONFIG_ENV];
|
|
173
|
+
if (raw === void 0 || raw.trim() === "") return;
|
|
174
|
+
return raw;
|
|
175
|
+
}
|
|
176
|
+
/** 内联是否生效(boot/装配链决定「不碰文件」的判定口径,与 readInlineConfigText 同源)。 */
|
|
177
|
+
function isInlineConfigActive() {
|
|
178
|
+
return readInlineConfigText() !== void 0;
|
|
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
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* 读内联配置文档(宽松口径:未设置 / 空串 / JSON 解析失败 / 非对象 → undefined)。
|
|
187
|
+
* 供日志段等「坏配置不阻塞启动」的消费方使用。
|
|
188
|
+
*/
|
|
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) {
|
|
205
|
+
let doc;
|
|
206
|
+
try {
|
|
207
|
+
doc = JSON.parse(text);
|
|
208
|
+
} catch (err) {
|
|
209
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
210
|
+
throw configError(`内联配置 JSON 解析失败: ${detail}`, { cause: err });
|
|
211
|
+
}
|
|
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));
|
|
222
|
+
}
|
|
223
|
+
//#endregion
|
|
13
224
|
//#region src/logger.ts
|
|
14
225
|
/**
|
|
15
226
|
* cli 进程级 logger(ADR-007 日志规范,2026-08-07 统一改造;2026-10-25 日志可配置化)。
|
|
@@ -27,13 +238,15 @@ import { access, readFile, writeFile } from "node:fs/promises";
|
|
|
27
238
|
let cachedConfig = null;
|
|
28
239
|
/** 解析配置时用的数据根([log.file] 相对路径展开基准)。 */
|
|
29
240
|
let cachedDataRoot = resolveDataRoot();
|
|
30
|
-
/**
|
|
31
|
-
*
|
|
241
|
+
/** 同步解析日志配置(内联 > toml 文件的 [log] 段 + env 覆盖)。损坏/缺失配置回退缺省
|
|
242
|
+
* (不阻塞启动:配置的严格校验由 loadCliConfig 主路径负责报错)。内联生效时不读
|
|
243
|
+
* 任何 toml 文件(嵌入式契约,2026-10-25)。 */
|
|
32
244
|
function resolveCliLogConfig(dataDir) {
|
|
33
245
|
if (cachedConfig !== null) return cachedConfig;
|
|
34
246
|
cachedDataRoot = resolveDataRoot(dataDir);
|
|
35
247
|
let section;
|
|
36
|
-
|
|
248
|
+
if (isInlineConfigActive()) section = readInlineConfigSection("log");
|
|
249
|
+
else try {
|
|
37
250
|
const configPath = resolveConfigPath({ dataRoot: cachedDataRoot });
|
|
38
251
|
section = parseToml(readFileSync(configPath, "utf8"))["log"];
|
|
39
252
|
} catch {
|
|
@@ -115,309 +328,15 @@ var LazyCliLogger = class {
|
|
|
115
328
|
/** cli 进程日志(懒构造,配置见 resolveCliLogConfig)。 */
|
|
116
329
|
const logger = new LazyCliLogger();
|
|
117
330
|
//#endregion
|
|
118
|
-
//#region src/
|
|
119
|
-
/**
|
|
120
|
-
* runtime-state.ts:账号运行时状态文件 + 进程控制原语(2026-09-08 T8)。
|
|
121
|
-
*
|
|
122
|
-
* 跨进程通信选型(决策记录):现有 IPC 为 stdio JSON 行协议(NAPUTO_IPC=1,
|
|
123
|
-
* koishi 插件专用),supervisor 子进程不在此模式;引入独立通道(socket/pipe)
|
|
124
|
-
* 复杂度高。采用 **PID 状态文件**:supervisor/单账号 boot 启动时把进程信息写
|
|
125
|
-
* `<数据根>/<uin>/runtime.json`,supervisor 自身写 `<数据根>/supervisor.json`;
|
|
126
|
-
* `napuketto status/stop/restart` 读文件 + liveness 检测 + 树杀(win32
|
|
127
|
-
* taskkill /T /F,杀 boot 进程树连带 self-host 孙进程)+ detached 重启。
|
|
128
|
-
*/
|
|
129
|
-
/** runtime.json 文件名。 */
|
|
130
|
-
const RUNTIME_FILE = "runtime.json";
|
|
131
|
-
/** supervisor.json 文件名。 */
|
|
132
|
-
const SUPERVISOR_FILE = "supervisor.json";
|
|
133
|
-
/** 账号状态文件路径。 */
|
|
134
|
-
function runtimeStatePath(dataRoot, uin) {
|
|
135
|
-
return join(dataRoot, uin, RUNTIME_FILE);
|
|
136
|
-
}
|
|
137
|
-
/** supervisor 状态文件路径。 */
|
|
138
|
-
function supervisorStatePath(dataRoot) {
|
|
139
|
-
return join(dataRoot, SUPERVISOR_FILE);
|
|
140
|
-
}
|
|
141
|
-
/** 写账号运行时状态(原子覆盖)。 */
|
|
142
|
-
function writeAccountRuntime(dataRoot, state) {
|
|
143
|
-
const path = runtimeStatePath(dataRoot, state.uin);
|
|
144
|
-
mkdirSync(join(path, ".."), { recursive: true });
|
|
145
|
-
writeFileSync(path, `${JSON.stringify(state, null, 2)}\n`, "utf8");
|
|
146
|
-
}
|
|
147
|
-
/** 读账号运行时状态(缺失/损坏返回 null)。 */
|
|
148
|
-
function readAccountRuntime(dataRoot, uin) {
|
|
149
|
-
return readJson(runtimeStatePath(dataRoot, uin));
|
|
150
|
-
}
|
|
151
|
-
/** 写 supervisor 运行时状态。 */
|
|
152
|
-
function writeSupervisorRuntime(dataRoot, state) {
|
|
153
|
-
writeFileSync(supervisorStatePath(dataRoot), `${JSON.stringify(state, null, 2)}\n`, "utf8");
|
|
154
|
-
}
|
|
155
|
-
/** 读 supervisor 运行时状态(缺失返回 null)。 */
|
|
156
|
-
function readSupervisorRuntime(dataRoot) {
|
|
157
|
-
return readJson(supervisorStatePath(dataRoot));
|
|
158
|
-
}
|
|
159
|
-
/** 读 JSON 文件(缺失/解析失败返回 null)。 */
|
|
160
|
-
function readJson(path) {
|
|
161
|
-
try {
|
|
162
|
-
return JSON.parse(readFileSync(path, "utf8"));
|
|
163
|
-
} catch {
|
|
164
|
-
return null;
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
/** 列出数据根下全部账号运行时状态(扫一级目录 runtime.json)。 */
|
|
168
|
-
function listAccountRuntimes(dataRoot) {
|
|
169
|
-
let entries = [];
|
|
170
|
-
try {
|
|
171
|
-
entries = readdirSync(dataRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
|
|
172
|
-
} catch {
|
|
173
|
-
return [];
|
|
174
|
-
}
|
|
175
|
-
const out = [];
|
|
176
|
-
for (const uin of entries) {
|
|
177
|
-
const state = readAccountRuntime(dataRoot, uin);
|
|
178
|
-
if (state !== null) out.push(state);
|
|
179
|
-
}
|
|
180
|
-
return out;
|
|
181
|
-
}
|
|
182
|
-
/** pid 存活检测(signal 0;EPERM 视为存活——进程存在但无权限)。 */
|
|
183
|
-
function isPidAlive(pid) {
|
|
184
|
-
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
185
|
-
try {
|
|
186
|
-
process.kill(pid, 0);
|
|
187
|
-
return true;
|
|
188
|
-
} catch (err) {
|
|
189
|
-
return err.code === "EPERM";
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
/** 树杀命令构造(win32:taskkill /T /F 连孙进程;posix:kill 信号)。 */
|
|
193
|
-
function killProcessTree(pid) {
|
|
194
|
-
if (process.platform === "win32") {
|
|
195
|
-
spawn("taskkill", [
|
|
196
|
-
"/PID",
|
|
197
|
-
String(pid),
|
|
198
|
-
"/T",
|
|
199
|
-
"/F"
|
|
200
|
-
], { stdio: "ignore" });
|
|
201
|
-
return;
|
|
202
|
-
}
|
|
203
|
-
try {
|
|
204
|
-
process.kill(pid, "SIGTERM");
|
|
205
|
-
} catch {}
|
|
206
|
-
}
|
|
207
|
-
/** detached 拉起 node 进程(restart 用;立即返回不等待)。 */
|
|
208
|
-
function spawnDetached(args, cwd) {
|
|
209
|
-
const child = spawn(process.execPath, args, {
|
|
210
|
-
detached: true,
|
|
211
|
-
stdio: "ignore",
|
|
212
|
-
...cwd !== void 0 ? { cwd } : {}
|
|
213
|
-
});
|
|
214
|
-
child.unref();
|
|
215
|
-
return child;
|
|
216
|
-
}
|
|
217
|
-
/** 聚合各账号状态(liveness 修正:文件 running 但 pid 已死 → not running)。 */
|
|
218
|
-
function aggregateStatus(runtimes, aliveFn = isPidAlive) {
|
|
219
|
-
return runtimes.map((r) => ({
|
|
220
|
-
uin: r.uin,
|
|
221
|
-
pid: r.pid,
|
|
222
|
-
alive: r.status === "running" ? aliveFn(r.pid) : false,
|
|
223
|
-
kind: r.kind,
|
|
224
|
-
startedAt: r.startedAt,
|
|
225
|
-
restartCount: r.restartCount ?? 0,
|
|
226
|
-
exitCode: r.exitCode
|
|
227
|
-
}));
|
|
228
|
-
}
|
|
229
|
-
//#endregion
|
|
230
|
-
//#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
|
-
/** 解析 workspace 包的 dist 入口(ESM 解析:包是 ESM-only,exports 无 require 条件)。 */
|
|
248
|
-
async function packageEntry(pkg) {
|
|
249
|
-
const url = await import.meta.resolve(pkg);
|
|
250
|
-
return fileURLToPath(url);
|
|
251
|
-
}
|
|
252
|
-
/** QR 透出标记行前缀(loader bootstrap-core 非 IPC 模式输出,cli 解析终端渲染)。 */
|
|
253
|
-
const QR_LINE_PREFIX = "NAPUTO_QR ";
|
|
254
|
-
/** 优雅停等待上限(毫秒):超时 kill 兜底(Windows 下为硬杀)。 */
|
|
255
|
-
const GRACEFUL_STOP_TIMEOUT_MS = 1e4;
|
|
331
|
+
//#region src/config/template.ts
|
|
256
332
|
/**
|
|
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 优化)。
|
|
333
|
+
* 配置模板(TOML 注释版,原 config-cmds.ts 拆分,2026-08-08 FTA 优化)。
|
|
413
334
|
* `config init` 与首次启动(loadCliConfig)缺失时生成。
|
|
414
335
|
*
|
|
415
336
|
* 2026-08-08 结构拍板:**一个 QQ 账号一个 [[accounts]] 段,协议与通信配置嵌在
|
|
416
337
|
* 账号内**([accounts.onebot11] / [accounts.satori]);账号必填(至少一个)。
|
|
417
338
|
* dataDir 不再写死(缺省 = 项目根/.napuketto,跨平台),模板保持可移植。
|
|
418
339
|
*/
|
|
419
|
-
/** 保留占位 QQ 号(模板默认值):必须替换为真实 QQ 号,否则启动校验报错。 */
|
|
420
|
-
const RESERVED_PLACEHOLDER_QINS = ["123456", "654321"];
|
|
421
340
|
function configTemplate() {
|
|
422
341
|
return `# ============================================================
|
|
423
342
|
# NapukettoQQ 全局配置文件
|
|
@@ -547,125 +466,31 @@ port = 3001
|
|
|
547
466
|
# ------------------------------------------------------------
|
|
548
467
|
# KuroBot 群服互通(kurobridge-ws 客户端,MVP-3)
|
|
549
468
|
# ------------------------------------------------------------
|
|
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
|
|
567
|
-
/**
|
|
568
|
-
* 主配置类型与手写校验器(从 config-cmds.ts 拆分,2026-08-08 FTA 优化)
|
|
569
|
-
*
|
|
570
|
-
* 主配置 parse(不引入 zod):数据根 / 自动重启 / 重启延迟 / 账号列表。
|
|
571
|
-
* 2026-08-08 结构拍板:**一个 QQ 账号一个 [[accounts]] 段,协议与通信配置嵌在
|
|
572
|
-
* 账号内**([accounts.onebot11] / [accounts.satori]);账号必填(至少一个)。
|
|
573
|
-
* 协议段为宽松对象,装配时由对应协议包的 zod schema 严格校验。
|
|
574
|
-
*/
|
|
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;
|
|
587
|
-
}
|
|
588
|
-
/**
|
|
589
|
-
* 解析 dataDir(缺省用当前解析的数据根 = 项目根/.napuketto)。
|
|
590
|
-
* 支持绝对路径、"~/" 前缀(用户主目录)、相对路径(相对启动目录),
|
|
591
|
-
* 消费端 resolveDataRoot 统一展开为绝对路径。
|
|
592
|
-
*/
|
|
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"];
|
|
597
|
-
}
|
|
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"];
|
|
603
|
-
}
|
|
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"];
|
|
609
|
-
}
|
|
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;
|
|
617
|
-
}
|
|
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;
|
|
629
|
-
}
|
|
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
|
-
}
|
|
639
|
-
/**
|
|
640
|
-
* [log] 段落库净化:format 为 undefined(= 按 TTY 自动)时剔除该键,
|
|
641
|
-
* 避免 toml 回写(config list/apply 的 stringifyToml)遇到 undefined 值。
|
|
642
|
-
*/
|
|
643
|
-
function stripUndefinedFormat(log) {
|
|
644
|
-
const { format, ...rest } = log;
|
|
645
|
-
return format === void 0 ? rest : {
|
|
646
|
-
...rest,
|
|
647
|
-
format
|
|
648
|
-
};
|
|
649
|
-
}
|
|
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;
|
|
659
|
-
return {
|
|
660
|
-
dataDir,
|
|
661
|
-
autoRestart,
|
|
662
|
-
restartDelayMs,
|
|
663
|
-
accounts,
|
|
664
|
-
...log !== void 0 ? { log } : {}
|
|
665
|
-
};
|
|
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
|
+
`;
|
|
666
483
|
}
|
|
667
484
|
//#endregion
|
|
668
|
-
//#region src/config
|
|
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
|
+
*/
|
|
669
494
|
/** 主配置默认值(dataRoot 为当前解析的数据根 = 项目根/.napuketto)。 */
|
|
670
495
|
function defaultCliConfig(dataRoot) {
|
|
671
496
|
return {
|
|
@@ -696,12 +521,58 @@ var CliConfigStore = class extends ConfigBase {
|
|
|
696
521
|
});
|
|
697
522
|
}
|
|
698
523
|
};
|
|
699
|
-
/**
|
|
524
|
+
/** 读取主配置(缺失自动落模板;loadCliConfigWithSource 文件分支内部用)。 */
|
|
700
525
|
async function loadCliConfig(dataRoot) {
|
|
701
526
|
const store = new CliConfigStore(dataRoot);
|
|
702
527
|
await ensureConfigTemplate(store.path);
|
|
703
528
|
return await store.load();
|
|
704
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
|
+
}
|
|
547
|
+
/** 「配置来源」日志每进程至多一行(autoStart 与 runSupervisor 各加载一次)。 */
|
|
548
|
+
let sourceLogged = false;
|
|
549
|
+
/**
|
|
550
|
+
* 加载主配置(内联优先,2026-10-25 嵌入式契约):
|
|
551
|
+
* NAPKETTO_CONFIG_JSON 非空 → 内存文档校验(不读 / 不写 / 不校验任何 toml
|
|
552
|
+
* 文件),打一行来源日志;否则现行文件链路(缺失自动落模板)。校验失败两形态
|
|
553
|
+
* 同为 ConfigError(exit 78),文案区别只在来源标注。
|
|
554
|
+
*/
|
|
555
|
+
async function loadCliConfigWithSource(opts = {}) {
|
|
556
|
+
const resolved = resolveCliConfigSource(opts);
|
|
557
|
+
if (resolved.source === "inline") {
|
|
558
|
+
const config = parseInlineConfig(resolved.text);
|
|
559
|
+
if (!sourceLogged) {
|
|
560
|
+
sourceLogged = true;
|
|
561
|
+
logger.info("配置来源: inline(NAPKETTO_CONFIG_JSON)");
|
|
562
|
+
}
|
|
563
|
+
return {
|
|
564
|
+
config,
|
|
565
|
+
source: "inline"
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
return {
|
|
569
|
+
config: await loadCliConfig(resolved.dataRoot),
|
|
570
|
+
source: "file",
|
|
571
|
+
path: resolved.path
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
//#endregion
|
|
575
|
+
//#region src/commands/config.ts
|
|
705
576
|
/** CliConfig → 普通对象(smol-toml stringify 入参)。 */
|
|
706
577
|
function toRecord(config) {
|
|
707
578
|
return config;
|
|
@@ -794,12 +665,175 @@ async function cmdConfigApply(file, opts) {
|
|
|
794
665
|
logger.info({ path: store.path }, "全局配置已更新");
|
|
795
666
|
process.stdout.write(`${stringifyToml(toRecord(next))}\n`);
|
|
796
667
|
}
|
|
668
|
+
/** 读取配置文件文本(validate 纯只读:ENOENT 不落模板,按「配置缺失」报 ConfigError)。 */
|
|
669
|
+
async function readConfigTextForValidate(path) {
|
|
670
|
+
try {
|
|
671
|
+
return await readFile(path, "utf8");
|
|
672
|
+
} catch (err) {
|
|
673
|
+
if (err.code === "ENOENT") throw configError(`配置文件不存在: ${path}`);
|
|
674
|
+
throw configError(`读取配置文件失败: ${path}`, { cause: err });
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
/**
|
|
678
|
+
* 校验配置文件(与运行时同构:ConfigBase.parseText 反序列化 + 校验,报错文案
|
|
679
|
+
* 含路径且与 loadCliConfig 主路径逐字一致;格式按扩展名推断,同 ConfigBase)。
|
|
680
|
+
*/
|
|
681
|
+
async function validateConfigFile(path, dataRoot) {
|
|
682
|
+
const raw = await readConfigTextForValidate(path);
|
|
683
|
+
new ConfigBase({
|
|
684
|
+
path,
|
|
685
|
+
schema: { parse: parseCliConfig },
|
|
686
|
+
defaults: defaultCliConfig(dataRoot)
|
|
687
|
+
}).parseText(raw);
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* config validate:校验配置(exit 0 = 合法;exit 78 = 校验失败,ConfigError 一族;
|
|
691
|
+
* --config 与 --config-json 同给 = 用法错误,exit 1)。纯只读——文件形态不落模板
|
|
692
|
+
* (无参形态文件缺失按配置缺失报 78),不触碰数据目录。
|
|
693
|
+
*/
|
|
694
|
+
async function cmdConfigValidate(opts) {
|
|
695
|
+
const { configPath, configJson } = opts;
|
|
696
|
+
if (configPath !== void 0 && configJson !== void 0) throw kernelError("config validate:--config 与 --config-json 只能二选一", "INVALID_PARAM");
|
|
697
|
+
if (configJson !== void 0) {
|
|
698
|
+
parseInlineConfig(configJson);
|
|
699
|
+
return { source: "inline" };
|
|
700
|
+
}
|
|
701
|
+
if (configPath !== void 0) {
|
|
702
|
+
await validateConfigFile(configPath, resolveDataRoot(opts.dataDir));
|
|
703
|
+
return {
|
|
704
|
+
source: "file",
|
|
705
|
+
path: configPath
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
const resolved = resolveCliConfigSource(opts);
|
|
709
|
+
if (resolved.source === "inline") {
|
|
710
|
+
parseInlineConfig(resolved.text);
|
|
711
|
+
return { source: "inline" };
|
|
712
|
+
}
|
|
713
|
+
await validateConfigFile(resolved.path, resolved.dataRoot);
|
|
714
|
+
return {
|
|
715
|
+
source: "file",
|
|
716
|
+
path: resolved.path
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
//#endregion
|
|
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
|
+
}
|
|
797
831
|
//#endregion
|
|
798
|
-
//#region src/ops
|
|
832
|
+
//#region src/commands/ops.ts
|
|
799
833
|
/**
|
|
800
|
-
* ops
|
|
834
|
+
* ops.ts:status / stop / restart 运维命令实现(2026-09-08 T8)。
|
|
801
835
|
*
|
|
802
|
-
* 数据源:runtime
|
|
836
|
+
* 数据源:runtime/state 状态文件(supervisor/单账号 boot 写入)+ liveness 检测。
|
|
803
837
|
* stop/restart 语义(2026-10-25 优雅化):
|
|
804
838
|
* - stop -q <uin>:写单账号停止哨兵 → 等该账号进程链优雅退出 → 超时树杀兜底。
|
|
805
839
|
* ⚠️ supervisor 在跑且 autoRestart 时账号会被自动拉起——提示用户先 `napuketto stop`。
|
|
@@ -879,57 +913,294 @@ async function stopSingleAccount(dataRoot, target) {
|
|
|
879
913
|
const supervisor = readSupervisorRuntime(dataRoot);
|
|
880
914
|
if (supervisor !== null) logger.warn({ supervisorPid: supervisor.pid }, "supervisor 仍在运行且 autoRestart 开启时会自动拉起该账号;如需彻底停止请执行 napuketto stop(停 supervisor)");
|
|
881
915
|
}
|
|
882
|
-
async function cmdStop(dataRoot, opts) {
|
|
883
|
-
const runtimes = listAccountRuntimes(dataRoot);
|
|
884
|
-
if (opts.qq !== void 0) {
|
|
885
|
-
const target = runtimes.find((r) => r.uin === opts.qq);
|
|
886
|
-
if (target === void 0) {
|
|
887
|
-
logger.error({ uin: opts.qq }, "账号无运行时状态(未启动过)");
|
|
888
|
-
process.exitCode = 1;
|
|
889
|
-
return;
|
|
890
|
-
}
|
|
891
|
-
await stopSingleAccount(dataRoot, target);
|
|
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;
|
|
892
1039
|
return;
|
|
893
1040
|
}
|
|
894
|
-
const supervisor = readSupervisorRuntime(dataRoot);
|
|
895
|
-
const supervisorPid = supervisor !== null && isPidAlive(supervisor.pid) ? supervisor.pid : 0;
|
|
896
|
-
if (supervisor !== null) {
|
|
897
|
-
logger.info({ pid: supervisor.pid }, "已发送停止请求(哨兵),等待 supervisor 退出");
|
|
898
|
-
writeStopSentinel(dataRoot, "all");
|
|
899
|
-
const alive = await waitForPidsExit([supervisorPid]);
|
|
900
|
-
for (const pid of alive) {
|
|
901
|
-
logger.warn({ pid }, "supervisor 限时内未退出,树杀兜底");
|
|
902
|
-
killProcessTree(pid);
|
|
903
|
-
}
|
|
904
|
-
} else logger.warn("supervisor 未运行(无状态文件)");
|
|
905
|
-
const stragglers = await waitForPidsExit(runtimes.map((r) => r.pid));
|
|
906
|
-
for (const runtime of runtimes) if (stragglers.includes(runtime.pid)) stopAccount(runtime);
|
|
907
|
-
removeStopSentinel(dataRoot);
|
|
908
1041
|
}
|
|
909
|
-
/**
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
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
|
+
});
|
|
1188
|
+
}
|
|
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));
|
|
930
1201
|
}
|
|
931
1202
|
//#endregion
|
|
932
|
-
//#region src/supervisor.ts
|
|
1203
|
+
//#region src/runtime/supervisor.ts
|
|
933
1204
|
/**
|
|
934
1205
|
* supervisor:多账号子进程编排(P6,2026-08-05;2026-08-07 自建宿主唯一)
|
|
935
1206
|
*
|
|
@@ -940,8 +1211,6 @@ async function cmdRestart(dataRoot, opts) {
|
|
|
940
1211
|
* - 守护:账号异常退出且 autoRestart → 延迟重启
|
|
941
1212
|
* - 信号转发:SIGINT/SIGTERM → 停止全部子进程 → 父进程退出
|
|
942
1213
|
*/
|
|
943
|
-
/** 默认重启延迟(毫秒)。 */
|
|
944
|
-
const DEFAULT_RESTART_DELAY_MS = 2e3;
|
|
945
1214
|
/** 退出轮询间隔(毫秒)。 */
|
|
946
1215
|
const EXIT_POLL_MS = 100;
|
|
947
1216
|
/** 子进程优雅退出时限(毫秒):哨兵/信号后子进程自行停止,超时强杀兜底。 */
|
|
@@ -1014,6 +1283,22 @@ function startAccount(ctx, acct) {
|
|
|
1014
1283
|
code,
|
|
1015
1284
|
signal: signal ?? "none"
|
|
1016
1285
|
}, "账号退出");
|
|
1286
|
+
if (code === EXIT_CONFIG_INVALID) {
|
|
1287
|
+
logger.error({
|
|
1288
|
+
qq: acct.qq,
|
|
1289
|
+
code
|
|
1290
|
+
}, "账号因配置校验失败退出(78),不自动重启");
|
|
1291
|
+
writeAccountRuntime(ctx.dataRoot, {
|
|
1292
|
+
uin: acct.qq,
|
|
1293
|
+
pid: child.pid ?? 0,
|
|
1294
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1295
|
+
kind: "supervisor-child",
|
|
1296
|
+
status: "exited",
|
|
1297
|
+
exitCode: code,
|
|
1298
|
+
restartCount
|
|
1299
|
+
});
|
|
1300
|
+
return;
|
|
1301
|
+
}
|
|
1017
1302
|
if (!ctx.isStopping() && ctx.autoRestart) {
|
|
1018
1303
|
ctx.restartCounts.set(acct.qq, restartCount + 1);
|
|
1019
1304
|
setTimeout(() => {
|
|
@@ -1064,7 +1349,7 @@ function stopAll(ctx) {
|
|
|
1064
1349
|
/** 运行 supervisor(多账号编排)。 */
|
|
1065
1350
|
async function runSupervisor(opts = {}) {
|
|
1066
1351
|
const dataRoot = resolveDataRoot(opts.dataDir);
|
|
1067
|
-
const config = await
|
|
1352
|
+
const { config } = await loadCliConfigWithSource(opts.dataDir !== void 0 ? { dataDir: opts.dataDir } : {});
|
|
1068
1353
|
const accounts = resolveAccounts(opts, config);
|
|
1069
1354
|
if (accounts.length === 0) {
|
|
1070
1355
|
logger.warn("supervisor:没有启用的账号(主配置 accounts 为空或全部禁用)");
|
|
@@ -1109,18 +1394,103 @@ async function runSupervisor(opts = {}) {
|
|
|
1109
1394
|
await new Promise(() => {});
|
|
1110
1395
|
}
|
|
1111
1396
|
//#endregion
|
|
1112
|
-
//#region src/
|
|
1397
|
+
//#region src/commands/start.ts
|
|
1113
1398
|
/**
|
|
1114
|
-
*
|
|
1115
|
-
* 2026-08-08 配置结构拍板:账号必填,协议配置嵌在账号内)
|
|
1399
|
+
* 默认动作(无子命令)用例:-q 单账号 / 多 -q supervisor / 无 -q 读配置拉起全部账号。
|
|
1116
1400
|
*
|
|
1117
|
-
* commander
|
|
1118
|
-
*
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1401
|
+
* 从 index.ts 拆出(2026-10-25 模块收拢):这里只做编排,不 import commander;
|
|
1402
|
+
* 参数解析、帮助文案与退出码收敛在 cli/program.ts。
|
|
1403
|
+
*/
|
|
1404
|
+
/** 构造可选 dataDir 参数(exactOptionalPropertyTypes 不允许显式 undefined)。 */
|
|
1405
|
+
function withDataDir(dataDir) {
|
|
1406
|
+
if (dataDir === void 0) return {};
|
|
1407
|
+
return { dataDir };
|
|
1408
|
+
}
|
|
1409
|
+
/** 构造可选 stubDir 参数(同 withDataDir)。 */
|
|
1410
|
+
function withStubDir(stubDir) {
|
|
1411
|
+
if (stubDir === void 0) return {};
|
|
1412
|
+
return { stubDir };
|
|
1413
|
+
}
|
|
1414
|
+
/** 构造可选 qqPath 参数(同 withDataDir)。 */
|
|
1415
|
+
function withQqPath(qqPath) {
|
|
1416
|
+
if (qqPath === void 0) return {};
|
|
1417
|
+
return { qqPath };
|
|
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(运行时崩溃,现状不变)。
|
|
1122
1469
|
*
|
|
1123
|
-
*
|
|
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/。禁止在此写业务逻辑。
|
|
1124
1494
|
*/
|
|
1125
1495
|
/** commander collect:累积 -q 多值。 */
|
|
1126
1496
|
function collectQq(value, prev) {
|
|
@@ -1136,23 +1506,10 @@ const BANNER = [
|
|
|
1136
1506
|
"/_/ |_/\\__,_/ .___/\\__,_/_/|_|\\___/\\__/\\__/\\____/\\___\\_\\___\\_\\ ",
|
|
1137
1507
|
" /_/ "
|
|
1138
1508
|
].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
|
-
/** 构造可选 dataDir 参数(exactOptionalPropertyTypes 不允许显式 undefined)。 */
|
|
1149
|
-
function withDataDir(dataDir) {
|
|
1150
|
-
if (dataDir === void 0) return {};
|
|
1151
|
-
return { dataDir };
|
|
1152
|
-
}
|
|
1153
1509
|
/** 读主命令已解析的 data-dir(-d 定义在主命令,子命令经此共享)。 */
|
|
1154
1510
|
function rootDataDir(program) {
|
|
1155
|
-
|
|
1511
|
+
const { dataDir } = program.opts();
|
|
1512
|
+
return dataDir === void 0 ? {} : { dataDir };
|
|
1156
1513
|
}
|
|
1157
1514
|
/** 注册 config 子命令(init/list/apply,P6;-d 复用主命令 option)。 */
|
|
1158
1515
|
function registerConfigCommands(program) {
|
|
@@ -1161,103 +1518,69 @@ function registerConfigCommands(program) {
|
|
|
1161
1518
|
try {
|
|
1162
1519
|
await cmdConfigInit(rootDataDir(program));
|
|
1163
1520
|
} catch (err) {
|
|
1164
|
-
|
|
1165
|
-
process.exitCode = 1;
|
|
1521
|
+
handleActionError(err);
|
|
1166
1522
|
}
|
|
1167
1523
|
});
|
|
1168
1524
|
configCmd.command("list").description("列出全局配置与账号配置").action(async () => {
|
|
1169
1525
|
try {
|
|
1170
1526
|
await cmdConfigList(rootDataDir(program));
|
|
1171
1527
|
} catch (err) {
|
|
1172
|
-
|
|
1173
|
-
process.exitCode = 1;
|
|
1528
|
+
handleActionError(err);
|
|
1174
1529
|
}
|
|
1175
1530
|
});
|
|
1176
1531
|
configCmd.command("apply <file>").description("应用外部配置(TOML/JSON,校验后写回全局配置)").action(async (file) => {
|
|
1177
1532
|
try {
|
|
1178
1533
|
await cmdConfigApply(file, rootDataDir(program));
|
|
1179
1534
|
} catch (err) {
|
|
1180
|
-
|
|
1181
|
-
process.exitCode = 1;
|
|
1535
|
+
handleActionError(err);
|
|
1182
1536
|
}
|
|
1183
1537
|
});
|
|
1184
|
-
|
|
1185
|
-
/** 注册 supervisor 子命令(读主配置 accounts 批量拉起,P6;-d 复用主命令 option)。 */
|
|
1186
|
-
function registerSupervisorCommand(program) {
|
|
1187
|
-
program.command("supervisor").description("多账号编排(读全局配置 accounts 拉起子进程)").action(async () => {
|
|
1538
|
+
configCmd.command("validate").description("校验配置(--config <path> / --config-json <json> 二选一;无参 = 校验生效配置)").option("--config <path>", "待校验配置文件路径(.toml/.json 按扩展名解析)").option("--config-json <json>", "待校验内联配置 JSON 文本").action(async (opts) => {
|
|
1188
1539
|
try {
|
|
1189
|
-
await
|
|
1540
|
+
const result = await cmdConfigValidate({
|
|
1541
|
+
configPath: opts.config,
|
|
1542
|
+
configJson: opts.configJson,
|
|
1543
|
+
...rootDataDir(program)
|
|
1544
|
+
});
|
|
1545
|
+
process.stdout.write(result.source === "inline" ? "配置校验通过(来源: inline)\n" : `配置校验通过(来源: file ${result.path})\n`);
|
|
1190
1546
|
} catch (err) {
|
|
1191
|
-
|
|
1192
|
-
process.exitCode = 1;
|
|
1547
|
+
handleActionError(err);
|
|
1193
1548
|
}
|
|
1194
1549
|
});
|
|
1195
1550
|
}
|
|
1196
|
-
/**
|
|
1197
|
-
function
|
|
1198
|
-
program.command("
|
|
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) => {
|
|
1551
|
+
/** 注册 supervisor 子命令(读主配置 accounts 批量拉起,P6;-d 复用主命令 option)。 */
|
|
1552
|
+
function registerSupervisorCommand(program) {
|
|
1553
|
+
program.command("supervisor").description("多账号编排(读全局配置 accounts 拉起子进程)").action(async () => {
|
|
1207
1554
|
try {
|
|
1208
|
-
await
|
|
1555
|
+
await runSupervisorCommand(rootDataDir(program));
|
|
1209
1556
|
} catch (err) {
|
|
1210
|
-
|
|
1211
|
-
process.exitCode = 1;
|
|
1557
|
+
handleActionError(err);
|
|
1212
1558
|
}
|
|
1213
1559
|
});
|
|
1214
|
-
|
|
1560
|
+
}
|
|
1561
|
+
/** 运维子命令公共壳:解析数据根 + 可选 -q 参数,统一 handleActionError 出口。 */
|
|
1562
|
+
function opsAction(program, run) {
|
|
1563
|
+
return async (opts) => {
|
|
1215
1564
|
try {
|
|
1216
|
-
await
|
|
1565
|
+
await run(resolveDataRoot(rootDataDir(program).dataDir), opts.qq !== void 0 ? { qq: opts.qq } : {});
|
|
1217
1566
|
} catch (err) {
|
|
1218
|
-
|
|
1219
|
-
process.exitCode = 1;
|
|
1567
|
+
handleActionError(err);
|
|
1220
1568
|
}
|
|
1221
|
-
}
|
|
1222
|
-
}
|
|
1223
|
-
/** 单账号启动分支(-q 单值;构造 bootOptions 后走 runSingleAccount)。 */
|
|
1224
|
-
async function runSingleAccountBranch(opts, qqs) {
|
|
1225
|
-
const [only] = qqs;
|
|
1226
|
-
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);
|
|
1569
|
+
};
|
|
1232
1570
|
}
|
|
1233
|
-
/**
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
...opts.dataDir !== void 0 ? { dataDir: opts.dataDir } : {},
|
|
1239
|
-
...opts.stubDir !== void 0 ? { stubDir: opts.stubDir } : {}
|
|
1240
|
-
});
|
|
1571
|
+
/** 注册运维子命令(status/stop/restart,2026-09-08 T8;-q 复用主命令 option)。 */
|
|
1572
|
+
function registerOpsCommands(program) {
|
|
1573
|
+
program.command("status").description("查看各账号运行状态(读 runtime.json + 进程存活检测)").option("-q, --qq <uin>", "只看指定账号").action(opsAction(program, (dataRoot, arg) => cmdStatus(dataRoot, arg)));
|
|
1574
|
+
program.command("stop").description("停止账号进程树(无 -q 停 supervisor 全部;-q 停单账号,supervisor 守护时会自动拉起)").option("-q, --qq <uin>", "目标账号(缺省停 supervisor + 全部账号)").action(opsAction(program, (dataRoot, arg) => cmdStop(dataRoot, arg)));
|
|
1575
|
+
program.command("restart").description("重启账号(无 -q 重启 supervisor 全量;-q 重启单账号;detached 拉起)").option("-q, --qq <uin>", "目标账号(缺省重启 supervisor 全量)").action(opsAction(program, (dataRoot, arg) => cmdRestart(dataRoot, arg)));
|
|
1241
1576
|
}
|
|
1242
1577
|
/** 注册主命令 action(-q 单账号 / 多 -q supervisor / 无 -q 读配置 supervisor 拉起)。 */
|
|
1243
1578
|
function registerMainAction(program) {
|
|
1244
1579
|
program.action(async (opts) => {
|
|
1245
1580
|
try {
|
|
1246
|
-
|
|
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
|
-
}
|
|
1581
|
+
await dispatchMainAction(opts);
|
|
1258
1582
|
} catch (err) {
|
|
1259
|
-
|
|
1260
|
-
process.exitCode = 1;
|
|
1583
|
+
handleActionError(err);
|
|
1261
1584
|
}
|
|
1262
1585
|
});
|
|
1263
1586
|
}
|
|
@@ -1275,6 +1598,25 @@ function main() {
|
|
|
1275
1598
|
registerMainAction(program);
|
|
1276
1599
|
program.parse(process.argv);
|
|
1277
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
|
+
*/
|
|
1278
1620
|
main();
|
|
1279
1621
|
//#endregion
|
|
1280
1622
|
export {};
|