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/LICENSE
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
专有软件许可协议 / Proprietary License
|
|
2
|
+
Copyright (c) 2025 acmuhan. All rights reserved.
|
|
3
|
+
|
|
4
|
+
本软件(koishi-plugin-newapi-status)及其源代码、编译产物、文档与示例图片
|
|
5
|
+
均为版权持有人 acmuhan 的专有财产。未经版权持有人事先书面授权,任何人不得:
|
|
6
|
+
|
|
7
|
+
1. 复制、转载、镜像、摘录本软件源代码的全部或任何部分;
|
|
8
|
+
2. 修改、翻译、演绎本软件,或基于本软件创作衍生作品;
|
|
9
|
+
3. 分发、发布、公开传播、出售、转售、出租或以其他方式再许可本软件;
|
|
10
|
+
4. 将本软件或其衍生作品用于商业用途,或以此对外提供收费服务;
|
|
11
|
+
5. 移除、掩盖或更改本软件中的任何版权、许可声明。
|
|
12
|
+
|
|
13
|
+
无需单独授权即可进行的行为(仅限以下):
|
|
14
|
+
|
|
15
|
+
- 通过 npm / 包管理器安装本软件,并在自用环境中运行;
|
|
16
|
+
- 在未修改本软件的前提下,将本软件作为依赖随自己的 Koishi 实例部署;
|
|
17
|
+
- 阅读源代码用于学习与评估(不得复制、摘录或再分发)。
|
|
18
|
+
|
|
19
|
+
任何超出上述范围的使用——包括但不限于二次开发、修改后发布、
|
|
20
|
+
把源码并入其他项目、商业部署或对外提供服务——必须先取得书面授权。
|
|
21
|
+
授权申请请通过以下地址联系版权持有人:
|
|
22
|
+
|
|
23
|
+
https://github.com/acmuhan/koishi-plugin-newapi-status/issues
|
|
24
|
+
|
|
25
|
+
取得授权后,双方另行签署书面许可协议,本协议不构成任何默示授权。
|
|
26
|
+
|
|
27
|
+
免责声明:本软件按"原样"提供,不附带任何明示或默示的担保,包括但不限于
|
|
28
|
+
适销性、特定用途适用性与不侵权的担保。在任何情况下,版权持有人均不对
|
|
29
|
+
因使用或无法使用本软件而产生的任何直接、间接、附带或后果性损害承担责任。
|
|
30
|
+
|
|
31
|
+
SPDX-License-Identifier: LicenseRef-Proprietary
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export * from './shared';
|
|
2
|
+
export * from './status';
|
|
3
|
+
export * from './notice';
|
|
4
|
+
export * from './pricing';
|
|
5
|
+
export * from './models';
|
|
6
|
+
export * from './uptime';
|
|
7
|
+
export * from './perf';
|
|
8
|
+
export * from './relay';
|
|
9
|
+
export * from './network';
|
|
10
|
+
export * from './ratio';
|
package/lib/api/index.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./shared"), exports);
|
|
18
|
+
__exportStar(require("./status"), exports);
|
|
19
|
+
__exportStar(require("./notice"), exports);
|
|
20
|
+
__exportStar(require("./pricing"), exports);
|
|
21
|
+
__exportStar(require("./models"), exports);
|
|
22
|
+
__exportStar(require("./uptime"), exports);
|
|
23
|
+
__exportStar(require("./perf"), exports);
|
|
24
|
+
__exportStar(require("./relay"), exports);
|
|
25
|
+
__exportStar(require("./network"), exports);
|
|
26
|
+
__exportStar(require("./ratio"), exports);
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import type { ModelsByChannel } from '../types';
|
|
3
|
+
import { ApiClientOptions } from './shared';
|
|
4
|
+
/**
|
|
5
|
+
* GET /api/models
|
|
6
|
+
* 走 middleware.UserAuth():**必须**面板 access_token / PAT,匿名会 401。
|
|
7
|
+
* data 形如 { "1": ["gpt-4o", ...], "14": [...] }(channelType → 模型名列表)。
|
|
8
|
+
*/
|
|
9
|
+
export declare function getModelsByChannel(ctx: Context, options: ApiClientOptions): Promise<ModelsByChannel>;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getModelsByChannel = getModelsByChannel;
|
|
4
|
+
const shared_1 = require("./shared");
|
|
5
|
+
/**
|
|
6
|
+
* GET /api/models
|
|
7
|
+
* 走 middleware.UserAuth():**必须**面板 access_token / PAT,匿名会 401。
|
|
8
|
+
* data 形如 { "1": ["gpt-4o", ...], "14": [...] }(channelType → 模型名列表)。
|
|
9
|
+
*/
|
|
10
|
+
async function getModelsByChannel(ctx, options) {
|
|
11
|
+
const { data } = await (0, shared_1.request)(ctx, options, '/api/models');
|
|
12
|
+
if (!data || typeof data !== 'object')
|
|
13
|
+
return {};
|
|
14
|
+
const result = {};
|
|
15
|
+
for (const [type, models] of Object.entries(data)) {
|
|
16
|
+
if (Array.isArray(models))
|
|
17
|
+
result[type] = models.filter((item) => typeof item === 'string');
|
|
18
|
+
}
|
|
19
|
+
return result;
|
|
20
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import type { SiteRoute } from '../types';
|
|
3
|
+
import { ApiClientOptions, ApiResponse } from './shared';
|
|
4
|
+
/**
|
|
5
|
+
* 站点线路(/api/status 的 data.api_info)。
|
|
6
|
+
* 官方前端用它给出「中国大陆 / 全球 / 备用」这类接入点,站内通常还会配 uptime_kuma;
|
|
7
|
+
* 但实测很多站点 uptime/status 是空数组,api_info 反而是唯一有内容的网络视图。
|
|
8
|
+
*/
|
|
9
|
+
export declare function getApiRoutes(ctx: Context, options: ApiClientOptions): Promise<ApiResponse<SiteRoute[]>>;
|
|
10
|
+
export interface RouteProbe {
|
|
11
|
+
route: SiteRoute;
|
|
12
|
+
ok: boolean;
|
|
13
|
+
latencyMs: number;
|
|
14
|
+
error?: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* 逐条探测线路的可达性与耗时。
|
|
18
|
+
* 探的是线路根地址下的 /api/status(无鉴权),和 /newapi status 的口径一致。
|
|
19
|
+
*/
|
|
20
|
+
export declare function probeRoutes(ctx: Context, options: ApiClientOptions, routes: SiteRoute[]): Promise<RouteProbe[]>;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getApiRoutes = getApiRoutes;
|
|
4
|
+
exports.probeRoutes = probeRoutes;
|
|
5
|
+
const shared_1 = require("./shared");
|
|
6
|
+
/**
|
|
7
|
+
* 站点线路(/api/status 的 data.api_info)。
|
|
8
|
+
* 官方前端用它给出「中国大陆 / 全球 / 备用」这类接入点,站内通常还会配 uptime_kuma;
|
|
9
|
+
* 但实测很多站点 uptime/status 是空数组,api_info 反而是唯一有内容的网络视图。
|
|
10
|
+
*/
|
|
11
|
+
async function getApiRoutes(ctx, options) {
|
|
12
|
+
const { data, latencyMs, status } = await (0, shared_1.request)(ctx, options, '/api/status', {
|
|
13
|
+
authorization: null,
|
|
14
|
+
});
|
|
15
|
+
const routes = Array.isArray(data?.api_info) ? data.api_info : [];
|
|
16
|
+
return {
|
|
17
|
+
data: routes.filter(route => route && typeof route.url === 'string' && route.url.trim()),
|
|
18
|
+
latencyMs,
|
|
19
|
+
status,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* 逐条探测线路的可达性与耗时。
|
|
24
|
+
* 探的是线路根地址下的 /api/status(无鉴权),和 /newapi status 的口径一致。
|
|
25
|
+
*/
|
|
26
|
+
async function probeRoutes(ctx, options, routes) {
|
|
27
|
+
return Promise.all(routes.map(async (route) => {
|
|
28
|
+
const started = Date.now();
|
|
29
|
+
try {
|
|
30
|
+
await (0, shared_1.request)(ctx, { ...options, baseUrl: route.url }, '/api/status', { authorization: null });
|
|
31
|
+
return { route, ok: true, latencyMs: Date.now() - started };
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
return {
|
|
35
|
+
route,
|
|
36
|
+
ok: false,
|
|
37
|
+
latencyMs: Date.now() - started,
|
|
38
|
+
error: error?.message,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
}));
|
|
42
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import { ApiClientOptions } from './shared';
|
|
3
|
+
/**
|
|
4
|
+
* GET /api/notice、GET /api/about。
|
|
5
|
+
* 注意:这两个接口的 data 是**裸字符串**(controller/misc.go: serveRevalidatedJSON),不是对象。
|
|
6
|
+
*/
|
|
7
|
+
export declare function getNotice(ctx: Context, options: ApiClientOptions): Promise<string>;
|
|
8
|
+
export declare function getAbout(ctx: Context, options: ApiClientOptions): Promise<string>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getNotice = getNotice;
|
|
4
|
+
exports.getAbout = getAbout;
|
|
5
|
+
const shared_1 = require("./shared");
|
|
6
|
+
/**
|
|
7
|
+
* GET /api/notice、GET /api/about。
|
|
8
|
+
* 注意:这两个接口的 data 是**裸字符串**(controller/misc.go: serveRevalidatedJSON),不是对象。
|
|
9
|
+
*/
|
|
10
|
+
async function getNotice(ctx, options) {
|
|
11
|
+
const { data } = await (0, shared_1.request)(ctx, options, '/api/notice', { authorization: null });
|
|
12
|
+
return typeof data === 'string' ? data : '';
|
|
13
|
+
}
|
|
14
|
+
async function getAbout(ctx, options) {
|
|
15
|
+
const { data } = await (0, shared_1.request)(ctx, options, '/api/about', { authorization: null });
|
|
16
|
+
return typeof data === 'string' ? data : '';
|
|
17
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import type { PerfQueryResult, PerfSummaryAllResult, PerfSummary } from '../types';
|
|
3
|
+
import { ApiClientOptions } from './shared';
|
|
4
|
+
/** hours 取值范围:controller 侧 min(hours, 24*30),<=0 时按 24 处理 */
|
|
5
|
+
export declare const MAX_PERF_HOURS: number;
|
|
6
|
+
/** pkg/perf_metrics MaxRecentModels */
|
|
7
|
+
export declare const MAX_RECENT_MODELS = 50;
|
|
8
|
+
export interface PerfQueryOptions {
|
|
9
|
+
model: string;
|
|
10
|
+
hours?: number;
|
|
11
|
+
group?: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* GET /api/perf-metrics?model=&hours=&group=
|
|
15
|
+
* 必须带 model;bucket 固定按小时聚合(perf_metrics_setting.BucketTime 默认 hour),
|
|
16
|
+
* 所以拿不到分钟级数据,任何"近 1 分钟"的文案都必须改写。
|
|
17
|
+
*/
|
|
18
|
+
export declare function getPerfMetrics(ctx: Context, options: ApiClientOptions, query: PerfQueryOptions): Promise<{
|
|
19
|
+
result: PerfQueryResult;
|
|
20
|
+
latencyMs: number;
|
|
21
|
+
}>;
|
|
22
|
+
/**
|
|
23
|
+
* GET /api/perf-metrics/summary?hours=&recent_model=...
|
|
24
|
+
* 返回全站模型汇总 + 每个模型的近期成功率序列(最多 50 个 recent_model)。
|
|
25
|
+
*/
|
|
26
|
+
export declare function getPerfMetricsSummary(ctx: Context, options: ApiClientOptions, hours?: number, recentModels?: string[]): Promise<{
|
|
27
|
+
result: PerfSummaryAllResult;
|
|
28
|
+
latencyMs: number;
|
|
29
|
+
}>;
|
|
30
|
+
/** 从 buckets 里按请求数加权估算整体指标(summary 缺失时的兜底) */
|
|
31
|
+
export declare function summarizeSeries(series: PerfQueryResult['series'] | undefined): PerfSummary | undefined;
|
package/lib/api/perf.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MAX_RECENT_MODELS = exports.MAX_PERF_HOURS = void 0;
|
|
4
|
+
exports.getPerfMetrics = getPerfMetrics;
|
|
5
|
+
exports.getPerfMetricsSummary = getPerfMetricsSummary;
|
|
6
|
+
exports.summarizeSeries = summarizeSeries;
|
|
7
|
+
const shared_1 = require("./shared");
|
|
8
|
+
/** hours 取值范围:controller 侧 min(hours, 24*30),<=0 时按 24 处理 */
|
|
9
|
+
exports.MAX_PERF_HOURS = 24 * 30;
|
|
10
|
+
/** pkg/perf_metrics MaxRecentModels */
|
|
11
|
+
exports.MAX_RECENT_MODELS = 50;
|
|
12
|
+
/**
|
|
13
|
+
* GET /api/perf-metrics?model=&hours=&group=
|
|
14
|
+
* 必须带 model;bucket 固定按小时聚合(perf_metrics_setting.BucketTime 默认 hour),
|
|
15
|
+
* 所以拿不到分钟级数据,任何"近 1 分钟"的文案都必须改写。
|
|
16
|
+
*/
|
|
17
|
+
async function getPerfMetrics(ctx, options, query) {
|
|
18
|
+
const { data, latencyMs } = await (0, shared_1.request)(ctx, options, '/api/perf-metrics', {
|
|
19
|
+
query: { model: query.model, hours: query.hours ?? 24, group: query.group || undefined },
|
|
20
|
+
});
|
|
21
|
+
return { result: data, latencyMs };
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* GET /api/perf-metrics/summary?hours=&recent_model=...
|
|
25
|
+
* 返回全站模型汇总 + 每个模型的近期成功率序列(最多 50 个 recent_model)。
|
|
26
|
+
*/
|
|
27
|
+
async function getPerfMetricsSummary(ctx, options, hours = 24, recentModels = []) {
|
|
28
|
+
const capped = recentModels.slice(0, exports.MAX_RECENT_MODELS);
|
|
29
|
+
const { data, latencyMs } = await (0, shared_1.request)(ctx, options, '/api/perf-metrics/summary', {
|
|
30
|
+
query: { hours, recent_model: capped.length ? capped : undefined },
|
|
31
|
+
});
|
|
32
|
+
return { result: data, latencyMs };
|
|
33
|
+
}
|
|
34
|
+
/** 从 buckets 里按请求数加权估算整体指标(summary 缺失时的兜底) */
|
|
35
|
+
function summarizeSeries(series) {
|
|
36
|
+
if (!series?.length)
|
|
37
|
+
return undefined;
|
|
38
|
+
const valid = series.filter((point) => Number.isFinite(point?.success_rate));
|
|
39
|
+
if (!valid.length)
|
|
40
|
+
return undefined;
|
|
41
|
+
const avg = (pick) => {
|
|
42
|
+
const values = valid.map(pick).filter((value) => Number.isFinite(value));
|
|
43
|
+
if (!values.length)
|
|
44
|
+
return 0;
|
|
45
|
+
return values.reduce((sum, value) => sum + value, 0) / values.length;
|
|
46
|
+
};
|
|
47
|
+
return {
|
|
48
|
+
success_rate: avg((point) => point.success_rate),
|
|
49
|
+
avg_latency_ms: avg((point) => point.avg_latency_ms),
|
|
50
|
+
avg_tps: avg((point) => point.avg_tps),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import type { PricingResponse } from '../types';
|
|
3
|
+
import { ApiClientOptions } from './shared';
|
|
4
|
+
/**
|
|
5
|
+
* GET /api/pricing
|
|
6
|
+
* 走 middleware.HeaderNavModuleAuth('pricing'):站点默认公开,登录后 group_ratio 会按用户分组覆写。
|
|
7
|
+
* 返回 data(Pricing[]) + vendors + group_ratio + usable_group + auto_groups。
|
|
8
|
+
*/
|
|
9
|
+
export declare function getPricing(ctx: Context, options: ApiClientOptions): Promise<PricingResponse>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getPricing = getPricing;
|
|
4
|
+
const shared_1 = require("./shared");
|
|
5
|
+
/**
|
|
6
|
+
* GET /api/pricing
|
|
7
|
+
* 走 middleware.HeaderNavModuleAuth('pricing'):站点默认公开,登录后 group_ratio 会按用户分组覆写。
|
|
8
|
+
* 返回 data(Pricing[]) + vendors + group_ratio + usable_group + auto_groups。
|
|
9
|
+
*/
|
|
10
|
+
async function getPricing(ctx, options) {
|
|
11
|
+
// 注意:/api/pricing 的 vendors / group_ratio / usable_group 与 data 同级(controller/pricing.go: GetPricing 的 gin.H),
|
|
12
|
+
// 所以这里必须拿整个响应体,不能只要 data。
|
|
13
|
+
const { data } = await (0, shared_1.request)(ctx, options, '/api/pricing', { raw: true });
|
|
14
|
+
const payload = (data ?? {});
|
|
15
|
+
return {
|
|
16
|
+
data: Array.isArray(payload.data) ? payload.data : [],
|
|
17
|
+
vendors: Array.isArray(payload.vendors) ? payload.vendors : [],
|
|
18
|
+
group_ratio: payload.group_ratio ?? {},
|
|
19
|
+
usable_group: payload.usable_group ?? {},
|
|
20
|
+
supported_endpoint: payload.supported_endpoint ?? {},
|
|
21
|
+
auto_groups: payload.auto_groups ?? [],
|
|
22
|
+
pricing_version: payload.pricing_version,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import type { RatioConfig } from '../types';
|
|
3
|
+
import { ApiClientOptions } from './shared';
|
|
4
|
+
/**
|
|
5
|
+
* GET /api/ratio_config —— 无鉴权,公开接口。
|
|
6
|
+
* 返回全站倍率字典:model_ratio / completion_ratio / cache_ratio / model_price / billing_mode / billing_expr。
|
|
7
|
+
* 实测部分站点这里下发的模型数远多于 /api/pricing(例如 4102 对 86),
|
|
8
|
+
* 所以「查某个模型的倍率」必须把这份字典当兜底数据源。
|
|
9
|
+
*/
|
|
10
|
+
export declare function getRatioConfig(ctx: Context, options: ApiClientOptions): Promise<RatioConfig>;
|
package/lib/api/ratio.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getRatioConfig = getRatioConfig;
|
|
4
|
+
const shared_1 = require("./shared");
|
|
5
|
+
/**
|
|
6
|
+
* GET /api/ratio_config —— 无鉴权,公开接口。
|
|
7
|
+
* 返回全站倍率字典:model_ratio / completion_ratio / cache_ratio / model_price / billing_mode / billing_expr。
|
|
8
|
+
* 实测部分站点这里下发的模型数远多于 /api/pricing(例如 4102 对 86),
|
|
9
|
+
* 所以「查某个模型的倍率」必须把这份字典当兜底数据源。
|
|
10
|
+
*/
|
|
11
|
+
async function getRatioConfig(ctx, options) {
|
|
12
|
+
try {
|
|
13
|
+
const { data } = await (0, shared_1.request)(ctx, options, '/api/ratio_config', { authorization: null });
|
|
14
|
+
const payload = (data ?? {});
|
|
15
|
+
return {
|
|
16
|
+
model_ratio: payload.model_ratio ?? {},
|
|
17
|
+
completion_ratio: payload.completion_ratio ?? {},
|
|
18
|
+
cache_ratio: payload.cache_ratio ?? {},
|
|
19
|
+
create_cache_ratio: payload.create_cache_ratio ?? {},
|
|
20
|
+
model_price: payload.model_price ?? {},
|
|
21
|
+
billing_mode: payload.billing_mode ?? {},
|
|
22
|
+
billing_expr: payload.billing_expr ?? {},
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
// 老版本没有这个接口:返回空字典,调用方退回 /api/pricing
|
|
27
|
+
return { model_ratio: {}, completion_ratio: {}, cache_ratio: {}, create_cache_ratio: {}, model_price: {}, billing_mode: {}, billing_expr: {} };
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
export interface RelayTestOptions {
|
|
3
|
+
baseUrl: string;
|
|
4
|
+
/** sk- 开头的调用令牌(relay key)。面板 access_token 在这里无效。 */
|
|
5
|
+
apiKey: string;
|
|
6
|
+
model: string;
|
|
7
|
+
prompt?: string;
|
|
8
|
+
maxTokens?: number;
|
|
9
|
+
timeout?: number;
|
|
10
|
+
}
|
|
11
|
+
export interface RelayTestResult {
|
|
12
|
+
ok: boolean;
|
|
13
|
+
model: string;
|
|
14
|
+
/** 第一个内容 delta 到达的耗时(毫秒),没有内容时等于总耗时 */
|
|
15
|
+
firstTokenMs: number;
|
|
16
|
+
/** 请求全程耗时(毫秒) */
|
|
17
|
+
totalMs: number;
|
|
18
|
+
status: number;
|
|
19
|
+
/** 服务端返回的前若干字符,失败时用于定位 */
|
|
20
|
+
preview?: string;
|
|
21
|
+
error?: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* 用 sk- 调用令牌发一条最短对话请求,测量总耗时与首 Token 耗时。
|
|
25
|
+
* 走 relay 的 OpenAI 兼容端点 POST /v1/chat/completions(不是 /api/* 面板接口)。
|
|
26
|
+
* token 只出现在请求头里,任何报错都会先 sanitize。
|
|
27
|
+
*/
|
|
28
|
+
/**
|
|
29
|
+
* GET /v1/models —— relay 端点的模型清单,用 sk- 调用令牌即可读取(不需要面板 access_token)。
|
|
30
|
+
* 这是「管理员禁用渠道」的可用观测口径:
|
|
31
|
+
* 某个模型的渠道被全部禁用后,它会从这份清单里消失,重新启用后又会回来。
|
|
32
|
+
*/
|
|
33
|
+
export declare function listRelayModels(ctx: Context, options: {
|
|
34
|
+
baseUrl: string;
|
|
35
|
+
apiKey: string;
|
|
36
|
+
timeout?: number;
|
|
37
|
+
}): Promise<{
|
|
38
|
+
ok: boolean;
|
|
39
|
+
models: string[];
|
|
40
|
+
status: number;
|
|
41
|
+
error?: string;
|
|
42
|
+
}>;
|
|
43
|
+
export declare function relayTest(ctx: Context, options: RelayTestOptions): Promise<RelayTestResult>;
|
package/lib/api/relay.js
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.listRelayModels = listRelayModels;
|
|
4
|
+
exports.relayTest = relayTest;
|
|
5
|
+
const shared_1 = require("./shared");
|
|
6
|
+
/**
|
|
7
|
+
* 把上游的错误响应体读成一段文本。
|
|
8
|
+
* responseType=stream 时 axios 的 error.response.data 是流不是字符串,
|
|
9
|
+
* 直接 String() 只会得到 "[object ReadableStream]",定位问题全靠这段。
|
|
10
|
+
*/
|
|
11
|
+
async function readErrorBody(raw, limit = 400) {
|
|
12
|
+
const stream = raw;
|
|
13
|
+
const reader = stream?.getReader?.();
|
|
14
|
+
if (!reader)
|
|
15
|
+
return typeof raw === 'string' ? raw.slice(0, limit) : undefined;
|
|
16
|
+
const decoder = new TextDecoder();
|
|
17
|
+
let text = '';
|
|
18
|
+
try {
|
|
19
|
+
while (text.length < limit) {
|
|
20
|
+
const { done, value } = await reader.read();
|
|
21
|
+
if (done)
|
|
22
|
+
break;
|
|
23
|
+
if (value)
|
|
24
|
+
text += decoder.decode(value, { stream: true });
|
|
25
|
+
}
|
|
26
|
+
text += decoder.decode();
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
// 读失败就用已读到的部分
|
|
30
|
+
}
|
|
31
|
+
text = text.trim();
|
|
32
|
+
return text ? text.slice(0, limit) : undefined;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* 取这一条 SSE 里的「首个有效增量」。
|
|
36
|
+
* 推理模型(实测 deepseek-v4.1-flash)先吐 reasoning_content 再吐 content,
|
|
37
|
+
* 只认 content 会把首 Token 耗时算成总耗时。
|
|
38
|
+
*/
|
|
39
|
+
function pickDelta(payload) {
|
|
40
|
+
const choice = payload?.choices?.[0];
|
|
41
|
+
const content = choice?.delta?.content
|
|
42
|
+
?? choice?.delta?.reasoning_content
|
|
43
|
+
?? choice?.message?.content;
|
|
44
|
+
return typeof content === 'string' ? content : '';
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* 用 sk- 调用令牌发一条最短对话请求,测量总耗时与首 Token 耗时。
|
|
48
|
+
* 走 relay 的 OpenAI 兼容端点 POST /v1/chat/completions(不是 /api/* 面板接口)。
|
|
49
|
+
* token 只出现在请求头里,任何报错都会先 sanitize。
|
|
50
|
+
*/
|
|
51
|
+
/**
|
|
52
|
+
* GET /v1/models —— relay 端点的模型清单,用 sk- 调用令牌即可读取(不需要面板 access_token)。
|
|
53
|
+
* 这是「管理员禁用渠道」的可用观测口径:
|
|
54
|
+
* 某个模型的渠道被全部禁用后,它会从这份清单里消失,重新启用后又会回来。
|
|
55
|
+
*/
|
|
56
|
+
async function listRelayModels(ctx, options) {
|
|
57
|
+
const url = (0, shared_1.resolveBaseUrl)(options.baseUrl) + '/v1/models';
|
|
58
|
+
try {
|
|
59
|
+
const response = await ctx.http(url, {
|
|
60
|
+
method: 'GET',
|
|
61
|
+
headers: { Authorization: `Bearer ${options.apiKey}`, Accept: 'application/json' },
|
|
62
|
+
timeout: options.timeout ?? 15000,
|
|
63
|
+
});
|
|
64
|
+
const payload = response.data;
|
|
65
|
+
const models = (payload?.data ?? [])
|
|
66
|
+
.map(item => (typeof item?.id === 'string' ? item.id : ''))
|
|
67
|
+
.filter(Boolean);
|
|
68
|
+
return { ok: true, models, status: response.status };
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
const status = error?.response?.status;
|
|
72
|
+
const hint = status === 404 ? `(404:请确认 baseUrl 只填站点根地址;本次实际请求 ${url})` : '';
|
|
73
|
+
return {
|
|
74
|
+
ok: false,
|
|
75
|
+
models: [],
|
|
76
|
+
status: status ?? 0,
|
|
77
|
+
error: (0, shared_1.sanitize)(String(error?.message ?? '请求失败') + hint, options.apiKey),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async function relayTest(ctx, options) {
|
|
82
|
+
const url = (0, shared_1.resolveBaseUrl)(options.baseUrl) + '/v1/chat/completions';
|
|
83
|
+
const body = {
|
|
84
|
+
model: options.model,
|
|
85
|
+
messages: [{ role: 'user', content: options.prompt || 'hi' }],
|
|
86
|
+
max_tokens: options.maxTokens ?? 16,
|
|
87
|
+
stream: true,
|
|
88
|
+
};
|
|
89
|
+
const started = Date.now();
|
|
90
|
+
let output = '';
|
|
91
|
+
try {
|
|
92
|
+
const response = await ctx.http(url, {
|
|
93
|
+
method: 'POST',
|
|
94
|
+
headers: {
|
|
95
|
+
Authorization: `Bearer ${options.apiKey}`,
|
|
96
|
+
'Content-Type': 'application/json',
|
|
97
|
+
Accept: 'text/event-stream',
|
|
98
|
+
},
|
|
99
|
+
data: body,
|
|
100
|
+
responseType: 'stream',
|
|
101
|
+
timeout: options.timeout ?? 30000,
|
|
102
|
+
});
|
|
103
|
+
const status = response.status;
|
|
104
|
+
const stream = response.data;
|
|
105
|
+
if (!stream)
|
|
106
|
+
throw new shared_1.NewApiError('上游没有返回响应体');
|
|
107
|
+
let firstTokenMs = 0;
|
|
108
|
+
const decoder = new TextDecoder();
|
|
109
|
+
let buffer = '';
|
|
110
|
+
const consume = (text) => {
|
|
111
|
+
buffer += text;
|
|
112
|
+
const lines = buffer.split('\n');
|
|
113
|
+
buffer = lines.pop() ?? '';
|
|
114
|
+
for (const raw of lines) {
|
|
115
|
+
const line = raw.trim();
|
|
116
|
+
if (!line || line.startsWith(':'))
|
|
117
|
+
continue;
|
|
118
|
+
const payload = line.startsWith('data:') ? line.slice(5).trim() : line;
|
|
119
|
+
if (!payload || payload === '[DONE]' || !payload.startsWith('{'))
|
|
120
|
+
continue;
|
|
121
|
+
try {
|
|
122
|
+
const delta = pickDelta(JSON.parse(payload));
|
|
123
|
+
if (!delta)
|
|
124
|
+
continue;
|
|
125
|
+
if (!firstTokenMs)
|
|
126
|
+
firstTokenMs = Date.now() - started;
|
|
127
|
+
output += delta;
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
// 忽略 SSE 心跳等非 JSON 行
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
const reader = stream.getReader?.();
|
|
135
|
+
if (reader) {
|
|
136
|
+
while (true) {
|
|
137
|
+
const { done, value } = await reader.read();
|
|
138
|
+
if (done)
|
|
139
|
+
break;
|
|
140
|
+
if (value)
|
|
141
|
+
consume(decoder.decode(value, { stream: true }));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
for await (const chunk of stream)
|
|
146
|
+
consume(decoder.decode(chunk, { stream: true }));
|
|
147
|
+
}
|
|
148
|
+
consume(decoder.decode());
|
|
149
|
+
const totalMs = Date.now() - started;
|
|
150
|
+
return {
|
|
151
|
+
ok: true,
|
|
152
|
+
model: options.model,
|
|
153
|
+
firstTokenMs: firstTokenMs || totalMs,
|
|
154
|
+
totalMs,
|
|
155
|
+
status,
|
|
156
|
+
preview: output.slice(0, 40) || undefined,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
const totalMs = Date.now() - started;
|
|
161
|
+
const status = error?.response?.status;
|
|
162
|
+
const raw = error?.response?.data;
|
|
163
|
+
const detail = typeof raw === 'string' ? raw : await readErrorBody(raw);
|
|
164
|
+
const base = detail ? `${detail}` : String(error?.message ?? '请求失败');
|
|
165
|
+
// 404 几乎都是 baseUrl 多写了 /v1 或 /api,直接把排查方向写进错误里
|
|
166
|
+
const hint = status === 404
|
|
167
|
+
? `(404:请确认 baseUrl 只填站点根地址、不带 /v1 或 /api;本次实际请求 ${url})`
|
|
168
|
+
: '';
|
|
169
|
+
return {
|
|
170
|
+
ok: false,
|
|
171
|
+
model: options.model,
|
|
172
|
+
firstTokenMs: totalMs,
|
|
173
|
+
totalMs,
|
|
174
|
+
status: status ?? 0,
|
|
175
|
+
error: (0, shared_1.sanitize)(base + hint, options.apiKey),
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
/**
|
|
3
|
+
* 站点 URL 归一化:补全协议、去掉尾部斜杠,并剥掉误粘进来的 /v1、/api 后缀。
|
|
4
|
+
* 插件自己会拼 /api/status、/v1/chat/completions,用户多写一段就会变成
|
|
5
|
+
* /v1/v1/chat/completions 这类 404 —— 这是最常见的配置错误,直接在这里吃掉。
|
|
6
|
+
*/
|
|
7
|
+
export declare function resolveBaseUrl(input: string): string;
|
|
8
|
+
/**
|
|
9
|
+
* 把令牌从任意文本里抹掉。所有对外报错、日志、卡片都必须先过这一层,
|
|
10
|
+
* 保证 access_token / PAT / sk- 调用令牌不会泄漏。
|
|
11
|
+
*/
|
|
12
|
+
export declare function sanitize(message: string, ...secrets: Array<string | undefined>): string;
|
|
13
|
+
export declare class NewApiError extends Error {
|
|
14
|
+
readonly status?: number | undefined;
|
|
15
|
+
readonly code?: string | undefined;
|
|
16
|
+
constructor(message: string, status?: number | undefined, code?: string | undefined);
|
|
17
|
+
}
|
|
18
|
+
export interface ApiClientOptions {
|
|
19
|
+
baseUrl: string;
|
|
20
|
+
token?: string;
|
|
21
|
+
/**
|
|
22
|
+
* 面板用户 ID。老版本 New API(v0.13 及以前)的 UserAuth / AdminAuth 除了
|
|
23
|
+
* Authorization 之外还强制要求 `New-Api-User` 头,且必须等于令牌所属用户 ID;
|
|
24
|
+
* 不带会直接 401「未提供 New-Api-User」。v1.0.0-rc 起该头不再被读取,带上也无副作用。
|
|
25
|
+
*/
|
|
26
|
+
userId?: number;
|
|
27
|
+
timeout?: number;
|
|
28
|
+
}
|
|
29
|
+
export interface ApiRequestOptions {
|
|
30
|
+
method?: 'GET' | 'POST';
|
|
31
|
+
query?: Record<string, string | number | boolean | string[] | null | undefined>;
|
|
32
|
+
body?: unknown;
|
|
33
|
+
/** 传入则覆盖默认令牌;传 null 表示本次不带 Authorization */
|
|
34
|
+
authorization?: string | null;
|
|
35
|
+
timeout?: number;
|
|
36
|
+
/** 以 ReadableStream 形式返回原始响应体(relay 流式测试用) */
|
|
37
|
+
stream?: boolean;
|
|
38
|
+
/**
|
|
39
|
+
* 返回整个响应体而不是 envelope.data。
|
|
40
|
+
* 用于 /api/pricing 这类「业务数据与 data 同级」的接口:
|
|
41
|
+
* 它的 vendors / group_ratio / usable_group 都在 success 旁边,不是 data 的字段。
|
|
42
|
+
*/
|
|
43
|
+
raw?: boolean;
|
|
44
|
+
}
|
|
45
|
+
export interface ApiResponse<T> {
|
|
46
|
+
data: T;
|
|
47
|
+
latencyMs: number;
|
|
48
|
+
status: number;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* 统一请求入口。所有 New API 面板接口都走这里:
|
|
52
|
+
* 强制 JSON、记录耗时、把 HTTP 状态映射成人能看懂的中文提示,且不泄漏令牌。
|
|
53
|
+
*/
|
|
54
|
+
export declare function request<T = unknown>(ctx: Context, options: ApiClientOptions, path: string, req?: ApiRequestOptions): Promise<ApiResponse<T>>;
|
|
55
|
+
/** 探测某个接口的可达性与耗时,不抛错(status 指令用) */
|
|
56
|
+
export declare function probe(ctx: Context, options: ApiClientOptions, path: string): Promise<{
|
|
57
|
+
ok: boolean;
|
|
58
|
+
latencyMs: number;
|
|
59
|
+
error?: string;
|
|
60
|
+
}>;
|