dsh-desktop-statusbar 3.0.5 → 3.0.6
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/client.js +513 -156
- package/lib/index.js +401 -83
- package/package.json +1 -1
- package/tests/helpers/client-harness.js +86 -0
- package/tests/verify-balance.js +55 -1
- package/tests/verify-copy.js +6 -2
- package/tests/verify-generic-relay.js +405 -6
- package/tests/verify-magpie-quota.mjs +24 -1
- package/tests/verify-modelrow-scroll.js +669 -0
- package/tests/verify-provider-fees.js +65 -0
- package/tests/verify-relay-settings.js +1166 -115
- package/tests/verify.js +23 -8
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
|
-
|
|
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
|
-
|
|
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
|
-
/**
|
|
2841
|
-
function
|
|
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
|
-
*
|
|
2856
|
-
*
|
|
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
|
|
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
|
-
|
|
2869
|
-
|
|
2870
|
-
if (amount === null
|
|
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,
|
|
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:
|
|
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
|
|
3116
|
-
if (
|
|
3117
|
-
|
|
3118
|
-
|
|
3119
|
-
|
|
3120
|
-
|
|
3121
|
-
|
|
3122
|
-
|
|
3123
|
-
|
|
3124
|
-
|
|
3125
|
-
|
|
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
|
-
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
|
|
3140
|
-
|
|
3141
|
-
|
|
3142
|
-
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
|
|
3146
|
-
|
|
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
|
-
|
|
3309
|
-
|
|
3310
|
-
|
|
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
|
-
|
|
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 为空时**绝不按模型名猜厂商**:
|
|
@@ -4125,6 +4395,39 @@ function tokenCost(model, at, parts, provider, feeMultiplier, book) {
|
|
|
4125
4395
|
* channelMultiplier * entryFee
|
|
4126
4396
|
}
|
|
4127
4397
|
|
|
4398
|
+
/** Magpie 子代理用量是否按「Magpie 模型价」计价:provider 含 magpie,或模型走 remote-magpie/ 命名空间。 */
|
|
4399
|
+
function isMagpieSubagentUsage(provider, model) {
|
|
4400
|
+
if (typeof provider === 'string' && provider.length > 0 && relayIsMagpie(provider) === true) return true
|
|
4401
|
+
return typeof model === 'string' && /^(?:remote-magpie|magpie)\//i.test(model) === true
|
|
4402
|
+
}
|
|
4403
|
+
|
|
4404
|
+
/**
|
|
4405
|
+
* Magpie 通道倍率:先按 channelKey 精确匹配;provider 大小写/别名对不上(magpie vs Magpie)时,
|
|
4406
|
+
* 退回配置里唯一的 Magpie 通道(readRelayConfig 保证最多一个)。缺省 1。
|
|
4407
|
+
*/
|
|
4408
|
+
function magpieChannelMultiplier(provider) {
|
|
4409
|
+
const config = relayFeeConfig()
|
|
4410
|
+
if (config === null) return 1
|
|
4411
|
+
const providerText = typeof provider === 'string' ? provider : ''
|
|
4412
|
+
const exact = config.channels.find((one) => one.channelKey === providerText)
|
|
4413
|
+
if (exact !== undefined && relayFeeMultiplierValid(exact.feeMultiplier)) return exact.feeMultiplier
|
|
4414
|
+
const magpie = config.channels.find((one) => relayIsMagpie(one.channelKey))
|
|
4415
|
+
return magpie !== undefined && relayFeeMultiplierValid(magpie.feeMultiplier) ? magpie.feeMultiplier : 1
|
|
4416
|
+
}
|
|
4417
|
+
|
|
4418
|
+
/**
|
|
4419
|
+
* Magpie 子代理费用:实际模型价(officialTokenCost)× Magpie 通道倍率 × 价格条目倍率。
|
|
4420
|
+
* 缺 Magpie 通道倍率 / 价格条目倍率时都默认 1 —— 不像通用 relay 那样缺 feeConfigured 就记 0 欠账
|
|
4421
|
+
* (用户规则:Magpie 是本机聚合网关,不套用自建通用 relay 的「缺倍率不计价」门槛)。
|
|
4422
|
+
* 只被子代理用量聚合调用,主会话与普通 relay 行为不变。
|
|
4423
|
+
*/
|
|
4424
|
+
function magpieSubagentTokenCost(model, at, parts, provider) {
|
|
4425
|
+
const entry = priceEntryFor(model)
|
|
4426
|
+
const entryFeeRaw = entry === null ? null : relayPriceFee(entry)
|
|
4427
|
+
const entryFee = entryFeeRaw === null ? 1 : entryFeeRaw
|
|
4428
|
+
return officialTokenCost(model, at, parts) * magpieChannelMultiplier(provider) * entryFee
|
|
4429
|
+
}
|
|
4430
|
+
|
|
4128
4431
|
/**
|
|
4129
4432
|
* 这个模型的条目是按哪种货币填的(`CNY` / `USD`,缺省 `CNY`)。
|
|
4130
4433
|
*
|
|
@@ -5339,8 +5642,15 @@ export {
|
|
|
5339
5642
|
queryBalance as queryBalanceForTest,
|
|
5340
5643
|
/* 通用中转站余额:测试直接驱动纯解析、settings 服务发现与本地 mock fetch。 */
|
|
5341
5644
|
providerConfigFromSettings,
|
|
5645
|
+
/* relaySettings 合并逻辑(仅测试:验证改地址/解析字段清 balanceKind、无关更新保留)。 */
|
|
5646
|
+
relaySettings as relaySettingsForTest,
|
|
5342
5647
|
parseGenericRelayBalance,
|
|
5343
5648
|
queryGenericRelayBalance,
|
|
5649
|
+
/* 空地址探测的冷却表与指纹(仅测试:验证同长度不同凭据不共享冷却、Map 容量上限)。 */
|
|
5650
|
+
relayDiscoveryFailures as relayDiscoveryFailuresForTest,
|
|
5651
|
+
recordRelayDiscoveryFailure,
|
|
5652
|
+
discoveryFingerprint,
|
|
5653
|
+
RELAY_DISCOVERY_FAILURES_MAX,
|
|
5344
5654
|
/* relay-balance-config GET 的来源校验纯函数(仅回环),供 verify-host 直接驱动。 */
|
|
5345
5655
|
isLocalRequestHost as isLocalRequestHostForTest,
|
|
5346
5656
|
isLocalOriginHeader as isLocalOriginHeaderForTest,
|
|
@@ -5616,8 +5926,10 @@ function usageAggOfEntry(entry, fromMs) {
|
|
|
5616
5926
|
agg.tokens.output += parts.output
|
|
5617
5927
|
/* 一次 usage 事件 = 一次调用(pickUsageEvents 已按 turn/step 去过重、全 0 的不算) */
|
|
5618
5928
|
agg.calls += 1
|
|
5619
|
-
|
|
5620
|
-
const amount =
|
|
5929
|
+
/* 子代理用量聚合的 Magpie 分支:按实际模型价计,缺倍率默认 1;其余走原 tokenCost(普通 relay 缺倍率仍记 0)。 */
|
|
5930
|
+
const amount = isMagpieSubagentUsage(event.provider, event.model) === true
|
|
5931
|
+
? magpieSubagentTokenCost(event.model, event.time, parts, event.provider)
|
|
5932
|
+
: tokenCost(event.model, event.time, parts, event.provider, relayFeeMultiplierForProvider(event.provider))
|
|
5621
5933
|
agg.cost += amount
|
|
5622
5934
|
/* 同一笔同时按"模型条目的币种"分桶:客户端混币时要折成一个数字(见 tokenCostCurrency) */
|
|
5623
5935
|
const code = tokenCostCurrency(event.model)
|
|
@@ -7549,15 +7861,11 @@ async function updateRelayConfig(ctx, body) {
|
|
|
7549
7861
|
const service = relayCredentials(ctx)
|
|
7550
7862
|
if (service === null) throw new Error('credential-unavailable')
|
|
7551
7863
|
const ref = relaySecretRef(channelKey)
|
|
7552
|
-
|
|
7553
|
-
|
|
7554
|
-
|
|
7555
|
-
|
|
7556
|
-
|
|
7557
|
-
} catch (error) {
|
|
7558
|
-
try { writeRelayConfig(current) } catch (nested) { /* preserve the original failure */ }
|
|
7559
|
-
throw error
|
|
7560
|
-
}
|
|
7864
|
+
/* 先清掉该 channel 的 credential envelope,成功后再删配置:unset 失败就不动配置、
|
|
7865
|
+
直接抛出(路由返回 500),绝不假装已删除 —— 否则同名重建会继承残留 token/userId。 */
|
|
7866
|
+
await service.unset(ref)
|
|
7867
|
+
relayDiscoveryFailures.delete(channelKey)
|
|
7868
|
+
writeRelayConfig({ version: RELAY_CONFIG_VERSION, channels })
|
|
7561
7869
|
} else {
|
|
7562
7870
|
writeRelayConfig({ version: RELAY_CONFIG_VERSION, channels })
|
|
7563
7871
|
}
|
|
@@ -7568,7 +7876,7 @@ async function updateRelayConfig(ctx, body) {
|
|
|
7568
7876
|
? new Set(['channelKey', 'feeMultiplier', 'remove'])
|
|
7569
7877
|
: new Set([
|
|
7570
7878
|
'channelKey', 'endpoint', 'tokenHeader', 'userIdHeader', 'tokenPrefix',
|
|
7571
|
-
'balancePath', 'currency', 'feeMultiplier', 'balanceDivisor', 'token', 'userId', 'headers', 'remove',
|
|
7879
|
+
'balancePath', 'currency', 'feeMultiplier', 'balanceDivisor', 'balanceKind', 'token', 'userId', 'headers', 'remove',
|
|
7572
7880
|
])
|
|
7573
7881
|
if (Object.keys(body).some((key) => !allowed.has(key))) return invalid
|
|
7574
7882
|
|
|
@@ -7584,7 +7892,11 @@ async function updateRelayConfig(ctx, body) {
|
|
|
7584
7892
|
return { status: 200, body: await relayConfigView(ctx, channels) }
|
|
7585
7893
|
}
|
|
7586
7894
|
|
|
7587
|
-
|
|
7895
|
+
/* 新建(含删除后同名重建)不得继承任何“上一份”凭据:credentials.resolve 可能回退到
|
|
7896
|
+
env/.env 的 ambient 值,沿用会把别人的令牌写进新平台。仅已有平台才继承其已存 envelope。 */
|
|
7897
|
+
const previousSecrets = existing === null
|
|
7898
|
+
? { token: '', userId: '', headers: {} }
|
|
7899
|
+
: await resolveRelaySecrets(ctx, channelKey)
|
|
7588
7900
|
if (previousSecrets === null) throw new Error('credential-unavailable')
|
|
7589
7901
|
let token = previousSecrets.token
|
|
7590
7902
|
if (body.token !== undefined) {
|
|
@@ -7603,7 +7915,12 @@ async function updateRelayConfig(ctx, body) {
|
|
|
7603
7915
|
headers = sanitizeRelayHeaders(body.headers)
|
|
7604
7916
|
if (headers === null) return invalid
|
|
7605
7917
|
}
|
|
7606
|
-
|
|
7918
|
+
/* 地址为空就保持空:平台可能晚点再自动探测余额端点(见 queryBalance),
|
|
7919
|
+
绝不能因为地址没填就把已填的 token / userId / 其它字段清掉。 */
|
|
7920
|
+
const effectiveBody = body.endpoint === undefined
|
|
7921
|
+
? Object.assign({}, body, { endpoint: existing === null ? '' : existing.endpoint })
|
|
7922
|
+
: body
|
|
7923
|
+
const settings = relaySettings(effectiveBody, existing, Object.keys(headers))
|
|
7607
7924
|
if (settings === null) return invalid
|
|
7608
7925
|
const channels = current.channels.slice()
|
|
7609
7926
|
const index = channels.findIndex((channel) => channel.channelKey === channelKey)
|
|
@@ -7613,6 +7930,7 @@ async function updateRelayConfig(ctx, body) {
|
|
|
7613
7930
|
writeRelayConfig(next)
|
|
7614
7931
|
try {
|
|
7615
7932
|
await storeRelaySecrets(ctx, channelKey, { token, userId, headers })
|
|
7933
|
+
relayDiscoveryFailures.delete(channelKey)
|
|
7616
7934
|
} catch (error) {
|
|
7617
7935
|
try { writeRelayConfig(current) } catch (nested) { /* preserve the original failure */ }
|
|
7618
7936
|
throw error
|