dsh-zcode-startplan 0.0.0-stage → 0.2.0
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 +108 -0
- package/LICENSE +674 -0
- package/README.md +345 -2
- package/bin/cli.mjs +450 -0
- package/client.js +659 -0
- package/cordis.patch.yml +30 -0
- package/icon.svg +18 -0
- package/index.js +313 -0
- package/lib/adapter.js +286 -0
- package/lib/anthropic-body.js +304 -0
- package/lib/assemble.js +309 -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 +338 -0
- package/lib/manage-routes.js +414 -0
- package/lib/plan-client.js +427 -0
- package/lib/pool.js +467 -0
- package/lib/sse.js +317 -0
- package/lib/stream-translator.js +279 -0
- package/lib/text-heuristics.js +35 -0
- package/lib/upstream-api.js +544 -0
- package/lib/upstream.js +123 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +80 -6
- package/scripts/bench-toks.mjs +138 -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,544 @@
|
|
|
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
|
+
for (const event of ['app_launch', 'app_daily_active']) {
|
|
380
|
+
try {
|
|
381
|
+
await 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)
|
|
386
|
+
} catch {
|
|
387
|
+
// 上报失败不阻塞(下一次调用会再补)。
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** 查当前可领的活动(priority 降序)。 */
|
|
393
|
+
export async function fetchClaimablePlans(credential, fetchImpl = globalThis.fetch) {
|
|
394
|
+
const appVersion = credential.app_version ?? ZCODE_APP_VERSION_FALLBACK
|
|
395
|
+
const url = `${ZCODE_BILLING_PREVIEW_URL}?app_version=${encodeURIComponent(appVersion)}&platform=win32`
|
|
396
|
+
const response = await fetchWithTimeout(fetchImpl, url, {
|
|
397
|
+
method: 'GET',
|
|
398
|
+
headers: buildZcodeHeaders(credential, { json: false }),
|
|
399
|
+
}, 25_000)
|
|
400
|
+
if (!response.ok) return []
|
|
401
|
+
let parsed
|
|
402
|
+
try {
|
|
403
|
+
parsed = await response.json()
|
|
404
|
+
} catch {
|
|
405
|
+
return []
|
|
406
|
+
}
|
|
407
|
+
const raw = Array.isArray(parsed.data?.plans) ? parsed.data.plans : []
|
|
408
|
+
const plans = []
|
|
409
|
+
for (const item of raw) {
|
|
410
|
+
if (typeof item !== 'object' || item === null) continue
|
|
411
|
+
if (typeof item.plan_id !== 'string' || item.plan_id.length === 0) continue
|
|
412
|
+
plans.push({ planId: item.plan_id, priority: num(item.priority) ?? 0, ...(typeof item.name === 'string' ? { name: item.name } : {}) })
|
|
413
|
+
}
|
|
414
|
+
plans.sort((a, b) => b.priority - a.priority)
|
|
415
|
+
return plans
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* 领取一个 plan。
|
|
420
|
+
*
|
|
421
|
+
* ⚠ captcha **一次性**:每个 plan 都必须重新 mint(复用同一个会得 3007)。
|
|
422
|
+
* ⚠ `1003` = 已领取过,是**幂等成功**而不是错误。
|
|
423
|
+
*/
|
|
424
|
+
export async function claimPlan(credential, planId, captcha, fetchImpl = globalThis.fetch) {
|
|
425
|
+
let response
|
|
426
|
+
try {
|
|
427
|
+
response = await fetchWithTimeout(fetchImpl, ZCODE_BILLING_CLAIM_URL, {
|
|
428
|
+
method: 'POST',
|
|
429
|
+
headers: buildZcodeHeaders(credential, { authorization: `Bearer ${credential.zcode_jwt}`, captcha }),
|
|
430
|
+
body: JSON.stringify({ plan_id: planId }),
|
|
431
|
+
}, 60_000)
|
|
432
|
+
} catch (error) {
|
|
433
|
+
return { planId, ok: false, message: error instanceof Error ? error.message : String(error) }
|
|
434
|
+
}
|
|
435
|
+
const text = await response.text().catch(() => '')
|
|
436
|
+
let code
|
|
437
|
+
let message
|
|
438
|
+
try {
|
|
439
|
+
const parsed = JSON.parse(text)
|
|
440
|
+
code = num(parsed.code)
|
|
441
|
+
message = typeof parsed.msg === 'string' ? parsed.msg : typeof parsed.message === 'string' ? parsed.message : undefined
|
|
442
|
+
} catch {
|
|
443
|
+
message = text.slice(0, 200)
|
|
444
|
+
}
|
|
445
|
+
const alreadyClaimed = code === 1003
|
|
446
|
+
return {
|
|
447
|
+
planId,
|
|
448
|
+
...(code !== undefined ? { code } : {}),
|
|
449
|
+
ok: response.ok && (code === 0 || alreadyClaimed),
|
|
450
|
+
...(alreadyClaimed ? { alreadyClaimed } : {}),
|
|
451
|
+
httpStatus: response.status,
|
|
452
|
+
...(message !== undefined ? { message } : {}),
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* 拉服务端下发的 captcha 配置(60 秒 TTL,失败返回 undefined 由调用方回退兜底值)。
|
|
458
|
+
*
|
|
459
|
+
* ⚠ `platform` 必须是 **`unknown`**(实测 win32/win64/windows/electron/desktop/linux 一律 400 code 3001)。
|
|
460
|
+
*/
|
|
461
|
+
export async function fetchCaptchaConfig(credential, fetchImpl = globalThis.fetch) {
|
|
462
|
+
const appVersion = credential.app_version ?? ZCODE_APP_VERSION_FALLBACK
|
|
463
|
+
const url = `${ZCODE_CLIENT_CONFIGS_URL}?app_version=${encodeURIComponent(appVersion)}&platform=unknown`
|
|
464
|
+
try {
|
|
465
|
+
const response = await fetchWithTimeout(fetchImpl, url, {
|
|
466
|
+
method: 'GET',
|
|
467
|
+
headers: buildZcodeHeaders(credential, { authorization: `Bearer ${credential.zcode_jwt}`, json: false }),
|
|
468
|
+
}, 20_000)
|
|
469
|
+
if (!response.ok) return undefined
|
|
470
|
+
const parsed = await response.json()
|
|
471
|
+
const captcha = parsed.data?.configs?.captcha
|
|
472
|
+
if (captcha === undefined) return undefined
|
|
473
|
+
const { region, prefix, sceneId } = captcha
|
|
474
|
+
if (typeof region !== 'string' || typeof prefix !== 'string' || typeof sceneId !== 'string') return undefined
|
|
475
|
+
return { region, prefix, sceneId }
|
|
476
|
+
} catch {
|
|
477
|
+
return undefined
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* 从上游拉模型目录(含上下文窗口、最大输出、思考档位、视觉能力)。
|
|
483
|
+
*
|
|
484
|
+
* ⚠ `builtinModels` 是**对象**(键为序号);用 Array.isArray 判定会得到假阴性。
|
|
485
|
+
* ⚠ `reasoning.levels` 的键序不是展示序:必须显式排序。
|
|
486
|
+
*/
|
|
487
|
+
export async function fetchModels(credential, fetchImpl = globalThis.fetch) {
|
|
488
|
+
const appVersion = credential.app_version ?? ZCODE_APP_VERSION_FALLBACK
|
|
489
|
+
const url = `${ZCODE_CLIENT_CONFIGS_URL}?app_version=${encodeURIComponent(appVersion)}&platform=unknown`
|
|
490
|
+
try {
|
|
491
|
+
const response = await fetchWithTimeout(fetchImpl, url, {
|
|
492
|
+
method: 'GET',
|
|
493
|
+
headers: buildZcodeHeaders(credential, { authorization: `Bearer ${credential.zcode_jwt}`, json: false }),
|
|
494
|
+
}, 20_000)
|
|
495
|
+
if (!response.ok) return undefined
|
|
496
|
+
const parsed = await response.json()
|
|
497
|
+
const raw = parsed.data?.builtinModels
|
|
498
|
+
if (typeof raw !== 'object' || raw === null) return undefined
|
|
499
|
+
const entries = Array.isArray(raw) ? raw : Object.values(raw)
|
|
500
|
+
const models = []
|
|
501
|
+
for (const item of entries) {
|
|
502
|
+
if (typeof item !== 'object' || item === null) continue
|
|
503
|
+
const id = item.modelId ?? item.id
|
|
504
|
+
if (typeof id !== 'string' || id.length === 0) continue
|
|
505
|
+
const contextWindow = num(item.contextWindow)
|
|
506
|
+
const maxCompletionTokens = num(item.maxCompletionTokens ?? item.maxTokens)
|
|
507
|
+
const vision = typeof item.capabilities === 'object' && item.capabilities !== null ? item.capabilities.vision === true : false
|
|
508
|
+
let reasoningLevels
|
|
509
|
+
let defaultReasoningLevel
|
|
510
|
+
if (typeof item.reasoning === 'object' && item.reasoning !== null) {
|
|
511
|
+
const levels = item.reasoning.levels
|
|
512
|
+
if (typeof levels === 'object' && levels !== null) {
|
|
513
|
+
const keys = Object.keys(levels)
|
|
514
|
+
if (keys.length > 0) reasoningLevels = orderReasoningLevels(keys)
|
|
515
|
+
}
|
|
516
|
+
if (typeof item.reasoning.defaultLevel === 'string' && item.reasoning.defaultLevel.length > 0) {
|
|
517
|
+
defaultReasoningLevel = item.reasoning.defaultLevel
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
models.push({
|
|
521
|
+
id,
|
|
522
|
+
name: typeof item.name === 'string' && item.name.length > 0 ? item.name : id,
|
|
523
|
+
contextWindow: contextWindow !== undefined && contextWindow > 0 ? contextWindow : 200_000,
|
|
524
|
+
maxTokens: maxCompletionTokens !== undefined && maxCompletionTokens > 0 ? maxCompletionTokens : 32_768,
|
|
525
|
+
supportsImage: vision,
|
|
526
|
+
...(reasoningLevels !== undefined ? { reasoningLevels } : {}),
|
|
527
|
+
...(defaultReasoningLevel !== undefined ? { defaultReasoningLevel } : {}),
|
|
528
|
+
})
|
|
529
|
+
}
|
|
530
|
+
return models.length > 0 ? models : undefined
|
|
531
|
+
} catch {
|
|
532
|
+
return undefined
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/** 把档位键排成展示序(不能直接用 JSON 键序)。 */
|
|
537
|
+
export function orderReasoningLevels(keys) {
|
|
538
|
+
const order = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']
|
|
539
|
+
const known = order.filter((level) => keys.includes(level))
|
|
540
|
+
const unknown = keys.filter((key) => !order.includes(key))
|
|
541
|
+
return [...known, ...unknown]
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
export { nextUtc8DayStartMs }
|
package/lib/upstream.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 上游协议常量与请求头构造。
|
|
3
|
+
*
|
|
4
|
+
* 全部取自参考实现 bonus-plan-4-open-zcode(`src/pool/upstream.ts`)的实测结论:
|
|
5
|
+
*
|
|
6
|
+
* | 端点 | 需要 Authorization | 需要 X-Device-Mid |
|
|
7
|
+
* |---|---|---|
|
|
8
|
+
* | GET /api/v1/zcode-plan/billing/balance | 是(缺则 401) | 是(缺则 400 code 3001) |
|
|
9
|
+
* | GET /api/v1/zcode-plan/billing/preview | 否 | 是 |
|
|
10
|
+
* | POST /api/v1/event/report | 否 | 是 |
|
|
11
|
+
* | POST /api/v1/zcode-plan/billing/claim | 是 | 是(另需 captcha 头) |
|
|
12
|
+
* | GET /api/v1/client/configs | 是 | 是 |
|
|
13
|
+
* | POST /api/v1/zcode-plan/anthropic/v1/messages | 是(Bearer zcode_jwt) | 是(captcha 视情况) |
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** ZCode 平台 origin。 */
|
|
17
|
+
export const ZCODE_ORIGIN = 'https://zcode.z.ai'
|
|
18
|
+
|
|
19
|
+
/** 免费额度通道的 Anthropic Messages 端点(推理主链路)。 */
|
|
20
|
+
export const ZCODE_PLAN_MESSAGES_URL = `${ZCODE_ORIGIN}/api/v1/zcode-plan/anthropic/v1/messages`
|
|
21
|
+
|
|
22
|
+
/** 额度余额。 */
|
|
23
|
+
export const ZCODE_BILLING_BALANCE_URL = `${ZCODE_ORIGIN}/api/v1/zcode-plan/billing/balance`
|
|
24
|
+
|
|
25
|
+
/** 可领活动预览(不需要 Authorization)。 */
|
|
26
|
+
export const ZCODE_BILLING_PREVIEW_URL = `${ZCODE_ORIGIN}/api/v1/zcode-plan/billing/preview`
|
|
27
|
+
|
|
28
|
+
/** 领取活动(需要 Authorization + 一次性 captcha)。 */
|
|
29
|
+
export const ZCODE_BILLING_CLAIM_URL = `${ZCODE_ORIGIN}/api/v1/zcode-plan/billing/claim`
|
|
30
|
+
|
|
31
|
+
/** 客户端活跃上报(不补则 preview 恒为空 plans)。 */
|
|
32
|
+
export const ZCODE_EVENT_REPORT_URL = `${ZCODE_ORIGIN}/api/v1/event/report`
|
|
33
|
+
|
|
34
|
+
/** 客户端配置(captcha 配置 + 模型池)。 */
|
|
35
|
+
export const ZCODE_CLIENT_CONFIGS_URL = `${ZCODE_ORIGIN}/api/v1/client/configs`
|
|
36
|
+
|
|
37
|
+
/** 设备授权流:发起。 */
|
|
38
|
+
export const ZCODE_OAUTH_CLI_INIT_URL = `${ZCODE_ORIGIN}/api/v1/oauth/cli/init`
|
|
39
|
+
|
|
40
|
+
/** 设备授权流:轮询。 */
|
|
41
|
+
export const zcodeOauthCliPollUrl = (flowId) =>
|
|
42
|
+
`${ZCODE_ORIGIN}/api/v1/oauth/cli/poll/${encodeURIComponent(flowId)}`
|
|
43
|
+
|
|
44
|
+
/** 客户端版本兜底值(官方 3.14.3 时代的取值;服务端只当展示/统计用)。 */
|
|
45
|
+
export const ZCODE_APP_VERSION_FALLBACK = '3.14.3'
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 构造 ZCode 的来源标识请求头。
|
|
49
|
+
*
|
|
50
|
+
* ⚠ `X-Device-Mid` 是 billing/* 与推理端点的硬需求(缺则 400 code 3001),
|
|
51
|
+
* 但**不是账号标识**:同一账号重新登录会换一个,去重必须用 `user_id`。
|
|
52
|
+
*
|
|
53
|
+
* @param {{ device_mid: string, app_version?: string }} credential 凭据(或任何带 device_mid 的对象)
|
|
54
|
+
* @param {{ authorization?: string, json?: boolean, captcha?: { param: string, region: string }, extra?: Record<string,string>, authHeader?: string }} [options]
|
|
55
|
+
* @returns {Record<string, string>}
|
|
56
|
+
*/
|
|
57
|
+
export function buildZcodeHeaders(credential, options = {}) {
|
|
58
|
+
const appVersion = credential.app_version ?? ZCODE_APP_VERSION_FALLBACK
|
|
59
|
+
/** @type {Record<string, string>} */
|
|
60
|
+
const headers = {
|
|
61
|
+
'User-Agent': `ZCode/${appVersion}`,
|
|
62
|
+
'HTTP-Referer': ZCODE_ORIGIN,
|
|
63
|
+
'X-ZCode-App-Version': appVersion,
|
|
64
|
+
'X-Release-Channel': 'stable',
|
|
65
|
+
'X-Client-Language': 'zh-CN',
|
|
66
|
+
'X-Client-Timezone': 'Asia/Shanghai',
|
|
67
|
+
'X-Device-Mid': credential.device_mid,
|
|
68
|
+
'X-Platform': 'win32',
|
|
69
|
+
'X-Os-Category': 'windows',
|
|
70
|
+
'anthropic-version': '2023-06-01',
|
|
71
|
+
}
|
|
72
|
+
if (options.json !== false) headers['Content-Type'] = 'application/json'
|
|
73
|
+
if (options.authorization !== undefined) headers['Authorization'] = options.authorization
|
|
74
|
+
if (options.authHeader !== undefined) headers['Authorization'] = options.authHeader
|
|
75
|
+
if (options.captcha !== undefined) {
|
|
76
|
+
headers['x-aliyun-captcha-verify-param'] = options.captcha.param
|
|
77
|
+
headers['x-aliyun-captcha-verify-region'] = options.captcha.region
|
|
78
|
+
}
|
|
79
|
+
if (options.extra !== undefined) Object.assign(headers, options.extra)
|
|
80
|
+
return headers
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** 生成自用的稳定设备标识。 */
|
|
84
|
+
export function generateDeviceMid() {
|
|
85
|
+
return globalThis.crypto.randomUUID()
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 把服务端时间戳归一成毫秒。
|
|
90
|
+
*
|
|
91
|
+
* ⚠ 服务端的 `expires_at` 是**秒级**(实测 1790746234);与 `Date.now()` 直接比会
|
|
92
|
+
* 立即判超时。小于 1e12 视为秒。
|
|
93
|
+
*/
|
|
94
|
+
export function toEpochMs(value) {
|
|
95
|
+
if (!Number.isFinite(value) || value <= 0) return 0
|
|
96
|
+
return value < 1e12 ? Math.round(value * 1000) : Math.round(value)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 下一个 UTC+8 零点(毫秒):免费额度按自然日结算。 */
|
|
100
|
+
export function nextUtc8DayStartMs(now = new Date()) {
|
|
101
|
+
const OFFSET = 8 * 60 * 60 * 1000
|
|
102
|
+
const shifted = now.getTime() + OFFSET
|
|
103
|
+
const dayStartShifted = Math.floor(shifted / 86_400_000) * 86_400_000
|
|
104
|
+
return dayStartShifted + 86_400_000 - OFFSET
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 兜底模型表(上游 client/configs 不可达时用;数值抄自实测,不是估值)。 */
|
|
108
|
+
export const ZCODE_FALLBACK_MODELS = Object.freeze([
|
|
109
|
+
Object.freeze({
|
|
110
|
+
id: 'GLM-5.3-Flash',
|
|
111
|
+
name: 'GLM-5.3-Flash',
|
|
112
|
+
contextWindow: 1_000_000,
|
|
113
|
+
maxTokens: 128_000,
|
|
114
|
+
supportsImage: true,
|
|
115
|
+
}),
|
|
116
|
+
Object.freeze({
|
|
117
|
+
id: 'GLM-5.3',
|
|
118
|
+
name: 'GLM-5.3',
|
|
119
|
+
contextWindow: 1_000_000,
|
|
120
|
+
maxTokens: 128_000,
|
|
121
|
+
supportsImage: false,
|
|
122
|
+
}),
|
|
123
|
+
])
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "ZCode Start Plan",
|
|
4
|
+
"description": "Route model calls through the ZCode free-plan channel (account:bigmodel-start-plan): multi-account pool, on-demand Aliyun captcha, and automatic account switching on quota exhaustion. Log in with a domestic bigmodel.cn or international z.ai account."
|
|
5
|
+
}
|
|
6
|
+
}
|