@kenz1117/dsh-ui-usage-billing 1.8.14 → 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)。
@@ -11176,6 +11248,128 @@ function registerUsageStatsRoute(ctx, deps) {
11176
11248
  }), "usage-billing: usage-stats route");
11177
11249
  }
11178
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
11179
11373
  //#region lib/types/task-queue.js
11180
11374
  /**
11181
11375
  * Durable off-peak FIFO task queue (issue #106, new-host capability preview).
@@ -11253,6 +11447,12 @@ var TaskQueueEngine = class {
11253
11447
  taskAbort;
11254
11448
  stopped = true;
11255
11449
  pumping = false;
11450
+ /**
11451
+ * 模型目录缓存(issue #143)。
11452
+ *
11453
+ * 只缓存**目录事实**(候选清单与根因),**不缓存档位**——档位随时间变化,
11454
+ * 缓存 60 秒会让面板显示过期的「距高峰还有 N 分钟」。每次快照现算档位。
11455
+ */
11256
11456
  modelCache;
11257
11457
  constructor(options) {
11258
11458
  this.options = options;
@@ -11279,42 +11479,70 @@ var TaskQueueEngine = class {
11279
11479
  this.taskAbort?.abort();
11280
11480
  }
11281
11481
  async snapshot(refreshModels = false) {
11282
- const countdown = channelCountdown(this.now(), "deepseek-metered");
11283
11482
  const controller = usableController(this.options.getController());
11284
11483
  const base = {
11285
11484
  supported: controller !== void 0,
11286
- tier: tierAt(this.now()),
11287
- nextSwitchInMs: countdown?.nextSwitchInMs ?? 0,
11288
11485
  tasks: (await this.readDocument()).tasks.map(publicTask),
11289
11486
  workspaces: this.options.getWorkspaces()
11290
11487
  };
11291
11488
  if (controller === void 0) return {
11292
11489
  ...base,
11490
+ ...this.officialBand(),
11293
11491
  models: []
11294
11492
  };
11295
11493
  try {
11494
+ const options = await this.modelOptions(controller, refreshModels);
11296
11495
  return {
11297
11496
  ...base,
11298
- ...await this.modelOptions(controller, refreshModels)
11497
+ ...this.bandOf(options),
11498
+ ...options
11299
11499
  };
11300
11500
  } catch (error) {
11301
11501
  return {
11302
11502
  ...base,
11503
+ ...this.officialBand(),
11303
11504
  models: [],
11304
11505
  optionsError: messageOf(error)
11305
11506
  };
11306
11507
  }
11307
11508
  }
11308
11509
  async summary() {
11309
- const countdown = channelCountdown(this.now(), "deepseek-metered");
11310
11510
  const document = await this.readDocument();
11311
11511
  return {
11312
11512
  supported: usableController(this.options.getController()) !== void 0,
11313
- tier: tierAt(this.now()),
11314
- nextSwitchInMs: countdown?.nextSwitchInMs ?? 0,
11513
+ ...this.bandOf(this.modelCache === void 0 ? void 0 : this.modelOptionsOf(this.modelCache)),
11315
11514
  queuedCount: document.tasks.filter((task) => task.status === "queued").length
11316
11515
  };
11317
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
+ }
11318
11546
  async enqueue(input) {
11319
11547
  await this.enqueueMany([input]);
11320
11548
  }
@@ -11377,47 +11605,109 @@ var TaskQueueEngine = class {
11377
11605
  });
11378
11606
  }
11379
11607
  async modelOptions(controller, refresh = false) {
11380
- 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);
11381
11609
  const catalog = await controller.modelCatalog();
11382
- const models = [];
11610
+ const candidates = [];
11383
11611
  let officialRoute = false;
11612
+ let otherRouteWithPeakModel = false;
11384
11613
  for (const group of catalog.groups) {
11385
- if (group.id !== "deepseek-official") continue;
11386
- 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;
11387
11618
  for (const model of group.models) {
11388
11619
  if (rateChannelOf(model.id, false) !== "deepseek-metered") continue;
11389
- models.push({
11620
+ if (!official) otherRouteWithPeakModel = true;
11621
+ if (!official && !this.hasPeakRule(channel.source, resolveCatalogKey(model.id))) continue;
11622
+ candidates.push({
11390
11623
  provider: group.id,
11391
11624
  providerName: group.name,
11392
11625
  id: model.id,
11393
- name: model.name
11626
+ name: model.name,
11627
+ saving: official ? "cash" : channel.saving
11394
11628
  });
11395
11629
  }
11396
11630
  }
11631
+ const blockedReason = candidates.length > 0 ? void 0 : officialRoute && !otherRouteWithPeakModel ? "no-official-model" : otherRouteWithPeakModel ? "no-scheduled-model" : "no-official-route";
11397
11632
  const candidate = catalog.default;
11398
11633
  const defaultModel = candidate === void 0 ? void 0 : {
11399
11634
  provider: candidate.provider,
11400
11635
  model: candidate.model
11401
11636
  };
11402
- const blockedReason = models.length > 0 ? void 0 : officialRoute ? "no-official-model" : "no-official-route";
11403
11637
  this.modelCache = {
11404
11638
  at: this.now(),
11405
- models,
11639
+ candidates,
11406
11640
  defaultModel,
11407
11641
  blockedReason
11408
11642
  };
11643
+ return this.modelOptionsOf(this.modelCache);
11644
+ }
11645
+ /** 缓存的目录事实 + 现算的档位 → 快照用的候选清单。 */
11646
+ modelOptionsOf(cache) {
11409
11647
  return {
11410
- models,
11411
- defaultModel,
11412
- blockedReason
11648
+ models: cache.candidates.map((entry) => this.decorateModel(entry)),
11649
+ defaultModel: cache.defaultModel,
11650
+ blockedReason: cache.blockedReason
11413
11651
  };
11414
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
+ }
11415
11705
  async pump() {
11416
11706
  if (this.stopped || this.pumping) return;
11417
11707
  this.pumping = true;
11418
11708
  try {
11419
11709
  await this.recoverExpired();
11420
- if (this.stopped || tierAt(this.now()) !== "offPeak") return;
11710
+ if (this.stopped) return;
11421
11711
  if (usableController(this.options.getController()) === void 0) return;
11422
11712
  const task = await this.claimNext();
11423
11713
  if (task !== void 0) await this.execute(task);
@@ -11427,10 +11717,20 @@ var TaskQueueEngine = class {
11427
11717
  this.pumping = false;
11428
11718
  }
11429
11719
  }
11720
+ /**
11721
+ * 领取下一个可执行的任务(issue #143:按来源判档)。
11722
+ *
11723
+ * 档位闸门落在**任务自己**的来源 × 模型上,而不是全局单一窗口——不同来源
11724
+ * 可能同一时刻处于不同档位(订阅通道的倍率窗口与官方窗口不一定重合),
11725
+ * 逐任务判定才能让「现在能跑的那一路」先跑。全局闸门会让所有任务一起等。
11726
+ *
11727
+ * FIFO 语义保持不变:按入队顺序找**第一个**当前处于低谷的任务。
11728
+ */
11430
11729
  async claimNext() {
11431
11730
  let claimed;
11731
+ const now = this.now();
11432
11732
  await this.update((tasks) => {
11433
- 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");
11434
11734
  if (task === void 0) return;
11435
11735
  const next = {
11436
11736
  ...task,
@@ -11479,7 +11779,7 @@ var TaskQueueEngine = class {
11479
11779
  this.heartbeat = heartbeat;
11480
11780
  try {
11481
11781
  if (!this.options.getWorkspaces().some((workspace) => workspace.path === claimed.cwd)) throw new TaskQueueError("workspace is no longer available", 409);
11482
- if (tierAt(this.now()) !== "offPeak") {
11782
+ if (this.tierOfTask(claimed.provider, claimed.model, this.now()) !== "offPeak") {
11483
11783
  await this.requeue(claimed.id);
11484
11784
  return;
11485
11785
  }
@@ -11491,7 +11791,7 @@ var TaskQueueEngine = class {
11491
11791
  if (!await this.patch(claimed.id, { fallbackReason: reuse.reason })) return;
11492
11792
  }
11493
11793
  const { models: availableModels } = await this.modelOptions(controller, true);
11494
- 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);
11495
11795
  sessionId = (await this.createGroupedSession(controller, claimed.cwd)).sessionId;
11496
11796
  }
11497
11797
  const sessionPatch = { sessionId };
@@ -11502,7 +11802,7 @@ var TaskQueueEngine = class {
11502
11802
  provider: claimed.provider,
11503
11803
  model: claimed.model
11504
11804
  });
11505
- if (tierAt(this.now()) !== "offPeak") {
11805
+ if (this.tierOfTask(claimed.provider, claimed.model, this.now()) !== "offPeak") {
11506
11806
  await this.requeue(claimed.id);
11507
11807
  return;
11508
11808
  }
@@ -12534,6 +12834,24 @@ function apply(ctx, config = {}) {
12534
12834
  });
12535
12835
  const taskQueue = new TaskQueueEngine({
12536
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,
12537
12855
  getController: () => {
12538
12856
  try {
12539
12857
  return ctx.get("sessionController");
@@ -12941,9 +13259,10 @@ function apply(ctx, config = {}) {
12941
13259
  const providers = await readPiAiProviders(ctx.settings);
12942
13260
  const resolve = refResolver(ctx.credentials);
12943
13261
  const routes = [];
12944
- for (const [route, entry] of Object.entries(providers)) {
12945
- if (entry.baseURL === void 0) continue;
12946
- 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];
12947
13266
  const apiKeyRefs = [.../* @__PURE__ */ new Set([...entry.apiKeyEnv !== void 0 ? [entry.apiKeyEnv] : [], ...routeKeyRefCandidates(route)])];
12948
13267
  const hit = await firstResolvedRef(apiKeyRefs, resolve);
12949
13268
  if (entry.apiKeyEnv === void 0 && hit === void 0) continue;
@@ -14,15 +14,22 @@
14
14
  * - 数同排的可见占位者(展开 display:contents 的子项,排除自己与不可见元素);
15
15
  * - 读行的 `flex-direction`(`column` = 纵向栈)。
16
16
  *
17
- * 判定(§25 方案 A:卡片型占用者有邻居时降级为按钮形态):
18
- * - 横向行且有邻居 → 收成 36×36 图标钮(此时禁止 `width:100%`);
19
- * - 纵向座位 → 只有「放不下宽卡」的窄座才收成图标钮;**整行宽座**(第三方
20
- * 皮肤显式给出的宽座,客人被拉满整行、宽卡放得下)保留宽卡(issue #140);
21
- * - 其余(独占一行 / 测不到行)→ 保持宽卡。
17
+ * 判定分四档(issue #148;前两档沿用社区约定 §25 方案 A):
18
+ * - `full`(用户显式选择):**无条件宽卡**,不做邻居 / 容量判断——用户的显式
19
+ * 意图优先于自动收窄;代价(同槽邻居被挤压)由触发卡悬停提示写明;
20
+ * - `compact`:无条件 36×36 图标钮;
21
+ * - `auto`(默认):按**座位容量**决定(社区约定 §20 的容量公式)——横向行用
22
+ * 「行宽 − 容器内边距 − 邻居占位」算出留给宽卡的空间,放得下出宽卡、放不下
23
+ * 收成图标钮;纵向座位仍按 §25.6:「整行宽座」保留宽卡,窄竖条收成图标钮
24
+ * (issue #140)。
25
+ *
26
+ * 宽度测不到时(未布局 / 座位不可见)**fail-closed 先收窄**,等 `ResizeObserver`
27
+ * 拿到真实尺寸再切回宽卡——宁可短暂多一个图标钮,也不要先把邻居挤出面板。
22
28
  *
23
29
  * 本模块只做测量与判定,不碰宿主容器(不得注入 `flex-wrap` /
24
30
  * `flex-direction` / `order`,见 §25 硬规则 2)。
25
31
  */
32
+ import type { BillingCardMode } from './usage-billing-settings.ts';
26
33
  /** 同槽占位事实。 */
27
34
  export interface FooterLaneFacts {
28
35
  /** 真正的行容器(最近的 flex 祖先);找不到时为 null(此时没有横向挤占问题)。 */
@@ -52,11 +59,45 @@ export interface FooterLaneWatch {
52
59
  */
53
60
  export declare function measureFooterLane(self: HTMLElement): FooterLaneFacts;
54
61
  /**
55
- * 由占位事实判定触发卡形态(社区约定 §25 方案 A)。
62
+ * 横向座位放不放得下宽卡(社区约定 §20 的容量公式)。
63
+ *
64
+ * `available = 行宽 − 容器内边距 − 邻居数 × (占位 112 + 间距 4)`,
65
+ * `available ≥ 141` 才放得下宽卡(卡面在 ≤140px 时只剩仪表图标)。
66
+ * 等价于「行宽 ≥ 157 + 邻居数 × 116」:0 邻居 → 157px、1 邻居 → 273px、
67
+ * 2 邻居 → 389px、3 邻居 → 505px。
68
+ *
69
+ * 宽度测不到(未布局 / 座位不可见)时 **fail-closed 返回 false**:宁可先收成
70
+ * 图标钮,也不要先把邻居挤出面板;`ResizeObserver` 拿到真实尺寸后会重算并切回。
71
+ * 刻意不用 `offsetParent` 判可见性——`position:fixed` 的行 `offsetParent` 为
72
+ * null,但它是**有**布局盒的(宽度可测),不该被误判成测不到。
73
+ *
74
+ * @param facts - 同槽占位事实。
75
+ * @returns 放得下宽卡返回 true。
76
+ */
77
+ export declare function fitsWideCard(facts: FooterLaneFacts): boolean;
78
+ /**
79
+ * 由占位事实 + 用户选择的形态档判定触发卡形态。
80
+ *
81
+ * - `full`:**无条件宽卡**——用户的显式意图优先于自动收窄(issue #148);
82
+ * 代价(同槽邻居被挤压)由调用方用 `facts.neighbors` 写进悬停提示;
83
+ * - `compact`:无条件图标钮;
84
+ * - `auto`(默认):按座位容量判断——横向行用 §20 容量公式,纵向座位沿用
85
+ * §25.6(「整行宽座」保留宽卡,窄竖条收成图标钮);
86
+ * - `hidden`:入口整体不渲染,形态判定无意义(调用方提前返回 null),这里按
87
+ * `auto` 处理。
88
+ *
56
89
  * @param facts - 同槽占位事实。
90
+ * @param mode - 侧栏入口形态档。
57
91
  * @returns `icon` = 收成 36×36 图标钮;`card` = 保持宽卡。
58
92
  */
59
- export declare function resolveTriggerForm(facts: FooterLaneFacts): TriggerForm;
93
+ export declare function resolveTriggerForm(facts: FooterLaneFacts, mode: BillingCardMode): TriggerForm;
94
+ /** 同槽占位状态:形态 + 邻居数(邻居数用于「强制宽卡挤压了几个」的提示)。 */
95
+ export interface FooterLaneState {
96
+ /** 触发卡形态(宽卡 / 图标钮)。 */
97
+ form: TriggerForm;
98
+ /** 同行可见占位者数量(不含自己)。 */
99
+ neighbors: number;
100
+ }
60
101
  /**
61
102
  * 观察同槽占位变化,形态变化时回调。
62
103
  *
@@ -65,8 +106,9 @@ export declare function resolveTriggerForm(facts: FooterLaneFacts): TriggerForm;
65
106
  * 只在**形态真的变了**时回调,避免自触发成环。
66
107
  *
67
108
  * @param self - 本插件在行内的元素。
68
- * @param onForm - 形态变化回调。
109
+ * @param mode - 侧栏入口形态档(`full` / `compact` 会在判定里直接短路)。
110
+ * @param onState - 形态 / 邻居数变化回调。
69
111
  * @returns 观察句柄。
70
112
  */
71
- export declare function watchFooterLane(self: HTMLElement, onForm: (form: TriggerForm) => void): FooterLaneWatch;
113
+ export declare function watchFooterLane(self: HTMLElement, mode: BillingCardMode, onState: (state: FooterLaneState) => void): FooterLaneWatch;
72
114
  //# sourceMappingURL=footer-lane.d.ts.map