@kenz1117/dsh-ui-usage-billing 1.8.13 → 1.8.15

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/lib/index.js CHANGED
@@ -9896,7 +9896,7 @@ function parseNewApiStatus(data) {
9896
9896
  return window === null ? null : { windows: [window] };
9897
9897
  }
9898
9898
  /** 归一化站点 origin(与聚合层 `siteOriginOf` 同口径)。 */
9899
- function originOf(baseURL) {
9899
+ function originOf$1(baseURL) {
9900
9900
  try {
9901
9901
  return new URL(baseURL).origin;
9902
9902
  } catch {
@@ -9926,7 +9926,7 @@ const OFFICIAL_HOSTS = /* @__PURE__ */ new Set([
9926
9926
  * @returns 官方端点返回 true(中转站面板应排除)。
9927
9927
  */
9928
9928
  function isOfficialBaseUrl(baseURL) {
9929
- const host = originOf(baseURL).replace(/^https?:\/\//, "");
9929
+ const host = originOf$1(baseURL).replace(/^https?:\/\//, "");
9930
9930
  return host !== baseURL && OFFICIAL_HOSTS.has(host);
9931
9931
  }
9932
9932
  /** 构造端点 URL:`/v1/usage` 与 `/api/status` 都以 baseURL 为宿主解析。 */
@@ -9955,7 +9955,7 @@ async function readRelayByKind(baseURL, apiKey, kind) {
9955
9955
  async function queryRelayQuota(ctx, route) {
9956
9956
  const base = {
9957
9957
  route: route.route,
9958
- origin: originOf(route.baseURL),
9958
+ origin: originOf$1(route.baseURL),
9959
9959
  displayName: route.displayName ?? route.route
9960
9960
  };
9961
9961
  const gateKey = `${route.baseURL}::${route.route}`;
@@ -10074,6 +10074,78 @@ async function queryRelayQuotas(ctx, routes) {
10074
10074
  return await Promise.all(routes.map(async (route) => queryRelayQuota(ctx, route)));
10075
10075
  }
10076
10076
  //#endregion
10077
+ //#region lib/types/relay-exclusion.js
10078
+ /**
10079
+ * 中转站额度探测的**排除项**(issue #152)。
10080
+ *
10081
+ * 背景:报告者的自建网关只实现 OpenAI 兼容的 `/v1/chat/completions`、`/v1/models`,
10082
+ * 没有余额/额度端点。插件的 `refreshRelay` 把「配了非官方 baseURL + 能解析到 key」
10083
+ * 的路由一律当疑似中转站探测,两个端点必然 404;而**识别失败不写指纹缓存**
10084
+ * (`fingerprintCache` 只在解析成功时写),于是每轮都重新探测——网关日志被稳定
10085
+ * 污染(每 10 分钟两条 404),按 4xx 统计错误率的告警持续误报,面板上却完全
10086
+ * 无感知。
10087
+ *
10088
+ * 熔断挡不住这个场景:`relayGate` 是 3 次失败冷却 60 秒,而轮询周期是 10 分钟,
10089
+ * 冷却早已过期。
10090
+ *
10091
+ * 排除项是**纯增量**:未配置时行为与此前逐字一致(存量中转站用户不受影响)。
10092
+ * 匹配语义刻意保守——**精确匹配**路由名或 origin,不支持通配/后缀:
10093
+ * 排除错了会让用户以为额度还在,代价(漏看余额)比多探测一次更大。
10094
+ */
10095
+ /** 路由的 origin(协议 + 主机 + 端口);baseURL 非法时原样返回。 */
10096
+ function originOf(baseURL) {
10097
+ try {
10098
+ return new URL(baseURL).origin;
10099
+ } catch {
10100
+ return baseURL;
10101
+ }
10102
+ }
10103
+ /**
10104
+ * 该路由是否被排除在额度探测之外。
10105
+ *
10106
+ * @param route - llm-pi-ai 路由名(如 `nas`)。
10107
+ * @param baseURL - 该路由的端点地址。
10108
+ * @param exclusions - 用户配置的排除项;每项可写路由名或 origin。
10109
+ * @returns 命中排除项返回 true。
10110
+ */
10111
+ function isRelayQuotaExcluded(route, baseURL, exclusions) {
10112
+ if (exclusions === void 0 || exclusions.length === 0) return false;
10113
+ const origin = originOf(baseURL);
10114
+ for (const raw of exclusions) {
10115
+ const item = raw.trim();
10116
+ if (item === "") continue;
10117
+ if (item === route) return true;
10118
+ if (item.toLowerCase() === origin.toLowerCase()) return true;
10119
+ }
10120
+ return false;
10121
+ }
10122
+ /**
10123
+ * 从 provider 路由表里挑出**可探测**的路由(issue #152)。
10124
+ *
10125
+ * 三道门,顺序固定:
10126
+ * 1. 没有 `baseURL` → 不是中转站形态,跳过;
10127
+ * 2. 官方厂商端点 → 卖的是官方按量余额而非中转站额度,跳过;
10128
+ * 3. 用户显式排除 → 命中即跳过,**不发任何请求**。
10129
+ *
10130
+ * @param providers - llm-pi-ai 的 provider 路由表。
10131
+ * @param isOfficial - 该 baseURL 是否指向官方厂商端点。
10132
+ * @param exclusions - 用户配置的排除项。
10133
+ * @returns 可探测的路由(保持配置里的顺序)。
10134
+ */
10135
+ function selectRelayQuotaCandidates(providers, isOfficial, exclusions) {
10136
+ const out = [];
10137
+ for (const [route, entry] of Object.entries(providers)) {
10138
+ if (entry.baseURL === void 0) continue;
10139
+ if (isOfficial(entry.baseURL)) continue;
10140
+ if (isRelayQuotaExcluded(route, entry.baseURL, exclusions)) continue;
10141
+ out.push({
10142
+ route,
10143
+ baseURL: entry.baseURL
10144
+ });
10145
+ }
10146
+ return out;
10147
+ }
10148
+ //#endregion
10077
10149
  //#region lib/types/guard.js
10078
10150
  /**
10079
10151
  * 共享 loopback 守卫(v1.5.2 抽自 src/index.ts)。
@@ -10130,15 +10202,26 @@ function isLoopbackHost(req, trustedHosts = /* @__PURE__ */ new Set()) {
10130
10202
  if (name === "localhost" || name === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(name)) return true;
10131
10203
  return name !== "" && trustedHosts.has(name);
10132
10204
  }
10133
- /** 校验 Origin 头是否回环(写操作用,防止跨站表单/fetch 改写设置)。Origin 缺失
10205
+ /** 校验 Origin 头是否可信(写操作用,防止跨站表单/fetch 改写设置)。Origin 缺失
10134
10206
  * (curl 或同源 fetch 不带)视为放行,交给下方的 Content-Type 校验兜底;Origin 存在
10135
- * 但主机非回环则拒绝——跨站脚本发起的写请求必带攻击者域名的 Origin。 */
10136
- function isLoopbackOrigin(origin) {
10207
+ * 但主机既非回环、也不在 trustedHosts 里则拒绝——跨站脚本发起的写请求必带攻击者
10208
+ * 域名的 Origin。
10209
+ *
10210
+ * 反向代理场景:浏览器把页面自身的地址写进 Origin(`https://dash.example.com`)。
10211
+ * Host 头因为同一域名被 trustedHosts 放行,Origin 却是同一个非回环域名——只认回环
10212
+ * 字面量会让「已显式信任的主机」在写操作上必然 403(读操作正常),表现为面板能
10213
+ * 打开、点任何保存/入队都报 `forbidden: loopback only`。因此 Origin 与 Host 共用
10214
+ * 同一份 trustedHosts:用户显式信任某个主机,就等于接受该主机的同源写请求。
10215
+ * @param origin - 原始 Origin 头(可能缺失)。
10216
+ * @param trustedHosts - 已归一化的可信主机名集合,与 {@link isLoopbackHost} 同口径。
10217
+ */
10218
+ function isLoopbackOrigin(origin, trustedHosts = /* @__PURE__ */ new Set()) {
10137
10219
  if (origin === void 0 || origin === "") return true;
10138
10220
  try {
10139
10221
  const raw = new URL(origin).hostname;
10140
10222
  const host = raw.startsWith("[") && raw.endsWith("]") ? raw.slice(1, -1) : raw;
10141
- return host === "localhost" || host === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host);
10223
+ if (host === "localhost" || host === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host)) return true;
10224
+ return host !== "" && trustedHosts.has(host.toLowerCase());
10142
10225
  } catch {
10143
10226
  return false;
10144
10227
  }
@@ -10342,7 +10425,7 @@ function registerPeakScheduleRoute(ctx, deps) {
10342
10425
  if (!guardLoopback(req, res, deps.trustedHosts)) return;
10343
10426
  let raw;
10344
10427
  if (req.method === "POST") {
10345
- if (!isLoopbackOrigin(req.headers.origin)) return reply(res, 403, {
10428
+ if (!isLoopbackOrigin(req.headers.origin, deps.trustedHosts)) return reply(res, 403, {
10346
10429
  error: "forbidden: loopback only",
10347
10430
  message: "仅限本机请求"
10348
10431
  });
@@ -10517,7 +10600,7 @@ function registerNotifyClaimRoute(ctx, deps) {
10517
10600
  res.end(JSON.stringify({ error: "method not allowed" }));
10518
10601
  return;
10519
10602
  }
10520
- if (!isLoopbackOrigin(req.headers.origin) || !(req.headers["content-type"] ?? "").toLowerCase().includes("application/json")) {
10603
+ if (!isLoopbackOrigin(req.headers.origin, deps.trustedHosts) || !(req.headers["content-type"] ?? "").toLowerCase().includes("application/json")) {
10521
10604
  res.writeHead(403, { "content-type": "application/json; charset=utf-8" });
10522
10605
  res.end(JSON.stringify({ error: "forbidden: loopback only" }));
10523
10606
  return;
@@ -10739,7 +10822,7 @@ function registerRefreshRoute(ctx, deps) {
10739
10822
  res.end(JSON.stringify({ error: "method not allowed" }));
10740
10823
  return;
10741
10824
  }
10742
- if (!isLoopbackOrigin(req.headers.origin)) {
10825
+ if (!isLoopbackOrigin(req.headers.origin, deps.trustedHosts)) {
10743
10826
  res.writeHead(403, { "content-type": "application/json; charset=utf-8" });
10744
10827
  res.end(JSON.stringify({ error: "forbidden: loopback only" }));
10745
10828
  return;
@@ -10854,7 +10937,7 @@ function registerUsageToolRoute(ctx, deps) {
10854
10937
  return;
10855
10938
  }
10856
10939
  if (req.method === "POST") {
10857
- if (!isLoopbackOrigin(req.headers.origin)) {
10940
+ if (!isLoopbackOrigin(req.headers.origin, deps.trustedHosts)) {
10858
10941
  res.writeHead(403, { "content-type": "application/json; charset=utf-8" });
10859
10942
  res.end(JSON.stringify({ error: "forbidden: loopback only" }));
10860
10943
  return;
@@ -11165,6 +11248,128 @@ function registerUsageStatsRoute(ctx, deps) {
11165
11248
  }), "usage-billing: usage-stats route");
11166
11249
  }
11167
11250
  //#endregion
11251
+ //#region lib/types/client/scheduled-band.js
11252
+ const MINUTE = 6e4;
11253
+ const DAY = 1440 * MINUTE;
11254
+ /** Only wall-clock boundaries can change a band. Infinity means no future transition. */
11255
+ function scheduledCountdown(now, channel, rule) {
11256
+ if (!rule || channel !== "deepseek-metered") return channelCountdown(now, channel);
11257
+ const tier = customTier(now, rule);
11258
+ const offset = rule.utcOffsetMinutes * MINUTE;
11259
+ const midnight = Math.floor((now + offset) / DAY) * DAY - offset;
11260
+ const boundaries = [.../* @__PURE__ */ new Set([0, ...rule.windows.filter((m) => m < 1440)])];
11261
+ const days = /* @__PURE__ */ new Set([
11262
+ 0,
11263
+ 1,
11264
+ 2,
11265
+ 3,
11266
+ 4,
11267
+ 5,
11268
+ 6,
11269
+ 7
11270
+ ]);
11271
+ for (const date of rule.holidays) {
11272
+ const day = (Date.parse(`${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6)}T00:00Z`) - offset - midnight) / DAY;
11273
+ if (day < 0) continue;
11274
+ for (let i = 0; i <= 7; i++) days.add(day + i);
11275
+ }
11276
+ for (const day of [...days].sort((a, b) => a - b)) for (const m of boundaries) {
11277
+ const at = midnight + day * DAY + m * MINUTE;
11278
+ if (at > now && customTier(at, rule) !== tier) return {
11279
+ tier,
11280
+ nextSwitchInMs: at - now
11281
+ };
11282
+ }
11283
+ return {
11284
+ tier,
11285
+ nextSwitchInMs: Infinity
11286
+ };
11287
+ }
11288
+ //#endregion
11289
+ //#region lib/types/task-queue-band.js
11290
+ /**
11291
+ * 低谷队列的**按来源判档**(issue #143)。
11292
+ *
11293
+ * 背景:报告者实测发现两件事——①订阅通道(如 `dsh-opencode-go`)确实有峰谷
11294
+ * 倍率(其模型目录里 `deepseek-v4.1-flash` / `deepseek-v4-pro` 在 UTC 周一至
11295
+ * 周五 01:00–04:00 / 06:00–10:00 时 `factor: 2`,其余为 1,即北京时间
11296
+ * 09:00–12:00 / 14:00–18:00 倍率 2);②插件的「按模型配峰谷时段」已经能让
11297
+ * 订阅通道的模型进入配置(`eligibleScheduleModel` 只要求目录里有 offPeak 价),
11298
+ * 但低谷队列此前**硬过滤官方路由**且用全局 `tierAt` 判档——用户配了、计费认了、
11299
+ * 队列不认。
11300
+ *
11301
+ * 本模块把「某个来源 × 某个模型此刻处于哪一档」收敛成一处判定,供队列的
11302
+ * 候选筛选、启动闸门与展示共用(**同一件事不许两处各写一套**)。
11303
+ *
11304
+ * 两条纪律:
11305
+ * 1. **来源桶与聚合层同源**——`site:` / `direct:` 的映射由调用方注入(用
11306
+ * `siteRefOf` + `siteBucketKey`),本模块不自己猜,避免队列与计费对同一
11307
+ * 条路由得出两个来源桶。
11308
+ * 2. **窗口语义分列**——官方按量通道的谷档省**现金**,订阅通道的谷段省**套餐
11309
+ * 额度**(倍率 2→1)。两者窗口数值可能相同,但省的东西不同;界面必须分开
11310
+ * 表述,混说就是假声明。
11311
+ */
11312
+ /**
11313
+ * 官方按量通道的来源桶前缀。宿主内置的 DeepSeek API Key 通道
11314
+ * (路由 id `deepseek-official`)不在 llm-pi-ai 路由表里,按直连归位。
11315
+ */
11316
+ const OFFICIAL_SOURCE_RE = /^direct:deepseek(?:-|$)|^site:https:\/\/api\.deepseek\.com$/i;
11317
+ /**
11318
+ * 用户为该来源 × 模型配置的规则(未配置则 undefined)。
11319
+ *
11320
+ * @param facts - 判档事实。
11321
+ * @returns 命中的规则,未命中时 undefined。
11322
+ */
11323
+ function ruleOf(facts) {
11324
+ if (facts.channel === void 0 || facts.schedule === void 0) return void 0;
11325
+ return facts.schedule.models[scheduleKey(facts.channel.source, facts.catalogKey)];
11326
+ }
11327
+ /**
11328
+ * 某来源 × 某模型此刻处于哪一档。
11329
+ *
11330
+ * 判定顺序:
11331
+ * 1. 用户配了该来源 × 模型的时段 → 用它(`effectiveRule` 补齐该来源的缺省:
11332
+ * 窗口、周末、时区;官方来源另补中国法定节假日);
11333
+ * 2. 未配 → 官方来源走全局 `tierAt`(含节假日),订阅来源走**同一组官方窗口
11334
+ * 但不含中国节假日**——订阅厂商的倍率表里没有中国节假日这一项,套上去会
11335
+ * 把本该计倍率的时段误判成低谷。
11336
+ *
11337
+ * @param facts - 判档事实。
11338
+ * @param at - 判定时刻(epoch ms)。
11339
+ * @returns `peak` / `offPeak`。
11340
+ */
11341
+ function tierOf(facts, at) {
11342
+ const channel = facts.channel;
11343
+ if (channel === void 0) return tierAt(at);
11344
+ const rule = ruleOf(facts);
11345
+ if (rule !== void 0) return customTier(at, effectiveRule(channel.source, rule));
11346
+ if (OFFICIAL_SOURCE_RE.test(channel.source)) return tierAt(at);
11347
+ return customTier(at, effectiveRule(channel.source, {}));
11348
+ }
11349
+ /**
11350
+ * 该来源 × 模型距离下一次档位切换还有多久(毫秒)。
11351
+ *
11352
+ * 复用客户端同源的倒计时实现(`scheduledCountdown`)——它已按「自定义规则」
11353
+ * 算切换点(含周末与节假日例外),与面板里显示的倒计时是同一份逻辑,不会
11354
+ * 出现「面板说还有 5 分钟、队列说还有 1 小时」的分裂。
11355
+ *
11356
+ * @param facts - 判档事实。
11357
+ * @param at - 判定时刻(epoch ms)。
11358
+ * @returns 距下次切换的毫秒数;无未来切换点时为 `Infinity`。
11359
+ */
11360
+ function nextSwitchMsOf(facts, at) {
11361
+ const channel = facts.channel;
11362
+ if (channel === void 0) return switchMsOf(scheduledCountdown(at, "deepseek-metered"));
11363
+ const rule = ruleOf(facts);
11364
+ if (rule !== void 0) return switchMsOf(scheduledCountdown(at, "deepseek-metered", effectiveRule(channel.source, rule)));
11365
+ if (OFFICIAL_SOURCE_RE.test(channel.source)) return switchMsOf(scheduledCountdown(at, "deepseek-metered"));
11366
+ return switchMsOf(scheduledCountdown(at, "deepseek-metered", effectiveRule(channel.source, {})));
11367
+ }
11368
+ /** 倒计时可能缺席(通道无窗口)——缺席时按「无切换点」处理(Infinity)。 */
11369
+ function switchMsOf(countdown) {
11370
+ return countdown?.nextSwitchInMs ?? Infinity;
11371
+ }
11372
+ //#endregion
11168
11373
  //#region lib/types/task-queue.js
11169
11374
  /**
11170
11375
  * Durable off-peak FIFO task queue (issue #106, new-host capability preview).
@@ -11242,6 +11447,12 @@ var TaskQueueEngine = class {
11242
11447
  taskAbort;
11243
11448
  stopped = true;
11244
11449
  pumping = false;
11450
+ /**
11451
+ * 模型目录缓存(issue #143)。
11452
+ *
11453
+ * 只缓存**目录事实**(候选清单与根因),**不缓存档位**——档位随时间变化,
11454
+ * 缓存 60 秒会让面板显示过期的「距高峰还有 N 分钟」。每次快照现算档位。
11455
+ */
11245
11456
  modelCache;
11246
11457
  constructor(options) {
11247
11458
  this.options = options;
@@ -11268,42 +11479,70 @@ var TaskQueueEngine = class {
11268
11479
  this.taskAbort?.abort();
11269
11480
  }
11270
11481
  async snapshot(refreshModels = false) {
11271
- const countdown = channelCountdown(this.now(), "deepseek-metered");
11272
11482
  const controller = usableController(this.options.getController());
11273
11483
  const base = {
11274
11484
  supported: controller !== void 0,
11275
- tier: tierAt(this.now()),
11276
- nextSwitchInMs: countdown?.nextSwitchInMs ?? 0,
11277
11485
  tasks: (await this.readDocument()).tasks.map(publicTask),
11278
11486
  workspaces: this.options.getWorkspaces()
11279
11487
  };
11280
11488
  if (controller === void 0) return {
11281
11489
  ...base,
11490
+ ...this.officialBand(),
11282
11491
  models: []
11283
11492
  };
11284
11493
  try {
11494
+ const options = await this.modelOptions(controller, refreshModels);
11285
11495
  return {
11286
11496
  ...base,
11287
- ...await this.modelOptions(controller, refreshModels)
11497
+ ...this.bandOf(options),
11498
+ ...options
11288
11499
  };
11289
11500
  } catch (error) {
11290
11501
  return {
11291
11502
  ...base,
11503
+ ...this.officialBand(),
11292
11504
  models: [],
11293
11505
  optionsError: messageOf(error)
11294
11506
  };
11295
11507
  }
11296
11508
  }
11297
11509
  async summary() {
11298
- const countdown = channelCountdown(this.now(), "deepseek-metered");
11299
11510
  const document = await this.readDocument();
11300
11511
  return {
11301
11512
  supported: usableController(this.options.getController()) !== void 0,
11302
- tier: tierAt(this.now()),
11303
- nextSwitchInMs: countdown?.nextSwitchInMs ?? 0,
11513
+ ...this.bandOf(this.modelCache === void 0 ? void 0 : this.modelOptionsOf(this.modelCache)),
11304
11514
  queuedCount: document.tasks.filter((task) => task.status === "queued").length
11305
11515
  };
11306
11516
  }
11517
+ /** 官方全局档位(无候选时的兜底口径,与旧行为逐字一致)。 */
11518
+ officialBand() {
11519
+ const countdown = channelCountdown(this.now(), "deepseek-metered");
11520
+ return {
11521
+ tier: tierAt(this.now()),
11522
+ nextSwitchInMs: countdown?.nextSwitchInMs ?? 0
11523
+ };
11524
+ }
11525
+ /**
11526
+ * 档位按**默认候选模型**判定(issue #143)。
11527
+ *
11528
+ * 候选为空 → 回落到官方全局档位(没有可判的来源);默认模型不在候选内
11529
+ * (宿主默认路由未配峰谷价)→ 用第一个候选。摘要接口不探测模型目录,
11530
+ * 因此复用已缓存的候选;缓存为空时同样回落到官方全局档位。
11531
+ */
11532
+ bandOf(options) {
11533
+ const models = options?.models ?? [];
11534
+ if (models.length === 0) return this.officialBand();
11535
+ const defaultModel = options?.defaultModel;
11536
+ const selected = defaultModel !== void 0 && models.some((model) => model.provider === defaultModel.provider && model.id === defaultModel.model) ? defaultModel : {
11537
+ provider: models[0].provider,
11538
+ model: models[0].id
11539
+ };
11540
+ const now = this.now();
11541
+ return {
11542
+ tier: this.tierOfTask(selected.provider, selected.model, now),
11543
+ nextSwitchInMs: this.nextSwitchMsOfTask(selected.provider, selected.model, now)
11544
+ };
11545
+ }
11307
11546
  async enqueue(input) {
11308
11547
  await this.enqueueMany([input]);
11309
11548
  }
@@ -11366,47 +11605,109 @@ var TaskQueueEngine = class {
11366
11605
  });
11367
11606
  }
11368
11607
  async modelOptions(controller, refresh = false) {
11369
- if (!refresh && this.modelCache !== void 0 && this.now() - this.modelCache.at < OPTIONS_CACHE_MS) return this.modelCache;
11608
+ if (!refresh && this.modelCache !== void 0 && this.now() - this.modelCache.at < OPTIONS_CACHE_MS) return this.modelOptionsOf(this.modelCache);
11370
11609
  const catalog = await controller.modelCatalog();
11371
- const models = [];
11610
+ const candidates = [];
11372
11611
  let officialRoute = false;
11612
+ let otherRouteWithPeakModel = false;
11373
11613
  for (const group of catalog.groups) {
11374
- if (group.id !== "deepseek-official") continue;
11375
- officialRoute = true;
11614
+ const channel = this.options.resolveRouteChannel?.(group.id);
11615
+ const official = group.id === DEEPSEEK_PLATFORM_ROUTE;
11616
+ if (official) officialRoute = true;
11617
+ if (!official && channel === void 0) continue;
11376
11618
  for (const model of group.models) {
11377
11619
  if (rateChannelOf(model.id, false) !== "deepseek-metered") continue;
11378
- models.push({
11620
+ if (!official) otherRouteWithPeakModel = true;
11621
+ if (!official && !this.hasPeakRule(channel.source, resolveCatalogKey(model.id))) continue;
11622
+ candidates.push({
11379
11623
  provider: group.id,
11380
11624
  providerName: group.name,
11381
11625
  id: model.id,
11382
- name: model.name
11626
+ name: model.name,
11627
+ saving: official ? "cash" : channel.saving
11383
11628
  });
11384
11629
  }
11385
11630
  }
11631
+ const blockedReason = candidates.length > 0 ? void 0 : officialRoute && !otherRouteWithPeakModel ? "no-official-model" : otherRouteWithPeakModel ? "no-scheduled-model" : "no-official-route";
11386
11632
  const candidate = catalog.default;
11387
11633
  const defaultModel = candidate === void 0 ? void 0 : {
11388
11634
  provider: candidate.provider,
11389
11635
  model: candidate.model
11390
11636
  };
11391
- const blockedReason = models.length > 0 ? void 0 : officialRoute ? "no-official-model" : "no-official-route";
11392
11637
  this.modelCache = {
11393
11638
  at: this.now(),
11394
- models,
11639
+ candidates,
11395
11640
  defaultModel,
11396
11641
  blockedReason
11397
11642
  };
11643
+ return this.modelOptionsOf(this.modelCache);
11644
+ }
11645
+ /** 缓存的目录事实 + 现算的档位 → 快照用的候选清单。 */
11646
+ modelOptionsOf(cache) {
11398
11647
  return {
11399
- models,
11400
- defaultModel,
11401
- blockedReason
11648
+ models: cache.candidates.map((entry) => this.decorateModel(entry)),
11649
+ defaultModel: cache.defaultModel,
11650
+ blockedReason: cache.blockedReason
11402
11651
  };
11403
11652
  }
11653
+ /**
11654
+ * 候选模型 + 它当前所处的档位(issue #143)。
11655
+ *
11656
+ * 档位按**该候选自己的来源**判定——不同来源可能同一时刻处于不同档位,
11657
+ * 逐候选给出,界面才能对所选模型说准话。
11658
+ */
11659
+ decorateModel(entry) {
11660
+ const now = this.now();
11661
+ return {
11662
+ ...entry,
11663
+ tier: this.tierOfTask(entry.provider, entry.id, now),
11664
+ nextSwitchInMs: this.nextSwitchMsOfTask(entry.provider, entry.id, now)
11665
+ };
11666
+ }
11667
+ /**
11668
+ * 用户是否为该来源 × 模型配了峰谷时段(issue #143)。
11669
+ *
11670
+ * 这是**用户显式声明「这个来源有峰谷分时」**的信号——与峰谷设置页同一份
11671
+ * 数据。订阅通道(如 `dsh-opencode-go`)的倍率表在厂商侧,插件无从探测;
11672
+ * 用户配了时段就说明他知道这个通道的分时规则,队列据此放行并按它排程。
11673
+ *
11674
+ * 注意判定键与峰谷设置页一致:`scheduleKey(source, 目录键)`——用**目录键**
11675
+ * (`resolveCatalogKey` 归一后)而非宿主原始模型 id,否则同一个模型在两处
11676
+ * 会对不上(#125 的同类坑)。
11677
+ */
11678
+ hasPeakRule(source, catalogKey) {
11679
+ const schedule = this.options.resolvePeakSchedule?.();
11680
+ if (schedule === void 0) return false;
11681
+ return schedule.models[scheduleKey(source, catalogKey)] !== void 0;
11682
+ }
11683
+ /**
11684
+ * 某条路由 × 某个模型此刻处于哪一档(issue #143:按来源判档)。
11685
+ *
11686
+ * 用户为该来源 × 模型配了时段就用它;没配时官方来源走全局窗口(含中国
11687
+ * 节假日),订阅来源走厂商倍率窗口(不含中国节假日——订阅厂商的倍率表里
11688
+ * 没有这一项)。
11689
+ */
11690
+ tierOfTask(provider, model, at) {
11691
+ return tierOf({
11692
+ channel: this.options.resolveRouteChannel?.(provider),
11693
+ schedule: this.options.resolvePeakSchedule?.(),
11694
+ catalogKey: resolveCatalogKey(model)
11695
+ }, at);
11696
+ }
11697
+ /** 某条路由 × 某个模型距下一次档位切换还有多久。 */
11698
+ nextSwitchMsOfTask(provider, model, at) {
11699
+ return nextSwitchMsOf({
11700
+ channel: this.options.resolveRouteChannel?.(provider),
11701
+ schedule: this.options.resolvePeakSchedule?.(),
11702
+ catalogKey: resolveCatalogKey(model)
11703
+ }, at);
11704
+ }
11404
11705
  async pump() {
11405
11706
  if (this.stopped || this.pumping) return;
11406
11707
  this.pumping = true;
11407
11708
  try {
11408
11709
  await this.recoverExpired();
11409
- if (this.stopped || tierAt(this.now()) !== "offPeak") return;
11710
+ if (this.stopped) return;
11410
11711
  if (usableController(this.options.getController()) === void 0) return;
11411
11712
  const task = await this.claimNext();
11412
11713
  if (task !== void 0) await this.execute(task);
@@ -11416,10 +11717,20 @@ var TaskQueueEngine = class {
11416
11717
  this.pumping = false;
11417
11718
  }
11418
11719
  }
11720
+ /**
11721
+ * 领取下一个可执行的任务(issue #143:按来源判档)。
11722
+ *
11723
+ * 档位闸门落在**任务自己**的来源 × 模型上,而不是全局单一窗口——不同来源
11724
+ * 可能同一时刻处于不同档位(订阅通道的倍率窗口与官方窗口不一定重合),
11725
+ * 逐任务判定才能让「现在能跑的那一路」先跑。全局闸门会让所有任务一起等。
11726
+ *
11727
+ * FIFO 语义保持不变:按入队顺序找**第一个**当前处于低谷的任务。
11728
+ */
11419
11729
  async claimNext() {
11420
11730
  let claimed;
11731
+ const now = this.now();
11421
11732
  await this.update((tasks) => {
11422
- const task = tasks.find((candidate) => candidate.status === "queued");
11733
+ const task = tasks.find((candidate) => candidate.status === "queued" && this.tierOfTask(candidate.provider, candidate.model, now) === "offPeak");
11423
11734
  if (task === void 0) return;
11424
11735
  const next = {
11425
11736
  ...task,
@@ -11468,7 +11779,7 @@ var TaskQueueEngine = class {
11468
11779
  this.heartbeat = heartbeat;
11469
11780
  try {
11470
11781
  if (!this.options.getWorkspaces().some((workspace) => workspace.path === claimed.cwd)) throw new TaskQueueError("workspace is no longer available", 409);
11471
- if (tierAt(this.now()) !== "offPeak") {
11782
+ if (this.tierOfTask(claimed.provider, claimed.model, this.now()) !== "offPeak") {
11472
11783
  await this.requeue(claimed.id);
11473
11784
  return;
11474
11785
  }
@@ -11480,7 +11791,7 @@ var TaskQueueEngine = class {
11480
11791
  if (!await this.patch(claimed.id, { fallbackReason: reuse.reason })) return;
11481
11792
  }
11482
11793
  const { models: availableModels } = await this.modelOptions(controller, true);
11483
- if (!availableModels.some((model) => model.provider === claimed.provider && model.id === claimed.model)) throw new TaskQueueError("the selected official DeepSeek model is no longer available", 409);
11794
+ if (!availableModels.some((model) => model.provider === claimed.provider && model.id === claimed.model)) throw new TaskQueueError("the selected DeepSeek model is no longer available", 409);
11484
11795
  sessionId = (await this.createGroupedSession(controller, claimed.cwd)).sessionId;
11485
11796
  }
11486
11797
  const sessionPatch = { sessionId };
@@ -11491,7 +11802,7 @@ var TaskQueueEngine = class {
11491
11802
  provider: claimed.provider,
11492
11803
  model: claimed.model
11493
11804
  });
11494
- if (tierAt(this.now()) !== "offPeak") {
11805
+ if (this.tierOfTask(claimed.provider, claimed.model, this.now()) !== "offPeak") {
11495
11806
  await this.requeue(claimed.id);
11496
11807
  return;
11497
11808
  }
@@ -11738,7 +12049,7 @@ function registerTaskQueueRoute(ctx, deps) {
11738
12049
  return;
11739
12050
  }
11740
12051
  if (req.method === "POST") {
11741
- if (!isLoopbackOrigin(req.headers.origin)) {
12052
+ if (!isLoopbackOrigin(req.headers.origin, deps.trustedHosts)) {
11742
12053
  send(res, 403, { error: "forbidden: loopback only" });
11743
12054
  return;
11744
12055
  }
@@ -12523,6 +12834,24 @@ function apply(ctx, config = {}) {
12523
12834
  });
12524
12835
  const taskQueue = new TaskQueueEngine({
12525
12836
  filePath: config.taskQueuePath ?? join(dshHome, ".dsh-usage-task-queue.json"),
12837
+ resolveRouteChannel: (route) => {
12838
+ if (route === "deepseek-official") return {
12839
+ source: `direct:${route}`,
12840
+ saving: "cash"
12841
+ };
12842
+ const subscription = subscriptionRoutes.has(route);
12843
+ const source = siteBucketKey(siteRefOf(route, readPiAiProviderRoutes(ctx.settings), { subscription }));
12844
+ if (source === "unknown") return void 0;
12845
+ if (subscription) return {
12846
+ source,
12847
+ saving: "quota"
12848
+ };
12849
+ return {
12850
+ source,
12851
+ saving: source.startsWith("site:") ? "cash" : "schedule"
12852
+ };
12853
+ },
12854
+ resolvePeakSchedule: schedules.current,
12526
12855
  getController: () => {
12527
12856
  try {
12528
12857
  return ctx.get("sessionController");
@@ -12930,9 +13259,10 @@ function apply(ctx, config = {}) {
12930
13259
  const providers = await readPiAiProviders(ctx.settings);
12931
13260
  const resolve = refResolver(ctx.credentials);
12932
13261
  const routes = [];
12933
- for (const [route, entry] of Object.entries(providers)) {
12934
- if (entry.baseURL === void 0) continue;
12935
- if (isOfficialBaseUrl(entry.baseURL)) continue;
13262
+ const candidates = selectRelayQuotaCandidates(providers, isOfficialBaseUrl, config.relayQuotaExclusions);
13263
+ for (const candidate of candidates) {
13264
+ const route = candidate.route;
13265
+ const entry = providers[route];
12936
13266
  const apiKeyRefs = [.../* @__PURE__ */ new Set([...entry.apiKeyEnv !== void 0 ? [entry.apiKeyEnv] : [], ...routeKeyRefCandidates(route)])];
12937
13267
  const hit = await firstResolvedRef(apiKeyRefs, resolve);
12938
13268
  if (entry.apiKeyEnv === void 0 && hit === void 0) continue;
@@ -25,6 +25,8 @@ type BillingBudgetStoreProps = PropsStore<ReturnType<typeof createBillingBudgetS
25
25
  export type UsageBillingProps = PropsRuntime<'sidebar.footer.action'> & SidebarFooterActionOwnerProps & InjectFace<UsageBillingInjected> & PropsRenderSlots<'billing.dashboard.decor'> & BillingBudgetStoreProps & PropsLocale<typeof NS> & {
26
26
  /** 原生设置页嵌入模式:只渲染完整设置分区,不渲染侧栏入口与弹窗外壳。 */
27
27
  embeddedSettings?: boolean;
28
+ /** 宿主 main 主面板:渲染完整仪表盘内容,但不渲染触发器、Modal 与关闭按钮。 */
29
+ embeddedPanel?: boolean;
28
30
  };
29
31
  /**
30
32
  * UsageBilling: sidebar trigger plus the billing dashboard modal.
@@ -0,0 +1,7 @@
1
+ /** 宿主 main 主面板:复用完整仪表盘,不再套底部触发器或 Modal(issue #144)。 */
2
+ import type { ReactNode } from 'react';
3
+ import { type UsageBillingProps } from './UsageBilling.tsx';
4
+ type UsageBillingMainPanelProps = Omit<UsageBillingProps, 'wide' | 'embeddedSettings' | 'embeddedPanel' | 'renderSlot' | '__renders'>;
5
+ export declare function UsageBillingMainPanel(props: UsageBillingMainPanelProps): ReactNode;
6
+ export {};
7
+ //# sourceMappingURL=UsageBillingMainPanel.d.ts.map
@@ -0,0 +1,5 @@
1
+ /** sidebar.panellist 的纯导航图标;宿主拥有外层按钮与选中态。 */
2
+ import { type ReactNode } from 'react';
3
+ import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots';
4
+ export declare function UsageBillingPanelIcon({ size }: PropsRuntime<'sidebar.panellist'>): ReactNode;
5
+ //# sourceMappingURL=UsageBillingPanelIcon.d.ts.map
@@ -151,6 +151,9 @@ export interface UsageBillingInjected {
151
151
  monthCost: number;
152
152
  }) => void;
153
153
  registerOpen: (handler: () => void) => () => void;
154
+ /** 宿主是否同时具备 main 与 sidebar.panellist;决定左侧入口能否安全独占(issue #144)。 */
155
+ leftPanelAvailable: () => boolean;
156
+ subscribeLeftPanelAvailable: (listener: () => void) => () => void;
154
157
  /** 原生设置页或 /usage 是否至少一个可用;完全隐藏必须有恢复入口(issue #108 防锁死)。 */
155
158
  recoveryEntryAvailable: boolean;
156
159
  /**