dsh-zcode-startplan 0.2.0 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -144,8 +144,22 @@ export async function startLocalEndpoint(options) {
144
144
  })
145
145
 
146
146
  if (!streaming) {
147
- /** 非流式:把事件折叠成一个 message、按上游 content-type 语义回 JSON。 */
148
- const message = await collapseToMessage(result.head)
147
+ /**
148
+ * 非流式:先读干 decoder 余量再折叠。
149
+ * ⚠ `result.head` 只是「首帧切片」(plan-client 读到首帧就返回,好尽早判定
150
+ * 零内容/业务错误);正文增量全在 `result.decoder` 里。只折叠 head 会把回答
151
+ * 截成开头几个字 —— 流式分支有读 decoder,这里此前漏了(pi-ai 路线几乎总走
152
+ * 流式所以没暴露;ZCode CLI 冒烟实测踩中)。
153
+ */
154
+ const events = [...result.head]
155
+ if (result.decoder !== undefined) {
156
+ for (;;) {
157
+ const next = await result.decoder.read()
158
+ if (next.done === true) break
159
+ events.push(next.value)
160
+ }
161
+ }
162
+ const message = await collapseToMessage(events)
149
163
  res.writeHead(200, { 'content-type': 'application/json' })
150
164
  res.end(JSON.stringify(message))
151
165
  return
@@ -127,13 +127,70 @@ function publicAccount(entry, index) {
127
127
  /**
128
128
  * 构造管理路由。
129
129
  *
130
- * @param {{ pool: import('./pool.js').AccountPool, fetchBalance?: (credential: any) => Promise<any>, log?: (message: string) => void }} deps
130
+ * @param {{
131
+ * pool: import('./pool.js').AccountPool,
132
+ * fetchBalance?: (credential: any) => Promise<any>,
133
+ * log?: (message: string) => void,
134
+ * onChanged?: () => void,
135
+ * onSetUnifiedVisible?: (visible: boolean) => void,
136
+ * onSetAccountVisible?: (accountId: string, visible: boolean) => void,
137
+ * settings?: { unifiedModelList?: boolean, hiddenModelLists?: string[] },
138
+ * }} deps
131
139
  * @returns {Array<{ kind: 'exact', path: string, handler: (req: any, res: any) => Promise<void> }>}
132
140
  */
133
141
  export function makeManageRoutes(deps) {
134
142
  const pool = deps.pool
135
143
  const fetchBalance = deps.fetchBalance
136
144
  const log = deps.log ?? (() => {})
145
+ /**
146
+ * 池子变更后的通知:账号栏位的路由集合随启用账号增删而变 —— 通知
147
+ * assemble 用 `handle.replace()` 原子换路由(内部自动广播
148
+ * `llm/adapters-updated`,模型选择器随即重拉目录)。
149
+ */
150
+ const notifyChanged = () => {
151
+ try {
152
+ deps.onChanged?.()
153
+ } catch {
154
+ // 通知失败不影响管理操作本身。
155
+ }
156
+ }
157
+
158
+ /** 「统一选号」栏位开关(POST /unified-list)。 */
159
+ const unifiedListHandler = async (req, res) => {
160
+ const body = (await readJsonBody(req)) ?? {}
161
+ if (typeof body.visible !== 'boolean') {
162
+ writeJson(res, 400, { ok: false, error: '需要 visible(布尔)' })
163
+ return
164
+ }
165
+ try {
166
+ deps.onSetUnifiedVisible?.(body.visible)
167
+ } catch (error) {
168
+ writeJson(res, 500, { ok: false, error: messageOf(error) })
169
+ return
170
+ }
171
+ writeJson(res, 200, { ok: true, visible: body.visible })
172
+ }
173
+
174
+ /** 单个账号「模型栏位」开关(POST /model-list-visible,每卡片右侧的开关)。 */
175
+ const modelListVisibleHandler = async (req, res) => {
176
+ const body = (await readJsonBody(req)) ?? {}
177
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
178
+ if (id.length === 0 || typeof body.visible !== 'boolean') {
179
+ writeJson(res, 400, { ok: false, error: '需要 id(字符串)与 visible(布尔)' })
180
+ return
181
+ }
182
+ if (!pool.list().some((entry) => entry.id === id)) {
183
+ writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
184
+ return
185
+ }
186
+ try {
187
+ deps.onSetAccountVisible?.(id, body.visible)
188
+ } catch (error) {
189
+ writeJson(res, 500, { ok: false, error: messageOf(error) })
190
+ return
191
+ }
192
+ writeJson(res, 200, { ok: true, id, visible: body.visible })
193
+ }
137
194
 
138
195
  // ── 登录流(两段式设备授权:Client 拿 URL → 浏览器授权 → Client 轮询)──
139
196
  //
@@ -174,38 +231,48 @@ export function makeManageRoutes(deps) {
174
231
  }
175
232
  }
176
233
 
177
- /** 池子当前状态(含每账号余额,拉取失败给 null)。 */
234
+ /** 池子当前状态(含每账号余额与栏位可见性,拉取失败给 null)。 */
178
235
  const summaryHandler = async (_req, res) => {
179
236
  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) {
237
+ const hidden = new Set(Array.isArray(deps.settings?.hiddenModelLists) ? deps.settings.hiddenModelLists : [])
238
+ /**
239
+ * 余额并行拉取(纯读、账号间无依赖):串行时最坏 30s × N(fetchBalance
240
+ * 每账号超时 30s),面板会一直「加载中…」。
241
+ * fetchBalance 失败路径返回 undefined / 抛错都归一为 null —— 明确下发
242
+ * `balance: null`,客户端(client.js load)只对缺键的账号补拉 /balance,
243
+ * 避免同一端点被二次重试双倍消耗。
244
+ */
245
+ const balances = await Promise.all(
246
+ entries.map(async (entry) => {
247
+ if (typeof fetchBalance !== 'function' || entry.enabled !== true) return null
185
248
  try {
186
249
  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
- }
250
+ if (balance === undefined) return null
251
+ return balance.enterprise === true
252
+ ? { enterprise: true, remaining: null, total: null, planName: null }
253
+ : {
254
+ enterprise: false,
255
+ remaining: typeof balance.remaining === 'number' ? balance.remaining : null,
256
+ total: typeof balance.total === 'number' ? balance.total : null,
257
+ planName: balance.planName ?? null,
258
+ }
197
259
  } catch {
198
- view.balance = null
260
+ return null
199
261
  }
200
- } else {
201
- view.balance = null
202
- }
203
- accounts.push(view)
204
- }
262
+ }),
263
+ )
264
+ const accounts = entries.map((entry, index) => {
265
+ const view = publicAccount(entry, index)
266
+ /** 账号「模型栏位」是否显示(面板每卡片右侧的开关状态)。 */
267
+ view.modelListVisible = !hidden.has(entry.id)
268
+ view.balance = balances[index]
269
+ return view
270
+ })
205
271
  writeJson(res, 200, {
206
272
  ok: true,
207
273
  accounts,
208
274
  enabledCount: accounts.filter((account) => account.enabled).length,
275
+ unifiedModelList: deps.settings?.unifiedModelList !== false,
209
276
  fetchedAt: Date.now(),
210
277
  })
211
278
  }
@@ -252,6 +319,7 @@ export function makeManageRoutes(deps) {
252
319
  return
253
320
  }
254
321
  pool.setEnabled(id, enabled)
322
+ notifyChanged()
255
323
  writeJson(res, 200, { ok: true, id, enabled })
256
324
  }
257
325
 
@@ -268,6 +336,7 @@ export function makeManageRoutes(deps) {
268
336
  writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
269
337
  return
270
338
  }
339
+ notifyChanged()
271
340
  writeJson(res, 200, { ok: true, id })
272
341
  }
273
342
 
@@ -293,6 +362,7 @@ export function makeManageRoutes(deps) {
293
362
  return
294
363
  }
295
364
  pool.reorder(ids)
365
+ notifyChanged()
296
366
  writeJson(res, 200, { ok: true, ids })
297
367
  }
298
368
 
@@ -311,6 +381,7 @@ export function makeManageRoutes(deps) {
311
381
  return
312
382
  }
313
383
  pool.patchAccount(id, { nickname })
384
+ notifyChanged()
314
385
  writeJson(res, 200, { ok: true, id, nickname })
315
386
  }
316
387
 
@@ -335,6 +406,7 @@ export function makeManageRoutes(deps) {
335
406
  }
336
407
  const ids = [id, ...entries.map((item) => item.id).filter((existing) => existing !== id)]
337
408
  pool.reorder(ids)
409
+ notifyChanged()
338
410
  writeJson(res, 200, { ok: true, id, order: ids })
339
411
  }
340
412
 
@@ -390,6 +462,7 @@ export function makeManageRoutes(deps) {
390
462
  source: 'plugin-web',
391
463
  }
392
464
  const { entry, created } = pool.add(credential)
465
+ notifyChanged()
393
466
  log(`[manage] 通过 Web UI ${created ? '添加' : '更新'}账号:${entry.nickname}(${record.channel})`)
394
467
  writeJson(res, 200, {
395
468
  ok: true,
@@ -408,6 +481,8 @@ export function makeManageRoutes(deps) {
408
481
  { kind: 'exact', path: `${MANAGE_PREFIX}/reorder`, handler: guard(reorderHandler) },
409
482
  { kind: 'exact', path: `${MANAGE_PREFIX}/rename`, handler: guard(renameHandler) },
410
483
  { kind: 'exact', path: `${MANAGE_PREFIX}/use`, handler: guard(useHandler) },
484
+ { kind: 'exact', path: `${MANAGE_PREFIX}/unified-list`, handler: guard(unifiedListHandler) },
485
+ { kind: 'exact', path: `${MANAGE_PREFIX}/model-list-visible`, handler: guard(modelListVisibleHandler) },
411
486
  { kind: 'exact', path: `${MANAGE_PREFIX}/login/start`, handler: guard(loginStartHandler) },
412
487
  { kind: 'exact', path: `${MANAGE_PREFIX}/login/poll`, handler: guard(loginPollHandler) },
413
488
  ]
@@ -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
  /**
@@ -234,14 +308,14 @@ export class ZcodePlanClient {
234
308
  * ③ 本次请求已逐个试完 → 汇报试了几个
235
309
  * 统一报「账号池为空」会把人带去错误的排查方向(实测踩过)。
236
310
  */
237
- const total = this.#pool.list().length
238
- const enabledCount = this.#pool.list().filter((entry) => entry.enabled).length
311
+ const total = this.#pool.list()
312
+ const enabledCount = total.filter((entry) => entry.enabled).length
239
313
  let message
240
- if (total === 0) {
314
+ if (total.length === 0) {
241
315
  message = '账号池为空。请先运行 `zcode-start-plan login` 添加 ZCode 账号。'
242
316
  } else if (tried.size === 0) {
243
317
  message = enabledCount === 0
244
- ? `账号池里有 ${total} 个账号,但全部被停用。用 \`zcode-start-plan enable <序号>\` 启用,或登录新账号。`
318
+ ? `账号池里有 ${total.length} 个账号,但全部被停用。用 \`zcode-start-plan enable <序号>\` 启用,或登录新账号。`
245
319
  : `模型「${model}」在 ${enabledCount} 个启用账号上都已限流(免费额度按自然日 UTC+8 结算)。` +
246
320
  `${detail}可等次日重置、换一个模型(config.models),或用 \`zcode-start-plan claim\` 领取当日额度。`
247
321
  } else {
@@ -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
@@ -25,6 +25,21 @@
25
25
  *
26
26
  * `usage` 必须在 `finish` 之前;`finish` 之后不得再有任何 chunk;工具参数以
27
27
  * **原始 JSON 字符串**增量下发。故这里采用「先 `block-end`,再 `usage`,再 `finish`」。
28
+ *
29
+ * ## finish chunk 的形状(官方契约,`dsh-llm` rc.3 起有 .d.ts 钉死)
30
+ *
31
+ * 终止块是 `{ type: 'finish', reason: FinishReason }` —— `reason` 是**对象**,
32
+ * 按 kind 区分(`FinishReasonMap`,`dsh-llm/lib/types/types.d.ts`):
33
+ *
34
+ * ```
35
+ * { kind: 'stop' } | { kind: 'tool-calls' } | { kind: 'max-tokens' }
36
+ * { kind: 'aborted', failure } | { kind: 'error', failure }
37
+ * ```
38
+ *
39
+ * 宿主 `BlockAssembler` 读 `chunk.reason`(`this._finish = chunk.reason`),
40
+ * agent-loop 再读 `finish.kind === 'error' | 'aborted'` 判错。
41
+ * 之前发的是 `{ kind, failure }`(kind 在顶层、没有 reason)—— 错误会被宿主
42
+ * 静默吞成 `{ kind: 'stop' }`「正常结束」,重试与错误上报全部失效。
28
43
  */
29
44
 
30
45
  /**
@@ -225,12 +240,14 @@ export class AnthropicStreamTranslator {
225
240
  if (this.#sawError !== undefined) {
226
241
  out.push({
227
242
  type: 'finish',
228
- kind: 'error',
229
- failure: { code: mapErrorCode(this.#sawError), message: this.#sawError.message },
243
+ reason: {
244
+ kind: 'error',
245
+ failure: { code: mapErrorCode(this.#sawError), message: this.#sawError.message },
246
+ },
230
247
  })
231
248
  return out
232
249
  }
233
- out.push({ type: 'finish', kind: 'stop', reason: this.#finishReason ?? 'stop' })
250
+ out.push({ type: 'finish', reason: this.#finishReason ?? { kind: 'stop' } })
234
251
  return out
235
252
  }
236
253
 
@@ -247,18 +264,23 @@ export class AnthropicStreamTranslator {
247
264
  }
248
265
  }
249
266
 
250
- /** Anthropic `stop_reason` → DSH finish reason。 */
267
+ /**
268
+ * Anthropic `stop_reason` → DSH finish reason 对象(`FinishReasonMap` 形态)。
269
+ *
270
+ * ⚠ 返回的是 `reason` **对象**(`{ kind: '…' }`),不是字符串 ——
271
+ * `BlockAssembler` 会把它原样存进 `finish`,agent-loop 按 `finish.kind` 路由。
272
+ */
251
273
  export function mapStopReason(stopReason) {
252
274
  switch (stopReason) {
253
275
  case 'tool_use':
254
- return 'tool-calls'
276
+ return { kind: 'tool-calls' }
255
277
  case 'max_tokens':
256
- return 'length'
278
+ return { kind: 'max-tokens' }
257
279
  case 'end_turn':
258
280
  case 'stop_sequence':
259
- return 'stop'
281
+ return { kind: 'stop' }
260
282
  default:
261
- return 'stop'
283
+ return { kind: 'stop' }
262
284
  }
263
285
  }
264
286