dsh-zcode-startplan 0.2.0 → 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.
@@ -18,7 +18,14 @@
18
18
  */
19
19
 
20
20
  import { isIP } from 'node:net'
21
- import { startZcodeLogin, pollZcodeLogin, normalizeLoginChannel } from './upstream-api.js'
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)。 */
@@ -127,13 +134,73 @@ function publicAccount(entry, index) {
127
134
  /**
128
135
  * 构造管理路由。
129
136
  *
130
- * @param {{ pool: import('./pool.js').AccountPool, fetchBalance?: (credential: any) => Promise<any>, log?: (message: string) => void }} deps
137
+ * @param {{
138
+ * pool: import('./pool.js').AccountPool,
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 }>,
143
+ * log?: (message: string) => void,
144
+ * onChanged?: () => void,
145
+ * onSetUnifiedVisible?: (visible: boolean) => void,
146
+ * onSetAccountVisible?: (accountId: string, visible: boolean) => void,
147
+ * settings?: { unifiedModelList?: boolean, hiddenModelLists?: string[] },
148
+ * }} deps
131
149
  * @returns {Array<{ kind: 'exact', path: string, handler: (req: any, res: any) => Promise<void> }>}
132
150
  */
133
151
  export function makeManageRoutes(deps) {
134
152
  const pool = deps.pool
135
153
  const fetchBalance = deps.fetchBalance
136
154
  const log = deps.log ?? (() => {})
155
+ /**
156
+ * 池子变更后的通知:账号栏位的路由集合随启用账号增删而变 —— 通知
157
+ * assemble 用 `handle.replace()` 原子换路由(内部自动广播
158
+ * `llm/adapters-updated`,模型选择器随即重拉目录)。
159
+ */
160
+ const notifyChanged = () => {
161
+ try {
162
+ deps.onChanged?.()
163
+ } catch {
164
+ // 通知失败不影响管理操作本身。
165
+ }
166
+ }
167
+
168
+ /** 「统一选号」栏位开关(POST /unified-list)。 */
169
+ const unifiedListHandler = async (req, res) => {
170
+ const body = (await readJsonBody(req)) ?? {}
171
+ if (typeof body.visible !== 'boolean') {
172
+ writeJson(res, 400, { ok: false, error: '需要 visible(布尔)' })
173
+ return
174
+ }
175
+ try {
176
+ deps.onSetUnifiedVisible?.(body.visible)
177
+ } catch (error) {
178
+ writeJson(res, 500, { ok: false, error: messageOf(error) })
179
+ return
180
+ }
181
+ writeJson(res, 200, { ok: true, visible: body.visible })
182
+ }
183
+
184
+ /** 单个账号「模型栏位」开关(POST /model-list-visible,每卡片右侧的开关)。 */
185
+ const modelListVisibleHandler = async (req, res) => {
186
+ const body = (await readJsonBody(req)) ?? {}
187
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
188
+ if (id.length === 0 || typeof body.visible !== 'boolean') {
189
+ writeJson(res, 400, { ok: false, error: '需要 id(字符串)与 visible(布尔)' })
190
+ return
191
+ }
192
+ if (!pool.list().some((entry) => entry.id === id)) {
193
+ writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
194
+ return
195
+ }
196
+ try {
197
+ deps.onSetAccountVisible?.(id, body.visible)
198
+ } catch (error) {
199
+ writeJson(res, 500, { ok: false, error: messageOf(error) })
200
+ return
201
+ }
202
+ writeJson(res, 200, { ok: true, id, visible: body.visible })
203
+ }
137
204
 
138
205
  // ── 登录流(两段式设备授权:Client 拿 URL → 浏览器授权 → Client 轮询)──
139
206
  //
@@ -174,38 +241,68 @@ export function makeManageRoutes(deps) {
174
241
  }
175
242
  }
176
243
 
177
- /** 池子当前状态(含每账号余额,拉取失败给 null)。 */
244
+ /** 池子当前状态(含每账号余额与栏位可见性,拉取失败给 null)。 */
178
245
  const summaryHandler = async (_req, res) => {
179
246
  const entries = pool.list({ withCredentials: true })
180
- const accounts = []
181
- for (let index = 0; index < entries.length; index += 1) {
182
- const entry = entries[index]
183
- const view = publicAccount(entry, index)
184
- if (typeof fetchBalance === 'function' && entry.enabled) {
247
+ const hidden = new Set(Array.isArray(deps.settings?.hiddenModelLists) ? deps.settings.hiddenModelLists : [])
248
+ /**
249
+ * 余额并行拉取(纯读、账号间无依赖):串行时最坏 30s × N(fetchBalance
250
+ * 每账号超时 30s),面板会一直「加载中…」。
251
+ * fetchBalance 失败路径返回 undefined / 抛错都归一为 null —— 明确下发
252
+ * `balance: null`,客户端(client.js load)只对缺键的账号补拉 /balance,
253
+ * 避免同一端点被二次重试双倍消耗。
254
+ */
255
+ const balances = await Promise.all(
256
+ entries.map(async (entry) => {
257
+ if (typeof fetchBalance !== 'function' || entry.enabled !== true) return null
185
258
  try {
186
259
  const balance = await fetchBalance(entry.credential)
187
- if (balance !== undefined) {
188
- view.balance = balance.enterprise === true
189
- ? { enterprise: true, remaining: null, total: null, planName: null }
190
- : {
191
- enterprise: false,
192
- remaining: typeof balance.remaining === 'number' ? balance.remaining : null,
193
- total: typeof balance.total === 'number' ? balance.total : null,
194
- planName: balance.planName ?? null,
195
- }
196
- }
260
+ if (balance === undefined) return null
261
+ return balance.enterprise === true
262
+ ? { enterprise: true, remaining: null, total: null, planName: null }
263
+ : {
264
+ enterprise: false,
265
+ remaining: typeof balance.remaining === 'number' ? balance.remaining : null,
266
+ total: typeof balance.total === 'number' ? balance.total : null,
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
+ : {}),
274
+ }
197
275
  } catch {
198
- view.balance = null
276
+ return null
199
277
  }
200
- } else {
201
- view.balance = null
278
+ }),
279
+ )
280
+ const accounts = entries.map((entry, index) => {
281
+ const view = publicAccount(entry, index)
282
+ /** 账号「模型栏位」是否显示(面板每卡片右侧的开关状态)。 */
283
+ view.modelListVisible = !hidden.has(entry.id)
284
+ view.balance = balances[index]
285
+ return view
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) }
202
298
  }
203
- accounts.push(view)
204
299
  }
205
300
  writeJson(res, 200, {
206
301
  ok: true,
207
302
  accounts,
208
303
  enabledCount: accounts.filter((account) => account.enabled).length,
304
+ unifiedModelList: deps.settings?.unifiedModelList !== false,
305
+ ...(captcha !== undefined ? { captcha } : {}),
209
306
  fetchedAt: Date.now(),
210
307
  })
211
308
  }
@@ -235,6 +332,12 @@ export function makeManageRoutes(deps) {
235
332
  remaining: typeof balance.remaining === 'number' ? balance.remaining : null,
236
333
  total: typeof balance.total === 'number' ? balance.total : null,
237
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
+ : {}),
238
341
  },
239
342
  })
240
343
  } catch (error) {
@@ -252,6 +355,7 @@ export function makeManageRoutes(deps) {
252
355
  return
253
356
  }
254
357
  pool.setEnabled(id, enabled)
358
+ notifyChanged()
255
359
  writeJson(res, 200, { ok: true, id, enabled })
256
360
  }
257
361
 
@@ -268,6 +372,7 @@ export function makeManageRoutes(deps) {
268
372
  writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
269
373
  return
270
374
  }
375
+ notifyChanged()
271
376
  writeJson(res, 200, { ok: true, id })
272
377
  }
273
378
 
@@ -293,6 +398,7 @@ export function makeManageRoutes(deps) {
293
398
  return
294
399
  }
295
400
  pool.reorder(ids)
401
+ notifyChanged()
296
402
  writeJson(res, 200, { ok: true, ids })
297
403
  }
298
404
 
@@ -311,6 +417,7 @@ export function makeManageRoutes(deps) {
311
417
  return
312
418
  }
313
419
  pool.patchAccount(id, { nickname })
420
+ notifyChanged()
314
421
  writeJson(res, 200, { ok: true, id, nickname })
315
422
  }
316
423
 
@@ -335,9 +442,134 @@ export function makeManageRoutes(deps) {
335
442
  }
336
443
  const ids = [id, ...entries.map((item) => item.id).filter((existing) => existing !== id)]
337
444
  pool.reorder(ids)
445
+ notifyChanged()
338
446
  writeJson(res, 200, { ok: true, id, order: ids })
339
447
  }
340
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
+
341
573
  /** /login/start:向渠道申请设备授权,返回 authorizeUrl + flowId(不含 secret)。 */
342
574
  const loginStartHandler = async (req, res) => {
343
575
  const body = (await readJsonBody(req)) ?? {}
@@ -390,6 +622,7 @@ export function makeManageRoutes(deps) {
390
622
  source: 'plugin-web',
391
623
  }
392
624
  const { entry, created } = pool.add(credential)
625
+ notifyChanged()
393
626
  log(`[manage] 通过 Web UI ${created ? '添加' : '更新'}账号:${entry.nickname}(${record.channel})`)
394
627
  writeJson(res, 200, {
395
628
  ok: true,
@@ -408,7 +641,12 @@ export function makeManageRoutes(deps) {
408
641
  { kind: 'exact', path: `${MANAGE_PREFIX}/reorder`, handler: guard(reorderHandler) },
409
642
  { kind: 'exact', path: `${MANAGE_PREFIX}/rename`, handler: guard(renameHandler) },
410
643
  { kind: 'exact', path: `${MANAGE_PREFIX}/use`, handler: guard(useHandler) },
644
+ { kind: 'exact', path: `${MANAGE_PREFIX}/unified-list`, handler: guard(unifiedListHandler) },
645
+ { kind: 'exact', path: `${MANAGE_PREFIX}/model-list-visible`, handler: guard(modelListVisibleHandler) },
411
646
  { kind: 'exact', path: `${MANAGE_PREFIX}/login/start`, handler: guard(loginStartHandler) },
412
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) },
413
651
  ]
414
652
  }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * 「钉定账号」模型 id 的编解码。
3
+ *
4
+ * ## 这个功能解决什么问题
5
+ *
6
+ * 默认选号是「手动顺序」:面板置顶谁,下一次请求就用谁。但用户有时想**同时**
7
+ * 用多个会话,各会话吃不同账号的额度 —— 顺序只有一个,做不到。
8
+ *
9
+ * 因此在模型选择器里为每个启用账号额外暴露一条「模型 × 账号」条目:
10
+ *
11
+ * ```
12
+ * GLM-5.3-Flash ← 普通条目:自动选号(手动顺序)
13
+ * GLM-5.3-Flash · 主号 ← 钉定条目:只消耗「主号」的额度
14
+ * ```
15
+ *
16
+ * ## id 编码
17
+ *
18
+ * 钉定条目的模型 id 形如 `GLM-5.3-Flash@acct:<账号id>`:
19
+ *
20
+ * - `@acct:` 之前是**发给上游的基础模型 id**(上游只认识 `GLM-5.3-Flash` 这类);
21
+ * - 之后是池内账号 id(`randomUUID`)。
22
+ *
23
+ * 上游合法模型 id 与账号 id 都不含 `@acct:`,该分隔符无歧义;用 `lastIndexOf`
24
+ * 解析,即便未来 id 里再出现该串也取最后一个分隔段。
25
+ *
26
+ * ⚠ 这个 id 会对宿主/上游/持久化(会话保存的模型名)三方可见,**编码格式一经
27
+ * 发布就不能变**,否则老会话里保存的钉定模型全部失效。
28
+ */
29
+
30
+ /** 分隔符(发布后不可更改,见文件头)。 */
31
+ export const PINNED_MODEL_SUFFIX = '@acct:'
32
+
33
+ /** 拼一个钉定模型 id。 */
34
+ export function makePinnedModelId(baseModelId, accountId) {
35
+ return `${baseModelId}${PINNED_MODEL_SUFFIX}${accountId}`
36
+ }
37
+
38
+ /**
39
+ * 解析钉定模型 id。
40
+ *
41
+ * @returns {{ baseModelId: string, accountId: string } | null} 非钉定 id 或形状不完整时返回 null
42
+ */
43
+ export function parsePinnedModelId(modelId) {
44
+ const raw = String(modelId ?? '')
45
+ const at = raw.lastIndexOf(PINNED_MODEL_SUFFIX)
46
+ if (at <= 0) return null
47
+ const baseModelId = raw.slice(0, at)
48
+ const accountId = raw.slice(at + PINNED_MODEL_SUFFIX.length)
49
+ if (baseModelId.length === 0 || accountId.length === 0) return null
50
+ return { baseModelId, accountId }
51
+ }
52
+
53
+ /** 是否是钉定模型 id。 */
54
+ export function isPinnedModelId(modelId) {
55
+ return parsePinnedModelId(modelId) !== null
56
+ }
@@ -22,7 +22,7 @@
22
22
  * 2. **每轮重试都必须重新 mint captcha**:param 一次性,复用必 3007。
23
23
  */
24
24
 
25
- import { buildUpstreamBody } from './anthropic-body.js'
25
+ import { buildUpstreamBody, resolveImages } from './anthropic-body.js'
26
26
  import {
27
27
  CONCURRENCY_RETRY_MAX,
28
28
  QUOTA_SWITCH_MAX,
@@ -33,6 +33,8 @@ import {
33
33
  import { readContentHead } from './sse.js'
34
34
  import { buildZcodeHeaders, ZCODE_PLAN_MESSAGES_URL, ZCODE_FALLBACK_MODELS, nextUtc8DayStartMs } from './upstream.js'
35
35
  import { ZCODE_CAPTCHA_FALLBACK } from './captcha/sdk-page.js'
36
+ import { parsePinnedModelId } from './pinned-model.js'
37
+ import { isUsableCredential } from './pool.js'
36
38
 
37
39
  /** 「该账号×模型当前需要 captcha」的记忆时长(避免每条消息都白吃一次 3007)。 */
38
40
  const CAPTCHA_REQUIRED_TTL_MS = 2 * 60_000
@@ -127,6 +129,8 @@ export class ZcodePlanClient {
127
129
  #captchaRequiredUntil = new Map()
128
130
  #captchaConfig
129
131
  #captchaConfigAt = 0
132
+ /** 附件服务回调(`() => ctx.get('attachments')`,可选):图片引用 → 请求字节。 */
133
+ #resolveDeps
130
134
 
131
135
  constructor(options) {
132
136
  this.#pool = options.pool
@@ -136,6 +140,7 @@ export class ZcodePlanClient {
136
140
  this.#now = options.now ?? (() => Date.now())
137
141
  this.#cwd = options.cwd ?? process.cwd()
138
142
  this.#captchaConfig = options.captchaConfig
143
+ this.#resolveDeps = options
139
144
  }
140
145
 
141
146
  /** 供状态工具读取观测值。 */
@@ -147,6 +152,48 @@ export class ZcodePlanClient {
147
152
  }
148
153
  }
149
154
 
155
+ /**
156
+ * 钉定模式选号:只取指定账号,**绝不换号**。
157
+ *
158
+ * 与 `pool.pick` 的差异:不按手动顺序、不看其他账号;但同样跳过「该模型
159
+ * 限流中」的账号 —— 限流标记意味着额度已尽,硬发只会吃一个 1005。
160
+ * 账号缺失 / 停用 / 凭据不可用 / 限流中都以**明确报错**收场(各自给出路),
161
+ * 不静默回退到别的账号 —— 那会让「钉定」名存实亡。
162
+ */
163
+ #pickPinned(accountId, modelId) {
164
+ const entry = this.#pool.get(accountId, { withCredentials: true })
165
+ if (entry === undefined) {
166
+ throw Object.assign(
167
+ new Error(`钉定的账号已不存在(可能已被删除)。请重新登录添加,或改选不带账号后缀的自动选号条目。`),
168
+ { code: 'QUOTA' },
169
+ )
170
+ }
171
+ if (entry.enabled !== true) {
172
+ throw Object.assign(
173
+ new Error(`钉定的账号「${entry.nickname}」已被停用。请在插件面板重新启用,或改选自动选号条目。`),
174
+ { code: 'QUOTA' },
175
+ )
176
+ }
177
+ const resetAt = entry.model_rate_limits?.[modelId]
178
+ if (typeof resetAt === 'number' && resetAt > 0 && this.#now() < resetAt) {
179
+ const at = new Date(resetAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
180
+ throw Object.assign(
181
+ new Error(
182
+ `钉定的账号「${entry.nickname}」在模型「${modelId}」上处于限流期(至 ${at})。` +
183
+ '可等待重置、在面板「清除限流」后重试,或改选自动选号条目换用其它账号。',
184
+ ),
185
+ { code: 'QUOTA' },
186
+ )
187
+ }
188
+ if (!isUsableCredential(entry.credential)) {
189
+ throw Object.assign(
190
+ new Error(`钉定的账号「${entry.nickname}」凭据不可用,请重新登录。`),
191
+ { code: 'AUTH' },
192
+ )
193
+ }
194
+ return { entry, credential: entry.credential }
195
+ }
196
+
150
197
  /** 拉 captcha 配置(60 秒 TTL;失败不缓存 —— 一次网络抖动不该让 sceneId 永久固化)。 */
151
198
  async #resolveCaptchaConfig() {
152
199
  const now = this.#now()
@@ -210,8 +257,31 @@ export class ZcodePlanClient {
210
257
  * }>}
211
258
  */
212
259
  async call(request) {
213
- const options = request.options
214
- const model = options.model
260
+ let options = request.options
261
+ /**
262
+ * 钉定账号的两个来源(优先级:provider 路由 > 模型 id 后缀):
263
+ *
264
+ * 1. **provider 路由**(`request.pinnedAccountId`):每个账号一个独立
265
+ * provider 栏位(`zcode-start-plan-acct-<id>`,像 workbuddy 一样),
266
+ * 路由本身就把「哪个账号出额度」钉死;
267
+ * 2. **模型 id 后缀**(`<base>@acct:<账号id>`,0.3.0 形态):保留兼容 ——
268
+ * 旧会话里保存的钉定模型继续可用。
269
+ *
270
+ * 上游永远只见基础模型 id;选号不再按手动顺序轮换,只走钉定账号。
271
+ */
272
+ const routePin =
273
+ typeof request.pinnedAccountId === 'string' && request.pinnedAccountId.trim().length > 0
274
+ ? request.pinnedAccountId.trim()
275
+ : null
276
+ const idPin = parsePinnedModelId(options.model)
277
+ const pinned = routePin !== null ? { accountId: routePin } : idPin
278
+ const model = idPin === null ? options.model : idPin.baseModelId
279
+ if (pinned !== null) {
280
+ options = { ...options, model }
281
+ if (typeof request.model?.id === 'string') {
282
+ request = { ...request, model: { ...request.model, id: model } }
283
+ }
284
+ }
215
285
  const tried = new Set()
216
286
  let lastFailure = '所有账号在模型「' + model + '」上都已用尽或无可用权益'
217
287
  /**
@@ -224,7 +294,11 @@ export class ZcodePlanClient {
224
294
  let lastQuotaDetail = ''
225
295
 
226
296
  for (let quotaRound = 0; quotaRound < QUOTA_SWITCH_MAX; quotaRound += 1) {
227
- const picked = this.#pool.pick(model, tried)
297
+ /**
298
+ * 选号:钉定模式只看指定账号(选不到直接报错,见 `#pickPinned`);
299
+ * 自动模式按手动顺序取第一个可用账号,逐个试到有产出为止。
300
+ */
301
+ const picked = pinned === null ? this.#pool.pick(model, tried) : this.#pickPinned(pinned.accountId, model)
228
302
  if (picked === null) {
229
303
  const detail = lastQuotaDetail.length > 0 ? `最后一次上游响应:${lastQuotaDetail}。` : ''
230
304
  /**
@@ -252,15 +326,42 @@ export class ZcodePlanClient {
252
326
  }
253
327
  const accountId = picked.entry.id
254
328
  const credential = picked.credential
329
+ /**
330
+ * 钉定模式下额度耗尽:如实报错而不是换号 —— 换号会让「钉定」名存实亡
331
+ * (用户选了「GLM-5.3 · 主号」就该知道失败意味着主号的额度尽了)。
332
+ */
333
+ const failPinnedQuota = (upstreamText) => {
334
+ const detail = upstreamText.length > 0 ? `上游响应:${upstreamText}。` : ''
335
+ throw Object.assign(
336
+ new Error(
337
+ `钉定的账号「${picked.entry.nickname}」在模型「${model}」上的额度已用尽(免费额度按自然日 UTC+8 结算)。` +
338
+ `${detail}可等次日重置、在面板把其它账号置顶后改选,或改选不带账号后缀的自动选号条目。`,
339
+ ),
340
+ { code: 'QUOTA' },
341
+ )
342
+ }
255
343
  const captchaKey = `${accountId}|${model}`
256
344
  let probeRejected = false
257
345
  let switched = false
258
346
 
347
+ const supportsImages = request.model?.inputModalities?.includes?.('image') ?? true
348
+ /**
349
+ * 宿主契约:DSH 的 image 块是持久引用(`{ type: 'image', attachment: ref }`),
350
+ * 字节须经附件服务 `readImageRequest` 解析(官方 `dsh-llm-deepseek` 同款链路)。
351
+ * 附件服务不可用 / 解析失败时 `resolvedImages` 缺项,`convertContent` 用
352
+ * 占位文本替换 —— 不再静默丢弃。
353
+ */
354
+ const resolvedImages = await resolveImages(options.messages, {
355
+ resolveAttachments: this.#resolveDeps?.resolveAttachments,
356
+ signal: request.signal,
357
+ })
358
+
259
359
  const body = buildUpstreamBody({
260
360
  options,
261
361
  cwd: this.#cwd,
262
362
  provider: 'zcode-start-plan',
263
- supportsImages: request.model?.inputModalities?.includes?.('image') ?? true,
363
+ supportsImages,
364
+ resolvedImages,
264
365
  maxTokens: request.maxTokens,
265
366
  })
266
367
 
@@ -315,6 +416,7 @@ export class ZcodePlanClient {
315
416
  if (kind === 'quota') {
316
417
  this.#pool.markModelRateLimited(accountId, model, nextUtc8DayStartMs(new Date(this.#now())))
317
418
  this.#pool.noteError(accountId, describeUpstreamError(response.status, text))
419
+ if (pinned !== null) failPinnedQuota(text.slice(0, 200))
318
420
  tried.add(accountId)
319
421
  switched = true
320
422
  break
@@ -350,6 +452,7 @@ export class ZcodePlanClient {
350
452
  if (response.body === null) {
351
453
  this.#log(`[zcode] 账号 ${accountId} 返回 200 但 body 为空 → 视为无权益,换号`)
352
454
  this.#pool.markModelRateLimited(accountId, model, nextUtc8DayStartMs(new Date(this.#now())))
455
+ if (pinned !== null) failPinnedQuota('HTTP 200 但响应体为空')
353
456
  tried.add(accountId)
354
457
  switched = true
355
458
  break
@@ -373,6 +476,7 @@ export class ZcodePlanClient {
373
476
  lastQuotaDetail = text.slice(0, 200)
374
477
  this.#pool.markModelRateLimited(accountId, model, nextUtc8DayStartMs(new Date(this.#now())))
375
478
  this.#pool.noteError(accountId, describeUpstreamError(200, text))
479
+ if (pinned !== null) failPinnedQuota(text.slice(0, 200))
376
480
  tried.add(accountId)
377
481
  switched = true
378
482
  break
@@ -400,6 +504,7 @@ export class ZcodePlanClient {
400
504
  this.#log(`[zcode] 账号 ${accountId} 在模型 ${model} 上返回 200 但零内容(${head.elapsedMs}ms)→ 视为无权益,换号`)
401
505
  this.#pool.markModelRateLimited(accountId, model, nextUtc8DayStartMs(new Date(this.#now())))
402
506
  this.#pool.noteError(accountId, `200 但零内容(${head.elapsedMs}ms)`)
507
+ if (pinned !== null) failPinnedQuota(`HTTP 200 但零内容(${head.elapsedMs}ms)`)
403
508
  tried.add(accountId)
404
509
  switched = true
405
510
  break
package/lib/pool.js CHANGED
@@ -278,6 +278,17 @@ export class AccountPool {
278
278
  return this.#store.list(options)
279
279
  }
280
280
 
281
+ /**
282
+ * 按 id 取单个账号。`store.get` 总是带凭据,这里按 `withCredentials` 决定
283
+ * 是否外发(与 `list` 的脱敏约定一致)。
284
+ */
285
+ get(id, options = {}) {
286
+ const entry = this.#store.get(id)
287
+ if (entry === undefined) return undefined
288
+ if (options.withCredentials !== true) delete entry.credential
289
+ return entry
290
+ }
291
+
281
292
  /** 启用中的账号数。 */
282
293
  enabledCount() {
283
294
  return this.list().filter((entry) => entry.enabled).length