dsh-zcode-startplan 0.4.5 → 0.5.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.
- package/CHANGELOG.md +267 -0
- package/README.md +73 -6
- package/client.js +299 -13
- package/index.js +35 -3
- package/lib/adapter.js +27 -0
- package/lib/assemble.js +164 -42
- package/lib/manage-routes.js +164 -1
- package/lib/plan-client.js +4 -4
- package/lib/upstream-api.js +45 -4
- package/package.json +3 -2
- package/scripts/restart-dsh.ps1 +41 -1
- package/tests/anthropic-body.test.mjs +305 -0
- package/tests/assembler-contract.test.mjs +256 -0
- package/tests/claim-routes.test.mjs +293 -0
- package/tests/client-panel.test.mjs +356 -0
- package/tests/e2e.test.mjs +353 -0
- package/tests/fixtures/quota-200.json +1 -0
- package/tests/login-channel.test.mjs +102 -0
- package/tests/pinned-models.test.mjs +497 -0
- package/tests/plan-client.test.mjs +222 -0
- package/tests/pool.test.mjs +93 -0
- package/tests/sse.test.mjs +86 -0
- package/tests/stream-translator.test.mjs +137 -0
- package/tests/support/resolve-profile-deps.mjs +52 -0
- package/tests/upstream-error-200.test.mjs +125 -0
- package/tests/upstream.test.mjs +250 -0
package/lib/assemble.js
CHANGED
|
@@ -8,7 +8,9 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
|
|
11
|
-
import { join } from 'node:path'
|
|
11
|
+
import { join, dirname } from 'node:path'
|
|
12
|
+
import { fileURLToPath } from 'node:url'
|
|
13
|
+
import { spawn } from 'node:child_process'
|
|
12
14
|
import { SqliteStore, AccountPool, resolveDbFile, resolveDataDir } from './pool.js'
|
|
13
15
|
import { CaptchaMinter } from './captcha/minter.js'
|
|
14
16
|
import { ZcodePlanClient } from './plan-client.js'
|
|
@@ -18,6 +20,50 @@ import { fetchBalance, fetchCaptchaConfig, fetchModels } from './upstream-api.js
|
|
|
18
20
|
import { ZCODE_FALLBACK_MODELS } from './upstream.js'
|
|
19
21
|
import { makeManageRoutes } from './manage-routes.js'
|
|
20
22
|
|
|
23
|
+
/**
|
|
24
|
+
* 以调试端口重启宿主的实现(供管理路由的 `/restart-cdp` 调用)。
|
|
25
|
+
*
|
|
26
|
+
* 跑 `scripts/restart-dsh.ps1`,三件事必须同时成立:
|
|
27
|
+
* 1. `detached: true` + `unref()`:脚本要在**本请求返回之后**才杀宿主,
|
|
28
|
+
* 若子进程挂在宿主进程树下,宿主一死它跟着死 → 没人拉起新实例;
|
|
29
|
+
* 2. 用 `powershell.exe`(Windows PowerShell 5.1 一定在)而不是 `pwsh`:
|
|
30
|
+
* 用户机器未必装了 PowerShell 7;
|
|
31
|
+
* 3. `cwd` 指到插件目录,脚本内部的相对路径才成立。
|
|
32
|
+
*
|
|
33
|
+
* @param {{ debugPort: number, waitSeconds: number }} options
|
|
34
|
+
*/
|
|
35
|
+
function spawnRestartScript(options) {
|
|
36
|
+
const pluginRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
|
|
37
|
+
const script = join(pluginRoot, 'scripts', 'restart-dsh.ps1')
|
|
38
|
+
const args = [
|
|
39
|
+
'-NoProfile',
|
|
40
|
+
'-ExecutionPolicy', 'Bypass',
|
|
41
|
+
'-File', script,
|
|
42
|
+
'-WaitSeconds', String(options.waitSeconds),
|
|
43
|
+
'-DebugPort', String(options.debugPort),
|
|
44
|
+
]
|
|
45
|
+
return new Promise((resolve, reject) => {
|
|
46
|
+
let child
|
|
47
|
+
try {
|
|
48
|
+
child = spawn('powershell.exe', args, {
|
|
49
|
+
cwd: pluginRoot,
|
|
50
|
+
detached: true,
|
|
51
|
+
stdio: 'ignore',
|
|
52
|
+
windowsHide: true,
|
|
53
|
+
})
|
|
54
|
+
} catch (error) {
|
|
55
|
+
reject(error)
|
|
56
|
+
return
|
|
57
|
+
}
|
|
58
|
+
child.once('error', reject)
|
|
59
|
+
child.once('spawn', () => {
|
|
60
|
+
/** 分离后立即放掉引用:宿主退出时不要连带杀死它。 */
|
|
61
|
+
child.unref()
|
|
62
|
+
resolve()
|
|
63
|
+
})
|
|
64
|
+
})
|
|
65
|
+
}
|
|
66
|
+
|
|
21
67
|
/**
|
|
22
68
|
* 装配并返回运行时句柄。
|
|
23
69
|
*
|
|
@@ -72,10 +118,15 @@ export function assemble(ctx, config, logger) {
|
|
|
72
118
|
adapterRegistered: false,
|
|
73
119
|
/** 最近一次致命错误(初始化 / 注册 / 加载)。 */
|
|
74
120
|
error: undefined,
|
|
121
|
+
/** llm 适配器实例(管理路由的可见性开关要用;`register()` 里建立)。 */
|
|
122
|
+
adapter: undefined,
|
|
123
|
+
/** 账号增删/启停/置顶后原子换路由(由 `register()` 里赋值)。 */
|
|
124
|
+
syncAdapterRoutes: undefined,
|
|
75
125
|
}
|
|
76
126
|
|
|
77
127
|
/** 模型目录缓存(拉上游一次,失败回退到 config.models + 兜底表)。 */
|
|
78
128
|
let modelsCache = { at: 0, value: undefined }
|
|
129
|
+
|
|
79
130
|
const loadModels = async () => {
|
|
80
131
|
if (modelsCache.value !== undefined && Date.now() - modelsCache.at < config.modelCacheMs) {
|
|
81
132
|
return modelsCache.value
|
|
@@ -225,6 +276,7 @@ export function assemble(ctx, config, logger) {
|
|
|
225
276
|
unifiedVisible: settings.unifiedModelList !== false,
|
|
226
277
|
hiddenAccounts: settings.hiddenModelLists,
|
|
227
278
|
})
|
|
279
|
+
runtime.adapter = adapter
|
|
228
280
|
/**
|
|
229
281
|
* 当前注册的路由集合(统一栏位 + 启用账号的栏位)。账号增删/启停/
|
|
230
282
|
* 统一栏位开关时用 `handle.replace()` 原子换路由 —— 宿主会在
|
|
@@ -281,51 +333,26 @@ export function assemble(ctx, config, logger) {
|
|
|
281
333
|
warn('timer 服务不可用,跳过每小时限流清理(限流标记仍会在每次请求时自然过期)')
|
|
282
334
|
}
|
|
283
335
|
|
|
284
|
-
/**
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
onSetUnifiedVisible: (visible) => {
|
|
299
|
-
adapter.setUnifiedVisible(visible)
|
|
300
|
-
settings.unifiedModelList = visible === true
|
|
301
|
-
saveSettings()
|
|
302
|
-
syncRoutes()
|
|
303
|
-
log(`统一选号栏位${visible === true ? '已显示' : '已隐藏'}`)
|
|
304
|
-
},
|
|
305
|
-
onSetAccountVisible: (accountId, visible) => {
|
|
306
|
-
adapter.setAccountVisible(accountId, visible)
|
|
307
|
-
const hidden = new Set(settings.hiddenModelLists)
|
|
308
|
-
if (visible === true) hidden.delete(accountId)
|
|
309
|
-
else hidden.add(accountId)
|
|
310
|
-
settings.hiddenModelLists = [...hidden]
|
|
311
|
-
saveSettings()
|
|
312
|
-
syncRoutes()
|
|
313
|
-
const nickname = runtime.pool.get(accountId)?.nickname ?? accountId.slice(0, 8)
|
|
314
|
-
log(`账号「${nickname}」的模型栏位${visible === true ? '已显示' : '已隐藏'}`)
|
|
315
|
-
},
|
|
316
|
-
})
|
|
317
|
-
for (const route of routes) addUndo(ctx.webServer.register(route))
|
|
318
|
-
log(`管理路由已注册:${routes.length} 条(/api/zcode-start-plan/*)`)
|
|
319
|
-
} catch (error) {
|
|
320
|
-
warn(`管理路由注册失败(Web UI 不可用,其它功能不受影响):${error instanceof Error ? error.message : String(error)}`)
|
|
321
|
-
}
|
|
322
|
-
}
|
|
336
|
+
/**
|
|
337
|
+
* ④ 账号池管理路由 —— **不在这里注册**。
|
|
338
|
+
*
|
|
339
|
+
* 路由要挂到 `webServer` 上,而 `webServer` 是可选服务:宿主只把
|
|
340
|
+
* `inject` 声明过的服务挂到 facade 上,把 `webServer` 写进硬 inject
|
|
341
|
+
* 又会让 headless profile 整个 fiber 挂起。两种写法都错过一个版本:
|
|
342
|
+
* - 0.4.4:从 facade 探测 `ctx.webServer` → 永远拿不到 → 静默跳过(面板 404);
|
|
343
|
+
* - 只把 `webServer` 加回 inject → headless 下整插件不加载。
|
|
344
|
+
*
|
|
345
|
+
* 正解在 `index.js` 的 `ctx.inject(['webServer'], …)` 回调里调用
|
|
346
|
+
* `registerManageRoutes(webCtx)`:服务出现才注册、消失则 effect 自动撤销。
|
|
347
|
+
* (`syncRoutes` / `settings` / `log` 都在闭包里,回调直接复用。)
|
|
348
|
+
*/
|
|
349
|
+
runtime.syncRoutes = syncRoutes
|
|
323
350
|
}
|
|
324
351
|
|
|
325
352
|
/**
|
|
326
353
|
* `inject: ['llm', …]` 已保证 `ctx.llm` 就绪后才 apply,
|
|
327
354
|
* 所以这里直接注册即可;保留一个兜底分支应对宿主延迟挂载的情况。
|
|
328
|
-
*
|
|
355
|
+
* facade 上没有 `ctx.inject`,不能用它做兜底。
|
|
329
356
|
*/
|
|
330
357
|
if (ctx.llm !== undefined) {
|
|
331
358
|
doRegister()
|
|
@@ -346,7 +373,102 @@ export function assemble(ctx, config, logger) {
|
|
|
346
373
|
}
|
|
347
374
|
}
|
|
348
375
|
|
|
349
|
-
|
|
376
|
+
/**
|
|
377
|
+
* ④ 账号池管理路由(由 `index.js` 的 `ctx.inject(['webServer'], …)` 调用)。
|
|
378
|
+
*
|
|
379
|
+
* 之所以单独暴露而不是在 `register()` 里顺手连上:`webServer` 是**可选**
|
|
380
|
+
* 服务,必须用 cordis 的可选注入在它出现时才注册。这里拿到的 `webCtx`
|
|
381
|
+
* 保证带 `webServer`,于是不需要任何探测分支 —— 路由条目多一条都会被
|
|
382
|
+
* 立刻打日志,面板 404 这类症状下次能直接从日志定位。
|
|
383
|
+
*
|
|
384
|
+
* @param {any} webCtx 带 `webServer` 的 context(可选注入回调参数)
|
|
385
|
+
* @returns {() => void} 撤销函数(已用 effect 托管时宿主会再调一次也无害)
|
|
386
|
+
*/
|
|
387
|
+
const registerManageRoutes = (webCtx) => {
|
|
388
|
+
const undos = []
|
|
389
|
+
const addUndo = (undo) => {
|
|
390
|
+
if (typeof undo === 'function' && undo !== webCtx) undos.push(undo)
|
|
391
|
+
}
|
|
392
|
+
const undoAll = () => {
|
|
393
|
+
for (const undo of undos.splice(0).reverse()) {
|
|
394
|
+
try {
|
|
395
|
+
undo()
|
|
396
|
+
} catch (error) {
|
|
397
|
+
warn(`撤销管理路由失败:${error instanceof Error ? error.message : String(error)}`)
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
if (typeof webCtx?.webServer?.register !== 'function') {
|
|
402
|
+
warn('webServer 服务不可用(预期的可选注入未生效):账号面板路由已跳过')
|
|
403
|
+
return undoAll
|
|
404
|
+
}
|
|
405
|
+
if (runtime.pool === undefined) {
|
|
406
|
+
warn('账号池尚未就绪:账号面板路由已跳过(初始化失败时才会发生)')
|
|
407
|
+
return undoAll
|
|
408
|
+
}
|
|
409
|
+
if (runtime.adapter === undefined) {
|
|
410
|
+
warn('llm 适配器尚未建立:账号面板路由已跳过(初始化失败时才会发生)')
|
|
411
|
+
return undoAll
|
|
412
|
+
}
|
|
413
|
+
const adapter = runtime.adapter
|
|
414
|
+
const routes = makeManageRoutes({
|
|
415
|
+
pool: runtime.pool,
|
|
416
|
+
fetchBalance: (credential) => fetchBalance(credential),
|
|
417
|
+
/**
|
|
418
|
+
* 领取赠送额度要 captcha:复用 plan-client 的**同一份**串行队列与退避闸门,
|
|
419
|
+
* 避免面板点击与推理链路各自起一份 CDP 会话互相踩页面。
|
|
420
|
+
*/
|
|
421
|
+
client: runtime.client,
|
|
422
|
+
/** 以调试端口重启宿主(让 captcha 载体可用);失败时面板看到明确错误。 */
|
|
423
|
+
requestRestart: (options) => spawnRestartScript(options),
|
|
424
|
+
/**
|
|
425
|
+
* captcha 载体状态:**每次 /summary 都现探一次**(一次本机 HTTP GET,几毫秒)。
|
|
426
|
+
* 不做缓存 —— 用户点「以调试模式重启」后回来刷新,必须立刻看到新状态。
|
|
427
|
+
* 探测本身失败不影响 summary 其余字段。
|
|
428
|
+
*/
|
|
429
|
+
probeCaptcha: async () => {
|
|
430
|
+
const minter = runtime.minter
|
|
431
|
+
const fallback = { mode: config.captcha.mode, debugPort: config.captcha.debugPort, reachable: false }
|
|
432
|
+
if (minter === undefined || typeof minter.probe !== 'function') return fallback
|
|
433
|
+
try {
|
|
434
|
+
const outcome = await minter.probe()
|
|
435
|
+
return {
|
|
436
|
+
...fallback,
|
|
437
|
+
reachable: outcome?.ok === true,
|
|
438
|
+
...(outcome?.ok === true ? {} : { reason: outcome?.reason }),
|
|
439
|
+
}
|
|
440
|
+
} catch (error) {
|
|
441
|
+
return { ...fallback, reason: error instanceof Error ? error.message : String(error) }
|
|
442
|
+
}
|
|
443
|
+
},
|
|
444
|
+
log,
|
|
445
|
+
settings,
|
|
446
|
+
onChanged: () => runtime.syncAdapterRoutes?.(),
|
|
447
|
+
onSetUnifiedVisible: (visible) => {
|
|
448
|
+
adapter.setUnifiedVisible(visible)
|
|
449
|
+
settings.unifiedModelList = visible === true
|
|
450
|
+
saveSettings()
|
|
451
|
+
runtime.syncAdapterRoutes?.()
|
|
452
|
+
log(`统一选号栏位${visible === true ? '已显示' : '已隐藏'}`)
|
|
453
|
+
},
|
|
454
|
+
onSetAccountVisible: (accountId, visible) => {
|
|
455
|
+
adapter.setAccountVisible(accountId, visible)
|
|
456
|
+
const hidden = new Set(settings.hiddenModelLists)
|
|
457
|
+
if (visible === true) hidden.delete(accountId)
|
|
458
|
+
else hidden.add(accountId)
|
|
459
|
+
settings.hiddenModelLists = [...hidden]
|
|
460
|
+
saveSettings()
|
|
461
|
+
runtime.syncAdapterRoutes?.()
|
|
462
|
+
const nickname = runtime.pool?.get(accountId)?.nickname ?? accountId.slice(0, 8)
|
|
463
|
+
log(`账号「${nickname}」的模型栏位${visible === true ? '已显示' : '已隐藏'}`)
|
|
464
|
+
},
|
|
465
|
+
})
|
|
466
|
+
for (const route of routes) addUndo(webCtx.webServer.register(route))
|
|
467
|
+
log(`管理路由已注册:${routes.length} 条(/api/zcode-start-plan/*)`)
|
|
468
|
+
return undoAll
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
return { runtime, init, register, registerManageRoutes, dispose, loadModels, dataDir }
|
|
350
472
|
}
|
|
351
473
|
|
|
352
474
|
/**
|
package/lib/manage-routes.js
CHANGED
|
@@ -18,7 +18,14 @@
|
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
20
|
import { isIP } from 'node:net'
|
|
21
|
-
import {
|
|
21
|
+
import {
|
|
22
|
+
startZcodeLogin,
|
|
23
|
+
pollZcodeLogin,
|
|
24
|
+
normalizeLoginChannel,
|
|
25
|
+
fetchClaimablePlans,
|
|
26
|
+
claimPlan,
|
|
27
|
+
reportActivation,
|
|
28
|
+
} from './upstream-api.js'
|
|
22
29
|
import { generateDeviceMid, ZCODE_APP_VERSION_FALLBACK } from './upstream.js'
|
|
23
30
|
|
|
24
31
|
/** 路由前缀(Client 半段用同一常量拼 URL)。 */
|
|
@@ -130,6 +137,9 @@ function publicAccount(entry, index) {
|
|
|
130
137
|
* @param {{
|
|
131
138
|
* pool: import('./pool.js').AccountPool,
|
|
132
139
|
* fetchBalance?: (credential: any) => Promise<any>,
|
|
140
|
+
* client?: { mintCaptcha?: () => Promise<{ param: string, region: string }> },
|
|
141
|
+
* requestRestart?: (options: { debugPort: number, waitSeconds: number }) => Promise<void>,
|
|
142
|
+
* probeCaptcha?: () => Promise<{ mode?: string, debugPort?: number, reachable: boolean, reason?: string }>,
|
|
133
143
|
* log?: (message: string) => void,
|
|
134
144
|
* onChanged?: () => void,
|
|
135
145
|
* onSetUnifiedVisible?: (visible: boolean) => void,
|
|
@@ -255,6 +265,12 @@ export function makeManageRoutes(deps) {
|
|
|
255
265
|
remaining: typeof balance.remaining === 'number' ? balance.remaining : null,
|
|
256
266
|
total: typeof balance.total === 'number' ? balance.total : null,
|
|
257
267
|
planName: balance.planName ?? null,
|
|
268
|
+
/** 还有余额的桶里最早的那个到期时间(毫秒);全用光则不给。 */
|
|
269
|
+
...(Number.isFinite(balance.expiresAt) ? { expiresAt: balance.expiresAt } : {}),
|
|
270
|
+
/** 未生效的计划额度(如 23 点启用的领取包);无则不下发该键。 */
|
|
271
|
+
...(Array.isArray(balance.pending) && balance.pending.length > 0
|
|
272
|
+
? { pending: balance.pending }
|
|
273
|
+
: {}),
|
|
258
274
|
}
|
|
259
275
|
} catch {
|
|
260
276
|
return null
|
|
@@ -268,11 +284,25 @@ export function makeManageRoutes(deps) {
|
|
|
268
284
|
view.balance = balances[index]
|
|
269
285
|
return view
|
|
270
286
|
})
|
|
287
|
+
/**
|
|
288
|
+
* captcha 载体状态:面板据此决定「领取」前要不要先给一个
|
|
289
|
+
* 「以调试模式重启」按钮(而不是让用户去手抄 param)。
|
|
290
|
+
* `probeCaptcha` 现探、不缓存;探测失败只是意味着领取暂时不可用。
|
|
291
|
+
*/
|
|
292
|
+
let captcha
|
|
293
|
+
if (typeof deps.probeCaptcha === 'function') {
|
|
294
|
+
try {
|
|
295
|
+
captcha = await deps.probeCaptcha()
|
|
296
|
+
} catch (error) {
|
|
297
|
+
captcha = { reachable: false, reason: messageOf(error) }
|
|
298
|
+
}
|
|
299
|
+
}
|
|
271
300
|
writeJson(res, 200, {
|
|
272
301
|
ok: true,
|
|
273
302
|
accounts,
|
|
274
303
|
enabledCount: accounts.filter((account) => account.enabled).length,
|
|
275
304
|
unifiedModelList: deps.settings?.unifiedModelList !== false,
|
|
305
|
+
...(captcha !== undefined ? { captcha } : {}),
|
|
276
306
|
fetchedAt: Date.now(),
|
|
277
307
|
})
|
|
278
308
|
}
|
|
@@ -302,6 +332,12 @@ export function makeManageRoutes(deps) {
|
|
|
302
332
|
remaining: typeof balance.remaining === 'number' ? balance.remaining : null,
|
|
303
333
|
total: typeof balance.total === 'number' ? balance.total : null,
|
|
304
334
|
planName: balance.planName ?? null,
|
|
335
|
+
/** 还有余额的桶里最早的那个到期时间(毫秒);全用光则不给。 */
|
|
336
|
+
...(Number.isFinite(balance.expiresAt) ? { expiresAt: balance.expiresAt } : {}),
|
|
337
|
+
/** 未生效的计划额度(如 23 点启用的领取包);无则不下发该键。 */
|
|
338
|
+
...(Array.isArray(balance.pending) && balance.pending.length > 0
|
|
339
|
+
? { pending: balance.pending }
|
|
340
|
+
: {}),
|
|
305
341
|
},
|
|
306
342
|
})
|
|
307
343
|
} catch (error) {
|
|
@@ -410,6 +446,130 @@ export function makeManageRoutes(deps) {
|
|
|
410
446
|
writeJson(res, 200, { ok: true, id, order: ids })
|
|
411
447
|
}
|
|
412
448
|
|
|
449
|
+
/**
|
|
450
|
+
* 领取赠送额度(一次性 captcha 的真正入口)。
|
|
451
|
+
*
|
|
452
|
+
* 两条路由(对应 `lib/upstream-api.js` 的两个上游调用):
|
|
453
|
+
* - `GET /claimable?id=` → 先 `reportActivation`(不补活跃信号时 preview 恒空),
|
|
454
|
+
* 再 `fetchClaimablePlans`;
|
|
455
|
+
* - `POST /claim {id, planId?}` → 逐 plan 领取;**每个 plan 重新 mint captcha**
|
|
456
|
+
* (param 一次性,复用必 3007)。`planId` 省略 = 领全部。
|
|
457
|
+
*
|
|
458
|
+
* ⚠ 为什么 captcha 走 `deps.client.mintCaptcha`(ZcodePlanClient 的串行队列):
|
|
459
|
+
* 面板点击与推理链路可能同时要 captcha,产出是**设备级**的,两条链路各自
|
|
460
|
+
* 起一份会互相踩 CDP 页面。复用同一个实例 = 同一把闸门。
|
|
461
|
+
*/
|
|
462
|
+
const claimableHandler = async (req, res) => {
|
|
463
|
+
const id = new URL(req.url ?? '/', 'http://localhost').searchParams.get('id')?.trim() ?? ''
|
|
464
|
+
const entry = id.length > 0 ? pool.list({ withCredentials: true }).find((item) => item.id === id) : undefined
|
|
465
|
+
if (entry === undefined) {
|
|
466
|
+
writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
|
|
467
|
+
return
|
|
468
|
+
}
|
|
469
|
+
if (typeof fetchClaimablePlans !== 'function') {
|
|
470
|
+
writeJson(res, 200, { ok: true, plans: [] })
|
|
471
|
+
return
|
|
472
|
+
}
|
|
473
|
+
try {
|
|
474
|
+
/** 先补活跃上报:不补则 preview 恒为空 plans(实测结论)。 */
|
|
475
|
+
await reportActivation?.(entry.credential)
|
|
476
|
+
const plans = await fetchClaimablePlans(entry.credential)
|
|
477
|
+
writeJson(res, 200, { ok: true, plans })
|
|
478
|
+
} catch (error) {
|
|
479
|
+
writeJson(res, 200, { ok: false, plans: [], error: messageOf(error) })
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
const claimHandler = async (req, res) => {
|
|
484
|
+
const body = (await readJsonBody(req)) ?? {}
|
|
485
|
+
const id = typeof body.id === 'string' ? body.id.trim() : ''
|
|
486
|
+
const wanted = typeof body.planId === 'string' && body.planId.trim().length > 0 ? body.planId.trim() : undefined
|
|
487
|
+
if (id.length === 0) {
|
|
488
|
+
writeJson(res, 400, { ok: false, error: '需要 id(字符串)' })
|
|
489
|
+
return
|
|
490
|
+
}
|
|
491
|
+
const entry = pool.list({ withCredentials: true }).find((item) => item.id === id)
|
|
492
|
+
if (entry === undefined) {
|
|
493
|
+
writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
|
|
494
|
+
return
|
|
495
|
+
}
|
|
496
|
+
if (typeof claimPlan !== 'function' || typeof deps.client?.mintCaptcha !== 'function') {
|
|
497
|
+
writeJson(res, 500, { ok: false, error: '领取链路未就绪(captcha 载体或上游客户端不可用)' })
|
|
498
|
+
return
|
|
499
|
+
}
|
|
500
|
+
await reportActivation?.(entry.credential)
|
|
501
|
+
const plans = (await fetchClaimablePlans(entry.credential)).filter((plan) => wanted === undefined || plan.planId === wanted)
|
|
502
|
+
if (plans.length === 0) {
|
|
503
|
+
writeJson(res, 200, { ok: true, results: [], message: '今天没有可领的活动(或已领完)' })
|
|
504
|
+
return
|
|
505
|
+
}
|
|
506
|
+
const results = []
|
|
507
|
+
for (const plan of plans) {
|
|
508
|
+
const label = plan.name ?? plan.planId
|
|
509
|
+
let captcha
|
|
510
|
+
try {
|
|
511
|
+
/** ⚠ 每个 plan 必须重新 mint:param 一次性。 */
|
|
512
|
+
captcha = await deps.client.mintCaptcha()
|
|
513
|
+
} catch (error) {
|
|
514
|
+
/**
|
|
515
|
+
* captcha 载体不可用(DSH 未以 --remote-debugging-port 启动等):
|
|
516
|
+
* 这里**不要**重试——mint 失败已有独立退避闸门,再打只会烧设备信誉。
|
|
517
|
+
*/
|
|
518
|
+
results.push({ planId: plan.planId, name: label, ok: false, error: `captcha 产出失败:${messageOf(error)}` })
|
|
519
|
+
break
|
|
520
|
+
}
|
|
521
|
+
const outcome = await claimPlan(entry.credential, plan.planId, captcha)
|
|
522
|
+
results.push({
|
|
523
|
+
planId: plan.planId,
|
|
524
|
+
name: label,
|
|
525
|
+
ok: outcome.ok === true,
|
|
526
|
+
...(outcome.alreadyClaimed === true ? { alreadyClaimed: true } : {}),
|
|
527
|
+
...(outcome.ok === true ? {} : { error: outcome.message ?? `HTTP ${outcome.httpStatus ?? '?'}` }),
|
|
528
|
+
})
|
|
529
|
+
log(`[manage] 领取 ${entry.nickname} × ${label}:${outcome.ok ? '成功' : '失败'}`)
|
|
530
|
+
}
|
|
531
|
+
writeJson(res, 200, { ok: results.every((item) => item.ok), results })
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* 以调试端口重启宿主(让 captcha 载体可用)。
|
|
536
|
+
*
|
|
537
|
+
* 触发条件是 `captcha.reachable === false` 且用户想在面板里领额度 —— 与其让
|
|
538
|
+
* 用户手动粘 captcha param,不如把「带 --remote-debugging-port 重启」做成一个按钮。
|
|
539
|
+
*
|
|
540
|
+
* ⚠ 三个实现要点:
|
|
541
|
+
* 1. **必须分离进程**:脚本要先等本请求返回、再杀掉宿主。用 `spawn` +
|
|
542
|
+
* `detached: true` + `unref()`,子进程不能跟宿主一起死,否则没人拉起新实例;
|
|
543
|
+
* 2. **不等待**:立刻回 200 + 预计秒数,面板提示「约 N 秒后自动重连」;
|
|
544
|
+
* 3. 脚本自带**失败回退**:CDP 起不来就不带参数重启,保证宿主仍可用
|
|
545
|
+
* (见 `scripts/restart-dsh.ps1` 尾部),所以这个按钮不会把用户锁在坏状态里。
|
|
546
|
+
*/
|
|
547
|
+
const restartCdpHandler = async (req, res) => {
|
|
548
|
+
const body = (await readJsonBody(req)) ?? {}
|
|
549
|
+
const debugPort = Number.isInteger(body.debugPort) ? body.debugPort : 9229
|
|
550
|
+
if (!(debugPort >= 1 && debugPort <= 65_535)) {
|
|
551
|
+
writeJson(res, 400, { ok: false, error: 'debugPort 必须是 1-65535 的整数' })
|
|
552
|
+
return
|
|
553
|
+
}
|
|
554
|
+
if (typeof deps.requestRestart !== 'function') {
|
|
555
|
+
writeJson(res, 501, { ok: false, error: '当前宿主不支持自动重启(缺少重启实现)' })
|
|
556
|
+
return
|
|
557
|
+
}
|
|
558
|
+
const waitSeconds = Number.isInteger(body.waitSeconds) ? Math.max(0, Math.min(120, body.waitSeconds)) : 3
|
|
559
|
+
try {
|
|
560
|
+
await deps.requestRestart({ debugPort, waitSeconds })
|
|
561
|
+
log(`[manage] 已请求以 --remote-debugging-port=${debugPort} 重启宿主(${waitSeconds}s 后)`)
|
|
562
|
+
writeJson(res, 200, {
|
|
563
|
+
ok: true,
|
|
564
|
+
debugPort,
|
|
565
|
+
/** 面板据此提示「稍后刷新」;真实就绪由下次 probe 决定。 */
|
|
566
|
+
estimatedReadyMs: (waitSeconds + 12) * 1_000,
|
|
567
|
+
})
|
|
568
|
+
} catch (error) {
|
|
569
|
+
writeJson(res, 500, { ok: false, error: messageOf(error) })
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
413
573
|
/** /login/start:向渠道申请设备授权,返回 authorizeUrl + flowId(不含 secret)。 */
|
|
414
574
|
const loginStartHandler = async (req, res) => {
|
|
415
575
|
const body = (await readJsonBody(req)) ?? {}
|
|
@@ -485,5 +645,8 @@ export function makeManageRoutes(deps) {
|
|
|
485
645
|
{ kind: 'exact', path: `${MANAGE_PREFIX}/model-list-visible`, handler: guard(modelListVisibleHandler) },
|
|
486
646
|
{ kind: 'exact', path: `${MANAGE_PREFIX}/login/start`, handler: guard(loginStartHandler) },
|
|
487
647
|
{ kind: 'exact', path: `${MANAGE_PREFIX}/login/poll`, handler: guard(loginPollHandler) },
|
|
648
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/claimable`, handler: guard(claimableHandler) },
|
|
649
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/claim`, handler: guard(claimHandler) },
|
|
650
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/restart-cdp`, handler: guard(restartCdpHandler) },
|
|
488
651
|
]
|
|
489
652
|
}
|
package/lib/plan-client.js
CHANGED
|
@@ -308,14 +308,14 @@ export class ZcodePlanClient {
|
|
|
308
308
|
* ③ 本次请求已逐个试完 → 汇报试了几个
|
|
309
309
|
* 统一报「账号池为空」会把人带去错误的排查方向(实测踩过)。
|
|
310
310
|
*/
|
|
311
|
-
const total = this.#pool.list()
|
|
312
|
-
const enabledCount =
|
|
311
|
+
const total = this.#pool.list().length
|
|
312
|
+
const enabledCount = this.#pool.list().filter((entry) => entry.enabled).length
|
|
313
313
|
let message
|
|
314
|
-
if (total
|
|
314
|
+
if (total === 0) {
|
|
315
315
|
message = '账号池为空。请先运行 `zcode-start-plan login` 添加 ZCode 账号。'
|
|
316
316
|
} else if (tried.size === 0) {
|
|
317
317
|
message = enabledCount === 0
|
|
318
|
-
? `账号池里有 ${total
|
|
318
|
+
? `账号池里有 ${total} 个账号,但全部被停用。用 \`zcode-start-plan enable <序号>\` 启用,或登录新账号。`
|
|
319
319
|
: `模型「${model}」在 ${enabledCount} 个启用账号上都已限流(免费额度按自然日 UTC+8 结算)。` +
|
|
320
320
|
`${detail}可等次日重置、换一个模型(config.models),或用 \`zcode-start-plan claim\` 领取当日额度。`
|
|
321
321
|
} else {
|
package/lib/upstream-api.js
CHANGED
|
@@ -351,23 +351,64 @@ export async function fetchBalance(credential, fetchImpl = globalThis.fetch) {
|
|
|
351
351
|
usedUnits: num(item.used_units),
|
|
352
352
|
remainingUnits: num(item.remaining_units),
|
|
353
353
|
availableUnits: num(item.available_units),
|
|
354
|
-
|
|
354
|
+
/**
|
|
355
|
+
* ⚠ 上游给的是**秒级**,统一归一到毫秒(与 `pending[].effectiveAt` 同单位)。
|
|
356
|
+
* 不归一会让 `new Date(x)` 落到 1970 年 —— 界面上就是「1970/1/21 到期」。
|
|
357
|
+
*/
|
|
358
|
+
expiresAt: toEpochMs(num(item.expires_at) ?? 0),
|
|
355
359
|
})
|
|
356
360
|
}
|
|
361
|
+
/**
|
|
362
|
+
* 未生效的**计划权益**(pending entitlements)。
|
|
363
|
+
*
|
|
364
|
+
* 上游把「已领但还没到点」的额度放在 `plans[].entitlements[]`:
|
|
365
|
+
* `balances` 只列**当前生效**的桶 —— 一个 23 点启用的 3 亿 token 包在 22 点的
|
|
366
|
+
* `balances` 里不存在,于是面板显示 0/0,用户以为领取失败(2026-10-26 实测)。
|
|
367
|
+
* 判据:`effective_at`(秒级)在 `server_time`(缺省取本地现在)之后,
|
|
368
|
+
* 且 `grant_units` 为正数。已生效的 entitlement 不收(balances 已覆盖)。
|
|
369
|
+
*/
|
|
370
|
+
const serverNowMs = toEpochMs(num(data.server_time) ?? 0) || Date.now()
|
|
371
|
+
const pending = []
|
|
372
|
+
for (const plan of Array.isArray(data.plans) ? data.plans : []) {
|
|
373
|
+
if (typeof plan !== 'object' || plan === null) continue
|
|
374
|
+
for (const item of Array.isArray(plan.entitlements) ? plan.entitlements : []) {
|
|
375
|
+
if (typeof item !== 'object' || item === null) continue
|
|
376
|
+
const effectiveAtMs = toEpochMs(num(item.effective_at) ?? 0)
|
|
377
|
+
const grantUnits = num(item.grant_units)
|
|
378
|
+
if (effectiveAtMs === 0 || !(grantUnits > 0) || effectiveAtMs <= serverNowMs) continue
|
|
379
|
+
/** 未生效权益的到期时间 = 所属 plan 的 `ends_at`(整份 plan 一起作废)。 */
|
|
380
|
+
const planEndsAtMs = toEpochMs(num(plan.ends_at) ?? 0)
|
|
381
|
+
pending.push({
|
|
382
|
+
planId: typeof plan.plan_id === 'string' ? plan.plan_id : undefined,
|
|
383
|
+
showName: typeof item.show_name === 'string' ? item.show_name : undefined,
|
|
384
|
+
unitType: typeof item.unit_type === 'string' ? item.unit_type : undefined,
|
|
385
|
+
grantUnits,
|
|
386
|
+
effectiveAt: effectiveAtMs,
|
|
387
|
+
...(planEndsAtMs > 0 ? { expiresAt: planEndsAtMs } : {}),
|
|
388
|
+
})
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
pending.sort((a, b) => a.effectiveAt - b.effectiveAt)
|
|
357
392
|
let remaining = 0
|
|
358
393
|
let total = 0
|
|
359
394
|
let expiresAt
|
|
360
395
|
for (const bucket of buckets) {
|
|
361
|
-
|
|
396
|
+
const available = bucket.availableUnits ?? bucket.remainingUnits ?? 0
|
|
397
|
+
remaining += available
|
|
362
398
|
total += bucket.totalUnits ?? 0
|
|
363
|
-
|
|
364
|
-
|
|
399
|
+
/**
|
|
400
|
+
* 顶层 `expiresAt` 只汇总**还有余额**的桶:已用光的桶到期没有意义,
|
|
401
|
+
* 若把它算进来,面板会对一个空桶提示「X 到期」,反而误导。
|
|
402
|
+
*/
|
|
403
|
+
if (available > 0 && Number.isFinite(bucket.expiresAt) && bucket.expiresAt > 0) {
|
|
404
|
+
if (expiresAt === undefined || bucket.expiresAt < expiresAt) expiresAt = bucket.expiresAt
|
|
365
405
|
}
|
|
366
406
|
}
|
|
367
407
|
return {
|
|
368
408
|
buckets,
|
|
369
409
|
remaining,
|
|
370
410
|
total,
|
|
411
|
+
...(pending.length > 0 ? { pending } : {}),
|
|
371
412
|
...(expiresAt !== undefined ? { expiresAt } : {}),
|
|
372
413
|
...(buckets[0]?.showName !== undefined ? { planName: buckets[0].showName } : {}),
|
|
373
414
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-zcode-startplan",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.2",
|
|
4
4
|
"description": "DSH 接入 ZCode 赠送免费 plan(account:bigmodel-start-plan):多账号池 + 按需阿里云 captcha + 直连 zcode-plan/anthropic 的 llm 适配器。移植自 gitee.com/iJetLi/bonus-plan-4-open-zcode。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "GPL-3.0-or-later",
|
|
@@ -36,6 +36,7 @@
|
|
|
36
36
|
"lib",
|
|
37
37
|
"bin",
|
|
38
38
|
"scripts",
|
|
39
|
+
"tests",
|
|
39
40
|
"locale/*.json",
|
|
40
41
|
"icon.svg",
|
|
41
42
|
"cordis.patch.yml",
|
|
@@ -64,7 +65,7 @@
|
|
|
64
65
|
"dsh": {
|
|
65
66
|
"id": "dsh-zcode-startplan",
|
|
66
67
|
"name": "ZCode Start Plan",
|
|
67
|
-
"version": "0.
|
|
68
|
+
"version": "0.5.2",
|
|
68
69
|
"permissions": "模型供应商接入, 账号池管理",
|
|
69
70
|
"bundle": {
|
|
70
71
|
"patch": "./cordis.patch.yml"
|
package/scripts/restart-dsh.ps1
CHANGED
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
param(
|
|
10
10
|
[int]$WaitSeconds = 25,
|
|
11
11
|
[int]$DebugPort = 9229,
|
|
12
|
-
|
|
12
|
+
# 留空 = 自动定位宿主可执行文件(见下方 Resolve-ExePath)。
|
|
13
|
+
[string]$Exe = '',
|
|
13
14
|
[string]$Log = "$env:TEMP\dsh-restart.log"
|
|
14
15
|
)
|
|
15
16
|
|
|
@@ -18,12 +19,51 @@ function Write-Log([string]$Message) {
|
|
|
18
19
|
Add-Content -Path $Log -Value $line -Encoding utf8
|
|
19
20
|
}
|
|
20
21
|
|
|
22
|
+
<#
|
|
23
|
+
自动定位宿主 exe。
|
|
24
|
+
|
|
25
|
+
⚠ 不能用「当前进程 = powershell 的父进程」推:本脚本是**分离启动**的,
|
|
26
|
+
父进程链已经断了。按下面的次序找,第一个命中即用:
|
|
27
|
+
|
|
28
|
+
1. 显式 -Exe(调用方知道确切路径时最可靠);
|
|
29
|
+
2. 正在运行的 `DeepSeek Harness.exe` 主进程的 ExecutablePath
|
|
30
|
+
(最准确:就是用户现在跑的那一份);
|
|
31
|
+
3. 常见安装位置。
|
|
32
|
+
#>
|
|
33
|
+
function Resolve-ExePath([string]$Explicit) {
|
|
34
|
+
if ($Explicit -and (Test-Path $Explicit)) { return (Resolve-Path $Explicit).Path }
|
|
35
|
+
|
|
36
|
+
$main = Get-CimInstance Win32_Process -Filter "Name='DeepSeek Harness.exe'" -ErrorAction SilentlyContinue |
|
|
37
|
+
Where-Object { $_.CommandLine -notmatch '--type=' } |
|
|
38
|
+
Select-Object -First 1
|
|
39
|
+
if ($main -and $main.ExecutablePath -and (Test-Path $main.ExecutablePath)) {
|
|
40
|
+
return $main.ExecutablePath
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
foreach ($candidate in @(
|
|
44
|
+
'D:\software\dsh\DeepSeek Harness.exe',
|
|
45
|
+
(Join-Path $env:LOCALAPPDATA 'Programs\DeepSeek Harness\DeepSeek Harness.exe'),
|
|
46
|
+
(Join-Path ${env:ProgramFiles} 'DeepSeek Harness\DeepSeek Harness.exe')
|
|
47
|
+
)) {
|
|
48
|
+
if ($candidate -and (Test-Path $candidate)) { return $candidate }
|
|
49
|
+
}
|
|
50
|
+
return ''
|
|
51
|
+
}
|
|
52
|
+
|
|
21
53
|
try {
|
|
22
54
|
Write-Log "restart scheduled in ${WaitSeconds}s (debug port $DebugPort)"
|
|
23
55
|
|
|
24
56
|
# 等这一轮 agent 回复写完,避免把正在进行的会话截断在半句上。
|
|
25
57
|
Start-Sleep -Seconds $WaitSeconds
|
|
26
58
|
|
|
59
|
+
# ⚠ 必须在**杀进程之前**解析 exe:进程一没,ExecutablePath 就查不到了。
|
|
60
|
+
$Exe = Resolve-ExePath $Exe
|
|
61
|
+
if (-not $Exe) {
|
|
62
|
+
Write-Log 'fatal: 找不到 DeepSeek Harness.exe(请用 -Exe 显式指定)'
|
|
63
|
+
exit 1
|
|
64
|
+
}
|
|
65
|
+
Write-Log "using exe: $Exe"
|
|
66
|
+
|
|
27
67
|
$main = Get-CimInstance Win32_Process -Filter "Name='DeepSeek Harness.exe'" |
|
|
28
68
|
Where-Object { $_.CommandLine -notmatch '--type=' }
|
|
29
69
|
|