dsh-sub2api 0.1.7 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/README.md +143 -100
- package/lib/adapter.js +33 -1
- package/lib/client.js +324 -90
- package/lib/commands.js +185 -0
- package/lib/config.js +4 -1
- package/lib/constants.js +31 -0
- package/lib/index.js +20 -9
- package/lib/panel-store.js +151 -0
- package/lib/routes.js +94 -2
- package/lib/schema.js +2 -0
- package/lib/sub2api/catalog.js +63 -16
- package/package.json +5 -3
- package/lib/selection.js +0 -66
package/lib/commands.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/sub2api` — the account's state without opening the panel.
|
|
3
|
+
*
|
|
4
|
+
* A command runs on the host and answers with text, so it works in the
|
|
5
|
+
* terminal client too, where the settings page has no surface.
|
|
6
|
+
* @module dsh-sub2api/commands
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { maskSecret } from "./util.js";
|
|
10
|
+
|
|
11
|
+
const HELP = [
|
|
12
|
+
"用法:/sub2api [status|models|balance|recharge]",
|
|
13
|
+
" status 账号、密钥、余额与模型数量(默认)",
|
|
14
|
+
" models 列出对话里可选的模型",
|
|
15
|
+
" balance 只看余额与订阅",
|
|
16
|
+
" recharge 给出充值入口",
|
|
17
|
+
].join("\n");
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {object} deps
|
|
21
|
+
* @param {import("./sub2api/api.js").Sub2ApiApi} deps.api
|
|
22
|
+
* @param {import("./sub2api/session.js").SessionStore} deps.session
|
|
23
|
+
* @param {import("./sub2api/catalog.js").ModelCatalog} deps.catalog
|
|
24
|
+
* @param {() => any} deps.cfg
|
|
25
|
+
* @returns {{name: string, description: string, input: {hint: string}, handler: Function}}
|
|
26
|
+
*/
|
|
27
|
+
export function commandDefinition(deps) {
|
|
28
|
+
return {
|
|
29
|
+
name: "sub2api",
|
|
30
|
+
description: "Sub2API 中转站:账号、密钥、余额与可用模型",
|
|
31
|
+
input: { hint: "[status|models|balance|recharge]" },
|
|
32
|
+
handler: async (invocation) => {
|
|
33
|
+
const verb = String(invocation?.rawInput ?? "").trim().split(/\s+/)[0]?.toLowerCase() ?? "";
|
|
34
|
+
try {
|
|
35
|
+
if (verb === "help" || verb === "-h" || verb === "--help") {
|
|
36
|
+
return { kind: "success", text: HELP };
|
|
37
|
+
}
|
|
38
|
+
if (verb === "recharge") return { kind: "success", text: await rechargeText(deps) };
|
|
39
|
+
if (verb === "models") return { kind: "success", text: await modelsText(deps) };
|
|
40
|
+
if (verb === "balance") return { kind: "success", text: await balanceText(deps) };
|
|
41
|
+
return { kind: "success", text: await statusText(deps) };
|
|
42
|
+
} catch (error) {
|
|
43
|
+
return {
|
|
44
|
+
kind: "error",
|
|
45
|
+
text: `Sub2API:${error instanceof Error ? error.message : String(error)}`,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Register the command when the host has a command runtime.
|
|
54
|
+
* @param {any} ctx
|
|
55
|
+
* @param {object} deps
|
|
56
|
+
*/
|
|
57
|
+
export function applyCommands(ctx, deps) {
|
|
58
|
+
const commands = safeGet(ctx, "commands");
|
|
59
|
+
if (commands === undefined || typeof commands.register !== "function") return undefined;
|
|
60
|
+
return commands.register(commandDefinition(deps));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function statusText(deps) {
|
|
64
|
+
const session = await deps.session.read();
|
|
65
|
+
const apiKey = await deps.session.apiKey();
|
|
66
|
+
await deps.catalog.load();
|
|
67
|
+
|
|
68
|
+
if (session === undefined) {
|
|
69
|
+
return [
|
|
70
|
+
"Sub2API:尚未登录。",
|
|
71
|
+
`在 DSH 的 设置 → Sub2API 里用一个邮箱和密码登录或注册即可(${deps.cfg().apiBase})。`,
|
|
72
|
+
].join("\n");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const token = await deps.session.accessToken().catch(() => undefined);
|
|
76
|
+
const profile = token ? await safe(() => deps.api.profile(token)) : undefined;
|
|
77
|
+
const models = deps.catalog.visible();
|
|
78
|
+
|
|
79
|
+
const lines = [
|
|
80
|
+
`Sub2API · ${deps.cfg().apiBase}`,
|
|
81
|
+
`账号 ${profile?.email ?? session.email ?? "已登录"}`,
|
|
82
|
+
`余额 ${money(profile?.balance)}`,
|
|
83
|
+
`密钥 ${apiKey ? maskSecret(apiKey) : "尚未创建"}`,
|
|
84
|
+
`模型 ${models.length} 个可选(上游共 ${deps.catalog.models.length})`,
|
|
85
|
+
];
|
|
86
|
+
|
|
87
|
+
const catalogError = deps.catalog.lastError;
|
|
88
|
+
if (catalogError) lines.push(`模型状态 ${catalogError.message}`);
|
|
89
|
+
|
|
90
|
+
const subscription = token ? await safe(() => deps.api.subscriptionSummary(token)) : undefined;
|
|
91
|
+
const active = subscription?.subscriptions;
|
|
92
|
+
if (Array.isArray(active) && active.length > 0) {
|
|
93
|
+
lines.push(
|
|
94
|
+
`订阅 ${active
|
|
95
|
+
.map((entry) => `${entry.group_name || "订阅"}(剩余 ${entry.days_remaining ?? "?"} 天)`)
|
|
96
|
+
.join("、")}`,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
lines.push("", "更多:/sub2api models · /sub2api balance · /sub2api recharge");
|
|
100
|
+
return lines.join("\n");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function balanceText(deps) {
|
|
104
|
+
const token = await deps.session.accessToken();
|
|
105
|
+
const [profile, subscription] = await Promise.all([
|
|
106
|
+
deps.api.profile(token).catch(() => undefined),
|
|
107
|
+
deps.api.subscriptionSummary(token).catch(() => undefined),
|
|
108
|
+
]);
|
|
109
|
+
const lines = [`余额 ${money(profile?.balance)}`];
|
|
110
|
+
const active = subscription?.subscriptions;
|
|
111
|
+
if (Array.isArray(active) && active.length > 0) {
|
|
112
|
+
for (const entry of active) {
|
|
113
|
+
lines.push(`${entry.group_name || "订阅"} 剩余 ${entry.days_remaining ?? "?"} 天`);
|
|
114
|
+
if (entry.daily_progress !== null && entry.daily_progress !== undefined) {
|
|
115
|
+
lines.push(` 日用量 ${percent(entry.daily_progress)} 周 ${percent(entry.weekly_progress)} 月 ${percent(entry.monthly_progress)}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return lines.join("\n");
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function modelsText(deps) {
|
|
123
|
+
await deps.catalog.load();
|
|
124
|
+
const models = deps.catalog.visible();
|
|
125
|
+
if (models.length === 0) {
|
|
126
|
+
const reason = deps.catalog.lastError?.message;
|
|
127
|
+
return reason
|
|
128
|
+
? `没有可用模型:${reason}`
|
|
129
|
+
: "没有可用模型。登录后在 设置 → Sub2API 里点「刷新模型」。";
|
|
130
|
+
}
|
|
131
|
+
const lines = models.map((model) => {
|
|
132
|
+
const bits = [`${Math.round((model.contextWindow ?? 0) / 1000)}k`];
|
|
133
|
+
if (model.vision) bits.push("图片");
|
|
134
|
+
if (model.contextSource === "default") bits.push("默认容量");
|
|
135
|
+
return `- ${model.id} ${bits.join(" · ")}`;
|
|
136
|
+
});
|
|
137
|
+
return [`共 ${models.length} 个模型:`, ...lines].join("\n");
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function rechargeText(deps) {
|
|
141
|
+
const session = await deps.session.read();
|
|
142
|
+
const userId = session?.user?.id;
|
|
143
|
+
const token = await deps.session.accessToken().catch(() => undefined);
|
|
144
|
+
if (!session || !token || userId === undefined) {
|
|
145
|
+
return "尚未登录,无法生成充值入口。";
|
|
146
|
+
}
|
|
147
|
+
// The panel opens this in a tab; the command can only hand over the URL.
|
|
148
|
+
const url = new URL(`${deps.cfg().payBase}/embedded/sub-recharge`);
|
|
149
|
+
url.searchParams.set("user_id", String(userId));
|
|
150
|
+
url.searchParams.set("token", token);
|
|
151
|
+
url.searchParams.set("ui_mode", "embedded");
|
|
152
|
+
url.searchParams.set("lang", "zh");
|
|
153
|
+
return [
|
|
154
|
+
"充值入口(在浏览器打开):",
|
|
155
|
+
url.toString(),
|
|
156
|
+
"",
|
|
157
|
+
"注意:链接里带着访问令牌,用完即可关闭;面板里的「去支付」会替你处理这些。",
|
|
158
|
+
].join("\n");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function money(value) {
|
|
162
|
+
const n = Number(value);
|
|
163
|
+
return Number.isFinite(n) ? `$${n.toFixed(2)}` : "—";
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function percent(value) {
|
|
167
|
+
const n = Number(value);
|
|
168
|
+
return Number.isFinite(n) ? `${(n * 100).toFixed(0)}%` : "—";
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function safe(run) {
|
|
172
|
+
try {
|
|
173
|
+
return await run();
|
|
174
|
+
} catch {
|
|
175
|
+
return undefined;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function safeGet(ctx, name) {
|
|
180
|
+
try {
|
|
181
|
+
return ctx?.get?.(name);
|
|
182
|
+
} catch {
|
|
183
|
+
return undefined;
|
|
184
|
+
}
|
|
185
|
+
}
|
package/lib/config.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
|
|
11
11
|
import { join } from "node:path";
|
|
12
12
|
import { homedir } from "node:os";
|
|
13
|
-
import { API_KEY_REF, KEY_NAME, MODELS_CACHE_FILE, SELECTION_FILE } from "./constants.js";
|
|
13
|
+
import { API_KEY_REF, KEY_NAME, MODELS_CACHE_FILE, PANEL_FILE, SELECTION_FILE } from "./constants.js";
|
|
14
14
|
import { normalizeBaseUrl } from "./util.js";
|
|
15
15
|
|
|
16
16
|
/**
|
|
@@ -65,10 +65,13 @@ export function resolveConfig(config) {
|
|
|
65
65
|
field(config, "modelsCachePath", join(dshHome, MODELS_CACHE_FILE)),
|
|
66
66
|
),
|
|
67
67
|
selectionPath: String(field(config, "selectionPath", join(dshHome, SELECTION_FILE))),
|
|
68
|
+
panelPath: String(field(config, "panelPath", join(dshHome, PANEL_FILE))),
|
|
68
69
|
showSidebarQuota: field(config, "showSidebarQuota", false) === true,
|
|
69
70
|
visibleModels: toStringArray(field(config, "visibleModels", [])),
|
|
70
71
|
contextWindow: toPositiveInt(field(config, "contextWindow", undefined)),
|
|
71
72
|
defaultContextWindow: toPositiveInt(field(config, "defaultContextWindow", undefined)),
|
|
73
|
+
reasoningModels: toStringArray(field(config, "reasoningModels", [])),
|
|
74
|
+
defaultReasoningEffort: String(field(config, "defaultReasoningEffort", "")).trim() || undefined,
|
|
72
75
|
autoProvision: field(config, "autoProvision", true) !== false,
|
|
73
76
|
announceToAgent: field(config, "announceToAgent", true) !== false,
|
|
74
77
|
};
|
package/lib/constants.js
CHANGED
|
@@ -34,6 +34,9 @@ export const MODELS_CACHE_FILE = "sub2api-models.json";
|
|
|
34
34
|
/** Where the panel keeps the model allowlist (an empty list means "show all"). */
|
|
35
35
|
export const SELECTION_FILE = "sub2api-selection.json";
|
|
36
36
|
|
|
37
|
+
/** Where the panel keeps its allowlist and per-model capacity corrections. */
|
|
38
|
+
export const PANEL_FILE = "sub2api-panel.json";
|
|
39
|
+
|
|
37
40
|
/** How long a discovered catalog stays fresh before a background refresh. */
|
|
38
41
|
export const CATALOG_TTL_MS = 10 * 60 * 1000;
|
|
39
42
|
|
|
@@ -63,6 +66,34 @@ export const KNOWN_CONTEXT = [
|
|
|
63
66
|
{ match: "deepseek-flash", contextWindow: 1048576 },
|
|
64
67
|
];
|
|
65
68
|
|
|
69
|
+
/**
|
|
70
|
+
* The four selectable reasoning efforts of an OpenAI-compatible endpoint, from
|
|
71
|
+
* least to greatest. `body` is merged into the request when one is selected.
|
|
72
|
+
*/
|
|
73
|
+
export const STANDARD_EFFORTS = [
|
|
74
|
+
{ id: "minimal", name: "极低", body: { reasoning_effort: "minimal" } },
|
|
75
|
+
{ id: "low", name: "低", body: { reasoning_effort: "low" } },
|
|
76
|
+
{ id: "medium", name: "中", body: { reasoning_effort: "medium" } },
|
|
77
|
+
{ id: "high", name: "高", body: { reasoning_effort: "high" } },
|
|
78
|
+
];
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Model id fragments whose upstream accepts `reasoning_effort`.
|
|
82
|
+
*
|
|
83
|
+
* Only families with a documented or observed mapping belong here: an endpoint
|
|
84
|
+
* that does not know the field either ignores it (the selector then lies) or
|
|
85
|
+
* rejects the request. Anything else can be opted in through `reasoningModels`.
|
|
86
|
+
*/
|
|
87
|
+
export const REASONING_HINTS = [
|
|
88
|
+
"deepseek-v4",
|
|
89
|
+
"deepseek-flash",
|
|
90
|
+
"deepseek-reasoner",
|
|
91
|
+
"deepseek-r1",
|
|
92
|
+
"gpt-5",
|
|
93
|
+
"o3",
|
|
94
|
+
"o4",
|
|
95
|
+
];
|
|
96
|
+
|
|
66
97
|
/** Model id fragments that mark an image-capable model when the endpoint says nothing. */
|
|
67
98
|
export const VISION_HINTS = [
|
|
68
99
|
"gpt-4o",
|
package/lib/index.js
CHANGED
|
@@ -15,7 +15,8 @@ import { Sub2ApiAdapter } from "./adapter.js";
|
|
|
15
15
|
import { makeRoutes } from "./routes.js";
|
|
16
16
|
import { Sub2ApiApi } from "./sub2api/api.js";
|
|
17
17
|
import { ModelCatalog } from "./sub2api/catalog.js";
|
|
18
|
-
import {
|
|
18
|
+
import { PanelStore } from "./panel-store.js";
|
|
19
|
+
import { applyCommands } from "./commands.js";
|
|
19
20
|
import { SessionStore } from "./sub2api/session.js";
|
|
20
21
|
|
|
21
22
|
export { Config } from "./schema.js";
|
|
@@ -57,9 +58,10 @@ export function apply(ctx, rawConfig = {}) {
|
|
|
57
58
|
apiKeyEnv: () => cfg().apiKeyEnv,
|
|
58
59
|
});
|
|
59
60
|
|
|
60
|
-
/** Panel-
|
|
61
|
-
const
|
|
62
|
-
path: () => cfg().
|
|
61
|
+
/** Panel-owned state: the model allowlist and per-model capacity fixes. */
|
|
62
|
+
const panel = new PanelStore({
|
|
63
|
+
path: () => cfg().panelPath,
|
|
64
|
+
legacyPath: () => cfg().selectionPath,
|
|
63
65
|
logger,
|
|
64
66
|
});
|
|
65
67
|
|
|
@@ -84,9 +86,12 @@ export function apply(ctx, rawConfig = {}) {
|
|
|
84
86
|
api,
|
|
85
87
|
cachePath: () => cfg().modelsCachePath,
|
|
86
88
|
visibleModels: () => cfg().visibleModels,
|
|
87
|
-
selection: () =>
|
|
89
|
+
selection: () => panel.visible(),
|
|
90
|
+
contextOverride: (id) => panel.contextOverride(id),
|
|
88
91
|
contextWindow: () => cfg().contextWindow,
|
|
89
92
|
defaultContextWindow: () => cfg().defaultContextWindow,
|
|
93
|
+
reasoningModels: () => cfg().reasoningModels,
|
|
94
|
+
defaultReasoningEffort: () => cfg().defaultReasoningEffort,
|
|
90
95
|
apiKey: () => session.apiKey(),
|
|
91
96
|
logger,
|
|
92
97
|
});
|
|
@@ -153,7 +158,7 @@ export function apply(ctx, rawConfig = {}) {
|
|
|
153
158
|
const routes = makeRoutes({
|
|
154
159
|
...deps,
|
|
155
160
|
cfg,
|
|
156
|
-
|
|
161
|
+
panel,
|
|
157
162
|
announceCatalog,
|
|
158
163
|
hostname: () => "dsh",
|
|
159
164
|
refreshCatalog: async (key) => {
|
|
@@ -166,7 +171,13 @@ export function apply(ctx, rawConfig = {}) {
|
|
|
166
171
|
return () => disposers.forEach((dispose) => dispose?.());
|
|
167
172
|
}, "sub2api: routes");
|
|
168
173
|
|
|
169
|
-
// 4)
|
|
174
|
+
// 4) Slash command for the terminal surface, where the panel does not exist.
|
|
175
|
+
ctx.effect(() => {
|
|
176
|
+
const dispose = applyCommands(ctx, { api, session, catalog, cfg });
|
|
177
|
+
return () => dispose?.();
|
|
178
|
+
}, "sub2api: command");
|
|
179
|
+
|
|
180
|
+
// 5) Agent tools: read-only status so the model can answer "how much is left".
|
|
170
181
|
// Imported lazily: a deployment without @deepseek-ai/dsh-tools still gets
|
|
171
182
|
// the provider and the panel, just no tools.
|
|
172
183
|
ctx.effect(() => {
|
|
@@ -188,13 +199,13 @@ export function apply(ctx, rawConfig = {}) {
|
|
|
188
199
|
};
|
|
189
200
|
}, "sub2api: tools");
|
|
190
201
|
|
|
191
|
-
//
|
|
202
|
+
// 6) Warm the catalog so the first picker open is not empty.
|
|
192
203
|
ctx.effect(() => {
|
|
193
204
|
void catalog.load().then(() => catalog.ensureFresh()).catch(() => {});
|
|
194
205
|
return () => {};
|
|
195
206
|
}, "sub2api: warm");
|
|
196
207
|
|
|
197
|
-
//
|
|
208
|
+
// 7) Agent guidance, so the model knows the panel exists.
|
|
198
209
|
ctx.effect(() => {
|
|
199
210
|
if (cfg().announceToAgent !== true) return () => {};
|
|
200
211
|
const systemPrompt = optional(ctx, "systemPrompt");
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Panel-owned state: which models to show, and per-model corrections.
|
|
3
|
+
*
|
|
4
|
+
* Neither belongs in the settings document. A list of upstream ids is not a
|
|
5
|
+
* schema, and a per-model number the operator never set is noise in a YAML
|
|
6
|
+
* file. Both live in one small sidecar next to the catalog cache instead.
|
|
7
|
+
* @module dsh-sub2api/panel-store
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
11
|
+
import { dirname } from "node:path";
|
|
12
|
+
|
|
13
|
+
/** @typedef {{visible: string[], contextOverrides: Record<string, number>}} PanelState */
|
|
14
|
+
|
|
15
|
+
export class PanelStore {
|
|
16
|
+
/**
|
|
17
|
+
* @param {object} deps
|
|
18
|
+
* @param {() => string} deps.path where the sidecar lives
|
|
19
|
+
* @param {() => string} [deps.legacyPath] older allowlist-only file to migrate from
|
|
20
|
+
* @param {{warn: Function}} [deps.logger]
|
|
21
|
+
*/
|
|
22
|
+
constructor(deps) {
|
|
23
|
+
this.deps = deps;
|
|
24
|
+
this.logger = deps.logger ?? { warn() {} };
|
|
25
|
+
/** @type {PanelState} */
|
|
26
|
+
this.state = { visible: [], contextOverrides: {} };
|
|
27
|
+
this.loaded = false;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async load() {
|
|
31
|
+
if (this.loaded) return this.state;
|
|
32
|
+
this.loaded = true;
|
|
33
|
+
|
|
34
|
+
const fromJson = async (path) => {
|
|
35
|
+
try {
|
|
36
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
37
|
+
} catch {
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const parsed = await fromJson(this.deps.path());
|
|
43
|
+
if (parsed !== undefined) {
|
|
44
|
+
this.state = normalizeState(parsed);
|
|
45
|
+
return this.state;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Migrate the allowlist-only file written by 0.1.6 and earlier.
|
|
49
|
+
const legacyPath = this.deps.legacyPath?.();
|
|
50
|
+
if (legacyPath) {
|
|
51
|
+
const legacy = await fromJson(legacyPath);
|
|
52
|
+
if (Array.isArray(legacy?.ids)) {
|
|
53
|
+
this.state = normalizeState({ visible: legacy.ids });
|
|
54
|
+
await this.#persist();
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return this.state;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** @returns {string[]} allowlist; empty means "show every model" */
|
|
61
|
+
visible() {
|
|
62
|
+
return this.state.visible;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** @param {string} id @returns {number | undefined} */
|
|
66
|
+
contextOverride(id) {
|
|
67
|
+
const value = this.state.contextOverrides[id];
|
|
68
|
+
return typeof value === "number" && value > 0 ? value : undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** @returns {Record<string, number>} */
|
|
72
|
+
contextOverrides() {
|
|
73
|
+
return { ...this.state.contextOverrides };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* @param {string[]} ids an empty list restores "show all"
|
|
78
|
+
* @returns {Promise<string[]>}
|
|
79
|
+
*/
|
|
80
|
+
async setVisible(ids) {
|
|
81
|
+
this.state.visible = cleanIds(ids);
|
|
82
|
+
await this.#persist();
|
|
83
|
+
return this.state.visible;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* @param {string} id model id
|
|
88
|
+
* @param {number | null | undefined} value positive tokens, or null/undefined to clear
|
|
89
|
+
* @returns {Promise<Record<string, number>>}
|
|
90
|
+
*/
|
|
91
|
+
async setContextOverride(id, value) {
|
|
92
|
+
const modelId = String(id ?? "").trim();
|
|
93
|
+
if (modelId === "") return this.contextOverrides();
|
|
94
|
+
|
|
95
|
+
if (value === null || value === undefined || value === "") {
|
|
96
|
+
delete this.state.contextOverrides[modelId];
|
|
97
|
+
} else {
|
|
98
|
+
const n = Number(value);
|
|
99
|
+
if (!Number.isFinite(n) || n <= 0) {
|
|
100
|
+
throw new TypeError(`上下文窗口必须是正数,收到 ${String(value)}`);
|
|
101
|
+
}
|
|
102
|
+
this.state.contextOverrides[modelId] = Math.trunc(n);
|
|
103
|
+
}
|
|
104
|
+
await this.#persist();
|
|
105
|
+
return this.contextOverrides();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
snapshot() {
|
|
109
|
+
return {
|
|
110
|
+
visible: [...this.state.visible],
|
|
111
|
+
contextOverrides: { ...this.state.contextOverrides },
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async #persist() {
|
|
116
|
+
try {
|
|
117
|
+
await mkdir(dirname(this.deps.path()), { recursive: true });
|
|
118
|
+
await writeFile(this.deps.path(), JSON.stringify(this.state, null, 0), { mode: 0o600 });
|
|
119
|
+
} catch (error) {
|
|
120
|
+
this.logger.warn?.(
|
|
121
|
+
`[sub2api] 面板状态保存失败:${error instanceof Error ? error.message : error}`,
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** @returns {PanelState} */
|
|
128
|
+
function normalizeState(raw) {
|
|
129
|
+
/** @type {PanelState} */
|
|
130
|
+
const state = { visible: [], contextOverrides: {} };
|
|
131
|
+
|
|
132
|
+
const list = Array.isArray(raw?.visible) ? raw.visible : Array.isArray(raw?.ids) ? raw.ids : [];
|
|
133
|
+
state.visible = cleanIds(list);
|
|
134
|
+
|
|
135
|
+
const overrides = raw?.contextOverrides;
|
|
136
|
+
if (overrides !== null && typeof overrides === "object") {
|
|
137
|
+
for (const [id, value] of Object.entries(overrides)) {
|
|
138
|
+
const n = Number(value);
|
|
139
|
+
if (typeof id === "string" && id !== "" && Number.isFinite(n) && n > 0) {
|
|
140
|
+
state.contextOverrides[id] = Math.trunc(n);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return state;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** @param {unknown} ids @returns {string[]} */
|
|
148
|
+
function cleanIds(ids) {
|
|
149
|
+
if (!Array.isArray(ids)) return [];
|
|
150
|
+
return [...new Set(ids.map((id) => String(id ?? "").trim()))].filter((id) => id !== "");
|
|
151
|
+
}
|
package/lib/routes.js
CHANGED
|
@@ -37,7 +37,7 @@ import {
|
|
|
37
37
|
* @returns {Array<{kind: "exact", path: string, handler: Function}>}
|
|
38
38
|
*/
|
|
39
39
|
export function makeRoutes(deps) {
|
|
40
|
-
const { api, session, catalog, cfg, logger,
|
|
40
|
+
const { api, session, catalog, cfg, logger, panel, announceCatalog } = deps;
|
|
41
41
|
|
|
42
42
|
/** Orders created by this process, keyed by the pay centre's order number. */
|
|
43
43
|
const orders = new Map();
|
|
@@ -59,6 +59,7 @@ export function makeRoutes(deps) {
|
|
|
59
59
|
hasKey: typeof apiKey === "string" && apiKey !== "",
|
|
60
60
|
keyMasked: maskSecret(apiKey),
|
|
61
61
|
models: catalog.snapshot(),
|
|
62
|
+
panel: panel.snapshot(),
|
|
62
63
|
showSidebarQuota: cfg().showSidebarQuota,
|
|
63
64
|
};
|
|
64
65
|
|
|
@@ -229,11 +230,102 @@ export function makeRoutes(deps) {
|
|
|
229
230
|
code: "unknown_model",
|
|
230
231
|
});
|
|
231
232
|
}
|
|
232
|
-
await
|
|
233
|
+
await panel.setVisible(ids);
|
|
233
234
|
announceCatalog?.();
|
|
234
235
|
return { ok: true, ids, models: catalog.snapshot() };
|
|
235
236
|
}),
|
|
236
237
|
|
|
238
|
+
/** Correct one model's capacity, or clear the correction with null. */
|
|
239
|
+
defineRoute("POST", `${ROUTE_PREFIX}/models/context`, async (body) => {
|
|
240
|
+
const id = String(body?.id ?? "").trim();
|
|
241
|
+
if (id === "") throw new Sub2ApiError("缺少模型 id", { code: "invalid_model" });
|
|
242
|
+
|
|
243
|
+
const known = catalog.snapshot().all.some((model) => model.id === id);
|
|
244
|
+
if (!known) throw new Sub2ApiError(`未知模型:${id}`, { code: "unknown_model" });
|
|
245
|
+
|
|
246
|
+
let value = body?.contextWindow;
|
|
247
|
+
if (value === null || value === undefined || value === "") {
|
|
248
|
+
value = null;
|
|
249
|
+
} else {
|
|
250
|
+
value = Number(value);
|
|
251
|
+
if (!Number.isFinite(value) || value < 1000) {
|
|
252
|
+
throw new Sub2ApiError("上下文窗口至少 1000 tokens", { code: "invalid_context" });
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
await panel.setContextOverride(id, value);
|
|
257
|
+
announceCatalog?.();
|
|
258
|
+
return { ok: true, overrides: panel.contextOverrides(), models: catalog.snapshot() };
|
|
259
|
+
}),
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* One checklist that names what is actually wrong, instead of leaving the
|
|
263
|
+
* user to guess from three separate cards.
|
|
264
|
+
*/
|
|
265
|
+
defineRoute("GET", `${ROUTE_PREFIX}/diagnose`, async () => {
|
|
266
|
+
const checks = [];
|
|
267
|
+
const add = (id, label, ok, detail, tone) => {
|
|
268
|
+
const entry = { id, label, ok };
|
|
269
|
+
if (detail !== undefined) entry.detail = detail;
|
|
270
|
+
if (tone !== undefined) entry.tone = tone;
|
|
271
|
+
checks.push(entry);
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
const stored = await session.read();
|
|
275
|
+
add("login", "登录状态", stored !== undefined, stored?.email ?? "未登录");
|
|
276
|
+
|
|
277
|
+
const token = stored === undefined ? undefined : await session.accessToken().catch(() => undefined);
|
|
278
|
+
add("token", "访问令牌", typeof token === "string", token ? "有效" : "无法获取");
|
|
279
|
+
|
|
280
|
+
const apiKey = await session.apiKey();
|
|
281
|
+
add("key", "API 密钥", typeof apiKey === "string" && apiKey !== "", apiKey ? maskSecret(apiKey) : "未创建");
|
|
282
|
+
|
|
283
|
+
if (token) {
|
|
284
|
+
const profile = await safe(() => api.profile(token));
|
|
285
|
+
const balance = Number(profile?.balance);
|
|
286
|
+
add(
|
|
287
|
+
"profile",
|
|
288
|
+
"账号资料",
|
|
289
|
+
profile !== undefined,
|
|
290
|
+
profile === undefined ? "读取失败" : `余额 ${Number.isFinite(balance) ? balance.toFixed(2) : "?"}`,
|
|
291
|
+
);
|
|
292
|
+
add(
|
|
293
|
+
"balance",
|
|
294
|
+
"余额",
|
|
295
|
+
Number.isFinite(balance) && balance > 0,
|
|
296
|
+
Number.isFinite(balance) ? String(balance) : "未知",
|
|
297
|
+
Number.isFinite(balance) && balance > 0 ? undefined : "warn",
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (typeof apiKey === "string" && apiKey !== "") {
|
|
302
|
+
const billing = await safe(() => api.gatewayBilling(apiKey));
|
|
303
|
+
const ungrouped = billing === undefined;
|
|
304
|
+
add(
|
|
305
|
+
"group",
|
|
306
|
+
"密钥分组",
|
|
307
|
+
!ungrouped,
|
|
308
|
+
ungrouped ? "网关拒绝了该密钥(可能未绑分组或已失效)" : "已绑定分组",
|
|
309
|
+
ungrouped ? "warn" : undefined,
|
|
310
|
+
);
|
|
311
|
+
|
|
312
|
+
const models = await safe(() => catalog.refresh(apiKey));
|
|
313
|
+
if (models === undefined) {
|
|
314
|
+
const error = catalog.lastError;
|
|
315
|
+
add("catalog", "模型目录", false, error?.message ?? "同步失败", "warn");
|
|
316
|
+
} else {
|
|
317
|
+
add("catalog", "模型目录", models > 0, `${models} 个模型`);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const failing = checks.filter((check) => !check.ok);
|
|
322
|
+
return {
|
|
323
|
+
checks,
|
|
324
|
+
ok: failing.length === 0,
|
|
325
|
+
summary: failing.length === 0 ? "一切正常" : `${failing.length} 项需要处理`,
|
|
326
|
+
};
|
|
327
|
+
}),
|
|
328
|
+
|
|
237
329
|
/** Recharge level 1: a signed-in URL the browser opens in a new tab. */
|
|
238
330
|
defineRoute("POST", `${ROUTE_PREFIX}/recharge/link`, async (body) => {
|
|
239
331
|
const stored = await session.read();
|
package/lib/schema.js
CHANGED
|
@@ -32,6 +32,8 @@ export const Config = z.object({
|
|
|
32
32
|
visibleModels: z.array(z.string()).description("只在这些模型 id 中显示;留空显示全部").volatile(),
|
|
33
33
|
contextWindow: count("强制覆盖所有模型的上下文窗口;留空则逐模型解析"),
|
|
34
34
|
defaultContextWindow: count("上游没有声明上下文窗口时使用的兜底值(默认 128000)"),
|
|
35
|
+
reasoningModels: z.array(z.string()).description("额外声明支持思考等级的模型 id 片段").volatile(),
|
|
36
|
+
defaultReasoningEffort: text("", "默认思考等级(minimal/low/medium/high);留空由上游决定"),
|
|
35
37
|
showSidebarQuota: z.boolean().default(false).description("在侧边栏显示余额卡片").volatile(),
|
|
36
38
|
autoProvision: z.boolean().default(true).description("登录后自动创建并保存密钥").volatile(),
|
|
37
39
|
announceToAgent: z.boolean().default(true).description("向 agent 注入插件说明").volatile(),
|