dsh-sub2api 0.1.7 → 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.
@@ -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,6 +65,7 @@ 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)),
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
 
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 { SelectionStore } from "./selection.js";
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-side model allowlist, kept beside the catalog cache. */
61
- const selection = new SelectionStore({
62
- path: () => cfg().selectionPath,
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,7 +86,8 @@ export function apply(ctx, rawConfig = {}) {
84
86
  api,
85
87
  cachePath: () => cfg().modelsCachePath,
86
88
  visibleModels: () => cfg().visibleModels,
87
- selection: () => selection.current(),
89
+ selection: () => panel.visible(),
90
+ contextOverride: (id) => panel.contextOverride(id),
88
91
  contextWindow: () => cfg().contextWindow,
89
92
  defaultContextWindow: () => cfg().defaultContextWindow,
90
93
  apiKey: () => session.apiKey(),
@@ -153,7 +156,7 @@ export function apply(ctx, rawConfig = {}) {
153
156
  const routes = makeRoutes({
154
157
  ...deps,
155
158
  cfg,
156
- selection,
159
+ panel,
157
160
  announceCatalog,
158
161
  hostname: () => "dsh",
159
162
  refreshCatalog: async (key) => {
@@ -166,7 +169,13 @@ export function apply(ctx, rawConfig = {}) {
166
169
  return () => disposers.forEach((dispose) => dispose?.());
167
170
  }, "sub2api: routes");
168
171
 
169
- // 4) Agent tools: read-only status so the model can answer "how much is left".
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".
170
179
  // Imported lazily: a deployment without @deepseek-ai/dsh-tools still gets
171
180
  // the provider and the panel, just no tools.
172
181
  ctx.effect(() => {
@@ -188,13 +197,13 @@ export function apply(ctx, rawConfig = {}) {
188
197
  };
189
198
  }, "sub2api: tools");
190
199
 
191
- // 5) Warm the catalog so the first picker open is not empty.
200
+ // 6) Warm the catalog so the first picker open is not empty.
192
201
  ctx.effect(() => {
193
202
  void catalog.load().then(() => catalog.ensureFresh()).catch(() => {});
194
203
  return () => {};
195
204
  }, "sub2api: warm");
196
205
 
197
- // 6) Agent guidance, so the model knows the panel exists.
206
+ // 7) Agent guidance, so the model knows the panel exists.
198
207
  ctx.effect(() => {
199
208
  if (cfg().announceToAgent !== true) return () => {};
200
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, selection, announceCatalog } = deps;
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 selection.save(ids);
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();
@@ -149,6 +149,30 @@ export class ModelCatalog {
149
149
  return this.deps.selection?.() ?? [];
150
150
  }
151
151
 
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
+
152
176
  /**
153
177
  * Models as the picker should see them: allowlist applied and a context
154
178
  * window always resolved.
@@ -160,24 +184,10 @@ export class ModelCatalog {
160
184
  */
161
185
  visible() {
162
186
  const allow = this.allowed();
163
- const forcedContext = this.deps.contextWindow();
164
- const fallback = this.deps.defaultContextWindow?.() ?? DEFAULT_CONTEXT_WINDOW;
165
187
 
166
188
  return this.models
167
189
  .filter((model) => allow.length === 0 || allow.includes(model.id))
168
- .map((model) => {
169
- if (forcedContext !== undefined) {
170
- return { ...model, contextWindow: forcedContext, contextSource: "config" };
171
- }
172
- if (model.contextWindow !== undefined) {
173
- return { ...model, contextSource: "upstream" };
174
- }
175
- const known = knownContext(model.id);
176
- if (known !== undefined) {
177
- return { ...model, contextWindow: known, contextSource: "known" };
178
- }
179
- return { ...model, contextWindow: fallback, contextSource: "default" };
180
- });
190
+ .map((model) => ({ ...model, ...this.resolveContext(model) }));
181
191
  }
182
192
 
183
193
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-sub2api",
3
- "version": "0.1.7",
3
+ "version": "0.2.0",
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",
@@ -12,6 +12,7 @@
12
12
  },
13
13
  "files": [
14
14
  "CHANGELOG.md",
15
+ "LICENSE",
15
16
  "README.md",
16
17
  "cordis.patch.yml",
17
18
  "lib"
@@ -66,10 +67,11 @@
66
67
  "gateway"
67
68
  ],
68
69
  "scripts": {
69
- "test": "node test/smoke.mjs && node test/edges.mjs && node test/client-load.mjs",
70
+ "test": "node test/all.mjs",
70
71
  "test:smoke": "node test/smoke.mjs",
71
72
  "test:edges": "node test/edges.mjs",
72
- "test:client": "node test/client-load.mjs"
73
+ "test:client": "node test/client-load.mjs",
74
+ "link:host": "node scripts/link-host.mjs"
73
75
  },
74
76
  "publishConfig": {
75
77
  "access": "public",