dsh-desktop-statusbar 3.0.5 → 3.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1575,6 +1575,7 @@ function sanitizeRelayEndpoint(value) {
1575
1575
  return parsed.toString()
1576
1576
  }
1577
1577
 
1578
+
1578
1579
  function relayChannelKeyValid(channelKey) {
1579
1580
  return typeof channelKey === 'string' && channelKey.length > 0 && channelKey.length <= 128
1580
1581
  && channelKey.trim() === channelKey && !/[\r\n\0]/.test(channelKey)
@@ -1593,12 +1594,20 @@ function relayBalanceDivisorValid(value) {
1593
1594
  return typeof value === 'number' && Number.isFinite(value) && value > 0 && value <= 1e12
1594
1595
  }
1595
1596
 
1597
+ /* 通用中转站解析方式(探测端点种类)。持久化到平台档案,是因为 credits 的余额是
1598
+ “total_credits - total_usage” 的减法,无法用单个 balancePath + 除数表达;第二次查询要按
1599
+ 同一个 kind 用 parseGenericRelayBalance 重算,才能保住余额正确。 */
1600
+ function genericRelayKindValid(value) {
1601
+ return value === 'usage' || value === 'user-self' || value === 'credit-grants' || value === 'credits'
1602
+ }
1603
+
1596
1604
  function relaySettings(body, previous, headerNames) {
1597
1605
  const source = body !== null && typeof body === 'object' && !Array.isArray(body) ? body : {}
1598
1606
  const prior = previous !== null && typeof previous === 'object' ? previous : {}
1599
1607
  const channelKey = source.channelKey === undefined ? prior.channelKey : source.channelKey
1600
1608
  const endpointValue = source.endpoint === undefined ? prior.endpoint : source.endpoint
1601
- const endpoint = sanitizeRelayEndpoint(endpointValue)
1609
+ /* endpoint 允许空串:平台可以只按倍率计费,或等首次查询自动探测;只有非空才做 URL 校验。 */
1610
+ const endpoint = endpointValue === '' ? '' : sanitizeRelayEndpoint(endpointValue)
1602
1611
  const tokenHeader = source.tokenHeader === undefined
1603
1612
  ? (prior.tokenHeader === undefined ? 'authorization' : prior.tokenHeader)
1604
1613
  : source.tokenHeader
@@ -1618,6 +1627,21 @@ function relaySettings(body, previous, headerNames) {
1618
1627
  ? (prior.feeMultiplier === undefined ? 1 : prior.feeMultiplier)
1619
1628
  : source.feeMultiplier
1620
1629
  const balanceDivisor = source.balanceDivisor ?? prior.balanceDivisor ?? 1
1630
+ /* balanceKind 只由“空地址探测命中 credits 这类无法用 balancePath 表达的余额”时写入。
1631
+ 用户一旦真正改动余额接口地址或解析字段(endpoint / balancePath / balanceDivisor 的值变了),
1632
+ 旧标记就失效,必须清除;只改 token / userId / 倍率等无关字段则保留。
1633
+ 注意:读取既有档案时 previous 为 null,不能把“和空 prior 比都算变化”而误清。 */
1634
+ let balanceKind = source.balanceKind === undefined ? prior.balanceKind : source.balanceKind
1635
+ const previousChannel = previous !== null && typeof previous === 'object' ? previous : null
1636
+ if (previousChannel !== null && source.balanceKind === undefined) {
1637
+ const priorEndpoint = previousChannel.endpoint === undefined ? '' : previousChannel.endpoint
1638
+ const priorBalancePath = previousChannel.balancePath === undefined ? '$.balance' : previousChannel.balancePath
1639
+ const priorBalanceDivisor = previousChannel.balanceDivisor === undefined ? 1 : previousChannel.balanceDivisor
1640
+ const parseChanged = (source.endpoint !== undefined && endpoint !== priorEndpoint)
1641
+ || (source.balancePath !== undefined && balancePath !== priorBalancePath)
1642
+ || (source.balanceDivisor !== undefined && balanceDivisor !== priorBalanceDivisor)
1643
+ if (parseChanged) balanceKind = undefined
1644
+ }
1621
1645
  const names = headerNames === undefined ? prior.headerNames : headerNames
1622
1646
  const segments = relayPathSegments(balancePath)
1623
1647
  if (!relayChannelKeyValid(channelKey) || relayIsMagpie(channelKey) || endpoint === null
@@ -1627,6 +1651,7 @@ function relaySettings(body, previous, headerNames) {
1627
1651
  || segments === null || typeof currency !== 'string' || !/^[A-Z]{3}$/.test(currency)
1628
1652
  || !relayFeeMultiplierValid(feeMultiplier)
1629
1653
  || !relayBalanceDivisorValid(balanceDivisor)
1654
+ || (balanceKind !== undefined && !genericRelayKindValid(balanceKind))
1630
1655
  || !Array.isArray(names) || names.length > RELAY_HEADER_LIMIT) return null
1631
1656
  const seen = new Set()
1632
1657
  for (const name of names) {
@@ -1645,6 +1670,7 @@ function relaySettings(body, previous, headerNames) {
1645
1670
  currency,
1646
1671
  feeMultiplier,
1647
1672
  balanceDivisor,
1673
+ ...(balanceKind === undefined ? {} : { balanceKind: balanceKind }),
1648
1674
  headerNames: names.slice(),
1649
1675
  }
1650
1676
  }
@@ -1665,7 +1691,7 @@ function readRelayConfig() {
1665
1691
  let hasMagpie = false
1666
1692
  const configKeys = new Set([
1667
1693
  'channelKey', 'endpoint', 'tokenHeader', 'userIdHeader', 'tokenPrefix',
1668
- 'balancePath', 'currency', 'feeMultiplier', 'balanceDivisor', 'headerNames',
1694
+ 'balancePath', 'currency', 'feeMultiplier', 'balanceDivisor', 'balanceKind', 'headerNames',
1669
1695
  ])
1670
1696
  for (const item of raw.channels) {
1671
1697
  if (item === null || typeof item !== 'object' || Array.isArray(item)
@@ -2042,7 +2068,12 @@ function writeRelayConfig(config) {
2042
2068
  }
2043
2069
 
2044
2070
  function relayCredentials(ctx) {
2045
- const service = ctx !== null && ctx !== undefined ? ctx.credentials : null
2071
+ if (ctx === null || ctx === undefined) return null
2072
+ let service = ctx.credentials !== undefined && ctx.credentials !== null ? ctx.credentials : null
2073
+ /* 部分测试/宿主只通过 ctx.get('credentials') 暴露服务(与 resolveAdapterKey 的口径一致)。 */
2074
+ if (service === null && typeof ctx.get === 'function') {
2075
+ try { service = ctx.get('credentials') } catch (error) { service = null }
2076
+ }
2046
2077
  return service !== null && service !== undefined
2047
2078
  && typeof service.resolve === 'function' && typeof service.set === 'function'
2048
2079
  && typeof service.unset === 'function' ? service : null
@@ -2130,6 +2161,7 @@ async function relayConfigView(ctx, channels) {
2130
2161
  currency: config.currency,
2131
2162
  feeMultiplier: config.feeMultiplier,
2132
2163
  balanceDivisor: config.balanceDivisor,
2164
+ ...(config.balanceKind === undefined ? {} : { balanceKind: config.balanceKind }),
2133
2165
  headerNames: config.headerNames.slice(),
2134
2166
  tokenConfigured: secrets.token.length > 0,
2135
2167
  userIdConfigured: secrets.userId.length > 0,
@@ -2187,6 +2219,23 @@ async function queryRelayBalance(ctx, config, now) {
2187
2219
  if (response.status >= 300 && response.status < 400) return { ok: false, at: now, reason: 'redirect-not-allowed', provider: config.channelKey }
2188
2220
  if (!response.ok) return { ok: false, at: now, reason: 'upstream-http-error', provider: config.channelKey }
2189
2221
  const data = await readLimitedRelayJson(response)
2222
+ /* 空地址探测命中过 credits 这类“减法”余额时,档案里带 balanceKind;按它用同一个解析器重算,
2223
+ 否则按默认 balancePath 解析会 invalid-balance。 */
2224
+ if (genericRelayKindValid(config.balanceKind)) {
2225
+ const generic = parseGenericRelayBalance(config.balanceKind, data)
2226
+ if (generic === null) return { ok: false, at: now, reason: 'invalid-balance', provider: config.channelKey }
2227
+ return {
2228
+ ok: true,
2229
+ at: now,
2230
+ source: 'relay',
2231
+ provider: config.channelKey,
2232
+ currency: generic.currency.length > 0 ? generic.currency : config.currency,
2233
+ total: generic.total,
2234
+ feeMultiplier: config.feeMultiplier,
2235
+ parts: [],
2236
+ available: true,
2237
+ }
2238
+ }
2190
2239
  const raw = relayValueAt(data, relayPathSegments(config.balancePath))
2191
2240
  const parsed = typeof raw === 'number' ? raw : typeof raw === 'string' && raw.trim().length > 0 ? Number(raw) : NaN
2192
2241
  if (!Number.isFinite(parsed)) return { ok: false, at: now, reason: 'invalid-balance', provider: config.channelKey }
@@ -2811,6 +2860,31 @@ function pickChainHit(ctx, targets, now, baseURL) {
2811
2860
 
2812
2861
  /* 通用中转站探测的超时:每个端点 2.5 秒;候选端点并发探测,全失败也只等一个超时。 */
2813
2862
  const GENERIC_RELAY_FETCH_TIMEOUT_MS = 2500
2863
+ /* 空地址平台自动探测失败后的冷却:同一平台不每轮刷新都重发 7 个候选。 */
2864
+ const RELAY_DISCOVERY_RETRY_MS = 10 * 60 * 1000
2865
+ /* 冷却表上限:这是进程级 Map,必须封顶,避免长期运行时无限增长(按插入顺序淘汰最旧的)。 */
2866
+ const RELAY_DISCOVERY_FAILURES_MAX = 256
2867
+ const relayDiscoveryFailures = new Map()
2868
+
2869
+ /* 冷却指纹:对 baseURL + token + userId 做 sha256,稳定且不泄露原始凭据。
2870
+ 不能只看长度 —— 同长度但不同值的凭据必须得到不同指纹,否则换了 token 仍被旧冷却挡住。 */
2871
+ function discoveryFingerprint(baseURL, token, userId) {
2872
+ return createHash('sha256')
2873
+ .update(String(baseURL)).update('\0')
2874
+ .update(String(token)).update('\0')
2875
+ .update(String(userId))
2876
+ .digest('hex')
2877
+ }
2878
+
2879
+ /* 记录一次探测失败(带容量上限):同一平台只留最新一条,超过上限按插入顺序淘汰最旧的。 */
2880
+ function recordRelayDiscoveryFailure(channelKey, fingerprint, now) {
2881
+ relayDiscoveryFailures.delete(channelKey)
2882
+ relayDiscoveryFailures.set(channelKey, { fingerprint: fingerprint, at: now })
2883
+ while (relayDiscoveryFailures.size > RELAY_DISCOVERY_FAILURES_MAX) {
2884
+ const oldest = relayDiscoveryFailures.keys().next().value
2885
+ relayDiscoveryFailures.delete(oldest)
2886
+ }
2887
+ }
2814
2888
 
2815
2889
  /** 金额字段宽容解析:数字或数字字符串都认,其它返回 null。 */
2816
2890
  function genericRelayNumber(value) {
@@ -2837,12 +2911,12 @@ function genericRelayCurrency(...values) {
2837
2911
  return ''
2838
2912
  }
2839
2913
 
2840
- /** 按候选字段顺序取第一个可解析为有限数字的金额;null / 布尔 / 对象等非数字一律跳过(绝不当 0)。 */
2841
- function firstGenericRelayAmount(object, fields) {
2914
+ /** 按候选字段顺序取第一个可解析为有限数字的金额,并返回命中的字段名(供探测命中后写回 balancePath);非数字跳过(绝不当 0)。 */
2915
+ function firstGenericRelayAmountField(object, fields) {
2842
2916
  if (object === null || object === undefined || typeof object !== 'object' || Array.isArray(object)) return null
2843
2917
  for (let i = 0; i < fields.length; i += 1) {
2844
2918
  const amount = genericRelayNumber(object[fields[i]])
2845
- if (amount !== null) return amount
2919
+ if (amount !== null) return { amount: amount, field: fields[i] }
2846
2920
  }
2847
2921
  return null
2848
2922
  }
@@ -2851,47 +2925,72 @@ function firstGenericRelayAmount(object, fields) {
2851
2925
  const GENERIC_RELAY_AMOUNT_FIELDS = ['available', 'remaining_balance', 'balance_remaining', 'credit', 'credits']
2852
2926
 
2853
2927
  /**
2854
- * 通用中转站余额响应解析(纯函数)。
2855
- * kind 对应探测端点:usage / user-self / credit-grants / credits。
2856
- * 返回 { currency, total }(total 已按界面口径格式化为两位小数字符串),解析不出返回 null。
2928
+ * 通用中转站余额响应解析(内部详细版)。仅在首次 endpoint 探测里使用,返回
2929
+ * { currency, total, balancePath, balanceDivisor }(total 已按界面口径格式化为两位小数字符串),
2930
+ * 解析不出返回 null。
2931
+ * balancePath / balanceDivisor 记录“这笔金额来自哪个字段、除了多少”:空地址首次探测命中后要把它
2932
+ * 一并写回平台档案,否则第二次查询会按默认 `$.balance` 解析而 invalid-balance。
2933
+ * 普通调用者请用下面的 parseGenericRelayBalance(只返回 { currency, total })。
2857
2934
  * 注意:subscription 的总额度字段不是余额,已从候选与解析中删除。
2858
2935
  */
2859
- function parseGenericRelayBalance(kind, data) {
2936
+ function parseGenericRelayBalanceDetailed(kind, data) {
2860
2937
  if (data === null || data === undefined || typeof data !== 'object' || Array.isArray(data)) return null
2861
2938
  const objectOf = (value) => value !== null && value !== undefined
2862
2939
  && typeof value === 'object' && Array.isArray(value) !== true ? value : null
2940
+ const joinPath = (base, key) => (base.length === 0 ? key : base + '.' + key)
2863
2941
  if (kind === 'usage') {
2864
2942
  /* 兼容 { data: { balance, billing, remaining } } 与顶层扁平两种响应。 */
2865
2943
  const inner = objectOf(data.data) === null ? data : data.data
2944
+ const base = inner === data ? '' : 'data'
2866
2945
  const billing = objectOf(inner.billing)
2867
2946
  let amount = genericRelayNumber(inner.balance)
2868
- if (amount === null && billing !== null) amount = genericRelayNumber(billing.balance)
2869
- if (amount === null) amount = genericRelayNumber(inner.remaining)
2870
- if (amount === null) amount = firstGenericRelayAmount(inner, GENERIC_RELAY_AMOUNT_FIELDS)
2947
+ let balancePath = joinPath(base, 'balance')
2948
+ let balanceDivisor = 1
2949
+ if (amount === null && billing !== null && genericRelayNumber(billing.balance) !== null) {
2950
+ amount = genericRelayNumber(billing.balance)
2951
+ balancePath = joinPath(joinPath(base, 'billing'), 'balance')
2952
+ }
2953
+ if (amount === null && genericRelayNumber(inner.remaining) !== null) {
2954
+ amount = genericRelayNumber(inner.remaining)
2955
+ balancePath = joinPath(base, 'remaining')
2956
+ }
2957
+ if (amount === null) {
2958
+ const extra = firstGenericRelayAmountField(inner, GENERIC_RELAY_AMOUNT_FIELDS)
2959
+ if (extra !== null) { amount = extra.amount; balancePath = joinPath(base, extra.field) }
2960
+ }
2871
2961
  if (amount === null) return null
2872
2962
  const currency = genericRelayCurrency(
2873
2963
  data.currency, inner.currency,
2874
2964
  billing === null ? null : billing.currency, billing === null ? null : billing.unit,
2875
2965
  data.unit, inner.unit,
2876
2966
  )
2877
- return { currency: currency, total: amount.toFixed(2) }
2967
+ return { currency: currency, total: amount.toFixed(2), balancePath: balancePath, balanceDivisor: balanceDivisor }
2878
2968
  }
2879
2969
  if (kind === 'user-self') {
2880
2970
  const inner = objectOf(data.data) === null ? data : data.data
2971
+ const base = inner === data ? '' : 'data'
2881
2972
  const billing = objectOf(inner.billing)
2882
2973
  let amount = genericRelayNumber(inner.balance)
2974
+ let balancePath = joinPath(base, 'balance')
2975
+ let balanceDivisor = 1
2883
2976
  if (amount === null) {
2884
2977
  const quota = genericRelayNumber(inner.quota)
2885
2978
  /* 部分中转站的 quota 以 500000 = ¥1 的积分口径返回。
2886
2979
  -1 表示不限量、0 表示没有额度:都不显示负数/0,也不能按 500000 换算。 */
2887
- if (quota !== null && quota > 0) amount = quota / 500000
2980
+ if (quota !== null && quota > 0) { amount = quota / 500000; balancePath = joinPath(base, 'quota'); balanceDivisor = 500000 }
2981
+ }
2982
+ if (amount === null && genericRelayNumber(inner.remaining) !== null) {
2983
+ amount = genericRelayNumber(inner.remaining)
2984
+ balancePath = joinPath(base, 'remaining')
2985
+ }
2986
+ if (amount === null) {
2987
+ const extra = firstGenericRelayAmountField(inner, GENERIC_RELAY_AMOUNT_FIELDS)
2988
+ if (extra !== null) { amount = extra.amount; balancePath = joinPath(base, extra.field) }
2888
2989
  }
2889
- if (amount === null) amount = genericRelayNumber(inner.remaining)
2890
- if (amount === null) amount = firstGenericRelayAmount(inner, GENERIC_RELAY_AMOUNT_FIELDS)
2891
2990
  if (amount === null) {
2892
2991
  /* 部分站把剩余积分放在顶层 remain_quota:同样按 500000 = ¥1 换算,只在 >0 时认。 */
2893
2992
  const remainQuota = genericRelayNumber(data.remain_quota)
2894
- if (remainQuota !== null && remainQuota > 0) amount = remainQuota / 500000
2993
+ if (remainQuota !== null && remainQuota > 0) { amount = remainQuota / 500000; balancePath = 'remain_quota'; balanceDivisor = 500000 }
2895
2994
  }
2896
2995
  if (amount === null) return null
2897
2996
  const currency = genericRelayCurrency(
@@ -2899,12 +2998,12 @@ function parseGenericRelayBalance(kind, data) {
2899
2998
  billing === null ? null : billing.currency, billing === null ? null : billing.unit,
2900
2999
  data.unit, inner.unit,
2901
3000
  )
2902
- return { currency: currency, total: amount.toFixed(2) }
3001
+ return { currency: currency, total: amount.toFixed(2), balancePath: balancePath, balanceDivisor: balanceDivisor }
2903
3002
  }
2904
3003
  if (kind === 'credit-grants') {
2905
3004
  const amount = genericRelayNumber(data.total_available)
2906
3005
  if (amount === null) return null
2907
- return { currency: genericRelayCurrency(data.currency, data.unit), total: amount.toFixed(2) }
3006
+ return { currency: genericRelayCurrency(data.currency, data.unit), total: amount.toFixed(2), balancePath: 'total_available', balanceDivisor: 1 }
2908
3007
  }
2909
3008
  if (kind === 'credits') {
2910
3009
  const inner = objectOf(data.data) === null ? data : data.data
@@ -2914,11 +3013,24 @@ function parseGenericRelayBalance(kind, data) {
2914
3013
  return {
2915
3014
  currency: genericRelayCurrency(data.currency, inner.currency, data.unit, inner.unit),
2916
3015
  total: (total - (used === null ? 0 : used)).toFixed(2),
3016
+ /* “总额 - 已用”是减法,无法用单个字段 + 除数表达,故不写回 balancePath(null);
3017
+ 探测流程会把 balanceKind='credits' 一并持久化,后续查询按该 kind 重算,余额仍然正确。 */
3018
+ balancePath: null,
3019
+ balanceDivisor: 1,
2917
3020
  }
2918
3021
  }
2919
3022
  return null
2920
3023
  }
2921
3024
 
3025
+ /**
3026
+ * 通用中转站余额响应解析(公共兼容版):只返回 { currency, total },与历史调用方/测试的约定一致。
3027
+ * balancePath / balanceDivisor 等详细解析信息只在首次探测(parseGenericRelayBalanceDetailed)内部使用。
3028
+ */
3029
+ function parseGenericRelayBalance(kind, data) {
3030
+ const detailed = parseGenericRelayBalanceDetailed(kind, data)
3031
+ return detailed === null ? null : { currency: detailed.currency, total: detailed.total }
3032
+ }
3033
+
2922
3034
  /**
2923
3035
  * 从 settings 服务的 live config 里找 provider 的接入配置。
2924
3036
  * settings.describe() 返回每个插件 entry 的 SettingsDescriptor,value 是当前配置;
@@ -3077,8 +3189,30 @@ function genericRelayRoot(baseURL) {
3077
3189
  return String(baseURL).trim().replace(/\/+$/, '').replace(/\/v1$/i, '')
3078
3190
  }
3079
3191
 
3192
+ /**
3193
+ * 通用中转站的候选余额端点(数组顺序即优先级)。
3194
+ * 前 4 个是 OpenAI 兼容站常用路径;后 3 个兼容不带 /v1 前缀的站点。
3195
+ */
3196
+ function genericRelayAttempts(baseURL) {
3197
+ const root = genericRelayRoot(baseURL)
3198
+ if (root.length === 0) return []
3199
+ return [
3200
+ { kind: 'usage', url: root + '/v1/usage' },
3201
+ { kind: 'user-self', url: root + '/v1/user/self' },
3202
+ /* OpenAI 兼容站只探测 credit_grants:total_available 才是剩余额;
3203
+ subscription 的总额度字段不是余额,不能当余额。 */
3204
+ { kind: 'credit-grants', url: root + '/v1/dashboard/billing/credit_grants' },
3205
+ { kind: 'credits', url: root + '/v1/credits' },
3206
+ /* B 方案:部分通用中转站的 user/self 与 usage 端点不带 /v1 前缀。
3207
+ 追加在 4 个原有端点之后,保持原优先级;仍并发探测 + 2.5s 超时 + 首个可解析者胜。 */
3208
+ { kind: 'user-self', url: root + '/api/user/self' },
3209
+ { kind: 'user-self', url: root + '/api/v1/user/self' },
3210
+ { kind: 'usage', url: root + '/api/usage' },
3211
+ ]
3212
+ }
3213
+
3080
3214
  /** 请求一个 JSON 端点;非 ok、解析失败、超时或网络错误一律返回 null。 */
3081
- async function fetchGenericRelayJson(url, key, signal) {
3215
+ async function fetchGenericRelayJson(url, headers, signal) {
3082
3216
  const controller = new AbortController()
3083
3217
  const timer = setTimeout(() => controller.abort(), GENERIC_RELAY_FETCH_TIMEOUT_MS)
3084
3218
  const requestSignal = signal === undefined || signal === null
@@ -3087,9 +3221,12 @@ async function fetchGenericRelayJson(url, key, signal) {
3087
3221
  try {
3088
3222
  const response = await fetch(url, {
3089
3223
  method: 'GET',
3090
- headers: { authorization: 'Bearer ' + key, accept: 'application/json' },
3224
+ headers: headers,
3225
+ /* 手动处理重定向:探测请求带着平台 token,绝不能被 3xx 带到别的域;3xx 直接当失败。 */
3226
+ redirect: 'manual',
3091
3227
  signal: requestSignal,
3092
3228
  })
3229
+ if (response.status >= 300 && response.status < 400) return null
3093
3230
  if (response.ok !== true) return null
3094
3231
  const body = await response.json()
3095
3232
  return body !== null && body !== undefined && typeof body === 'object' ? body : null
@@ -3100,6 +3237,30 @@ async function fetchGenericRelayJson(url, key, signal) {
3100
3237
  }
3101
3238
  }
3102
3239
 
3240
+ /**
3241
+ * 并发探测 7 个候选端点,按数组顺序取第一个能解析出余额的。
3242
+ * 早退时 abort 剩余请求:否则它们会挂满 2.5 秒,每轮刷新都留一批悬挂请求。
3243
+ * 全部失败 / 超时返回 null,不抛错。
3244
+ */
3245
+ async function probeGenericRelayBalance(baseURL, headers) {
3246
+ const attempts = genericRelayAttempts(baseURL)
3247
+ if (attempts.length === 0) return null
3248
+ const controllers = attempts.map(() => new AbortController())
3249
+ const probes = attempts.map((attempt, i) => fetchGenericRelayJson(attempt.url, headers, controllers[i].signal))
3250
+ for (let i = 0; i < attempts.length; i += 1) {
3251
+ const data = await probes[i]
3252
+ if (data === null) continue
3253
+ const parsed = parseGenericRelayBalanceDetailed(attempts[i].kind, data)
3254
+ if (parsed !== null) {
3255
+ for (let k = 0; k < controllers.length; k += 1) {
3256
+ if (k !== i) controllers[k].abort()
3257
+ }
3258
+ return { parsed: parsed, endpoint: attempts[i].url, kind: attempts[i].kind }
3259
+ }
3260
+ }
3261
+ return null
3262
+ }
3263
+
3103
3264
  /**
3104
3265
  * 通用中转站余额查询:按常见 OpenAI 兼容余额接口并发探测。
3105
3266
  * 全部失败返回 null(调用方继续原逻辑);不抛错,也不记录 key。
@@ -3112,55 +3273,148 @@ async function queryGenericRelayBalance(ctx, now, provider, config) {
3112
3273
  ? configuredKey
3113
3274
  : await resolveGenericRelayKey(ctx, provider, typeof config.apiKeyEnv === 'string' ? config.apiKeyEnv : null)
3114
3275
  if (baseURL.length === 0 || typeof key !== 'string' || key.length === 0) return null
3115
- const root = genericRelayRoot(baseURL)
3116
- if (root.length === 0) return null
3117
- const finish = (parsed) => {
3118
- logHost(ctx, 'balance(generic): ' + String(provider) + ' → ' + parsed.total + ' ' + parsed.currency)
3119
- return {
3120
- ok: true,
3121
- at: now,
3122
- source: 'generic-relay',
3123
- provider: provider,
3124
- currency: parsed.currency,
3125
- total: parsed.total,
3126
- parts: [],
3127
- }
3276
+ const hit = await probeGenericRelayBalance(baseURL, { authorization: 'Bearer ' + key, accept: 'application/json' })
3277
+ if (hit === null) return null
3278
+ logHost(ctx, 'balance(generic): ' + String(provider) + ' → ' + hit.parsed.total + ' ' + hit.parsed.currency)
3279
+ return {
3280
+ ok: true,
3281
+ at: now,
3282
+ source: 'generic-relay',
3283
+ provider: provider,
3284
+ currency: hit.parsed.currency,
3285
+ total: hit.parsed.total,
3286
+ parts: [],
3128
3287
  }
3129
- const attempts = [
3130
- { kind: 'usage', url: root + '/v1/usage' },
3131
- { kind: 'user-self', url: root + '/v1/user/self' },
3132
- /* OpenAI 兼容站只探测 credit_grants:total_available 才是剩余额;
3133
- subscription 的总额度字段不是余额,不能当余额。 */
3134
- { kind: 'credit-grants', url: root + '/v1/dashboard/billing/credit_grants' },
3135
- { kind: 'credits', url: root + '/v1/credits' },
3136
- /* B 方案:部分通用中转站的 user/self 与 usage 端点不带 /v1 前缀。
3137
- 追加在 4 个原有端点之后,保持原优先级;仍并发探测 + 2.5s 超时 + 首个可解析者胜。 */
3138
- { kind: 'user-self', url: root + '/api/user/self' },
3139
- { kind: 'user-self', url: root + '/api/v1/user/self' },
3140
- { kind: 'usage', url: root + '/api/usage' },
3141
- ]
3142
- /* 候选端点并发探测(按数组顺序定优先级):最坏只等一个 2.5 秒超时,不再是串行累加。
3143
- 按优先级逐个**早退**:前面的端点一旦解析出结果就立刻返回,不再等后面还在飞的请求;
3144
- 失败 / 超时 / 解析不出照旧跳过(fetchGenericRelayJson 内部已把错误归一成 null)。
3145
- 不能改成串行 await —— 那会把最坏耗时从 2.5 秒变成 7 个端点累加。
3146
- 早退时必须 abort 其余还在飞的探测:否则它们会挂满 2.5 秒,每 60 秒轮询都留一批
3147
- 悬挂请求(保留原有优先级语义,只是把落选请求掐掉)。 */
3148
- const controllers = attempts.map(() => new AbortController())
3149
- const probes = attempts.map((attempt, i) => fetchGenericRelayJson(attempt.url, key, controllers[i].signal))
3150
- for (let i = 0; i < attempts.length; i += 1) {
3151
- const data = await probes[i]
3152
- if (data === null) continue
3153
- const parsed = parseGenericRelayBalance(attempts[i].kind, data)
3154
- if (parsed !== null) {
3155
- for (let k = 0; k < controllers.length; k += 1) {
3156
- if (k !== i) controllers[k].abort()
3157
- }
3158
- return finish(parsed)
3288
+ }
3289
+
3290
+ /** 从模型页 settings(其次 cordis.patch.yml)取 provider 的 baseURL;取不到返回 null。 */
3291
+ function relayProviderBaseUrl(ctx, provider) {
3292
+ if (typeof provider !== 'string' || provider.trim().length === 0) return null
3293
+ const config = providerConfigFromSettings(ctx, provider)
3294
+ const candidates = []
3295
+ if (config !== null && typeof config.baseURL === 'string') candidates.push(config.baseURL)
3296
+ const fromPatch = providerBaseUrlOf(provider)
3297
+ if (typeof fromPatch === 'string') candidates.push(fromPatch)
3298
+ for (let i = 0; i < candidates.length; i += 1) {
3299
+ const text = candidates[i].trim()
3300
+ if (text.length === 0) continue
3301
+ try {
3302
+ const parsed = new URL(text)
3303
+ if ((parsed.protocol === 'http:' || parsed.protocol === 'https:') && parsed.hostname.length > 0) return text
3304
+ } catch (error) {
3305
+ /* 换下一个来源 */
3159
3306
  }
3160
3307
  }
3161
3308
  return null
3162
3309
  }
3163
3310
 
3311
+ /**
3312
+ * 空地址平台自动探测时用的 baseURL:只认**平台自己**的地址。
3313
+ * 绝不再回退到会话 provider 的 baseURL —— 那会把本平台的 token/userId 发到另一个
3314
+ * provider 的域名(凭据跨域泄露)。取不到平台自身地址就不探测,由调用方报 relay-endpoint-empty。
3315
+ */
3316
+ function relayDiscoveryBaseUrl(ctx, channelKey) {
3317
+ return relayProviderBaseUrl(ctx, channelKey)
3318
+ }
3319
+
3320
+ /** 自动探测请求头:平台自定义 header + 平台 token / userId(不记录任何值)。 */
3321
+ function relayProbeHeaders(channel, secrets) {
3322
+ const headers = { accept: 'application/json' }
3323
+ const put = (name, value) => {
3324
+ const lower = name.toLowerCase()
3325
+ for (const key of Object.keys(headers)) {
3326
+ if (key.toLowerCase() === lower) delete headers[key]
3327
+ }
3328
+ headers[name] = value
3329
+ }
3330
+ for (const name of Object.keys(secrets.headers)) put(name, secrets.headers[name])
3331
+ if (secrets.token.length > 0) put(channel.tokenHeader, channel.tokenPrefix + secrets.token)
3332
+ if (secrets.userId.length > 0) put(channel.userIdHeader, secrets.userId)
3333
+ return headers
3334
+ }
3335
+
3336
+ /**
3337
+ * 把探测命中的 endpoint 以及解析这笔金额用到的 balancePath / currency / balanceDivisor 一起写回
3338
+ * 平台档案;只填空地址,绝不覆盖并发写入的地址。
3339
+ * 只写 endpoint 不写解析字段的话,第二次查询会按默认 `$.balance` 解析而 invalid-balance。
3340
+ */
3341
+ async function writeDiscoveredRelayEndpoint(channelKey, endpoint, fields) {
3342
+ const clean = sanitizeRelayEndpoint(endpoint)
3343
+ if (clean === null) return false
3344
+ const patch = { endpoint: clean }
3345
+ if (fields !== null && typeof fields === 'object') {
3346
+ if (typeof fields.balancePath === 'string' && relayPathSegments(fields.balancePath) !== null) {
3347
+ patch.balancePath = fields.balancePath
3348
+ }
3349
+ if (typeof fields.currency === 'string' && /^[A-Z]{3}$/.test(fields.currency)) {
3350
+ patch.currency = fields.currency
3351
+ }
3352
+ if (relayBalanceDivisorValid(fields.balanceDivisor)) {
3353
+ patch.balanceDivisor = fields.balanceDivisor
3354
+ }
3355
+ if (genericRelayKindValid(fields.balanceKind)) {
3356
+ patch.balanceKind = fields.balanceKind
3357
+ }
3358
+ }
3359
+ return queueRelayConfigWrite(async () => {
3360
+ const config = readRelayConfig()
3361
+ if (config === null) return false
3362
+ const index = config.channels.findIndex((one) => one.channelKey === channelKey && relayIsMagpie(one.channelKey) !== true)
3363
+ if (index < 0) return false
3364
+ if (config.channels[index].endpoint.length > 0) return false
3365
+ const channels = config.channels.slice()
3366
+ channels[index] = Object.assign({}, config.channels[index], patch)
3367
+ writeRelayConfig({ version: RELAY_CONFIG_VERSION, channels: channels })
3368
+ return true
3369
+ })
3370
+ }
3371
+
3372
+ /**
3373
+ * 空地址平台首次查询:用平台 token/userId/header 并发探测 7 个候选,
3374
+ * 命中后写回 endpoint;后续 queryRelayBalance 只请求这一个地址。
3375
+ * 探测失败返回 null(调用方报 relay-endpoint-empty),且不触碰 token/userId/平台记录。
3376
+ */
3377
+ async function queryDiscoveredRelayBalance(ctx, now, channel) {
3378
+ const baseURL = relayDiscoveryBaseUrl(ctx, channel.channelKey)
3379
+ if (baseURL === null) return null
3380
+ const secrets = await resolveRelaySecrets(ctx, channel.channelKey)
3381
+ if (secrets === null) return null
3382
+ const fingerprint = discoveryFingerprint(baseURL, secrets.token, secrets.userId)
3383
+ const failed = relayDiscoveryFailures.get(channel.channelKey)
3384
+ if (failed !== undefined && failed.fingerprint === fingerprint && now - failed.at < RELAY_DISCOVERY_RETRY_MS) return null
3385
+ const hit = await probeGenericRelayBalance(baseURL, relayProbeHeaders(channel, secrets))
3386
+ if (hit === null) {
3387
+ recordRelayDiscoveryFailure(channel.channelKey, fingerprint, now)
3388
+ logHost(ctx, 'balance(relay): ' + channel.channelKey + ' 空地址自动探测未命中(' + baseURL + ')')
3389
+ return null
3390
+ }
3391
+ relayDiscoveryFailures.delete(channel.channelKey)
3392
+ try {
3393
+ const writeFields = {
3394
+ balancePath: hit.parsed.balancePath,
3395
+ currency: hit.parsed.currency,
3396
+ balanceDivisor: hit.parsed.balanceDivisor,
3397
+ }
3398
+ /* credits 的余额是 total-usage,balancePath 为 null 表示无法用单一路径表达;
3399
+ 改持久化解析 kind,让第二次查询按同一解析器重算,余额仍然正确。 */
3400
+ if (hit.parsed.balancePath === null) writeFields.balanceKind = hit.kind
3401
+ await writeDiscoveredRelayEndpoint(channel.channelKey, hit.endpoint, writeFields)
3402
+ } catch (error) {
3403
+ logHost(ctx, 'balance(relay): ' + channel.channelKey + ' endpoint 写回失败(' + String(error && error.message ? error.message : error) + ')')
3404
+ }
3405
+ logHost(ctx, 'balance(relay): ' + channel.channelKey + ' 自动探测命中 ' + hit.endpoint + ' → ' + hit.parsed.total + ' ' + hit.parsed.currency)
3406
+ return {
3407
+ ok: true,
3408
+ at: now,
3409
+ source: 'generic-relay',
3410
+ provider: channel.channelKey,
3411
+ currency: hit.parsed.currency.length > 0 ? hit.parsed.currency : channel.currency,
3412
+ total: hit.parsed.total,
3413
+ feeMultiplier: channel.feeMultiplier,
3414
+ parts: [],
3415
+ }
3416
+ }
3417
+
3164
3418
  /* ------------------------------------------------------------ Magpie 网关余额 */
3165
3419
 
3166
3420
  /** Magpie 网关地址:`MAGPIE_URL` / `MAGPIE_BASE_URL` 优先,默认本机 3425,去掉尾斜杠。 */
@@ -3300,14 +3554,21 @@ async function queryBalance(ctx, force, provider, model, relay, session) {
3300
3554
  if (hasProvider === true || hasRelay === true) {
3301
3555
  const relayConfig = readRelayConfig()
3302
3556
  const channels = relayConfig === null ? [] : relayConfig.channels
3557
+ /* 地址为空的平台档案仍然保留(只按倍率计费 / 等待首次自动探测),首次查询会并发探测候选端点;
3558
+ 优先用第一个有地址的档位,全部都没有地址时明确返回「无余额端点」,不落到 Magpie 查询。 */
3559
+ const emptyEndpoint = (one) => one !== undefined && relayIsMagpie(one.channelKey) !== true
3560
+ && (typeof one.endpoint !== 'string' || one.endpoint.length === 0)
3303
3561
  const usable = (one) => one !== undefined && relayIsMagpie(one.channelKey) !== true
3562
+ && typeof one.endpoint === 'string' && one.endpoint.length > 0
3304
3563
  const exact = (key) => (typeof key === 'string' && key.trim().length > 0
3305
3564
  ? channels.find((one) => one.channelKey === key)
3306
3565
  : undefined)
3307
3566
  const byRelay = exact(relay)
3308
- if (usable(byRelay) === true) return queryRelayBalance(ctx, byRelay, now)
3309
- const byProvider = exact(provider)
3310
- if (usable(byProvider) === true) return queryRelayBalance(ctx, byProvider, now)
3567
+ /* provider 名只有在宿主确实提供凭据服务时才算平台档案:
3568
+ 否则一个与全局 relay-balance.json 里同名的 provider(如 orbi)会被当成平台通道,
3569
+ 抢先拦截本来该走 Magpie providerHint 的查询。显式 relay 参数不受此限。 */
3570
+ const providerPlatform = hasProvider === true && relayCredentials(ctx) !== null
3571
+ const byProvider = providerPlatform ? exact(provider) : undefined
3311
3572
  /* 模型名回退:先精确,再按紧凑串宽容匹配(前缀/分隔符写法不同也能命中同一模型)。 */
3312
3573
  let byModel = exact(model)
3313
3574
  if (usable(byModel) !== true && typeof model === 'string' && model.trim().length > 0) {
@@ -3316,7 +3577,16 @@ async function queryBalance(ctx, force, provider, model, relay, session) {
3316
3577
  ? channels.find((one) => relayIsMagpie(one.channelKey) !== true && compactModelName(one.channelKey) === compact)
3317
3578
  : undefined
3318
3579
  }
3319
- if (usable(byModel) === true) return queryRelayBalance(ctx, byModel, now)
3580
+ const matches = [byRelay, byProvider, byModel]
3581
+ for (const one of matches) {
3582
+ if (usable(one) === true) return queryRelayBalance(ctx, one, now)
3583
+ }
3584
+ const emptyHit = matches.find((one) => emptyEndpoint(one) === true)
3585
+ if (emptyHit !== undefined) {
3586
+ const discovered = await queryDiscoveredRelayBalance(ctx, now, emptyHit)
3587
+ if (discovered !== null) return discovered
3588
+ return { ok: false, at: now, reason: 'relay-endpoint-empty', provider: emptyHit.channelKey }
3589
+ }
3320
3590
  }
3321
3591
 
3322
3592
  /* 已知 provider 只按 provider 名匹配;provider 为空时**绝不按模型名猜厂商**:
@@ -4113,18 +4383,77 @@ function tokenCost(model, at, parts, provider, feeMultiplier, book) {
4113
4383
  const price = entry.tiered === false ? entry.peak : (isPeakTime(at) ? entry.peak : entry.offPeak)
4114
4384
  const use = price !== null && price !== undefined ? price : entry.peak
4115
4385
  if (use === null || use === undefined) return 0
4386
+ /* Magpie 是**本机聚合网关**,不套用通用自建 relay「缺倍率不计价」的门槛:
4387
+ provider 含 magpie / 模型走 remote-magpie/、magpie/ 时,缺价格条目倍率默认按 1 计价,
4388
+ 与子代理 Magpie 路径(magpieSubagentTokenCost)口径一致,否则主会话里走 Magpie
4389
+ 的调用会一律算成 0、只在台账里挂成欠账(用户报的「走 Magpie 有时不被计费」)。
4390
+ 通用 relay(非 Magpie)仍走下面「缺 feeConfigured 就返回 0 / 记欠账」的老行为。 */
4391
+ const magpie = isMagpieMainUsage(provider, model)
4116
4392
  /* relay:必须明确配置过价格条目的费用倍率,否则视为无价(由调用方记欠账)。 */
4117
- const entryFee = relayPriceFee(entry)
4393
+ const entryFeeRaw = relayPriceFee(entry)
4394
+ const entryFee = entryFeeRaw === null ? (magpie === true ? 1 : null) : entryFeeRaw
4118
4395
  if (entryFee === null) return 0
4119
- const channelMultiplier = typeof feeMultiplier === 'number' && Number.isFinite(feeMultiplier) && feeMultiplier > 0
4120
- ? feeMultiplier
4121
- : relayFeeMultiplierForProvider(provider)
4396
+ /* Magpie 与子代理路径一致:通道倍率一律取 magpieChannelMultiplier(含 channelKey 大小写/别名
4397
+ 兜底到唯一 Magpie 通道),不用事件上那个通用 relay 的 feeMultiplier —— 后者按 channelKey
4398
+ 精确匹配,provider 写作小写 magpie 时匹配不到 'Magpie' 通道会退回 1,配置就丢了。
4399
+ 通用 relay 仍走 feeMultiplier 参数 / relayFeeMultiplierForProvider。 */
4400
+ const channelMultiplier = magpie === true
4401
+ ? magpieChannelMultiplier(provider)
4402
+ : (typeof feeMultiplier === 'number' && Number.isFinite(feeMultiplier) && feeMultiplier > 0
4403
+ ? feeMultiplier
4404
+ : relayFeeMultiplierForProvider(provider))
4122
4405
  /* 旧 relay 通道倍率(兼容存量)× 价格条目倍率(新口径) */
4123
4406
  return ((parts.input * numOrZero(use.input) + parts.cacheRead * numOrZero(use.cacheRead)
4124
4407
  + parts.cacheWrite * numOrZero(use.cacheWrite) + parts.output * numOrZero(use.output)) / 1e6)
4125
4408
  * channelMultiplier * entryFee
4126
4409
  }
4127
4410
 
4411
+ /** Magpie 子代理用量是否按「Magpie 模型价」计价:provider 含 magpie,或模型走 remote-magpie/ 命名空间。 */
4412
+ function isMagpieSubagentUsage(provider, model) {
4413
+ if (typeof provider === 'string' && provider.length > 0 && relayIsMagpie(provider) === true) return true
4414
+ return typeof model === 'string' && /^(?:remote-magpie|magpie)\//i.test(model) === true
4415
+ }
4416
+
4417
+ /**
4418
+ * 主会话(非子代理)用量是否按 Magpie 计价:provider 含 magpie(magpie / remote-magpie 等别名),
4419
+ * **或**模型走 `remote-magpie/`、`magpie/` 命名空间(无论 provider 是否为空)。
4420
+ *
4421
+ * remote-magpie/ 前缀就是局域网 Magpie 的模型命名空间,前缀本身即归属 Magpie,
4422
+ * 不能因为 provider 为空就降级成通用 relay。与 isMagpieSubagentUsage 口径一致。
4423
+ */
4424
+ function isMagpieMainUsage(provider, model) {
4425
+ const providerText = typeof provider === 'string' ? provider : ''
4426
+ if (providerText.length > 0 && relayIsMagpie(providerText) === true) return true
4427
+ return typeof model === 'string' && /^(?:remote-magpie|magpie)\//i.test(model) === true
4428
+ }
4429
+
4430
+ /**
4431
+ * Magpie 通道倍率:先按 channelKey 精确匹配;provider 大小写/别名对不上(magpie vs Magpie)时,
4432
+ * 退回配置里唯一的 Magpie 通道(readRelayConfig 保证最多一个)。缺省 1。
4433
+ */
4434
+ function magpieChannelMultiplier(provider) {
4435
+ const config = relayFeeConfig()
4436
+ if (config === null) return 1
4437
+ const providerText = typeof provider === 'string' ? provider : ''
4438
+ const exact = config.channels.find((one) => one.channelKey === providerText)
4439
+ if (exact !== undefined && relayFeeMultiplierValid(exact.feeMultiplier)) return exact.feeMultiplier
4440
+ const magpie = config.channels.find((one) => relayIsMagpie(one.channelKey))
4441
+ return magpie !== undefined && relayFeeMultiplierValid(magpie.feeMultiplier) ? magpie.feeMultiplier : 1
4442
+ }
4443
+
4444
+ /**
4445
+ * Magpie 子代理费用:实际模型价(officialTokenCost)× Magpie 通道倍率 × 价格条目倍率。
4446
+ * 缺 Magpie 通道倍率 / 价格条目倍率时都默认 1 —— 不像通用 relay 那样缺 feeConfigured 就记 0 欠账
4447
+ * (用户规则:Magpie 是本机聚合网关,不套用自建通用 relay 的「缺倍率不计价」门槛)。
4448
+ * 只被子代理用量聚合调用,主会话与普通 relay 行为不变。
4449
+ */
4450
+ function magpieSubagentTokenCost(model, at, parts, provider) {
4451
+ const entry = priceEntryFor(model)
4452
+ const entryFeeRaw = entry === null ? null : relayPriceFee(entry)
4453
+ const entryFee = entryFeeRaw === null ? 1 : entryFeeRaw
4454
+ return officialTokenCost(model, at, parts) * magpieChannelMultiplier(provider) * entryFee
4455
+ }
4456
+
4128
4457
  /**
4129
4458
  * 这个模型的条目是按哪种货币填的(`CNY` / `USD`,缺省 `CNY`)。
4130
4459
  *
@@ -5339,8 +5668,15 @@ export {
5339
5668
  queryBalance as queryBalanceForTest,
5340
5669
  /* 通用中转站余额:测试直接驱动纯解析、settings 服务发现与本地 mock fetch。 */
5341
5670
  providerConfigFromSettings,
5671
+ /* relaySettings 合并逻辑(仅测试:验证改地址/解析字段清 balanceKind、无关更新保留)。 */
5672
+ relaySettings as relaySettingsForTest,
5342
5673
  parseGenericRelayBalance,
5343
5674
  queryGenericRelayBalance,
5675
+ /* 空地址探测的冷却表与指纹(仅测试:验证同长度不同凭据不共享冷却、Map 容量上限)。 */
5676
+ relayDiscoveryFailures as relayDiscoveryFailuresForTest,
5677
+ recordRelayDiscoveryFailure,
5678
+ discoveryFingerprint,
5679
+ RELAY_DISCOVERY_FAILURES_MAX,
5344
5680
  /* relay-balance-config GET 的来源校验纯函数(仅回环),供 verify-host 直接驱动。 */
5345
5681
  isLocalRequestHost as isLocalRequestHostForTest,
5346
5682
  isLocalOriginHeader as isLocalOriginHeaderForTest,
@@ -5616,8 +5952,10 @@ function usageAggOfEntry(entry, fromMs) {
5616
5952
  agg.tokens.output += parts.output
5617
5953
  /* 一次 usage 事件 = 一次调用(pickUsageEvents 已按 turn/step 去过重、全 0 的不算) */
5618
5954
  agg.calls += 1
5619
- const multiplier = relayFeeMultiplierForProvider(event.provider)
5620
- const amount = tokenCost(event.model, event.time, parts, event.provider, multiplier)
5955
+ /* 子代理用量聚合的 Magpie 分支:按实际模型价计,缺倍率默认 1;其余走原 tokenCost(普通 relay 缺倍率仍记 0)。 */
5956
+ const amount = isMagpieSubagentUsage(event.provider, event.model) === true
5957
+ ? magpieSubagentTokenCost(event.model, event.time, parts, event.provider)
5958
+ : tokenCost(event.model, event.time, parts, event.provider, relayFeeMultiplierForProvider(event.provider))
5621
5959
  agg.cost += amount
5622
5960
  /* 同一笔同时按"模型条目的币种"分桶:客户端混币时要折成一个数字(见 tokenCostCurrency) */
5623
5961
  const code = tokenCostCurrency(event.model)
@@ -6272,10 +6610,23 @@ function settleUnpriced(ledger) {
6272
6610
  ? peakPrice
6273
6611
  : (entry.offPeak !== null && entry.offPeak !== undefined ? entry.offPeak : entry.peak)
6274
6612
  const affiliation = providerAffiliation(debt.provider, debt.model)
6275
- const entryFee = affiliation === 'relay' ? relayPriceFee(entry) : 1
6276
- /* 新口径:relay 必须明确配置倍率才结算;旧债务(feeMultiplier>1)保持兼容。 */
6277
- if (affiliation === 'relay' && entryFee === null && !(debt.feeMultiplier > 1)) { remaining.push(debt); continue }
6278
- const effectiveEntryFee = affiliation === 'relay' && entryFee !== null ? entryFee : 1
6613
+ /* Magpie 归属(provider 含 magpie / 模型 remote-magpie/、magpie/)缺倍率默认 1,
6614
+ 与 tokenCost / magpieSubagentTokenCost 口径一致:老台账里挂了 Magpie 欠账的,
6615
+ 这里也照 1 结算掉,不再永远留在欠账里。通用 relay 缺倍率仍要求显式配置。 */
6616
+ const magpie = isMagpieMainUsage(debt.provider, debt.model)
6617
+ /* 两条路径,互斥且各自写清:
6618
+ · Magpie:恒可结算,价格条目倍率优先用**已配置**的(relayPriceFee 非 null),没配默认 1 ——
6619
+ 不能把已配置的倍率抹成 1。
6620
+ · 普通 relay:必须明确配置倍率才结算(旧债务 feeMultiplier>1 保持兼容),否则继续挂欠账。 */
6621
+ let effectiveEntryFee
6622
+ if (magpie === true) {
6623
+ const magpieEntryFee = relayPriceFee(entry)
6624
+ effectiveEntryFee = magpieEntryFee === null ? 1 : magpieEntryFee
6625
+ } else {
6626
+ const relayEntryFee = affiliation === 'relay' ? relayPriceFee(entry) : null
6627
+ if (affiliation === 'relay' && relayEntryFee === null && !(debt.feeMultiplier > 1)) { remaining.push(debt); continue }
6628
+ effectiveEntryFee = affiliation === 'relay' && relayEntryFee !== null ? relayEntryFee : 1
6629
+ }
6279
6630
  const cost = (costOfTier(debt.peak, peakPrice) + costOfTier(debt.offPeak, offPeakPrice))
6280
6631
  * debt.feeMultiplier * effectiveEntryFee
6281
6632
  addDayCost(day, debt.model, cost)
@@ -6367,7 +6718,9 @@ async function auditProviderPricingHistory(ledger, book) {
6367
6718
  slot.oldCost += officialCost
6368
6719
  slot.oldCurrency[code] = numOrZero(slot.oldCurrency[code]) + officialCost
6369
6720
  const entryFee = relayPriceFee(entry)
6370
- if (entryFee === null) {
6721
+ /* Magpie 缺倍率默认按 1(与 tokenCost 一致),不当欠账处理。 */
6722
+ const magpieAudit = isMagpieMainUsage(one.provider, one.model)
6723
+ if (entryFee === null && magpieAudit !== true) {
6371
6724
  slot.debts.push({ provider: one.provider, model: one.model, parts: one.parts, peakTime: isPeakTime(one.time) })
6372
6725
  } else {
6373
6726
  const newCost = tokenCost(one.model, one.time, one.parts, one.provider, 1, auditBook)
@@ -6734,8 +7087,12 @@ async function collectFileIntoLedger(ledger, file, text, fromMs, rebuilding) {
6734
7087
  v4 重算那一轮的钱由重建通道独立算出并在末尾覆盖,这里不吃双份。 */
6735
7088
  const affiliation = providerAffiliation(one.provider, one.model)
6736
7089
  const entry = priceEntryFor(one.model)
7090
+ /* Magpie 归属(provider 含 magpie / 模型 remote-magpie/、magpie/)即使价格条目没配倍率也
7091
+ 视为「有价」(tokenCost 对 Magpie 缺倍率默认按 1 折),绝不能挂成欠账 —— 否则主会话
7092
+ 走 Magpie 的调用会一直不计费,与子代理 Magpie 路径口径不一致。通用 relay 不变。 */
7093
+ const magpie = isMagpieMainUsage(one.provider, one.model)
6737
7094
  const relayFee = affiliation === "relay" && entry !== null ? relayPriceFee(entry) : null
6738
- const priced = entry !== null && (affiliation !== "relay" || relayFee !== null)
7095
+ const priced = entry !== null && (affiliation !== "relay" || relayFee !== null || magpie === true)
6739
7096
  if (priced !== true) {
6740
7097
  /* relay 没配倍率:记 provider/model 欠账(feeMultiplier 记 1),绝不按官方价结算。 */
6741
7098
  addUnpricedByProvider(day, one.provider, one.model, one.parts, peakTime, affiliation === "relay" ? 1 : one.feeMultiplier)
@@ -7549,15 +7906,11 @@ async function updateRelayConfig(ctx, body) {
7549
7906
  const service = relayCredentials(ctx)
7550
7907
  if (service === null) throw new Error('credential-unavailable')
7551
7908
  const ref = relaySecretRef(channelKey)
7552
- await service.resolve(ref)
7553
- const next = { version: RELAY_CONFIG_VERSION, channels }
7554
- writeRelayConfig(next)
7555
- try {
7556
- await service.unset(ref)
7557
- } catch (error) {
7558
- try { writeRelayConfig(current) } catch (nested) { /* preserve the original failure */ }
7559
- throw error
7560
- }
7909
+ /* 先清掉该 channel 的 credential envelope,成功后再删配置:unset 失败就不动配置、
7910
+ 直接抛出(路由返回 500),绝不假装已删除 —— 否则同名重建会继承残留 token/userId。 */
7911
+ await service.unset(ref)
7912
+ relayDiscoveryFailures.delete(channelKey)
7913
+ writeRelayConfig({ version: RELAY_CONFIG_VERSION, channels })
7561
7914
  } else {
7562
7915
  writeRelayConfig({ version: RELAY_CONFIG_VERSION, channels })
7563
7916
  }
@@ -7568,7 +7921,7 @@ async function updateRelayConfig(ctx, body) {
7568
7921
  ? new Set(['channelKey', 'feeMultiplier', 'remove'])
7569
7922
  : new Set([
7570
7923
  'channelKey', 'endpoint', 'tokenHeader', 'userIdHeader', 'tokenPrefix',
7571
- 'balancePath', 'currency', 'feeMultiplier', 'balanceDivisor', 'token', 'userId', 'headers', 'remove',
7924
+ 'balancePath', 'currency', 'feeMultiplier', 'balanceDivisor', 'balanceKind', 'token', 'userId', 'headers', 'remove',
7572
7925
  ])
7573
7926
  if (Object.keys(body).some((key) => !allowed.has(key))) return invalid
7574
7927
 
@@ -7584,7 +7937,11 @@ async function updateRelayConfig(ctx, body) {
7584
7937
  return { status: 200, body: await relayConfigView(ctx, channels) }
7585
7938
  }
7586
7939
 
7587
- const previousSecrets = await resolveRelaySecrets(ctx, channelKey)
7940
+ /* 新建(含删除后同名重建)不得继承任何“上一份”凭据:credentials.resolve 可能回退到
7941
+ env/.env 的 ambient 值,沿用会把别人的令牌写进新平台。仅已有平台才继承其已存 envelope。 */
7942
+ const previousSecrets = existing === null
7943
+ ? { token: '', userId: '', headers: {} }
7944
+ : await resolveRelaySecrets(ctx, channelKey)
7588
7945
  if (previousSecrets === null) throw new Error('credential-unavailable')
7589
7946
  let token = previousSecrets.token
7590
7947
  if (body.token !== undefined) {
@@ -7603,7 +7960,12 @@ async function updateRelayConfig(ctx, body) {
7603
7960
  headers = sanitizeRelayHeaders(body.headers)
7604
7961
  if (headers === null) return invalid
7605
7962
  }
7606
- const settings = relaySettings(body, existing, Object.keys(headers))
7963
+ /* 地址为空就保持空:平台可能晚点再自动探测余额端点(见 queryBalance),
7964
+ 绝不能因为地址没填就把已填的 token / userId / 其它字段清掉。 */
7965
+ const effectiveBody = body.endpoint === undefined
7966
+ ? Object.assign({}, body, { endpoint: existing === null ? '' : existing.endpoint })
7967
+ : body
7968
+ const settings = relaySettings(effectiveBody, existing, Object.keys(headers))
7607
7969
  if (settings === null) return invalid
7608
7970
  const channels = current.channels.slice()
7609
7971
  const index = channels.findIndex((channel) => channel.channelKey === channelKey)
@@ -7613,6 +7975,7 @@ async function updateRelayConfig(ctx, body) {
7613
7975
  writeRelayConfig(next)
7614
7976
  try {
7615
7977
  await storeRelaySecrets(ctx, channelKey, { token, userId, headers })
7978
+ relayDiscoveryFailures.delete(channelKey)
7616
7979
  } catch (error) {
7617
7980
  try { writeRelayConfig(current) } catch (nested) { /* preserve the original failure */ }
7618
7981
  throw error