koishi-plugin-newapi-status 0.0.0-stage → 0.2.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/LICENSE +31 -0
- package/lib/api/index.d.ts +10 -0
- package/lib/api/index.js +26 -0
- package/lib/api/models.d.ts +9 -0
- package/lib/api/models.js +20 -0
- package/lib/api/network.d.ts +20 -0
- package/lib/api/network.js +42 -0
- package/lib/api/notice.d.ts +8 -0
- package/lib/api/notice.js +17 -0
- package/lib/api/perf.d.ts +31 -0
- package/lib/api/perf.js +52 -0
- package/lib/api/pricing.d.ts +9 -0
- package/lib/api/pricing.js +24 -0
- package/lib/api/ratio.d.ts +10 -0
- package/lib/api/ratio.js +29 -0
- package/lib/api/relay.d.ts +43 -0
- package/lib/api/relay.js +178 -0
- package/lib/api/shared.d.ts +60 -0
- package/lib/api/shared.js +123 -0
- package/lib/api/status.d.ts +12 -0
- package/lib/api/status.js +13 -0
- package/lib/api/uptime.d.ts +9 -0
- package/lib/api/uptime.js +18 -0
- package/lib/config.d.ts +59 -0
- package/lib/config.js +112 -0
- package/lib/format.d.ts +76 -0
- package/lib/format.js +242 -0
- package/lib/index.d.ts +11 -0
- package/lib/index.js +567 -0
- package/lib/log.d.ts +39 -0
- package/lib/log.js +39 -0
- package/lib/monitor.d.ts +39 -0
- package/lib/monitor.js +186 -0
- package/lib/render/ChannelCard.d.ts +6 -0
- package/lib/render/ChannelCard.js +12 -0
- package/lib/render/StatusCard.d.ts +6 -0
- package/lib/render/StatusCard.js +18 -0
- package/lib/render/index.d.ts +12 -0
- package/lib/render/index.js +71 -0
- package/lib/render/styles.d.ts +23 -0
- package/lib/render/styles.js +192 -0
- package/lib/text.d.ts +10 -0
- package/lib/text.js +107 -0
- package/lib/types.d.ts +201 -0
- package/lib/types.js +6 -0
- package/lib/view.d.ts +149 -0
- package/lib/view.js +360 -0
- package/package.json +73 -4
- package/readme.md +225 -0
- package/README.md +0 -3
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import type { Config as PluginConfig } from './config';
|
|
3
|
+
export declare const name = "newapi-status";
|
|
4
|
+
export declare const inject: {
|
|
5
|
+
required: string[];
|
|
6
|
+
optional: string[];
|
|
7
|
+
};
|
|
8
|
+
export declare const Config: import("schemastery")<PluginConfig>;
|
|
9
|
+
/** 把用户填的前缀归一化成合法指令名:去斜杠、去 .* 后缀、去尾部点。支持逗号分隔多个前缀。 */
|
|
10
|
+
export declare function normalizePrefix(input?: string): string[];
|
|
11
|
+
export declare function apply(ctx: Context, config: PluginConfig): void;
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,567 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Config = exports.inject = exports.name = void 0;
|
|
4
|
+
exports.normalizePrefix = normalizePrefix;
|
|
5
|
+
exports.apply = apply;
|
|
6
|
+
const koishi_1 = require("koishi");
|
|
7
|
+
const config_1 = require("./config");
|
|
8
|
+
const api_1 = require("./api");
|
|
9
|
+
const format_1 = require("./format");
|
|
10
|
+
const log_1 = require("./log");
|
|
11
|
+
const monitor_1 = require("./monitor");
|
|
12
|
+
const render_1 = require("./render");
|
|
13
|
+
const text_1 = require("./text");
|
|
14
|
+
const view_1 = require("./view");
|
|
15
|
+
exports.name = 'newapi-status';
|
|
16
|
+
exports.inject = { required: ['http'], optional: ['puppeteer'] };
|
|
17
|
+
exports.Config = config_1.Config;
|
|
18
|
+
const PLUGIN = 'koishi-plugin-newapi-status';
|
|
19
|
+
const PLUGIN_VERSION = '0.1.0';
|
|
20
|
+
/** 把用户填的前缀归一化成合法指令名:去斜杠、去 .* 后缀、去尾部点。支持逗号分隔多个前缀。 */
|
|
21
|
+
function normalizePrefix(input) {
|
|
22
|
+
const list = (input || 'newapi')
|
|
23
|
+
.split(/[,,\s]+/)
|
|
24
|
+
.map(raw => raw.trim().replace(/^\/+/, '').replace(/\.\*$/, '').replace(/[.\s]+$/, ''))
|
|
25
|
+
.filter(Boolean);
|
|
26
|
+
const unique = [...new Set(list)];
|
|
27
|
+
return unique.length ? unique : ['newapi'];
|
|
28
|
+
}
|
|
29
|
+
function maskKey(key) {
|
|
30
|
+
if (!key)
|
|
31
|
+
return '--';
|
|
32
|
+
if (key.length <= 8)
|
|
33
|
+
return key.slice(0, 2) + '***';
|
|
34
|
+
return key.slice(0, 3) + '***' + key.slice(-2);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* 指令清单:help 与各分组默认动作共用同一份,避免文案漂移。
|
|
38
|
+
* healthHours 必须传进来——文案里写死「1 小时」会和实际配置对不上。
|
|
39
|
+
*/
|
|
40
|
+
function commandList(prefix, healthHours = 1) {
|
|
41
|
+
return [
|
|
42
|
+
{ usage: `${prefix} help`, desc: '列出全部指令和用法' },
|
|
43
|
+
{ usage: `${prefix} status`, desc: '站点名、版本、运行时长、接口延迟、可访问性' },
|
|
44
|
+
{ usage: `${prefix} notice`, desc: '最新时间线与站内公告' },
|
|
45
|
+
{ usage: `${prefix} about`, desc: '关于本插件' },
|
|
46
|
+
{ usage: `${prefix} model search <关键词>`, desc: '模糊搜索模型名' },
|
|
47
|
+
{ usage: `${prefix} model list [供应商]`, desc: '站点可用的模型列表' },
|
|
48
|
+
{ usage: `${prefix} model status <模型> [-t 小时] [-g 分组]`, desc: '成功率、平均延迟、首 Token、TPS,附每小时成功率色块' },
|
|
49
|
+
{ usage: `${prefix} model health`, desc: `列出近 ${healthHours} 小时成功率高于阈值的模型及其分组` },
|
|
50
|
+
{ usage: `${prefix} group`, desc: '分组列表、每个分组的倍率和说明' },
|
|
51
|
+
{ usage: `${prefix} group ratio [模型]`, desc: '模型倍率和补全倍率' },
|
|
52
|
+
{ usage: `${prefix} group status [分组]`, desc: '分组状态,未指定分组时为全部' },
|
|
53
|
+
{ usage: `${prefix} group search <关键词>`, desc: '模糊搜索分组名' },
|
|
54
|
+
{ usage: `${prefix} network [名称]`, desc: '站点线路与 Uptime Kuma 监控项的在线状态' },
|
|
55
|
+
{ usage: `${prefix} test <模型> [预设keyId | sk-令牌]`, desc: '发一条最短对话请求,返回成功与否、总耗时、首 Token 耗时' },
|
|
56
|
+
{ usage: `${prefix} test list`, desc: '列出配置里预设的 keyId 与分组' },
|
|
57
|
+
];
|
|
58
|
+
}
|
|
59
|
+
/** 把多段输出拼成一个消息元素数组(图片元素是字符串形式的标记,需要归一化) */
|
|
60
|
+
function concat(...parts) {
|
|
61
|
+
return parts.flatMap(part => koishi_1.h.normalize(part));
|
|
62
|
+
}
|
|
63
|
+
function clampHours(value, fallback) {
|
|
64
|
+
const hours = Number(value);
|
|
65
|
+
if (!Number.isFinite(hours) || hours <= 0)
|
|
66
|
+
return Math.min(fallback || 24, api_1.MAX_PERF_HOURS);
|
|
67
|
+
return Math.min(Math.max(1, Math.floor(hours)), api_1.MAX_PERF_HOURS);
|
|
68
|
+
}
|
|
69
|
+
function apply(ctx, config) {
|
|
70
|
+
// 5 等级 logger(success/error/info/warn/debug),命名空间 newapi-status 注册给 Koishi
|
|
71
|
+
const logger = (0, log_1.createLogger)(ctx, config.logLevel);
|
|
72
|
+
const prefixes = normalizePrefix(config.commandPrefix);
|
|
73
|
+
const client = {
|
|
74
|
+
baseUrl: config.baseUrl,
|
|
75
|
+
token: config.accessToken?.trim() || undefined,
|
|
76
|
+
userId: Number(config.userId) > 0 ? Number(config.userId) : undefined,
|
|
77
|
+
timeout: config.timeout,
|
|
78
|
+
};
|
|
79
|
+
const renderOptions = { mode: config.render, enabled: true };
|
|
80
|
+
const secrets = () => [
|
|
81
|
+
config.accessToken,
|
|
82
|
+
config.monitor.apiKey,
|
|
83
|
+
...Object.values(config.test.presets || {}).map(preset => preset?.key),
|
|
84
|
+
];
|
|
85
|
+
const now = () => Math.floor(Date.now() / 1000);
|
|
86
|
+
const view = () => ({ pluginName: PLUGIN, updatedAt: now() });
|
|
87
|
+
/** 统一兜底:异常变成可读文字,且绝不把令牌写进日志或回复 */
|
|
88
|
+
function action(task) {
|
|
89
|
+
return async (...args) => {
|
|
90
|
+
try {
|
|
91
|
+
return await task(...args);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
const raw = error instanceof api_1.NewApiError ? error.message : String(error?.message ?? error);
|
|
95
|
+
const message = (0, api_1.sanitize)(raw, ...secrets());
|
|
96
|
+
if (error instanceof api_1.NewApiError) {
|
|
97
|
+
// 上游明确拒绝(4xx/网络),属于可恢复的业务失败
|
|
98
|
+
logger.warn('%s', message);
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
logger.error('指令执行异常:%s', message);
|
|
102
|
+
if (error instanceof Error && error.stack)
|
|
103
|
+
logger.debug('%s', (0, api_1.sanitize)(error.stack, ...secrets()));
|
|
104
|
+
}
|
|
105
|
+
return koishi_1.h.text((0, text_1.renderError)('查询失败', message));
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
const pricing = () => (0, api_1.getPricing)(ctx, client);
|
|
110
|
+
const pricingOrNull = () => pricing().catch((error) => {
|
|
111
|
+
logger.debug('定价接口不可用:%s', (0, api_1.sanitize)(String(error?.message), ...secrets()));
|
|
112
|
+
return null;
|
|
113
|
+
});
|
|
114
|
+
function listView(title, rows, extra = {}) {
|
|
115
|
+
return {
|
|
116
|
+
title,
|
|
117
|
+
rows,
|
|
118
|
+
footerLeft: PLUGIN,
|
|
119
|
+
footerRight: (0, format_1.formatClock)(now()),
|
|
120
|
+
...extra,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
const showList = (list) => (0, render_1.renderList)(ctx, list, renderOptions);
|
|
124
|
+
const showCard = (card) => (0, render_1.renderCard)(ctx, card, renderOptions);
|
|
125
|
+
// ── 站点 ──────────────────────────────────────────────────────
|
|
126
|
+
async function statusAction() {
|
|
127
|
+
const probe = await (0, api_1.probeSite)(ctx, client);
|
|
128
|
+
let status = null;
|
|
129
|
+
if (probe.ok) {
|
|
130
|
+
status = await (0, api_1.getSiteStatus)(ctx, client).then(result => result.data).catch(() => null);
|
|
131
|
+
}
|
|
132
|
+
// 注意:真实站点(v1.0.0-rc.51)的 /api/perf-metrics/summary 只有 models[],
|
|
133
|
+
// 没有顶层 recent_success_series —— 两种形态都带上,由 buildStatusCard 决定用哪个。
|
|
134
|
+
const [sitePricing, perf] = await Promise.all([
|
|
135
|
+
pricingOrNull(),
|
|
136
|
+
probe.ok
|
|
137
|
+
? (0, api_1.getPerfMetricsSummary)(ctx, client, Math.min(config.perfHours, 24)).then(result => result.result).catch(() => undefined)
|
|
138
|
+
: Promise.resolve(undefined),
|
|
139
|
+
]);
|
|
140
|
+
let announcements = (0, view_1.collectAnnouncements)(status, null, config.noticeLimit);
|
|
141
|
+
if (!announcements.length && probe.ok) {
|
|
142
|
+
const notice = await (0, api_1.getNotice)(ctx, client).catch(() => '');
|
|
143
|
+
announcements = (0, view_1.collectAnnouncements)(status, notice, config.noticeLimit);
|
|
144
|
+
}
|
|
145
|
+
const card = (0, view_1.buildStatusCard)({
|
|
146
|
+
status,
|
|
147
|
+
baseUrl: config.baseUrl,
|
|
148
|
+
latencyMs: probe.latencyMs,
|
|
149
|
+
reachable: probe.ok,
|
|
150
|
+
pricing: sitePricing,
|
|
151
|
+
successSeries: perf?.recent_success_series,
|
|
152
|
+
perfModels: perf?.models,
|
|
153
|
+
perfModelCount: perf?.models?.length,
|
|
154
|
+
announcements,
|
|
155
|
+
seriesHours: Math.min(config.perfHours || 24, 24),
|
|
156
|
+
fallbackName: (0, view_1.hostOf)(config.baseUrl),
|
|
157
|
+
}, view());
|
|
158
|
+
const rendered = await showCard(card);
|
|
159
|
+
if (probe.ok || !probe.error)
|
|
160
|
+
return rendered;
|
|
161
|
+
return concat(koishi_1.h.text((0, text_1.renderError)('站点不可访问', probe.error)), rendered);
|
|
162
|
+
}
|
|
163
|
+
async function noticeAction() {
|
|
164
|
+
const status = await (0, api_1.getSiteStatus)(ctx, client).then(result => result.data).catch(() => null);
|
|
165
|
+
const notice = await (0, api_1.getNotice)(ctx, client).catch(() => '');
|
|
166
|
+
const timeline = (0, view_1.collectAnnouncements)(status, null, config.noticeLimit);
|
|
167
|
+
// /api/notice 是 Markdown 裸字符串(# 标题 / **加粗**),卡片不渲染 Markdown,
|
|
168
|
+
// 走 parseAnnouncements 统一剥标记并按段落切
|
|
169
|
+
const notices = notice
|
|
170
|
+
? (0, format_1.parseAnnouncements)((0, api_1.sanitize)(notice, ...secrets()), config.noticeLimit)
|
|
171
|
+
: [];
|
|
172
|
+
// wrap: true —— 公告正文是长文本,卡片里要换行,不能右对齐挤成一行省略号
|
|
173
|
+
const rows = [
|
|
174
|
+
...timeline.map((text, index) => ({ name: `时间线 ${index + 1}`, value: text, level: 'ok', wrap: true })),
|
|
175
|
+
...notices.map((text, index) => ({ name: `公告 ${index + 1}`, value: text, wrap: true })),
|
|
176
|
+
];
|
|
177
|
+
return showList(listView('公告与时间线', rows, {
|
|
178
|
+
subtitle: status?.system_name || (0, view_1.hostOf)(config.baseUrl),
|
|
179
|
+
note: `时间线 ${timeline.length} 条 · 公告 ${notices.length} 条`,
|
|
180
|
+
empty: '站点没有下发公告(console_setting.Announcements 与 Notice 均为空)。',
|
|
181
|
+
}));
|
|
182
|
+
}
|
|
183
|
+
async function aboutAction() {
|
|
184
|
+
const about = await (0, api_1.getAbout)(ctx, client).catch(() => '');
|
|
185
|
+
const rows = [
|
|
186
|
+
{ name: '插件', value: PLUGIN, level: 'ok' },
|
|
187
|
+
{ name: '版本', value: PLUGIN_VERSION },
|
|
188
|
+
{ name: '指令前缀', value: prefixes.join(', ') },
|
|
189
|
+
{ name: '站点', value: (0, view_1.hostOf)(config.baseUrl) },
|
|
190
|
+
{ name: '渲染方式', value: config.render },
|
|
191
|
+
{ name: '数据来源', value: '/api/status · /api/pricing · /api/ratio_config · /api/perf-metrics' },
|
|
192
|
+
{ name: '巡检口径', value: config.monitor.apiKey ? '/v1/models 差集轮询' : '仅站点可用性' },
|
|
193
|
+
{ name: '面板令牌', value: client.token ? '已配置' : '未配置(公开接口仍可用)' },
|
|
194
|
+
];
|
|
195
|
+
const output = await showList(listView('关于', rows, {
|
|
196
|
+
subtitle: '查询 New API 站点状态',
|
|
197
|
+
note: about ? '含站点关于信息' : undefined,
|
|
198
|
+
}));
|
|
199
|
+
if (!about)
|
|
200
|
+
return output;
|
|
201
|
+
return concat(output, koishi_1.h.text('\n站点关于:' + (0, api_1.sanitize)(about, ...secrets())));
|
|
202
|
+
}
|
|
203
|
+
// ── 模型 ──────────────────────────────────────────────────────
|
|
204
|
+
async function modelSearchAction(keyword) {
|
|
205
|
+
const data = await pricing();
|
|
206
|
+
const models = (0, view_1.pricingModels)(data);
|
|
207
|
+
return showList((0, view_1.buildModelList)(models, {
|
|
208
|
+
title: `模型搜索 ${keyword}`,
|
|
209
|
+
subtitle: `${(0, view_1.hostOf)(config.baseUrl)} · /api/pricing`,
|
|
210
|
+
keyword,
|
|
211
|
+
}, view()));
|
|
212
|
+
}
|
|
213
|
+
async function modelListAction(vendor) {
|
|
214
|
+
const data = await pricing();
|
|
215
|
+
const models = (0, view_1.pricingModels)(data);
|
|
216
|
+
const keyword = (vendor || '').trim().toLowerCase();
|
|
217
|
+
const filtered = keyword
|
|
218
|
+
? models.filter(item => (item.vendor || '').toLowerCase().includes(keyword)
|
|
219
|
+
|| item.groups.some(group => group.toLowerCase().includes(keyword)))
|
|
220
|
+
: models;
|
|
221
|
+
return showList((0, view_1.buildModelList)(filtered, {
|
|
222
|
+
title: keyword ? `供应商 ${vendor}` : '站点可用模型',
|
|
223
|
+
subtitle: `${(0, view_1.hostOf)(config.baseUrl)} · /api/pricing`,
|
|
224
|
+
// 不传 note 时由 buildModelList 自己写「86 个 · 显示前 24」;
|
|
225
|
+
// 原先无条件传 "${filtered.length}/${models.length} 个",没有过滤时会显示成没头没脑的「86/86 个」。
|
|
226
|
+
note: keyword ? `${filtered.length}/${models.length} 个` : undefined,
|
|
227
|
+
}, view()));
|
|
228
|
+
}
|
|
229
|
+
async function modelStatusAction(model, options) {
|
|
230
|
+
const hours = clampHours(options.hours, config.perfHours);
|
|
231
|
+
const group = (options.group || '').trim() || undefined;
|
|
232
|
+
const { result } = await (0, api_1.getPerfMetrics)(ctx, client, { model, hours, group });
|
|
233
|
+
if (!result.summary && !result.series?.length) {
|
|
234
|
+
result.summary = (0, api_1.summarizeSeries)(result.series);
|
|
235
|
+
}
|
|
236
|
+
return showCard((0, view_1.buildModelStatusCard)({ model, group, hours, result }, view()));
|
|
237
|
+
}
|
|
238
|
+
async function modelHealthAction() {
|
|
239
|
+
const threshold = Math.min(100, Math.max(0, config.healthThreshold || 95));
|
|
240
|
+
const hours = clampHours(config.healthHours, 1);
|
|
241
|
+
const [{ result }, data] = await Promise.all([
|
|
242
|
+
(0, api_1.getPerfMetricsSummary)(ctx, client, hours),
|
|
243
|
+
pricingOrNull(),
|
|
244
|
+
]);
|
|
245
|
+
const groupsOf = new Map();
|
|
246
|
+
for (const item of (0, view_1.pricingModels)(data))
|
|
247
|
+
groupsOf.set(item.model_name, item.groups);
|
|
248
|
+
const rows = [];
|
|
249
|
+
for (const item of result.models ?? []) {
|
|
250
|
+
const points = item.recent_success_series ?? [];
|
|
251
|
+
const latest = points.length ? points[points.length - 1].success_rate : item.success_rate;
|
|
252
|
+
if (!Number.isFinite(latest) || latest < threshold)
|
|
253
|
+
continue;
|
|
254
|
+
const groups = groupsOf.get(item.model_name) ?? [];
|
|
255
|
+
rows.push({
|
|
256
|
+
name: item.model_name,
|
|
257
|
+
tag: groups.length ? groups.slice(0, 3).join('/') : '未标注分组',
|
|
258
|
+
value: `${(0, format_1.formatSuccessRate)(latest)} · ${(0, format_1.formatLatency)(item.avg_latency_ms)}`,
|
|
259
|
+
level: (0, format_1.classifySuccessRate)(latest),
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
rows.sort((a, b) => Number.parseFloat(b.value ?? '0') - Number.parseFloat(a.value ?? '0'));
|
|
263
|
+
const latestBucket = result.models?.[0]?.recent_success_series?.slice(-1)[0]?.ts;
|
|
264
|
+
return showList(listView('模型健康度', rows.slice(0, 20), {
|
|
265
|
+
subtitle: `成功率 ≥ ${threshold}% · 近 ${hours} 小时`,
|
|
266
|
+
note: latestBucket ? `最近桶 ${(0, format_1.formatClock)(latestBucket)} · perf-metrics` : 'perf-metrics',
|
|
267
|
+
empty: `近 ${hours} 小时没有模型的成功率高于 ${threshold}%(New API 的 perf-metrics 最小粒度是小时桶,取不到分钟级数据)。`,
|
|
268
|
+
}));
|
|
269
|
+
}
|
|
270
|
+
// ── 分组 ──────────────────────────────────────────────────────
|
|
271
|
+
function groupRows(data, keyword) {
|
|
272
|
+
const names = new Set([
|
|
273
|
+
...Object.keys(data.group_ratio ?? {}),
|
|
274
|
+
...Object.keys(data.usable_group ?? {}),
|
|
275
|
+
]);
|
|
276
|
+
const rows = [];
|
|
277
|
+
for (const name of [...names].sort()) {
|
|
278
|
+
if (keyword && !name.toLowerCase().includes(keyword.toLowerCase()))
|
|
279
|
+
continue;
|
|
280
|
+
const ratio = data.group_ratio?.[name];
|
|
281
|
+
const desc = data.usable_group?.[name];
|
|
282
|
+
const count = (0, view_1.pricingModels)(data).filter(item => item.groups.includes(name) || item.groups.includes('all')).length;
|
|
283
|
+
rows.push({
|
|
284
|
+
name,
|
|
285
|
+
tag: desc || undefined,
|
|
286
|
+
value: [(0, format_1.formatRatio)(ratio, 0), count ? `${count} 个模型` : '无模型'].join(' · '),
|
|
287
|
+
level: desc ? 'ok' : 'unknown',
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
return rows;
|
|
291
|
+
}
|
|
292
|
+
async function groupAction() {
|
|
293
|
+
const data = await pricing();
|
|
294
|
+
return showList(listView('分组倍率', groupRows(data), {
|
|
295
|
+
subtitle: `${(0, view_1.hostOf)(config.baseUrl)} · /api/pricing`,
|
|
296
|
+
note: `${groupRows(data).length} 个分组`,
|
|
297
|
+
empty: '站点没有返回分组倍率(group_ratio 为空)。',
|
|
298
|
+
}));
|
|
299
|
+
}
|
|
300
|
+
async function groupSearchAction(keyword) {
|
|
301
|
+
const data = await pricing();
|
|
302
|
+
const rows = groupRows(data, keyword);
|
|
303
|
+
return showList(listView(`分组搜索 ${keyword}`, rows, {
|
|
304
|
+
subtitle: `${(0, view_1.hostOf)(config.baseUrl)} · /api/pricing`,
|
|
305
|
+
note: `${rows.length} 个匹配`,
|
|
306
|
+
empty: `没有匹配「${keyword}」的分组。`,
|
|
307
|
+
}));
|
|
308
|
+
}
|
|
309
|
+
async function groupStatusAction(group) {
|
|
310
|
+
const data = await pricing();
|
|
311
|
+
const keyword = (group || '').trim();
|
|
312
|
+
const rows = groupRows(data, keyword || undefined);
|
|
313
|
+
return showList(listView(keyword ? `分组状态 ${keyword}` : '分组状态', rows, {
|
|
314
|
+
subtitle: `${(0, view_1.hostOf)(config.baseUrl)} · /api/pricing`,
|
|
315
|
+
note: keyword ? undefined : '全部分组',
|
|
316
|
+
empty: keyword
|
|
317
|
+
? `站点没有名为「${keyword}」的分组。`
|
|
318
|
+
: '站点没有返回分组信息。',
|
|
319
|
+
}));
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* 模型倍率查询。
|
|
323
|
+
* 主数据源是 /api/pricing(含厂商、分组、端点的完整信息),
|
|
324
|
+
* 但实测有站点 pricing 只下发 86 个模型、/api/ratio_config 却有 4102 个,
|
|
325
|
+
* 所以查单个模型时要用 ratio_config 兜底,并把缓存倍率一并展示。
|
|
326
|
+
*/
|
|
327
|
+
async function groupRatioAction(model) {
|
|
328
|
+
const keyword = (model || '').trim().toLowerCase();
|
|
329
|
+
const [data, ratioConfig] = await Promise.all([
|
|
330
|
+
pricingOrNull(),
|
|
331
|
+
keyword ? (0, api_1.getRatioConfig)(ctx, client) : Promise.resolve(null),
|
|
332
|
+
]);
|
|
333
|
+
const models = (0, view_1.pricingModels)(data);
|
|
334
|
+
const rows = [];
|
|
335
|
+
const seen = new Set();
|
|
336
|
+
const describe = (name, ratio, completion, cache, quotaType = 0, vendor, price) => {
|
|
337
|
+
const parts = [];
|
|
338
|
+
if (quotaType === 1 && Number.isFinite(price)) {
|
|
339
|
+
parts.push(`按次 ${(0, format_1.formatRatio)(price, 1)}`);
|
|
340
|
+
}
|
|
341
|
+
else {
|
|
342
|
+
parts.push(`模型 ${(0, format_1.formatRatio)(ratio, 0)}`);
|
|
343
|
+
parts.push(`补全 ${(0, format_1.formatRatio)(completion, 0)}`);
|
|
344
|
+
if (Number.isFinite(cache) && cache > 0)
|
|
345
|
+
parts.push(`缓存 ${(0, format_1.formatRatio)(cache, 0)}`);
|
|
346
|
+
}
|
|
347
|
+
return { name, tag: vendor, value: parts.join(' · ') };
|
|
348
|
+
};
|
|
349
|
+
const matched = keyword
|
|
350
|
+
? models.filter(item => item.model_name.toLowerCase() === keyword)
|
|
351
|
+
.concat(models.filter(item => item.model_name.toLowerCase() !== keyword && item.model_name.toLowerCase().includes(keyword)))
|
|
352
|
+
: models;
|
|
353
|
+
for (const item of matched) {
|
|
354
|
+
if (seen.has(item.model_name))
|
|
355
|
+
continue;
|
|
356
|
+
seen.add(item.model_name);
|
|
357
|
+
rows.push(describe(item.model_name, item.ratio, item.completionRatio, item.pricing.cache_ratio, item.quotaType, item.vendor, item.pricing.model_price));
|
|
358
|
+
}
|
|
359
|
+
// ratio_config 兜底:pricing 里没有的模型,用全站倍率字典补上
|
|
360
|
+
if (keyword && ratioConfig) {
|
|
361
|
+
const candidates = Object.keys(ratioConfig.model_ratio ?? {})
|
|
362
|
+
.filter(name => name.toLowerCase().includes(keyword))
|
|
363
|
+
.sort((a, b) => Number(a.toLowerCase() === keyword) * -1 - Number(b.toLowerCase() === keyword) * -1);
|
|
364
|
+
for (const name of candidates.slice(0, 10)) {
|
|
365
|
+
if (seen.has(name))
|
|
366
|
+
continue;
|
|
367
|
+
seen.add(name);
|
|
368
|
+
rows.push(describe(name, ratioConfig.model_ratio[name] ?? 0, ratioConfig.completion_ratio?.[name] ?? 0, ratioConfig.cache_ratio?.[name], ratioConfig.model_price?.[name] ? 1 : 0, undefined, ratioConfig.model_price?.[name]));
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
const total = Object.keys(ratioConfig?.model_ratio ?? {}).length;
|
|
372
|
+
return showList(listView(keyword ? `模型倍率 ${model}` : '模型倍率与补全倍率', rows, {
|
|
373
|
+
subtitle: `${(0, view_1.hostOf)(config.baseUrl)} · /api/pricing · /api/ratio_config`,
|
|
374
|
+
note: keyword
|
|
375
|
+
? `${rows.length} 个匹配`
|
|
376
|
+
: `显示前 ${rows.length}/${models.length} 个,用 <模型> 精确查询`,
|
|
377
|
+
empty: keyword
|
|
378
|
+
? `定价表和全站倍率字典(${total} 个模型)里都没有「${model}」。`
|
|
379
|
+
: '站点没有返回模型倍率。',
|
|
380
|
+
}));
|
|
381
|
+
}
|
|
382
|
+
// ── 监控 ──────────────────────────────────────────────────────
|
|
383
|
+
/**
|
|
384
|
+
* 网络视图优先用 /api/status 的 api_info 线路(逐条实测可达性),
|
|
385
|
+
* 没有线路时才退回 Uptime Kuma —— 实测不少站点 uptime/status 返回空数组,
|
|
386
|
+
* 但 api_info 是有内容的。
|
|
387
|
+
*/
|
|
388
|
+
async function networkAction(target) {
|
|
389
|
+
const name = (target || '').trim() || undefined;
|
|
390
|
+
const routes = await (0, api_1.getApiRoutes)(ctx, client).then(result => result.data).catch(() => []);
|
|
391
|
+
if (routes.length) {
|
|
392
|
+
const probes = await (0, api_1.probeRoutes)(ctx, client, routes);
|
|
393
|
+
return showList((0, view_1.buildRouteList)(probes, name, view()));
|
|
394
|
+
}
|
|
395
|
+
const groups = await (0, api_1.getUptimeStatus)(ctx, client);
|
|
396
|
+
return showList((0, view_1.buildUptimeList)(groups, name, view()));
|
|
397
|
+
}
|
|
398
|
+
// ── 测试 ──────────────────────────────────────────────────────
|
|
399
|
+
function presetRows() {
|
|
400
|
+
const presets = config.test.presets || {};
|
|
401
|
+
return Object.entries(presets).map(([keyId, preset]) => ({
|
|
402
|
+
name: keyId,
|
|
403
|
+
tag: preset?.group,
|
|
404
|
+
value: [preset?.model || config.test.model, maskKey(preset?.key || '')].join(' · '),
|
|
405
|
+
level: preset?.key ? 'ok' : 'fail',
|
|
406
|
+
}));
|
|
407
|
+
}
|
|
408
|
+
async function testListAction() {
|
|
409
|
+
const rows = presetRows();
|
|
410
|
+
return showList(listView('测试预设', rows, {
|
|
411
|
+
subtitle: config.test.enabled ? 'test.enabled 已开启' : 'test.enabled 未开启,测试指令不可用',
|
|
412
|
+
note: `${rows.length} 个预设`,
|
|
413
|
+
empty: '还没有配置 test.presets。可以在插件配置里添加 { keyId: { key, model, group } }。',
|
|
414
|
+
}));
|
|
415
|
+
}
|
|
416
|
+
async function testAction(model, credential) {
|
|
417
|
+
if (!config.test.enabled) {
|
|
418
|
+
return koishi_1.h.text((0, text_1.renderError)('测试功能未开启', '请在插件配置里打开 test.enabled,并配置 test.presets 或直接传 sk- 令牌。'));
|
|
419
|
+
}
|
|
420
|
+
const presets = config.test.presets || {};
|
|
421
|
+
const keyIds = Object.keys(presets);
|
|
422
|
+
let apiKey = '';
|
|
423
|
+
let targetModel = (model || '').trim();
|
|
424
|
+
let presetNote = '';
|
|
425
|
+
if (credential) {
|
|
426
|
+
if (credential.startsWith('sk-')) {
|
|
427
|
+
apiKey = credential;
|
|
428
|
+
presetNote = '指令内令牌(不会写入日志)';
|
|
429
|
+
}
|
|
430
|
+
else if (presets[credential]) {
|
|
431
|
+
apiKey = presets[credential]?.key || '';
|
|
432
|
+
targetModel = targetModel || presets[credential]?.model || '';
|
|
433
|
+
presetNote = `预设 ${credential}`;
|
|
434
|
+
}
|
|
435
|
+
else {
|
|
436
|
+
return koishi_1.h.text((0, text_1.renderError)('找不到该预设', `可用 keyId:${keyIds.join(', ') || '(未配置)'};也可以直接传 sk- 开头的调用令牌。`));
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
else if (keyIds.length === 1) {
|
|
440
|
+
apiKey = presets[keyIds[0]]?.key || '';
|
|
441
|
+
targetModel = targetModel || presets[keyIds[0]]?.model || '';
|
|
442
|
+
presetNote = `预设 ${keyIds[0]}`;
|
|
443
|
+
}
|
|
444
|
+
else if (keyIds.length === 0) {
|
|
445
|
+
return koishi_1.h.text((0, text_1.renderError)('缺少调用令牌', `请在指令里补一个 sk- 令牌,或在配置 test.presets 里预设 keyId(当前预设:0 个)。`));
|
|
446
|
+
}
|
|
447
|
+
else {
|
|
448
|
+
return koishi_1.h.text((0, text_1.renderError)('请指定预设', `站点配置了多个预设,请写明 keyId:${keyIds.join(', ')}。`));
|
|
449
|
+
}
|
|
450
|
+
if (!apiKey)
|
|
451
|
+
return koishi_1.h.text((0, text_1.renderError)('预设缺少令牌', '该预设没有填写 key,请检查 test.presets。'));
|
|
452
|
+
targetModel = targetModel || config.test.model;
|
|
453
|
+
if (!targetModel)
|
|
454
|
+
return koishi_1.h.text((0, text_1.renderError)('缺少模型名', '请在指令里写明模型,或配置 test.model 作为默认值。'));
|
|
455
|
+
const result = await (0, api_1.relayTest)(ctx, {
|
|
456
|
+
baseUrl: config.baseUrl,
|
|
457
|
+
apiKey,
|
|
458
|
+
model: targetModel,
|
|
459
|
+
prompt: config.test.prompt,
|
|
460
|
+
maxTokens: config.test.maxTokens,
|
|
461
|
+
timeout: config.test.timeout || config.timeout,
|
|
462
|
+
});
|
|
463
|
+
if (result.ok) {
|
|
464
|
+
logger.success('连通性测试通过:%s,总耗时 %dms,首 Token %dms', targetModel, result.totalMs, result.firstTokenMs);
|
|
465
|
+
}
|
|
466
|
+
else {
|
|
467
|
+
logger.warn('连通性测试失败:%s,HTTP %s,%s', targetModel, result.status || '--', result.error ?? '未知错误');
|
|
468
|
+
}
|
|
469
|
+
const rows = [
|
|
470
|
+
{ name: '结果', value: result.ok ? '成功' : '失败', level: result.ok ? 'ok' : 'fail' },
|
|
471
|
+
{ name: '模型', value: result.model },
|
|
472
|
+
{ name: '总耗时', value: (0, format_1.formatLatency)(result.totalMs), level: (0, format_1.classifyLatency)(result.totalMs) },
|
|
473
|
+
{ name: '首 Token', value: (0, format_1.formatLatency)(result.firstTokenMs), level: (0, format_1.classifyLatency)(result.firstTokenMs) },
|
|
474
|
+
{ name: 'HTTP', value: String(result.status || '--') },
|
|
475
|
+
{ name: '令牌来源', value: presetNote },
|
|
476
|
+
];
|
|
477
|
+
if (result.preview)
|
|
478
|
+
rows.push({ name: '回复预览', value: result.preview });
|
|
479
|
+
if (result.error)
|
|
480
|
+
rows.push({ name: '错误', value: result.error, level: 'fail' });
|
|
481
|
+
return showList(listView(`连通性测试 ${targetModel}`, rows, {
|
|
482
|
+
subtitle: (0, view_1.hostOf)(config.baseUrl),
|
|
483
|
+
note: 'POST /v1/chat/completions',
|
|
484
|
+
}));
|
|
485
|
+
}
|
|
486
|
+
// ── 帮助 ──────────────────────────────────────────────────────
|
|
487
|
+
/**
|
|
488
|
+
* 帮助正文交给 Koishi 自己的 help 指令生成,不再自己拼一份文本。
|
|
489
|
+
* session.execute(..., true) 只取返回值、不发送(core: shouldEmit=false → h.normalize),
|
|
490
|
+
* 避免一次调用发出两条消息;再把 config.helpText 追加到最末尾。
|
|
491
|
+
* 宿主没装 @koishijs/plugin-help(或 help 指令被禁用)时,回退到内置清单。
|
|
492
|
+
*/
|
|
493
|
+
async function koishiHelp(argv, target, fallback) {
|
|
494
|
+
const footer = (config.helpText || '').trim();
|
|
495
|
+
let body = null;
|
|
496
|
+
const session = argv?.session;
|
|
497
|
+
if (session && typeof session.execute === 'function') {
|
|
498
|
+
try {
|
|
499
|
+
body = koishi_1.h.normalize(await session.execute({ name: 'help', args: [target] }, true));
|
|
500
|
+
}
|
|
501
|
+
catch (error) {
|
|
502
|
+
logger.debug('Koishi help 不可用,回退内置清单:%s', (0, api_1.sanitize)(String(error?.message), ...secrets()));
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
if (!body || !body.length)
|
|
506
|
+
body = koishi_1.h.normalize(fallback());
|
|
507
|
+
if (!footer)
|
|
508
|
+
return body;
|
|
509
|
+
return concat(body, koishi_1.h.text('\n' + (0, api_1.sanitize)(footer, ...secrets())));
|
|
510
|
+
}
|
|
511
|
+
// ── 指令注册 ──────────────────────────────────────────────────
|
|
512
|
+
for (const prefix of prefixes) {
|
|
513
|
+
const fullList = () => commandList(prefix, clampHours(config.healthHours, 1));
|
|
514
|
+
const root = ctx.command(prefix, 'New API 站点状态查询')
|
|
515
|
+
.usage(`输入 ${prefix} help 查看全部子指令;任意子指令加 -h 查看详细帮助。`);
|
|
516
|
+
root.action(action(argv => koishiHelp(argv, prefix, () => koishi_1.h.text((0, text_1.renderHelp)(prefix, fullList())))));
|
|
517
|
+
ctx.command(`${prefix}.help`, '列出全部指令和用法')
|
|
518
|
+
.example(`${prefix} help`)
|
|
519
|
+
.action(action(argv => koishiHelp(argv, prefix, () => koishi_1.h.text((0, text_1.renderHelp)(prefix, fullList())))));
|
|
520
|
+
ctx.command(`${prefix}.status`, '查询站点状态').action(action(statusAction));
|
|
521
|
+
ctx.command(`${prefix}.notice`, '查看最新时间线与公告').action(action(noticeAction));
|
|
522
|
+
ctx.command(`${prefix}.about`, '关于本插件').action(action(aboutAction));
|
|
523
|
+
const modelRoot = ctx.command(`${prefix}.model`, '模型相关查询')
|
|
524
|
+
.usage(`输入 ${prefix} model 查看模型相关子指令。`);
|
|
525
|
+
modelRoot.action(action(argv => koishiHelp(argv, `${prefix}.model`, () => koishi_1.h.text((0, text_1.renderHelp)(prefix, fullList().filter(item => item.usage.includes(`${prefix} model`)))))));
|
|
526
|
+
ctx.command(`${prefix}.model.search <keyword>`, '模糊搜索模型名')
|
|
527
|
+
.action(action(async (_argv, keyword) => modelSearchAction(String(keyword ?? ''))));
|
|
528
|
+
ctx.command(`${prefix}.model.list [vendor]`, '站点可用模型列表')
|
|
529
|
+
.action(action(async (_argv, vendor) => modelListAction(vendor ? String(vendor) : undefined)));
|
|
530
|
+
ctx.command(`${prefix}.model.status <model>`, '查询模型表现')
|
|
531
|
+
.option('hours', '-t <hours:natural> 统计窗口(小时),默认 24')
|
|
532
|
+
.option('group', '-g <group> 只看某个分组')
|
|
533
|
+
.action(action(async (argv, model) => modelStatusAction(String(model ?? ''), {
|
|
534
|
+
hours: argv.options?.hours,
|
|
535
|
+
group: argv.options?.group,
|
|
536
|
+
})));
|
|
537
|
+
ctx.command(`${prefix}.model.health`, '列出成功率高于阈值的模型及其分组')
|
|
538
|
+
.action(action(modelHealthAction));
|
|
539
|
+
const groupRoot = ctx.command(`${prefix}.group`, '分组相关查询');
|
|
540
|
+
groupRoot.action(action(groupAction));
|
|
541
|
+
ctx.command(`${prefix}.group.ratio [model]`, '模型倍率和补全倍率')
|
|
542
|
+
.action(action(async (_argv, model) => groupRatioAction(model ? String(model) : undefined)));
|
|
543
|
+
ctx.command(`${prefix}.group.status [group]`, '分组状态')
|
|
544
|
+
.action(action(async (_argv, group) => groupStatusAction(group ? String(group) : undefined)));
|
|
545
|
+
ctx.command(`${prefix}.group.search <keyword>`, '模糊搜索分组名')
|
|
546
|
+
.action(action(async (_argv, keyword) => groupSearchAction(String(keyword ?? ''))));
|
|
547
|
+
ctx.command(`${prefix}.network [name]`, '站点线路与监控项状态')
|
|
548
|
+
.action(action(async (_argv, name) => networkAction(name ? String(name) : undefined)));
|
|
549
|
+
ctx.command(`${prefix}.test [model] [credential]`, '用调用令牌做一次连通性测试', { permissions: ['authority:3'] })
|
|
550
|
+
.action(action(async (_argv, model, credential) => {
|
|
551
|
+
if (String(model ?? '') === 'list')
|
|
552
|
+
return testListAction();
|
|
553
|
+
return testAction(model ? String(model) : undefined, credential ? String(credential) : undefined);
|
|
554
|
+
}));
|
|
555
|
+
}
|
|
556
|
+
logger.info('插件已加载:前缀 %s,站点 %s,渲染 %s,日志等级 %s', prefixes.join(', '), (0, view_1.hostOf)(config.baseUrl), config.render, config.logLevel);
|
|
557
|
+
if (config.monitor.enabled) {
|
|
558
|
+
ctx.on('ready', () => {
|
|
559
|
+
try {
|
|
560
|
+
(0, monitor_1.startMonitor)(ctx, config);
|
|
561
|
+
}
|
|
562
|
+
catch (error) {
|
|
563
|
+
logger.warn('巡检启动失败:%s', (0, api_1.sanitize)(String(error?.message), ...secrets()));
|
|
564
|
+
}
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
}
|
package/lib/log.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Context } from 'koishi';
|
|
2
|
+
/**
|
|
3
|
+
* 日志命名空间。Koishi 控制台「日志」页按这个名字分组,
|
|
4
|
+
* 用 `ctx.logger('newapi-status')` 打出来的每一行都会落在这里。
|
|
5
|
+
*/
|
|
6
|
+
export declare const LOGGER_NAME = "newapi-status";
|
|
7
|
+
/** reggol 提供的 5 个日志等级,顺序即语义强度 */
|
|
8
|
+
export declare const LOG_METHODS: readonly ["success", "error", "info", "warn", "debug"];
|
|
9
|
+
export type LogMethod = typeof LOG_METHODS[number];
|
|
10
|
+
/**
|
|
11
|
+
* 配置里的过滤档位 → reggol 的数值等级。
|
|
12
|
+
* reggol 常量:SILENT=0,SUCCESS/ERROR=1,INFO/WARN=2,DEBUG=3
|
|
13
|
+
* (info 与 warn 同档,success 与 error 同档,这是上游定义,插件不另造)。
|
|
14
|
+
*/
|
|
15
|
+
export declare const LOG_LEVELS: {
|
|
16
|
+
readonly silent: 0;
|
|
17
|
+
readonly error: 1;
|
|
18
|
+
readonly info: 2;
|
|
19
|
+
readonly debug: 3;
|
|
20
|
+
};
|
|
21
|
+
export type LogLevelName = keyof typeof LOG_LEVELS;
|
|
22
|
+
export declare const LOG_LEVEL_NAMES: LogLevelName[];
|
|
23
|
+
export interface PluginLogger {
|
|
24
|
+
/** 达成类事件:连通性测试通过、巡检恢复 */
|
|
25
|
+
success(message: string, ...args: any[]): void;
|
|
26
|
+
/** 真正的异常:未预期错误、栈信息 */
|
|
27
|
+
error(message: string, ...args: any[]): void;
|
|
28
|
+
/** 常规事件:插件加载、巡检启动、基线建立 */
|
|
29
|
+
info(message: string, ...args: any[]): void;
|
|
30
|
+
/** 可恢复的降级:接口不可用、卡片渲染失败、巡检失败 */
|
|
31
|
+
warn(message: string, ...args: any[]): void;
|
|
32
|
+
/** 诊断细节:请求耗时、回退路径 */
|
|
33
|
+
debug(message: string, ...args: any[]): void;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* 创建插件的 5 等级 logger,并在注册时把配置里的档位写回 Koishi 的全局等级表。
|
|
37
|
+
* 所有日志都经这一个入口,脱敏责任留给调用方(sanitize)。
|
|
38
|
+
*/
|
|
39
|
+
export declare function createLogger(ctx: Context, level?: LogLevelName): PluginLogger;
|
package/lib/log.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LOG_LEVEL_NAMES = exports.LOG_LEVELS = exports.LOG_METHODS = exports.LOGGER_NAME = void 0;
|
|
4
|
+
exports.createLogger = createLogger;
|
|
5
|
+
/**
|
|
6
|
+
* 日志命名空间。Koishi 控制台「日志」页按这个名字分组,
|
|
7
|
+
* 用 `ctx.logger('newapi-status')` 打出来的每一行都会落在这里。
|
|
8
|
+
*/
|
|
9
|
+
exports.LOGGER_NAME = 'newapi-status';
|
|
10
|
+
/** reggol 提供的 5 个日志等级,顺序即语义强度 */
|
|
11
|
+
exports.LOG_METHODS = ['success', 'error', 'info', 'warn', 'debug'];
|
|
12
|
+
/**
|
|
13
|
+
* 配置里的过滤档位 → reggol 的数值等级。
|
|
14
|
+
* reggol 常量:SILENT=0,SUCCESS/ERROR=1,INFO/WARN=2,DEBUG=3
|
|
15
|
+
* (info 与 warn 同档,success 与 error 同档,这是上游定义,插件不另造)。
|
|
16
|
+
*/
|
|
17
|
+
exports.LOG_LEVELS = { silent: 0, error: 1, info: 2, debug: 3 };
|
|
18
|
+
exports.LOG_LEVEL_NAMES = Object.keys(exports.LOG_LEVELS);
|
|
19
|
+
/**
|
|
20
|
+
* 创建插件的 5 等级 logger,并在注册时把配置里的档位写回 Koishi 的全局等级表。
|
|
21
|
+
* 所有日志都经这一个入口,脱敏责任留给调用方(sanitize)。
|
|
22
|
+
*/
|
|
23
|
+
function createLogger(ctx, level = 'info') {
|
|
24
|
+
const raw = ctx.logger(exports.LOGGER_NAME);
|
|
25
|
+
const numeric = exports.LOG_LEVELS[level] ?? exports.LOG_LEVELS.info;
|
|
26
|
+
try {
|
|
27
|
+
raw.level = numeric;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
// 旧版 reggol 没有 level setter,忽略即可,不影响日志输出
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
success: (message, ...args) => raw.success(message, ...args),
|
|
34
|
+
error: (message, ...args) => raw.error(message, ...args),
|
|
35
|
+
info: (message, ...args) => raw.info(message, ...args),
|
|
36
|
+
warn: (message, ...args) => raw.warn(message, ...args),
|
|
37
|
+
debug: (message, ...args) => raw.debug(message, ...args),
|
|
38
|
+
};
|
|
39
|
+
}
|