dsh-unified-router 0.8.2 → 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
@@ -15,7 +15,9 @@ export const AUTOMATION_METHODS = Object.freeze(new Set([
15
15
 
16
16
  /** 分渠道布尔覆盖字段。 */
17
17
  const BOOL_FIELDS = ['autoCheckin', 'autoClaimRewards', 'autoCompleteTasks', 'cotLoopGuard']
18
- const GLOBAL_BOOL_FIELDS = [...BOOL_FIELDS, 'preferExpiringQuota', 'raccoonUnifiedModels']
18
+ // `quotaIngest` 是全局开关(不分渠道):向 subusage 推送额度,默认关闭,
19
+ // 避免接收端被一次塞入过多卡片。
20
+ const GLOBAL_BOOL_FIELDS = [...BOOL_FIELDS, 'preferExpiringQuota', 'raccoonUnifiedModels', 'quotaIngest']
19
21
  // 分渠道的默认输出上限(token):**只在上游没给输出规格时生效**
20
22
  // (目录 `max_output` 缺失或为 null,如云知声 u2-med / u2-radimed)。
21
23
  // 上游有值就用上游值,这个设置只补缺,不覆盖真实规格。
@@ -49,6 +51,7 @@ function readInitialConfig(file, defaults) {
49
51
  cotLoopGuard: defaults.cotLoopGuard !== false,
50
52
  preferExpiringQuota: defaults.preferExpiringQuota === true,
51
53
  raccoonUnifiedModels: defaults.raccoonUnifiedModels === true,
54
+ quotaIngest: defaults.quotaIngest === true,
52
55
  routingMode: routingModeOf(defaults.routingMode, defaults.preferExpiringQuota === true ? 'expiring' : 'manual'),
53
56
  providers: {},
54
57
  }
@@ -102,6 +105,7 @@ export function publicAutomationConfig(value, allowedProviders = null) {
102
105
  routingMode: routingModeOf(source.routingMode, source.preferExpiringQuota === true ? 'expiring' : 'manual'),
103
106
  preferExpiringQuota: routingModeOf(source.routingMode, source.preferExpiringQuota === true ? 'expiring' : 'manual') === 'expiring',
104
107
  raccoonUnifiedModels: source.raccoonUnifiedModels === true,
108
+ quotaIngest: source.quotaIngest === true,
105
109
  providers,
106
110
  }
107
111
  }
@@ -150,6 +154,7 @@ export function createAutomationSettings({ file, defaults = {}, allowedProviders
150
154
  cotLoopGuard: state.cotLoopGuard,
151
155
  preferExpiringQuota: state.preferExpiringQuota,
152
156
  raccoonUnifiedModels: state.raccoonUnifiedModels,
157
+ quotaIngest: state.quotaIngest,
153
158
  routingMode: state.routingMode,
154
159
  providers: Object.fromEntries(Object.entries(state.providers).map(([id, entry]) => [id, { ...entry }])),
155
160
  }
@@ -218,6 +223,7 @@ export function createAutomationSettings({ file, defaults = {}, allowedProviders
218
223
  isAutoClaimRewardsEnabled: provider => effective('autoClaimRewards', provider),
219
224
  isAutoCompleteTasksEnabled: provider => effective('autoCompleteTasks', provider),
220
225
  isCotLoopGuardEnabled: provider => effective('cotLoopGuard', provider),
226
+ isQuotaIngestEnabled: () => state.quotaIngest === true,
221
227
  isQuotaPriorityEnabled: () => state.preferExpiringQuota === true,
222
228
  routingMode: () => state.routingMode,
223
229
  /**
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
  /**
@@ -1666,6 +1660,7 @@ function automationFrom(value) {
1666
1660
  cotLoopGuard: cfg.cotLoopGuard !== false,
1667
1661
  preferExpiringQuota: cfg.preferExpiringQuota === true,
1668
1662
  raccoonUnifiedModels: cfg.raccoonUnifiedModels === true,
1663
+ quotaIngest: cfg.quotaIngest === true,
1669
1664
  routingMode: ['manual', 'free', 'expiring', 'sticky'].includes(cfg.routingMode) ? cfg.routingMode
1670
1665
  : cfg.preferExpiringQuota === true ? 'expiring' : 'manual',
1671
1666
  providers,
@@ -4144,6 +4139,18 @@ function automationRowsFor(provider, state) {
4144
4139
  const inherited = field => !state.automation ? '待读取' : typeof overrides[field] === 'boolean' ? '本渠道单独设置' : '跟随全局设置'
4145
4140
  const scope = 'automation'
4146
4141
  const rows = []
4142
+ // 全局开关(只在一个渠道卡渲染,避免每张卡重复):向 subusage 推送额度。
4143
+ // 默认关闭——接收端一次会被塞入多张卡,开与不开由用户决定。
4144
+ if (provider.caps?.quotaIngestToggle === true) {
4145
+ const enabled = state.automation?.config?.quotaIngest === true
4146
+ rows.push({ id: 'quota-ingest', name: '向 subusage 推送额度', scope,
4147
+ meta: enabled ? '按渠道分卡推送 · 与额度刷新同频(60 秒)' : '关闭 · 不向 subusage 推送',
4148
+ value: enabled,
4149
+ options: [
4150
+ { value: false, label: '关' },
4151
+ { value: true, label: '开' },
4152
+ ].map(option => ({ ...option, call: ['setAutomationConfig', { quotaIngest: option.value }] })) })
4153
+ }
4147
4154
  if (state.automation?.quotaProviders?.includes(id)) {
4148
4155
  // 智能选号模式(全局单选):分段控件代替旧的布尔开关。
4149
4156
  // manual = 手动顺序;free = 免费额度优先;expiring = 临期优先(兼容旧开关);
@@ -4943,6 +4950,8 @@ const raccoon = {
4943
4950
  familySide: 'free',
4944
4951
  quotaExtraResources: ['automation.status'],
4945
4952
  permanentPackageNames: ['奖励积分'],
4953
+ // 全局「向 subusage 推送额度」开关只在本卡渲染(家族卡是设置页第一张)。
4954
+ quotaIngestToggle: true,
4946
4955
  },
4947
4956
  }
4948
4957
 
@@ -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)) {