dsh-plugin-weapp-gateway 0.8.23 → 0.8.34
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/LICENSE +21 -21
- package/PROTOCOL.md +1545 -1486
- package/README.md +503 -464
- package/THIRD-PARTY-NOTICES/dsh-cost-meter.txt +31 -31
- package/bin/setup-ip.mjs +474 -474
- package/cordis.patch.yml +50 -50
- package/docs/agent-team-app-integration.md +945 -0
- package/docs/blog-mobile-gateway.md +542 -542
- package/docs/dsh-0.1.5-rc.2-compatibility-audit.md +255 -255
- package/docs/dsh-0.1.6-alpha.1-compatibility-audit.md +122 -122
- package/docs/dsh-0.1.7-rc.1-compatibility-audit.md +52 -52
- package/docs/dsh-0.2.0-rc.2-plugin-management-mobile-integration.md +109 -109
- package/docs/dsh-rc2-mobile-integration.md +155 -155
- package/docs/file-upload-app-integration.md +250 -0
- package/docs/multi-gateway-app-integration.md +141 -125
- package/docs/multi-gateway-phase1-acceptance.md +179 -179
- package/docs/multi-gateway-todo.md +137 -137
- package/docs/remote-gateway-refactor-plan.md +52 -52
- package/docs/runtime-architecture.architecture.json +264 -264
- package/docs/runtime-architecture.html +15001 -15001
- package/docs/runtime-architecture.visual-check.html +32 -32
- package/docs/runtime-architecture.visual-check.json +548 -548
- package/docs/session-agent-preset-app-integration.md +93 -93
- package/docs/turn-outline-app-integration.md +196 -0
- package/docs/typert-remote-gateway-feature-checklist.md +294 -294
- package/docs/voice-input-implementation.md +219 -219
- package/docs/workspace-changes-mobile-integration.md +32 -32
- package/helper/dsh_mobile_gateway_helper.py +227 -227
- package/lib/account-bridge.mjs +57 -57
- package/lib/client.js +1409 -1361
- package/lib/cloudflare-tunnel.mjs +314 -314
- package/lib/cloudflared-binary.mjs +135 -135
- package/lib/context-bridge.mjs +3338 -1715
- package/lib/cost-meter-bridge.mjs +794 -794
- package/lib/cost-meter-dashboard-bridge.mjs +1655 -1449
- package/lib/devices.js +273 -245
- package/lib/dsh-host-adapter.mjs +508 -426
- package/lib/file-upload.mjs +205 -0
- package/lib/gateway-probe.mjs +6 -6
- package/lib/gateway-state.mjs +57 -57
- package/lib/gateway-tools.mjs +36 -36
- package/lib/history-cache.mjs +66 -0
- package/lib/index.mjs +4390 -3803
- package/lib/plugin-management.mjs +251 -233
- package/lib/public-endpoint-check.mjs +61 -61
- package/lib/relay-connector.mjs +213 -181
- package/lib/relay-state.mjs +83 -76
- package/lib/session-follower.mjs +140 -136
- package/lib/session-resume-bridge.mjs +86 -0
- package/lib/session-target.mjs +29 -0
- package/lib/speech-input.mjs +192 -192
- package/lib/vendor/cost-meter/aliyun-balance.mjs +123 -123
- package/lib/vendor/cost-meter/coding-plans.mjs +1668 -1668
- package/lib/vendor/cost-meter/credentials-shim.mjs +8 -8
- package/lib/vendor/cost-meter/custom-balance.mjs +281 -281
- package/lib/vendor/cost-meter/factory-quota.mjs +69 -69
- package/lib/vendor/cost-meter/gateway-quota-adapters.mjs +1006 -1006
- package/lib/vendor/cost-meter/gateway-quotas.mjs +664 -664
- package/lib/vendor/cost-meter/home-paths-shim.mjs +13 -13
- package/lib/vendor/cost-meter/net.mjs +183 -183
- package/lib/vendor/cost-meter/opendesign.mjs +204 -204
- package/lib/vendor/cost-meter/tokenrhythm-balance.mjs +95 -95
- package/lib/vendor/cost-meter/workbuddy-accounts.mjs +44 -44
- package/lib/vendor/cost-meter/workbuddy-transport.mjs +38 -38
- package/lib/vendor/cost-meter/workbuddy.mjs +356 -356
- package/lib/web-restart.mjs +47 -47
- package/lib/wire-json.mjs +7 -7
- package/lib/workspace-changes-bridge.mjs +32 -32
- package/package.json +54 -54
- package/relay/agent-connector.js +588 -569
- package/relay/vendor/tweetnacl.js +2391 -2391
|
@@ -1,204 +1,204 @@
|
|
|
1
|
-
/** OpenDesign public list prices and workspace-scoped, read-only billing queries. */
|
|
2
|
-
import { fetchWithRetry, readJsonBounded } from './net.mjs'
|
|
3
|
-
|
|
4
|
-
export const OPENDESIGN_API = 'https://amr-api.open-design.ai/api/v1'
|
|
5
|
-
export const OPENDESIGN_PRICES_URL = OPENDESIGN_API + '/public/model-prices'
|
|
6
|
-
export const OPENDESIGN_PROVIDER_IDS = ['opendesign', 'open-design', 'open-design-api', 'amr-link.open-design.ai']
|
|
7
|
-
/** Machine-readable query failure codes so callers/logs can distinguish causes without parsing text. */
|
|
8
|
-
export const OPEN_DESIGN_QUOTA_FAILURES = Object.freeze({
|
|
9
|
-
invalidRequest: 'invalid_request',
|
|
10
|
-
unauthorized: 'unauthorized',
|
|
11
|
-
http: 'http_error',
|
|
12
|
-
noSubscription: 'no_subscription',
|
|
13
|
-
invalidResponse: 'invalid_response',
|
|
14
|
-
network: 'network_error',
|
|
15
|
-
identityMismatch: 'identity_mismatch',
|
|
16
|
-
})
|
|
17
|
-
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
18
|
-
const rate = value => typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1e6
|
|
19
|
-
const id = value => typeof value === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(value)
|
|
20
|
-
const queryError = (message, soft = false, code) => Object.assign(new Error(message), { opendesignPublic: true, ...(code === undefined ? {} : { code }), ...(soft ? { soft: true } : {}) })
|
|
21
|
-
/** Issue #274: `billing/preflight` wraps the same member identity under `codingPlan` when present. */
|
|
22
|
-
const quotaMemberOf = value => object(value)
|
|
23
|
-
? value.workspaceMemberId ?? (object(value.codingPlan) ? value.codingPlan.workspaceMemberId : undefined)
|
|
24
|
-
: undefined
|
|
25
|
-
/** Preflight also reports balanceUsd; it is only a fallback when the wallet endpoint fails. */
|
|
26
|
-
const balanceWindowOf = value => {
|
|
27
|
-
const raw = object(value) ? value.balanceUsd : undefined
|
|
28
|
-
const text = typeof raw === 'string' ? raw : typeof raw === 'number' && Number.isFinite(raw) ? String(raw) : ''
|
|
29
|
-
return /^-?\d{1,12}(?:\.\d{1,12})?$/.test(text) ? { text: '$' + text, resetsAt: '' } : null
|
|
30
|
-
}
|
|
31
|
-
export function normalizeOpenDesignWorkspace(value) {
|
|
32
|
-
if (value === undefined || value === '') return ''
|
|
33
|
-
return typeof value === 'string' && id(value.trim()) ? value.trim() : null
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/** The public API explicitly uses USD per million tokens; never apply a 1M conversion twice. */
|
|
37
|
-
export function parseOpenDesignPrices(value, checkedAt = new Date().toISOString().slice(0, 10)) {
|
|
38
|
-
if (!object(value) || !Array.isArray(value.data) || value.data.length > 10000) throw Error('OpenDesign: invalid public price catalog')
|
|
39
|
-
const models = Object.create(null)
|
|
40
|
-
const tier = raw => {
|
|
41
|
-
if (!object(raw) || !rate(raw.input) || !rate(raw.output)) return null
|
|
42
|
-
if (['cacheRead', 'cacheWrite'].some(key => raw[key] !== undefined && !rate(raw[key]))) return null
|
|
43
|
-
return { cacheMiss: raw.input, output: raw.output,
|
|
44
|
-
...(raw.cacheRead !== undefined ? { cacheHit: raw.cacheRead } : {}), ...(raw.cacheWrite !== undefined ? { cacheWrite: raw.cacheWrite } : {}) }
|
|
45
|
-
}
|
|
46
|
-
for (const row of value.data) {
|
|
47
|
-
if (!object(row) || typeof row.model !== 'string' || !/^[\w./:@+-]{1,200}$/.test(row.model) || ['__proto__', 'constructor', 'prototype'].includes(row.model)) throw Error('OpenDesign: invalid model id')
|
|
48
|
-
if (Object.hasOwn(models, row.model)) throw Error('OpenDesign: duplicate model price')
|
|
49
|
-
if (row.pricing?.unit !== '1m_tokens' || row.pricing?.currency !== 'USD') throw Error('OpenDesign: unsupported pricing unit or currency')
|
|
50
|
-
const price = tier(row.pricing)
|
|
51
|
-
if (!price) throw Error('OpenDesign: invalid token price')
|
|
52
|
-
if (row.pricing.longContext !== undefined) {
|
|
53
|
-
const raw = row.pricing.longContext, long = tier(raw)
|
|
54
|
-
if (!long || !Number.isSafeInteger(raw.inputTokensAbove) || raw.inputTokensAbove <= 0) throw Error('OpenDesign: invalid long-context price')
|
|
55
|
-
price.longContext = { aboveInputTokens: raw.inputTokensAbove, ...long }
|
|
56
|
-
}
|
|
57
|
-
models[row.model] = { ...price, billingMode: 'flat', sourceUrl: OPENDESIGN_PRICES_URL, checkedAt }
|
|
58
|
-
}
|
|
59
|
-
if (!Object.keys(models).length) throw Error('OpenDesign: empty public price catalog')
|
|
60
|
-
return { models }
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/** Each quota window is an independent simultaneous limit, not an additive balance. */
|
|
64
|
-
export function parseOpenDesignUsage(value, workspaceId) {
|
|
65
|
-
// Issue #274: the `billing/preflight` form wraps the identical window payload in `codingPlan`.
|
|
66
|
-
if (object(value) && object(value.codingPlan)) {
|
|
67
|
-
if ([value.workspaceId, value.codingPlan.workspaceId].some(id => id !== undefined && id !== workspaceId)
|
|
68
|
-
|| value.workspaceMemberId !== undefined && value.codingPlan.workspaceMemberId !== undefined && value.workspaceMemberId !== value.codingPlan.workspaceMemberId) return null
|
|
69
|
-
value = { ...value, ...value.codingPlan, workspaceMemberId: value.workspaceMemberId ?? value.codingPlan.workspaceMemberId }
|
|
70
|
-
}
|
|
71
|
-
if (!object(value) || value.workspaceId !== workspaceId || value.workspaceMemberId !== undefined && !id(value.workspaceMemberId) || typeof value.eligible !== 'boolean'
|
|
72
|
-
|| !Array.isArray(value.windows) || value.windows.length > 32) return null
|
|
73
|
-
const windows = {}, seen = new Set()
|
|
74
|
-
for (const row of value.windows) {
|
|
75
|
-
if (!object(row) || typeof row.policyId !== 'string' || !row.policyId || seen.has(row.policyId)
|
|
76
|
-
|| !Number.isSafeInteger(row.durationSeconds) || row.durationSeconds <= 0
|
|
77
|
-
|| !['usedCredits', 'remainingCredits', 'limitCredits'].every(key => typeof row[key] === 'string' && /^\d{1,80}$/.test(row[key]))) return null
|
|
78
|
-
seen.add(row.policyId)
|
|
79
|
-
const used = BigInt(row.usedCredits), remaining = BigInt(row.remainingCredits), limit = BigInt(row.limitCredits)
|
|
80
|
-
if (limit <= 0n || remaining > limit || remaining !== (used >= limit ? 0n : limit - used)) return null
|
|
81
|
-
const resetsAt = row.resetsAt == null ? '' : typeof row.resetsAt === 'string' && Number.isFinite(Date.parse(row.resetsAt)) ? new Date(row.resetsAt).toISOString() : null
|
|
82
|
-
if (resetsAt === null) return null
|
|
83
|
-
// Identify the window by its duration, keeping usage and reset time on that same row.
|
|
84
|
-
const duration = row.durationSeconds, base = duration === 5 * 60 * 60 ? 'fiveHour' : duration === 7 * 24 * 60 * 60 ? 'weekly' : 'window_' + duration + 's'
|
|
85
|
-
const key = Object.hasOwn(windows, base) ? base + '_' + seen.size : base
|
|
86
|
-
windows[key] = { percent: Number((used > limit ? limit : used) * 100000n / limit) / 1000, resetsAt }
|
|
87
|
-
}
|
|
88
|
-
if (value.eligible && !Object.keys(windows).length) return null
|
|
89
|
-
if (!value.eligible && value.windows.length) return null
|
|
90
|
-
return windows
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
export function parseOpenDesignWallet(value, workspaceId) {
|
|
94
|
-
if (!object(value) || value.billingScopeVersion !== 2 || value.workspaceId !== workspaceId || !id(value.workspaceMemberId)
|
|
95
|
-
|| typeof value.balanceUsd !== 'string' || !/^-?\d{1,12}(?:\.\d{1,12})?$/.test(value.balanceUsd)) return null
|
|
96
|
-
return { text: '$' + value.balanceUsd, resetsAt: '' }
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
export async function queryOpenDesignQuota(key, locale, t, { workspaceId, signal, fetchImpl } = {}) {
|
|
100
|
-
const zh = locale === 'zh', workspace = normalizeOpenDesignWorkspace(workspaceId)
|
|
101
|
-
if (!workspace) throw queryError(zh ? 'OpenDesign:请先填写工作区 ID。' : 'OpenDesign: configure a workspace ID first.', true, OPEN_DESIGN_QUOTA_FAILURES.invalidRequest)
|
|
102
|
-
if (typeof key !== 'string' || !key.trim()) throw queryError(zh
|
|
103
|
-
? 'OpenDesign:额度查询需要 Control Key(OPENDESIGN_CONTROL_KEY / VELA_CONTROL_KEY),不能使用推理 API Key。'
|
|
104
|
-
: 'OpenDesign: quota queries require a Control Key (OPENDESIGN_CONTROL_KEY / VELA_CONTROL_KEY), not an inference API key.', true, OPEN_DESIGN_QUOTA_FAILURES.invalidRequest)
|
|
105
|
-
const controller = new AbortController(), combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal
|
|
106
|
-
const timer = setTimeout(() => controller.abort(), 15000); timer.unref?.()
|
|
107
|
-
const prefix = OPENDESIGN_API + '/workspaces/' + encodeURIComponent(workspace)
|
|
108
|
-
// The preflight and wallet routes accept a Control Key without a browser cookie.
|
|
109
|
-
// Read both sides independently and only fail
|
|
110
|
-
// when both fail; a single 401 must never discard the other side's valid answer.
|
|
111
|
-
const read = async (path, side) => {
|
|
112
|
-
const url = prefix + path
|
|
113
|
-
let response
|
|
114
|
-
try {
|
|
115
|
-
response = await fetchWithRetry(url, { method: 'GET', redirect: 'error', signal: combined,
|
|
116
|
-
headers: { accept: 'application/json', authorization: 'Bearer ' + key.trim(), 'x-vela-workspace-id': workspace } }, { attempts: 2, fetchImpl })
|
|
117
|
-
} catch (error) {
|
|
118
|
-
if (combined.aborted) throw error // caller cancellation / 15 s deadline must not degrade to a partial card
|
|
119
|
-
return { ok: false, side, kind: OPEN_DESIGN_QUOTA_FAILURES.network, url }
|
|
120
|
-
}
|
|
121
|
-
if (!response.ok) {
|
|
122
|
-
try { await response.body?.cancel?.() } catch {}
|
|
123
|
-
const unauthorized = response.status === 401 || response.status === 403
|
|
124
|
-
return { ok: false, side, kind: unauthorized ? OPEN_DESIGN_QUOTA_FAILURES.unauthorized : OPEN_DESIGN_QUOTA_FAILURES.http, status: response.status, url }
|
|
125
|
-
}
|
|
126
|
-
try { return { ok: true, side, value: await readJsonBounded(response, 256 * 1024), url } }
|
|
127
|
-
catch (error) {
|
|
128
|
-
if (combined.aborted) throw error
|
|
129
|
-
return { ok: false, side, kind: OPEN_DESIGN_QUOTA_FAILURES.invalidResponse, source: 'body', url }
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
const describe = failure => {
|
|
133
|
-
if (failure.kind === OPEN_DESIGN_QUOTA_FAILURES.unauthorized) return queryError(t(locale, 'codingPlanUnauthorized', { provider: 'OpenDesign', code: String(failure.status) }), true, failure.kind)
|
|
134
|
-
if (failure.kind === OPEN_DESIGN_QUOTA_FAILURES.http) return queryError(t(locale, 'codingPlanHttp', { provider: 'OpenDesign', code: String(failure.status), url: failure.url }), false, failure.kind)
|
|
135
|
-
if (failure.kind === OPEN_DESIGN_QUOTA_FAILURES.invalidResponse && failure.source === 'body') return queryError(t(locale, 'codingPlanInvalidJson', { provider: 'OpenDesign', url: failure.url }), false, failure.kind)
|
|
136
|
-
if (failure.kind === OPEN_DESIGN_QUOTA_FAILURES.invalidResponse) return queryError(failure.side === 'wallet'
|
|
137
|
-
? (zh ? 'OpenDesign:钱包响应的工作区、成员或数据无效。' : 'OpenDesign: invalid wallet response or workspace/member identity.')
|
|
138
|
-
: (zh ? 'OpenDesign:额度响应的工作区、成员或数据无效。' : 'OpenDesign: invalid quota response or workspace/member identity.'), false, failure.kind)
|
|
139
|
-
if (failure.kind === OPEN_DESIGN_QUOTA_FAILURES.noSubscription) {
|
|
140
|
-
const code = 'codingPlanNoSubscription', text = t(locale, code, { provider: 'OpenDesign' })
|
|
141
|
-
// Fallback keeps "no subscription" distinguishable from "bad credential" until the catalog ships the key.
|
|
142
|
-
return queryError(text === code
|
|
143
|
-
? (zh ? 'OpenDesign:当前账户没有生效的套餐订阅(未订阅或已到期)。' : 'OpenDesign: no active plan subscription was detected for this workspace (not subscribed or expired).')
|
|
144
|
-
: text, true, failure.kind)
|
|
145
|
-
}
|
|
146
|
-
return queryError(zh ? 'OpenDesign:查询失败,请检查控制端凭据、工作区权限和网络。' : 'OpenDesign: query failed; check the control credential, workspace access and connection.', false, failure.kind)
|
|
147
|
-
}
|
|
148
|
-
const partialResult = (windows, endpoint, failures, fallback = false) => ({
|
|
149
|
-
windows, endpoint,
|
|
150
|
-
partial: Object.fromEntries(failures.map(([side, failure]) => [side, failure.kind])),
|
|
151
|
-
message: [
|
|
152
|
-
...(fallback ? [zh ? '钱包余额来自 billing/preflight。' : 'Wallet balance is from billing/preflight.'] : []),
|
|
153
|
-
...failures.map(([side, failure]) => (side === 'usage' ? (zh ? '套餐额度:' : 'Plan quota: ') : (zh ? '钱包端点:' : 'Wallet endpoint: ')) + describe(failure).message),
|
|
154
|
-
].join('\n'),
|
|
155
|
-
})
|
|
156
|
-
try {
|
|
157
|
-
// #274 / #313: do not spend a request on the browser-session-only usage route.
|
|
158
|
-
const [usageRead, walletRead] = await Promise.all([read('/billing/preflight', 'preflight'), read('/wallet/balance', 'wallet')])
|
|
159
|
-
combined.throwIfAborted()
|
|
160
|
-
// The preflight answer is already scoped by URL and x-vela-workspace-id; tolerate a body that
|
|
161
|
-
// omits the redundant workspaceId, but never accept one that names a different workspace.
|
|
162
|
-
const preflight = usageRead.ok && usageRead.side === 'preflight'
|
|
163
|
-
const identifiesOtherWorkspace = value => object(value) && value.workspaceId !== undefined && value.workspaceId !== workspace
|
|
164
|
-
const usageWorkspaceConflict = preflight && object(usageRead.value)
|
|
165
|
-
&& (identifiesOtherWorkspace(usageRead.value) || identifiesOtherWorkspace(usageRead.value.codingPlan))
|
|
166
|
-
const usagePayload = preflight && object(usageRead.value) && usageRead.value.workspaceId === undefined
|
|
167
|
-
? { ...usageRead.value, workspaceId: workspace } : usageRead.value
|
|
168
|
-
const usageWindows = usageRead.ok && !usageWorkspaceConflict ? parseOpenDesignUsage(usagePayload, workspace) : null
|
|
169
|
-
const usageFailure = !usageRead.ok ? usageRead
|
|
170
|
-
: usageWindows === null ? { ok: false, side: usageRead.side, kind: OPEN_DESIGN_QUOTA_FAILURES.invalidResponse, source: 'shape', url: usageRead.url }
|
|
171
|
-
// The parser returns {} only for eligible:false with no windows: a definitive no-subscription answer.
|
|
172
|
-
: Object.keys(usageWindows).length === 0 ? { ok: false, side: usageRead.side, kind: OPEN_DESIGN_QUOTA_FAILURES.noSubscription } : null
|
|
173
|
-
const balance = walletRead.ok ? parseOpenDesignWallet(walletRead.value, workspace) : null
|
|
174
|
-
const walletFailure = !walletRead.ok ? walletRead
|
|
175
|
-
: balance === null ? { ok: false, side: 'wallet', kind: OPEN_DESIGN_QUOTA_FAILURES.invalidResponse, source: 'shape', url: walletRead.url } : null
|
|
176
|
-
// A preflight answer carries balanceUsd too; it only fills in when the wallet endpoint failed.
|
|
177
|
-
const fallbackBalance = usageWindows !== null && preflight ? balanceWindowOf(usageRead.value) : null
|
|
178
|
-
if (usageWindows !== null && balance !== null) {
|
|
179
|
-
// Only an identity the quota response actually provides must agree with the wallet member.
|
|
180
|
-
const usageMember = quotaMemberOf(usageRead.value)
|
|
181
|
-
if (usageMember !== undefined && walletRead.value.workspaceMemberId !== usageMember) {
|
|
182
|
-
throw queryError(zh ? 'OpenDesign:钱包与额度的工作区成员不一致。' : 'OpenDesign: wallet and quota member identities do not match.', false, OPEN_DESIGN_QUOTA_FAILURES.identityMismatch)
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
if (usageFailure === null && walletFailure === null) return { windows: { ...usageWindows, balance }, endpoint: usageRead.url }
|
|
186
|
-
// Partial degradation (issue #274): keep whichever side answered. `partial` names the failing
|
|
187
|
-
// side and its machine-readable cause; it never replaces the existing windows contract.
|
|
188
|
-
if (usageFailure === null) return partialResult(fallbackBalance === null ? usageWindows : { ...usageWindows, balance: fallbackBalance }, usageRead.url, [['wallet', walletFailure]], fallbackBalance !== null)
|
|
189
|
-
if (walletFailure === null) return partialResult({ balance }, walletRead.url, [['usage', usageFailure]])
|
|
190
|
-
// No subscription is a valid preflight answer too: its readable wallet balance
|
|
191
|
-
// must survive an unavailable wallet route, without inventing any quota windows.
|
|
192
|
-
if (fallbackBalance !== null) return partialResult({ balance: fallbackBalance }, usageRead.url, [['usage', usageFailure], ['wallet', walletFailure]], true)
|
|
193
|
-
// Both failed: report the most actionable cause, preferring a definitive account state
|
|
194
|
-
// (no subscription / rejected credential) over a secondary transport or shape failure.
|
|
195
|
-
const priority = [OPEN_DESIGN_QUOTA_FAILURES.noSubscription, OPEN_DESIGN_QUOTA_FAILURES.unauthorized,
|
|
196
|
-
OPEN_DESIGN_QUOTA_FAILURES.invalidResponse, OPEN_DESIGN_QUOTA_FAILURES.http, OPEN_DESIGN_QUOTA_FAILURES.network]
|
|
197
|
-
throw describe(priority.indexOf(walletFailure.kind) < priority.indexOf(usageFailure.kind) ? walletFailure : usageFailure)
|
|
198
|
-
} catch (error) {
|
|
199
|
-
combined.throwIfAborted()
|
|
200
|
-
// Never put an upstream body, arbitrary network exception or credential in the UI.
|
|
201
|
-
if (error?.opendesignPublic === true) throw error
|
|
202
|
-
throw Error(zh ? 'OpenDesign:查询失败,请检查控制端凭据、工作区权限和网络。' : 'OpenDesign: query failed; check the control credential, workspace access and connection.')
|
|
203
|
-
} finally { clearTimeout(timer) }
|
|
204
|
-
}
|
|
1
|
+
/** OpenDesign public list prices and workspace-scoped, read-only billing queries. */
|
|
2
|
+
import { fetchWithRetry, readJsonBounded } from './net.mjs'
|
|
3
|
+
|
|
4
|
+
export const OPENDESIGN_API = 'https://amr-api.open-design.ai/api/v1'
|
|
5
|
+
export const OPENDESIGN_PRICES_URL = OPENDESIGN_API + '/public/model-prices'
|
|
6
|
+
export const OPENDESIGN_PROVIDER_IDS = ['opendesign', 'open-design', 'open-design-api', 'amr-link.open-design.ai']
|
|
7
|
+
/** Machine-readable query failure codes so callers/logs can distinguish causes without parsing text. */
|
|
8
|
+
export const OPEN_DESIGN_QUOTA_FAILURES = Object.freeze({
|
|
9
|
+
invalidRequest: 'invalid_request',
|
|
10
|
+
unauthorized: 'unauthorized',
|
|
11
|
+
http: 'http_error',
|
|
12
|
+
noSubscription: 'no_subscription',
|
|
13
|
+
invalidResponse: 'invalid_response',
|
|
14
|
+
network: 'network_error',
|
|
15
|
+
identityMismatch: 'identity_mismatch',
|
|
16
|
+
})
|
|
17
|
+
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
18
|
+
const rate = value => typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1e6
|
|
19
|
+
const id = value => typeof value === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(value)
|
|
20
|
+
const queryError = (message, soft = false, code) => Object.assign(new Error(message), { opendesignPublic: true, ...(code === undefined ? {} : { code }), ...(soft ? { soft: true } : {}) })
|
|
21
|
+
/** Issue #274: `billing/preflight` wraps the same member identity under `codingPlan` when present. */
|
|
22
|
+
const quotaMemberOf = value => object(value)
|
|
23
|
+
? value.workspaceMemberId ?? (object(value.codingPlan) ? value.codingPlan.workspaceMemberId : undefined)
|
|
24
|
+
: undefined
|
|
25
|
+
/** Preflight also reports balanceUsd; it is only a fallback when the wallet endpoint fails. */
|
|
26
|
+
const balanceWindowOf = value => {
|
|
27
|
+
const raw = object(value) ? value.balanceUsd : undefined
|
|
28
|
+
const text = typeof raw === 'string' ? raw : typeof raw === 'number' && Number.isFinite(raw) ? String(raw) : ''
|
|
29
|
+
return /^-?\d{1,12}(?:\.\d{1,12})?$/.test(text) ? { text: '$' + text, resetsAt: '' } : null
|
|
30
|
+
}
|
|
31
|
+
export function normalizeOpenDesignWorkspace(value) {
|
|
32
|
+
if (value === undefined || value === '') return ''
|
|
33
|
+
return typeof value === 'string' && id(value.trim()) ? value.trim() : null
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The public API explicitly uses USD per million tokens; never apply a 1M conversion twice. */
|
|
37
|
+
export function parseOpenDesignPrices(value, checkedAt = new Date().toISOString().slice(0, 10)) {
|
|
38
|
+
if (!object(value) || !Array.isArray(value.data) || value.data.length > 10000) throw Error('OpenDesign: invalid public price catalog')
|
|
39
|
+
const models = Object.create(null)
|
|
40
|
+
const tier = raw => {
|
|
41
|
+
if (!object(raw) || !rate(raw.input) || !rate(raw.output)) return null
|
|
42
|
+
if (['cacheRead', 'cacheWrite'].some(key => raw[key] !== undefined && !rate(raw[key]))) return null
|
|
43
|
+
return { cacheMiss: raw.input, output: raw.output,
|
|
44
|
+
...(raw.cacheRead !== undefined ? { cacheHit: raw.cacheRead } : {}), ...(raw.cacheWrite !== undefined ? { cacheWrite: raw.cacheWrite } : {}) }
|
|
45
|
+
}
|
|
46
|
+
for (const row of value.data) {
|
|
47
|
+
if (!object(row) || typeof row.model !== 'string' || !/^[\w./:@+-]{1,200}$/.test(row.model) || ['__proto__', 'constructor', 'prototype'].includes(row.model)) throw Error('OpenDesign: invalid model id')
|
|
48
|
+
if (Object.hasOwn(models, row.model)) throw Error('OpenDesign: duplicate model price')
|
|
49
|
+
if (row.pricing?.unit !== '1m_tokens' || row.pricing?.currency !== 'USD') throw Error('OpenDesign: unsupported pricing unit or currency')
|
|
50
|
+
const price = tier(row.pricing)
|
|
51
|
+
if (!price) throw Error('OpenDesign: invalid token price')
|
|
52
|
+
if (row.pricing.longContext !== undefined) {
|
|
53
|
+
const raw = row.pricing.longContext, long = tier(raw)
|
|
54
|
+
if (!long || !Number.isSafeInteger(raw.inputTokensAbove) || raw.inputTokensAbove <= 0) throw Error('OpenDesign: invalid long-context price')
|
|
55
|
+
price.longContext = { aboveInputTokens: raw.inputTokensAbove, ...long }
|
|
56
|
+
}
|
|
57
|
+
models[row.model] = { ...price, billingMode: 'flat', sourceUrl: OPENDESIGN_PRICES_URL, checkedAt }
|
|
58
|
+
}
|
|
59
|
+
if (!Object.keys(models).length) throw Error('OpenDesign: empty public price catalog')
|
|
60
|
+
return { models }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Each quota window is an independent simultaneous limit, not an additive balance. */
|
|
64
|
+
export function parseOpenDesignUsage(value, workspaceId) {
|
|
65
|
+
// Issue #274: the `billing/preflight` form wraps the identical window payload in `codingPlan`.
|
|
66
|
+
if (object(value) && object(value.codingPlan)) {
|
|
67
|
+
if ([value.workspaceId, value.codingPlan.workspaceId].some(id => id !== undefined && id !== workspaceId)
|
|
68
|
+
|| value.workspaceMemberId !== undefined && value.codingPlan.workspaceMemberId !== undefined && value.workspaceMemberId !== value.codingPlan.workspaceMemberId) return null
|
|
69
|
+
value = { ...value, ...value.codingPlan, workspaceMemberId: value.workspaceMemberId ?? value.codingPlan.workspaceMemberId }
|
|
70
|
+
}
|
|
71
|
+
if (!object(value) || value.workspaceId !== workspaceId || value.workspaceMemberId !== undefined && !id(value.workspaceMemberId) || typeof value.eligible !== 'boolean'
|
|
72
|
+
|| !Array.isArray(value.windows) || value.windows.length > 32) return null
|
|
73
|
+
const windows = {}, seen = new Set()
|
|
74
|
+
for (const row of value.windows) {
|
|
75
|
+
if (!object(row) || typeof row.policyId !== 'string' || !row.policyId || seen.has(row.policyId)
|
|
76
|
+
|| !Number.isSafeInteger(row.durationSeconds) || row.durationSeconds <= 0
|
|
77
|
+
|| !['usedCredits', 'remainingCredits', 'limitCredits'].every(key => typeof row[key] === 'string' && /^\d{1,80}$/.test(row[key]))) return null
|
|
78
|
+
seen.add(row.policyId)
|
|
79
|
+
const used = BigInt(row.usedCredits), remaining = BigInt(row.remainingCredits), limit = BigInt(row.limitCredits)
|
|
80
|
+
if (limit <= 0n || remaining > limit || remaining !== (used >= limit ? 0n : limit - used)) return null
|
|
81
|
+
const resetsAt = row.resetsAt == null ? '' : typeof row.resetsAt === 'string' && Number.isFinite(Date.parse(row.resetsAt)) ? new Date(row.resetsAt).toISOString() : null
|
|
82
|
+
if (resetsAt === null) return null
|
|
83
|
+
// Identify the window by its duration, keeping usage and reset time on that same row.
|
|
84
|
+
const duration = row.durationSeconds, base = duration === 5 * 60 * 60 ? 'fiveHour' : duration === 7 * 24 * 60 * 60 ? 'weekly' : 'window_' + duration + 's'
|
|
85
|
+
const key = Object.hasOwn(windows, base) ? base + '_' + seen.size : base
|
|
86
|
+
windows[key] = { percent: Number((used > limit ? limit : used) * 100000n / limit) / 1000, resetsAt }
|
|
87
|
+
}
|
|
88
|
+
if (value.eligible && !Object.keys(windows).length) return null
|
|
89
|
+
if (!value.eligible && value.windows.length) return null
|
|
90
|
+
return windows
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function parseOpenDesignWallet(value, workspaceId) {
|
|
94
|
+
if (!object(value) || value.billingScopeVersion !== 2 || value.workspaceId !== workspaceId || !id(value.workspaceMemberId)
|
|
95
|
+
|| typeof value.balanceUsd !== 'string' || !/^-?\d{1,12}(?:\.\d{1,12})?$/.test(value.balanceUsd)) return null
|
|
96
|
+
return { text: '$' + value.balanceUsd, resetsAt: '' }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export async function queryOpenDesignQuota(key, locale, t, { workspaceId, signal, fetchImpl } = {}) {
|
|
100
|
+
const zh = locale === 'zh', workspace = normalizeOpenDesignWorkspace(workspaceId)
|
|
101
|
+
if (!workspace) throw queryError(zh ? 'OpenDesign:请先填写工作区 ID。' : 'OpenDesign: configure a workspace ID first.', true, OPEN_DESIGN_QUOTA_FAILURES.invalidRequest)
|
|
102
|
+
if (typeof key !== 'string' || !key.trim()) throw queryError(zh
|
|
103
|
+
? 'OpenDesign:额度查询需要 Control Key(OPENDESIGN_CONTROL_KEY / VELA_CONTROL_KEY),不能使用推理 API Key。'
|
|
104
|
+
: 'OpenDesign: quota queries require a Control Key (OPENDESIGN_CONTROL_KEY / VELA_CONTROL_KEY), not an inference API key.', true, OPEN_DESIGN_QUOTA_FAILURES.invalidRequest)
|
|
105
|
+
const controller = new AbortController(), combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal
|
|
106
|
+
const timer = setTimeout(() => controller.abort(), 15000); timer.unref?.()
|
|
107
|
+
const prefix = OPENDESIGN_API + '/workspaces/' + encodeURIComponent(workspace)
|
|
108
|
+
// The preflight and wallet routes accept a Control Key without a browser cookie.
|
|
109
|
+
// Read both sides independently and only fail
|
|
110
|
+
// when both fail; a single 401 must never discard the other side's valid answer.
|
|
111
|
+
const read = async (path, side) => {
|
|
112
|
+
const url = prefix + path
|
|
113
|
+
let response
|
|
114
|
+
try {
|
|
115
|
+
response = await fetchWithRetry(url, { method: 'GET', redirect: 'error', signal: combined,
|
|
116
|
+
headers: { accept: 'application/json', authorization: 'Bearer ' + key.trim(), 'x-vela-workspace-id': workspace } }, { attempts: 2, fetchImpl })
|
|
117
|
+
} catch (error) {
|
|
118
|
+
if (combined.aborted) throw error // caller cancellation / 15 s deadline must not degrade to a partial card
|
|
119
|
+
return { ok: false, side, kind: OPEN_DESIGN_QUOTA_FAILURES.network, url }
|
|
120
|
+
}
|
|
121
|
+
if (!response.ok) {
|
|
122
|
+
try { await response.body?.cancel?.() } catch {}
|
|
123
|
+
const unauthorized = response.status === 401 || response.status === 403
|
|
124
|
+
return { ok: false, side, kind: unauthorized ? OPEN_DESIGN_QUOTA_FAILURES.unauthorized : OPEN_DESIGN_QUOTA_FAILURES.http, status: response.status, url }
|
|
125
|
+
}
|
|
126
|
+
try { return { ok: true, side, value: await readJsonBounded(response, 256 * 1024), url } }
|
|
127
|
+
catch (error) {
|
|
128
|
+
if (combined.aborted) throw error
|
|
129
|
+
return { ok: false, side, kind: OPEN_DESIGN_QUOTA_FAILURES.invalidResponse, source: 'body', url }
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const describe = failure => {
|
|
133
|
+
if (failure.kind === OPEN_DESIGN_QUOTA_FAILURES.unauthorized) return queryError(t(locale, 'codingPlanUnauthorized', { provider: 'OpenDesign', code: String(failure.status) }), true, failure.kind)
|
|
134
|
+
if (failure.kind === OPEN_DESIGN_QUOTA_FAILURES.http) return queryError(t(locale, 'codingPlanHttp', { provider: 'OpenDesign', code: String(failure.status), url: failure.url }), false, failure.kind)
|
|
135
|
+
if (failure.kind === OPEN_DESIGN_QUOTA_FAILURES.invalidResponse && failure.source === 'body') return queryError(t(locale, 'codingPlanInvalidJson', { provider: 'OpenDesign', url: failure.url }), false, failure.kind)
|
|
136
|
+
if (failure.kind === OPEN_DESIGN_QUOTA_FAILURES.invalidResponse) return queryError(failure.side === 'wallet'
|
|
137
|
+
? (zh ? 'OpenDesign:钱包响应的工作区、成员或数据无效。' : 'OpenDesign: invalid wallet response or workspace/member identity.')
|
|
138
|
+
: (zh ? 'OpenDesign:额度响应的工作区、成员或数据无效。' : 'OpenDesign: invalid quota response or workspace/member identity.'), false, failure.kind)
|
|
139
|
+
if (failure.kind === OPEN_DESIGN_QUOTA_FAILURES.noSubscription) {
|
|
140
|
+
const code = 'codingPlanNoSubscription', text = t(locale, code, { provider: 'OpenDesign' })
|
|
141
|
+
// Fallback keeps "no subscription" distinguishable from "bad credential" until the catalog ships the key.
|
|
142
|
+
return queryError(text === code
|
|
143
|
+
? (zh ? 'OpenDesign:当前账户没有生效的套餐订阅(未订阅或已到期)。' : 'OpenDesign: no active plan subscription was detected for this workspace (not subscribed or expired).')
|
|
144
|
+
: text, true, failure.kind)
|
|
145
|
+
}
|
|
146
|
+
return queryError(zh ? 'OpenDesign:查询失败,请检查控制端凭据、工作区权限和网络。' : 'OpenDesign: query failed; check the control credential, workspace access and connection.', false, failure.kind)
|
|
147
|
+
}
|
|
148
|
+
const partialResult = (windows, endpoint, failures, fallback = false) => ({
|
|
149
|
+
windows, endpoint,
|
|
150
|
+
partial: Object.fromEntries(failures.map(([side, failure]) => [side, failure.kind])),
|
|
151
|
+
message: [
|
|
152
|
+
...(fallback ? [zh ? '钱包余额来自 billing/preflight。' : 'Wallet balance is from billing/preflight.'] : []),
|
|
153
|
+
...failures.map(([side, failure]) => (side === 'usage' ? (zh ? '套餐额度:' : 'Plan quota: ') : (zh ? '钱包端点:' : 'Wallet endpoint: ')) + describe(failure).message),
|
|
154
|
+
].join('\n'),
|
|
155
|
+
})
|
|
156
|
+
try {
|
|
157
|
+
// #274 / #313: do not spend a request on the browser-session-only usage route.
|
|
158
|
+
const [usageRead, walletRead] = await Promise.all([read('/billing/preflight', 'preflight'), read('/wallet/balance', 'wallet')])
|
|
159
|
+
combined.throwIfAborted()
|
|
160
|
+
// The preflight answer is already scoped by URL and x-vela-workspace-id; tolerate a body that
|
|
161
|
+
// omits the redundant workspaceId, but never accept one that names a different workspace.
|
|
162
|
+
const preflight = usageRead.ok && usageRead.side === 'preflight'
|
|
163
|
+
const identifiesOtherWorkspace = value => object(value) && value.workspaceId !== undefined && value.workspaceId !== workspace
|
|
164
|
+
const usageWorkspaceConflict = preflight && object(usageRead.value)
|
|
165
|
+
&& (identifiesOtherWorkspace(usageRead.value) || identifiesOtherWorkspace(usageRead.value.codingPlan))
|
|
166
|
+
const usagePayload = preflight && object(usageRead.value) && usageRead.value.workspaceId === undefined
|
|
167
|
+
? { ...usageRead.value, workspaceId: workspace } : usageRead.value
|
|
168
|
+
const usageWindows = usageRead.ok && !usageWorkspaceConflict ? parseOpenDesignUsage(usagePayload, workspace) : null
|
|
169
|
+
const usageFailure = !usageRead.ok ? usageRead
|
|
170
|
+
: usageWindows === null ? { ok: false, side: usageRead.side, kind: OPEN_DESIGN_QUOTA_FAILURES.invalidResponse, source: 'shape', url: usageRead.url }
|
|
171
|
+
// The parser returns {} only for eligible:false with no windows: a definitive no-subscription answer.
|
|
172
|
+
: Object.keys(usageWindows).length === 0 ? { ok: false, side: usageRead.side, kind: OPEN_DESIGN_QUOTA_FAILURES.noSubscription } : null
|
|
173
|
+
const balance = walletRead.ok ? parseOpenDesignWallet(walletRead.value, workspace) : null
|
|
174
|
+
const walletFailure = !walletRead.ok ? walletRead
|
|
175
|
+
: balance === null ? { ok: false, side: 'wallet', kind: OPEN_DESIGN_QUOTA_FAILURES.invalidResponse, source: 'shape', url: walletRead.url } : null
|
|
176
|
+
// A preflight answer carries balanceUsd too; it only fills in when the wallet endpoint failed.
|
|
177
|
+
const fallbackBalance = usageWindows !== null && preflight ? balanceWindowOf(usageRead.value) : null
|
|
178
|
+
if (usageWindows !== null && balance !== null) {
|
|
179
|
+
// Only an identity the quota response actually provides must agree with the wallet member.
|
|
180
|
+
const usageMember = quotaMemberOf(usageRead.value)
|
|
181
|
+
if (usageMember !== undefined && walletRead.value.workspaceMemberId !== usageMember) {
|
|
182
|
+
throw queryError(zh ? 'OpenDesign:钱包与额度的工作区成员不一致。' : 'OpenDesign: wallet and quota member identities do not match.', false, OPEN_DESIGN_QUOTA_FAILURES.identityMismatch)
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (usageFailure === null && walletFailure === null) return { windows: { ...usageWindows, balance }, endpoint: usageRead.url }
|
|
186
|
+
// Partial degradation (issue #274): keep whichever side answered. `partial` names the failing
|
|
187
|
+
// side and its machine-readable cause; it never replaces the existing windows contract.
|
|
188
|
+
if (usageFailure === null) return partialResult(fallbackBalance === null ? usageWindows : { ...usageWindows, balance: fallbackBalance }, usageRead.url, [['wallet', walletFailure]], fallbackBalance !== null)
|
|
189
|
+
if (walletFailure === null) return partialResult({ balance }, walletRead.url, [['usage', usageFailure]])
|
|
190
|
+
// No subscription is a valid preflight answer too: its readable wallet balance
|
|
191
|
+
// must survive an unavailable wallet route, without inventing any quota windows.
|
|
192
|
+
if (fallbackBalance !== null) return partialResult({ balance: fallbackBalance }, usageRead.url, [['usage', usageFailure], ['wallet', walletFailure]], true)
|
|
193
|
+
// Both failed: report the most actionable cause, preferring a definitive account state
|
|
194
|
+
// (no subscription / rejected credential) over a secondary transport or shape failure.
|
|
195
|
+
const priority = [OPEN_DESIGN_QUOTA_FAILURES.noSubscription, OPEN_DESIGN_QUOTA_FAILURES.unauthorized,
|
|
196
|
+
OPEN_DESIGN_QUOTA_FAILURES.invalidResponse, OPEN_DESIGN_QUOTA_FAILURES.http, OPEN_DESIGN_QUOTA_FAILURES.network]
|
|
197
|
+
throw describe(priority.indexOf(walletFailure.kind) < priority.indexOf(usageFailure.kind) ? walletFailure : usageFailure)
|
|
198
|
+
} catch (error) {
|
|
199
|
+
combined.throwIfAborted()
|
|
200
|
+
// Never put an upstream body, arbitrary network exception or credential in the UI.
|
|
201
|
+
if (error?.opendesignPublic === true) throw error
|
|
202
|
+
throw Error(zh ? 'OpenDesign:查询失败,请检查控制端凭据、工作区权限和网络。' : 'OpenDesign: query failed; check the control credential, workspace access and connection.')
|
|
203
|
+
} finally { clearTimeout(timer) }
|
|
204
|
+
}
|
|
@@ -1,95 +1,95 @@
|
|
|
1
|
-
/** Token Rhythm 账户可用余额(#290);复用余额缓存及 DSH 只写凭据库。 */
|
|
2
|
-
import { credentialRef } from './credentials-shim.mjs'
|
|
3
|
-
import { fetchWithRetry, readJsonBounded } from './net.mjs'
|
|
4
|
-
|
|
5
|
-
// 与官方网站账户页相同的 wallet summary / availableBalanceCny,见 docs/tokenrhythm-balance.md。
|
|
6
|
-
export const TOKENRHYTHM_BALANCE_URL = 'https://tokenrhythm.studio/api/wallet/summary'
|
|
7
|
-
export const TOKENRHYTHM_BALANCE_CREDENTIAL_VARS = ['TOKENRHYTHM_COOKIE']
|
|
8
|
-
const messages = {
|
|
9
|
-
zh: {
|
|
10
|
-
missing: '请填写 Token Rhythm 网站登录 Cookie(tr_session,不是模型 API Key)',
|
|
11
|
-
cookie: 'Token Rhythm Cookie 格式无效,请填写 tr_session 或包含它的 Cookie',
|
|
12
|
-
network: 'Token Rhythm 余额网络请求失败,请稍后重试',
|
|
13
|
-
redirect: 'Token Rhythm 余额接口发生重定向,已拒绝转发 Cookie',
|
|
14
|
-
permission: 'Token Rhythm 登录已失效或无权查询,请登录官网后更新 Cookie',
|
|
15
|
-
http: 'Token Rhythm 余额接口返回 HTTP {status}',
|
|
16
|
-
payload: 'Token Rhythm 余额响应无效或过大,请稍后重试',
|
|
17
|
-
amount: 'Token Rhythm 未返回有效的可用余额,未将其视为零余额',
|
|
18
|
-
currency: 'Token Rhythm 余额币种不是 CNY,请检查平台接口',
|
|
19
|
-
},
|
|
20
|
-
en: {
|
|
21
|
-
missing: 'Enter the Token Rhythm website session cookie (tr_session, not a model API key)',
|
|
22
|
-
cookie: 'Invalid Token Rhythm cookie; enter tr_session or a Cookie header containing it',
|
|
23
|
-
network: 'Token Rhythm balance network request failed; please retry later',
|
|
24
|
-
redirect: 'Token Rhythm balance redirect refused to protect the cookie',
|
|
25
|
-
permission: 'Token Rhythm session expired or access denied; sign in on the website and update the cookie',
|
|
26
|
-
http: 'Token Rhythm balance returned HTTP {status}',
|
|
27
|
-
payload: 'Token Rhythm balance response is invalid or too large; please retry later',
|
|
28
|
-
amount: 'Token Rhythm returned no valid available balance; it was not treated as zero',
|
|
29
|
-
currency: 'Token Rhythm balance currency is not CNY; check the platform API',
|
|
30
|
-
},
|
|
31
|
-
}
|
|
32
|
-
const failure = (locale, key, status = '') => new Error(messages[locale === 'en' ? 'en' : 'zh'][key].replace('{status}', String(status)))
|
|
33
|
-
|
|
34
|
-
export function parseTokenRhythmCookie(value, locale = 'zh') {
|
|
35
|
-
const text = String(value ?? '').trim()
|
|
36
|
-
if (!text || text.length > 16384 || /[\r\n]/.test(text)) throw failure(locale, 'cookie')
|
|
37
|
-
if (/^[A-Za-z0-9._-]+$/.test(text)) return text
|
|
38
|
-
const parts = text.replace(/^Cookie:\s*/i, '').split(';').map(part => part.trim())
|
|
39
|
-
const sessions = parts.filter(part => /^tr_session\s*=/.test(part))
|
|
40
|
-
const match = sessions.length === 1 && /^tr_session\s*=\s*([A-Za-z0-9._-]+)$/.exec(sessions[0])
|
|
41
|
-
if (!match) throw failure(locale, 'cookie')
|
|
42
|
-
return match[1]
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export function parseTokenRhythmBalance(payload, locale = 'zh') {
|
|
46
|
-
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw failure(locale, 'payload')
|
|
47
|
-
// 官网成功码为 0 / 200(兼容字符串);拒绝夹带余额的业务错误,不回显原始响应。
|
|
48
|
-
if ((payload.code !== undefined && ![0, '0', 200, '200'].includes(payload.code)) || payload.success === false) throw failure(locale, 'permission')
|
|
49
|
-
const data = Object.hasOwn(payload, 'data') ? payload.data : payload
|
|
50
|
-
if (!data || typeof data !== 'object' || Array.isArray(data)) throw failure(locale, 'payload')
|
|
51
|
-
if (data.currency !== undefined && data.currency !== 'CNY') throw failure(locale, 'currency')
|
|
52
|
-
const raw = Object.hasOwn(data, 'availableBalanceCny') ? data.availableBalanceCny : data.available_balance_cny
|
|
53
|
-
const text = typeof raw === 'string' ? raw.trim() : ''
|
|
54
|
-
const remaining = typeof raw === 'number' ? raw : /^[+-]?\d+(\.\d+)?$/.test(text) ? Number(text) : NaN
|
|
55
|
-
if (!Number.isFinite(remaining)) throw failure(locale, 'amount')
|
|
56
|
-
// 可用余额与累计消费/赠额/冻结金额分开;接口没有预算上限时不伪造百分比。
|
|
57
|
-
return { remaining, unit: 'CNY', maxBudget: null, spend: null }
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export async function queryTokenRhythmBalance(ctx, config, { fetchImpl = fetch, signal } = {}) {
|
|
61
|
-
signal?.throwIfAborted()
|
|
62
|
-
const locale = config?.locale
|
|
63
|
-
let value
|
|
64
|
-
try { value = (await ctx?.get?.('credentials')?.resolve(credentialRef('TOKENRHYTHM_COOKIE')))?.value } catch { /* 回落环境变量。 */ }
|
|
65
|
-
if (typeof value !== 'string' || !value.trim()) value = process.env.TOKENRHYTHM_COOKIE
|
|
66
|
-
if (!value?.trim()) throw Object.assign(failure(locale, 'missing'), { soft: true })
|
|
67
|
-
const session = parseTokenRhythmCookie(value, locale)
|
|
68
|
-
let response
|
|
69
|
-
try {
|
|
70
|
-
response = await fetchWithRetry(TOKENRHYTHM_BALANCE_URL, {
|
|
71
|
-
method: 'GET', redirect: 'manual', signal,
|
|
72
|
-
headers: {
|
|
73
|
-
Accept: 'application/json', Cookie: 'tr_session=' + session,
|
|
74
|
-
Referer: 'https://tokenrhythm.studio/account', Origin: 'https://tokenrhythm.studio',
|
|
75
|
-
'User-Agent': 'Mozilla/5.0 (compatible; dsh-cost-meter)',
|
|
76
|
-
},
|
|
77
|
-
}, { attempts: 2, timeoutMs: 15000, fetchImpl })
|
|
78
|
-
} catch {
|
|
79
|
-
signal?.throwIfAborted()
|
|
80
|
-
throw failure(locale, 'network')
|
|
81
|
-
}
|
|
82
|
-
if (!response.ok) {
|
|
83
|
-
await response.body?.cancel().catch(() => {})
|
|
84
|
-
if (response.status >= 300 && response.status < 400) throw failure(locale, 'redirect')
|
|
85
|
-
if (response.status === 401 || response.status === 403) throw failure(locale, 'permission')
|
|
86
|
-
throw failure(locale, 'http', response.status)
|
|
87
|
-
}
|
|
88
|
-
let payload
|
|
89
|
-
try { payload = await readJsonBounded(response) } catch {
|
|
90
|
-
signal?.throwIfAborted()
|
|
91
|
-
throw failure(locale, 'payload')
|
|
92
|
-
}
|
|
93
|
-
signal?.throwIfAborted()
|
|
94
|
-
return { label: config?.customBalance?.label || 'Token Rhythm', ...parseTokenRhythmBalance(payload, locale) }
|
|
95
|
-
}
|
|
1
|
+
/** Token Rhythm 账户可用余额(#290);复用余额缓存及 DSH 只写凭据库。 */
|
|
2
|
+
import { credentialRef } from './credentials-shim.mjs'
|
|
3
|
+
import { fetchWithRetry, readJsonBounded } from './net.mjs'
|
|
4
|
+
|
|
5
|
+
// 与官方网站账户页相同的 wallet summary / availableBalanceCny,见 docs/tokenrhythm-balance.md。
|
|
6
|
+
export const TOKENRHYTHM_BALANCE_URL = 'https://tokenrhythm.studio/api/wallet/summary'
|
|
7
|
+
export const TOKENRHYTHM_BALANCE_CREDENTIAL_VARS = ['TOKENRHYTHM_COOKIE']
|
|
8
|
+
const messages = {
|
|
9
|
+
zh: {
|
|
10
|
+
missing: '请填写 Token Rhythm 网站登录 Cookie(tr_session,不是模型 API Key)',
|
|
11
|
+
cookie: 'Token Rhythm Cookie 格式无效,请填写 tr_session 或包含它的 Cookie',
|
|
12
|
+
network: 'Token Rhythm 余额网络请求失败,请稍后重试',
|
|
13
|
+
redirect: 'Token Rhythm 余额接口发生重定向,已拒绝转发 Cookie',
|
|
14
|
+
permission: 'Token Rhythm 登录已失效或无权查询,请登录官网后更新 Cookie',
|
|
15
|
+
http: 'Token Rhythm 余额接口返回 HTTP {status}',
|
|
16
|
+
payload: 'Token Rhythm 余额响应无效或过大,请稍后重试',
|
|
17
|
+
amount: 'Token Rhythm 未返回有效的可用余额,未将其视为零余额',
|
|
18
|
+
currency: 'Token Rhythm 余额币种不是 CNY,请检查平台接口',
|
|
19
|
+
},
|
|
20
|
+
en: {
|
|
21
|
+
missing: 'Enter the Token Rhythm website session cookie (tr_session, not a model API key)',
|
|
22
|
+
cookie: 'Invalid Token Rhythm cookie; enter tr_session or a Cookie header containing it',
|
|
23
|
+
network: 'Token Rhythm balance network request failed; please retry later',
|
|
24
|
+
redirect: 'Token Rhythm balance redirect refused to protect the cookie',
|
|
25
|
+
permission: 'Token Rhythm session expired or access denied; sign in on the website and update the cookie',
|
|
26
|
+
http: 'Token Rhythm balance returned HTTP {status}',
|
|
27
|
+
payload: 'Token Rhythm balance response is invalid or too large; please retry later',
|
|
28
|
+
amount: 'Token Rhythm returned no valid available balance; it was not treated as zero',
|
|
29
|
+
currency: 'Token Rhythm balance currency is not CNY; check the platform API',
|
|
30
|
+
},
|
|
31
|
+
}
|
|
32
|
+
const failure = (locale, key, status = '') => new Error(messages[locale === 'en' ? 'en' : 'zh'][key].replace('{status}', String(status)))
|
|
33
|
+
|
|
34
|
+
export function parseTokenRhythmCookie(value, locale = 'zh') {
|
|
35
|
+
const text = String(value ?? '').trim()
|
|
36
|
+
if (!text || text.length > 16384 || /[\r\n]/.test(text)) throw failure(locale, 'cookie')
|
|
37
|
+
if (/^[A-Za-z0-9._-]+$/.test(text)) return text
|
|
38
|
+
const parts = text.replace(/^Cookie:\s*/i, '').split(';').map(part => part.trim())
|
|
39
|
+
const sessions = parts.filter(part => /^tr_session\s*=/.test(part))
|
|
40
|
+
const match = sessions.length === 1 && /^tr_session\s*=\s*([A-Za-z0-9._-]+)$/.exec(sessions[0])
|
|
41
|
+
if (!match) throw failure(locale, 'cookie')
|
|
42
|
+
return match[1]
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function parseTokenRhythmBalance(payload, locale = 'zh') {
|
|
46
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw failure(locale, 'payload')
|
|
47
|
+
// 官网成功码为 0 / 200(兼容字符串);拒绝夹带余额的业务错误,不回显原始响应。
|
|
48
|
+
if ((payload.code !== undefined && ![0, '0', 200, '200'].includes(payload.code)) || payload.success === false) throw failure(locale, 'permission')
|
|
49
|
+
const data = Object.hasOwn(payload, 'data') ? payload.data : payload
|
|
50
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) throw failure(locale, 'payload')
|
|
51
|
+
if (data.currency !== undefined && data.currency !== 'CNY') throw failure(locale, 'currency')
|
|
52
|
+
const raw = Object.hasOwn(data, 'availableBalanceCny') ? data.availableBalanceCny : data.available_balance_cny
|
|
53
|
+
const text = typeof raw === 'string' ? raw.trim() : ''
|
|
54
|
+
const remaining = typeof raw === 'number' ? raw : /^[+-]?\d+(\.\d+)?$/.test(text) ? Number(text) : NaN
|
|
55
|
+
if (!Number.isFinite(remaining)) throw failure(locale, 'amount')
|
|
56
|
+
// 可用余额与累计消费/赠额/冻结金额分开;接口没有预算上限时不伪造百分比。
|
|
57
|
+
return { remaining, unit: 'CNY', maxBudget: null, spend: null }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function queryTokenRhythmBalance(ctx, config, { fetchImpl = fetch, signal } = {}) {
|
|
61
|
+
signal?.throwIfAborted()
|
|
62
|
+
const locale = config?.locale
|
|
63
|
+
let value
|
|
64
|
+
try { value = (await ctx?.get?.('credentials')?.resolve(credentialRef('TOKENRHYTHM_COOKIE')))?.value } catch { /* 回落环境变量。 */ }
|
|
65
|
+
if (typeof value !== 'string' || !value.trim()) value = process.env.TOKENRHYTHM_COOKIE
|
|
66
|
+
if (!value?.trim()) throw Object.assign(failure(locale, 'missing'), { soft: true })
|
|
67
|
+
const session = parseTokenRhythmCookie(value, locale)
|
|
68
|
+
let response
|
|
69
|
+
try {
|
|
70
|
+
response = await fetchWithRetry(TOKENRHYTHM_BALANCE_URL, {
|
|
71
|
+
method: 'GET', redirect: 'manual', signal,
|
|
72
|
+
headers: {
|
|
73
|
+
Accept: 'application/json', Cookie: 'tr_session=' + session,
|
|
74
|
+
Referer: 'https://tokenrhythm.studio/account', Origin: 'https://tokenrhythm.studio',
|
|
75
|
+
'User-Agent': 'Mozilla/5.0 (compatible; dsh-cost-meter)',
|
|
76
|
+
},
|
|
77
|
+
}, { attempts: 2, timeoutMs: 15000, fetchImpl })
|
|
78
|
+
} catch {
|
|
79
|
+
signal?.throwIfAborted()
|
|
80
|
+
throw failure(locale, 'network')
|
|
81
|
+
}
|
|
82
|
+
if (!response.ok) {
|
|
83
|
+
await response.body?.cancel().catch(() => {})
|
|
84
|
+
if (response.status >= 300 && response.status < 400) throw failure(locale, 'redirect')
|
|
85
|
+
if (response.status === 401 || response.status === 403) throw failure(locale, 'permission')
|
|
86
|
+
throw failure(locale, 'http', response.status)
|
|
87
|
+
}
|
|
88
|
+
let payload
|
|
89
|
+
try { payload = await readJsonBounded(response) } catch {
|
|
90
|
+
signal?.throwIfAborted()
|
|
91
|
+
throw failure(locale, 'payload')
|
|
92
|
+
}
|
|
93
|
+
signal?.throwIfAborted()
|
|
94
|
+
return { label: config?.customBalance?.label || 'Token Rhythm', ...parseTokenRhythmBalance(payload, locale) }
|
|
95
|
+
}
|