dsh-unified-router 0.8.3 → 0.8.4

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.
@@ -68,8 +68,9 @@
68
68
  | 输出快捷档最多提供 `512K`;模型能力更高时仍可通过自定义数值调整,受上下文和渠道限制 | 避免同为 `1M` 的上下文和输出产生无法选择的顶档 | `test/automation-and-ux.test.mjs` |
69
69
  | **同名模型(如 Raccoon 免费/订阅)必须显示模型 id**;其它情况可只在重名时显示 | 免费/付费两侧展示名相同,只有 `-p` 后缀能区分 | 渲染核对(窄屏 id 换行显示) |
70
70
  | **倍率只由选择器原生 badge 显示**,`name` 里不得再拼「· x0.75 / · 免费」。只显示上游或已核验目录的扣费倍率、优惠和免费状态;商汤和云知声目录没有已核验的逐模型倍率 | 同一信息出现一次,统一设置页和会话选择器 | `test/model-rate-badge.test.mjs`、`test/model-rate-badge-paths.test.mjs` |
71
+ | 上游同时给出多档倍率、无法选定单一生效档时,设置页和选择器显示范围(如 `x0.09–x0.18`),不挑一档冒充当前价 | CodeArts 的峰谷倍率都能看见,模型名和实际扣费不受影响 | `test/model-rate-badge-paths.test.mjs`、`test/web-client.test.mjs` |
71
72
  | **订阅限定(仅付费会员可用)挂独立「订阅限定」徽标(info)**,与倍率/免费徽标并存、互不覆盖。判据来自官方会员门槛声明或上游目录的订阅标志,**不按倍率推断**;缺失即不挂标。TRAE 的 Qwen4、GLM-5.4、Kimi-K3.1 系列为付费专用 | 用户要求区分 TRAE/Qoder 的订阅限定模型;倍率高低不等于会员门槛 | `test/model-rate-badge.test.mjs` 与 `test/web-client.test.mjs` 订阅限定用例 |
72
- | **小浣熊「统一免费与订阅模型」开关在渠道分区(默认关)**:开启后模型分区只显示一个「统一模型」组,统一 id = 免费侧 id,订阅侧条目去 `-p` 合并、免费侧条目优先(徽标与思考档以免费面为准);额度药丸显示全部账号。关闭时恢复免费/订阅两组与按套餐过滤 | 同名模型只出现一次;免费额度用尽自动改用订阅账号,订阅账号出站请求自动加 `-p`、限流键按本侧真实 id 记 | `test/raccoon-unified.test.mjs`、`test/quota-pill.test.mjs` |
73
+ | **小浣熊「统一免费与订阅模型」开关在渠道分区(默认关)**:开启后模型分区只显示一个「统一模型」组,订阅侧条目去 `-p` 合并、免费侧条目优先(徽标与思考档以免费面为准);额度药丸显示全部账号。关闭时恢复免费/订阅两组与按套餐过滤 | 同名模型只出现一次;订阅独有模型直接走订阅账号;两侧共有的模型才在免费侧不可用时改走订阅。出站与限流键使用目录里的本侧实际 ID | `test/raccoon-unified.test.mjs`、`test/quota-pill.test.mjs` |
73
74
  | 设置列表和会话选择器统一清理 ID 格式的展示名,即使上游的名称与请求 ID 不同。内部代号(`qmodel_38max` / `qfmodel`…)使用已知别名,请求 ID 原样保留 | 「模型名显示的是内部代号」 | `test/qoder-cli.test.mjs` 别名用例 |
74
75
 
75
76
  ### 3.1 会话输入栏的上下文窗口药丸
@@ -22,6 +22,12 @@
22
22
  | **AStudio** (`astudio`) | 本机导入(读取 `astron-session.json` / `config.toml`)、微信扫码 SSO、粘贴 JWT/JSON | 目录 `GET .../api/v1/model-manager/models`(自动补位 `xdeepseek-flash-in`);推理走 `POST .../model-gateway/v1/responses`(`store:false`,关闭思考发 `reasoning.effort:"none"`) | 余额 `points/balance` + `membership/me`(字段 `totalBalance` / `activityTotal+activityBalance` / `memberTotal+memberBalance` / `buyTotal+buyBalance` / `sparkTotalBalance`,实测口径 `totalBalance` = 各分项余额之和);每日签到(先查北京时间 `points/details` GRANT 流水零写判重,无则 `init-app` + 关闭 `DAILY_REWARD_DIALOG`);`claimRewards` 领取新人弹窗 | **积分只认 `ssoSessionId`**:实测 `points/balance` 单独带 `account_id`、单独带 `token`、或两者同带都回 `code 80000`,只有 `ssoSessionId` 能通。故仅粘贴 `modelBearerToken` 的账号读不到积分,报 `no_web_session`(界面显示「仅推理 Token · 不读积分」),不再显示「额度待更新」或误判登录失效 |
23
23
  | **CodeArts** (`codearts`) | 本机导入(Windows 同用户 DPAPI + AES-256-GCM 解密 `%APPDATA%\codearts\secretStorage`,兼容 JSON 字符串形态的 DPoP JWK;导入与推理按账号单飞自动刷新)、浏览器 OAuth(PKCE 128-hex + ES256 DPoP,`127.0.0.1:>=10000/oauth/callback`,同时兼容 `code` 与 `secret` ticket 回调)、粘贴 JSON 凭据 | `GET /v1/model/builtin` + 免费权益 `opengw.../gateway/config`(`SDK-HMAC-SHA256` 签名);推理走 `/api/v2/chat/completions`(输出上限按 v2 `RANGE_VALIDATOR` 夹取 `65536`、合并相邻同角色消息、免费模型带 `maas_type:benefit`,遇 `APIG.0602` 令牌过期自动刷新重签重试一次) | `snap-manager/v1/statistics/plugin` + 免费日池 `user/tokens/balance`;每日签到(`events/trigger user.login` + `ops/delivery?channel=DESKTOP` + `claim` + `confirm`);`claimRewards` 领取可领活动福利 | `refresh_token` 为一次性轮换,与本机桌面端共用同一会话刷新会导致对端需要重新登录;本机导入账号在刷新失败或缺失 DPoP 密钥时回退重读本机 `secretStorage` 自愈 |
24
24
 
25
+ ### CodeArts 模型积分倍率
26
+
27
+ - 倍率直接读取 `GET /v1/model/builtin` 的 `builtinModels[].credit[].ratio_display`,兼容旧版的单对象 `credit`。2026-11-27 只读实测 12 个模型均返回倍率数组;同一倍率可能因输入或输出区间重复出现。
28
+ - 所有档位的倍率相同就显示单值;倍率不同就显示上游值的范围。比如 DeepSeek-V4.1-Flash 显示 `x0.09–x0.18`,DeepSeek-V4.1-Flash-1017 显示 `x0.12–x0.18`。范围不是某一时刻的生效价,不作为单一倍率参与推荐比较。峰谷时段见[华为云积分计费说明](https://support.huaweicloud.com/price-codeartsagent/codeartsagent_billing_0028.html)。
29
+ - 设置页和选择器共用解析后的模型目录;档位不全不挂倍率,仅在上游明确标免费或所有档位都是零时标「免费」。倍率随现有目录刷新更新,不新增请求。双入口见 [倍率回归](../test/model-rate-badge-paths.test.mjs)。
30
+
25
31
  ### 推理响应兼容
26
32
 
27
33
  - CodeArts 推理使用 `/api/v2/chat/completions`。`openpangu-2.0-flash` 在旧 v1 路径出现无正文的结束帧;同账号的 v2 请求返回标准 OpenAI 正文和用量帧。旧版累计 `text`、顶层 `delta.content` 和完整 `choices[].message` 仍转为增量,去除重复快照;已返回工具调用时将 `stop`、`other` 或仅有 `[DONE]` 的收尾归一为 `tool_calls`。裸断流不补成功终止,业务错误返回固定摘要。
package/lib/auto-tasks.js CHANGED
@@ -262,6 +262,9 @@ export function createAutoTasks({ dir, adapters, isEnabled, now = Date.now, onCh
262
262
  outcome: verdict.outcome, local: record,
263
263
  localIsDone: localDone, confirmed, confirmedIsDone: secured,
264
264
  })
265
+ if (verified && verdict.state === 'done' && !localDone && !secured) {
266
+ await onChange?.(provider, mode, outcome)
267
+ }
265
268
  results.push({ ...row, outcome, repeated: true, verified })
266
269
  }
267
270
  return results
package/lib/backend.js CHANGED
@@ -14022,11 +14022,7 @@ var RaccoonAdapter = class extends LlmAdapter3 {
14022
14022
  this.options = options;
14023
14023
  this.product = options.product ?? RACCOON;
14024
14024
  this.fetchImpl = options.fetchImpl ?? fetch;
14025
- const cached2 = readCatalogCache(options.catalogFile);
14026
- if (cached2) {
14027
- this.remoteModels = cached2;
14028
- this.catalogSource = "cached";
14029
- }
14025
+ this.syncCatalogScope();
14030
14026
  this.fallbackIndex = new Map(this.product.fallbackModels.map((model) => [model.id, model]));
14031
14027
  }
14032
14028
  product;
@@ -14038,6 +14034,25 @@ var RaccoonAdapter = class extends LlmAdapter3 {
14038
14034
  /** 目录加载闸门:并发去重 + 失败/空结果冷却(见 `remote-catalog-gate.ts`)。 */
14039
14035
  catalogGate = new RemoteCatalogGate();
14040
14036
  catalogSource = "fallback";
14037
+ catalogScope;
14038
+ syncCatalogScope() {
14039
+ const scope = this.options.catalogScope?.() ?? "";
14040
+ if (scope !== this.catalogScope) {
14041
+ this.catalogScope = scope;
14042
+ this.remoteModels = readCatalogCache(this.catalogFileFor(scope), scope);
14043
+ this.catalogSource = this.remoteModels ? "cached" : "fallback";
14044
+ this.catalogGate.reset();
14045
+ }
14046
+ return scope;
14047
+ }
14048
+ catalogFileFor(scope) {
14049
+ const file = this.options.catalogFile;
14050
+ return file && scope ? `${file}.${scope}` : file;
14051
+ }
14052
+ unifiedAvailability(modelId) {
14053
+ this.syncCatalogScope();
14054
+ return this.remoteModels?.find((model) => model.id === modelId)?.unifiedAvailability;
14055
+ }
14041
14056
  /**
14042
14057
  * 描述本适配器拥有的 provider 路由。
14043
14058
  *
@@ -14057,12 +14072,15 @@ var RaccoonAdapter = class extends LlmAdapter3 {
14057
14072
  * 只有远端目录才是「上游全量」的证据,兜底表只是精选子集。
14058
14073
  */
14059
14074
  catalogStatus() {
14075
+ this.syncCatalogScope();
14060
14076
  return { source: this.catalogSource };
14061
14077
  }
14062
14078
  isRemoteCatalog() {
14079
+ this.syncCatalogScope();
14063
14080
  return this.remoteModels !== void 0 && this.catalogSource === "remote";
14064
14081
  }
14065
14082
  listAllModels() {
14083
+ this.syncCatalogScope();
14066
14084
  const source = this.remoteModels ?? this.product.fallbackModels.map(fallbackToRemote);
14067
14085
  return source.map((model) => {
14068
14086
  const fallback = this.fallbackIndex.get(model.id);
@@ -14094,15 +14112,16 @@ var RaccoonAdapter = class extends LlmAdapter3 {
14094
14112
  * 并用 {@link RemoteCatalogGate} 的冷却挡住「每模型重试一次」的放大。
14095
14113
  */
14096
14114
  async loadModels() {
14115
+ const scope = this.syncCatalogScope();
14097
14116
  if (this.remoteModels !== void 0) return this.remoteModels;
14098
14117
  const fetchRemote = this.options.fetchRemoteModels;
14099
14118
  if (fetchRemote !== void 0) {
14100
14119
  await this.catalogGate.run(async () => {
14101
14120
  const fetched = await fetchRemote();
14102
- if (fetched.length === 0) return false;
14121
+ if (this.syncCatalogScope() !== scope || fetched.length === 0) return false;
14103
14122
  this.remoteModels = fetched;
14104
14123
  this.catalogSource = "remote";
14105
- await saveCatalogCache(this.options.catalogFile, fetched).catch(() => {
14124
+ await saveCatalogCache(this.catalogFileFor(scope), fetched, scope).catch(() => {
14106
14125
  });
14107
14126
  return true;
14108
14127
  });
@@ -14112,20 +14131,21 @@ var RaccoonAdapter = class extends LlmAdapter3 {
14112
14131
  }
14113
14132
  /** Refresh without clearing the last successful catalog. */
14114
14133
  async refreshRemoteModels() {
14134
+ const scope = this.syncCatalogScope();
14115
14135
  const fetchRemote = this.options.fetchRemoteModels;
14116
14136
  if (fetchRemote && await providerCatalogVisible(this.options.accountPool, this.product.id)) {
14117
14137
  let updated = false;
14118
14138
  await this.catalogGate.run(async () => {
14119
14139
  const models = await fetchRemote();
14120
- if (!models.length) return false;
14140
+ if (this.syncCatalogScope() !== scope || !models.length) return false;
14121
14141
  this.remoteModels = models;
14122
14142
  this.catalogSource = "remote";
14123
14143
  updated = true;
14124
- await saveCatalogCache(this.options.catalogFile, models).catch(() => {
14144
+ await saveCatalogCache(this.catalogFileFor(scope), models, scope).catch(() => {
14125
14145
  });
14126
14146
  return true;
14127
14147
  }, { force: true });
14128
- if (!updated && this.remoteModels) this.catalogSource = "cached";
14148
+ if (!updated && this.syncCatalogScope() === scope && this.remoteModels) this.catalogSource = "cached";
14129
14149
  }
14130
14150
  return { count: this.remoteModels?.length ?? this.product.fallbackModels.length, source: this.catalogSource };
14131
14151
  }
@@ -14215,6 +14235,9 @@ var RaccoonAdapter = class extends LlmAdapter3 {
14215
14235
  }
14216
14236
  let credential = await this.options.resolveCredential(options.model);
14217
14237
  let accountId = credential === void 0 ? void 0 : await this.options.accountPool?.findAccountIdByCredential(this.product.id, credential.access_token);
14238
+ if (credential === void 0 && entry?.unifiedAvailability?.freeExcluded === true) {
14239
+ throw new LlmError9("raccoon: \u6B64\u6A21\u578B\u6CA1\u6709\u53EF\u7528\u8BA2\u9605\u8D26\u53F7", "MISSING_CREDENTIAL");
14240
+ }
14218
14241
  if (credential === void 0 || isRaccoonExpired(credential)) {
14219
14242
  credential = await this.options.refresh(accountId || void 0) ?? await this.options.resolveCredential(options.model);
14220
14243
  }
@@ -14389,12 +14412,21 @@ function registerRaccoonLlm(ctx, options) {
14389
14412
 
14390
14413
  // src/backend/providers/raccoon.ts
14391
14414
  function mergeUnifiedRaccoonCatalogs(freeModels, proModels) {
14392
- const seen = new Set(freeModels.map((model) => model.id));
14393
- const extra = proModels.flatMap((model) => {
14415
+ const proById = /* @__PURE__ */ new Map();
14416
+ for (const model of proModels) {
14394
14417
  const id = model.id.endsWith("-p") ? model.id.slice(0, -2) : model.id;
14395
- return seen.has(id) ? [] : [{ ...model, id }];
14418
+ if (!proById.has(id)) proById.set(id, model);
14419
+ }
14420
+ const free = freeModels.map((model) => {
14421
+ const pro = proById.get(model.id);
14422
+ proById.delete(model.id);
14423
+ return { ...model, unifiedAvailability: pro ? { proId: pro.id } : proModels.length ? { proId: null } : {} };
14396
14424
  });
14397
- return [...freeModels, ...extra];
14425
+ return [...free, ...[...proById].map(([id, model]) => ({
14426
+ ...model,
14427
+ id,
14428
+ unifiedAvailability: { ...freeModels.length ? { freeExcluded: true } : {}, proId: model.id }
14429
+ }))];
14398
14430
  }
14399
14431
  function mountRaccoon({ ctx, pool, throwIfAllAccountsRateLimited, readImage, readImageRequest, catalogFile, noteQuotaAccount }, isUnifiedModels) {
14400
14432
  const raccoonSideOf = (entry) => entry.plan === "pro" ? "pro" : "free";
@@ -14422,15 +14454,20 @@ function mountRaccoon({ ctx, pool, throwIfAllAccountsRateLimited, readImage, rea
14422
14454
  return typeof value === "function" ? value.bind(target) : value;
14423
14455
  }
14424
14456
  });
14457
+ const unifiedRoute = (modelId) => {
14458
+ const available = raccoonAdapter.unifiedAvailability(modelId);
14459
+ return {
14460
+ free: available?.freeExcluded !== true,
14461
+ proId: available?.proId === null ? null : available?.proId ?? (modelId ? `${modelId}-p` : null)
14462
+ };
14463
+ };
14425
14464
  const raccoonUnifiedPick = async (modelId, exclude) => {
14426
- if (modelId.length === 0) {
14427
- const free2 = await pool.getAvailableAccount(RACCOON.id, "", unionIds(exclude, raccoonOtherSideIds("free")));
14428
- return free2 ? { pick: free2, wire: "" } : null;
14429
- }
14430
- const free = await pool.getAvailableAccount(RACCOON.id, modelId, unionIds(exclude, raccoonOtherSideIds("free")));
14431
- if (free) return { pick: free, wire: modelId };
14432
- const pro = await pool.getAvailableAccount(RACCOON.id, `${modelId}-p`, unionIds(exclude, raccoonOtherSideIds("pro")));
14433
- return pro ? { pick: pro, wire: `${modelId}-p` } : null;
14465
+ const route = unifiedRoute(modelId);
14466
+ if (route.free) {
14467
+ const free = await pool.getAvailableAccount(RACCOON.id, modelId, unionIds(exclude, raccoonOtherSideIds("free")));
14468
+ if (free) return free;
14469
+ }
14470
+ return route.proId === null ? null : pool.getAvailableAccount(RACCOON.id, route.proId, unionIds(exclude, raccoonOtherSideIds("pro")));
14434
14471
  };
14435
14472
  const raccoonSideCredential = async (side) => {
14436
14473
  try {
@@ -14443,12 +14480,12 @@ function mountRaccoon({ ctx, pool, throwIfAllAccountsRateLimited, readImage, rea
14443
14480
  };
14444
14481
  const mountRaccoon2 = (product, auth, side, proRemoteFetch2) => registerRaccoonLlm(ctx, {
14445
14482
  catalogFile: catalogFile(product.id),
14483
+ ...side === "free" ? { catalogScope: () => unified() ? "unified-routing-v1" : "" } : {},
14446
14484
  credentialRef: credentialRef6(product.defaultCredentialRef),
14447
14485
  resolveCredential: async (modelId) => {
14448
14486
  let available = null;
14449
14487
  if (side === "free" && unified()) {
14450
- const pick = await raccoonUnifiedPick(modelId ?? "", /* @__PURE__ */ new Set());
14451
- available = pick?.pick ?? null;
14488
+ available = await raccoonUnifiedPick(modelId ?? "", /* @__PURE__ */ new Set());
14452
14489
  } else {
14453
14490
  available = await pool.getAvailableAccount(
14454
14491
  RACCOON.id,
@@ -14462,8 +14499,10 @@ function mountRaccoon({ ctx, pool, throwIfAllAccountsRateLimited, readImage, rea
14462
14499
  return available.credential;
14463
14500
  }
14464
14501
  if (side === "free" && unified()) {
14465
- throwIfAllAccountsRateLimited(product, modelId, raccoonAccountsOf("free"));
14466
- throwIfAllAccountsRateLimited(product, `${modelId ?? ""}-p`, raccoonAccountsOf("pro"));
14502
+ const route = unifiedRoute(modelId ?? "");
14503
+ if (route.free) throwIfAllAccountsRateLimited(product, modelId, raccoonAccountsOf("free"));
14504
+ if (route.proId !== null) throwIfAllAccountsRateLimited(product, route.proId, raccoonAccountsOf("pro"));
14505
+ if (!route.free) return void 0;
14467
14506
  } else {
14468
14507
  throwIfAllAccountsRateLimited(product, modelId, raccoonAccountsOf(side));
14469
14508
  }
@@ -14487,8 +14526,7 @@ function mountRaccoon({ ctx, pool, throwIfAllAccountsRateLimited, readImage, rea
14487
14526
  nextAccount: async (modelId, tried) => {
14488
14527
  let next = null;
14489
14528
  if (side === "free" && unified()) {
14490
- const pick = await raccoonUnifiedPick(modelId, tried);
14491
- next = pick?.pick ?? null;
14529
+ next = await raccoonUnifiedPick(modelId, tried);
14492
14530
  } else {
14493
14531
  const excluded = raccoonOtherSideIds(side);
14494
14532
  for (const id of tried) excluded.add(id);
@@ -14509,6 +14547,7 @@ function mountRaccoon({ ctx, pool, throwIfAllAccountsRateLimited, readImage, rea
14509
14547
  const credential = await raccoonSideCredential(side);
14510
14548
  const own = credential === void 0 ? [] : await auth.fetchModelsWithCredential(credential);
14511
14549
  if (side !== "free" || !unified() || proRemoteFetch2 === void 0) return own;
14550
+ if (own.length === 0 && raccoonAccountsOf("free").some((account) => account.enabled !== false)) return [];
14512
14551
  let proModels = [];
14513
14552
  try {
14514
14553
  proModels = await proRemoteFetch2();
@@ -14525,13 +14564,13 @@ function mountRaccoon({ ctx, pool, throwIfAllAccountsRateLimited, readImage, rea
14525
14564
  // 两侧都传「按 plan 门控」的池视图:门控只影响目录可见性判定,
14526
14565
  // 黑名单/限流/凭据读写仍落在真池上。
14527
14566
  accountPool: raccoonSidePool(side),
14528
- // 统一模式出站翻译:订阅账号把统一 id 还原成上游订阅线(`<id>-p`),
14567
+ // 统一模式出站翻译:订阅账号使用原始订阅 ID(目录未知时回退 `<id>-p`),
14529
14568
  // 免费账号原样。适配器据此构造请求体与限流标记,选号/账本仍记统一 id。
14530
14569
  ...side === "free" ? {
14531
14570
  outboundModelId: (modelId, accountId) => {
14532
14571
  if (!unified() || accountId === void 0) return modelId;
14533
14572
  const entry = pool.listAccountsByProvider(RACCOON.id).find((account) => account.id === accountId);
14534
- return raccoonSideOf(entry ?? {}) === "pro" ? `${modelId}-p` : modelId;
14573
+ return raccoonSideOf(entry ?? {}) === "pro" ? unifiedRoute(modelId).proId ?? modelId : modelId;
14535
14574
  }
14536
14575
  } : {},
14537
14576
  product
@@ -118,18 +118,20 @@ export function modelWire(raw) {
118
118
  /**
119
119
  * 倍率徽标 wire 投影。
120
120
  *
121
- * 只认「免费」或 `xN` 形态的文案,加上有限正倍率;未知形态一律不挂标
122
- * (不谎报免费、不编造倍率)。
121
+ * 只认「免费」、单倍率或多档倍率区间;区间不携带可比较的单一 multiplier。
123
122
  */
124
- function wireRate(value) {
125
- const label = wireText(value?.label ?? value?.text?.zh, 24)
126
- if (!(label === '免费' || /^(?:参考 )?x\d+(?:\.\d+)?$/.test(label))) return undefined
123
+ export function wireRate(value) {
124
+ const label = value?.label ?? value?.text?.zh
125
+ if (typeof label !== 'string' || label.length > 24) return undefined
126
+ const scalar = /^(?:参考 )?x\d+(?:\.\d+)?$/.test(label)
127
+ const range = /^x(\d+(?:\.\d+)?)–x(\d+(?:\.\d+)?)$/.exec(label)
128
+ if (label !== '免费' && !scalar && !(range && Number(range[1]) < Number(range[2]))) return undefined
127
129
  if (!['neutral', 'info', 'success', 'warning'].includes(value?.tone)) return undefined
128
130
  const multiplier = wireFinite(value?.multiplier)
129
131
  return {
130
132
  label,
131
133
  tone: value.tone,
132
- ...(multiplier !== null && multiplier > 0 ? { multiplier } : {}),
134
+ ...(!range && multiplier !== null && multiplier > 0 ? { multiplier } : {}),
133
135
  }
134
136
  }
135
137
 
@@ -166,15 +168,7 @@ export function modelView(wire, provider) {
166
168
 
167
169
  /** 倍率徽标视图收编(幂等:wire 形状再进一次也不变形)。 */
168
170
  export function viewRate(value) {
169
- const label = typeof value?.label === 'string' ? value.label : ''
170
- if (!(label === '免费' || /^(?:参考 )?x\d+(?:\.\d+)?$/.test(label))) return null
171
- if (!['neutral', 'info', 'success', 'warning'].includes(value?.tone)) return null
172
- const multiplier = wireFinite(value?.multiplier)
173
- return {
174
- label,
175
- tone: value.tone,
176
- ...(multiplier !== null && multiplier > 0 ? { multiplier } : {}),
177
- }
171
+ return wireRate(value) ?? null
178
172
  }
179
173
 
180
174
  /**
package/lib/client.js CHANGED
@@ -702,18 +702,20 @@ function modelWire(raw) {
702
702
  /**
703
703
  * 倍率徽标 wire 投影。
704
704
  *
705
- * 只认「免费」或 `xN` 形态的文案,加上有限正倍率;未知形态一律不挂标
706
- * (不谎报免费、不编造倍率)。
705
+ * 只认「免费」、单倍率或多档倍率区间;区间不携带可比较的单一 multiplier。
707
706
  */
708
707
  function wireRate(value) {
709
- const label = wireText(value?.label ?? value?.text?.zh, 24)
710
- if (!(label === '免费' || /^(?:参考 )?x\d+(?:\.\d+)?$/.test(label))) return undefined
708
+ const label = value?.label ?? value?.text?.zh
709
+ if (typeof label !== 'string' || label.length > 24) return undefined
710
+ const scalar = /^(?:参考 )?x\d+(?:\.\d+)?$/.test(label)
711
+ const range = /^x(\d+(?:\.\d+)?)–x(\d+(?:\.\d+)?)$/.exec(label)
712
+ if (label !== '免费' && !scalar && !(range && Number(range[1]) < Number(range[2]))) return undefined
711
713
  if (!['neutral', 'info', 'success', 'warning'].includes(value?.tone)) return undefined
712
714
  const multiplier = wireFinite(value?.multiplier)
713
715
  return {
714
716
  label,
715
717
  tone: value.tone,
716
- ...(multiplier !== null && multiplier > 0 ? { multiplier } : {}),
718
+ ...(!range && multiplier !== null && multiplier > 0 ? { multiplier } : {}),
717
719
  }
718
720
  }
719
721
 
@@ -750,15 +752,7 @@ function modelView(wire, provider) {
750
752
 
751
753
  /** 倍率徽标视图收编(幂等:wire 形状再进一次也不变形)。 */
752
754
  function viewRate(value) {
753
- const label = typeof value?.label === 'string' ? value.label : ''
754
- if (!(label === '免费' || /^(?:参考 )?x\d+(?:\.\d+)?$/.test(label))) return null
755
- if (!['neutral', 'info', 'success', 'warning'].includes(value?.tone)) return null
756
- const multiplier = wireFinite(value?.multiplier)
757
- return {
758
- label,
759
- tone: value.tone,
760
- ...(multiplier !== null && multiplier > 0 ? { multiplier } : {}),
761
- }
755
+ return wireRate(value) ?? null
762
756
  }
763
757
 
764
758
  /**
@@ -18,6 +18,7 @@ import { createManagedAdapter } from './managed-llm.js'
18
18
  import { readCatalogCache, saveCatalogCache } from './catalog-cache.js'
19
19
  import { readableModelName } from './model-catalog.js'
20
20
  import { PLAN_EFFORTS } from './sensenova-params.js'
21
+ import { normalizeRateRange } from './rate-badge.js'
21
22
 
22
23
  export const MANAGED_METHODS = Object.freeze(new Set([
23
24
  'managed.snapshot',
@@ -113,6 +114,7 @@ export function publicManagedModel(source) {
113
114
  const mappedEfforts = rawEfforts.map(e => e === 'none' ? 'off' : e)
114
115
  const efforts = PLAN_EFFORTS.filter(level => mappedEfforts.includes(level))
115
116
  const declaredEffort = row.defaultEffort === 'none' ? 'off' : row.defaultEffort
117
+ const rateRange = normalizeRateRange(row.rateRange)
116
118
  return {
117
119
  id,
118
120
  name: readableModelName(id, text(row.name, 160)),
@@ -125,6 +127,7 @@ export function publicManagedModel(source) {
125
127
  free: row.free === true || (row.free !== false && row.rate === 0),
126
128
  rate: finite(row.rate),
127
129
  rateWas: finite(row.rateWas),
130
+ ...(rateRange ? { rateRange } : {}),
128
131
  rateLabel: text(row.rateLabel, 24),
129
132
  rateTone: ['neutral', 'info', 'success', 'warning'].includes(row.rateTone) ? row.rateTone : '',
130
133
  protocol: ['openai-completions', 'openai-responses', 'anthropic-messages'].includes(row.protocol) ? row.protocol : '',
@@ -177,7 +180,8 @@ export function createManagedChannelManager(ctx, spec, deps = {}) {
177
180
  let catalogSource = catalogRows.length ? 'cached' : 'fallback'
178
181
  let catalogAt = 0
179
182
  let catalogJob = null
180
- let rrCursor = 0
183
+ let catalogGeneration = 0
184
+ let catalogWrites = Promise.resolve()
181
185
  const rateLimitedUntil = new Map() // `${accountId}:${modelId}` -> ts
182
186
 
183
187
  // 渠道开关持久化(默认:有账号后自动启用,显式关闭则保持关闭)。
@@ -382,16 +386,18 @@ export function createManagedChannelManager(ctx, spec, deps = {}) {
382
386
  }
383
387
 
384
388
  const CATALOG_TTL_MS = 10 * 60_000
389
+ const currentCatalog = () => ({ rows: catalogRows.length ? catalogRows : fallbackCatalog(), source: catalogSource })
385
390
 
386
391
  async function loadCatalog({ force = false, signal } = {}) {
387
392
  if (!force && catalogRows.length && catalogSource === 'remote' && Date.now() - catalogAt < CATALOG_TTL_MS) {
388
- return { rows: catalogRows, source: catalogSource }
393
+ return currentCatalog()
389
394
  }
390
395
  if (!force && catalogJob) {
391
396
  // 有中间态磁盘缓存时不等在途远端,立刻返回缓存让界面秒显。
392
- if (catalogRows.length) return { rows: catalogRows, source: catalogSource }
397
+ if (catalogRows.length) return currentCatalog()
393
398
  return catalogJob
394
399
  }
400
+ const generation = ++catalogGeneration
395
401
  const job = (async () => {
396
402
  const { entries } = await readIndex()
397
403
  const eligible = entries
@@ -417,33 +423,33 @@ export function createManagedChannelManager(ctx, spec, deps = {}) {
417
423
  } catch {}
418
424
  }
419
425
  }
426
+ signal?.throwIfAborted()
427
+ if (disposed || generation !== catalogGeneration) return currentCatalog()
420
428
  if (remote?.length) {
421
429
  catalogRows = remote
422
430
  catalogSource = 'remote'
423
431
  catalogAt = Date.now()
424
- await saveCatalogCache(catalogFile, remote, catalogScope).catch(() => {})
425
- return { rows: catalogRows, source: catalogSource }
426
- }
427
- const cached = readCachedCatalog()
428
- if (cached?.length) {
429
- catalogRows = cached.map(publicManagedModel).filter(Boolean)
432
+ // 保持磁盘写入顺序;较新目录永远最后落盘。
433
+ catalogWrites = catalogWrites.then(() => saveCatalogCache(catalogFile, remote, catalogScope)).catch(() => {})
434
+ await catalogWrites
435
+ } else if (catalogRows.length && catalogSource !== 'fallback') {
430
436
  catalogSource = 'cached'
431
437
  } else if (!catalogRows.length) {
432
438
  catalogRows = fallbackCatalog()
433
439
  catalogSource = 'fallback'
434
440
  }
435
- return { rows: catalogRows, source: catalogSource }
441
+ return currentCatalog()
436
442
  })().finally(() => { if (catalogJob === job) catalogJob = null })
437
443
  catalogJob = job
438
444
  // 非强制刷新且已有磁盘中间态缓存:立即返回缓存,远端拉取在后台静默完成并自动更新适配器。
439
445
  if (!force && catalogRows.length && catalogSource === 'cached') {
440
446
  void job.then(async res => {
441
- if (!disposed && res.source === 'remote') {
447
+ if (!disposed && generation === catalogGeneration && res.source === 'remote') {
442
448
  const models = await modelSettings.list(res.rows)
443
- await syncRegistration(models).catch(() => {})
449
+ await syncRegistration(models, generation).catch(() => {})
444
450
  }
445
451
  }).catch(() => {})
446
- return { rows: catalogRows, source: catalogSource }
452
+ return currentCatalog()
447
453
  }
448
454
  return job
449
455
  }
@@ -466,13 +472,11 @@ export function createManagedChannelManager(ctx, spec, deps = {}) {
466
472
  if (typeof spec.createTransport !== 'function') {
467
473
  throw new Error(`${spec.title}:推理传输层未实现`)
468
474
  }
469
- const start = rrCursor++ % pool.length
470
- const rotated = [...pool.slice(start), ...pool.slice(0, start)]
471
- const baseOrder = rotated.map(entry => entry.id)
475
+ const baseOrder = pool.map(entry => entry.id)
472
476
  const order = healthy.length && deps.quotaAccountOrder ? deps.quotaAccountOrder(id, baseOrder, { modelId, model }) : baseOrder
473
- const accounts = new Map(rotated.map(entry => [entry.id, entry]))
477
+ const accounts = new Map(pool.map(entry => [entry.id, entry]))
474
478
  let lastError = null
475
- // 按轮询顺序逐账号故障切换:某个账号缺少推理凭据或初始化失败时自动尝试下一个账号。
479
+ // 按候选顺序逐账号故障切换:凭据缺失或初始化失败时自动尝试下一个账号。
476
480
  for (const accountId of order) {
477
481
  const picked = accounts.get(accountId)
478
482
  if (!picked) continue
@@ -499,13 +503,14 @@ export function createManagedChannelManager(ctx, spec, deps = {}) {
499
503
  throw lastError ?? new Error(`${spec.title}:当前没有可用于推理的账号`)
500
504
  }
501
505
 
502
- async function syncRegistration(describedRows) {
506
+ async function syncRegistration(describedRows, catalogTicket) {
507
+ const current = () => !disposed && (catalogTicket === undefined || catalogTicket === catalogGeneration)
508
+ if (!current()) return false
503
509
  const ticket = ++regGeneration
504
- if (disposed) return false
505
510
  const llm = serviceOf(ctx, 'llm')
506
511
  if (!llm || typeof llm.registerAdapter !== 'function') return false
507
512
  const { entries } = await readIndex()
508
- if (disposed || ticket !== regGeneration) return false
513
+ if (!current() || ticket !== regGeneration) return false
509
514
  if (!channelState.enabled || !entries.some(entry => entry.enabled !== false)) {
510
515
  if (!registered) return false
511
516
  releaseRegistration()
@@ -513,7 +518,7 @@ export function createManagedChannelManager(ctx, spec, deps = {}) {
513
518
  return false
514
519
  }
515
520
  const rows = describedRows ?? await modelSettings.list((await loadCatalog()).rows)
516
- if (disposed || ticket !== regGeneration) return false
521
+ if (!current() || ticket !== regGeneration) return false
517
522
  if (!rows.some(row => row.enabled)) {
518
523
  releaseRegistration()
519
524
  llm.emitAdaptersUpdated?.()
@@ -529,7 +534,7 @@ export function createManagedChannelManager(ctx, spec, deps = {}) {
529
534
  })
530
535
  // 异步边界后复核:防止 await 期间发生 logout / setEnabled(false) / dispose 复活注册。
531
536
  const latest = await readIndex()
532
- const stillValid = !disposed && ticket === regGeneration && channelState.enabled
537
+ const stillValid = current() && ticket === regGeneration && channelState.enabled
533
538
  && latest.entries.some(entry => entry.enabled !== false)
534
539
  if (!stillValid) {
535
540
  built?.adapter?.dispose?.()
@@ -620,10 +625,23 @@ export function createManagedChannelManager(ctx, spec, deps = {}) {
620
625
  }
621
626
 
622
627
  if (method === 'managed.models' || method === 'managed.refreshModels') {
623
- const { rows, source } = await loadCatalog({ force: method === 'managed.refreshModels', signal })
624
- const models = await modelSettings.list(rows)
625
- if (method === 'managed.refreshModels') await syncRegistration(models).catch(() => {})
626
- return { provider: id, models, source }
628
+ const force = method === 'managed.refreshModels'
629
+ const loading = loadCatalog({ force, signal })
630
+ const ticket = catalogGeneration
631
+ const initial = await loading
632
+ signal?.throwIfAborted()
633
+ if (!force) return { provider: id, models: await modelSettings.list(initial.rows), source: initial.source }
634
+ // 已被取代的显式读取跟随最新作业,旧请求不再发布目录或适配器。
635
+ for (;;) {
636
+ if (ticket !== catalogGeneration && catalogJob) await catalogJob
637
+ signal?.throwIfAborted()
638
+ const current = catalogGeneration
639
+ const { rows, source } = currentCatalog()
640
+ const models = await modelSettings.list(rows)
641
+ if (ticket === current) await syncRegistration(models, ticket).catch(() => {})
642
+ signal?.throwIfAborted()
643
+ if (current === catalogGeneration && (ticket === current || !catalogJob)) return { provider: id, models, source }
644
+ }
627
645
  }
628
646
 
629
647
  if (MANAGED_MODEL_WRITES.includes(method)) {
@@ -456,12 +456,33 @@ async function codeArtsPostOps(handle, cred, path, body, signal) {
456
456
  }
457
457
 
458
458
  function parseRatio(value) {
459
- if (typeof value === 'number' && Number.isFinite(value)) return value
460
- if (typeof value === 'string') {
461
- const m = /([\d.]+)/.exec(value)
462
- if (m) return Number(m[1])
459
+ const match = typeof value === 'string' && /^(?:[x×]\s*)?(\d+(?:\.\d+)?)(?:\s*[x×])?$/i.exec(value.trim())
460
+ const ratio = match ? Number(match[1]) : value
461
+ return Number.isFinite(ratio) && ratio >= 0 ? Math.max(0, ratio) : null
462
+ }
463
+
464
+ function quotaNumber(value) {
465
+ const n = typeof value === 'string' && /^\d+(?:\.\d+)?$/.test(value.trim()) ? Number(value) : value
466
+ return Number.isFinite(n) && n >= 0 ? n : null
467
+ }
468
+
469
+ function codeArtsModelRates(credit) {
470
+ const items = Array.isArray(credit) ? credit : [credit]
471
+ // 缺档时无法判断全时段倍率,尤其不能把某一档的 0 当作全时段免费。
472
+ if (!items.length) return {}
473
+ let min = Infinity
474
+ let max = 0
475
+ const before = parseRatio(items[0]?.before_display_ratio)
476
+ let consistentBefore = before !== null
477
+ for (const item of items) {
478
+ const rate = parseRatio(item?.ratio_display)
479
+ if (rate === null) return {}
480
+ min = Math.min(min, rate)
481
+ max = Math.max(max, rate)
482
+ consistentBefore &&= parseRatio(item?.before_display_ratio) === before
463
483
  }
464
- return null
484
+ if (min !== max) return { rateRange: [min, max] }
485
+ return { rate: min, ...(consistentBefore ? { rateWas: before } : {}) }
465
486
  }
466
487
 
467
488
  // 合并相邻同角色消息,保留 CodeArts 请求的 user/assistant 交替约定。
@@ -517,8 +538,7 @@ export function parseCodeArtsBuiltinModels(json) {
517
538
  if (!id || hidden.has(id) || m.display_enabled === false) continue
518
539
  const rawName = typeof m.display_name === 'string' && m.display_name.trim() ? m.display_name.trim()
519
540
  : typeof m.model_name === 'string' && m.model_name.trim() ? m.model_name.trim() : id
520
- const ratio = parseRatio(m.credit?.ratio_display)
521
- const beforeRatio = parseRatio(m.credit?.before_display_ratio)
541
+ const rates = codeArtsModelRates(m.credit)
522
542
  out.push({
523
543
  id,
524
544
  name: rawName,
@@ -526,9 +546,8 @@ export function parseCodeArtsBuiltinModels(json) {
526
546
  output: catalogOutput(m),
527
547
  attachment: m.supports_images === true,
528
548
  efforts: [],
529
- free: m.is_free_benefit === true || ratio === 0,
530
- rate: ratio,
531
- rateWas: beforeRatio,
549
+ free: m.is_free_benefit === true || rates.rate === 0,
550
+ ...rates,
532
551
  protocol: 'openai-completions',
533
552
  meta: { maasType: m.maas_type || (m.is_free_benefit ? 'benefit' : '') },
534
553
  })
@@ -850,37 +869,39 @@ export const codeartsSpec = {
850
869
  let totalRemain = null
851
870
  for (const m of metrics) {
852
871
  if (!m || m.show === false) continue
853
- const amount = Number(m.package_credit_amount)
854
- const remain = Number(m.package_credit_remain)
855
- const used = Number(m.package_credit_used)
856
- if (m.name === 'usageTotalPackageCredit' && Number.isFinite(remain)) totalRemain = remain
857
- if (Number.isFinite(amount) && amount > 0 && Number.isFinite(remain)) {
872
+ const limit = quotaNumber(m.package_credit_amount)
873
+ const remain = quotaNumber(m.package_credit_remain)
874
+ const used = quotaNumber(m.package_credit_used)
875
+ if (m.name === 'usageTotalPackageCredit' && remain !== null) totalRemain = remain
876
+ if (limit > 0 && (remain !== null || used !== null)) {
858
877
  const labelMap = {
859
878
  usageTotalPackageCredit: '总积分包',
860
879
  usageBasicPackageCredit: '基础积分包',
861
880
  usageOnDemandPackageCredit: '按需积分包',
862
881
  usageBonusPackageCredit: '赠送积分包',
863
882
  }
883
+ const consumed = used ?? Math.max(0, limit - remain)
864
884
  windows.push({
865
885
  name: labelMap[m.name] || m.name,
866
886
  balance: remain,
867
- limit: amount,
868
- amount: Number.isFinite(used) ? used : amount - remain,
869
- used: Math.round((1 - remain / amount) * 100),
887
+ limit,
888
+ amount: consumed,
889
+ used: Math.round((consumed / limit) * 100),
870
890
  unit: '积分',
871
891
  resetsAt: typeof stats?.end_date === 'string' ? stats.end_date : '',
872
892
  })
873
893
  }
874
894
  }
875
895
  const freeResult = freeBal?.result
876
- if (Number.isFinite(freeResult?.daily_token_limit) && freeResult.daily_token_limit > 0) {
877
- const usedTokens = Number(freeResult.daily_tokens_used) || 0
896
+ const tokenLimit = quotaNumber(freeResult?.daily_token_limit)
897
+ const usedTokens = quotaNumber(freeResult?.daily_tokens_used)
898
+ if (tokenLimit > 0 && usedTokens !== null) {
878
899
  windows.push({
879
900
  name: '免费日额度',
880
- balance: Math.max(0, freeResult.daily_token_limit - usedTokens),
881
- limit: freeResult.daily_token_limit,
901
+ balance: Math.max(0, tokenLimit - usedTokens),
902
+ limit: tokenLimit,
882
903
  amount: usedTokens,
883
- used: Math.round((usedTokens / freeResult.daily_token_limit) * 100),
904
+ used: Math.round((usedTokens / tokenLimit) * 100),
884
905
  unit: 'Tokens',
885
906
  })
886
907
  }
@@ -17,7 +17,7 @@
17
17
  // 1. **时间用数据时间,不用推送时间**:`receivedAt` 取该卡保留项里最旧的数据时间,
18
18
  // `resetsAt` 由数据时间 + `resetInMs`(或上游绝对 `resetAt`)推出。
19
19
  // 2. **0 是合法值**:控制台明确余额 0 要如实报,不能被 API 余额顶掉。
20
- // 3. **条数有上限**(接收端 `MAX_WINDOWS + MAX_EXTRAS` = 56):超出截断并报
20
+ // 3. **条数有上限**(接收端最多 16 个窗口、40 个其他元素):超出截断并报
21
21
  // `coverage: 'partial'`,不静默丢。
22
22
  import { CHANNEL_SPECS } from './channel-specs.js'
23
23
 
@@ -27,8 +27,8 @@ export const QUOTA_INGEST_PREFIX = 'unified-router'
27
27
  export const QUOTA_INGEST_LABEL = 'Unified Router'
28
28
  /** 推送有效期:与宿主快照采集周期同量级,过期只标 stale。 */
29
29
  export const QUOTA_INGEST_TTL_MS = 10 * 60_000
30
- /** 接收端 `parseIngestPayload` 的 quotas 上限(MAX_WINDOWS 16 + MAX_EXTRAS 40)。 */
31
- export const QUOTA_INGEST_MAX_ITEMS = 56
30
+ const MAX_WINDOWS = 16
31
+ const MAX_EXTRAS = 40
32
32
  /** 接收端单条 64KiB;留一点余量后逐步丢尾。 */
33
33
  const MAX_PAYLOAD_BYTES = 60_000
34
34
 
@@ -80,11 +80,6 @@ function roundPercent(value) {
80
80
  return Math.min(99.9, Math.max(0, Math.round(value * 10) / 10))
81
81
  }
82
82
 
83
- function windowPercent(id, used, limit, remaining) {
84
- const raw = rawPercent(id, used, limit, remaining)
85
- return raw === null ? null : roundPercent(raw)
86
- }
87
-
88
83
  /** 接收端秘密闸门会整条拒绝含令牌形态的文本:所有自由文本先兜底成渠道名。 */
89
84
  function safeLabel(value, fallback) {
90
85
  const text = String(value ?? '').trim().slice(0, 64)
@@ -108,7 +103,6 @@ function createCollector(now, resources) {
108
103
  const quotas = []
109
104
  const itemAts = []
110
105
  let stale = false
111
- let truncated = false
112
106
  // 当前账号的池归属:接收端按 `poolLabel` 分池,同名账号必须可区分。
113
107
  let pool
114
108
  let poolLabel
@@ -166,32 +160,32 @@ function createCollector(now, resources) {
166
160
  const ranked = quotas
167
161
  .map((item, index) => ({ item, at: itemAts[index] }))
168
162
  .sort((a, b) => (a.item.type === 'amount' ? 0 : 1) - (b.item.type === 'amount' ? 0 : 1))
169
- let kept = ranked.slice(0, QUOTA_INGEST_MAX_ITEMS)
170
- if (ranked.length > kept.length) truncated = true
171
- let items = kept.map(entry => entry.item)
163
+ let windows = 0, extras = 0
164
+ const kept = ranked.filter(({ item }) => item.type === 'window' ? ++windows <= MAX_WINDOWS : ++extras <= MAX_EXTRAS)
165
+ if (!kept.length) return undefined
166
+ const items = kept.map(entry => entry.item)
172
167
  // receivedAt 取保留项里**最旧**的数据时间:一条新快照不能把整批旧数据洗成 fresh。
173
- const times = kept.map(entry => entry.at).filter(value => Number.isFinite(value))
174
- const receivedAt = times.length > 0 ? Math.min(...times) : now()
175
- const state = items.length > 0 ? 'ok' : 'error'
168
+ const dataTime = () => {
169
+ const times = kept.map(entry => entry.at).filter(value => Number.isFinite(value))
170
+ return times.length ? Math.min(...times) : now()
171
+ }
176
172
  const payload = {
177
173
  source: `${QUOTA_INGEST_PREFIX}-${spec.id}`,
178
174
  label: spec.title,
179
- state,
180
- ...(state === 'error' ? { error: `未采集到 ${spec.title} 的额度` } : {}),
181
- coverage: stale || truncated ? 'partial' : 'complete',
175
+ state: 'ok',
176
+ coverage: stale || kept.length < ranked.length ? 'partial' : 'complete',
182
177
  quotas: items,
183
178
  ttlMs: QUOTA_INGEST_TTL_MS,
184
- receivedAt,
179
+ receivedAt: dataTime(),
185
180
  }
186
181
  // 接收端单条上限 64KiB:超了就逐步丢尾部条目并标 partial。
187
- while (items.length > 1 && JSON.stringify(payload).length > MAX_PAYLOAD_BYTES) {
188
- items = items.slice(0, -1)
189
- payload.quotas = items
182
+ while (items.length && Buffer.byteLength(JSON.stringify(payload), 'utf8') > MAX_PAYLOAD_BYTES) {
183
+ items.pop()
184
+ kept.pop()
190
185
  payload.coverage = 'partial'
191
- truncated = true
186
+ payload.receivedAt = dataTime()
192
187
  }
193
- if (state === 'error') return undefined
194
- return payload
188
+ return items.length ? payload : undefined
195
189
  }
196
190
  return { add, read, pushAmount, pushWindow, finish, setPool, markStale: () => { stale = true } }
197
191
  }
@@ -212,6 +206,20 @@ export function quotaIngestResourceKeys() {
212
206
  return keys
213
207
  }
214
208
 
209
+ /** 只有明确、未标陈旧的空账号列表才撤回;缺快照或读取失败时保留上次结果。 */
210
+ export function emptyQuotaIngestSources(resources) {
211
+ return quotaIngestResourceKeys().flatMap(key => {
212
+ const [provider, method] = key.split('/')
213
+ const entry = resources[key]
214
+ const value = valueOf(entry)
215
+ const accounts = value?.accounts
216
+ return ['credits.balances', 'managed.snapshot', 'workbuddy.snapshot'].includes(method)
217
+ && entry?.stale !== true && Array.isArray(accounts) && !accounts.length
218
+ && (method !== 'workbuddy.snapshot' || value.accountsEmptyConfirmed === true)
219
+ ? [`${QUOTA_INGEST_PREFIX}-${provider}`] : []
220
+ })
221
+ }
222
+
215
223
  /**
216
224
  * 把宿主快照翻译成**按渠道拆分**的 ingest 载荷数组(每渠道一张卡)。
217
225
  *
@@ -289,8 +297,9 @@ export function buildQuotaIngestPayloads(resources = {}, { now = Date.now } = {}
289
297
  `${safeLabel(account?.name, 'WorkBuddy')} · ${shortId(account.id)}`)
290
298
  const dataAt = finite(account?.updatedAt) ?? at
291
299
  for (const window of Array.isArray(account?.windows) ? account.windows : []) {
292
- const raw = rawPercent(`wb:${window?.name}`, window?.used, window?.limit, window?.remaining)
293
- if (raw === null) continue
300
+ // WorkBuddy 的 used 已经是百分比;绝对已用量是 amount。
301
+ const raw = finite(window?.used) ?? rawPercent('', window?.amount, window?.limit, window?.balance)
302
+ if (raw === null || raw < 0) continue
294
303
  const resetsAt = typeof window?.resetsAt === 'string' && Number.isFinite(Date.parse(window.resetsAt))
295
304
  ? new Date(window.resetsAt).toISOString() : undefined
296
305
  add({
package/lib/rate-badge.js CHANGED
@@ -28,7 +28,9 @@
28
28
  // carries it.」核心 `normalizeModelInfo()` 也只在 `listModels()` 的归一化里复制
29
29
  // badge。价格只属于选择列表语境,故包装层只重写 `listModels`。
30
30
 
31
- /** 徽标文案:`en` 必填(wire 侧 schema 的硬要求),纯数字/「免费」中英文同形。 */
31
+ import { wireRate } from './channel-contract.js'
32
+
33
+ /** 徽标文案:`en` 必填(wire 侧 schema 的硬要求);数字与区间中英文同形。 */
32
34
  export function rateBadgeText(zh, en = zh) {
33
35
  return { en, zh }
34
36
  }
@@ -38,6 +40,13 @@ export function formatRate(value) {
38
40
  return `x${value.toFixed(2)}`
39
41
  }
40
42
 
43
+ /** 多档计费只交付合法的上下界,不把任一档冒充当前生效倍率。 */
44
+ export function normalizeRateRange(value) {
45
+ if (!Array.isArray(value) || value.length !== 2) return null
46
+ const [min, max] = value
47
+ return Number.isFinite(min) && Number.isFinite(max) && min >= 0 && max > min ? [Math.max(0, min), max] : null
48
+ }
49
+
41
50
  /**
42
51
  * 把「当前生效倍率」转成模型选择器徽标(与 channel-pack TS 版同规则)。
43
52
  *
@@ -79,6 +88,7 @@ export function modelRateBadge(multiplier, options = {}) {
79
88
  * 行字段(各渠道解析器已归一,见 `lib/managed-providers/*.js`):
80
89
  * - `free`:渠道明说这个模型不消耗额度(点倍率 0、上游免费标记、文案「免费」);
81
90
  * - `rate`:当前生效倍率;`rateWas`:促销前倍率(仅促销时为上游给出);
91
+ * - `rateRange`:多档倍率的上下界(未选定适用档位,不参与单值比较);
82
92
  * - `rateLabel` / `rateTone`:上游自带的展示文案与语气;
83
93
  * 文案本身只当「免费」证据使用,其余一律按 `rate` 数值重新格式化,避免上游文案
84
94
  * 与倍率数字互相矛盾。
@@ -90,6 +100,17 @@ export function rateBadgeFromRow(row) {
90
100
  if (!row || typeof row !== 'object') return undefined
91
101
  const label = typeof row.rateLabel === 'string' ? row.rateLabel : ''
92
102
  if (row.free === true || label === '免费') return modelRateBadge(0)
103
+ const range = normalizeRateRange(row.rateRange)
104
+ if (range) {
105
+ for (let precision = 2; precision <= 6; precision++) {
106
+ const [min, max] = range.map(value => value.toFixed(precision))
107
+ if (min === max) continue
108
+ const display = `x${min}–x${max}`
109
+ const badge = { text: rateBadgeText(display), tone: 'neutral' }
110
+ return wireRate(badge) ? badge : undefined
111
+ }
112
+ return undefined
113
+ }
93
114
  const rate = row.rate
94
115
  if (typeof rate !== 'number' || !Number.isFinite(rate) || rate < 0) return undefined
95
116
  if (rate === 0 && row.free === false) return undefined
@@ -84,7 +84,10 @@ export function settingsResources(read, publicResult, { managedIds = MANAGED_PRO
84
84
  }
85
85
  register('plan.snapshot', PLAN_PROVIDER_ID)
86
86
  register('workbuddy.snapshot', WORKBUDDY_PROVIDER_ID, {
87
- project: value => ({ accounts: publicResult('workbuddy.snapshot', value).accounts }),
87
+ project: value => {
88
+ const { loginUrl: _omit, ...rest } = publicResult('workbuddy.snapshot', value)
89
+ return rest
90
+ },
88
91
  merge: mergeWorkBuddy,
89
92
  })
90
93
  register('workbuddy.models', WORKBUDDY_PROVIDER_ID)
package/lib/web-host.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { normalizePlanParams, PLAN_EFFORTS } from "./sensenova-params.js"
2
- import { accountWire, modelWire, wireJson } from './channel-contract.js'
2
+ import { accountWire, modelWire, wireJson, wireRate } from './channel-contract.js'
3
3
  import { guardedRpc, sharedTransport, loginUrl, PROVIDERS, PLAN_PROVIDER_ID, PLAN_METHODS, WORKBUDDY_METHODS, APIKEY_PROVIDER_IDS, APIKEY_METHODS, MANAGED_PROVIDER_IDS, MANAGED_METHODS, AUTOMATION_METHODS, ALL_PROVIDER_IDS } from './rpc.js'
4
4
  import { createSenseNovaManager } from './sensenova.js'
5
5
  import { projectSenseNovaQuota } from './sensenova-quota.js'
@@ -19,7 +19,7 @@ import { pruneRetiredChannels } from './retired-channels.js'
19
19
  import { projectApiKeyQuota, projectApiKeyRateLimit } from './apikey-quota-projection.js'
20
20
  import { dirname, join } from 'node:path'
21
21
  import { createDailyCheckin } from './daily-checkin.js'
22
- import { buildQuotaIngestPayloads, quotaIngestResourceKeys } from './quota-ingest.js'
22
+ import { buildQuotaIngestPayloads, emptyQuotaIngestSources, quotaIngestResourceKeys } from './quota-ingest.js'
23
23
  import { publicAutomationStatus, publicCheckinStatus, settingsCheckinAdapters, settingsTaskAdapters, settingsResources, settingsResourceKey, settingsSnapshotFile, updateSettingsSnapshots } from './settings-providers.js'
24
24
  import { rateBadgeFromRow } from './rate-badge.js'
25
25
  export const name = 'dsh-unified-router'
@@ -46,12 +46,6 @@ function publicCatalogStatus(value) {
46
46
  ...(['login-required', 'cli-missing', 'timeout', 'cli-failed', 'empty'].includes(value?.issue) ? { issue: value.issue } : {}),
47
47
  }
48
48
  }
49
- function publicRate(value) {
50
- const label = text(value?.text?.zh ?? value?.label, 24)
51
- return (label === '免费' || /^(?:参考 )?x\d+(?:\.\d+)?$/.test(label)) && ['neutral', 'info', 'success', 'warning'].includes(value?.tone)
52
- ? { label, tone: value.tone, ...(Number.isFinite(value.multiplier) && value.multiplier > 0 ? { multiplier: value.multiplier } : {}) }
53
- : undefined
54
- }
55
49
  // 设置页模型列表的倍率/免费标签:与 `lib/rate-badge.js`(会话选择器徽标)同一份
56
50
  // 规则,只是换成设置页要的 `{ label, tone, multiplier }` 形状。
57
51
  // 未知(没有 free 证据、也没有有限倍率)→ 不返回 rate,界面不挂标、不谎报免费。
@@ -59,12 +53,12 @@ function publicModelRate(row) {
59
53
  // 幂等:输入可能已是投影形状(快照文件恢复、写后乐观补丁会二次投影),
60
54
  // 此时 `rate` 是 `{ label, tone, multiplier }` 而不是原始数值。
61
55
  if (row?.rate && typeof row.rate === 'object') {
62
- const existing = publicRate(row.rate)
56
+ const existing = wireRate(row.rate)
63
57
  return existing ? { rate: existing } : {}
64
58
  }
65
59
  const badge = rateBadgeFromRow(row)
66
60
  if (!badge) return {}
67
- const rate = publicRate({ label: badge.text?.zh, tone: badge.tone, multiplier: row?.rate })
61
+ const rate = wireRate({ ...badge, multiplier: row?.rate })
68
62
  return rate ? { rate } : {}
69
63
  }
70
64
  function sameOriginRequest(request) {
@@ -234,6 +228,7 @@ function projectPublicResult(method, value) {
234
228
  try { safeLoginUrl = typeof v.loginUrl === 'string' && v.loginUrl ? loginUrl(v.loginUrl) : '' } catch {}
235
229
  return {
236
230
  accounts: (Array.isArray(v.accounts) ? v.accounts : []).slice(0, 16).map(wbAccount).filter(Boolean),
231
+ ...(v.accountsEmptyConfirmed === true ? { accountsEmptyConfirmed: true } : {}),
237
232
  loginUrl: safeLoginUrl,
238
233
  }
239
234
  }
@@ -778,17 +773,20 @@ ${String(error?.stack ?? error)}
778
773
  const quotaIngestKeys = quotaIngestResourceKeys()
779
774
  let quotaIngestTimer = null
780
775
  let quotaIngestBootTimer = null
776
+ let quotaIngestRunning = false
781
777
  const reportQuota = async () => {
778
+ if (!active || quotaIngestRunning || !automationSettings.isQuotaIngestEnabled()) return
779
+ quotaIngestRunning = true
782
780
  // 整体兜底:服务 lookup、快照读取与推送都不得把异常抛回定时器回调
783
781
  // (否则会变成 unhandled rejection)。
784
782
  try {
785
- if (!automationSettings.isQuotaIngestEnabled()) return
786
783
  const service = typeof ctx.get === 'function' ? ctx.get('subUsage') : undefined
787
784
  if (!service || typeof service.ingest !== 'function') return
788
785
  const resources = {}
789
786
  for (const key of quotaIngestKeys) resources[key] = snapshots.peek(key)
790
787
  // 按渠道拆源:每个渠道一张卡(卡标题 = 渠道名),条目才是账号名。
791
788
  for (const payload of buildQuotaIngestPayloads(resources)) {
789
+ if (!active || !automationSettings.isQuotaIngestEnabled()) return
792
790
  const result = await service.ingest(payload)
793
791
  // ingest 以 `{ ok:false, error }` 正常返回(秘密闸门 / 超限 / 未启用等),
794
792
  // 不抛错:如实记一条,避免长期静默失败。
@@ -796,7 +794,15 @@ ${String(error?.stack ?? error)}
796
794
  host.logger?.warn?.(`[unified-router] ${payload.label} 额度推送被拒:${result.error ?? '未知原因'}`)
797
795
  }
798
796
  }
797
+ if (typeof service.revokeIngest === 'function') {
798
+ for (const source of emptyQuotaIngestSources(resources)) {
799
+ if (!active || !automationSettings.isQuotaIngestEnabled()) return
800
+ const result = await service.revokeIngest(source)
801
+ if (result?.ok === false) host.logger?.warn?.(`[unified-router] ${source} 额度撤回失败`)
802
+ }
803
+ }
799
804
  } catch { /* 推送失败不影响推理 */ }
805
+ finally { quotaIngestRunning = false }
800
806
  }
801
807
  // 与药丸/快照刷新同频(宿主采集周期 60s),不额外加密轮询。
802
808
  quotaIngestTimer = setInterval(() => { void reportQuota() }, 60_000)
package/lib/workbuddy.js CHANGED
@@ -371,8 +371,9 @@ export function createWorkBuddyManager(ctx, rawConfig = {}, testDeps = {}) {
371
371
  // 旧单账号采纳:索引缺失/为空且旧引用存在时,把它复制成第一个账号。
372
372
  // 任何一步失败都按空账号处理(不抛错);失败时保留旧引用,下次启动还能重试。
373
373
  // 成功后才清除旧引用——旧名只允许「清除」这一个写动作。
374
- const adoptLegacy = async () => {
374
+ const adoptLegacy = async (status) => {
375
375
  const { readable, raw } = await credentialRaw(WORKBUDDY_LEGACY_AUTH_REF)
376
+ if (status) status.empty = readable && raw === null
376
377
  if (!readable || raw === null) return []
377
378
  let parsed
378
379
  try { parsed = JSON.parse(raw) } catch { return [] }
@@ -404,11 +405,11 @@ export function createWorkBuddyManager(ctx, rawConfig = {}, testDeps = {}) {
404
405
 
405
406
  // accounts 是所有方法的账号来源:索引损坏按空处理(不采纳、不覆盖,避免把
406
407
  // 损坏状态写成「一个账号都没有」的数据丢失),缺失/为空才走旧单账号采纳。
407
- const accounts = async () => {
408
+ const accounts = async (status) => {
408
409
  const index = await readIndex()
409
410
  if (index.state === 'ok' || index.state === 'unavailable') return index.entries
410
411
  if (index.state === 'corrupt') return []
411
- return adoptLegacy()
412
+ return adoptLegacy(status)
412
413
  }
413
414
 
414
415
  const readAccountAuth = async entry => {
@@ -672,7 +673,8 @@ export function createWorkBuddyManager(ctx, rawConfig = {}, testDeps = {}) {
672
673
  const snapshot = async signal => {
673
674
  signal?.throwIfAborted()
674
675
  if (disposed) throw new Error('请求已结束')
675
- const entries = await accounts()
676
+ const indexStatus = { empty: false }
677
+ const entries = await accounts(indexStatus)
676
678
  signal?.throwIfAborted()
677
679
  const rows = (await Promise.all(entries.map(entry => readAccount(entry, signal).catch(error => {
678
680
  if (signal?.aborted) throw error
@@ -682,7 +684,7 @@ export function createWorkBuddyManager(ctx, rawConfig = {}, testDeps = {}) {
682
684
  // 面板上那三个 credits 窗口无法回答「这个号还能不能继续用」。
683
685
  .map(row => withRateLimitWindow(row))
684
686
  signal?.throwIfAborted()
685
- return { accounts: rows, loginUrl: pendingLoginUrl }
687
+ return { accounts: rows, loginUrl: pendingLoginUrl, ...(indexStatus.empty ? { accountsEmptyConfirmed: true } : {}) }
686
688
  }
687
689
 
688
690
  // ---- 登录(新增账号) ---------------------------------------------------
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-unified-router",
3
- "version": "0.8.3",
3
+ "version": "0.8.4",
4
4
  "type": "module",
5
5
  "main": "lib/web-host.js",
6
6
  "license": "MIT",
@@ -61,7 +61,7 @@
61
61
  "scripts": {
62
62
  "build": "node scripts/build.mjs",
63
63
  "test": "node scripts/build.mjs && npm run test:run",
64
- "test:run": "node --test test/backend.test.mjs test/cleanup-loomy.test.mjs test/channel-method-parity.test.mjs test/channel-contract.test.mjs test/client-channel-agnostic.test.mjs test/host.test.mjs test/retired-channels.test.mjs test/web-client.test.mjs test/model-selection-ui.test.mjs test/context-pill.test.mjs test/quota-pill.test.mjs test/quota-priority.test.mjs test/sensenova-manager.test.mjs test/sensenova-models.test.mjs test/plan-models-ui.test.mjs test/workbuddy.test.mjs test/model-rate-badge.test.mjs test/model-rate-badge-paths.test.mjs test/qoder-cli.test.mjs test/raccoon-thinking.test.mjs test/raccoon-checkin.test.mjs test/thinking-defaults.test.mjs test/model-blacklist-hygiene.test.mjs test/apikey-providers.test.mjs test/apikey-new-channel.test.mjs test/apikey-llm.test.mjs test/apikey-models.test.mjs test/apikey-channel.test.mjs test/apikey-host.test.mjs test/apikey-client.test.mjs test/unisound-tools.test.mjs test/agnes-image-tool.test.mjs test/managed-channels.test.mjs test/automation-and-ux.test.mjs test/balance-confirm.test.mjs test/quota-ingest.test.mjs test/trae-cache.test.mjs test/cot-loop-guard.test.mjs",
64
+ "test:run": "node --test test/backend.test.mjs test/cleanup-loomy.test.mjs test/channel-method-parity.test.mjs test/channel-contract.test.mjs test/client-channel-agnostic.test.mjs test/host.test.mjs test/retired-channels.test.mjs test/web-client.test.mjs test/model-selection-ui.test.mjs test/context-pill.test.mjs test/quota-pill.test.mjs test/quota-priority.test.mjs test/sensenova-manager.test.mjs test/sensenova-models.test.mjs test/plan-models-ui.test.mjs test/workbuddy.test.mjs test/model-rate-badge.test.mjs test/model-rate-badge-paths.test.mjs test/qoder-cli.test.mjs test/raccoon-thinking.test.mjs test/raccoon-checkin.test.mjs test/raccoon-unified.test.mjs test/thinking-defaults.test.mjs test/model-blacklist-hygiene.test.mjs test/apikey-providers.test.mjs test/apikey-new-channel.test.mjs test/apikey-llm.test.mjs test/apikey-models.test.mjs test/apikey-channel.test.mjs test/apikey-host.test.mjs test/apikey-client.test.mjs test/unisound-tools.test.mjs test/agnes-image-tool.test.mjs test/managed-channels.test.mjs test/automation-and-ux.test.mjs test/balance-confirm.test.mjs test/quota-ingest.test.mjs test/trae-cache.test.mjs test/cot-loop-guard.test.mjs",
65
65
  "check:residue": "node scripts/check-vendor-residue.mjs"
66
66
  },
67
67
  "dsh": {