dsh-sub2api 0.6.2 → 0.8.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 CHANGED
@@ -1,5 +1,32 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.8.0
4
+
5
+ - **Models that cannot be routed leave the picker.** A sub2api catalogue lists
6
+ models the account pool no longer serves — choosing one fails only when you
7
+ press send. Refreshing now asks every model for a single token, and the ones
8
+ that answer 404/502 are hidden from the conversation picker while staying in
9
+ the panel with a reason, so the list can be explained rather than just shorter.
10
+ A sweep costs a handful of tokens and can be re-run from the panel.
11
+ - Timeouts are reported as "undecided", never as unavailable: image and video
12
+ models do not answer a chat completion at all, and hiding something usable is
13
+ worse than leaving it.
14
+
15
+ ## 0.7.0
16
+
17
+ - **Measure context windows from the panel.** Models still on the default are
18
+ listed with a 自动测量容量 button: the plugin probes the gateway with the
19
+ user's own key, saves what it finds as a per-model override, and applies it
20
+ immediately. Rejected probes are not billed, unreachable models are reported
21
+ by id instead of failing the batch, and the whole thing is capped at eight
22
+ models per click.
23
+ - The same measurement is available headlessly through
24
+ `scripts/measure-context.mjs` for filling the shipped table.
25
+ - Fixed a render crash the unit tests could not see: the new handler called a
26
+ helper that had been replaced during an earlier refactor, so the panel showed
27
+ its error boundary instead of the settings page. Caught by rendering the panel
28
+ in a real browser, which is now part of the release check.
29
+
3
30
  ## 0.6.2
4
31
 
5
32
  - The measurement itself is in the repository now (`scripts/measure-context.mjs`),
package/README.md CHANGED
@@ -310,7 +310,12 @@ Cannot switch to sub2api/...: no context capacity; configure contextWindow on th
310
310
 
311
311
  面板里标「默认」的模型就是**没测到**的(上游当时不可用),会有一行提示列出来,点右侧数字可以手填。
312
312
 
313
- 账号恢复后想补齐,仓库里带了两条命令:
313
+ ### 面板里点一下就补
314
+
315
+ 模型卡片会列出「不知道真实容量」的模型,旁边有个 **自动测量容量** 按钮:插件用你当前的密钥向网关发超长请求,
316
+ 把测得的值存进面板,立刻生效。被拒绝的请求不计费;账号不可用的模型会被跳过并报出来。
317
+
318
+ 账号完全不可用时,也可以在仓库里跑命令批量补:
314
319
 
315
320
  ```sh
316
321
  # 1) 重新测一遍(--only 可选,只测指定模型)
@@ -321,6 +326,15 @@ node scripts/build-context-table.mjs /tmp/ctx.json
321
326
  npm test && npm publish
322
327
  ```
323
328
 
329
+ ## 不可用的模型不会出现在选择器里
330
+
331
+ 网关的目录不等于承诺:分组里列着一些**账号池已经服务不了**的模型,只有按发送时才会报错。
332
+ 现在「刷新模型」会顺带给每个模型发一个单 token 请求,路由不到的(404 / 502)从对话的选择器里隐藏,
333
+ 但仍在面板里列出来并说明原因——列表变短是可以解释的,不是凭空少东西。
334
+
335
+ - 一次扫描成本是几十个 token,面板上可以手动「重新检查」
336
+ - **超时不算不可用**:图像/视频模型本来就不响应聊天请求,隐藏一个能用的比留着更糟
337
+
324
338
  ## 自动重试
325
339
 
326
340
  回答还没吐出第一个字之前,插件会自动重试这几类失败:
package/lib/client.js CHANGED
@@ -1110,7 +1110,7 @@ window.__ModuleLoader__.load({
1110
1110
  );
1111
1111
  }
1112
1112
 
1113
- function ModelsDetail({ state, pending, onRefreshModels, onSaveVisible, onSaveContext, onGoRecharge }) {
1113
+ function ModelsDetail({ state, pending, onRefreshModels, onSaveVisible, onSaveContext, onMeasureContext, onCheckHealth, onGoRecharge }) {
1114
1114
  const models = state.models || { models: [], all: [], allowed: [], fetchedAt: 0, stale: false, error: null };
1115
1115
  const shown = models.models || [];
1116
1116
  const everything = models.all || [];
@@ -1121,6 +1121,7 @@ window.__ModuleLoader__.load({
1121
1121
  const [saving, setSaving] = useState(false);
1122
1122
  const [query, setQuery] = useState("");
1123
1123
  const [expanded, setExpanded] = useState(false);
1124
+ const [measuring, setMeasuring] = useState(false);
1124
1125
 
1125
1126
  const checked = draft ?? (showingAll ? everything.map((m) => m.id) : allowed);
1126
1127
  const isOn = (id) => checked.includes(id);
@@ -1179,7 +1180,34 @@ window.__ModuleLoader__.load({
1179
1180
  );
1180
1181
  }
1181
1182
 
1183
+ const broken = Array.isArray(models.unavailable) ? models.unavailable : [];
1184
+
1182
1185
  return h("div", null,
1186
+ broken.length > 0
1187
+ ? h("div", { style: { marginBottom: 10 } },
1188
+ h("div", { style: { ...T.hint, color: C.warn } },
1189
+ `${broken.length} 个模型网关当前路由不到,已从对话的选择器里隐藏:`,
1190
+ broken.map((m) => m.id).join("、"),
1191
+ "。"),
1192
+ h("div", { style: { ...T.row, marginTop: 6 } },
1193
+ h(Button, {
1194
+ size: "sm",
1195
+ onClick: async () => {
1196
+ try {
1197
+ const result = await onCheckHealth();
1198
+ toastStore.push(
1199
+ result?.unavailable > 0
1200
+ ? `仍有 ${result.unavailable} 个不可用`
1201
+ : "全部恢复可用",
1202
+ result?.unavailable > 0 ? "error" : "ok",
1203
+ );
1204
+ } catch (e) {
1205
+ toastStore.push(e instanceof Error ? e.message : String(e), "error");
1206
+ }
1207
+ },
1208
+ }, "重新检查"),
1209
+ h("span", { style: T.hint }, "会给每个模型发一个单 token 请求,成本可以忽略。")))
1210
+ : null,
1183
1211
  h("div", { style: { ...T.row, marginBottom: 10 } },
1184
1212
  h("span", { style: { ...T.small, fontWeight: 500 } },
1185
1213
  showingAll && !dirty ? `全部 ${everything.length} 个` : `已选 ${checked.length} / ${everything.length}`),
@@ -1249,10 +1277,37 @@ window.__ModuleLoader__.load({
1249
1277
  (() => {
1250
1278
  const fallback = shown.filter((m) => m.contextSource === "default");
1251
1279
  if (fallback.length === 0) return null;
1252
- return h("div", { style: { ...T.hint, marginTop: 6, color: C.warn } },
1253
- `${fallback.length} 个模型不知道真实容量,暂按 ${Math.round((state.defaultContextWindow || 128000) / 1000)}k 显示:`,
1254
- fallback.map((m) => m.id).join("、"),
1255
- "。点右侧数字可以手动填。");
1280
+ return h("div", { style: { marginTop: 6 } },
1281
+ h("div", { style: { ...T.hint, color: C.warn } },
1282
+ `${fallback.length} 个模型不知道真实容量,暂按 ${Math.round((state.defaultContextWindow || 128000) / 1000)}k 显示:`,
1283
+ fallback.map((m) => m.id).join("、"),
1284
+ "。"),
1285
+ h("div", { style: { ...T.row, marginTop: 8, alignItems: "flex-start" } },
1286
+ h(Button, {
1287
+ size: "sm",
1288
+ disabled: measuring,
1289
+ onClick: async () => {
1290
+ setMeasuring(true);
1291
+ try {
1292
+ const result = await onMeasureContext(fallback.map((m) => m.id));
1293
+ const ok = result?.measured?.length ?? 0;
1294
+ const bad = result?.failed?.length ?? 0;
1295
+ toastStore.push(
1296
+ ok === 0
1297
+ ? `没测出来(${bad} 个失败)`
1298
+ : `测到 ${ok} 个模型${bad > 0 ? `,${bad} 个失败` : ""}`,
1299
+ ok === 0 ? "error" : "ok",
1300
+ );
1301
+ } catch (e) {
1302
+ toastStore.push(e instanceof Error ? e.message : String(e), "error");
1303
+ } finally {
1304
+ setMeasuring(false);
1305
+ }
1306
+ },
1307
+ }, measuring ? "测量中…" : "自动测量容量"),
1308
+ h("span", { style: { ...T.hint, flex: "1 1 200px" } },
1309
+ "向网关发超长请求试探上限,被拒绝的不计费;账号不可用的模型会跳过。"),
1310
+ ));
1256
1311
  })()),
1257
1312
  );
1258
1313
  }
@@ -1394,6 +1449,18 @@ window.__ModuleLoader__.load({
1394
1449
  await statusStore.refresh();
1395
1450
  }, []);
1396
1451
 
1452
+ const onMeasureContext = useCallback((ids) => run("measure", async () => {
1453
+ const result = await call("/models/measure", { method: "POST", body: { ids } });
1454
+ await statusStore.refresh();
1455
+ return result;
1456
+ }), [run]);
1457
+
1458
+ const onCheckHealth = useCallback(() => run("health", async () => {
1459
+ const result = await call("/models/health", { method: "POST", body: {} });
1460
+ await statusStore.refresh();
1461
+ return result;
1462
+ }), [run]);
1463
+
1397
1464
  const onDiagnose = useCallback(() => call("/diagnose"), []);
1398
1465
 
1399
1466
  const onRecharge = useCallback(async (amountYuan) => {
@@ -1476,6 +1543,8 @@ window.__ModuleLoader__.load({
1476
1543
  onRefreshModels,
1477
1544
  onSaveVisible,
1478
1545
  onSaveContext,
1546
+ onMeasureContext,
1547
+ onCheckHealth,
1479
1548
  onGoRecharge: () => { setOpen((prev) => ({ ...prev, recharge: true })); },
1480
1549
  })),
1481
1550
 
package/lib/index.js CHANGED
@@ -115,6 +115,7 @@ export function apply(ctx, rawConfig = {}) {
115
115
  reasoningModels: () => cfg().reasoningModels,
116
116
  defaultReasoningEffort: () => cfg().defaultReasoningEffort,
117
117
  apiKey: () => session.apiKey(),
118
+ apiBase: () => cfg().apiBase,
118
119
  logger,
119
120
  });
120
121
 
package/lib/routes.js CHANGED
@@ -17,6 +17,7 @@ import { buildRechargeLink, createRechargeOrder, describeOrderStatus, fetchOrder
17
17
  import { loginOrRegister } from "./sub2api/auth.js";
18
18
  import { provisionAccount } from "./sub2api/provision.js";
19
19
  import { sessionFromAuth } from "./sub2api/session.js";
20
+ import { measureContext } from "./sub2api/measure.js";
20
21
  import {
21
22
  Sub2ApiError,
22
23
  isLoopbackRequest,
@@ -267,11 +268,82 @@ export function makeRoutes(deps) {
267
268
  status: failure instanceof Sub2ApiError ? failure.status : undefined,
268
269
  };
269
270
  }
270
- if (error === undefined) announceCatalog?.();
271
- return { ok: error === undefined, count, error: error ?? null, models: catalog.snapshot() };
271
+ let unavailable = 0;
272
+ if (error === undefined) {
273
+ // Refreshing is the moment a user expects the list to be truthful, so
274
+ // the availability sweep rides along. It is best-effort: a failure here
275
+ // leaves the previous verdicts rather than failing the refresh.
276
+ const apiKey = await session.apiKey();
277
+ unavailable = await catalog.sweepHealth(apiKey);
278
+ announceCatalog?.();
279
+ }
280
+ return {
281
+ ok: error === undefined,
282
+ count,
283
+ unavailable,
284
+ error: error ?? null,
285
+ models: catalog.snapshot(),
286
+ };
287
+ }),
288
+
289
+ /** Re-check availability without re-fetching the catalogue. */
290
+ defineRoute("POST", `${ROUTE_PREFIX}/models/health`, async () => {
291
+ const apiKey = await session.apiKey();
292
+ const unavailable = await catalog.sweepHealth(apiKey);
293
+ announceCatalog?.();
294
+ return { unavailable, models: catalog.snapshot() };
272
295
  }),
273
296
 
274
297
  /** Save which models the picker offers. An empty list restores "show all". */
298
+ /**
299
+ * Measure context windows the table does not know, through the configured
300
+ * gateway. A model this cannot reach is reported by id instead of failing
301
+ * the whole call, because "three of five measured" is a useful answer and
302
+ * "error" is not.
303
+ */
304
+ defineRoute("POST", `${ROUTE_PREFIX}/models/measure`, async (body) => {
305
+ const apiKey = await session.apiKey();
306
+ if (typeof apiKey !== "string" || apiKey === "") {
307
+ throw new Sub2ApiError("还没有密钥,无法测量", { code: "no_api_key" });
308
+ }
309
+
310
+ const wanted = Array.isArray(body?.ids) ? body.ids.map((id) => String(id)).filter(Boolean) : [];
311
+ const targets =
312
+ wanted.length > 0
313
+ ? wanted
314
+ : catalog
315
+ .visible()
316
+ .filter((model) => model.contextSource === "default")
317
+ .map((model) => model.id);
318
+
319
+ const LIMIT = 8;
320
+ const queue = targets.slice(0, LIMIT);
321
+ if (queue.length === 0) return { measured: [], failed: [], skipped: 0 };
322
+
323
+ const measured = [];
324
+ const failed = [];
325
+ for (const id of queue) {
326
+ try {
327
+ const result = await measureContext({
328
+ apiBase: cfg().apiBase,
329
+ apiKey,
330
+ model: id,
331
+ });
332
+ await panel.setContextOverride(id, result.contextWindow);
333
+ measured.push({ id, contextWindow: result.contextWindow, probes: result.probes.length });
334
+ } catch (error) {
335
+ failed.push({ id, message: error instanceof Error ? error.message : String(error) });
336
+ }
337
+ }
338
+ announceCatalog?.();
339
+ return {
340
+ measured,
341
+ failed,
342
+ skipped: Math.max(0, targets.length - queue.length),
343
+ models: catalog.snapshot(),
344
+ };
345
+ }),
346
+
275
347
  defineRoute("POST", `${ROUTE_PREFIX}/models/visible`, async (body) => {
276
348
  const ids = Array.isArray(body?.ids) ? body.ids.map((id) => String(id)) : [];
277
349
  const known = new Set(catalog.snapshot().all.map((model) => model.id));
@@ -21,6 +21,7 @@ import {
21
21
  import { Sub2ApiError } from "../util.js";
22
22
  import { BUILTIN_MODEL } from "../constants.js";
23
23
  import { measuredContext } from "../model-context.js";
24
+ import { checkAvailability } from "./health.js";
24
25
 
25
26
  /**
26
27
  * @typedef {object} ModelRecord
@@ -59,6 +60,13 @@ export class ModelCatalog {
59
60
  * @type {{code?: string, message: string, status?: number, at: number} | undefined}
60
61
  */
61
62
  this.lastError = undefined;
63
+ /**
64
+ * Models the last availability sweep could not route, with the reason.
65
+ * They stay in `all` so the panel can name them, but leave the picker —
66
+ * offering a model that answers 502 when you press send helps nobody.
67
+ * @type {Map<string, {reason: string, status?: number}>}
68
+ */
69
+ this.unavailable = new Map();
62
70
  }
63
71
 
64
72
  /** Read the disk cache once, so a cold start is not an empty picker. */
@@ -112,6 +120,13 @@ export class ModelCatalog {
112
120
  this.models = records;
113
121
  this.fetchedAt = Date.now();
114
122
  this.lastError = undefined;
123
+ /**
124
+ * Models the last availability sweep could not route, with the reason.
125
+ * They stay in `all` so the panel can name them, but leave the picker —
126
+ * offering a model that answers 502 when you press send helps nobody.
127
+ * @type {Map<string, {reason: string, status?: number}>}
128
+ */
129
+ this.unavailable = new Map();
115
130
  await this.#persist();
116
131
  this.logger.info?.(`[sub2api] 模型目录已同步:${records.length} 个`);
117
132
  return records.length;
@@ -240,6 +255,41 @@ export class ModelCatalog {
240
255
  return has ? [...this.models] : [...this.models, { ...BUILTIN_MODEL }];
241
256
  }
242
257
 
258
+ /**
259
+ * Probe every listed model and remember which ones cannot be routed.
260
+ *
261
+ * Best-effort: a failure here must never break a catalogue refresh, because
262
+ * the catalogue is still useful without it.
263
+ * @param {string} apiKey
264
+ * @param {AbortSignal} [signal]
265
+ * @returns {Promise<number>} how many models were found unavailable
266
+ */
267
+ async sweepHealth(apiKey, signal) {
268
+ if (typeof apiKey !== "string" || apiKey === "") return this.unavailable.size;
269
+ try {
270
+ const results = await checkAvailability({
271
+ apiBase: this.deps.apiBase?.() ?? "",
272
+ apiKey,
273
+ models: this.catalogue().map((model) => model.id),
274
+ signal,
275
+ });
276
+ const next = new Map();
277
+ for (const [id, result] of results) {
278
+ if (!result.ok) next.set(id, { reason: result.reason ?? "不可用", status: result.status });
279
+ }
280
+ this.unavailable = next;
281
+ return next.size;
282
+ } catch (error) {
283
+ this.logger.warn?.(`[sub2api] 可用性检查失败:${String(error?.message ?? error)}`);
284
+ return this.unavailable.size;
285
+ }
286
+ }
287
+
288
+ /** @returns {{id: string, reason: string, status?: number}[]} */
289
+ unavailableList() {
290
+ return [...this.unavailable].map(([id, info]) => ({ id, ...info }));
291
+ }
292
+
243
293
  visible() {
244
294
  const allow = this.allowed();
245
295
  const keep = (model) =>
@@ -247,6 +297,7 @@ export class ModelCatalog {
247
297
 
248
298
  return this.catalogue()
249
299
  .filter(keep)
300
+ .filter((model) => model.builtin === true || !this.unavailable.has(model.id))
250
301
  .map((model) => ({ ...model, ...this.resolveContext(model) }));
251
302
  }
252
303
 
@@ -292,6 +343,7 @@ export class ModelCatalog {
292
343
  stale: this.stale,
293
344
  error: this.lastError ?? null,
294
345
  needsRecharge: this.lastError?.code === "INSUFFICIENT_BALANCE",
346
+ unavailable: this.unavailableList(),
295
347
  allowed: this.allowed(),
296
348
  all: this.catalogue().map((model) => ({
297
349
  id: model.id,
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Which models the gateway can actually serve right now.
3
+ *
4
+ * A sub2api catalogue is not a promise: the group lists models that no
5
+ * configured account can serve, so choosing one fails with 502 or 404 only when
6
+ * the user presses send. A one-token request answers the same question in about
7
+ * a tenth of a second and costs a handful of tokens, which is cheap enough to
8
+ * run whenever the catalogue refreshes.
9
+ *
10
+ * @module dsh-sub2api/sub2api/health
11
+ */
12
+
13
+ import { Sub2ApiError } from "../util.js";
14
+
15
+ /**
16
+ * Models a chat completion cannot judge: image and video generators never
17
+ * answer one, and probing them only wastes the sweep's time budget.
18
+ */
19
+ const NON_CHAT = /(?:^|[-_/])(?:image|video|embed|embedding|tts|speech|whisper|rerank)(?:$|[-_/])/i;
20
+
21
+ /** A model the gateway could not route at all. */
22
+ const DEAD = /not supported by any configured account|isn't included|model_not_found|must be called via/i;
23
+
24
+ /**
25
+ * @typedef {object} HealthResult
26
+ * @property {boolean} ok
27
+ * @property {number} [status]
28
+ * @property {string} [reason] short, shown in the panel
29
+ */
30
+
31
+ /**
32
+ * Ask for one token from `model`.
33
+ * @param {object} options
34
+ * @param {string} options.apiBase
35
+ * @param {string} options.apiKey
36
+ * @param {string} options.model
37
+ * @param {AbortSignal} [options.signal]
38
+ * @returns {Promise<HealthResult>}
39
+ */
40
+ async function probeOne({ apiBase, apiKey, model, signal }) {
41
+ const controller = new AbortController();
42
+ const timer = setTimeout(() => controller.abort(), 15_000);
43
+ const onAbort = () => controller.abort();
44
+ signal?.addEventListener("abort", onAbort, { once: true });
45
+
46
+ try {
47
+ const response = await fetch(`${String(apiBase).replace(/\/+$/, "")}/v1/chat/completions`, {
48
+ method: "POST",
49
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
50
+ body: JSON.stringify({
51
+ model,
52
+ messages: [{ role: "user", content: "hi" }],
53
+ max_tokens: 1,
54
+ stream: false,
55
+ }),
56
+ signal: controller.signal,
57
+ });
58
+
59
+ if (response.ok) {
60
+ await response.text();
61
+ return { ok: true, status: response.status };
62
+ }
63
+
64
+ const body = (await response.text()).slice(0, 400);
65
+ if (response.status === 429) return { ok: true, status: 429, reason: "限流" };
66
+ if (DEAD.test(body)) return { ok: false, status: response.status, reason: "网关没有可用账号" };
67
+ if (response.status >= 500) {
68
+ return { ok: false, status: response.status, reason: "上游不可用" };
69
+ }
70
+ // 400/401/403 on a one-token request is about the request, not the route.
71
+ return { ok: true, status: response.status, reason: "请求被拒绝但不代表模型不可用" };
72
+ } catch (error) {
73
+ // A timeout says nothing about whether the model works — an image or video
74
+ // model never answers a chat completion at all. Keep it in the picker and
75
+ // say so, rather than hiding something that may be perfectly usable.
76
+ const aborted = error?.name === "AbortError";
77
+ return { ok: true, status: 0, reason: aborted ? "探测超时,未判定" : "探测失败,未判定" };
78
+ } finally {
79
+ clearTimeout(timer);
80
+ signal?.removeEventListener("abort", onAbort);
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Probe every model, a few at a time.
86
+ *
87
+ * @param {object} options
88
+ * @param {string} options.apiBase
89
+ * @param {string} options.apiKey
90
+ * @param {string[]} options.models
91
+ * @param {number} [options.concurrency]
92
+ * @param {AbortSignal} [options.signal]
93
+ * @returns {Promise<Map<string, HealthResult>>}
94
+ */
95
+ export async function checkAvailability({ apiBase, apiKey, models, concurrency = 6, signal }) {
96
+ if (typeof apiKey !== "string" || apiKey === "") {
97
+ throw new Sub2ApiError("还没有密钥,无法检查可用性", { code: "no_api_key" });
98
+ }
99
+
100
+ const queue = [...new Set(models.map((id) => String(id ?? "")).filter(Boolean))].filter(
101
+ (id) => !NON_CHAT.test(id),
102
+ );
103
+ /** @type {Map<string, HealthResult>} */
104
+ const results = new Map();
105
+
106
+ let next = 0;
107
+ const workers = Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
108
+ while (next < queue.length) {
109
+ if (signal?.aborted === true) return;
110
+ const model = queue[next];
111
+ next += 1;
112
+ results.set(model, await probeOne({ apiBase, apiKey, model, signal }));
113
+ }
114
+ });
115
+
116
+ await Promise.all(workers);
117
+ return results;
118
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Measure a model's context window by asking the gateway.
3
+ *
4
+ * `/v1/models` from sub2api carries no capacity field at all, so the only
5
+ * authority is the model itself: send a prompt larger than its window and the
6
+ * upstream rejects it before generating, usually naming the limit. Models that
7
+ * only say "your input exceeds the context window" are narrowed by bisection
8
+ * between the largest size that passed and the smallest that failed.
9
+ *
10
+ * Rejected requests are not billed; a probe that *succeeds* is, which is why the
11
+ * ladder starts small and stops at the first rejection.
12
+ *
13
+ * @module dsh-sub2api/sub2api/measure
14
+ */
15
+
16
+ import { Sub2ApiError } from "../util.js";
17
+
18
+ /** Sizes to try, smallest first. The first rejection brackets the limit. */
19
+ const LADDER = [65_536, 131_072, 262_144, 524_288, 1_048_576, 2_097_152];
20
+
21
+ const TOO_BIG = /exceed|too long|longer than|maximum context|context window|prompt is too long/i;
22
+ const DEAD = /not supported by any configured account|isn't included|must be called via/i;
23
+
24
+ /**
25
+ * One probe: a prompt of `tokens` repeated words, asking for a single output
26
+ * token so a successful request stays as cheap as it can be.
27
+ * @param {object} options
28
+ * @param {string} options.apiBase
29
+ * @param {string} options.apiKey
30
+ * @param {string} options.model
31
+ * @param {number} options.tokens
32
+ * @param {AbortSignal} [options.signal]
33
+ * @returns {Promise<{ok: boolean, status: number, body: string}>}
34
+ */
35
+ async function probe({ apiBase, apiKey, model, tokens, signal }) {
36
+ const body = JSON.stringify({
37
+ model,
38
+ messages: [{ role: "user", content: "a ".repeat(tokens) }],
39
+ max_tokens: 1,
40
+ stream: false,
41
+ });
42
+
43
+ const controller = new AbortController();
44
+ const timer = setTimeout(() => controller.abort(), 120_000);
45
+ const onAbort = () => controller.abort();
46
+ signal?.addEventListener("abort", onAbort, { once: true });
47
+
48
+ try {
49
+ const response = await fetch(`${String(apiBase).replace(/\/+$/, "")}/v1/chat/completions`, {
50
+ method: "POST",
51
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
52
+ body,
53
+ signal: controller.signal,
54
+ });
55
+ const text = (await response.text()).slice(0, 600);
56
+ return { ok: response.ok, status: response.status, body: text };
57
+ } catch (error) {
58
+ return { ok: false, status: 0, body: String(error?.message ?? error).slice(0, 200) };
59
+ } finally {
60
+ clearTimeout(timer);
61
+ signal?.removeEventListener("abort", onAbort);
62
+ }
63
+ }
64
+
65
+ /**
66
+ * @param {{ok: boolean, status: number, body: string}} result
67
+ * @returns {"ok"|"too_big"|"dead"|"transient"|"other"}
68
+ */
69
+ function classify(result) {
70
+ if (result.ok) return "ok";
71
+ if (DEAD.test(result.body)) return "dead";
72
+ if (TOO_BIG.test(result.body)) return "too_big";
73
+ if (result.status >= 500) return "transient";
74
+ return "other";
75
+ }
76
+
77
+ /**
78
+ * Measure one model's context window.
79
+ *
80
+ * The returned value is the smallest size known to be rejected, so it is never
81
+ * larger than the real limit — over-claiming is what makes the host compact too
82
+ * late and the upstream answer with a 400.
83
+ *
84
+ * @param {object} options
85
+ * @param {string} options.apiBase
86
+ * @param {string} options.apiKey
87
+ * @param {string} options.model
88
+ * @param {AbortSignal} [options.signal]
89
+ * @returns {Promise<{contextWindow: number, probes: Array<{size: number, verdict: string}>}>}
90
+ */
91
+ export async function measureContext({ apiBase, apiKey, model, signal }) {
92
+ const id = String(model ?? "").trim();
93
+ if (id === "") throw new Sub2ApiError("缺少模型 id", { code: "invalid_model" });
94
+
95
+ const probes = [];
96
+ let low = 0;
97
+ let high;
98
+
99
+ for (const size of LADDER) {
100
+ if (signal?.aborted === true) break;
101
+ const result = await probe({ apiBase, apiKey, model: id, tokens: size, signal });
102
+ const verdict = classify(result);
103
+ probes.push({ size, verdict });
104
+
105
+ if (verdict === "ok") {
106
+ low = size;
107
+ continue;
108
+ }
109
+ if (verdict === "too_big") {
110
+ high = size;
111
+ break;
112
+ }
113
+ // Dead route or an upstream fault: measuring is pointless until that is
114
+ // fixed, and retrying just burns time.
115
+ throw new Sub2ApiError(
116
+ verdict === "dead"
117
+ ? `${id}:网关没有能服务这个模型的账号`
118
+ : `${id}:上游不可用(HTTP ${result.status})`,
119
+ { code: verdict === "dead" ? "model_not_found" : "upstream", status: result.status },
120
+ );
121
+ }
122
+
123
+ if (high === undefined) {
124
+ if (low === 0) throw new Sub2ApiError(`${id}:没有测出容量`, { code: "unmeasurable" });
125
+ // Passed the whole ladder: the limit is above what we were willing to send.
126
+ return { contextWindow: low, probes };
127
+ }
128
+
129
+ // Narrow the bracket to ~4% before reporting it.
130
+ while (high - low > Math.max(4096, low * 0.04)) {
131
+ if (signal?.aborted === true) break;
132
+ const mid = Math.floor((low + high) / 2);
133
+ const result = await probe({ apiBase, apiKey, model: id, tokens: mid, signal });
134
+ const verdict = classify(result);
135
+ probes.push({ size: mid, verdict });
136
+ if (verdict === "too_big") high = mid;
137
+ else if (verdict === "ok") low = mid;
138
+ else break;
139
+ }
140
+
141
+ return { contextWindow: high, probes };
142
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-sub2api",
3
- "version": "0.6.2",
3
+ "version": "0.8.0",
4
4
  "description": "Psapi (sub.pscly.cc) provider for DeepSeek Harness: zero-friction signup, auto-provisioned API key, upstream model sync, balance and recharge",
5
5
  "type": "module",
6
6
  "license": "GPL-3.0-only",