dsh-sub2api 0.6.1 → 0.7.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,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.0
4
+
5
+ - **Measure context windows from the panel.** Models still on the default are
6
+ listed with a 自动测量容量 button: the plugin probes the gateway with the
7
+ user's own key, saves what it finds as a per-model override, and applies it
8
+ immediately. Rejected probes are not billed, unreachable models are reported
9
+ by id instead of failing the batch, and the whole thing is capped at eight
10
+ models per click.
11
+ - The same measurement is available headlessly through
12
+ `scripts/measure-context.mjs` for filling the shipped table.
13
+ - Fixed a render crash the unit tests could not see: the new handler called a
14
+ helper that had been replaced during an earlier refactor, so the panel showed
15
+ its error boundary instead of the settings page. Caught by rendering the panel
16
+ in a real browser, which is now part of the release check.
17
+
18
+ ## 0.6.2
19
+
20
+ - The measurement itself is in the repository now (`scripts/measure-context.mjs`),
21
+ so the table can be refreshed with one command whenever upstream accounts
22
+ come back — seven models were unreachable during this run and still fall back
23
+ to the default.
24
+
3
25
  ## 0.6.1
4
26
 
5
27
  - Adds `gpt-6.2-sol` (950,272) and `qwen3.8-max` (1,015,808) to the measured
package/README.md CHANGED
@@ -310,6 +310,22 @@ Cannot switch to sub2api/...: no context capacity; configure contextWindow on th
310
310
 
311
311
  面板里标「默认」的模型就是**没测到**的(上游当时不可用),会有一行提示列出来,点右侧数字可以手填。
312
312
 
313
+ ### 面板里点一下就补
314
+
315
+ 模型卡片会列出「不知道真实容量」的模型,旁边有个 **自动测量容量** 按钮:插件用你当前的密钥向网关发超长请求,
316
+ 把测得的值存进面板,立刻生效。被拒绝的请求不计费;账号不可用的模型会被跳过并报出来。
317
+
318
+ 账号完全不可用时,也可以在仓库里跑命令批量补:
319
+
320
+ ```sh
321
+ # 1) 重新测一遍(--only 可选,只测指定模型)
322
+ node scripts/measure-context.mjs --key sk-... --out /tmp/ctx.json
323
+
324
+ # 2) 生成插件用的表
325
+ node scripts/build-context-table.mjs /tmp/ctx.json
326
+ npm test && npm publish
327
+ ```
328
+
313
329
  ## 自动重试
314
330
 
315
331
  回答还没吐出第一个字之前,插件会自动重试这几类失败:
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, 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);
@@ -1249,10 +1250,37 @@ window.__ModuleLoader__.load({
1249
1250
  (() => {
1250
1251
  const fallback = shown.filter((m) => m.contextSource === "default");
1251
1252
  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
- "。点右侧数字可以手动填。");
1253
+ return h("div", { style: { marginTop: 6 } },
1254
+ h("div", { style: { ...T.hint, color: C.warn } },
1255
+ `${fallback.length} 个模型不知道真实容量,暂按 ${Math.round((state.defaultContextWindow || 128000) / 1000)}k 显示:`,
1256
+ fallback.map((m) => m.id).join("、"),
1257
+ "。"),
1258
+ h("div", { style: { ...T.row, marginTop: 8, alignItems: "flex-start" } },
1259
+ h(Button, {
1260
+ size: "sm",
1261
+ disabled: measuring,
1262
+ onClick: async () => {
1263
+ setMeasuring(true);
1264
+ try {
1265
+ const result = await onMeasureContext(fallback.map((m) => m.id));
1266
+ const ok = result?.measured?.length ?? 0;
1267
+ const bad = result?.failed?.length ?? 0;
1268
+ toastStore.push(
1269
+ ok === 0
1270
+ ? `没测出来(${bad} 个失败)`
1271
+ : `测到 ${ok} 个模型${bad > 0 ? `,${bad} 个失败` : ""}`,
1272
+ ok === 0 ? "error" : "ok",
1273
+ );
1274
+ } catch (e) {
1275
+ toastStore.push(e instanceof Error ? e.message : String(e), "error");
1276
+ } finally {
1277
+ setMeasuring(false);
1278
+ }
1279
+ },
1280
+ }, measuring ? "测量中…" : "自动测量容量"),
1281
+ h("span", { style: { ...T.hint, flex: "1 1 200px" } },
1282
+ "向网关发超长请求试探上限,被拒绝的不计费;账号不可用的模型会跳过。"),
1283
+ ));
1256
1284
  })()),
1257
1285
  );
1258
1286
  }
@@ -1394,6 +1422,12 @@ window.__ModuleLoader__.load({
1394
1422
  await statusStore.refresh();
1395
1423
  }, []);
1396
1424
 
1425
+ const onMeasureContext = useCallback((ids) => run("measure", async () => {
1426
+ const result = await call("/models/measure", { method: "POST", body: { ids } });
1427
+ await statusStore.refresh();
1428
+ return result;
1429
+ }), [run]);
1430
+
1397
1431
  const onDiagnose = useCallback(() => call("/diagnose"), []);
1398
1432
 
1399
1433
  const onRecharge = useCallback(async (amountYuan) => {
@@ -1476,6 +1510,7 @@ window.__ModuleLoader__.load({
1476
1510
  onRefreshModels,
1477
1511
  onSaveVisible,
1478
1512
  onSaveContext,
1513
+ onMeasureContext,
1479
1514
  onGoRecharge: () => { setOpen((prev) => ({ ...prev, recharge: true })); },
1480
1515
  })),
1481
1516
 
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,
@@ -272,6 +273,55 @@ export function makeRoutes(deps) {
272
273
  }),
273
274
 
274
275
  /** Save which models the picker offers. An empty list restores "show all". */
276
+ /**
277
+ * Measure context windows the table does not know, through the configured
278
+ * gateway. A model this cannot reach is reported by id instead of failing
279
+ * the whole call, because "three of five measured" is a useful answer and
280
+ * "error" is not.
281
+ */
282
+ defineRoute("POST", `${ROUTE_PREFIX}/models/measure`, async (body) => {
283
+ const apiKey = await session.apiKey();
284
+ if (typeof apiKey !== "string" || apiKey === "") {
285
+ throw new Sub2ApiError("还没有密钥,无法测量", { code: "no_api_key" });
286
+ }
287
+
288
+ const wanted = Array.isArray(body?.ids) ? body.ids.map((id) => String(id)).filter(Boolean) : [];
289
+ const targets =
290
+ wanted.length > 0
291
+ ? wanted
292
+ : catalog
293
+ .visible()
294
+ .filter((model) => model.contextSource === "default")
295
+ .map((model) => model.id);
296
+
297
+ const LIMIT = 8;
298
+ const queue = targets.slice(0, LIMIT);
299
+ if (queue.length === 0) return { measured: [], failed: [], skipped: 0 };
300
+
301
+ const measured = [];
302
+ const failed = [];
303
+ for (const id of queue) {
304
+ try {
305
+ const result = await measureContext({
306
+ apiBase: cfg().apiBase,
307
+ apiKey,
308
+ model: id,
309
+ });
310
+ await panel.setContextOverride(id, result.contextWindow);
311
+ measured.push({ id, contextWindow: result.contextWindow, probes: result.probes.length });
312
+ } catch (error) {
313
+ failed.push({ id, message: error instanceof Error ? error.message : String(error) });
314
+ }
315
+ }
316
+ announceCatalog?.();
317
+ return {
318
+ measured,
319
+ failed,
320
+ skipped: Math.max(0, targets.length - queue.length),
321
+ models: catalog.snapshot(),
322
+ };
323
+ }),
324
+
275
325
  defineRoute("POST", `${ROUTE_PREFIX}/models/visible`, async (body) => {
276
326
  const ids = Array.isArray(body?.ids) ? body.ids.map((id) => String(id)) : [];
277
327
  const known = new Set(catalog.snapshot().all.map((model) => model.id));
@@ -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.1",
3
+ "version": "0.7.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",