dsh-sub2api 0.1.6 → 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/CHANGELOG.md +24 -0
- package/README.md +128 -82
- package/lib/client.js +333 -83
- package/lib/commands.js +185 -0
- package/lib/config.js +3 -1
- package/lib/constants.js +23 -0
- package/lib/index.js +19 -9
- package/lib/panel-store.js +151 -0
- package/lib/routes.js +94 -2
- package/lib/schema.js +2 -1
- package/lib/sub2api/catalog.js +48 -6
- 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,9 +65,11 @@ 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)),
|
|
72
|
+
defaultContextWindow: toPositiveInt(field(config, "defaultContextWindow", undefined)),
|
|
71
73
|
autoProvision: field(config, "autoProvision", true) !== false,
|
|
72
74
|
announceToAgent: field(config, "announceToAgent", true) !== false,
|
|
73
75
|
};
|
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
|
|
|
@@ -43,6 +46,26 @@ export const TOKEN_REFRESH_LEAD_MS = 60 * 1000;
|
|
|
43
46
|
/** Default page size when listing API keys. */
|
|
44
47
|
export const KEY_PAGE_SIZE = 100;
|
|
45
48
|
|
|
49
|
+
/**
|
|
50
|
+
* Context window used when neither the endpoint nor the configuration says
|
|
51
|
+
* anything. DSH cannot compact a conversation without a capacity figure and
|
|
52
|
+
* refuses to switch to such a model, so "unknown" is not an option the adapter
|
|
53
|
+
* can afford to return.
|
|
54
|
+
*/
|
|
55
|
+
export const DEFAULT_CONTEXT_WINDOW = 128000;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Context windows measured against this gateway, keyed by model id fragment.
|
|
59
|
+
* Only families with direct evidence belong here: a figure larger than the real
|
|
60
|
+
* limit turns every long request into a 400, and a smaller one compacts early.
|
|
61
|
+
*/
|
|
62
|
+
export const KNOWN_CONTEXT = [
|
|
63
|
+
// Measured on sub.pscly.cc: 897,791 tokens accepted, 1,050,041 rejected with
|
|
64
|
+
// "maximum context length is 1048576 tokens".
|
|
65
|
+
{ match: "deepseek-v4.1-flash", contextWindow: 1048576 },
|
|
66
|
+
{ match: "deepseek-flash", contextWindow: 1048576 },
|
|
67
|
+
];
|
|
68
|
+
|
|
46
69
|
/** Model id fragments that mark an image-capable model when the endpoint says nothing. */
|
|
47
70
|
export const VISION_HINTS = [
|
|
48
71
|
"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,8 +86,10 @@ 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,
|
|
92
|
+
defaultContextWindow: () => cfg().defaultContextWindow,
|
|
89
93
|
apiKey: () => session.apiKey(),
|
|
90
94
|
logger,
|
|
91
95
|
});
|
|
@@ -152,7 +156,7 @@ export function apply(ctx, rawConfig = {}) {
|
|
|
152
156
|
const routes = makeRoutes({
|
|
153
157
|
...deps,
|
|
154
158
|
cfg,
|
|
155
|
-
|
|
159
|
+
panel,
|
|
156
160
|
announceCatalog,
|
|
157
161
|
hostname: () => "dsh",
|
|
158
162
|
refreshCatalog: async (key) => {
|
|
@@ -165,7 +169,13 @@ export function apply(ctx, rawConfig = {}) {
|
|
|
165
169
|
return () => disposers.forEach((dispose) => dispose?.());
|
|
166
170
|
}, "sub2api: routes");
|
|
167
171
|
|
|
168
|
-
// 4)
|
|
172
|
+
// 4) Slash command for the terminal surface, where the panel does not exist.
|
|
173
|
+
ctx.effect(() => {
|
|
174
|
+
const dispose = applyCommands(ctx, { api, session, catalog, cfg });
|
|
175
|
+
return () => dispose?.();
|
|
176
|
+
}, "sub2api: command");
|
|
177
|
+
|
|
178
|
+
// 5) Agent tools: read-only status so the model can answer "how much is left".
|
|
169
179
|
// Imported lazily: a deployment without @deepseek-ai/dsh-tools still gets
|
|
170
180
|
// the provider and the panel, just no tools.
|
|
171
181
|
ctx.effect(() => {
|
|
@@ -187,13 +197,13 @@ export function apply(ctx, rawConfig = {}) {
|
|
|
187
197
|
};
|
|
188
198
|
}, "sub2api: tools");
|
|
189
199
|
|
|
190
|
-
//
|
|
200
|
+
// 6) Warm the catalog so the first picker open is not empty.
|
|
191
201
|
ctx.effect(() => {
|
|
192
202
|
void catalog.load().then(() => catalog.ensureFresh()).catch(() => {});
|
|
193
203
|
return () => {};
|
|
194
204
|
}, "sub2api: warm");
|
|
195
205
|
|
|
196
|
-
//
|
|
206
|
+
// 7) Agent guidance, so the model knows the panel exists.
|
|
197
207
|
ctx.effect(() => {
|
|
198
208
|
if (cfg().announceToAgent !== true) return () => {};
|
|
199
209
|
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
|
@@ -30,7 +30,8 @@ export const Config = z.object({
|
|
|
30
30
|
streamIdleTimeoutMs: count("流式请求空闲超时(毫秒)").default(300000),
|
|
31
31
|
modelsCachePath: text("", "模型目录缓存路径;留空使用 $DSH_HOME/sub2api-models.json"),
|
|
32
32
|
visibleModels: z.array(z.string()).description("只在这些模型 id 中显示;留空显示全部").volatile(),
|
|
33
|
-
contextWindow: count("
|
|
33
|
+
contextWindow: count("强制覆盖所有模型的上下文窗口;留空则逐模型解析"),
|
|
34
|
+
defaultContextWindow: count("上游没有声明上下文窗口时使用的兜底值(默认 128000)"),
|
|
34
35
|
showSidebarQuota: z.boolean().default(false).description("在侧边栏显示余额卡片").volatile(),
|
|
35
36
|
autoProvision: z.boolean().default(true).description("登录后自动创建并保存密钥").volatile(),
|
|
36
37
|
announceToAgent: z.boolean().default(true).description("向 agent 注入插件说明").volatile(),
|
package/lib/sub2api/catalog.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
|
|
11
11
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
12
12
|
import { dirname } from "node:path";
|
|
13
|
-
import { CATALOG_TTL_MS, VISION_HINTS } from "../constants.js";
|
|
13
|
+
import { CATALOG_TTL_MS, DEFAULT_CONTEXT_WINDOW, KNOWN_CONTEXT, VISION_HINTS } from "../constants.js";
|
|
14
14
|
import { Sub2ApiError } from "../util.js";
|
|
15
15
|
|
|
16
16
|
/**
|
|
@@ -149,15 +149,45 @@ export class ModelCatalog {
|
|
|
149
149
|
return this.deps.selection?.() ?? [];
|
|
150
150
|
}
|
|
151
151
|
|
|
152
|
-
/**
|
|
152
|
+
/**
|
|
153
|
+
* Where a model's capacity came from, in precedence order.
|
|
154
|
+
* @param {ModelRecord} model
|
|
155
|
+
* @returns {{contextWindow: number, contextSource: "config"|"panel"|"upstream"|"known"|"default"}}
|
|
156
|
+
*/
|
|
157
|
+
resolveContext(model) {
|
|
158
|
+
const forced = this.deps.contextWindow();
|
|
159
|
+
if (forced !== undefined) return { contextWindow: forced, contextSource: "config" };
|
|
160
|
+
|
|
161
|
+
const override = this.deps.contextOverride?.(model.id);
|
|
162
|
+
if (override !== undefined) return { contextWindow: override, contextSource: "panel" };
|
|
163
|
+
|
|
164
|
+
if (model.contextWindow !== undefined) {
|
|
165
|
+
return { contextWindow: model.contextWindow, contextSource: "upstream" };
|
|
166
|
+
}
|
|
167
|
+
const known = knownContext(model.id);
|
|
168
|
+
if (known !== undefined) return { contextWindow: known, contextSource: "known" };
|
|
169
|
+
|
|
170
|
+
return {
|
|
171
|
+
contextWindow: this.deps.defaultContextWindow?.() ?? DEFAULT_CONTEXT_WINDOW,
|
|
172
|
+
contextSource: "default",
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Models as the picker should see them: allowlist applied and a context
|
|
178
|
+
* window always resolved.
|
|
179
|
+
*
|
|
180
|
+
* A model with no capacity figure is unusable here: the host's compaction
|
|
181
|
+
* refuses to switch to it ("no context capacity for <route>"), so the fall
|
|
182
|
+
* back chain is config → upstream → measured table → conservative default,
|
|
183
|
+
* and `contextSource` records which one answered.
|
|
184
|
+
*/
|
|
153
185
|
visible() {
|
|
154
186
|
const allow = this.allowed();
|
|
155
|
-
|
|
187
|
+
|
|
156
188
|
return this.models
|
|
157
189
|
.filter((model) => allow.length === 0 || allow.includes(model.id))
|
|
158
|
-
.map((model) =>
|
|
159
|
-
forcedContext === undefined ? model : { ...model, contextWindow: forcedContext },
|
|
160
|
-
);
|
|
190
|
+
.map((model) => ({ ...model, ...this.resolveContext(model) }));
|
|
161
191
|
}
|
|
162
192
|
|
|
163
193
|
/**
|
|
@@ -203,6 +233,7 @@ export class ModelCatalog {
|
|
|
203
233
|
id: model.id,
|
|
204
234
|
name: model.name,
|
|
205
235
|
contextWindow: model.contextWindow ?? null,
|
|
236
|
+
contextSource: model.contextSource ?? null,
|
|
206
237
|
maxTokens: model.maxTokens ?? null,
|
|
207
238
|
vision: model.vision === true,
|
|
208
239
|
ownedBy: model.ownedBy ?? null,
|
|
@@ -292,6 +323,17 @@ function normalizeOne(raw, id) {
|
|
|
292
323
|
return record;
|
|
293
324
|
}
|
|
294
325
|
|
|
326
|
+
/**
|
|
327
|
+
* A measured context window for a known family, when the endpoint omits one.
|
|
328
|
+
* @param {string} id
|
|
329
|
+
* @returns {number | undefined}
|
|
330
|
+
*/
|
|
331
|
+
export function knownContext(id) {
|
|
332
|
+
const lower = String(id).toLowerCase();
|
|
333
|
+
const hit = KNOWN_CONTEXT.find((entry) => lower.includes(entry.match));
|
|
334
|
+
return hit?.contextWindow;
|
|
335
|
+
}
|
|
336
|
+
|
|
295
337
|
/** A model id is the only reliable label; strip a provider prefix for display. */
|
|
296
338
|
function displayName(id) {
|
|
297
339
|
const tail = id.includes("/") ? id.slice(id.lastIndexOf("/") + 1) : id;
|