dsh-unified-router 0.7.3 → 0.7.5

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.
@@ -913,9 +913,20 @@ const bailian = {
913
913
  rate_limit_exceeded: 'rpm',
914
914
  Throttling: 'rpm',
915
915
  'Throttling.RateQuota': 'rpm',
916
+ 'Throttling.ServiceOverloaded': 'rpm',
916
917
  'Throttling.AllocationQuota': 'tpm',
918
+ 'Throttling.ResourceExhausted': 'tpm',
919
+ // 百炼把每分钟 Token 限流也标成 `insufficient_quota`(429 实测样本见
920
+ // throttlePattern),按 TPM 限流处理;真正的额度用尽由 exhaustedPattern
921
+ // 与 exhaustedCodes 拦住。
922
+ insufficient_quota: 'tpm',
917
923
  },
918
- exhaustedCodes: ['insufficient_quota', 'AllocationQuota.FreeTierOnly'],
924
+ // 429 实测原文:`Allocated quota exceeded, please increase your quota limit.
925
+ // For details, see: …/error-code#token-limit` —— message 与锚点都指向
926
+ // **每分钟 Token 限流**,不是账户额度耗尽。
927
+ throttlePattern: /token-limit|allocated[\s_-]+quota[\s_-]+exceeded|increase[\s_-]+your[\s_-]+quota[\s_-]+limit|quota[\s_-]+per[\s_-]+minute|\brate[\s_-]+limit|too[\s_-]+many[\s_-]+requests/i,
928
+ exhaustedCodes: ['AllocationQuota.FreeTierOnly'],
929
+ exhaustedPattern: /free[\s_-]+tier|free[\s_-]+quota|欠费|arrears|balance[\s_-]+(?:exhausted|depleted)|out[\s_-]+of[\s_-]+(?:credits?|budget)/i,
919
930
  },
920
931
  }
921
932
 
@@ -93,13 +93,39 @@ async function peekApiKeyError(response) {
93
93
  } catch { return null } finally { clearTimeout(timer); void reader.cancel().catch(() => {}) }
94
94
  }
95
95
 
96
+ /**
97
+ * 通用限流/耗尽判据(默认值,渠道规格可用 `throttlePattern` / `exhaustedPattern` 覆盖)。
98
+ *
99
+ * 为什么用文本判据而不是错误码表:上游对「每分钟 Token 超限」与「账户额度用尽」
100
+ * 用同一个错误码(百炼 429 实测两者都是 `insufficient_quota`),只查码必然误判;
101
+ * 而各家的码表既不稳定也无法穷举。同类实现(magpie 网关)同样以正文措辞为主判据,
102
+ * 只在少数明确码上走快路径 —— 这里沿用同一口径。
103
+ *
104
+ * 判定顺序:**先认「明确指向用尽」且不指向限流的**(真耗尽不能换号/不能当可重试),
105
+ * 其余落到限流或未知。文本取自错误正文的 message。
106
+ */
107
+ const DEFAULT_THROTTLE_PATTERN = new RegExp([
108
+ 'rate[\\s_.-]?limit', 'frequency[\\s_.-]?limit', 'too many requests',
109
+ 'per[\\s_.-]?(?:second|sec|minute|min)\\b', '\\b[rt]p[ms]\\b',
110
+ '(?:token|call|request)[\\s_.-]+rate[\\s_.-]+limit',
111
+ '每分钟', '每秒', '频率', '太频繁', '过于频繁', '速率',
112
+ 'token[\\s_.-]?limit',
113
+ ].join('|'), 'i')
114
+ const DEFAULT_EXHAUSTED_PATTERN = new RegExp([
115
+ 'insufficient[\\s_.-]?(?:balance|credit|fund)', '\\bcredits? (?:are )?exhausted\\b',
116
+ 'credit[\\s_.-]?balance[\\s_.-]?exhausted', 'out of (?:credits?|budget)',
117
+ 'budget.{0,32}(?:exceeded|exhausted)', 'free[\\s_.-]?tier', 'free[\\s_.-]?quota',
118
+ '余额不足', '欠费', '请充值', 'arrears',
119
+ ].join('|'), 'i')
120
+
96
121
  /**
97
122
  * 识别限流信号。
98
123
  *
99
- * 规格用两个字段表达差异:
124
+ * 规格用四个字段表达差异:
100
125
  * - `scanOnOk`:有的上游用 2xx + 业务码回限流(云知声 `100501`/`100502`),
101
126
  * 这类渠道连成功响应也要读 body;其余渠道只在 429 时读。
102
127
  * - `codes`:业务码 → `rpm` / `tpm` 的映射。
128
+ * - `throttlePattern` / `exhaustedPattern`:可选覆盖默认文本判据。
103
129
  */
104
130
  export async function detectApiKeyRateLimit(spec, response, now = Date.now()) {
105
131
  const recipe = spec?.rateLimit
@@ -107,16 +133,28 @@ export async function detectApiKeyRateLimit(spec, response, now = Date.now()) {
107
133
  // 只在 429,或规格声明「2xx 也可能带限流」时才读 body。
108
134
  if (response.status !== 429 && !(recipe.scanOnOk === true && response.ok)) return null
109
135
  const body = await peekApiKeyError(response)
110
- const code = String(body?.base_resp?.status_code ?? body?.error?.code ?? body?.error?.type ?? '')
111
- const type = String(body?.error?.type ?? '')
136
+ // 错误信封有两种形状:OpenAI 兼容(`{error:{code,type,message}}`)与阿里云风格
137
+ // (顶层 `{code,type,message}`)。只查 `error.*` 会把后者读成空串,进而把限流
138
+ // 误判为「unknown」。两种都要取。
139
+ const code = String(body?.base_resp?.status_code ?? body?.error?.code ?? body?.code ?? body?.error?.type ?? body?.type ?? '')
140
+ const type = String(body?.error?.type ?? body?.type ?? '')
141
+ const message = String(body?.error?.message ?? body?.message ?? body?.msg ?? '')
112
142
  // 额度耗尽不是限流:这类信号交给额度面板,不参与换号。
113
143
  const exhausted = new Set([
114
144
  '100104', '220107', '220108', '220109',
115
145
  'insufficient_quota', 'insufficient_balance', 'billing_hard_limit_reached',
116
146
  ...(recipe.exhaustedCodes ?? []),
117
147
  ])
118
- if (exhausted.has(code) || exhausted.has(type)) return null
119
- const reason = recipe.codes?.[code] ?? 'unknown'
148
+ // ⚠️ 上游会把**每分钟 Token 限流**也标成 `insufficient_quota`(百炼 429 实测:
149
+ // `{"code":"insufficient_quota","message":"Allocated quota exceeded, please
150
+ // increase your quota limit. …#token-limit"}`),只按错误码一刀切会把可恢复的
151
+ // TPM 限流当成账户额度用尽。故用正文二次判定:明确指向限流的不算耗尽,
152
+ // 明确指向额度/余额用尽的仍然排除。
153
+ const looksThrottled = (recipe.throttlePattern ?? DEFAULT_THROTTLE_PATTERN).test(message)
154
+ const looksExhausted = (recipe.exhaustedPattern ?? DEFAULT_EXHAUSTED_PATTERN).test(message)
155
+ if (looksExhausted && !looksThrottled) return null
156
+ if ((exhausted.has(code) || exhausted.has(type)) && !looksThrottled) return null
157
+ const reason = recipe.codes?.[code] ?? recipe.codes?.[type] ?? (looksThrottled ? 'tpm' : 'unknown')
120
158
  if (reason === 'unknown' && response.status !== 429) return null
121
159
  const header = response.headers.get('retry-after')?.trim()
122
160
  const delay = header && /^\d+(?:\.\d+)?$/.test(header) ? Number(header) * 1000
package/lib/backend.js CHANGED
@@ -2505,6 +2505,7 @@ var OFFICIAL_MODEL_SPECS = Object.freeze({
2505
2505
  "deepseek-v4-pro": { context: 1048576, maxOutput: 393216 },
2506
2506
  "deepseek-v4-pro-0813": { context: 1048576, maxOutput: 393216 },
2507
2507
  "deepseek-v4-flash": { context: 1048576, maxOutput: 393216 },
2508
+ "glm-5-4": { context: 1e6, maxOutput: 131072 },
2508
2509
  "glm-5-3": { context: 1048576, maxOutput: 131072 },
2509
2510
  "glm-5-3-flash": { context: 1048576, maxOutput: 131072 },
2510
2511
  "glm-5-3-flashx": { context: 1048576, maxOutput: 131072 },
@@ -3263,7 +3264,6 @@ var QODER_CN_FALLBACK_MODELS = [
3263
3264
  { id: "fast", name: "Fast", contextWindow: 2e5, supportsImage: true, supportsThinking: false, priceFactor: 0.8 },
3264
3265
  // 2026-11-19 --list-models lists these titles without publishing their backend keys or capabilities.
3265
3266
  { id: "Qwen4-Max", name: "Qwen4-Max", contextWindow: 1e6, supportsImage: true, supportsThinking: true, priceFactor: 0.4, efforts: ["xhigh", "low", "medium"], defaultEffort: "medium", supportsDisable: true },
3266
- { id: "Qwen4-Max-Preview", name: "Qwen4-Max-Preview", contextWindow: 0 },
3267
3267
  {
3268
3268
  id: "qmodel_38max",
3269
3269
  name: "Qwen3.8-Max",
@@ -3292,6 +3292,8 @@ var QODER_CN_FALLBACK_MODELS = [
3292
3292
  { id: "dmodel", name: "DeepSeek-V4-Pro", contextWindow: 1e6, supportsImage: true, supportsThinking: true, priceFactor: 0.5, efforts: ["low", "high", "max"], defaultEffort: "max", supportsDisable: true },
3293
3293
  // 滚动别名按渠道原名保留,不凭别名推断具体快照版本。
3294
3294
  { id: "dfmodel", name: "DeepSeek-Flash", contextWindow: 1e6, maxTokens: 393216, supportsImage: true, priceFactor: 0.1, efforts: ["low", "high", "max"], defaultEffort: "high", supportsDisable: true },
3295
+ // 2026-11-26 实跑 --list-models 新增 GLM-5.4(CLI 不下发能力字段);规格取智谱官方文档(1M/128K、原生视觉、三档思考),倍率未知不编造。
3296
+ { id: "GLM-5.4", name: "GLM-5.4", contextWindow: 1e6, maxTokens: 131072, supportsImage: true, supportsThinking: true, efforts: ["low", "high", "max"], defaultEffort: "high" },
3295
3297
  { id: "gmodel", name: "GLM-5.3", contextWindow: 1e6, supportsImage: true, supportsThinking: true, priceFactor: 0.8, efforts: ["low", "high", "max"], defaultEffort: "high" },
3296
3298
  { id: "gfmodel", name: "GLM-5.3-Flash", contextWindow: 1e6, supportsImage: true, supportsThinking: true, priceFactor: 0.1, efforts: ["high", "max"], defaultEffort: "max" },
3297
3299
  { id: "kmodel_latest", name: "Kimi-K3.1-Pro", contextWindow: 1e6, supportsImage: true, priceFactor: 1, efforts: ["low", "high", "max"], defaultEffort: "high" },
package/lib/client.js CHANGED
@@ -477,6 +477,7 @@ const OFFICIAL_MODEL_SPECS = Object.freeze({
477
477
  'deepseek-v4-pro': { context: 1_048_576, maxOutput: 393_216 },
478
478
  'deepseek-v4-pro-0813': { context: 1_048_576, maxOutput: 393_216 },
479
479
  'deepseek-v4-flash': { context: 1_048_576, maxOutput: 393_216 },
480
+ 'glm-5-4': { context: 1_000_000, maxOutput: 131_072 },
480
481
  'glm-5-3': { context: 1_048_576, maxOutput: 131_072 },
481
482
  'glm-5-3-flash': { context: 1_048_576, maxOutput: 131_072 },
482
483
  'glm-5-3-flashx': { context: 1_048_576, maxOutput: 131_072 },
@@ -2629,10 +2630,14 @@ function createRouterStore(call, provider = PROVIDERS[0].id) {
2629
2630
  if (result.status !== 'fulfilled' || !result.value || typeof result.value !== 'object') return
2630
2631
  sources[side] = CACHE_MODEL_SOURCES.has(result.value.source) ? result.value.source : 'fallback'
2631
2632
  })
2632
- const fresh = await Promise.all(sides.map(side => request('model.list', { provider: side }, controller.signal)))
2633
+ // 写后重读必须走实时路径(live: true),否则会读回宿主旧快照里的 `cached` 覆盖刚刷新的 `remote`。
2634
+ const fresh = await Promise.all(sides.map(side => request('model.list', { provider: side, live: true }, controller.signal)))
2633
2635
  if (disposed || controller.signal.aborted || state.provider !== channel) return false
2634
2636
  const refreshedAt = Date.now()
2635
2637
  for (const side of sides) newestModelRead.set(side, refreshedAt)
2638
+ sides.forEach((side, index) => {
2639
+ if (!sources[side] && CACHE_MODEL_SOURCES.has(fresh[index]?.source)) sources[side] = fresh[index].source
2640
+ })
2636
2641
  const refreshed = new Map(sides.map((side, index) => [side, modelsFrom(fresh[index], side)]))
2637
2642
  publish({
2638
2643
  models: modelProvidersOf(channel).flatMap(side => refreshed.has(side)
@@ -12,6 +12,8 @@ import {
12
12
  const MINUTE = 60_000
13
13
  // preflight 明确"未提交"后的自动重查退避。
14
14
  const PREFLIGHT_BACKOFF = 15 * MINUTE
15
+ // pending 主记录(已提交、等待上游结算确认)的自动只读核实间隔:只查不重放。
16
+ const PENDING_VERIFY_INTERVAL = 5 * MINUTE
15
17
  const OUTCOMES = new Set(['claimed', 'already-claimed', 'inactive', 'ineligible', 'failed', 'pending'])
16
18
  // 上游确认已签(核实终态,可修复本地账本)。
17
19
  const DONE_KINDS = new Set(['claimed', 'already-claimed'])
@@ -56,6 +58,7 @@ export function createDailyCheckin({ dir, adapters, enabled = true, isEnabled, n
56
58
  let timer = null
57
59
  let running = null
58
60
  const localJobs = new Map()
61
+ const pendingVerifiedAt = new Map()
59
62
  const providerEnabled = provider => typeof isEnabled === 'function' ? isEnabled(provider) === true : enabled === true
60
63
  const anyEnabled = () => typeof isEnabled === 'function'
61
64
  ? (adapters.size ? [...adapters.keys()].some(providerEnabled) : isEnabled() === true)
@@ -200,6 +203,9 @@ export function createDailyCheckin({ dir, adapters, enabled = true, isEnabled, n
200
203
  outcome: verdict.outcome, local: record,
201
204
  localIsDone: localDone, confirmed, confirmedIsDone: secured,
202
205
  })
206
+ if (verified && verdict.state === 'done' && !localDone && !secured) {
207
+ await onChange?.(provider, outcome)
208
+ }
203
209
  results.push({ ...row, outcome, repeated: true, verified })
204
210
  }
205
211
  return results
@@ -229,7 +235,22 @@ export function createDailyCheckin({ dir, adapters, enabled = true, isEnabled, n
229
235
  if (!providerEnabled(provider)) continue
230
236
  // 只在本轮日界之后执行:Qoder 10:00 日界在 10:00 前属于上一轮,已在上一轮签过。
231
237
  if (dayOf(now(), adapter.resetHour) !== dayOf(now())) continue
232
- try { await claim(provider, undefined, lifetime.signal, true) }
238
+ try {
239
+ const rows = await claim(provider, undefined, lifetime.signal, true)
240
+ // 已有 pending 主记录(已提交但结算未确认)且适配器有只读 verify:
241
+ // 按间隔自动只读核实,上游结算后落 .confirmed 票据并刷新快照,绝不重复提交 claim。
242
+ if (typeof adapter.verify === 'function') {
243
+ for (const row of rows) {
244
+ if (lifetime.signal.aborted) break
245
+ if (row.outcome?.kind !== 'pending' || !row.repeated) continue
246
+ const key = `${provider}:${row.accountId}`
247
+ const last = pendingVerifiedAt.get(key) ?? 0
248
+ if (now() - last < PENDING_VERIFY_INTERVAL) continue
249
+ pendingVerifiedAt.set(key, now())
250
+ try { await query(provider, row.accountId, lifetime.signal) } catch {}
251
+ }
252
+ }
253
+ }
233
254
  catch { if (!lifetime.signal.aborted) logger?.warn?.('[unified-router] 自动签到暂未完成') }
234
255
  }
235
256
  })().finally(() => { running = null })
@@ -923,7 +923,27 @@ export const codeartsSpec = {
923
923
  for (const { item, ch } of campaigns) {
924
924
  const campaignId = item?.campaignId ?? item?.id
925
925
  if (codeArtsDailyClaimed(item)) { doneCount++; continue }
926
- if (String(item?.status ?? '').toUpperCase() === 'CLAIMED') { pendingCount++; continue }
926
+ if (String(item?.status ?? '').toUpperCase() === 'CLAIMED') {
927
+ // 已领取待确认:不重发 claim,只尝试补发一次 confirm 推进结算。
928
+ const existingBenefitId = item?.userBenefitId ?? item?.benefitRecordId
929
+ if ((ch === 'IDE' && campaignId) || existingBenefitId != null) {
930
+ const confirmRes = await codeArtsPostOps(handle, cred, '/v1/ops/confirm',
931
+ ch === 'IDE' ? { campaignId } : { userBenefitId: existingBenefitId }, signal)
932
+ if (codeArtsBizOk(confirmRes)) {
933
+ claimed++
934
+ creditSum += Number(item?.benefitAmount ?? item?.creditAmount) || 0
935
+ continue
936
+ }
937
+ const seenItem = campaignId ? await codeArtsFindDailyItem(handle, cred, signal, campaignId) : null
938
+ if (codeArtsDailyClaimed(seenItem) && String(seenItem?.status ?? '').toUpperCase() !== 'CLAIMED') {
939
+ claimed++
940
+ creditSum += Number(item?.benefitAmount ?? item?.creditAmount) || 0
941
+ continue
942
+ }
943
+ }
944
+ pendingCount++
945
+ continue
946
+ }
927
947
  if (item?.claimable !== true) continue
928
948
  if (!campaignId) { failedCount++; continue }
929
949
  submitted = true
@@ -386,6 +386,7 @@ const OFFICIAL_MODEL_SPECS = Object.freeze({
386
386
  'deepseek-v4-pro': { context: 1_048_576, maxOutput: 393_216 },
387
387
  'deepseek-v4-pro-0813': { context: 1_048_576, maxOutput: 393_216 },
388
388
  'deepseek-v4-flash': { context: 1_048_576, maxOutput: 393_216 },
389
+ 'glm-5-4': { context: 1_000_000, maxOutput: 131_072 },
389
390
  'glm-5-3': { context: 1_048_576, maxOutput: 131_072 },
390
391
  'glm-5-3-flash': { context: 1_048_576, maxOutput: 131_072 },
391
392
  'glm-5-3-flashx': { context: 1_048_576, maxOutput: 131_072 },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-unified-router",
3
- "version": "0.7.3",
3
+ "version": "0.7.5",
4
4
  "type": "module",
5
5
  "main": "lib/web-host.js",
6
6
  "license": "MIT",