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
package/bin/cli.mjs CHANGED
@@ -1,450 +1,509 @@
1
- #!/usr/bin/env node
2
- /**
3
- * `zcode-start-plan` 命令行:在没有 DSH 的情况下完成「登录 / 看状态 / 领取 / 探活」。
4
- *
5
- * 这些操作**不需要** captcha 载体(除 claim 外):登录是纯 HTTP 设备授权流,
6
- * 余额与模型目录是 GET。故 CLI 可以在 Harness 没启动时独立使用。
7
- *
8
- * ```powershell
9
- * node bin/cli.mjs login # 设备授权:打印链接 → 浏览器授权 → 自动入池
10
- * node bin/cli.mjs import "<PATH_TO_ZCODE_JWT>" # 从文件读 JWT(已有 ZCode 登录时)
11
- * node bin/cli.mjs list # 账号列表(不含凭据)
12
- * node bin/cli.mjs status # 账号 + 余额 + 限流标记
13
- * node bin/cli.mjs probe --model GLM-5.3-Flash # 真发一条最小请求,验证全链路
14
- * node bin/cli.mjs claim # 领取当日免费额度(需要 captcha 载体)
15
- * node bin/cli.mjs captcha # 单独产出一次 captcha(诊断用)
16
- * node bin/cli.mjs disable 1 / enable 1 / remove 1
17
- * ```
18
- */
19
-
20
- import { existsSync, readFileSync } from 'node:fs'
21
- import { resolve } from 'node:path'
22
- import { AccountPool, SqliteStore, resolveDbFile, resolveDataDir } from '../lib/pool.js'
23
- import { beginZcodeLogin, fetchBalance, fetchCaptchaConfig, fetchClaimablePlans, fetchModels, claimPlan, reportActivation, resolveLoginChannel, LOGIN_CHANNELS } from '../lib/upstream-api.js'
24
- import { CaptchaMinter } from '../lib/captcha/minter.js'
25
- import { ZcodePlanClient } from '../lib/plan-client.js'
26
- import { generateDeviceMid } from '../lib/upstream.js'
27
-
28
- const args = process.argv.slice(2)
29
- const command = args[0] ?? 'help'
30
-
31
- /** `--flag value` / `--flag=value` 解析。 */
32
- function option(name, fallback) {
33
- const exact = args.indexOf(`--${name}`)
34
- if (exact !== -1 && args[exact + 1] !== undefined) return args[exact + 1]
35
- const prefixed = args.find((arg) => arg.startsWith(`--${name}=`))
36
- if (prefixed !== undefined) return prefixed.slice(name.length + 3)
37
- return fallback
38
- }
39
-
40
- const log = (message) => process.stdout.write(`${message}\n`)
41
- const warn = (message) => process.stderr.write(`${message}\n`)
42
-
43
- /**
44
- * 退出看门狗(必须在任何命令执行前就位)。
45
- *
46
- * ⚠ **只**兜「异常路径上句柄没释放导致进程永不退出」,默认 15 秒。
47
- * 需要长时间等待的命令(`login` 等人工授权)必须先调 `clearExitWatchdog()` ——
48
- * 否则看门狗会在授权完成前杀掉进程,表现为
49
- * `Detected unsettled top-level await` + 退出码 13。
50
- */
51
- const EXIT_WATCHDOG_MS = 15_000
52
- let exitWatchdog = setTimeout(() => {
53
- process.exit(process.exitCode ?? 0)
54
- }, EXIT_WATCHDOG_MS)
55
- /** 不要因为看门狗让进程多活 15 秒:它只是兜底,不持有存活权。 */
56
- exitWatchdog.unref()
57
-
58
- /** 取消看门狗(长任务用)。 */
59
- function clearExitWatchdog() {
60
- clearTimeout(exitWatchdog)
61
- exitWatchdog = undefined
62
- }
63
-
64
- /** 打开账号库 + 账号池。 */
65
- async function openPool() {
66
- const store = await new SqliteStore(resolveDbFile(process.env))
67
- return { store, pool: new AccountPool({ store, log: warn }) }
68
- }
69
-
70
- function maskJwt(jwt) {
71
- if (typeof jwt !== 'string' || jwt.length < 12) return '***'
72
- return `${jwt.slice(0, 6)}…${jwt.slice(-4)}(${jwt.length} 字符)`
73
- }
74
-
75
- function printAccounts(pool) {
76
- const entries = pool.list({ withCredentials: true })
77
- if (entries.length === 0) {
78
- log('账号池为空。先运行:node bin/cli.mjs login')
79
- return entries
80
- }
81
- entries.forEach((entry, index) => {
82
- const limits = Object.keys(entry.model_rate_limits ?? {})
83
- /** 渠道:凭据里记的 login_channel 优先;老凭据没有则显示「未标注」。 */
84
- const channelId = entry.credential?.login_channel
85
- const channelLabel = channelId !== undefined && LOGIN_CHANNELS[channelId] !== undefined
86
- ? LOGIN_CHANNELS[channelId].label
87
- : '未标注'
88
- log(
89
- `[${index + 1}] ${entry.enabled ? '●' : '○'} ${entry.nickname} id=${entry.id.slice(0, 8)} ` +
90
- `渠道=${channelLabel} ` +
91
- `jwt=${maskJwt(entry.credential?.zcode_jwt)} ` +
92
- `device=${entry.credential?.device_mid?.slice(0, 8) ?? '?'} ` +
93
- `${limits.length > 0 ? `限流:${limits.join(',')}` : ''}` +
94
- `${entry.last_error !== undefined ? ` 最近错误:${entry.last_error}` : ''}`,
95
- )
96
- })
97
- return entries
98
- }
99
-
100
- async function cmdLogin() {
101
- const { store, pool } = await openPool()
102
- /**
103
- * 登录渠道:`--channel cn|intl`(也认 `bigmodel`/`zai`/`国内`/`国际`)。
104
- *
105
- * 两条渠道**协议完全一致**,只是 `provider` 与授权站点不同:
106
- * 国内 = bigmodel.cn,国际 = chat.z.ai。账号属于哪边就用哪边登录。
107
- */
108
- const channel = resolveLoginChannel(option('channel', option('provider', undefined)))
109
- /**
110
- * ⚠ 登录必须**取消看门狗**:这个命令的语义就是「一直等到用户在浏览器里点完授权」
111
- * (默认 10 分钟),而看门狗是给「异常路径挂死句柄」用的。不取消的话,
112
- * 15 秒后被强制 exit → 顶层 await 悬空 → 打印 unsettled 警告,且授权永远等不到。
113
- */
114
- clearExitWatchdog()
115
- const deadline = Date.now() + 10 * 60_000
116
- const keepalive = setInterval(() => {
117
- const left = Math.max(0, Math.round((deadline - Date.now()) / 1000))
118
- process.stderr.write(`\r等待授权中… 剩余 ${left}s(Ctrl+C 取消) `)
119
- }, 5_000)
120
- try {
121
- log(`正在向 ZCode 申请设备授权(${channel.label})…`)
122
- const { loginUrl, result } = await beginZcodeLogin({ channel: channel.provider })
123
- log('')
124
- log(`请在浏览器里打开下面这个链接完成授权(用拥有赠送免费 plan 的【${channel.site}】账号):`)
125
- log('')
126
- log(` ${loginUrl}`)
127
- log('')
128
- log('若链接已过期:重跑本命令,或加 --channel intl 切换到国际站。')
129
- const credential = await result
130
- process.stderr.write('\n')
131
- const { entry, created } = pool.add(credential, option('name', undefined))
132
- log(`${created ? '已添加' : '已更新'}账号:${entry.nickname}(id=${entry.id.slice(0, 8)},渠道=${channel.label})`)
133
- log(`数据目录:${resolveDataDir(process.env)}`)
134
- } catch (error) {
135
- process.stderr.write('\n')
136
- warn(`✗ 登录失败:${error instanceof Error ? error.message : String(error)}`)
137
- process.exitCode = 1
138
- } finally {
139
- clearInterval(keepalive)
140
- store.close()
141
- }
142
- }
143
-
144
- async function cmdImport() {
145
- const jwtFile = args[1]
146
- if (jwtFile === undefined) {
147
- warn('用法:node bin/cli.mjs import <含 JWT 的文件路径>')
148
- process.exitCode = 1
149
- return
150
- }
151
- const raw = readFileSync(resolve(jwtFile), 'utf8').trim()
152
- let jwt = raw
153
- /** 容忍把整段 JSON 存进文件的情况(官方客户端的凭据结构)。 */
154
- try {
155
- const parsed = JSON.parse(raw)
156
- jwt = parsed.zcode_jwt ?? parsed.token ?? parsed.data?.token ?? raw
157
- } catch {
158
- // 纯文本就是 JWT。
159
- }
160
- if (typeof jwt !== 'string' || jwt.length < 32) {
161
- warn('文件里没找到像样的 JWT(期望 ≥32 字符的字符串)。')
162
- process.exitCode = 1
163
- return
164
- }
165
- const { store, pool } = await openPool()
166
- try {
167
- const { entry, created } = pool.add(
168
- { zcode_jwt: jwt, device_mid: generateDeviceMid(), account_label: option('name', '导入账号'), source: 'ide' },
169
- option('name', undefined),
170
- )
171
- log(`${created ? '已添加' : '已更新'}账号:${entry.nickname}`)
172
- log('⚠ 导入的账号没有 user_id,无法按账号去重;重复导入会新增条目。')
173
- } finally {
174
- store.close()
175
- }
176
- }
177
-
178
- async function cmdList() {
179
- const { store, pool } = await openPool()
180
- try {
181
- printAccounts(pool)
182
- } finally {
183
- store.close()
184
- }
185
- }
186
-
187
- async function cmdStatus() {
188
- const { store, pool } = await openPool()
189
- try {
190
- const entries = printAccounts(pool)
191
- log('')
192
- for (const entry of entries) {
193
- try {
194
- const balance = await fetchBalance(entry.credential)
195
- if (balance === undefined) {
196
- log(`· ${entry.nickname}:余额查询失败(凭据可能已过期,重新 login 这个账号)`)
197
- } else if (balance.enterprise === true) {
198
- log(`· ${entry.nickname}:企业版(不下发用量数字)`)
199
- } else {
200
- log(
201
- `· ${entry.nickname}:剩余 ${balance.remaining}/${balance.total} ` +
202
- `${balance.planName !== undefined ? `(${balance.planName})` : ''}`,
203
- )
204
- }
205
- } catch (error) {
206
- log(`· ${entry.nickname}:余额查询异常 ${error instanceof Error ? error.message : String(error)}`)
207
- }
208
- }
209
- const first = entries[0]
210
- if (first !== undefined) {
211
- const models = await fetchModels(first.credential)
212
- log('')
213
- log(`上游模型目录${models === undefined ? '(不可达,用兜底表)' : ''}:${(models ?? []).map((model) => model.id).join(', ') || '(空)'}`)
214
- const config = await fetchCaptchaConfig(first.credential)
215
- log(`服务端 captcha 配置:${config === undefined ? '(不可达,用兜底值)' : JSON.stringify(config)}`)
216
- }
217
- log('')
218
- log(`数据目录:${resolveDataDir(process.env)}`)
219
- log(`账号库:${resolveDbFile(process.env)}`)
220
- } finally {
221
- store.close()
222
- }
223
- }
224
-
225
- async function cmdProbe() {
226
- const model = option('model', 'GLM-5.3-Flash')
227
- const { store, pool } = await openPool()
228
- const minter = new CaptchaMinter({ debugPort: Number(option('port', '9229')), log: warn })
229
- try {
230
- if (pool.list().length === 0) {
231
- warn('账号池为空。先运行 login。')
232
- process.exitCode = 1
233
- return
234
- }
235
- const client = new ZcodePlanClient({ pool, minter, log: warn })
236
- const started = Date.now()
237
- const result = await client.call({
238
- options: {
239
- model,
240
- messages: [{ role: 'user', content: [{ type: 'text', text: 'ping(只回复 pong)' }] }],
241
- },
242
- maxTokens: 64,
243
- onRetry: (info) => warn(`重试(${info.reason}):${info.message}`),
244
- })
245
- let text = ''
246
- for (const event of result.head) {
247
- const data = event.data
248
- if (data?.type === 'content_block_delta' && data.delta?.type === 'text_delta') text += data.delta.text
249
- }
250
- if (result.head.decoder !== undefined) {
251
- for (;;) {
252
- const next = await result.head.decoder.read()
253
- if (next.done === true) break
254
- const data = next.value.data
255
- if (data?.type === 'content_block_delta' && data.delta?.type === 'text_delta') text += data.delta.text
256
- }
257
- }
258
- log(`✓ 全链路通过(账号 ${result.accountId.slice(0, 8)},${Date.now() - started}ms)`)
259
- log(` 回复:${text.trim().slice(0, 200) || '(流里没有文本)'}`)
260
- } catch (error) {
261
- warn(`✗ 失败(${error?.code ?? 'ERR'}):${error instanceof Error ? error.message : String(error)}`)
262
- process.exitCode = 1
263
- } finally {
264
- minter.dispose()
265
- store.close()
266
- }
267
- }
268
-
269
- async function cmdCaptcha() {
270
- const minter = new CaptchaMinter({ debugPort: Number(option('port', '9229')), log: warn })
271
- try {
272
- const probe = await minter.probe()
273
- log(`调试端口:${probe.ok ? '可达' : `不可达(${probe.reason})`}`)
274
- if (!probe.ok) {
275
- process.exitCode = 1
276
- return
277
- }
278
- const { store, pool } = await openPool()
279
- try {
280
- const first = pool.list({ withCredentials: true })[0]
281
- const config = first === undefined ? undefined : await fetchCaptchaConfig(first.credential)
282
- const started = Date.now()
283
- const outcome = await minter.mint(config ?? { region: 'cn', prefix: 'no8xfe', sceneId: '11xygtvd' })
284
- log(`✓ captcha 产出成功(${Date.now() - started}ms,param 长度 ${outcome.param.length},交互式=${outcome.interactive})`)
285
- } finally {
286
- store.close()
287
- }
288
- } catch (error) {
289
- warn(`✗ ${error instanceof Error ? error.message : String(error)}`)
290
- process.exitCode = 1
291
- } finally {
292
- minter.dispose()
293
- }
294
- }
295
-
296
- async function cmdClaim() {
297
- const { store, pool } = await openPool()
298
- const minter = new CaptchaMinter({ debugPort: Number(option('port', '9229')), log: warn })
299
- try {
300
- const entries = pool.list({ withCredentials: true })
301
- if (entries.length === 0) {
302
- warn('账号池为空。先运行 login。')
303
- process.exitCode = 1
304
- return
305
- }
306
- const client = new ZcodePlanClient({ pool, minter, log: warn })
307
- for (const entry of entries) {
308
- if (!entry.enabled) continue
309
- log(`· ${entry.nickname}`)
310
- await reportActivation(entry.credential)
311
- const plans = await fetchClaimablePlans(entry.credential)
312
- if (plans.length === 0) {
313
- log(' 今天没有可领的活动(或已领完)')
314
- continue
315
- }
316
- for (const plan of plans) {
317
- /** ⚠ captcha 一次性:每个 plan 必须重新产出。 */
318
- const captcha = await client.mintCaptcha()
319
- const outcome = await claimPlan(entry.credential, plan.planId, captcha)
320
- log(
321
- ` ${outcome.ok ? '✓' : '✗'} ${plan.name ?? plan.planId}` +
322
- `${outcome.alreadyClaimed === true ? '(已领过)' : ''}` +
323
- `${outcome.ok ? '' : ` ${outcome.code ?? outcome.httpStatus ?? ''} ${outcome.message ?? ''}`}`,
324
- )
325
- }
326
- const balance = await fetchBalance(entry.credential)
327
- if (balance !== undefined && balance.enterprise !== true) {
328
- log(` 当前剩余:${balance.remaining}/${balance.total}`)
329
- }
330
- }
331
- } catch (error) {
332
- warn(`✗ ${error instanceof Error ? error.message : String(error)}`)
333
- process.exitCode = 1
334
- } finally {
335
- minter.dispose()
336
- store.close()
337
- }
338
- }
339
-
340
- async function cmdAccountAction(action) {
341
- const reference = args[1]
342
- if (reference === undefined) {
343
- warn(`用法:node bin/cli.mjs ${action} <序号|id|昵称片段>`)
344
- process.exitCode = 1
345
- return
346
- }
347
- const { store, pool } = await openPool()
348
- try {
349
- const entry = pool.resolve(reference)
350
- if (entry === undefined) {
351
- warn(`找不到账号:${reference}(先运行 list 看序号)`)
352
- process.exitCode = 1
353
- return
354
- }
355
- if (action === 'disable') pool.setEnabled(entry.id, false)
356
- else if (action === 'enable') pool.setEnabled(entry.id, true)
357
- else if (action === 'remove') pool.remove(entry.id)
358
- else if (action === 'reset') pool.clearModelRateLimits(entry.id)
359
- log(`已对「${entry.nickname}」执行 ${action}`)
360
- } finally {
361
- store.close()
362
- }
363
- }
364
-
365
- function cmdHelp() {
366
- log(`zcode-start-plan — ZCode 赠送免费 plan 的 DSH 接入
367
-
368
- 用法(在插件目录下运行):
369
- node bin/cli.mjs login [--name 备注] [--channel cn|intl]
370
- 设备授权登录并把账号入池
371
- --channel cn = 智谱国内站 bigmodel.cn(默认)
372
- --channel intl = Z.AI 国际站 z.ai
373
- node bin/cli.mjs import <文件> [--name 备注] 从含 JWT 的文件导入账号
374
- node bin/cli.mjs list 账号列表(脱敏,含来源渠道)
375
- node bin/cli.mjs status 账号 + 余额 + 上游模型目录 + captcha 配置
376
- node bin/cli.mjs probe [--model M] 真发一条最小请求,验证全链路
377
- node bin/cli.mjs claim 领取当日额度(需要 captcha 载体)
378
- node bin/cli.mjs captcha [--port 9229] 单独产出一次 captcha(诊断)
379
- node bin/cli.mjs enable|disable|remove|reset <序号|id|昵称>
380
-
381
- 登录渠道(两条渠道协议相同,选择你的账号所属站点):
382
- cn / bigmodel / 国内 智谱 https://bigmodel.cn (默认)
383
- intl / zai / 国际 Z.AI https://chat.z.ai
384
-
385
- 环境变量:
386
- ZCODE_START_PLAN_DATA_DIR 数据目录(默认 ~/.dsh/zcode-start-plan)
387
- ZCODE_START_PLAN_CDP_PORT 宿主 CDP 端口(默认 9229)
388
-
389
- 数据文件:
390
- ${resolveDataDir(process.env)}
391
- accounts.db 账号库(SQLite,600 权限;含 ZCode JWT)
392
- `)
393
- }
394
-
395
- const handlers = {
396
- login: cmdLogin,
397
- import: cmdImport,
398
- list: cmdList,
399
- status: cmdStatus,
400
- probe: cmdProbe,
401
- captcha: cmdCaptcha,
402
- claim: cmdClaim,
403
- enable: () => cmdAccountAction('enable'),
404
- disable: () => cmdAccountAction('disable'),
405
- remove: () => cmdAccountAction('remove'),
406
- reset: () => cmdAccountAction('reset'),
407
- help: cmdHelp,
408
- }
409
-
410
- const handler = handlers[command]
411
- if (handler === undefined) {
412
- warn(`未知命令:${command}`)
413
- cmdHelp()
414
- process.exitCode = 1
415
- } else {
416
- /**
417
- * ⚠ 只在真的拿到 Promise 时才 `await`:`help` 这类同步处理函数返回 `undefined`,
418
- * `await undefined` 会让模块顶层 await 悬空,Node 会打印
419
- * “Detected unsettled top-level await”。同时捕获异常,统一落到 exitCode。
420
- */
421
- try {
422
- const outcome = handler()
423
- if (outcome !== undefined && typeof outcome.then === 'function') await outcome
424
- } catch (error) {
425
- warn(`✗ ${error instanceof Error ? error.message : String(error)}`)
426
- process.exitCode = 1
427
- }
428
- }
429
-
430
- /**
431
- * 收尾策略:**不 await、不 process.exit()**。
432
- *
433
- * ## 为什么两条都不能用
434
- *
435
- * 1. `await` 一个「等 stdio 写空」的 promise —— `stream.write('', cb)` 在 stdout 不是
436
- * TTY 时(管道 / 重定向,也就是父进程捕获输出的常见情形)**不会回调**:Node 对空
437
- * chunk 直接 return true,根本不排进写入队列。于是 await 永久挂起 → 模块顶层 await
438
- * 悬空 → 打印 "Detected unsettled top-level await"。
439
- * 2. `process.exit()` —— 它**立即**退出,而管道写入是异步的,会把还没 flush 的输出
440
- * (尤其是 `login` 打印的授权链接)截掉。
441
- *
442
- * ## 采用的写法
443
- *
444
- * 什么也不做:`process.exitCode` 已经设好,事件循环会在所有句柄(SQLite / fetch /
445
- * 定时器)释放后**自然退出**,退出码由 exitCode 决定,stdout 也会在退出前正常排空。
446
- *
447
- * 只兜一个病态:真挂了不释放的句柄时进程永不退出。看门狗定义在文件顶部(见
448
- * `EXIT_WATCHDOG_MS`);需要长时间等待的命令(`login`)会先取消它。
449
- */
450
-
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `zcode-start-plan` 命令行:在没有 DSH 的情况下完成「登录 / 看状态 / 领取 / 探活」。
4
+ *
5
+ * 这些操作**不需要** captcha 载体(除 claim 外):登录是纯 HTTP 设备授权流,
6
+ * 余额与模型目录是 GET。故 CLI 可以在 Harness 没启动时独立使用。
7
+ *
8
+ * ```powershell
9
+ * node bin/cli.mjs login # 设备授权:打印链接 → 浏览器授权 → 自动入池
10
+ * node bin/cli.mjs import "<PATH_TO_ZCODE_JWT>" # 从文件读 JWT(已有 ZCode 登录时)
11
+ * node bin/cli.mjs list # 账号列表(不含凭据)
12
+ * node bin/cli.mjs status # 账号 + 余额 + 限流标记
13
+ * node bin/cli.mjs probe --model GLM-5.3-Flash # 真发一条最小请求,验证全链路
14
+ * node bin/cli.mjs claim # 领取当日免费额度(需要 captcha 载体)
15
+ * node bin/cli.mjs captcha # 单独产出一次 captcha(诊断用)
16
+ * node bin/cli.mjs disable 1 / enable 1 / remove 1
17
+ * ```
18
+ */
19
+
20
+ import { existsSync, readFileSync } from 'node:fs'
21
+ import { resolve } from 'node:path'
22
+ import { AccountPool, SqliteStore, resolveDbFile, resolveDataDir } from '../lib/pool.js'
23
+ import { beginZcodeLogin, fetchBalance, fetchCaptchaConfig, fetchClaimablePlans, fetchModels, claimPlan, reportActivation, resolveLoginChannel, LOGIN_CHANNELS } from '../lib/upstream-api.js'
24
+ import { CaptchaMinter } from '../lib/captcha/minter.js'
25
+ import { ZcodePlanClient } from '../lib/plan-client.js'
26
+ import { checkModelId } from '../lib/model-catalog.js'
27
+ import { generateDeviceMid } from '../lib/upstream.js'
28
+
29
+ const args = process.argv.slice(2)
30
+ const command = args[0] ?? 'help'
31
+
32
+ /** `--flag value` / `--flag=value` 解析。 */
33
+ function option(name, fallback) {
34
+ const exact = args.indexOf(`--${name}`)
35
+ if (exact !== -1 && args[exact + 1] !== undefined) return args[exact + 1]
36
+ const prefixed = args.find((arg) => arg.startsWith(`--${name}=`))
37
+ if (prefixed !== undefined) return prefixed.slice(name.length + 3)
38
+ return fallback
39
+ }
40
+
41
+ const log = (message) => process.stdout.write(`${message}\n`)
42
+ const warn = (message) => process.stderr.write(`${message}\n`)
43
+
44
+ /**
45
+ * 退出看门狗(必须在任何命令执行前就位)。
46
+ *
47
+ * ⚠ **只**兜「异常路径上句柄没释放导致进程永不退出」,默认 15 秒。
48
+ * 需要长时间等待的命令必须先调 `clearExitWatchdog()`,否则看门狗会在任务完成前
49
+ * 杀掉进程 —— 而且旧实现用的是 `process.exit(process.exitCode ?? 0)`:被杀时
50
+ * **退出码 0**,`probe` / `claim` / `captcha` 这类诊断命令会「假成功」,
51
+ * 比失败更误导(脚本据此判定全链路通过)。故:
52
+ *
53
+ * - 长命令(login / status / probe / claim / captcha)显式取消看门狗;
54
+ * - 兜底触发一律用**非零**退出码(`EXIT_WATCHDOG_CODE`),并说明被谁杀。
55
+ */
56
+ const EXIT_WATCHDOG_MS = 15_000
57
+ const EXIT_WATCHDOG_CODE = 124
58
+ let exitWatchdog = setTimeout(() => {
59
+ process.stderr.write(
60
+ `\n✗ 命令超过 ${EXIT_WATCHDOG_MS / 1000}s 未完成,已由看门狗强制退出(退出码 ${EXIT_WATCHDOG_CODE})。` +
61
+ '这不是成功:常见原因是某个句柄(数据库 / fetch / 定时器)没释放。\n',
62
+ )
63
+ process.exit(process.exitCode ?? EXIT_WATCHDOG_CODE)
64
+ }, EXIT_WATCHDOG_MS)
65
+ /** 不要因为看门狗让进程多活 15 秒:它只是兜底,不持有存活权。 */
66
+ exitWatchdog.unref()
67
+
68
+ /** 取消看门狗(长任务用)。 */
69
+ function clearExitWatchdog() {
70
+ clearTimeout(exitWatchdog)
71
+ exitWatchdog = undefined
72
+ }
73
+
74
+ /**
75
+ * CDP 调试端口的来源优先级(与插件侧 `minter.js` 一致,见 P8 审计):
76
+ *
77
+ * `--port` 显式参数 → 环境变量 `ZCODE_START_PLAN_CDP_PORT` → 默认 9229。
78
+ *
79
+ * ⚠ 旧实现直接写死 `Number(option('port', '9229'))`,环境变量只在 minter 内部
80
+ * 生效 —— 用户按 README 设了环境变量,CLI 仍然连 9229,`captcha`/`claim`/`probe`
81
+ * 全部报「连不上调试端口」,而文档说这是可以配的。
82
+ */
83
+ function resolveCdpPort(flagValue) {
84
+ const fromFlag = flagValue !== undefined ? Number(flagValue) : Number.NaN
85
+ if (Number.isInteger(fromFlag) && fromFlag >= 1 && fromFlag <= 65_535) return fromFlag
86
+ const fromEnv = Number(process.env['ZCODE_START_PLAN_CDP_PORT'] ?? '')
87
+ if (Number.isInteger(fromEnv) && fromEnv >= 1 && fromEnv <= 65_535) return fromEnv
88
+ return 9229
89
+ }
90
+
91
+ /** 打开账号库 + 账号池。 */
92
+ async function openPool() {
93
+ const store = await new SqliteStore(resolveDbFile(process.env))
94
+ return { store, pool: new AccountPool({ store, log: warn }) }
95
+ }
96
+
97
+ function maskJwt(jwt) {
98
+ if (typeof jwt !== 'string' || jwt.length < 12) return '***'
99
+ return `${jwt.slice(0, 6)}…${jwt.slice(-4)}(${jwt.length} 字符)`
100
+ }
101
+
102
+ function printAccounts(pool) {
103
+ const entries = pool.list({ withCredentials: true })
104
+ if (entries.length === 0) {
105
+ log('账号池为空。先运行:node bin/cli.mjs login')
106
+ return entries
107
+ }
108
+ entries.forEach((entry, index) => {
109
+ const limits = Object.keys(entry.model_rate_limits ?? {})
110
+ /** 渠道:凭据里记的 login_channel 优先;老凭据没有则显示「未标注」。 */
111
+ const channelId = entry.credential?.login_channel
112
+ const channelLabel = channelId !== undefined && LOGIN_CHANNELS[channelId] !== undefined
113
+ ? LOGIN_CHANNELS[channelId].label
114
+ : '未标注'
115
+ log(
116
+ `[${index + 1}] ${entry.enabled ? '●' : '○'} ${entry.nickname} id=${entry.id.slice(0, 8)} ` +
117
+ `渠道=${channelLabel} ` +
118
+ `jwt=${maskJwt(entry.credential?.zcode_jwt)} ` +
119
+ `device=${entry.credential?.device_mid?.slice(0, 8) ?? '?'} ` +
120
+ `${limits.length > 0 ? `限流:${limits.join(',')}` : ''}` +
121
+ `${entry.last_error !== undefined ? ` 最近错误:${entry.last_error}` : ''}`,
122
+ )
123
+ })
124
+ return entries
125
+ }
126
+
127
+ async function cmdLogin() {
128
+ const { store, pool } = await openPool()
129
+ /**
130
+ * 登录渠道:`--channel cn|intl`(也认 `bigmodel`/`zai`/`国内`/`国际`)。
131
+ *
132
+ * 两条渠道**协议完全一致**,只是 `provider` 与授权站点不同:
133
+ * 国内 = bigmodel.cn,国际 = chat.z.ai。账号属于哪边就用哪边登录。
134
+ */
135
+ const channel = resolveLoginChannel(option('channel', option('provider', undefined)))
136
+ /**
137
+ * ⚠ 登录必须**取消看门狗**:这个命令的语义就是「一直等到用户在浏览器里点完授权」
138
+ * (默认 10 分钟),而看门狗是给「异常路径挂死句柄」用的。不取消的话,
139
+ * 15 秒后被强制 exit → 顶层 await 悬空 → 打印 unsettled 警告,且授权永远等不到。
140
+ */
141
+ clearExitWatchdog()
142
+ const deadline = Date.now() + 10 * 60_000
143
+ const keepalive = setInterval(() => {
144
+ const left = Math.max(0, Math.round((deadline - Date.now()) / 1000))
145
+ process.stderr.write(`\r等待授权中… 剩余 ${left}s(Ctrl+C 取消) `)
146
+ }, 5_000)
147
+ try {
148
+ log(`正在向 ZCode 申请设备授权(${channel.label})…`)
149
+ const { loginUrl, result } = await beginZcodeLogin({ channel: channel.provider })
150
+ log('')
151
+ log(`请在浏览器里打开下面这个链接完成授权(用拥有赠送免费 plan 的【${channel.site}】账号):`)
152
+ log('')
153
+ log(` ${loginUrl}`)
154
+ log('')
155
+ log('若链接已过期:重跑本命令,或加 --channel intl 切换到国际站。')
156
+ const credential = await result
157
+ process.stderr.write('\n')
158
+ const { entry, created } = pool.add(credential, option('name', undefined))
159
+ log(`${created ? '已添加' : '已更新'}账号:${entry.nickname}(id=${entry.id.slice(0, 8)},渠道=${channel.label})`)
160
+ log(`数据目录:${resolveDataDir(process.env)}`)
161
+ } catch (error) {
162
+ process.stderr.write('\n')
163
+ warn(`✗ 登录失败:${error instanceof Error ? error.message : String(error)}`)
164
+ process.exitCode = 1
165
+ } finally {
166
+ clearInterval(keepalive)
167
+ store.close()
168
+ }
169
+ }
170
+
171
+ async function cmdImport() {
172
+ const jwtFile = args[1]
173
+ if (jwtFile === undefined) {
174
+ warn('用法:node bin/cli.mjs import <含 JWT 的文件路径>')
175
+ process.exitCode = 1
176
+ return
177
+ }
178
+ const raw = readFileSync(resolve(jwtFile), 'utf8').trim()
179
+ let jwt = raw
180
+ /** 容忍把整段 JSON 存进文件的情况(官方客户端的凭据结构)。 */
181
+ try {
182
+ const parsed = JSON.parse(raw)
183
+ jwt = parsed.zcode_jwt ?? parsed.token ?? parsed.data?.token ?? raw
184
+ } catch {
185
+ // 纯文本就是 JWT。
186
+ }
187
+ if (typeof jwt !== 'string' || jwt.length < 32) {
188
+ warn('文件里没找到像样的 JWT(期望 ≥32 字符的字符串)。')
189
+ process.exitCode = 1
190
+ return
191
+ }
192
+ const { store, pool } = await openPool()
193
+ try {
194
+ const { entry, created } = pool.add(
195
+ { zcode_jwt: jwt, device_mid: generateDeviceMid(), account_label: option('name', '导入账号'), source: 'ide' },
196
+ option('name', undefined),
197
+ )
198
+ log(`${created ? '已添加' : '已更新'}账号:${entry.nickname}`)
199
+ log('⚠ 导入的账号没有 user_id,无法按账号去重;重复导入会新增条目。')
200
+ } finally {
201
+ store.close()
202
+ }
203
+ }
204
+
205
+ async function cmdList() {
206
+ const { store, pool } = await openPool()
207
+ try {
208
+ printAccounts(pool)
209
+ } finally {
210
+ store.close()
211
+ }
212
+ }
213
+
214
+ async function cmdStatus() {
215
+ /**
216
+ * ⚠ 逐账号拉余额(每账号 30s 超时)+ 模型目录 + captcha 配置,账号一多必然超过
217
+ * 15s 看门狗 —— 旧实现会在打印完账号列表后**以退出码 0 静默截断**。
218
+ */
219
+ clearExitWatchdog()
220
+ const { store, pool } = await openPool()
221
+ try {
222
+ const entries = printAccounts(pool)
223
+ log('')
224
+ for (const entry of entries) {
225
+ try {
226
+ const balance = await fetchBalance(entry.credential)
227
+ if (balance === undefined) {
228
+ log(`· ${entry.nickname}:余额查询失败(凭据可能已过期,重新 login 这个账号)`)
229
+ } else if (balance.enterprise === true) {
230
+ log(`· ${entry.nickname}:企业版(不下发用量数字)`)
231
+ } else {
232
+ log(
233
+ `· ${entry.nickname}:剩余 ${balance.remaining}/${balance.total} ` +
234
+ `${balance.planName !== undefined ? `(${balance.planName})` : ''}`,
235
+ )
236
+ }
237
+ } catch (error) {
238
+ log(`· ${entry.nickname}:余额查询异常 ${error instanceof Error ? error.message : String(error)}`)
239
+ }
240
+ }
241
+ const first = entries[0]
242
+ if (first !== undefined) {
243
+ const models = await fetchModels(first.credential)
244
+ log('')
245
+ log(`上游模型目录${models === undefined ? '(不可达,用兜底表)' : ''}:${(models ?? []).map((model) => model.id).join(', ') || '(空)'}`)
246
+ const config = await fetchCaptchaConfig(first.credential)
247
+ log(`服务端 captcha 配置:${config === undefined ? '(不可达,用兜底值)' : JSON.stringify(config)}`)
248
+ }
249
+ log('')
250
+ log(`数据目录:${resolveDataDir(process.env)}`)
251
+ log(`账号库:${resolveDbFile(process.env)}`)
252
+ } finally {
253
+ store.close()
254
+ }
255
+ }
256
+
257
+ async function cmdProbe() {
258
+ /** ⚠ captcha mint 可达 75s + 退避重试,必然超过 15s 看门狗(见 EXIT_WATCHDOG_MS 注释)。 */
259
+ clearExitWatchdog()
260
+ const model = option('model', 'GLM-5.3-Flash')
261
+ const { store, pool } = await openPool()
262
+ const minter = new CaptchaMinter({ debugPort: resolveCdpPort(option('port')), log: warn })
263
+ try {
264
+ if (pool.list().length === 0) {
265
+ warn('账号池为空。先运行 login。')
266
+ process.exitCode = 1
267
+ return
268
+ }
269
+ /**
270
+ * ⚠ 模型名先按目录校验(0.10.0 审计 S6):拼错一个字母 → 上游回 200 零内容 →
271
+ * `plan-client` 判定「该账号×模型当日用尽」→ **账号被标限流到当日**。
272
+ * probe 是诊断命令,不该反过来污染账号状态。
273
+ */
274
+ const first = pool.list({ withCredentials: true })[0]
275
+ const catalog = first === undefined ? [] : (await fetchModels(first.credential)) ?? []
276
+ const check = checkModelId(model, catalog)
277
+ if (!check.ok) {
278
+ warn(`✗ ${check.reason}(可用:${check.available.join(', ') || '无'})`)
279
+ process.exitCode = 1
280
+ return
281
+ }
282
+ const client = new ZcodePlanClient({ pool, minter, log: warn })
283
+ const started = Date.now()
284
+ const result = await client.call({
285
+ options: {
286
+ model: check.id,
287
+ messages: [{ role: 'user', content: [{ type: 'text', text: 'ping(只回复 pong)' }] }],
288
+ },
289
+ maxTokens: 64,
290
+ onRetry: (info) => warn(`重试(${info.reason}):${info.message}`),
291
+ })
292
+ let text = ''
293
+ for (const event of result.head) {
294
+ const data = event.data
295
+ if (data?.type === 'content_block_delta' && data.delta?.type === 'text_delta') text += data.delta.text
296
+ }
297
+ if (result.head.decoder !== undefined) {
298
+ for (;;) {
299
+ const next = await result.head.decoder.read()
300
+ if (next.done === true) break
301
+ const data = next.value.data
302
+ if (data?.type === 'content_block_delta' && data.delta?.type === 'text_delta') text += data.delta.text
303
+ }
304
+ }
305
+ log(`✓ 全链路通过(账号 ${result.accountId.slice(0, 8)},${Date.now() - started}ms)`)
306
+ log(` 回复:${text.trim().slice(0, 200) || '(流里没有文本)'}`)
307
+ } catch (error) {
308
+ warn(`✗ 失败(${error?.code ?? 'ERR'}):${error instanceof Error ? error.message : String(error)}`)
309
+ process.exitCode = 1
310
+ } finally {
311
+ minter.dispose()
312
+ store.close()
313
+ }
314
+ }
315
+
316
+ async function cmdCaptcha() {
317
+ /** ⚠ 单次 mint 最长 ~75s,必须取消看门狗(否则「captcha 产出成功」永远打不出来)。 */
318
+ clearExitWatchdog()
319
+ const minter = new CaptchaMinter({ debugPort: resolveCdpPort(option('port')), log: warn })
320
+ try {
321
+ const probe = await minter.probe()
322
+ log(`调试端口:${probe.ok ? '可达' : `不可达(${probe.reason})`}`)
323
+ if (!probe.ok) {
324
+ process.exitCode = 1
325
+ return
326
+ }
327
+ const { store, pool } = await openPool()
328
+ try {
329
+ const first = pool.list({ withCredentials: true })[0]
330
+ const config = first === undefined ? undefined : await fetchCaptchaConfig(first.credential)
331
+ const started = Date.now()
332
+ const outcome = await minter.mint(config ?? { region: 'cn', prefix: 'no8xfe', sceneId: '11xygtvd' })
333
+ log(`✓ captcha 产出成功(${Date.now() - started}ms,param 长度 ${outcome.param.length},交互式=${outcome.interactive})`)
334
+ } finally {
335
+ store.close()
336
+ }
337
+ } catch (error) {
338
+ warn(`✗ ${error instanceof Error ? error.message : String(error)}`)
339
+ process.exitCode = 1
340
+ } finally {
341
+ minter.dispose()
342
+ }
343
+ }
344
+
345
+ async function cmdClaim() {
346
+ /** ⚠ 逐账号逐 plan mint captcha(每个最长 ~75s),必须取消看门狗。 */
347
+ clearExitWatchdog()
348
+ const { store, pool } = await openPool()
349
+ const minter = new CaptchaMinter({ debugPort: resolveCdpPort(option('port')), log: warn })
350
+ try {
351
+ const entries = pool.list({ withCredentials: true })
352
+ if (entries.length === 0) {
353
+ warn('账号池为空。先运行 login。')
354
+ process.exitCode = 1
355
+ return
356
+ }
357
+ const client = new ZcodePlanClient({ pool, minter, log: warn })
358
+ for (const entry of entries) {
359
+ if (!entry.enabled) continue
360
+ log(`· ${entry.nickname}`)
361
+ await reportActivation(entry.credential)
362
+ const plans = await fetchClaimablePlans(entry.credential)
363
+ if (plans.length === 0) {
364
+ log(' 当前没有探测到可领取的活动(官方营销投放可能为空,稍后再试)')
365
+ continue
366
+ }
367
+ for (const plan of plans) {
368
+ /** ⚠ captcha 一次性:每个 plan 必须重新产出。 */
369
+ const captcha = await client.mintCaptcha()
370
+ const outcome = await claimPlan(entry.credential, plan.planId, captcha)
371
+ log(
372
+ ` ${outcome.ok ? '✓' : '✗'} ${plan.name ?? plan.planId}` +
373
+ `${outcome.alreadyClaimed === true ? '(已领过)' : ''}` +
374
+ `${outcome.ok ? '' : ` ${outcome.code ?? outcome.httpStatus ?? ''} ${outcome.message ?? ''}`}`,
375
+ )
376
+ }
377
+ const balance = await fetchBalance(entry.credential)
378
+ if (balance !== undefined && balance.enterprise !== true) {
379
+ log(` 当前剩余:${balance.remaining}/${balance.total}`)
380
+ }
381
+ }
382
+ } catch (error) {
383
+ warn(`✗ ${error instanceof Error ? error.message : String(error)}`)
384
+ process.exitCode = 1
385
+ } finally {
386
+ minter.dispose()
387
+ store.close()
388
+ }
389
+ }
390
+
391
+ async function cmdAccountAction(action) {
392
+ const reference = args[1]
393
+ if (reference === undefined) {
394
+ warn(`用法:node bin/cli.mjs ${action} <序号|id|昵称片段>`)
395
+ process.exitCode = 1
396
+ return
397
+ }
398
+ const { store, pool } = await openPool()
399
+ try {
400
+ const entry = pool.resolve(reference)
401
+ if (entry === undefined) {
402
+ warn(`找不到账号:${reference}(先运行 list 看序号)`)
403
+ process.exitCode = 1
404
+ return
405
+ }
406
+ if (action === 'disable') pool.setEnabled(entry.id, false)
407
+ else if (action === 'enable') pool.setEnabled(entry.id, true)
408
+ else if (action === 'remove') pool.remove(entry.id)
409
+ else if (action === 'reset') pool.clearModelRateLimits(entry.id)
410
+ log(`已对「${entry.nickname}」执行 ${action}`)
411
+ } finally {
412
+ store.close()
413
+ }
414
+ }
415
+
416
+ function cmdHelp() {
417
+ log(`zcode-start-plan — ZCode 赠送免费 plan 的 DSH 接入
418
+
419
+ 用法(在插件目录下运行):
420
+ node bin/cli.mjs login [--name 备注] [--channel cn|intl]
421
+ 设备授权登录并把账号入池
422
+ --channel cn = 智谱国内站 bigmodel.cn(默认)
423
+ --channel intl = Z.AI 国际站 z.ai
424
+ node bin/cli.mjs import <文件> [--name 备注] 从含 JWT 的文件导入账号
425
+ node bin/cli.mjs list 账号列表(脱敏,含来源渠道)
426
+ node bin/cli.mjs status 账号 + 余额 + 上游模型目录 + captcha 配置
427
+ node bin/cli.mjs probe [--model M] 真发一条最小请求,验证全链路
428
+ node bin/cli.mjs claim 领取当日额度(需要 captcha 载体)
429
+ node bin/cli.mjs captcha [--port 9229] 单独产出一次 captcha(诊断)
430
+ node bin/cli.mjs enable|disable|remove|reset <序号|id|昵称>
431
+
432
+ 登录渠道(两条渠道协议相同,选择你的账号所属站点):
433
+ cn / bigmodel / 国内 智谱 https://bigmodel.cn (默认)
434
+ intl / zai / 国际 Z.AI https://chat.z.ai
435
+
436
+ 环境变量:
437
+ ZCODE_START_PLAN_DATA_DIR 数据目录(默认 ~/.dsh/zcode-start-plan)
438
+ ZCODE_START_PLAN_CDP_PORT 宿主 CDP 端口(默认 9229)
439
+
440
+ 数据文件:
441
+ ${resolveDataDir(process.env)}
442
+ accounts.db 账号库(SQLite,600 权限;含 ZCode JWT)
443
+ `)
444
+ }
445
+
446
+ const handlers = {
447
+ login: cmdLogin,
448
+ import: cmdImport,
449
+ list: cmdList,
450
+ status: cmdStatus,
451
+ probe: cmdProbe,
452
+ captcha: cmdCaptcha,
453
+ claim: cmdClaim,
454
+ enable: () => cmdAccountAction('enable'),
455
+ disable: () => cmdAccountAction('disable'),
456
+ remove: () => cmdAccountAction('remove'),
457
+ reset: () => cmdAccountAction('reset'),
458
+ help: cmdHelp,
459
+ }
460
+
461
+ const handler = handlers[command]
462
+ if (handler === undefined) {
463
+ warn(`未知命令:${command}`)
464
+ cmdHelp()
465
+ /**
466
+ * ⚠ 必须设**非零**退出码:旧实现只打印帮助、退出码 0,脚本层面会误判「执行成功」。
467
+ * 这里放在 `cmdHelp()` 之后是为了让帮助先正常输出到 stdout。
468
+ */
469
+ process.exitCode = 1
470
+ } else {
471
+ /**
472
+ * ⚠ 只在真的拿到 Promise 时才 `await`:`help` 这类同步处理函数返回 `undefined`,
473
+ * `await undefined` 会让模块顶层 await 悬空,Node 会打印
474
+ * “Detected unsettled top-level await”。同时捕获异常,统一落到 exitCode。
475
+ */
476
+ try {
477
+ const outcome = handler()
478
+ if (outcome !== undefined && typeof outcome.then === 'function') await outcome
479
+ } catch (error) {
480
+ warn(`✗ ${error instanceof Error ? error.message : String(error)}`)
481
+ process.exitCode = 1
482
+ }
483
+ }
484
+
485
+ /**
486
+ * 收尾策略:**不 await、不 process.exit()**。
487
+ *
488
+ * ## 为什么两条都不能用
489
+ *
490
+ * 1. `await` 一个「等 stdio 写空」的 promise —— `stream.write('', cb)` 在 stdout 不是
491
+ * TTY 时(管道 / 重定向,也就是父进程捕获输出的常见情形)**不会回调**:Node 对空
492
+ * chunk 直接 return true,根本不排进写入队列。于是 await 永久挂起 → 模块顶层 await
493
+ * 悬空 → 打印 "Detected unsettled top-level await"。
494
+ * 2. `process.exit()` —— 它**立即**退出,而管道写入是异步的,会把还没 flush 的输出
495
+ * (尤其是 `login` 打印的授权链接)截掉。
496
+ *
497
+ * ## 采用的写法
498
+ *
499
+ * 什么也不做:`process.exitCode` 已经设好,事件循环会在所有句柄(SQLite / fetch /
500
+ * 定时器)释放后**自然退出**,退出码由 exitCode 决定,stdout 也会在退出前正常排空。
501
+ *
502
+ * 只兜一个病态:真挂了不释放的句柄时进程永不退出。看门狗定义在文件顶部(见
503
+ * `EXIT_WATCHDOG_MS`);需要长时间等待的命令(login / status / probe / claim /
504
+ * captcha)会先取消它。
505
+ *
506
+ * ⚠ 未知命令 / 同步处理函数抛错必须把 `process.exitCode` 设成非零(1)——
507
+ * 否则脚本层面判定「命令成功」,而实际上一个字母都没执行。
508
+ */
509
+