dsh-zcode-startplan 0.4.5 → 1.0.2

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.
Files changed (58) hide show
  1. package/CHANGELOG.md +1963 -405
  2. package/README.md +88 -405
  3. package/bin/cli.mjs +509 -450
  4. package/client.js +2459 -716
  5. package/cordis.patch.yml +4 -2
  6. package/index.js +144 -14
  7. package/lib/adapter.js +476 -422
  8. package/lib/anthropic-body.js +513 -469
  9. package/lib/assemble.js +808 -420
  10. package/lib/auto-claim.js +229 -0
  11. package/lib/captcha/minter.js +61 -7
  12. package/lib/distribution-keys.js +202 -0
  13. package/lib/errors.js +281 -125
  14. package/lib/fallback.js +120 -0
  15. package/lib/local-endpoint.js +367 -352
  16. package/lib/manage-routes.js +1245 -489
  17. package/lib/model-catalog.js +57 -0
  18. package/lib/openai-gateway.js +776 -0
  19. package/lib/plan-client.js +942 -532
  20. package/lib/pool.js +771 -478
  21. package/lib/sse.js +429 -317
  22. package/lib/upstream-api.js +948 -570
  23. package/lib/upstream.js +294 -134
  24. package/lib/version-probe.js +110 -0
  25. package/package.json +84 -80
  26. package/scripts/analyze-grant-intervals.mjs +171 -0
  27. package/scripts/check-compat-rc3.mjs +21 -11
  28. package/scripts/debug-claimable.mjs +130 -0
  29. package/scripts/probe-marketing.mjs +203 -0
  30. package/scripts/restart-dsh.ps1 +119 -76
  31. package/scripts/test-claimed-pending.mjs +152 -0
  32. package/scripts/verify_compat.mjs +75 -64
  33. package/scripts/watch-marketing.mjs +155 -0
  34. package/tests/anthropic-body.test.mjs +305 -0
  35. package/tests/assembler-contract.test.mjs +256 -0
  36. package/tests/auto-claim.test.mjs +318 -0
  37. package/tests/claim-routes.test.mjs +438 -0
  38. package/tests/client-panel.test.mjs +1141 -0
  39. package/tests/distribution-keys.test.mjs +123 -0
  40. package/tests/e2e.test.mjs +388 -0
  41. package/tests/fallback-scrub.test.mjs +105 -0
  42. package/tests/fixtures/quota-200.json +1 -0
  43. package/tests/launch-command.test.mjs +68 -0
  44. package/tests/login-channel.test.mjs +102 -0
  45. package/tests/openai-gateway.test.mjs +454 -0
  46. package/tests/pinned-models.test.mjs +505 -0
  47. package/tests/plan-client.test.mjs +582 -0
  48. package/tests/pool.test.mjs +319 -0
  49. package/tests/quota-blackhole.test.mjs +409 -0
  50. package/tests/restart-script.test.mjs +53 -0
  51. package/tests/routing-quota.test.mjs +251 -0
  52. package/tests/sse.test.mjs +86 -0
  53. package/tests/stream-translator.test.mjs +137 -0
  54. package/tests/support/hanging-stream.mjs +48 -0
  55. package/tests/support/resolve-profile-deps.mjs +52 -0
  56. package/tests/upstream-error-200.test.mjs +164 -0
  57. package/tests/upstream.test.mjs +330 -0
  58. package/tests/version-probe.test.mjs +172 -0
@@ -1,570 +1,948 @@
1
- /**
2
- * 上游 API 客户端:设备授权登录 / 额度 / 领取 / 模型目录 / captcha 配置。
3
- *
4
- * 全部判据来自参考实现的实测:
5
- * - 登录三段式:`POST oauth/cli/init`(Bearer 是**我们自己生成的会话密钥**)→
6
- * 浏览器完成授权 → `GET oauth/cli/poll/{id}` 拿 `token` / `user.user_id` / `bigmodel.access_token`;
7
- * - `device_mid` 自己生成即可(服务端不绑定校验,只需稳定);
8
- * - captcha 配置要 `platform=unknown`(`win32`/`windows`/… 一律 400 code 3001);
9
- * - 领取前必须补 `app_launch` + `app_daily_active` 上报,否则 preview 恒为空;
10
- * - `1003` = 已领取过,是**幂等成功**而不是错误。
11
- */
12
-
13
- import {
14
- ZCODE_BILLING_BALANCE_URL,
15
- ZCODE_BILLING_CLAIM_URL,
16
- ZCODE_BILLING_PREVIEW_URL,
17
- ZCODE_CLIENT_CONFIGS_URL,
18
- ZCODE_EVENT_REPORT_URL,
19
- ZCODE_OAUTH_CLI_INIT_URL,
20
- ZCODE_ORIGIN,
21
- ZCODE_APP_VERSION_FALLBACK,
22
- buildZcodeHeaders,
23
- generateDeviceMid,
24
- nextUtc8DayStartMs,
25
- toEpochMs,
26
- zcodeOauthCliPollUrl,
27
- } from './upstream.js'
28
-
29
- /** 登录渠道(默认国内站)。 */
30
- export const ZCODE_LOGIN_PROVIDER = 'bigmodel'
31
-
32
- /**
33
- * 两条登录渠道(实测,2026-10-23)。
34
- *
35
- * 两者**共用同一套设备授权协议**(同一个 `/api/v1/oauth/cli/init` 与 `poll/{id}`、
36
- * 相同的响应形状),只在 `provider` 参数与授权站点上不同:
37
- *
38
- * | provider | 站点 | authorize_url | 适用 |
39
- * |---|---|---|---|
40
- * | `bigmodel` | 国内 智谱 | `bigmodel.cn/login?appId=zcode&redirect=…/callback/bigmodel` | 国内账号 |
41
- * | `zai` | 国际 Z.AI | `chat.z.ai/api/oauth/authorize?client_id=…&redirect_uri=…/callback/zai` | 国际账号 |
42
- *
43
- * ⚠ 非法值会返回 **HTTP 500 `{"code":1000,"msg":"something went wrong"}`**
44
- * (实测 `z-ai` / `bigmodel-intl` 均如此)—— 所以这里做白名单,不做"猜"。
45
- */
46
- export const LOGIN_CHANNELS = Object.freeze({
47
- bigmodel: Object.freeze({
48
- provider: 'bigmodel',
49
- aliases: Object.freeze(['bigmodel', 'cn', 'china', 'domestic', '智谱', '国内']),
50
- label: '智谱(国内站)',
51
- site: 'bigmodel.cn',
52
- apiKeyUrl: 'https://bigmodel.cn/usercenter/proj-mgmt/apikeys',
53
- accountSettingUrl: 'https://bigmodel.cn/',
54
- }),
55
- zai: Object.freeze({
56
- provider: 'zai',
57
- aliases: Object.freeze(['zai', 'z-ai', 'intl', 'international', 'global', 'global站', '国际', '海外']),
58
- label: 'Z.AI(国际站)',
59
- site: 'z.ai',
60
- apiKeyUrl: 'https://z.ai/manage-apikey/apikey-list',
61
- accountSettingUrl: 'https://chat.z.ai/',
62
- }),
63
- })
64
-
65
- /** 默认渠道。 */
66
- export const DEFAULT_LOGIN_CHANNEL = 'bigmodel'
67
-
68
- /**
69
- * 把用户输入的渠道名(含别名/中文)归一成 `bigmodel` 或 `zai`。
70
- *
71
- * @param {string | undefined | null} input
72
- * @returns {'bigmodel' | 'zai'}
73
- */
74
- export function normalizeLoginChannel(input) {
75
- const needle = String(input ?? '').trim().toLowerCase()
76
- if (needle.length === 0) return DEFAULT_LOGIN_CHANNEL
77
- for (const [id, channel] of Object.entries(LOGIN_CHANNELS)) {
78
- if (id === needle) return /** @type {'bigmodel' | 'zai'} */ (id)
79
- if (channel.aliases.some((alias) => alias.toLowerCase() === needle)) return /** @type {'bigmodel' | 'zai'} */ (id)
80
- }
81
- return DEFAULT_LOGIN_CHANNEL
82
- }
83
-
84
- /** 取渠道描述(未知值回退默认)。 */
85
- export function resolveLoginChannel(input) {
86
- return LOGIN_CHANNELS[normalizeLoginChannel(input)]
87
- }
88
-
89
- /** 一次登录尝试的失败原因(人类可读)。 */
90
- export class ZcodeLoginError extends Error {
91
- constructor(message, kind) {
92
- super(message)
93
- this.name = 'ZcodeLoginError'
94
- this.kind = kind
95
- }
96
- }
97
-
98
- /** fetch + 超时包装(外部输入必须有上限)。 */
99
- async function fetchWithTimeout(fetchImpl, input, init, timeoutMs) {
100
- const controller = new AbortController()
101
- const timer = setTimeout(() => controller.abort(), timeoutMs)
102
- timer.unref?.()
103
- try {
104
- return await fetchImpl(input, { ...init, signal: controller.signal })
105
- } finally {
106
- clearTimeout(timer)
107
- }
108
- }
109
-
110
- const num = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : undefined)
111
-
112
- /**
113
- * 发起登录:立刻拿到 `authorize_url`。
114
- *
115
- * ⚠ 授权 URL 必须**立刻**返回(浏览器 `window.open` 只在用户手势窗口内有效)。
116
- *
117
- * @param {typeof fetch} [fetchImpl]
118
- * @param {{ appVersion?: string, provider?: string, channel?: string }} [options]
119
- * `channel` 是友好名(`cn`/`intl`/`国内`/`国际` 都认),`provider` 是原始值。
120
- * 两者都给时 `provider` 优先(保持向后兼容)。
121
- */
122
- export async function startZcodeLogin(fetchImpl = globalThis.fetch, options = {}) {
123
- const flowSecret = globalThis.crypto.randomBytes ? globalThis.crypto.randomBytes(32).toString('hex') : fallbackSecret()
124
- const appVersion = options.appVersion ?? ZCODE_APP_VERSION_FALLBACK
125
- const provider = options.provider ?? resolveLoginChannel(options.channel).provider
126
-
127
- let response
128
- try {
129
- response = await fetchImpl(ZCODE_OAUTH_CLI_INIT_URL, {
130
- method: 'POST',
131
- headers: {
132
- /** ⚠ 这里的 Bearer 是**我们自己生成的会话密钥**,不是用户凭据。 */
133
- Authorization: `Bearer ${flowSecret}`,
134
- 'Content-Type': 'application/json',
135
- 'User-Agent': `ZCode/${appVersion}`,
136
- 'HTTP-Referer': ZCODE_ORIGIN,
137
- 'X-ZCode-App-Version': appVersion,
138
- 'X-Platform': 'win32',
139
- },
140
- body: JSON.stringify({ provider }),
141
- signal: AbortSignal.timeout(30_000),
142
- })
143
- } catch (error) {
144
- throw new ZcodeLoginError(
145
- `无法连接 ZCode 授权服务:${error instanceof Error ? error.message : String(error)}`,
146
- 'init',
147
- )
148
- }
149
-
150
- const text = await response.text().catch(() => '')
151
- if (!response.ok) {
152
- /**
153
- * 非法 provider 会返回 500 code=1000("something went wrong")—— 把这句话翻译成
154
- * 可操作的原因,避免用户以为服务挂了。
155
- */
156
- const hint = /code"?\s*:\s*1000/.test(text) || response.status === 500
157
- ? `;渠道「${provider}」可能不被支持(合法值:bigmodel=国内、zai=国际)`
158
- : ''
159
- throw new ZcodeLoginError(`授权初始化失败(HTTP ${response.status}${hint}):${text.slice(0, 200)}`, 'init')
160
- }
161
- let parsed
162
- try {
163
- parsed = JSON.parse(text)
164
- } catch {
165
- throw new ZcodeLoginError(`授权初始化响应不是 JSON:${text.slice(0, 200)}`, 'init')
166
- }
167
- const data = parsed.data
168
- const flowId = data?.flow_id
169
- const authorizeUrl = data?.authorize_url
170
- if (typeof flowId !== 'string' || flowId.length === 0) {
171
- throw new ZcodeLoginError(`授权初始化响应缺 flow_id:${typeof parsed.msg === 'string' ? parsed.msg : text.slice(0, 160)}`, 'init')
172
- }
173
- if (typeof authorizeUrl !== 'string' || !authorizeUrl.startsWith('https://')) {
174
- throw new ZcodeLoginError('授权初始化响应缺合法的 authorize_url', 'init')
175
- }
176
- /** ⚠ 服务端给的是**秒级**时间戳,必须归一再与毫秒比较。 */
177
- const expiresAt = toEpochMs(typeof data?.expires_at === 'number' ? data.expires_at : 0)
178
- const rawInterval = typeof data?.poll_interval_sec === 'number' ? data.poll_interval_sec : 2
179
- const pollIntervalSec = Number.isFinite(rawInterval) && rawInterval >= 1 ? rawInterval : 2
180
- return { flowId, authorizeUrl, expiresAt, pollIntervalSec, flowSecret }
181
- }
182
-
183
- function fallbackSecret() {
184
- const bytes = new Uint8Array(32)
185
- globalThis.crypto.getRandomValues(bytes)
186
- return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')
187
- }
188
-
189
- /**
190
- * 轮询一次。
191
- *
192
- * ⚠ 网络抖动**不算失败**(返回 pending 让调用方继续轮询);
193
- * HTTP 4xx(除 408/429)才是终态失败;5xx 与网络错误继续重试。
194
- */
195
- export async function pollZcodeLogin(flow, fetchImpl = globalThis.fetch, appVersion = ZCODE_APP_VERSION_FALLBACK) {
196
- let response
197
- try {
198
- response = await fetchImpl(zcodeOauthCliPollUrl(flow.flowId), {
199
- method: 'GET',
200
- headers: {
201
- Authorization: `Bearer ${flow.flowSecret}`,
202
- 'User-Agent': `ZCode/${appVersion}`,
203
- 'HTTP-Referer': ZCODE_ORIGIN,
204
- 'X-ZCode-App-Version': appVersion,
205
- },
206
- signal: AbortSignal.timeout(20_000),
207
- })
208
- } catch {
209
- return { kind: 'pending' }
210
- }
211
-
212
- if (response.status >= 400 && response.status < 500 && response.status !== 408 && response.status !== 429) {
213
- const text = await response.text().catch(() => '')
214
- return { kind: 'failed', message: `轮询被拒(HTTP ${response.status}):${text.slice(0, 200)}` }
215
- }
216
- if (!response.ok) return { kind: 'pending' }
217
-
218
- let parsed
219
- try {
220
- parsed = await response.json()
221
- } catch {
222
- return { kind: 'pending' }
223
- }
224
- const data = parsed.data
225
- if (parsed.code !== 0 || data === undefined || data === null) return { kind: 'pending' }
226
- const status = typeof data.status === 'string' ? data.status : undefined
227
- if (status === 'pending') return { kind: 'pending' }
228
- if (status === 'failed') return { kind: 'failed', message: '用户拒绝了授权或授权失败' }
229
- if (status !== 'ready') return { kind: 'failed', message: `轮询响应状态无法识别:${String(status)}` }
230
-
231
- /**
232
- * 容错取值:**两条渠道的字段名不完全一致**(国际站 z.ai 实测不返回
233
- * `bigmodel.access_token` 之外的同构字段,且 `user_id` 可能落在别的键上)。
234
- *
235
- * 判据只看**推理必需**的那两样:`zcode_jwt` 与 `user_id`。
236
- * `access_token` 是可选的备用身份 —— 缺了不该让登录失败(此前正是因为
237
- * 把它当成必需字段,国际站授权完成后直接报「缺关键字段」)。
238
- */
239
- const pick = (...values) => values.find((value) => typeof value === 'string' && value.length > 0)
240
-
241
- const zcodeJwt = pick(data.token, data.access_token, data.accessToken)
242
- const userId = pick(data.user?.user_id, data.user?.id, data.user_id, data.userId, data.uid)
243
- const bigmodelAccessToken = pick(
244
- data.bigmodel?.access_token,
245
- data.bigmodel?.accessToken,
246
- data.bigmodel_access_token,
247
- )
248
-
249
- if (zcodeJwt === undefined) {
250
- /**
251
- * 拿不到 JWT 就真的无法推理 —— 但要把「服务端到底给了什么键」报出来,
252
- * 否则排查只能靠猜(本次国际站的坑就是这样踩到的)。
253
- */
254
- const keys = Object.keys(data ?? {}).join(', ') || '(空)'
255
- return { kind: 'failed', message: `轮询响应里没有 token(实际字段:${keys})` }
256
- }
257
- if (userId === undefined) {
258
- /** 没有 user_id 只影响「按账号去重」,不阻塞入池。 */
259
- return {
260
- kind: 'ready',
261
- result: {
262
- zcodeJwt,
263
- userId: zcodeJwt.slice(-12),
264
- displayName: pick(data.user?.name, data.user?.email, data.account?.name) ?? '未命名账号',
265
- bigmodelAccessToken: bigmodelAccessToken ?? '',
266
- note: '响应未返回 user_id,已用 JWT 尾段临时作账号标识(无法按账号去重)',
267
- },
268
- }
269
- }
270
-
271
- const displayName =
272
- pick(data.user?.name, data.user?.email, data.user?.username, data.account?.name) ?? userId
273
- return { kind: 'ready', result: { zcodeJwt, userId, displayName, bigmodelAccessToken: bigmodelAccessToken ?? '' } }
274
- }
275
-
276
- /**
277
- * 两段式登录:立即返回授权 URL,授权完成由 `result` 兑现。
278
- *
279
- * @param {{ fetchImpl?: typeof fetch, appVersion?: string, signal?: AbortSignal, now?: () => number, sleep?: (ms: number) => Promise<void>, channel?: string, provider?: string }} [options]
280
- */
281
- export async function beginZcodeLogin(options = {}) {
282
- const fetchImpl = options.fetchImpl ?? globalThis.fetch
283
- const appVersion = options.appVersion ?? ZCODE_APP_VERSION_FALLBACK
284
- const now = options.now ?? (() => Date.now())
285
- const sleep = options.sleep ?? ((ms) => new Promise((resolve) => {
286
- const timer = setTimeout(resolve, ms)
287
- timer.unref?.()
288
- }))
289
- const channelId = normalizeLoginChannel(options.provider ?? options.channel)
290
-
291
- const flow = await startZcodeLogin(fetchImpl, { appVersion, channel: channelId })
292
- const result = (async () => {
293
- const deadline = flow.expiresAt > 0 ? flow.expiresAt : now() + 600_000
294
- for (;;) {
295
- if (options.signal?.aborted === true) throw new ZcodeLoginError('登录已取消', 'cancelled')
296
- if (now() >= deadline) throw new ZcodeLoginError('授权超时(请重新发起登录)', 'timeout')
297
- const outcome = await pollZcodeLogin(flow, fetchImpl, appVersion)
298
- if (outcome.kind === 'ready') {
299
- return {
300
- zcode_jwt: outcome.result.zcodeJwt,
301
- /** ⚠ 自己生成(服务端不绑定校验);生成后持久化,登录一次即固定。 */
302
- device_mid: generateDeviceMid(),
303
- user_id: outcome.result.userId,
304
- bigmodel_access_token: outcome.result.bigmodelAccessToken,
305
- account_label: outcome.result.displayName,
306
- app_version: appVersion,
307
- /** 记下这条凭据来自哪条渠道(国内/国际),便于状态展示与排查。 */
308
- login_channel: channelId,
309
- source: 'plugin',
310
- }
311
- }
312
- if (outcome.kind === 'failed') throw new ZcodeLoginError(outcome.message, 'denied')
313
- await sleep(Math.max(1, flow.pollIntervalSec) * 1_000)
314
- }
315
- })()
316
- return { loginUrl: flow.authorizeUrl, result, channel: LOGIN_CHANNELS[channelId] }
317
- }
318
-
319
- /**
320
- * 查余额。
321
- *
322
- * ⚠ `Authorization` 必需(缺则 401);`X-Device-Mid` 也必需(缺则 400 code 3001)。
323
- * 企业版不下发额度数字(`displayMode: "enterprise"`)—— 返回 `{enterprise:true}`,
324
- * **不要**显示成 0(0 是「已用光」的语义)。
325
- */
326
- export async function fetchBalance(credential, fetchImpl = globalThis.fetch) {
327
- const response = await fetchWithTimeout(fetchImpl, ZCODE_BILLING_BALANCE_URL, {
328
- method: 'GET',
329
- headers: buildZcodeHeaders(credential, { authorization: `Bearer ${credential.zcode_jwt}` }),
330
- }, 30_000)
331
- if (!response.ok) return undefined
332
- let parsed
333
- try {
334
- parsed = await response.json()
335
- } catch {
336
- return undefined
337
- }
338
- const data = parsed.data
339
- if (data === undefined) return undefined
340
- if (typeof data.displayMode === 'string' && data.displayMode === 'enterprise') {
341
- return { enterprise: true, buckets: [], remaining: 0, total: 0 }
342
- }
343
- const buckets = []
344
- for (const item of Array.isArray(data.balances) ? data.balances : []) {
345
- if (typeof item !== 'object' || item === null) continue
346
- buckets.push({
347
- planId: typeof item.plan_id === 'string' ? item.plan_id : undefined,
348
- showName: typeof item.show_name === 'string' ? item.show_name : undefined,
349
- unitType: typeof item.unit_type === 'string' ? item.unit_type : undefined,
350
- totalUnits: num(item.total_units),
351
- usedUnits: num(item.used_units),
352
- remainingUnits: num(item.remaining_units),
353
- availableUnits: num(item.available_units),
354
- expiresAt: num(item.expires_at),
355
- })
356
- }
357
- let remaining = 0
358
- let total = 0
359
- let expiresAt
360
- for (const bucket of buckets) {
361
- remaining += bucket.availableUnits ?? bucket.remainingUnits ?? 0
362
- total += bucket.totalUnits ?? 0
363
- if (bucket.expiresAt !== undefined && (expiresAt === undefined || bucket.expiresAt < expiresAt)) {
364
- expiresAt = bucket.expiresAt
365
- }
366
- }
367
- return {
368
- buckets,
369
- remaining,
370
- total,
371
- ...(expiresAt !== undefined ? { expiresAt } : {}),
372
- ...(buckets[0]?.showName !== undefined ? { planName: buckets[0].showName } : {}),
373
- }
374
- }
375
-
376
- /** 补客户端活跃信号(不补则 preview 恒为空 plans)。 */
377
- export async function reportActivation(credential, fetchImpl = globalThis.fetch) {
378
- const appVersion = credential.app_version ?? ZCODE_APP_VERSION_FALLBACK
379
- /** 两个事件相互独立,并行上报(省一个 RTT;失败不阻塞,下次调用会再补)。 */
380
- await Promise.all(['app_launch', 'app_daily_active'].map((event) =>
381
- fetchWithTimeout(fetchImpl, ZCODE_EVENT_REPORT_URL, {
382
- method: 'POST',
383
- headers: buildZcodeHeaders(credential, { json: true }),
384
- body: JSON.stringify({ event, device_mid: credential.device_mid, platform: 'win32', app_version: appVersion }),
385
- }, 20_000).catch(() => {}),
386
- ))
387
- }
388
-
389
- /** 查当前可领的活动(priority 降序)。 */
390
- export async function fetchClaimablePlans(credential, fetchImpl = globalThis.fetch) {
391
- const appVersion = credential.app_version ?? ZCODE_APP_VERSION_FALLBACK
392
- const url = `${ZCODE_BILLING_PREVIEW_URL}?app_version=${encodeURIComponent(appVersion)}&platform=win32`
393
- const response = await fetchWithTimeout(fetchImpl, url, {
394
- method: 'GET',
395
- headers: buildZcodeHeaders(credential, { json: false }),
396
- }, 25_000)
397
- if (!response.ok) return []
398
- let parsed
399
- try {
400
- parsed = await response.json()
401
- } catch {
402
- return []
403
- }
404
- const raw = Array.isArray(parsed.data?.plans) ? parsed.data.plans : []
405
- const plans = []
406
- for (const item of raw) {
407
- if (typeof item !== 'object' || item === null) continue
408
- if (typeof item.plan_id !== 'string' || item.plan_id.length === 0) continue
409
- plans.push({ planId: item.plan_id, priority: num(item.priority) ?? 0, ...(typeof item.name === 'string' ? { name: item.name } : {}) })
410
- }
411
- plans.sort((a, b) => b.priority - a.priority)
412
- return plans
413
- }
414
-
415
- /**
416
- * 领取一个 plan。
417
- *
418
- * ⚠ captcha **一次性**:每个 plan 都必须重新 mint(复用同一个会得 3007)。
419
- * ⚠ `1003` = 已领取过,是**幂等成功**而不是错误。
420
- */
421
- export async function claimPlan(credential, planId, captcha, fetchImpl = globalThis.fetch) {
422
- let response
423
- try {
424
- response = await fetchWithTimeout(fetchImpl, ZCODE_BILLING_CLAIM_URL, {
425
- method: 'POST',
426
- headers: buildZcodeHeaders(credential, { authorization: `Bearer ${credential.zcode_jwt}`, captcha }),
427
- body: JSON.stringify({ plan_id: planId }),
428
- }, 60_000)
429
- } catch (error) {
430
- return { planId, ok: false, message: error instanceof Error ? error.message : String(error) }
431
- }
432
- const text = await response.text().catch(() => '')
433
- let code
434
- let message
435
- try {
436
- const parsed = JSON.parse(text)
437
- code = num(parsed.code)
438
- message = typeof parsed.msg === 'string' ? parsed.msg : typeof parsed.message === 'string' ? parsed.message : undefined
439
- } catch {
440
- message = text.slice(0, 200)
441
- }
442
- const alreadyClaimed = code === 1003
443
- return {
444
- planId,
445
- ...(code !== undefined ? { code } : {}),
446
- ok: response.ok && (code === 0 || alreadyClaimed),
447
- ...(alreadyClaimed ? { alreadyClaimed } : {}),
448
- httpStatus: response.status,
449
- ...(message !== undefined ? { message } : {}),
450
- }
451
- }
452
-
453
- /**
454
- * `GET /api/v1/client/configs` 的共享缓存(60s TTL,仅缓存成功结果 + in-flight 去重)。
455
- *
456
- * captcha 配置与模型目录**是同一端点的两个字段**,此前两条链路各打一次且缓存
457
- * 互相独立 —— 这里统一成一次请求、一份缓存。缓存键带上 `zcode_jwt` 与
458
- * `fetchImpl` 身份:不同账号不串味;测试里逐个注入的 mock fetch 也不互相污染。
459
- * **失败不缓存**(一次网络抖动不该把 sceneId 固化 60 秒)。
460
- */
461
- const CLIENT_CONFIGS_CACHE_MS = 60_000
462
- const clientConfigsCache = new Map()
463
- const clientConfigsInflight = new Map()
464
-
465
- /** 拉一次 client/configs 原文(不缓存);非 2xx / 网络错误 → undefined。 */
466
- async function fetchClientConfigsOnce(credential, fetchImpl) {
467
- const appVersion = credential.app_version ?? ZCODE_APP_VERSION_FALLBACK
468
- const url = `${ZCODE_CLIENT_CONFIGS_URL}?app_version=${encodeURIComponent(appVersion)}&platform=unknown`
469
- try {
470
- const response = await fetchWithTimeout(fetchImpl, url, {
471
- method: 'GET',
472
- headers: buildZcodeHeaders(credential, { authorization: `Bearer ${credential.zcode_jwt}`, json: false }),
473
- }, 20_000)
474
- if (!response.ok) return undefined
475
- return await response.json()
476
- } catch {
477
- return undefined
478
- }
479
- }
480
-
481
- /** 共享入口:命中缓存或复用在途请求;失败(undefined)不写缓存。 */
482
- function fetchClientConfigs(credential, fetchImpl) {
483
- /**
484
- * 缓存/in-flight 去重只对**全局 fetch** 生效:注入的 fetchImpl 几乎都是测试
485
- * mock,没有稳定可区分的身份标识,按函数名拼 key 会串味 —— 直接透传。
486
- */
487
- if (fetchImpl !== globalThis.fetch) return fetchClientConfigsOnce(credential, fetchImpl)
488
- const key = String(credential?.zcode_jwt ?? '')
489
- const hit = clientConfigsCache.get(key)
490
- if (hit !== undefined && Date.now() - hit.at < CLIENT_CONFIGS_CACHE_MS) return hit.promise
491
- const pending = clientConfigsInflight.get(key)
492
- if (pending !== undefined) return pending
493
- const promise = fetchClientConfigsOnce(credential, fetchImpl).then((parsed) => {
494
- clientConfigsInflight.delete(key)
495
- if (parsed !== undefined) clientConfigsCache.set(key, { at: Date.now(), promise: Promise.resolve(parsed) })
496
- return parsed
497
- })
498
- clientConfigsInflight.set(key, promise)
499
- return promise
500
- }
501
-
502
- /**
503
- * 拉服务端下发的 captcha 配置(60 秒 TTL,失败返回 undefined 由调用方回退兜底值)。
504
- *
505
- * ⚠ `platform` 必须是 **`unknown`**(实测 win32/win64/windows/electron/desktop/linux 一律 400 code 3001)。
506
- */
507
- export async function fetchCaptchaConfig(credential, fetchImpl = globalThis.fetch) {
508
- const parsed = await fetchClientConfigs(credential, fetchImpl)
509
- if (parsed === undefined) return undefined
510
- const captcha = parsed.data?.configs?.captcha
511
- if (captcha === undefined) return undefined
512
- const { region, prefix, sceneId } = captcha
513
- if (typeof region !== 'string' || typeof prefix !== 'string' || typeof sceneId !== 'string') return undefined
514
- return { region, prefix, sceneId }
515
- }
516
-
517
- /**
518
- * 从上游拉模型目录(含上下文窗口、最大输出、思考档位、视觉能力)。
519
- *
520
- * ⚠ `builtinModels` 是**对象**(键为序号);用 Array.isArray 判定会得到假阴性。
521
- * ⚠ `reasoning.levels` 的键序不是展示序:必须显式排序。
522
- */
523
- export async function fetchModels(credential, fetchImpl = globalThis.fetch) {
524
- const parsed = await fetchClientConfigs(credential, fetchImpl)
525
- if (parsed === undefined) return undefined
526
- const raw = parsed.data?.builtinModels
527
- if (typeof raw !== 'object' || raw === null) return undefined
528
- const entries = Array.isArray(raw) ? raw : Object.values(raw)
529
- const models = []
530
- for (const item of entries) {
531
- if (typeof item !== 'object' || item === null) continue
532
- const id = item.modelId ?? item.id
533
- if (typeof id !== 'string' || id.length === 0) continue
534
- const contextWindow = num(item.contextWindow)
535
- const maxCompletionTokens = num(item.maxCompletionTokens ?? item.maxTokens)
536
- const vision = typeof item.capabilities === 'object' && item.capabilities !== null ? item.capabilities.vision === true : false
537
- let reasoningLevels
538
- let defaultReasoningLevel
539
- if (typeof item.reasoning === 'object' && item.reasoning !== null) {
540
- const levels = item.reasoning.levels
541
- if (typeof levels === 'object' && levels !== null) {
542
- const keys = Object.keys(levels)
543
- if (keys.length > 0) reasoningLevels = orderReasoningLevels(keys)
544
- }
545
- if (typeof item.reasoning.defaultLevel === 'string' && item.reasoning.defaultLevel.length > 0) {
546
- defaultReasoningLevel = item.reasoning.defaultLevel
547
- }
548
- }
549
- models.push({
550
- id,
551
- name: typeof item.name === 'string' && item.name.length > 0 ? item.name : id,
552
- contextWindow: contextWindow !== undefined && contextWindow > 0 ? contextWindow : 200_000,
553
- maxTokens: maxCompletionTokens !== undefined && maxCompletionTokens > 0 ? maxCompletionTokens : 32_768,
554
- supportsImage: vision,
555
- ...(reasoningLevels !== undefined ? { reasoningLevels } : {}),
556
- ...(defaultReasoningLevel !== undefined ? { defaultReasoningLevel } : {}),
557
- })
558
- }
559
- return models.length > 0 ? models : undefined
560
- }
561
-
562
- /** 把档位键排成展示序(不能直接用 JSON 键序)。 */
563
- export function orderReasoningLevels(keys) {
564
- const order = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']
565
- const known = order.filter((level) => keys.includes(level))
566
- const unknown = keys.filter((key) => !order.includes(key))
567
- return [...known, ...unknown]
568
- }
569
-
570
- export { nextUtc8DayStartMs }
1
+ /**
2
+ * 上游 API 客户端:设备授权登录 / 额度 / 领取 / 模型目录 / captcha 配置。
3
+ *
4
+ * 全部判据来自参考实现的实测:
5
+ * - 登录三段式:`POST oauth/cli/init`(Bearer 是**我们自己生成的会话密钥**)→
6
+ * 浏览器完成授权 → `GET oauth/cli/poll/{id}` 拿 `token` / `user.user_id` / `bigmodel.access_token`;
7
+ * - `device_mid` 自己生成即可(服务端不绑定校验,只需稳定);
8
+ * - captcha 配置要 `platform=unknown`(`win32`/`windows`/… 一律 400 code 3001);
9
+ * - 领取前必须补 `app_launch` + `app_daily_active` 上报,否则 preview 恒为空;
10
+ * - `1003` = 已领取过,是**幂等成功**而不是错误。
11
+ */
12
+
13
+ import {
14
+ ZCODE_BILLING_BALANCE_URL,
15
+ ZCODE_BILLING_CLAIM_URL,
16
+ ZCODE_BILLING_PREVIEW_URL,
17
+ ZCODE_CLIENT_CONFIGS_URL,
18
+ ZCODE_EVENT_REPORT_URL,
19
+ ZCODE_MARKETING_TOUCH_URL,
20
+ ZCODE_OAUTH_CLI_INIT_URL,
21
+ ZCODE_ORIGIN,
22
+ ZCODE_APP_VERSION_FALLBACK,
23
+ buildZcodeHeaders,
24
+ generateDeviceMid,
25
+ nextUtc8DayStartMs,
26
+ toEpochMs,
27
+ zcodeCredentialAppVersion,
28
+ zcodeOauthCliPollUrl,
29
+ zcodeVersionGatedAppVersion,
30
+ } from './upstream.js'
31
+
32
+ /** 登录渠道(默认国内站)。 */
33
+ export const ZCODE_LOGIN_PROVIDER = 'bigmodel'
34
+
35
+ /**
36
+ * 两条登录渠道(实测,2026-10-23)。
37
+ *
38
+ * 两者**共用同一套设备授权协议**(同一个 `/api/v1/oauth/cli/init` 与 `poll/{id}`、
39
+ * 相同的响应形状),只在 `provider` 参数与授权站点上不同:
40
+ *
41
+ * | provider | 站点 | authorize_url | 适用 |
42
+ * |---|---|---|---|
43
+ * | `bigmodel` | 国内 智谱 | `bigmodel.cn/login?appId=zcode&redirect=…/callback/bigmodel` | 国内账号 |
44
+ * | `zai` | 国际 Z.AI | `chat.z.ai/api/oauth/authorize?client_id=…&redirect_uri=…/callback/zai` | 国际账号 |
45
+ *
46
+ * ⚠ 非法值会返回 **HTTP 500 `{"code":1000,"msg":"something went wrong"}`**
47
+ * (实测 `z-ai` / `bigmodel-intl` 均如此)—— 所以这里做白名单,不做"猜"。
48
+ */
49
+ export const LOGIN_CHANNELS = Object.freeze({
50
+ bigmodel: Object.freeze({
51
+ provider: 'bigmodel',
52
+ aliases: Object.freeze(['bigmodel', 'cn', 'china', 'domestic', '智谱', '国内']),
53
+ label: '智谱(国内站)',
54
+ site: 'bigmodel.cn',
55
+ apiKeyUrl: 'https://bigmodel.cn/usercenter/proj-mgmt/apikeys',
56
+ accountSettingUrl: 'https://bigmodel.cn/',
57
+ }),
58
+ zai: Object.freeze({
59
+ provider: 'zai',
60
+ aliases: Object.freeze(['zai', 'z-ai', 'intl', 'international', 'global', 'global站', '国际', '海外']),
61
+ label: 'Z.AI(国际站)',
62
+ site: 'z.ai',
63
+ apiKeyUrl: 'https://z.ai/manage-apikey/apikey-list',
64
+ accountSettingUrl: 'https://chat.z.ai/',
65
+ }),
66
+ })
67
+
68
+ /** 默认渠道。 */
69
+ export const DEFAULT_LOGIN_CHANNEL = 'bigmodel'
70
+
71
+ /**
72
+ * 把用户输入的渠道名(含别名/中文)归一成 `bigmodel` 或 `zai`。
73
+ *
74
+ * @param {string | undefined | null} input
75
+ * @returns {'bigmodel' | 'zai'}
76
+ */
77
+ export function normalizeLoginChannel(input) {
78
+ const needle = String(input ?? '').trim().toLowerCase()
79
+ if (needle.length === 0) return DEFAULT_LOGIN_CHANNEL
80
+ for (const [id, channel] of Object.entries(LOGIN_CHANNELS)) {
81
+ if (id === needle) return /** @type {'bigmodel' | 'zai'} */ (id)
82
+ if (channel.aliases.some((alias) => alias.toLowerCase() === needle)) return /** @type {'bigmodel' | 'zai'} */ (id)
83
+ }
84
+ return DEFAULT_LOGIN_CHANNEL
85
+ }
86
+
87
+ /** 取渠道描述(未知值回退默认)。 */
88
+ export function resolveLoginChannel(input) {
89
+ return LOGIN_CHANNELS[normalizeLoginChannel(input)]
90
+ }
91
+
92
+ /** 一次登录尝试的失败原因(人类可读)。 */
93
+ export class ZcodeLoginError extends Error {
94
+ constructor(message, kind) {
95
+ super(message)
96
+ this.name = 'ZcodeLoginError'
97
+ this.kind = kind
98
+ }
99
+ }
100
+
101
+ /** fetch + 超时包装(外部输入必须有上限)。 */
102
+ async function fetchWithTimeout(fetchImpl, input, init, timeoutMs) {
103
+ const controller = new AbortController()
104
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
105
+ timer.unref?.()
106
+ try {
107
+ return await fetchImpl(input, { ...init, signal: controller.signal })
108
+ } finally {
109
+ clearTimeout(timer)
110
+ }
111
+ }
112
+
113
+ const num = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : undefined)
114
+
115
+ /**
116
+ * 发起登录:立刻拿到 `authorize_url`。
117
+ *
118
+ * ⚠ 授权 URL 必须**立刻**返回(浏览器 `window.open` 只在用户手势窗口内有效)。
119
+ *
120
+ * @param {typeof fetch} [fetchImpl]
121
+ * @param {{ appVersion?: string, provider?: string, channel?: string }} [options]
122
+ * `channel` 是友好名(`cn`/`intl`/`国内`/`国际` 都认),`provider` 是原始值。
123
+ * 两者都给时 `provider` 优先(保持向后兼容)。
124
+ */
125
+ export async function startZcodeLogin(fetchImpl = globalThis.fetch, options = {}) {
126
+ const flowSecret = globalThis.crypto.randomBytes ? globalThis.crypto.randomBytes(32).toString('hex') : fallbackSecret()
127
+ const appVersion = options.appVersion ?? ZCODE_APP_VERSION_FALLBACK
128
+ const provider = options.provider ?? resolveLoginChannel(options.channel).provider
129
+
130
+ let response
131
+ try {
132
+ response = await fetchImpl(ZCODE_OAUTH_CLI_INIT_URL, {
133
+ method: 'POST',
134
+ headers: {
135
+ /** ⚠ 这里的 Bearer 是**我们自己生成的会话密钥**,不是用户凭据。 */
136
+ Authorization: `Bearer ${flowSecret}`,
137
+ 'Content-Type': 'application/json',
138
+ 'User-Agent': `ZCode/${appVersion}`,
139
+ 'HTTP-Referer': ZCODE_ORIGIN,
140
+ 'X-ZCode-App-Version': appVersion,
141
+ 'X-Platform': 'win32',
142
+ },
143
+ body: JSON.stringify({ provider }),
144
+ signal: AbortSignal.timeout(30_000),
145
+ })
146
+ } catch (error) {
147
+ throw new ZcodeLoginError(
148
+ `无法连接 ZCode 授权服务:${error instanceof Error ? error.message : String(error)}`,
149
+ 'init',
150
+ )
151
+ }
152
+
153
+ const text = await response.text().catch(() => '')
154
+ if (!response.ok) {
155
+ /**
156
+ * 非法 provider 会返回 500 code=1000("something went wrong")—— 把这句话翻译成
157
+ * 可操作的原因,避免用户以为服务挂了。
158
+ */
159
+ const hint = /code"?\s*:\s*1000/.test(text) || response.status === 500
160
+ ? `;渠道「${provider}」可能不被支持(合法值:bigmodel=国内、zai=国际)`
161
+ : ''
162
+ throw new ZcodeLoginError(`授权初始化失败(HTTP ${response.status}${hint}):${text.slice(0, 200)}`, 'init')
163
+ }
164
+ let parsed
165
+ try {
166
+ parsed = JSON.parse(text)
167
+ } catch {
168
+ throw new ZcodeLoginError(`授权初始化响应不是 JSON:${text.slice(0, 200)}`, 'init')
169
+ }
170
+ const data = parsed.data
171
+ const flowId = data?.flow_id
172
+ const authorizeUrl = data?.authorize_url
173
+ if (typeof flowId !== 'string' || flowId.length === 0) {
174
+ throw new ZcodeLoginError(`授权初始化响应缺 flow_id:${typeof parsed.msg === 'string' ? parsed.msg : text.slice(0, 160)}`, 'init')
175
+ }
176
+ if (typeof authorizeUrl !== 'string' || !authorizeUrl.startsWith('https://')) {
177
+ throw new ZcodeLoginError('授权初始化响应缺合法的 authorize_url', 'init')
178
+ }
179
+ /** ⚠ 服务端给的是**秒级**时间戳,必须归一再与毫秒比较。 */
180
+ const expiresAt = toEpochMs(typeof data?.expires_at === 'number' ? data.expires_at : 0)
181
+ const rawInterval = typeof data?.poll_interval_sec === 'number' ? data.poll_interval_sec : 2
182
+ const pollIntervalSec = Number.isFinite(rawInterval) && rawInterval >= 1 ? rawInterval : 2
183
+ return { flowId, authorizeUrl, expiresAt, pollIntervalSec, flowSecret }
184
+ }
185
+
186
+ function fallbackSecret() {
187
+ const bytes = new Uint8Array(32)
188
+ globalThis.crypto.getRandomValues(bytes)
189
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')
190
+ }
191
+
192
+ /**
193
+ * 轮询一次。
194
+ *
195
+ * ⚠ 网络抖动**不算失败**(返回 pending 让调用方继续轮询);
196
+ * HTTP 4xx(除 408/429)才是终态失败;5xx 与网络错误继续重试。
197
+ */
198
+ export async function pollZcodeLogin(flow, fetchImpl = globalThis.fetch, appVersion = ZCODE_APP_VERSION_FALLBACK) {
199
+ let response
200
+ try {
201
+ response = await fetchImpl(zcodeOauthCliPollUrl(flow.flowId), {
202
+ method: 'GET',
203
+ headers: {
204
+ Authorization: `Bearer ${flow.flowSecret}`,
205
+ 'User-Agent': `ZCode/${appVersion}`,
206
+ 'HTTP-Referer': ZCODE_ORIGIN,
207
+ 'X-ZCode-App-Version': appVersion,
208
+ },
209
+ signal: AbortSignal.timeout(20_000),
210
+ })
211
+ } catch {
212
+ return { kind: 'pending' }
213
+ }
214
+
215
+ if (response.status >= 400 && response.status < 500 && response.status !== 408 && response.status !== 429) {
216
+ const text = await response.text().catch(() => '')
217
+ return { kind: 'failed', message: `轮询被拒(HTTP ${response.status}):${text.slice(0, 200)}` }
218
+ }
219
+ if (!response.ok) return { kind: 'pending' }
220
+
221
+ let parsed
222
+ try {
223
+ parsed = await response.json()
224
+ } catch {
225
+ return { kind: 'pending' }
226
+ }
227
+ const data = parsed.data
228
+ if (parsed.code !== 0 || data === undefined || data === null) return { kind: 'pending' }
229
+ const status = typeof data.status === 'string' ? data.status : undefined
230
+ if (status === 'pending') return { kind: 'pending' }
231
+ if (status === 'failed') return { kind: 'failed', message: '用户拒绝了授权或授权失败' }
232
+ if (status !== 'ready') return { kind: 'failed', message: `轮询响应状态无法识别:${String(status)}` }
233
+
234
+ /**
235
+ * 容错取值:**两条渠道的字段名不完全一致**(国际站 z.ai 实测不返回
236
+ * `bigmodel.access_token` 之外的同构字段,且 `user_id` 可能落在别的键上)。
237
+ *
238
+ * 判据只看**推理必需**的那两样:`zcode_jwt` 与 `user_id`。
239
+ * `access_token` 是可选的备用身份 —— 缺了不该让登录失败(此前正是因为
240
+ * 把它当成必需字段,国际站授权完成后直接报「缺关键字段」)。
241
+ */
242
+ const pick = (...values) => values.find((value) => typeof value === 'string' && value.length > 0)
243
+
244
+ const zcodeJwt = pick(data.token, data.access_token, data.accessToken)
245
+ const userId = pick(data.user?.user_id, data.user?.id, data.user_id, data.userId, data.uid)
246
+ const bigmodelAccessToken = pick(
247
+ data.bigmodel?.access_token,
248
+ data.bigmodel?.accessToken,
249
+ data.bigmodel_access_token,
250
+ )
251
+
252
+ if (zcodeJwt === undefined) {
253
+ /**
254
+ * 拿不到 JWT 就真的无法推理 —— 但要把「服务端到底给了什么键」报出来,
255
+ * 否则排查只能靠猜(本次国际站的坑就是这样踩到的)。
256
+ */
257
+ const keys = Object.keys(data ?? {}).join(', ') || '(空)'
258
+ return { kind: 'failed', message: `轮询响应里没有 token(实际字段:${keys})` }
259
+ }
260
+ if (userId === undefined) {
261
+ /** 没有 user_id 只影响「按账号去重」,不阻塞入池。 */
262
+ return {
263
+ kind: 'ready',
264
+ result: {
265
+ zcodeJwt,
266
+ userId: zcodeJwt.slice(-12),
267
+ displayName: pick(data.user?.name, data.user?.email, data.account?.name) ?? '未命名账号',
268
+ bigmodelAccessToken: bigmodelAccessToken ?? '',
269
+ note: '响应未返回 user_id,已用 JWT 尾段临时作账号标识(无法按账号去重)',
270
+ },
271
+ }
272
+ }
273
+
274
+ const displayName =
275
+ pick(data.user?.name, data.user?.email, data.user?.username, data.account?.name) ?? userId
276
+ return { kind: 'ready', result: { zcodeJwt, userId, displayName, bigmodelAccessToken: bigmodelAccessToken ?? '' } }
277
+ }
278
+
279
+ /**
280
+ * 两段式登录:立即返回授权 URL,授权完成由 `result` 兑现。
281
+ *
282
+ * @param {{ fetchImpl?: typeof fetch, appVersion?: string, signal?: AbortSignal, now?: () => number, sleep?: (ms: number) => Promise<void>, channel?: string, provider?: string }} [options]
283
+ */
284
+ export async function beginZcodeLogin(options = {}) {
285
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch
286
+ const appVersion = options.appVersion ?? ZCODE_APP_VERSION_FALLBACK
287
+ const now = options.now ?? (() => Date.now())
288
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => {
289
+ const timer = setTimeout(resolve, ms)
290
+ timer.unref?.()
291
+ }))
292
+ const channelId = normalizeLoginChannel(options.provider ?? options.channel)
293
+
294
+ const flow = await startZcodeLogin(fetchImpl, { appVersion, channel: channelId })
295
+ const result = (async () => {
296
+ const deadline = flow.expiresAt > 0 ? flow.expiresAt : now() + 600_000
297
+ for (;;) {
298
+ if (options.signal?.aborted === true) throw new ZcodeLoginError('登录已取消', 'cancelled')
299
+ if (now() >= deadline) throw new ZcodeLoginError('授权超时(请重新发起登录)', 'timeout')
300
+ const outcome = await pollZcodeLogin(flow, fetchImpl, appVersion)
301
+ if (outcome.kind === 'ready') {
302
+ return {
303
+ zcode_jwt: outcome.result.zcodeJwt,
304
+ /** ⚠ 自己生成(服务端不绑定校验);生成后持久化,登录一次即固定。 */
305
+ device_mid: generateDeviceMid(),
306
+ user_id: outcome.result.userId,
307
+ bigmodel_access_token: outcome.result.bigmodelAccessToken,
308
+ account_label: outcome.result.displayName,
309
+ app_version: appVersion,
310
+ /** 记下这条凭据来自哪条渠道(国内/国际),便于状态展示与排查。 */
311
+ login_channel: channelId,
312
+ source: 'plugin',
313
+ }
314
+ }
315
+ if (outcome.kind === 'failed') throw new ZcodeLoginError(outcome.message, 'denied')
316
+ await sleep(Math.max(1, flow.pollIntervalSec) * 1_000)
317
+ }
318
+ })()
319
+ return { loginUrl: flow.authorizeUrl, result, channel: LOGIN_CHANNELS[channelId] }
320
+ }
321
+
322
+ /**
323
+ * 查该账号**已领取**的 plan 记录(`billing/balance` 的 `data.plans[]`)。
324
+ *
325
+ * ## 为什么需要(2026-10-31 实测)
326
+ *
327
+ * 服务端行为:**领取成功后 `marketing/touch` 不再给该账号投放**(deliveries 变空)。
328
+ * 只看投放的话,已领账号显示「无可领」、未领账号显示「可领」——面板参差不齐。
329
+ * 领取记录在这里可查,用来给已领活动回填「已领取」标记与元数据。
330
+ *
331
+ * ## 数据形状(2026-11-03/07 原始响应实测)
332
+ *
333
+ * ```
334
+ * data.plans[]: { plan_id, name: "ZCODE WEEKEND BUILD", status: "active",
335
+ * starts_at(s), ends_at(s), priority,
336
+ * entitlements: [{ show_name: "GLM-5.3-Flash", unit_type: "token",
337
+ * grant_units, effective_at(s) }] }
338
+ * data.balances[]: 到账后的额度桶(expires_at(s))
339
+ * ```
340
+ *
341
+ * ## ⚠ 历史教训:不要发明上游没有的字段
342
+ *
343
+ * 曾有一版实现扫「`data.plans[]` + `data.pending[]`」并把 camelCase
344
+ * (`planId/grantUnits`)也当上游形态处理 —— 那是把**插件自己派生的**
345
+ * `balance.pending`(`fetchBalance` 从 entitlements 算出的未生效额度,见 0.4.7)
346
+ * 误当成上游字段所致。上游 `billing/balance` **没有**顶层 `pending`。
347
+ * 「已领未生效」的判据是:entitlements 的 `effective_at`(**秒**)晚于
348
+ * `server_time`(秒),归一用 `toEpochMs`。
349
+ *
350
+ * ⚠ 多条 entitlement 按 unit_type 求和(与 0.6.x「1024 活动两条 entitlement
351
+ * 少报 2 亿」的教训一致:不同单位不混加,宁可少报)。
352
+ * ⚠ 名称取 plan 行的 `name`(活动名,如 "ZCODE WEEKEND BUILD");
353
+ * `show_name` 是模型名(GLM-5.3-Flash),语义不同不要混用。
354
+ *
355
+ * @param {any} credential
356
+ * @param {typeof fetch} [fetchImpl]
357
+ * @returns {Promise<Map<string, { plan_id: string, claimed: true, name?: string,
358
+ * unitType?: string, grantUnits?: number, effectiveAt?: number, expiresAt?: number,
359
+ * pending: boolean, priority?: number, status?: string }>>}
360
+ * 已领取 plan 的元数据(查询失败 = 空 Map,不抛)
361
+ */
362
+ export async function fetchClaimedPlans(credential, fetchImpl = globalThis.fetch) {
363
+ try {
364
+ const response = await fetchWithTimeout(fetchImpl, ZCODE_BILLING_BALANCE_URL, {
365
+ method: 'GET',
366
+ headers: buildZcodeHeaders(credential, { authorization: `Bearer ${credential.zcode_jwt}` }),
367
+ }, 20_000)
368
+ if (!response.ok) return new Map()
369
+ const parsed = await response.json().catch(() => undefined)
370
+ const data = parsed?.data
371
+ const serverTimeSec = num(data?.server_time) ?? Math.floor(Date.now() / 1000)
372
+ const out = new Map()
373
+ const rows = Array.isArray(data?.plans) ? data.plans : []
374
+ for (const row of rows) {
375
+ if (row === null || typeof row !== 'object') continue
376
+ const planId = typeof row.plan_id === 'string' ? row.plan_id.trim() : ''
377
+ if (planId.length === 0) continue
378
+ /** 同 unit_type 求和;不同单位不混加(宁可少报)。effective_at 取最早一条。 */
379
+ let grantUnits
380
+ let unitType
381
+ let effectiveAtSec
382
+ const entitlements = Array.isArray(row.entitlements) ? row.entitlements : []
383
+ for (const ent of entitlements) {
384
+ if (ent === null || typeof ent !== 'object') continue
385
+ const units = num(ent.grant_units)
386
+ const type = typeof ent.unit_type === 'string' && ent.unit_type.length > 0 ? ent.unit_type : undefined
387
+ if (units !== undefined) {
388
+ if (unitType === undefined) unitType = type
389
+ if (type === unitType) grantUnits = (grantUnits ?? 0) + units
390
+ }
391
+ const eff = num(ent.effective_at)
392
+ if (eff !== undefined && (effectiveAtSec === undefined || eff < effectiveAtSec)) effectiveAtSec = eff
393
+ }
394
+ const endsAt = num(row.ends_at)
395
+ const priority = num(row.priority)
396
+ out.set(planId, {
397
+ plan_id: planId,
398
+ claimed: true,
399
+ ...(typeof row.name === 'string' && row.name.length > 0 ? { name: row.name } : {}),
400
+ ...(unitType !== undefined ? { unitType } : {}),
401
+ ...(grantUnits !== undefined ? { grantUnits } : {}),
402
+ ...(effectiveAtSec !== undefined ? { effectiveAt: toEpochMs(effectiveAtSec) } : {}),
403
+ ...(endsAt !== undefined ? { expiresAt: toEpochMs(endsAt) } : {}),
404
+ ...(priority !== undefined ? { priority } : {}),
405
+ /** 「已领未生效」= 生效点还没到(秒级比较,与上游 server_time 同单位)。 */
406
+ pending: effectiveAtSec !== undefined && effectiveAtSec > serverTimeSec,
407
+ ...(typeof row.status === 'string' ? { status: row.status } : {}),
408
+ })
409
+ }
410
+ return out
411
+ } catch {
412
+ return new Map()
413
+ }
414
+ }
415
+
416
+ /**
417
+ * 兼容旧调用方:只要 plan_id 集合。
418
+ * @deprecated 用 {@link fetchClaimedPlans}(它还带回元数据,回填不再丢名称/额度)。
419
+ */
420
+ export async function fetchClaimedPlanIds(credential, fetchImpl = globalThis.fetch) {
421
+ const plans = await fetchClaimedPlans(credential, fetchImpl)
422
+ return new Set(plans.keys())
423
+ }
424
+
425
+ /**
426
+ * 查余额。
427
+ *
428
+ * ⚠ `Authorization` 必需(缺则 401);`X-Device-Mid` 也必需(缺则 400 code 3001)。
429
+ * 企业版不下发额度数字(`displayMode: "enterprise"`)—— 返回 `{enterprise:true}`,
430
+ * **不要**显示成 0(0 是「已用光」的语义)。
431
+ */
432
+ export async function fetchBalance(credential, fetchImpl = globalThis.fetch) {
433
+ const response = await fetchWithTimeout(fetchImpl, ZCODE_BILLING_BALANCE_URL, {
434
+ method: 'GET',
435
+ headers: buildZcodeHeaders(credential, { authorization: `Bearer ${credential.zcode_jwt}` }),
436
+ }, 30_000)
437
+ if (!response.ok) return undefined
438
+ let parsed
439
+ try {
440
+ parsed = await response.json()
441
+ } catch {
442
+ return undefined
443
+ }
444
+ const data = parsed.data
445
+ if (data === undefined) return undefined
446
+ if (typeof data.displayMode === 'string' && data.displayMode === 'enterprise') {
447
+ return { enterprise: true, buckets: [], remaining: 0, total: 0 }
448
+ }
449
+ const buckets = []
450
+ for (const item of Array.isArray(data.balances) ? data.balances : []) {
451
+ if (typeof item !== 'object' || item === null) continue
452
+ buckets.push({
453
+ planId: typeof item.plan_id === 'string' ? item.plan_id : undefined,
454
+ showName: typeof item.show_name === 'string' ? item.show_name : undefined,
455
+ unitType: typeof item.unit_type === 'string' ? item.unit_type : undefined,
456
+ totalUnits: num(item.total_units),
457
+ usedUnits: num(item.used_units),
458
+ remainingUnits: num(item.remaining_units),
459
+ availableUnits: num(item.available_units),
460
+ /**
461
+ * ⚠ 上游给的是**秒级**,统一归一到毫秒(与 `pending[].effectiveAt` 同单位)。
462
+ * 不归一会让 `new Date(x)` 落到 1970 年 —— 界面上就是「1970/1/21 到期」。
463
+ */
464
+ expiresAt: toEpochMs(num(item.expires_at) ?? 0),
465
+ })
466
+ }
467
+ /**
468
+ * 未生效的**计划权益**(pending entitlements)。
469
+ *
470
+ * 上游把「已领但还没到点」的额度放在 `plans[].entitlements[]`:
471
+ * `balances` 只列**当前生效**的桶 —— 一个 23 点启用的 3 亿 token 包在 22 点的
472
+ * `balances` 里不存在,于是面板显示 0/0,用户以为领取失败(2026-10-26 实测)。
473
+ * 判据:`effective_at`(秒级)在 `server_time`(缺省取本地现在)之后,
474
+ * 且 `grant_units` 为正数。已生效的 entitlement 不收(balances 已覆盖)。
475
+ */
476
+ const serverNowMs = toEpochMs(num(data.server_time) ?? 0) || Date.now()
477
+ const pending = []
478
+ for (const plan of Array.isArray(data.plans) ? data.plans : []) {
479
+ if (typeof plan !== 'object' || plan === null) continue
480
+ for (const item of Array.isArray(plan.entitlements) ? plan.entitlements : []) {
481
+ if (typeof item !== 'object' || item === null) continue
482
+ const effectiveAtMs = toEpochMs(num(item.effective_at) ?? 0)
483
+ const grantUnits = num(item.grant_units)
484
+ if (effectiveAtMs === 0 || !(grantUnits > 0) || effectiveAtMs <= serverNowMs) continue
485
+ /** 未生效权益的到期时间 = 所属 plan 的 `ends_at`(整份 plan 一起作废)。 */
486
+ const planEndsAtMs = toEpochMs(num(plan.ends_at) ?? 0)
487
+ pending.push({
488
+ planId: typeof plan.plan_id === 'string' ? plan.plan_id : undefined,
489
+ showName: typeof item.show_name === 'string' ? item.show_name : undefined,
490
+ unitType: typeof item.unit_type === 'string' ? item.unit_type : undefined,
491
+ grantUnits,
492
+ effectiveAt: effectiveAtMs,
493
+ ...(planEndsAtMs > 0 ? { expiresAt: planEndsAtMs } : {}),
494
+ })
495
+ }
496
+ }
497
+ pending.sort((a, b) => a.effectiveAt - b.effectiveAt)
498
+ let remaining = 0
499
+ let total = 0
500
+ for (const bucket of buckets) {
501
+ const available = bucket.availableUnits ?? bucket.remainingUnits ?? 0
502
+ remaining += available
503
+ total += bucket.totalUnits ?? 0
504
+ }
505
+ /**
506
+ * 有余额的桶按到期时间升序(面板逐桶画条,每桶带自己的到期时间;
507
+ * 空桶沉底)。顶层 `expiresAt` 保留为「最早到期」的快捷值,兼容旧面板。
508
+ */
509
+ const active = buckets
510
+ .filter((bucket) => (bucket.availableUnits ?? bucket.remainingUnits ?? 0) > 0)
511
+ .sort((a, b) => (a.expiresAt || Infinity) - (b.expiresAt || Infinity))
512
+ const empty = buckets.filter((bucket) => (bucket.availableUnits ?? bucket.remainingUnits ?? 0) <= 0)
513
+ const ordered = [...active, ...empty]
514
+ let expiresAt
515
+ for (const bucket of active) {
516
+ if (Number.isFinite(bucket.expiresAt) && bucket.expiresAt > 0) {
517
+ expiresAt = bucket.expiresAt
518
+ break
519
+ }
520
+ }
521
+ return {
522
+ buckets: ordered,
523
+ remaining,
524
+ total,
525
+ ...(pending.length > 0 ? { pending } : {}),
526
+ ...(expiresAt !== undefined ? { expiresAt } : {}),
527
+ ...(buckets[0]?.showName !== undefined ? { planName: buckets[0].showName } : {}),
528
+ }
529
+ }
530
+
531
+ /** 补客户端活跃信号(不补则 preview 恒为空 plans)。 */
532
+ export async function reportActivation(credential, fetchImpl = globalThis.fetch) {
533
+ const appVersion = credential.app_version ?? ZCODE_APP_VERSION_FALLBACK
534
+ /** 两个事件相互独立,并行上报(省一个 RTT;失败不阻塞,下次调用会再补)。 */
535
+ await Promise.all(['app_launch', 'app_daily_active'].map((event) =>
536
+ fetchWithTimeout(fetchImpl, ZCODE_EVENT_REPORT_URL, {
537
+ method: 'POST',
538
+ headers: buildZcodeHeaders(credential, { json: true }),
539
+ body: JSON.stringify({ event, device_mid: credential.device_mid, platform: 'win32', app_version: appVersion }),
540
+ }, 20_000).catch(() => {}),
541
+ ))
542
+ }
543
+
544
+ /**
545
+ * 查当前可领的活动 —— **双来源合并**(0.8.0,对齐参考实现 zcode-upstream.ts 的
546
+ * `fetchAllClaimablePlans`)。
547
+ *
548
+ * ## 为什么要两个来源(参考实现用户报障:1024 活动领不到)
549
+ *
550
+ * | 来源 | 端点 | 实测 |
551
+ * |---|---|---|
552
+ * | 每日赠送 | `GET /billing/preview` | `plans` 里有每日包;1024 活动不在这里 |
553
+ * | **营销投放** | `GET /marketing/touch` | 1024 活动只在这里 |
554
+ *
555
+ * ⚠ **版本门控**:两个请求都必须把 `X-ZCode-App-Version` 抬到 ≥3.16.3 ——
556
+ * `3.14.3` 时投放恒空、claim 回 `1004 no permission`(同账号同头只改版本实测)。
557
+ *
558
+ * ⚠ 顺序与失败隔离:preview 先(主路径),marketing 后(补充,失败降级 `[]`);
559
+ * 同 planId 以 preview 为准,只把 marketing 的 `campaignId` 补进去(否则领完不回执)。
560
+ *
561
+ * @param {any} credential
562
+ * @param {typeof fetch} [fetchImpl]
563
+ * @returns {Promise<Array<{ planId: string, campaignId?: string, priority: number, name?: string }>>}
564
+ */
565
+ export async function fetchClaimablePlans(credential, fetchImpl = globalThis.fetch) {
566
+ const preview = await fetchPreviewPlans(credential, fetchImpl)
567
+ const marketing = await fetchMarketingPlans(credential, fetchImpl)
568
+ const byId = new Map()
569
+ for (const plan of preview) if (!byId.has(plan.planId)) byId.set(plan.planId, plan)
570
+ for (const plan of marketing) {
571
+ const existing = byId.get(plan.planId)
572
+ if (existing === undefined) {
573
+ byId.set(plan.planId, plan)
574
+ continue
575
+ }
576
+ if (existing.campaignId === undefined && plan.campaignId !== undefined) {
577
+ byId.set(plan.planId, { ...existing, campaignId: plan.campaignId })
578
+ }
579
+ }
580
+ return [...byId.values()].sort((a, b) => b.priority - a.priority)
581
+ }
582
+
583
+ /** 每日赠送来源(`/billing/preview`;参考实现实测每日包只在这里)。 */
584
+ async function fetchPreviewPlans(credential, fetchImpl) {
585
+ const appVersion = zcodeCredentialAppVersion(credential)
586
+ const url = `${ZCODE_BILLING_PREVIEW_URL}?app_version=${encodeURIComponent(appVersion)}&platform=win32`
587
+ let parsed
588
+ try {
589
+ const response = await fetchWithTimeout(fetchImpl, url, {
590
+ method: 'GET',
591
+ headers: buildZcodeHeaders(credential, { json: false, appVersion }),
592
+ }, 25_000)
593
+ if (!response.ok) return []
594
+ parsed = await response.json().catch(() => undefined)
595
+ } catch {
596
+ return []
597
+ }
598
+ const raw = Array.isArray(parsed?.data?.plans) ? parsed.data.plans : []
599
+ const plans = []
600
+ for (const item of raw) {
601
+ if (typeof item !== 'object' || item === null) continue
602
+ if (typeof item.plan_id !== 'string' || item.plan_id.length === 0) continue
603
+ plans.push({
604
+ planId: item.plan_id,
605
+ priority: num(item.priority) ?? 0,
606
+ ...(typeof item.name === 'string' ? { name: item.name } : {}),
607
+ })
608
+ }
609
+ return plans
610
+ }
611
+
612
+ /**
613
+ * 营销投放来源(`/marketing/touch`)。
614
+ *
615
+ * ⚠ 投送物里的 plan 元数据**镜像多处**(banner 的 background.args、success_popup
616
+ * 的 hero.args 等 —— 参考实现实测),解析必须**递归扫描**整个投送物,
617
+ * 写死按钮路径会在下一次投放改版时静默失效(少报额度、不发回执)。
618
+ */
619
+ async function fetchMarketingPlans(credential, fetchImpl) {
620
+ try {
621
+ const response = await fetchWithTimeout(fetchImpl, `${ZCODE_MARKETING_TOUCH_URL}?seq=0`, {
622
+ method: 'GET',
623
+ headers: buildZcodeHeaders(credential, {
624
+ authorization: `Bearer ${credential.zcode_jwt}`,
625
+ json: false,
626
+ /** 版本门控:低版本 → deliveries 恒空(与「没活动」同形)。 */
627
+ appVersion: zcodeVersionGatedAppVersion(credential),
628
+ extra: { 'X-Client-Language': 'zh-CN' },
629
+ }),
630
+ }, 20_000)
631
+ if (!response.ok) return []
632
+ const parsed = await response.json().catch(() => undefined)
633
+ return claimablePlansFromMarketingDeliveries(parsed?.data?.deliveries)
634
+ } catch {
635
+ return []
636
+ }
637
+ }
638
+
639
+ /** 递归扫描深度上限(投送物是服务端可控的任意 JSON,递归必须有界)。 */
640
+ const MARKETING_SCAN_MAX_DEPTH = 8
641
+
642
+ /** 把投送物里 `entitlements[]` 的 `grant_units` 求和(**同 unit_type 才相加**)。 */
643
+ function sumMarketingGrantUnits(plan) {
644
+ const raw = plan.entitlements
645
+ if (!Array.isArray(raw)) return {}
646
+ let units = 0
647
+ let unitType
648
+ let saw = false
649
+ for (const item of raw) {
650
+ if (item === null || typeof item !== 'object') continue
651
+ const value = num(item.grant_units)
652
+ if (value === undefined) continue
653
+ const type = typeof item.unit_type === 'string' && item.unit_type.length > 0 ? item.unit_type : undefined
654
+ if (unitType === undefined) unitType = type
655
+ /** 单位不同不混加(宁可少报,也不把 token 与积分加成一个数)。 */
656
+ if (type !== unitType) continue
657
+ units += value
658
+ saw = true
659
+ }
660
+ return saw ? { units, unitType } : { unitType }
661
+ }
662
+
663
+ /**
664
+ * 收集投送物里所有「形如 plan」的对象(按 plan_id 索引)。
665
+ * plan 元数据镜像在投送物多处(参考实现实证),递归找才不会漏。
666
+ */
667
+ function collectMarketingPlanMetas(root) {
668
+ const out = new Map()
669
+ const visit = (node, depth) => {
670
+ if (depth > MARKETING_SCAN_MAX_DEPTH || node === null || typeof node !== 'object') return
671
+ if (Array.isArray(node)) {
672
+ for (const item of node) visit(item, depth + 1)
673
+ return
674
+ }
675
+ const planId = node.plan_id
676
+ if (typeof planId === 'string' && planId.length > 0) {
677
+ const meta = out.get(planId) ?? {}
678
+ if (typeof node.name === 'string' && node.name.length > 0) meta.name = node.name
679
+ const priority = num(node.priority)
680
+ if (priority !== undefined && meta.priority === undefined) meta.priority = priority
681
+ const grant = sumMarketingGrantUnits(node)
682
+ if (grant.units !== undefined) {
683
+ meta.grantUnits = grant.units
684
+ meta.unitType = grant.unitType
685
+ }
686
+ out.set(planId, meta)
687
+ }
688
+ for (const value of Object.values(node)) visit(value, depth + 1)
689
+ }
690
+ visit(root, 0)
691
+ return out
692
+ }
693
+
694
+ /**
695
+ * 取投送物里所有按钮:banner 本体 + banner 的 `success_popup` + popup 本体
696
+ * (投放 schema:`resource_position` 二选一,banner 另有 `success_popup`)。
697
+ */
698
+ function marketingButtonsOf(delivery) {
699
+ const out = []
700
+ const pushButtons = (value) => {
701
+ if (!Array.isArray(value)) return
702
+ for (const item of value) {
703
+ if (item !== null && typeof item === 'object') out.push(item)
704
+ }
705
+ }
706
+ const banner = delivery.banner
707
+ if (banner !== null && typeof banner === 'object') {
708
+ pushButtons(banner.buttons)
709
+ if (banner.success_popup !== null && typeof banner.success_popup === 'object') {
710
+ pushButtons(banner.success_popup.buttons)
711
+ }
712
+ }
713
+ if (delivery.popup !== null && typeof delivery.popup === 'object') {
714
+ pushButtons(delivery.popup.buttons)
715
+ }
716
+ return out
717
+ }
718
+
719
+ /**
720
+ * 从营销投送物里取出可领 plan(纯函数,便于单测)。
721
+ *
722
+ * 判据是按钮的 action `{type:'claim_zcode_plan', args:{plan_id}}`。
723
+ * ⚠ 其余 action(close / open_url / navigate / copy_text)一律**不是**领取 ——
724
+ * 把 `close` 当领取会对着空 plan_id 发请求。
725
+ */
726
+ export function claimablePlansFromMarketingDeliveries(deliveries) {
727
+ if (!Array.isArray(deliveries)) return []
728
+ const plans = []
729
+ const seen = new Set()
730
+ for (const delivery of deliveries) {
731
+ if (delivery === null || typeof delivery !== 'object') continue
732
+ const campaignId = typeof delivery.campaign_id === 'string' && delivery.campaign_id.length > 0
733
+ ? delivery.campaign_id
734
+ : undefined
735
+ const metas = collectMarketingPlanMetas(delivery)
736
+ const fallbackPriority = num(delivery.priority) ?? 0
737
+ for (const button of marketingButtonsOf(delivery)) {
738
+ const action = button?.action
739
+ if (action === null || typeof action !== 'object' || action.type !== 'claim_zcode_plan') continue
740
+ const planId = typeof action.args?.plan_id === 'string' ? action.args.plan_id.trim() : ''
741
+ if (planId.length === 0 || seen.has(planId)) continue
742
+ seen.add(planId)
743
+ const meta = metas.get(planId) ?? {}
744
+ const label = typeof button?.text?.content === 'string' ? button.text.content.trim() : ''
745
+ plans.push({
746
+ planId,
747
+ priority: meta.priority ?? fallbackPriority,
748
+ ...(meta.name !== undefined ? { name: meta.name } : label.length > 0 ? { name: label } : {}),
749
+ ...(meta.grantUnits !== undefined ? { grantUnits: meta.grantUnits, unitType: meta.unitType } : {}),
750
+ ...(campaignId !== undefined ? { campaignId } : {}),
751
+ })
752
+ }
753
+ }
754
+ return plans
755
+ }
756
+
757
+ /**
758
+ * 上报营销投放按钮的点击结果(confirm/cancel)。
759
+ *
760
+ * ⚠ **只在领取成功 / 已领取(code 0 / 1003)后发 `confirm`**(参考实现实证):
761
+ * 官方 renderer 在动作成功后立刻回报;不回报的后果不是「少了记账」,而是
762
+ * **服务端会继续重复投放同一个 campaign** ⇒ 每轮都为已领的 plan 再烧一次 captcha。
763
+ * ⚠ 失败时**绝不**发(更不发 cancel)—— 那等于告诉服务端「别再给我看了」,
764
+ * 用户会白丢一次领取机会。
765
+ */
766
+ export async function reportMarketingAction(credential, campaignId, actionType, fetchImpl = globalThis.fetch) {
767
+ if (typeof campaignId !== 'string' || campaignId.length === 0) return
768
+ if (actionType !== 'confirm' && actionType !== 'cancel') return
769
+ try {
770
+ await fetchWithTimeout(fetchImpl, ZCODE_MARKETING_TOUCH_URL.replace(/\/touch$/, '/touch/action'), {
771
+ method: 'POST',
772
+ headers: buildZcodeHeaders(credential, {
773
+ authorization: `Bearer ${credential.zcode_jwt}`,
774
+ json: true,
775
+ appVersion: zcodeVersionGatedAppVersion(credential),
776
+ }),
777
+ body: JSON.stringify({ campaign_id: campaignId, action_type: actionType }),
778
+ }, 15_000).catch(() => {})
779
+ } catch {
780
+ // 统计上报,失败无关紧要。
781
+ }
782
+ }
783
+
784
+ /**
785
+ * 领取一个 plan。
786
+ *
787
+ * ⚠ captcha **一次性**:每个 plan 都必须重新 mint(复用同一个会得 3007)。
788
+ * ⚠ `1003` = 已领取过,是**幂等成功**而不是错误。
789
+ * ⚠ **版本门控**(0.8.0):`X-ZCode-App-Version` 必须抬到 ≥3.16.3 ——
790
+ * `3.14.3` 真机实测 `400 / code 1004 "no permission"`,官方文案是
791
+ * 「当前账号或**客户端版本**不满足领取条件」,不抬版本会被误判成账号没资格。
792
+ * ⚠ `code` 必须认**纯数字字符串**(`{"code":"3012"}` 会吃成 undefined 丢掉风控码)。
793
+ */
794
+ export async function claimPlan(credential, planId, captcha, fetchImpl = globalThis.fetch) {
795
+ let response
796
+ try {
797
+ response = await fetchWithTimeout(fetchImpl, ZCODE_BILLING_CLAIM_URL, {
798
+ method: 'POST',
799
+ headers: buildZcodeHeaders(credential, {
800
+ authorization: `Bearer ${credential.zcode_jwt}`,
801
+ captcha,
802
+ appVersion: zcodeVersionGatedAppVersion(credential),
803
+ }),
804
+ body: JSON.stringify({ plan_id: planId }),
805
+ }, 60_000)
806
+ } catch (error) {
807
+ return { planId, ok: false, message: error instanceof Error ? error.message : String(error) }
808
+ }
809
+ const text = await response.text().catch(() => '')
810
+ let code
811
+ let message
812
+ try {
813
+ const parsed = JSON.parse(text)
814
+ /** `num()` 只认 number;上游会回字符串 code("3012"),必须先 Number 化。 */
815
+ code = num(typeof parsed.code === 'string' && /^\d+$/.test(parsed.code) ? Number(parsed.code) : parsed.code)
816
+ message = typeof parsed.msg === 'string' ? parsed.msg : typeof parsed.message === 'string' ? parsed.message : undefined
817
+ } catch {
818
+ message = text.slice(0, 200)
819
+ }
820
+ const alreadyClaimed = code === 1003
821
+ return {
822
+ planId,
823
+ ...(code !== undefined ? { code } : {}),
824
+ ok: response.ok && (code === 0 || alreadyClaimed),
825
+ ...(alreadyClaimed ? { alreadyClaimed } : {}),
826
+ httpStatus: response.status,
827
+ ...(message !== undefined ? { message } : {}),
828
+ }
829
+ }
830
+
831
+ /**
832
+ * `GET /api/v1/client/configs` 的共享缓存(60s TTL,仅缓存成功结果 + in-flight 去重)。
833
+ *
834
+ * captcha 配置与模型目录**是同一端点的两个字段**,此前两条链路各打一次且缓存
835
+ * 互相独立 —— 这里统一成一次请求、一份缓存。缓存键带上 `zcode_jwt` 与
836
+ * `fetchImpl` 身份:不同账号不串味;测试里逐个注入的 mock fetch 也不互相污染。
837
+ * **失败不缓存**(一次网络抖动不该把 sceneId 固化 60 秒)。
838
+ */
839
+ const CLIENT_CONFIGS_CACHE_MS = 60_000
840
+ const clientConfigsCache = new Map()
841
+ const clientConfigsInflight = new Map()
842
+
843
+ /** 拉一次 client/configs 原文(不缓存);非 2xx / 网络错误 → undefined。 */
844
+ async function fetchClientConfigsOnce(credential, fetchImpl) {
845
+ const appVersion = credential.app_version ?? ZCODE_APP_VERSION_FALLBACK
846
+ const url = `${ZCODE_CLIENT_CONFIGS_URL}?app_version=${encodeURIComponent(appVersion)}&platform=unknown`
847
+ try {
848
+ const response = await fetchWithTimeout(fetchImpl, url, {
849
+ method: 'GET',
850
+ headers: buildZcodeHeaders(credential, { authorization: `Bearer ${credential.zcode_jwt}`, json: false }),
851
+ }, 20_000)
852
+ if (!response.ok) return undefined
853
+ return await response.json()
854
+ } catch {
855
+ return undefined
856
+ }
857
+ }
858
+
859
+ /** 共享入口:命中缓存或复用在途请求;失败(undefined)不写缓存。 */
860
+ function fetchClientConfigs(credential, fetchImpl) {
861
+ /**
862
+ * 缓存/in-flight 去重只对**全局 fetch** 生效:注入的 fetchImpl 几乎都是测试
863
+ * mock,没有稳定可区分的身份标识,按函数名拼 key 会串味 —— 直接透传。
864
+ */
865
+ if (fetchImpl !== globalThis.fetch) return fetchClientConfigsOnce(credential, fetchImpl)
866
+ const key = String(credential?.zcode_jwt ?? '')
867
+ const hit = clientConfigsCache.get(key)
868
+ if (hit !== undefined && Date.now() - hit.at < CLIENT_CONFIGS_CACHE_MS) return hit.promise
869
+ const pending = clientConfigsInflight.get(key)
870
+ if (pending !== undefined) return pending
871
+ const promise = fetchClientConfigsOnce(credential, fetchImpl).then((parsed) => {
872
+ clientConfigsInflight.delete(key)
873
+ if (parsed !== undefined) clientConfigsCache.set(key, { at: Date.now(), promise: Promise.resolve(parsed) })
874
+ return parsed
875
+ })
876
+ clientConfigsInflight.set(key, promise)
877
+ return promise
878
+ }
879
+
880
+ /**
881
+ * 拉服务端下发的 captcha 配置(60 秒 TTL,失败返回 undefined 由调用方回退兜底值)。
882
+ *
883
+ * ⚠ `platform` 必须是 **`unknown`**(实测 win32/win64/windows/electron/desktop/linux 一律 400 code 3001)。
884
+ */
885
+ export async function fetchCaptchaConfig(credential, fetchImpl = globalThis.fetch) {
886
+ const parsed = await fetchClientConfigs(credential, fetchImpl)
887
+ if (parsed === undefined) return undefined
888
+ const captcha = parsed.data?.configs?.captcha
889
+ if (captcha === undefined) return undefined
890
+ const { region, prefix, sceneId } = captcha
891
+ if (typeof region !== 'string' || typeof prefix !== 'string' || typeof sceneId !== 'string') return undefined
892
+ return { region, prefix, sceneId }
893
+ }
894
+
895
+ /**
896
+ * 从上游拉模型目录(含上下文窗口、最大输出、思考档位、视觉能力)。
897
+ *
898
+ * ⚠ `builtinModels` 是**对象**(键为序号);用 Array.isArray 判定会得到假阴性。
899
+ * ⚠ `reasoning.levels` 的键序不是展示序:必须显式排序。
900
+ */
901
+ export async function fetchModels(credential, fetchImpl = globalThis.fetch) {
902
+ const parsed = await fetchClientConfigs(credential, fetchImpl)
903
+ if (parsed === undefined) return undefined
904
+ const raw = parsed.data?.builtinModels
905
+ if (typeof raw !== 'object' || raw === null) return undefined
906
+ const entries = Array.isArray(raw) ? raw : Object.values(raw)
907
+ const models = []
908
+ for (const item of entries) {
909
+ if (typeof item !== 'object' || item === null) continue
910
+ const id = item.modelId ?? item.id
911
+ if (typeof id !== 'string' || id.length === 0) continue
912
+ const contextWindow = num(item.contextWindow)
913
+ const maxCompletionTokens = num(item.maxCompletionTokens ?? item.maxTokens)
914
+ const vision = typeof item.capabilities === 'object' && item.capabilities !== null ? item.capabilities.vision === true : false
915
+ let reasoningLevels
916
+ let defaultReasoningLevel
917
+ if (typeof item.reasoning === 'object' && item.reasoning !== null) {
918
+ const levels = item.reasoning.levels
919
+ if (typeof levels === 'object' && levels !== null) {
920
+ const keys = Object.keys(levels)
921
+ if (keys.length > 0) reasoningLevels = orderReasoningLevels(keys)
922
+ }
923
+ if (typeof item.reasoning.defaultLevel === 'string' && item.reasoning.defaultLevel.length > 0) {
924
+ defaultReasoningLevel = item.reasoning.defaultLevel
925
+ }
926
+ }
927
+ models.push({
928
+ id,
929
+ name: typeof item.name === 'string' && item.name.length > 0 ? item.name : id,
930
+ contextWindow: contextWindow !== undefined && contextWindow > 0 ? contextWindow : 200_000,
931
+ maxTokens: maxCompletionTokens !== undefined && maxCompletionTokens > 0 ? maxCompletionTokens : 32_768,
932
+ supportsImage: vision,
933
+ ...(reasoningLevels !== undefined ? { reasoningLevels } : {}),
934
+ ...(defaultReasoningLevel !== undefined ? { defaultReasoningLevel } : {}),
935
+ })
936
+ }
937
+ return models.length > 0 ? models : undefined
938
+ }
939
+
940
+ /** 把档位键排成展示序(不能直接用 JSON 键序)。 */
941
+ export function orderReasoningLevels(keys) {
942
+ const order = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']
943
+ const known = order.filter((level) => keys.includes(level))
944
+ const unknown = keys.filter((key) => !order.includes(key))
945
+ return [...known, ...unknown]
946
+ }
947
+
948
+ export { nextUtc8DayStartMs }