koishi-plugin-newapi-status 0.0.0-stage → 0.1.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 +20 -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 +144 -0
- package/lib/api/shared.d.ts +56 -0
- package/lib/api/shared.js +111 -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 +54 -0
- package/lib/config.js +100 -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 +522 -0
- package/lib/monitor.d.ts +38 -0
- package/lib/monitor.js +184 -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 +70 -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 +72 -4
- package/readme.md +227 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 acmuhan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -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,144 @@
|
|
|
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
|
+
* 取这一条 SSE 里的「首个有效增量」。
|
|
8
|
+
* 推理模型(实测 deepseek-v4.1-flash)先吐 reasoning_content 再吐 content,
|
|
9
|
+
* 只认 content 会把首 Token 耗时算成总耗时。
|
|
10
|
+
*/
|
|
11
|
+
function pickDelta(payload) {
|
|
12
|
+
const choice = payload?.choices?.[0];
|
|
13
|
+
const content = choice?.delta?.content
|
|
14
|
+
?? choice?.delta?.reasoning_content
|
|
15
|
+
?? choice?.message?.content;
|
|
16
|
+
return typeof content === 'string' ? content : '';
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* 用 sk- 调用令牌发一条最短对话请求,测量总耗时与首 Token 耗时。
|
|
20
|
+
* 走 relay 的 OpenAI 兼容端点 POST /v1/chat/completions(不是 /api/* 面板接口)。
|
|
21
|
+
* token 只出现在请求头里,任何报错都会先 sanitize。
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* GET /v1/models —— relay 端点的模型清单,用 sk- 调用令牌即可读取(不需要面板 access_token)。
|
|
25
|
+
* 这是「管理员禁用渠道」的可用观测口径:
|
|
26
|
+
* 某个模型的渠道被全部禁用后,它会从这份清单里消失,重新启用后又会回来。
|
|
27
|
+
*/
|
|
28
|
+
async function listRelayModels(ctx, options) {
|
|
29
|
+
const url = (0, shared_1.resolveBaseUrl)(options.baseUrl) + '/v1/models';
|
|
30
|
+
try {
|
|
31
|
+
const response = await ctx.http(url, {
|
|
32
|
+
method: 'GET',
|
|
33
|
+
headers: { Authorization: `Bearer ${options.apiKey}`, Accept: 'application/json' },
|
|
34
|
+
timeout: options.timeout ?? 15000,
|
|
35
|
+
});
|
|
36
|
+
const payload = response.data;
|
|
37
|
+
const models = (payload?.data ?? [])
|
|
38
|
+
.map(item => (typeof item?.id === 'string' ? item.id : ''))
|
|
39
|
+
.filter(Boolean);
|
|
40
|
+
return { ok: true, models, status: response.status };
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
const status = error?.response?.status;
|
|
44
|
+
return {
|
|
45
|
+
ok: false,
|
|
46
|
+
models: [],
|
|
47
|
+
status: status ?? 0,
|
|
48
|
+
error: (0, shared_1.sanitize)(String(error?.message ?? '请求失败'), options.apiKey),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async function relayTest(ctx, options) {
|
|
53
|
+
const url = (0, shared_1.resolveBaseUrl)(options.baseUrl) + '/v1/chat/completions';
|
|
54
|
+
const body = {
|
|
55
|
+
model: options.model,
|
|
56
|
+
messages: [{ role: 'user', content: options.prompt || 'hi' }],
|
|
57
|
+
max_tokens: options.maxTokens ?? 16,
|
|
58
|
+
stream: true,
|
|
59
|
+
};
|
|
60
|
+
const started = Date.now();
|
|
61
|
+
let output = '';
|
|
62
|
+
try {
|
|
63
|
+
const response = await ctx.http(url, {
|
|
64
|
+
method: 'POST',
|
|
65
|
+
headers: {
|
|
66
|
+
Authorization: `Bearer ${options.apiKey}`,
|
|
67
|
+
'Content-Type': 'application/json',
|
|
68
|
+
Accept: 'text/event-stream',
|
|
69
|
+
},
|
|
70
|
+
data: body,
|
|
71
|
+
responseType: 'stream',
|
|
72
|
+
timeout: options.timeout ?? 30000,
|
|
73
|
+
});
|
|
74
|
+
const status = response.status;
|
|
75
|
+
const stream = response.data;
|
|
76
|
+
if (!stream)
|
|
77
|
+
throw new shared_1.NewApiError('上游没有返回响应体');
|
|
78
|
+
let firstTokenMs = 0;
|
|
79
|
+
const decoder = new TextDecoder();
|
|
80
|
+
let buffer = '';
|
|
81
|
+
const consume = (text) => {
|
|
82
|
+
buffer += text;
|
|
83
|
+
const lines = buffer.split('\n');
|
|
84
|
+
buffer = lines.pop() ?? '';
|
|
85
|
+
for (const raw of lines) {
|
|
86
|
+
const line = raw.trim();
|
|
87
|
+
if (!line || line.startsWith(':'))
|
|
88
|
+
continue;
|
|
89
|
+
const payload = line.startsWith('data:') ? line.slice(5).trim() : line;
|
|
90
|
+
if (!payload || payload === '[DONE]' || !payload.startsWith('{'))
|
|
91
|
+
continue;
|
|
92
|
+
try {
|
|
93
|
+
const delta = pickDelta(JSON.parse(payload));
|
|
94
|
+
if (!delta)
|
|
95
|
+
continue;
|
|
96
|
+
if (!firstTokenMs)
|
|
97
|
+
firstTokenMs = Date.now() - started;
|
|
98
|
+
output += delta;
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
// 忽略 SSE 心跳等非 JSON 行
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
const reader = stream.getReader?.();
|
|
106
|
+
if (reader) {
|
|
107
|
+
while (true) {
|
|
108
|
+
const { done, value } = await reader.read();
|
|
109
|
+
if (done)
|
|
110
|
+
break;
|
|
111
|
+
if (value)
|
|
112
|
+
consume(decoder.decode(value, { stream: true }));
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
for await (const chunk of stream)
|
|
117
|
+
consume(decoder.decode(chunk, { stream: true }));
|
|
118
|
+
}
|
|
119
|
+
consume(decoder.decode());
|
|
120
|
+
const totalMs = Date.now() - started;
|
|
121
|
+
return {
|
|
122
|
+
ok: true,
|
|
123
|
+
model: options.model,
|
|
124
|
+
firstTokenMs: firstTokenMs || totalMs,
|
|
125
|
+
totalMs,
|
|
126
|
+
status,
|
|
127
|
+
preview: output.slice(0, 40) || undefined,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
const totalMs = Date.now() - started;
|
|
132
|
+
const status = error?.response?.status;
|
|
133
|
+
const raw = error?.response?.data;
|
|
134
|
+
const message = typeof raw === 'string' ? raw : error?.message;
|
|
135
|
+
return {
|
|
136
|
+
ok: false,
|
|
137
|
+
model: options.model,
|
|
138
|
+
firstTokenMs: totalMs,
|
|
139
|
+
totalMs,
|
|
140
|
+
status: status ?? 0,
|
|
141
|
+
error: (0, shared_1.sanitize)(String(message ?? '请求失败'), options.apiKey),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
/** 站点 URL 归一化:去掉尾部斜杠,补全协议 */
|
|
3
|
+
export declare function resolveBaseUrl(input: string): string;
|
|
4
|
+
/**
|
|
5
|
+
* 把令牌从任意文本里抹掉。所有对外报错、日志、卡片都必须先过这一层,
|
|
6
|
+
* 保证 access_token / PAT / sk- 调用令牌不会泄漏。
|
|
7
|
+
*/
|
|
8
|
+
export declare function sanitize(message: string, ...secrets: Array<string | undefined>): string;
|
|
9
|
+
export declare class NewApiError extends Error {
|
|
10
|
+
readonly status?: number | undefined;
|
|
11
|
+
readonly code?: string | undefined;
|
|
12
|
+
constructor(message: string, status?: number | undefined, code?: string | undefined);
|
|
13
|
+
}
|
|
14
|
+
export interface ApiClientOptions {
|
|
15
|
+
baseUrl: string;
|
|
16
|
+
token?: string;
|
|
17
|
+
/**
|
|
18
|
+
* 面板用户 ID。老版本 New API(v0.13 及以前)的 UserAuth / AdminAuth 除了
|
|
19
|
+
* Authorization 之外还强制要求 `New-Api-User` 头,且必须等于令牌所属用户 ID;
|
|
20
|
+
* 不带会直接 401「未提供 New-Api-User」。v1.0.0-rc 起该头不再被读取,带上也无副作用。
|
|
21
|
+
*/
|
|
22
|
+
userId?: number;
|
|
23
|
+
timeout?: number;
|
|
24
|
+
}
|
|
25
|
+
export interface ApiRequestOptions {
|
|
26
|
+
method?: 'GET' | 'POST';
|
|
27
|
+
query?: Record<string, string | number | boolean | string[] | null | undefined>;
|
|
28
|
+
body?: unknown;
|
|
29
|
+
/** 传入则覆盖默认令牌;传 null 表示本次不带 Authorization */
|
|
30
|
+
authorization?: string | null;
|
|
31
|
+
timeout?: number;
|
|
32
|
+
/** 以 ReadableStream 形式返回原始响应体(relay 流式测试用) */
|
|
33
|
+
stream?: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* 返回整个响应体而不是 envelope.data。
|
|
36
|
+
* 用于 /api/pricing 这类「业务数据与 data 同级」的接口:
|
|
37
|
+
* 它的 vendors / group_ratio / usable_group 都在 success 旁边,不是 data 的字段。
|
|
38
|
+
*/
|
|
39
|
+
raw?: boolean;
|
|
40
|
+
}
|
|
41
|
+
export interface ApiResponse<T> {
|
|
42
|
+
data: T;
|
|
43
|
+
latencyMs: number;
|
|
44
|
+
status: number;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* 统一请求入口。所有 New API 面板接口都走这里:
|
|
48
|
+
* 强制 JSON、记录耗时、把 HTTP 状态映射成人能看懂的中文提示,且不泄漏令牌。
|
|
49
|
+
*/
|
|
50
|
+
export declare function request<T = unknown>(ctx: Context, options: ApiClientOptions, path: string, req?: ApiRequestOptions): Promise<ApiResponse<T>>;
|
|
51
|
+
/** 探测某个接口的可达性与耗时,不抛错(status 指令用) */
|
|
52
|
+
export declare function probe(ctx: Context, options: ApiClientOptions, path: string): Promise<{
|
|
53
|
+
ok: boolean;
|
|
54
|
+
latencyMs: number;
|
|
55
|
+
error?: string;
|
|
56
|
+
}>;
|