dsh-sub2api 0.0.0-stage → 0.1.4
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 +48 -0
- package/LICENSE +674 -0
- package/README.md +163 -2
- package/cordis.patch.yml +16 -0
- package/lib/adapter.js +205 -0
- package/lib/client.js +754 -0
- package/lib/config.js +86 -0
- package/lib/constants.js +64 -0
- package/lib/index.js +197 -0
- package/lib/pay.js +243 -0
- package/lib/routes.js +378 -0
- package/lib/schema.js +37 -0
- package/lib/sub2api/api.js +247 -0
- package/lib/sub2api/auth.js +106 -0
- package/lib/sub2api/catalog.js +330 -0
- package/lib/sub2api/provision.js +244 -0
- package/lib/sub2api/session.js +187 -0
- package/lib/tools.js +171 -0
- package/lib/util.js +225 -0
- package/package.json +76 -4
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Authentication: one form, two outcomes.
|
|
3
|
+
*
|
|
4
|
+
* The deployment has registration open and email verification off, so a user
|
|
5
|
+
* who has never signed up should not have to discover a separate "register"
|
|
6
|
+
* tab. The panel sends one email/password pair and this module tries login
|
|
7
|
+
* first; only a rejected credential falls through to registration.
|
|
8
|
+
*
|
|
9
|
+
* The important rule is the ordering: a wrong password on an existing account
|
|
10
|
+
* must never create a second account, and must not be reported as "no such
|
|
11
|
+
* account".
|
|
12
|
+
* @module dsh-sub2api/sub2api/auth
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { Sub2ApiError } from "../util.js";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @param {object} deps
|
|
19
|
+
* @param {import("./api.js").Sub2ApiApi} deps.api
|
|
20
|
+
* @param {string} deps.email
|
|
21
|
+
* @param {string} deps.password
|
|
22
|
+
* @param {string} [deps.promoCode]
|
|
23
|
+
* @param {boolean} [deps.allowRegister] when false, a rejected login is final
|
|
24
|
+
* @returns {Promise<{mode: "login" | "register", auth: any}>}
|
|
25
|
+
*/
|
|
26
|
+
export async function loginOrRegister(deps) {
|
|
27
|
+
const { api, email, password, promoCode, allowRegister = true } = deps;
|
|
28
|
+
|
|
29
|
+
try {
|
|
30
|
+
const auth = await api.login(email, password);
|
|
31
|
+
return { mode: "login", auth };
|
|
32
|
+
} catch (error) {
|
|
33
|
+
if (!isCredentialRejection(error)) throw translateLogin(error);
|
|
34
|
+
if (!allowRegister) throw new Sub2ApiError("邮箱或密码不正确", { code: "wrong_password" });
|
|
35
|
+
|
|
36
|
+
try {
|
|
37
|
+
const auth = await registerWithFallbacks(api, email, password, promoCode);
|
|
38
|
+
// Some deployments turn email verification on later. The account is
|
|
39
|
+
// created but unusable until the address is confirmed, and pretending
|
|
40
|
+
// otherwise would fail later with a confusing 401.
|
|
41
|
+
if (typeof auth?.access_token !== "string" || auth.access_token === "") {
|
|
42
|
+
throw new Sub2ApiError(
|
|
43
|
+
"注册成功,但这个站点要求邮箱验证:请先到邮箱点击确认链接,再回来用同一密码登录。",
|
|
44
|
+
{ code: "email_verification_required" },
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
return { mode: "register", auth };
|
|
48
|
+
} catch (registerError) {
|
|
49
|
+
// The address is taken, so the login rejection really was a bad password.
|
|
50
|
+
if (isEmailTaken(registerError)) {
|
|
51
|
+
throw new Sub2ApiError("这个邮箱已注册,密码不正确", { code: "wrong_password" });
|
|
52
|
+
}
|
|
53
|
+
throw registerError;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Some deployments require a username. Try the minimal body first, then add one
|
|
60
|
+
* derived from the address rather than making the user fill another field.
|
|
61
|
+
*/
|
|
62
|
+
async function registerWithFallbacks(api, email, password, promoCode) {
|
|
63
|
+
try {
|
|
64
|
+
return await api.register({ email, password, promoCode });
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (!mentionsField(error, "username")) throw error;
|
|
67
|
+
return api.register({ email, password, promoCode, username: usernameFromEmail(email) });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** A stable, readable username derived from the address local part. */
|
|
72
|
+
export function usernameFromEmail(email) {
|
|
73
|
+
const local = String(email).split("@")[0] ?? "";
|
|
74
|
+
const cleaned = local.replace(/[^a-zA-Z0-9_.-]/g, "").slice(0, 24);
|
|
75
|
+
return cleaned === "" ? `dsh${Date.now().toString(36)}` : cleaned;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Whether an error means "these credentials are wrong", as opposed to an outage. */
|
|
79
|
+
export function isCredentialRejection(error) {
|
|
80
|
+
if (!(error instanceof Sub2ApiError)) return false;
|
|
81
|
+
if (error.status === 401) return true;
|
|
82
|
+
if (error.status !== 400 && error.status !== 403 && error.status !== 422) return false;
|
|
83
|
+
return /invalid|incorrect|wrong|credential|password|email or password|密码|凭据|账号或密码/i.test(
|
|
84
|
+
error.message,
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Whether an error means the address already has an account. */
|
|
89
|
+
export function isEmailTaken(error) {
|
|
90
|
+
if (!(error instanceof Sub2ApiError)) return false;
|
|
91
|
+
return /exist|already|taken|registered|duplicate|已注册|已存在|重复/i.test(error.message);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Re-word a transport failure so the panel can say something actionable. */
|
|
95
|
+
function translateLogin(error) {
|
|
96
|
+
if (error instanceof Sub2ApiError && error.code === "network") {
|
|
97
|
+
return new Sub2ApiError("连不上 Sub2API,请检查网络或服务地址", { code: "network" });
|
|
98
|
+
}
|
|
99
|
+
return error;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Whether a validation error names one specific field. */
|
|
103
|
+
function mentionsField(error, field) {
|
|
104
|
+
if (!(error instanceof Sub2ApiError)) return false;
|
|
105
|
+
return new RegExp(field, "i").test(error.message);
|
|
106
|
+
}
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Upstream model catalog.
|
|
3
|
+
*
|
|
4
|
+
* The site is the source of truth: `/v1/models` returns whatever the operator
|
|
5
|
+
* has routed, and the panel must follow it without the user editing a list.
|
|
6
|
+
* The catalog is cached on disk so a restart shows models before the first
|
|
7
|
+
* network call, and refreshed on a TTL and on demand.
|
|
8
|
+
* @module dsh-sub2api/sub2api/catalog
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
12
|
+
import { dirname } from "node:path";
|
|
13
|
+
import { CATALOG_TTL_MS, VISION_HINTS } from "../constants.js";
|
|
14
|
+
import { Sub2ApiError } from "../util.js";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @typedef {object} ModelRecord
|
|
18
|
+
* @property {string} id upstream model id, the value a request names
|
|
19
|
+
* @property {string} name display name
|
|
20
|
+
* @property {string} [ownedBy]
|
|
21
|
+
* @property {number} [contextWindow]
|
|
22
|
+
* @property {number} [maxTokens]
|
|
23
|
+
* @property {boolean} [vision]
|
|
24
|
+
* @property {string} [description]
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
export class ModelCatalog {
|
|
28
|
+
/**
|
|
29
|
+
* @param {object} deps
|
|
30
|
+
* @param {import("./api.js").Sub2ApiApi} deps.api
|
|
31
|
+
* @param {() => string} deps.cachePath
|
|
32
|
+
* @param {() => (string | undefined)} deps.visibleModels allowlist, empty means all
|
|
33
|
+
* @param {() => (number | undefined)} deps.contextWindow forced context window
|
|
34
|
+
* @param {(apiKey: string) => Promise<string | undefined>} deps.apiKey resolves the stored key
|
|
35
|
+
* @param {{info: Function, warn: Function}} [deps.logger]
|
|
36
|
+
*/
|
|
37
|
+
constructor(deps) {
|
|
38
|
+
this.deps = deps;
|
|
39
|
+
this.logger = deps.logger ?? { info() {}, warn() {} };
|
|
40
|
+
/** @type {ModelRecord[]} */
|
|
41
|
+
this.models = [];
|
|
42
|
+
this.fetchedAt = 0;
|
|
43
|
+
this.loaded = false;
|
|
44
|
+
this.inflight = undefined;
|
|
45
|
+
/**
|
|
46
|
+
* Why the last refresh failed, kept for the panel. An empty picker with no
|
|
47
|
+
* explanation is the worst outcome: sub2api refuses `/v1/models` with
|
|
48
|
+
* `INSUFFICIENT_BALANCE` on a zero-balance account, and the user can only
|
|
49
|
+
* act on that if the reason is visible.
|
|
50
|
+
* @type {{code?: string, message: string, status?: number, at: number} | undefined}
|
|
51
|
+
*/
|
|
52
|
+
this.lastError = undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Read the disk cache once, so a cold start is not an empty picker. */
|
|
56
|
+
async load() {
|
|
57
|
+
if (this.loaded) return;
|
|
58
|
+
this.loaded = true;
|
|
59
|
+
try {
|
|
60
|
+
const text = await readFile(this.deps.cachePath(), "utf8");
|
|
61
|
+
const parsed = JSON.parse(text);
|
|
62
|
+
if (Array.isArray(parsed?.models)) {
|
|
63
|
+
this.models = parsed.models.filter(isModelRecord);
|
|
64
|
+
this.fetchedAt = Number(parsed.fetchedAt) || 0;
|
|
65
|
+
}
|
|
66
|
+
} catch {
|
|
67
|
+
// No cache yet is the normal first run.
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Whether the cached snapshot is older than the TTL. */
|
|
72
|
+
get stale() {
|
|
73
|
+
return Date.now() - this.fetchedAt > CATALOG_TTL_MS;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Refresh from the gateway and persist.
|
|
78
|
+
* @param {string} [apiKey] overrides the stored key (used right after provisioning)
|
|
79
|
+
* @param {AbortSignal} [signal]
|
|
80
|
+
* @returns {Promise<number>} how many models are now known
|
|
81
|
+
*/
|
|
82
|
+
async refresh(apiKey, signal) {
|
|
83
|
+
const explicit = typeof apiKey === "string" && apiKey !== "";
|
|
84
|
+
|
|
85
|
+
// Dedupe only among callers asking for the same thing. The warm-up runs
|
|
86
|
+
// with no key at all; letting it share this slot would poison a later
|
|
87
|
+
// explicit refresh with its "no key" failure.
|
|
88
|
+
if (this.inflight !== undefined && (!explicit || this.inflightKey === apiKey)) {
|
|
89
|
+
return this.inflight;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const key = explicit ? apiKey : await this.deps.apiKey();
|
|
93
|
+
this.inflightKey = key;
|
|
94
|
+
|
|
95
|
+
this.inflight = (async () => {
|
|
96
|
+
try {
|
|
97
|
+
if (!key) throw new Sub2ApiError("还没有可用的 API Key,无法同步模型", { code: "no_api_key" });
|
|
98
|
+
const payload = await this.deps.api.gatewayModels(key, signal);
|
|
99
|
+
const records = normalizeModels(payload);
|
|
100
|
+
if (records.length === 0) {
|
|
101
|
+
throw new Sub2ApiError("上游没有返回任何模型", { code: "empty_catalog" });
|
|
102
|
+
}
|
|
103
|
+
this.models = records;
|
|
104
|
+
this.fetchedAt = Date.now();
|
|
105
|
+
this.lastError = undefined;
|
|
106
|
+
await this.#persist();
|
|
107
|
+
this.logger.info?.(`[sub2api] 模型目录已同步:${records.length} 个`);
|
|
108
|
+
return records.length;
|
|
109
|
+
} catch (error) {
|
|
110
|
+
this.lastError = {
|
|
111
|
+
code: error instanceof Sub2ApiError ? error.code : undefined,
|
|
112
|
+
message: error instanceof Error ? error.message : String(error),
|
|
113
|
+
status: error instanceof Sub2ApiError ? error.status : undefined,
|
|
114
|
+
at: Date.now(),
|
|
115
|
+
};
|
|
116
|
+
throw error;
|
|
117
|
+
} finally {
|
|
118
|
+
this.inflight = undefined;
|
|
119
|
+
this.inflightKey = undefined;
|
|
120
|
+
}
|
|
121
|
+
})();
|
|
122
|
+
|
|
123
|
+
return this.inflight;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Refresh only when the snapshot is stale; failures keep the old snapshot. */
|
|
127
|
+
async ensureFresh(signal) {
|
|
128
|
+
await this.load();
|
|
129
|
+
if (!this.stale && this.models.length > 0) return this.models.length;
|
|
130
|
+
// Without a key there is nothing to ask the gateway; stay on the cache
|
|
131
|
+
// instead of recording a failure the user never triggered.
|
|
132
|
+
if ((await this.deps.apiKey()) === undefined) return this.models.length;
|
|
133
|
+
try {
|
|
134
|
+
return await this.refresh(undefined, signal);
|
|
135
|
+
} catch (error) {
|
|
136
|
+
this.logger.warn?.(`[sub2api] 模型同步失败,沿用缓存:${describe(error)}`);
|
|
137
|
+
return this.models.length;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Models as the picker should see them: allowlist applied, forced context honored. */
|
|
142
|
+
visible() {
|
|
143
|
+
const allow = this.deps.visibleModels() ?? [];
|
|
144
|
+
const forcedContext = this.deps.contextWindow();
|
|
145
|
+
return this.models
|
|
146
|
+
.filter((model) => allow.length === 0 || allow.includes(model.id))
|
|
147
|
+
.map((model) =>
|
|
148
|
+
forcedContext === undefined ? model : { ...model, contextWindow: forcedContext },
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The shape the reused transport wants (`OpenAiLlmModelConfig`).
|
|
154
|
+
* @returns {Array<Record<string, unknown>>}
|
|
155
|
+
*/
|
|
156
|
+
llmModels() {
|
|
157
|
+
return this.visible().map((model) => {
|
|
158
|
+
/** @type {Record<string, unknown>} */
|
|
159
|
+
const entry = { id: model.id, name: model.name };
|
|
160
|
+
if (model.contextWindow !== undefined) entry.contextWindow = model.contextWindow;
|
|
161
|
+
if (model.maxTokens !== undefined) entry.maxTokens = model.maxTokens;
|
|
162
|
+
if (model.vision === true) entry.vision = true;
|
|
163
|
+
return entry;
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The shape the host's model picker wants (`LlmModelInfo`). */
|
|
168
|
+
listModels(provider) {
|
|
169
|
+
return this.visible().map((model) => {
|
|
170
|
+
/** @type {Record<string, unknown>} */
|
|
171
|
+
const entry = {
|
|
172
|
+
provider,
|
|
173
|
+
id: model.id,
|
|
174
|
+
name: model.name,
|
|
175
|
+
inputModalities: model.vision === true ? ["text", "image"] : ["text"],
|
|
176
|
+
};
|
|
177
|
+
if (model.description) entry.description = model.description;
|
|
178
|
+
return entry;
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Snapshot for the panel: everything the user may need to judge a model. */
|
|
183
|
+
snapshot() {
|
|
184
|
+
return {
|
|
185
|
+
fetchedAt: this.fetchedAt,
|
|
186
|
+
stale: this.stale,
|
|
187
|
+
error: this.lastError ?? null,
|
|
188
|
+
needsRecharge: this.lastError?.code === "INSUFFICIENT_BALANCE",
|
|
189
|
+
models: this.visible().map((model) => ({
|
|
190
|
+
id: model.id,
|
|
191
|
+
name: model.name,
|
|
192
|
+
contextWindow: model.contextWindow ?? null,
|
|
193
|
+
maxTokens: model.maxTokens ?? null,
|
|
194
|
+
vision: model.vision === true,
|
|
195
|
+
ownedBy: model.ownedBy ?? null,
|
|
196
|
+
})),
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async #persist() {
|
|
201
|
+
const path = this.deps.cachePath();
|
|
202
|
+
try {
|
|
203
|
+
await mkdir(dirname(path), { recursive: true });
|
|
204
|
+
await writeFile(
|
|
205
|
+
path,
|
|
206
|
+
JSON.stringify({ fetchedAt: this.fetchedAt, models: this.models }, null, 0),
|
|
207
|
+
{ mode: 0o600 },
|
|
208
|
+
);
|
|
209
|
+
} catch (error) {
|
|
210
|
+
this.logger.warn?.(`[sub2api] 模型缓存写入失败:${describe(error)}`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Accept every shape an OpenAI-compatible `/v1/models` may reasonably return,
|
|
217
|
+
* including the sub2api envelope that is already unwrapped by `requestJson`.
|
|
218
|
+
* @param {any} payload
|
|
219
|
+
* @returns {ModelRecord[]}
|
|
220
|
+
*/
|
|
221
|
+
export function normalizeModels(payload) {
|
|
222
|
+
const list = Array.isArray(payload)
|
|
223
|
+
? payload
|
|
224
|
+
: Array.isArray(payload?.data)
|
|
225
|
+
? payload.data
|
|
226
|
+
: Array.isArray(payload?.models)
|
|
227
|
+
? payload.models
|
|
228
|
+
: Array.isArray(payload?.data?.data)
|
|
229
|
+
? payload.data.data
|
|
230
|
+
: [];
|
|
231
|
+
|
|
232
|
+
const seen = new Set();
|
|
233
|
+
const out = [];
|
|
234
|
+
for (const raw of list) {
|
|
235
|
+
const id = typeof raw === "string" ? raw : raw?.id;
|
|
236
|
+
if (typeof id !== "string" || id.trim() === "" || seen.has(id)) continue;
|
|
237
|
+
seen.add(id);
|
|
238
|
+
out.push(normalizeOne(raw, id.trim()));
|
|
239
|
+
}
|
|
240
|
+
out.sort((a, b) => a.id.localeCompare(b.id));
|
|
241
|
+
return out;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** @returns {ModelRecord} */
|
|
245
|
+
function normalizeOne(raw, id) {
|
|
246
|
+
/** @type {ModelRecord} */
|
|
247
|
+
const record = { id, name: displayName(id) };
|
|
248
|
+
if (typeof raw !== "object" || raw === null) return record;
|
|
249
|
+
|
|
250
|
+
if (typeof raw.owned_by === "string") record.ownedBy = raw.owned_by;
|
|
251
|
+
if (typeof raw.description === "string" && raw.description.trim() !== "") {
|
|
252
|
+
record.description = raw.description;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const context =
|
|
256
|
+
firstNumber(
|
|
257
|
+
raw.context_length,
|
|
258
|
+
raw.context_window,
|
|
259
|
+
raw.max_context_length,
|
|
260
|
+
raw.max_input_tokens,
|
|
261
|
+
raw.limits?.context_window,
|
|
262
|
+
) ?? undefined;
|
|
263
|
+
if (context !== undefined) record.contextWindow = context;
|
|
264
|
+
|
|
265
|
+
const maxTokens =
|
|
266
|
+
firstNumber(
|
|
267
|
+
raw.max_output_tokens,
|
|
268
|
+
raw.max_completion_tokens,
|
|
269
|
+
raw.max_tokens,
|
|
270
|
+
raw.limits?.max_output_tokens,
|
|
271
|
+
) ?? undefined;
|
|
272
|
+
if (maxTokens !== undefined) record.maxTokens = maxTokens;
|
|
273
|
+
|
|
274
|
+
const capabilities = raw.capabilities ?? raw.features ?? raw.modalities;
|
|
275
|
+
if (declaresVision(capabilities)) record.vision = true;
|
|
276
|
+
else if (declaresTextOnly(capabilities)) record.vision = false;
|
|
277
|
+
else if (VISION_HINTS.some((hint) => id.toLowerCase().includes(hint))) record.vision = true;
|
|
278
|
+
|
|
279
|
+
return record;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** A model id is the only reliable label; strip a provider prefix for display. */
|
|
283
|
+
function displayName(id) {
|
|
284
|
+
const tail = id.includes("/") ? id.slice(id.lastIndexOf("/") + 1) : id;
|
|
285
|
+
return tail === "" ? id : tail;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** First finite positive number among the candidates. */
|
|
289
|
+
function firstNumber(...values) {
|
|
290
|
+
for (const value of values) {
|
|
291
|
+
const n = typeof value === "number" ? value : Number(value);
|
|
292
|
+
if (Number.isFinite(n) && n > 0) return Math.trunc(n);
|
|
293
|
+
}
|
|
294
|
+
return undefined;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Whether a capability declaration says pictures are accepted. */
|
|
298
|
+
function declaresVision(capabilities) {
|
|
299
|
+
if (capabilities === undefined || capabilities === null) return false;
|
|
300
|
+
if (Array.isArray(capabilities)) {
|
|
301
|
+
return capabilities.some((item) => String(item).toLowerCase() === "image");
|
|
302
|
+
}
|
|
303
|
+
if (typeof capabilities === "object") {
|
|
304
|
+
if (capabilities.vision === true || capabilities.image === true) return true;
|
|
305
|
+
const inputs = capabilities.input_modalities ?? capabilities.inputs;
|
|
306
|
+
if (Array.isArray(inputs)) return inputs.some((item) => String(item).toLowerCase() === "image");
|
|
307
|
+
}
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** An explicit text-only declaration must beat the id heuristics. */
|
|
312
|
+
function declaresTextOnly(capabilities) {
|
|
313
|
+
if (capabilities === undefined || capabilities === null || Array.isArray(capabilities)) {
|
|
314
|
+
return false;
|
|
315
|
+
}
|
|
316
|
+
if (typeof capabilities !== "object") return false;
|
|
317
|
+
if (capabilities.vision === false || capabilities.image === false) return true;
|
|
318
|
+
const inputs = capabilities.input_modalities ?? capabilities.inputs;
|
|
319
|
+
return Array.isArray(inputs) && !inputs.some((item) => String(item).toLowerCase() === "image");
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Whether a cached entry still has the fields this module reads. */
|
|
323
|
+
function isModelRecord(value) {
|
|
324
|
+
return Boolean(value) && typeof value === "object" && typeof value.id === "string";
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** @param {unknown} error */
|
|
328
|
+
function describe(error) {
|
|
329
|
+
return error instanceof Error ? error.message : String(error);
|
|
330
|
+
}
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provisioning: turn a fresh login into a working provider.
|
|
3
|
+
*
|
|
4
|
+
* After a successful sign-in the plugin needs four things before the model
|
|
5
|
+
* picker can offer anything: the account snapshot, the groups the account may
|
|
6
|
+
* bind to, one API key in that group, and the upstream catalog behind it.
|
|
7
|
+
* Each step reports its own outcome so a partial failure still leaves a usable
|
|
8
|
+
* panel — a missing catalog is recoverable, a missing key is not.
|
|
9
|
+
* @module dsh-sub2api/sub2api/provision
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { Sub2ApiError } from "../util.js";
|
|
13
|
+
|
|
14
|
+
/** @typedef {{id: string, label: string, ok: boolean, detail?: string, error?: string}} ProvisionStep */
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @param {object} deps
|
|
18
|
+
* @param {import("./api.js").Sub2ApiApi} deps.api
|
|
19
|
+
* @param {(key: string) => Promise<void>} deps.saveApiKey
|
|
20
|
+
* @param {(apiKey: string) => Promise<number>} deps.refreshCatalog resolves the model count
|
|
21
|
+
* @param {string} deps.keyName name given to the provisioned key
|
|
22
|
+
* @param {number} [deps.groupId] forced group, overriding automatic selection
|
|
23
|
+
* @param {{info: Function, warn: Function}} [deps.logger]
|
|
24
|
+
* @param {string} deps.accessToken
|
|
25
|
+
* @returns {Promise<{steps: ProvisionStep[], key?: string, groupId?: number, models: number, ready: boolean}>}
|
|
26
|
+
*/
|
|
27
|
+
export async function provisionAccount(deps) {
|
|
28
|
+
const { api, accessToken, keyName } = deps;
|
|
29
|
+
const logger = deps.logger ?? { info() {}, warn() {} };
|
|
30
|
+
const steps = [];
|
|
31
|
+
|
|
32
|
+
// 1) Account snapshot. Balance is what the panel shows first, so a failure
|
|
33
|
+
// here degrades the header rather than blocking the flow.
|
|
34
|
+
const profile = await attempt(() => api.profile(accessToken));
|
|
35
|
+
steps.push(
|
|
36
|
+
profile.ok
|
|
37
|
+
? step("profile", "账号信息", true, profile.value?.email ?? undefined)
|
|
38
|
+
: step("profile", "账号信息", false, undefined, describe(profile.error)),
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
// 2) Groups decide where the key lives; the site may hand back none at all.
|
|
42
|
+
const groupsResult = await attempt(() => api.groups(accessToken));
|
|
43
|
+
const groups = groupsResult.ok && Array.isArray(groupsResult.value) ? groupsResult.value : [];
|
|
44
|
+
steps.push(
|
|
45
|
+
groupsResult.ok
|
|
46
|
+
? step("groups", "可用分组", true, groups.length === 0 ? "默认分组" : `${groups.length} 个`)
|
|
47
|
+
: step("groups", "可用分组", false, undefined, describe(groupsResult.error)),
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
// 3) An existing key with our name is reused, so re-login never piles up keys.
|
|
51
|
+
const keysResult = await attempt(() => api.listKeys(accessToken));
|
|
52
|
+
const existing = pickKey(
|
|
53
|
+
keysResult.ok ? (keysResult.value?.items ?? []) : [],
|
|
54
|
+
keyName,
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
let key = existing?.key;
|
|
58
|
+
let groupId = existing?.group_id ?? undefined;
|
|
59
|
+
|
|
60
|
+
if (typeof key === "string" && key !== "") {
|
|
61
|
+
steps.push(step("key", "API 密钥", true, `复用已有密钥 ${keyName}`));
|
|
62
|
+
} else {
|
|
63
|
+
const chosenGroup = chooseGroup({
|
|
64
|
+
forced: deps.groupId,
|
|
65
|
+
groups,
|
|
66
|
+
allowed: profile.ok ? profile.value?.allowed_groups : undefined,
|
|
67
|
+
});
|
|
68
|
+
const created = await attempt(() =>
|
|
69
|
+
api.createKey(accessToken, { name: keyName, groupId: chosenGroup }),
|
|
70
|
+
);
|
|
71
|
+
if (created.ok && typeof created.value?.key === "string" && created.value.key !== "") {
|
|
72
|
+
key = created.value.key;
|
|
73
|
+
groupId = created.value.group_id ?? chosenGroup ?? undefined;
|
|
74
|
+
steps.push(
|
|
75
|
+
step("key", "API 密钥", true, `已创建密钥 ${keyName}${groupLabel(groups, groupId)}`),
|
|
76
|
+
);
|
|
77
|
+
} else {
|
|
78
|
+
steps.push(
|
|
79
|
+
step(
|
|
80
|
+
"key",
|
|
81
|
+
"API 密钥",
|
|
82
|
+
false,
|
|
83
|
+
undefined,
|
|
84
|
+
created.ok ? "创建成功但未返回密钥值" : describe(created.error),
|
|
85
|
+
),
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// 4) Persist. Without this the adapter has no credential to resolve and every
|
|
91
|
+
// request fails, so it is the one step that gates `ready`.
|
|
92
|
+
if (typeof key === "string" && key !== "") {
|
|
93
|
+
const saved = await attempt(() => deps.saveApiKey(key));
|
|
94
|
+
steps.push(
|
|
95
|
+
saved.ok
|
|
96
|
+
? step("credential", "保存凭据", true, "已写入本机凭据库")
|
|
97
|
+
: step("credential", "保存凭据", false, undefined, describe(saved.error)),
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// 5) Catalog. A failure here is retryable from the panel, not fatal — and a
|
|
102
|
+
// zero-balance account is the expected case, not an error: sub2api answers
|
|
103
|
+
// `/v1/models` with INSUFFICIENT_BALANCE until the account is topped up.
|
|
104
|
+
let models = 0;
|
|
105
|
+
if (typeof key === "string" && key !== "") {
|
|
106
|
+
const catalog = await attempt(() => deps.refreshCatalog(key));
|
|
107
|
+
models = catalog.ok ? catalog.value : 0;
|
|
108
|
+
if (catalog.ok) {
|
|
109
|
+
steps.push(step("catalog", "同步模型", true, `${models} 个模型`));
|
|
110
|
+
} else if (isInsufficientBalance(catalog.error)) {
|
|
111
|
+
steps.push(
|
|
112
|
+
step("catalog", "同步模型", false, "余额不足", "充值后会自动同步模型", "warn"),
|
|
113
|
+
);
|
|
114
|
+
} else {
|
|
115
|
+
steps.push(step("catalog", "同步模型", false, undefined, describe(catalog.error)));
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const blocking = steps.filter(
|
|
120
|
+
(entry) => !entry.ok && (entry.id === "key" || entry.id === "credential"),
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
if (blocking.length > 0) {
|
|
124
|
+
logger.warn(`[sub2api] 自动开通未完成:${blocking.map((entry) => entry.error).join(";")}`);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return { steps, key, groupId, models, ready: blocking.length === 0 };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Reuse the key this plugin already made. Matching on name alone would reuse a
|
|
132
|
+
* key the user revoked, so status is checked too.
|
|
133
|
+
* @param {Array<any>} items
|
|
134
|
+
* @param {string} keyName
|
|
135
|
+
*/
|
|
136
|
+
export function pickKey(items, keyName) {
|
|
137
|
+
if (!Array.isArray(items)) return undefined;
|
|
138
|
+
return items.find(
|
|
139
|
+
(item) => item && item.name === keyName && item.status !== "inactive" && typeof item.key === "string",
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Pick the group a new key belongs to.
|
|
145
|
+
*
|
|
146
|
+
* Leaving it unset is not a neutral default: an ungrouped key is rejected by
|
|
147
|
+
* the gateway's permission check, so the catalog never loads and the panel
|
|
148
|
+
* shows a failure nobody can act on. The order is therefore explicit and always
|
|
149
|
+
* lands on a real group when one exists.
|
|
150
|
+
*
|
|
151
|
+
* Preference: the operator's forced id, the account's own allowed group, the
|
|
152
|
+
* only group on offer, then a group that speaks the protocol this plugin does
|
|
153
|
+
* (an OpenAI-compatible route cannot serve a message from a group whose
|
|
154
|
+
* platform is something else), then the first non-exclusive one.
|
|
155
|
+
* @param {{forced?: number, groups: any[], allowed?: number[]}} input
|
|
156
|
+
* @returns {number | undefined}
|
|
157
|
+
*/
|
|
158
|
+
export function chooseGroup(input) {
|
|
159
|
+
const { forced, groups, allowed } = input;
|
|
160
|
+
if (typeof forced === "number") return forced;
|
|
161
|
+
|
|
162
|
+
const available = (Array.isArray(groups) ? groups : []).filter(
|
|
163
|
+
(group) => group && typeof group.id === "number" && group.status !== "disabled",
|
|
164
|
+
);
|
|
165
|
+
if (available.length === 0) return undefined;
|
|
166
|
+
|
|
167
|
+
if (Array.isArray(allowed) && allowed.length > 0) {
|
|
168
|
+
const match = available.find((group) => allowed.includes(group.id));
|
|
169
|
+
if (match) return match.id;
|
|
170
|
+
}
|
|
171
|
+
if (available.length === 1) return available[0].id;
|
|
172
|
+
|
|
173
|
+
const sameProtocol = available.find(
|
|
174
|
+
(group) => String(group.platform ?? "").toLowerCase() === "openai",
|
|
175
|
+
);
|
|
176
|
+
if (sameProtocol) return sameProtocol.id;
|
|
177
|
+
|
|
178
|
+
const open = available.find((group) => group.is_exclusive !== true);
|
|
179
|
+
if (open) return open.id;
|
|
180
|
+
|
|
181
|
+
return available[0].id;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Render the group name for a step detail, when one is known. */
|
|
185
|
+
function groupLabel(groups, groupId) {
|
|
186
|
+
if (typeof groupId !== "number") return "";
|
|
187
|
+
const match = (Array.isArray(groups) ? groups : []).find((group) => group?.id === groupId);
|
|
188
|
+
return match?.name ? `(分组:${match.name})` : "";
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Whether a failure is the expected zero-balance state rather than a fault. */
|
|
192
|
+
export function isInsufficientBalance(error) {
|
|
193
|
+
return error instanceof Sub2ApiError && error.code === "INSUFFICIENT_BALANCE";
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* @param {string} id
|
|
198
|
+
* @param {string} label
|
|
199
|
+
* @param {boolean} ok
|
|
200
|
+
* @param {string} [detail]
|
|
201
|
+
* @param {string} [error]
|
|
202
|
+
* @param {"error" | "warn"} [tone] how the panel should color a failed step
|
|
203
|
+
* @returns {ProvisionStep}
|
|
204
|
+
*/
|
|
205
|
+
function step(id, label, ok, detail, error, tone) {
|
|
206
|
+
const entry = { id, label, ok };
|
|
207
|
+
if (detail !== undefined) entry.detail = detail;
|
|
208
|
+
if (error !== undefined) entry.error = error;
|
|
209
|
+
if (tone !== undefined) entry.tone = tone;
|
|
210
|
+
return entry;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Run one step without letting its failure escape the pipeline. */
|
|
214
|
+
async function attempt(run) {
|
|
215
|
+
try {
|
|
216
|
+
return { ok: true, value: await run() };
|
|
217
|
+
} catch (error) {
|
|
218
|
+
return { ok: false, error };
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* A short, redacted description of a failure.
|
|
224
|
+
*
|
|
225
|
+
* `String(object)` is "[object Object]", which is what the panel used to show
|
|
226
|
+
* when a lower layer threw a plain object rather than an Error.
|
|
227
|
+
*/
|
|
228
|
+
export function describe(error) {
|
|
229
|
+
if (typeof error === "string") return error;
|
|
230
|
+
if (error instanceof Sub2ApiError) return error.message;
|
|
231
|
+
if (error instanceof Error) return error.message || error.name || "未知错误";
|
|
232
|
+
if (error !== null && typeof error === "object") {
|
|
233
|
+
for (const key of ["message", "error", "detail", "code"]) {
|
|
234
|
+
const value = error[key];
|
|
235
|
+
if (typeof value === "string" && value.trim() !== "") return value;
|
|
236
|
+
}
|
|
237
|
+
try {
|
|
238
|
+
return JSON.stringify(error).slice(0, 300);
|
|
239
|
+
} catch {
|
|
240
|
+
return "未知错误";
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return String(error);
|
|
244
|
+
}
|