dsh-zcode-startplan 0.0.0-stage → 0.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +405 -0
- package/LICENSE +674 -0
- package/README.md +404 -2
- package/bin/cli.mjs +450 -0
- package/client.js +716 -0
- package/cordis.patch.yml +32 -0
- package/icon.svg +18 -0
- package/index.js +335 -0
- package/lib/adapter.js +422 -0
- package/lib/anthropic-body.js +469 -0
- package/lib/assemble.js +420 -0
- package/lib/captcha/minter.js +654 -0
- package/lib/captcha/sdk-page.js +20 -0
- package/lib/errors.js +125 -0
- package/lib/local-endpoint.js +352 -0
- package/lib/manage-routes.js +489 -0
- package/lib/pinned-model.js +56 -0
- package/lib/plan-client.js +532 -0
- package/lib/pool.js +478 -0
- package/lib/sse.js +317 -0
- package/lib/stream-translator.js +301 -0
- package/lib/text-heuristics.js +35 -0
- package/lib/upstream-api.js +570 -0
- package/lib/upstream.js +134 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +78 -4
- package/scripts/_cdp-inspect.mjs +54 -0
- package/scripts/asar-list.mjs +66 -0
- package/scripts/bench-toks.mjs +138 -0
- package/scripts/check-compat-rc3.mjs +11 -0
- package/scripts/check-data-dir.mjs +31 -0
- package/scripts/restart-dsh.ps1 +76 -0
- package/scripts/run-tests.mjs +68 -0
- package/scripts/smoke-install.mjs +204 -0
- package/scripts/verify_compat.mjs +64 -0
|
@@ -0,0 +1,570 @@
|
|
|
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 }
|