dsh-sub2api 0.1.5 → 0.1.6

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,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.6
4
+
5
+ - Make the chat model picker see a fresh catalog. It rebuilds itself from
6
+ `llm/adapters-updated`, and the plugin never published one, so a session
7
+ opened before the first sync kept an empty provider until the page reloaded.
8
+ Refreshing the catalog now swaps the adapter route set, which is the
9
+ documented way to announce the change.
10
+ - Add a model allowlist: the panel's 模型 card lists every upstream model with
11
+ checkboxes, stores the choice in `$DSH_HOME/sub2api-selection.json`, and
12
+ `listModels` honours it, so the picker shows exactly what was chosen. All
13
+ boxes ticked means no restriction; the `visibleModels` config still wins when
14
+ an operator sets it.
15
+
3
16
  ## 0.1.5
4
17
 
5
18
  - Published to npm as `dsh-sub2api`, which is what DSH Desktop's community
package/README.md CHANGED
@@ -124,6 +124,15 @@ dsh plugin --profile desktop add dsh-sub2api
124
124
  - 日志与错误信息不包含 token、密钥或密码。
125
125
  - 支付链接里的 `token` 是 sub2api 的访问令牌,只在用户点「去支付」时生成,不写日志、不落盘。
126
126
 
127
+ ## 选择对话里显示哪些模型
128
+
129
+ 上游一个中转站往往有几十个模型,全部塞进选择器既难找也容易选错。面板的「模型 → 选择模型」里可以勾选要用的那几个:
130
+
131
+ - 勾选结果存在 `$DSH_HOME/sub2api-selection.json`(0600),不写进设置文档
132
+ - **全部勾选等于不做限制**,等同于没设置
133
+ - 通过 `groupId` 之外的方式固定的话,配置里的 `visibleModels` 优先级更高(适合运营方统一指定)
134
+ - 保存后会立刻通知宿主刷新选择器,不用重开会话
135
+
127
136
  ## 密钥建在哪个分组
128
137
 
129
138
  网关会拒绝**没有分组的密钥**(`API key is not assigned to a group`),所以自动选择必须有确定结果:
package/lib/client.js CHANGED
@@ -499,11 +499,28 @@ window.__ModuleLoader__.load({
499
499
 
500
500
  // ------------------------------------------------------------ models
501
501
 
502
- function ModelsCard({ state, busy, onRefreshModels, onGoRecharge }) {
503
- const models = state.models || { models: [], fetchedAt: 0, stale: false, error: null };
504
- const list = models.models || [];
502
+ function ModelsCard({ state, busy, onRefreshModels, onReload, onGoRecharge }) {
503
+ const models = state.models || { models: [], all: [], allowed: [], fetchedAt: 0, stale: false, error: null };
504
+ const shown = models.models || [];
505
+ const everything = models.all || [];
506
+ const allowed = models.allowed || [];
507
+ const showingAll = allowed.length === 0;
508
+
505
509
  const [open, setOpen] = useState(false);
506
510
  const [error, setError] = useState("");
511
+ const [draft, setDraft] = useState(null); // null = untouched
512
+ const [saving, setSaving] = useState(false);
513
+ const [saved, setSaved] = useState(false);
514
+
515
+ const checked = draft ?? (showingAll ? everything.map((m) => m.id) : allowed);
516
+ const isOn = (id) => checked.includes(id);
517
+ const dirty = draft !== null;
518
+
519
+ const toggle = (id) => {
520
+ const next = isOn(id) ? checked.filter((x) => x !== id) : [...checked, id];
521
+ setDraft(next);
522
+ setSaved(false);
523
+ };
507
524
 
508
525
  const refresh = async () => {
509
526
  setError("");
@@ -515,13 +532,34 @@ window.__ModuleLoader__.load({
515
532
  }
516
533
  };
517
534
 
535
+ const save = async () => {
536
+ setSaving(true);
537
+ setError("");
538
+ setSaved(false);
539
+ try {
540
+ // Every model selected is the same as no restriction.
541
+ const ids = checked.length === everything.length ? [] : checked;
542
+ await call("/models/visible", { method: "POST", body: { ids } });
543
+ // Saving only changes the allowlist, so re-read the panel state
544
+ // instead of asking the upstream for its catalog again.
545
+ await onReload();
546
+ setDraft(null);
547
+ setSaved(true);
548
+ setTimeout(() => setSaved(false), 2000);
549
+ } catch (e) {
550
+ setError(e instanceof Error ? e.message : String(e));
551
+ } finally {
552
+ setSaving(false);
553
+ }
554
+ };
555
+
518
556
  const reason = error || models.error?.message || "";
519
557
 
520
558
  return h(Card, {
521
559
  title: "模型",
522
- meta: list.length > 0
523
- ? list.length + " 个 · " + (models.fetchedAt ? new Date(models.fetchedAt).toLocaleTimeString() : "—")
524
- : "0 个 · 未同步",
560
+ meta: everything.length > 0
561
+ ? `对话里显示 ${showingAll && !dirty ? everything.length : checked.length} / ${everything.length}`
562
+ : "0 个",
525
563
  },
526
564
  models.needsRecharge
527
565
  ? h("div", { style: { marginBottom: 12 } },
@@ -541,43 +579,66 @@ window.__ModuleLoader__.load({
541
579
  ? h("div", { style: { marginBottom: 12 } }, h(Alert, { tone: "error", title: "同步失败" }, reason))
542
580
  : null,
543
581
 
544
- h("div", { style: T.row },
582
+ h("div", { style: { ...T.row, marginBottom: everything.length > 0 ? 12 : 0 } },
545
583
  h(Button, { onClick: refresh, disabled: busy || !state.loggedIn }, busy ? "同步中…" : "刷新模型"),
546
- h(Button, { onClick: () => setOpen((v) => !v), disabled: list.length === 0 },
547
- open ? "收起列表" : "查看列表"),
548
- models.stale && list.length > 0 ? h("span", { style: T.hint }, "缓存已过期") : null,
584
+ h(Button, { onClick: () => setOpen((v) => !v), disabled: everything.length === 0 },
585
+ open ? "收起选择" : "选择模型"),
586
+ models.stale && everything.length > 0 ? h("span", { style: T.hint }, "缓存已过期") : null,
549
587
  ),
550
588
 
551
- open
552
- ? h("div", {
553
- style: {
554
- marginTop: 12,
555
- maxHeight: 240,
556
- overflow: "auto",
557
- border: "0.5px solid " + C.line,
558
- borderRadius: 12,
589
+ open && everything.length > 0
590
+ ? h("div", null,
591
+ h("div", {
592
+ style: {
593
+ maxHeight: 260,
594
+ overflow: "auto",
595
+ border: "0.5px solid " + C.line,
596
+ borderRadius: 12,
597
+ },
559
598
  },
560
- },
561
- list.map((model) =>
562
- h("div", {
563
- key: model.id,
564
- style: {
565
- display: "flex",
566
- gap: 10,
567
- alignItems: "baseline",
568
- padding: "7px 12px",
569
- borderTop: "0.5px solid " + C.line,
599
+ everything.map((model) =>
600
+ h("label", {
601
+ key: model.id,
602
+ style: {
603
+ display: "flex",
604
+ alignItems: "center",
605
+ gap: 8,
606
+ padding: "7px 12px",
607
+ borderTop: "0.5px solid " + C.line,
608
+ cursor: "pointer",
609
+ fontSize: 13,
610
+ },
570
611
  },
571
- },
572
- h("code", { style: { ...T.mono, flex: "1 1 auto", minWidth: 0, overflow: "hidden", textOverflow: "ellipsis" } }, model.id),
573
- model.contextWindow ? h("span", { style: T.hint }, Math.round(model.contextWindow / 1000) + "k") : null,
574
- model.vision ? h("span", { style: T.hint }, "图片") : null,
612
+ h("input", {
613
+ type: "checkbox",
614
+ checked: isOn(model.id),
615
+ onChange: () => toggle(model.id),
616
+ }),
617
+ h("code", { style: { ...T.mono, flex: "1 1 auto", minWidth: 0, overflow: "hidden", textOverflow: "ellipsis" } }, model.id),
618
+ shown.some((m) => m.id === model.id && m.vision) ? h("span", { style: T.hint }, "图片") : null,
619
+ ),
620
+ )),
621
+ h("div", { style: { ...T.row, marginTop: 10 } },
622
+ h(Button, { size: "sm", onClick: () => { setDraft(everything.map((m) => m.id)); setSaved(false); } }, "全选"),
623
+ h(Button, { size: "sm", onClick: () => { setDraft([]); setSaved(false); } }, "全不选"),
624
+ h(Button, { size: "sm", onClick: () => { setDraft(null); setSaved(false); } }, "还原"),
625
+ h("div", { style: { marginLeft: "auto", display: "flex", gap: 8, alignItems: "center" } },
626
+ saved ? h("span", { style: { ...T.hint, color: C.ok } }, "已保存") : null,
627
+ h(Button, {
628
+ variant: "primary",
629
+ size: "sm",
630
+ onClick: save,
631
+ disabled: !dirty || saving,
632
+ }, saving ? "保存中…" : "保存选择"),
575
633
  ),
576
- ))
634
+ ),
635
+ )
577
636
  : null,
578
637
 
579
638
  h("div", { style: { ...T.hint, marginTop: 10 } },
580
- "目录来自上游 /v1/models,登录后自动同步,10 分钟内不重复拉取。"),
639
+ everything.length === 0
640
+ ? "目录来自上游 /v1/models,登录后自动同步。"
641
+ : "勾选的模型会出现在对话的模型选择器里;全部勾选等于不做限制。"),
581
642
  );
582
643
  }
583
644
 
@@ -668,6 +729,7 @@ window.__ModuleLoader__.load({
668
729
  state,
669
730
  busy,
670
731
  onRefreshModels,
732
+ onReload: refresh,
671
733
  onGoRecharge: () => {
672
734
  const target = document.getElementById("sub2api-recharge");
673
735
  if (target && typeof target.scrollIntoView === "function") {
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 } from "./constants.js";
13
+ import { API_KEY_REF, KEY_NAME, MODELS_CACHE_FILE, SELECTION_FILE } from "./constants.js";
14
14
  import { normalizeBaseUrl } from "./util.js";
15
15
 
16
16
  /**
@@ -64,6 +64,7 @@ export function resolveConfig(config) {
64
64
  modelsCachePath: String(
65
65
  field(config, "modelsCachePath", join(dshHome, MODELS_CACHE_FILE)),
66
66
  ),
67
+ selectionPath: String(field(config, "selectionPath", join(dshHome, SELECTION_FILE))),
67
68
  showSidebarQuota: field(config, "showSidebarQuota", false) === true,
68
69
  visibleModels: toStringArray(field(config, "visibleModels", [])),
69
70
  contextWindow: toPositiveInt(field(config, "contextWindow", undefined)),
package/lib/constants.js CHANGED
@@ -31,6 +31,9 @@ export const ROUTE_PREFIX = "/api/sub2api";
31
31
  /** Default model catalog cache file name under $DSH_HOME. */
32
32
  export const MODELS_CACHE_FILE = "sub2api-models.json";
33
33
 
34
+ /** Where the panel keeps the model allowlist (an empty list means "show all"). */
35
+ export const SELECTION_FILE = "sub2api-selection.json";
36
+
34
37
  /** How long a discovered catalog stays fresh before a background refresh. */
35
38
  export const CATALOG_TTL_MS = 10 * 60 * 1000;
36
39
 
package/lib/index.js CHANGED
@@ -15,6 +15,7 @@ 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 { SelectionStore } from "./selection.js";
18
19
  import { SessionStore } from "./sub2api/session.js";
19
20
 
20
21
  export { Config } from "./schema.js";
@@ -56,10 +57,34 @@ export function apply(ctx, rawConfig = {}) {
56
57
  apiKeyEnv: () => cfg().apiKeyEnv,
57
58
  });
58
59
 
60
+ /** Panel-side model allowlist, kept beside the catalog cache. */
61
+ const selection = new SelectionStore({
62
+ path: () => cfg().selectionPath,
63
+ logger,
64
+ });
65
+
66
+ /**
67
+ * Tell the host the catalog changed.
68
+ *
69
+ * The model picker rebuilds itself from `llm/adapters-updated` (and the
70
+ * credential events), not from our HTTP routes. Without this a session that
71
+ * opened before the first sync keeps showing an empty provider until the page
72
+ * is reloaded. `replace()` on the registration handle is the documented way
73
+ * to publish that event.
74
+ */
75
+ const announceCatalog = () => {
76
+ try {
77
+ adapterHandle?.replace?.([PROVIDER]);
78
+ } catch {
79
+ // A disposed registration is not an error worth failing a refresh over.
80
+ }
81
+ };
82
+
59
83
  const catalog = new ModelCatalog({
60
84
  api,
61
85
  cachePath: () => cfg().modelsCachePath,
62
86
  visibleModels: () => cfg().visibleModels,
87
+ selection: () => selection.current(),
63
88
  contextWindow: () => cfg().contextWindow,
64
89
  apiKey: () => session.apiKey(),
65
90
  logger,
@@ -79,6 +104,8 @@ export function apply(ctx, rawConfig = {}) {
79
104
 
80
105
  // 1) Provider directory + adapter. The directory entry is what the Models
81
106
  // page turns into a card for this namespace.
107
+ /** @type {{replace?: (providers: string[]) => void} | undefined} */
108
+ let adapterHandle;
82
109
  ctx.effect(() => {
83
110
  const providers = ctx.llm.registerConfigurableProviders([
84
111
  {
@@ -89,7 +116,9 @@ export function apply(ctx, rawConfig = {}) {
89
116
  },
90
117
  ]);
91
118
  const adapters = ctx.llm.registerAdapter([PROVIDER], adapter);
119
+ adapterHandle = adapters;
92
120
  return () => {
121
+ adapterHandle = undefined;
93
122
  adapters?.();
94
123
  providers?.();
95
124
  };
@@ -123,8 +152,14 @@ export function apply(ctx, rawConfig = {}) {
123
152
  const routes = makeRoutes({
124
153
  ...deps,
125
154
  cfg,
155
+ selection,
156
+ announceCatalog,
126
157
  hostname: () => "dsh",
127
- refreshCatalog: (key) => catalog.refresh(key),
158
+ refreshCatalog: async (key) => {
159
+ const count = await catalog.refresh(key);
160
+ announceCatalog();
161
+ return count;
162
+ },
128
163
  });
129
164
  const disposers = routes.map((route) => webServer.register(route));
130
165
  return () => disposers.forEach((dispose) => dispose?.());
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 } = deps;
40
+ const { api, session, catalog, cfg, logger, selection, 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();
@@ -215,9 +215,25 @@ export function makeRoutes(deps) {
215
215
  status: failure instanceof Sub2ApiError ? failure.status : undefined,
216
216
  };
217
217
  }
218
+ if (error === undefined) announceCatalog?.();
218
219
  return { ok: error === undefined, count, error: error ?? null, models: catalog.snapshot() };
219
220
  }),
220
221
 
222
+ /** Save which models the picker offers. An empty list restores "show all". */
223
+ defineRoute("POST", `${ROUTE_PREFIX}/models/visible`, async (body) => {
224
+ const ids = Array.isArray(body?.ids) ? body.ids.map((id) => String(id)) : [];
225
+ const known = new Set(catalog.snapshot().all.map((model) => model.id));
226
+ const unknown = ids.filter((id) => !known.has(id));
227
+ if (unknown.length > 0) {
228
+ throw new Sub2ApiError(`这些模型不在当前目录里:${unknown.slice(0, 3).join("、")}`, {
229
+ code: "unknown_model",
230
+ });
231
+ }
232
+ await selection.save(ids);
233
+ announceCatalog?.();
234
+ return { ok: true, ids, models: catalog.snapshot() };
235
+ }),
236
+
221
237
  /** Recharge level 1: a signed-in URL the browser opens in a new tab. */
222
238
  defineRoute("POST", `${ROUTE_PREFIX}/recharge/link`, async (body) => {
223
239
  const stored = await session.read();
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Which models the user wants in the picker.
3
+ *
4
+ * Configuration can pin a list, but typing model ids into a YAML file is not a
5
+ * reasonable way to choose from forty of them, so the panel writes this small
6
+ * sidecar instead. It is deliberately separate from the settings document: the
7
+ * settings service projects a schema, and a growing list of upstream ids is not
8
+ * a schema.
9
+ * @module dsh-sub2api/selection
10
+ */
11
+
12
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
13
+ import { dirname } from "node:path";
14
+
15
+ export class SelectionStore {
16
+ /**
17
+ * @param {object} deps
18
+ * @param {() => string} deps.path file to keep the selection in
19
+ * @param {{warn: Function}} [deps.logger]
20
+ */
21
+ constructor(deps) {
22
+ this.deps = deps;
23
+ this.logger = deps.logger ?? { warn() {} };
24
+ /** @type {string[] | undefined} */
25
+ this.ids = undefined;
26
+ this.loaded = false;
27
+ }
28
+
29
+ async load() {
30
+ if (this.loaded) return this.current();
31
+ this.loaded = true;
32
+ try {
33
+ const text = await readFile(this.deps.path(), "utf8");
34
+ const parsed = JSON.parse(text);
35
+ if (Array.isArray(parsed?.ids)) {
36
+ this.ids = parsed.ids.filter((id) => typeof id === "string" && id.trim() !== "");
37
+ }
38
+ } catch {
39
+ // No file yet: an empty selection means "show everything".
40
+ }
41
+ return this.current();
42
+ }
43
+
44
+ /** The stored ids, synchronously. Empty means no restriction. */
45
+ current() {
46
+ return Array.isArray(this.ids) ? this.ids : [];
47
+ }
48
+
49
+ /**
50
+ * @param {string[]} ids model ids to keep; an empty list restores "show all"
51
+ * @returns {Promise<string[]>}
52
+ */
53
+ async save(ids) {
54
+ const clean = [...new Set((Array.isArray(ids) ? ids : []).map((id) => String(id).trim()))]
55
+ .filter((id) => id !== "");
56
+ this.ids = clean;
57
+ this.loaded = true;
58
+ try {
59
+ await mkdir(dirname(this.deps.path()), { recursive: true });
60
+ await writeFile(this.deps.path(), JSON.stringify({ ids: clean }, null, 0), { mode: 0o600 });
61
+ } catch (error) {
62
+ this.logger.warn?.(`[sub2api] 模型选择保存失败:${error instanceof Error ? error.message : error}`);
63
+ }
64
+ return clean;
65
+ }
66
+ }
@@ -138,9 +138,20 @@ export class ModelCatalog {
138
138
  }
139
139
  }
140
140
 
141
+ /**
142
+ * The allowlist in force: the configuration wins when it names anything,
143
+ * otherwise the panel's stored selection applies. Empty means "show all".
144
+ * @returns {string[]}
145
+ */
146
+ allowed() {
147
+ const configured = this.deps.visibleModels() ?? [];
148
+ if (configured.length > 0) return configured;
149
+ return this.deps.selection?.() ?? [];
150
+ }
151
+
141
152
  /** Models as the picker should see them: allowlist applied, forced context honored. */
142
153
  visible() {
143
- const allow = this.deps.visibleModels() ?? [];
154
+ const allow = this.allowed();
144
155
  const forcedContext = this.deps.contextWindow();
145
156
  return this.models
146
157
  .filter((model) => allow.length === 0 || allow.includes(model.id))
@@ -186,6 +197,8 @@ export class ModelCatalog {
186
197
  stale: this.stale,
187
198
  error: this.lastError ?? null,
188
199
  needsRecharge: this.lastError?.code === "INSUFFICIENT_BALANCE",
200
+ allowed: this.allowed(),
201
+ all: this.models.map((model) => ({ id: model.id, name: model.name })),
189
202
  models: this.visible().map((model) => ({
190
203
  id: model.id,
191
204
  name: model.name,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-sub2api",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "Sub2API 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",