dsh-zcode-startplan 0.5.2 → 1.0.3

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 (51) hide show
  1. package/CHANGELOG.md +1963 -672
  2. package/README.md +92 -472
  3. package/bin/cli.mjs +509 -450
  4. package/client.js +2459 -1002
  5. package/cordis.patch.yml +4 -2
  6. package/index.js +109 -11
  7. package/lib/adapter.js +476 -449
  8. package/lib/anthropic-body.js +513 -469
  9. package/lib/assemble.js +808 -542
  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 -652
  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 -611
  23. package/lib/upstream.js +294 -134
  24. package/lib/version-probe.js +110 -0
  25. package/package.json +84 -81
  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 -116
  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/auto-claim.test.mjs +318 -0
  35. package/tests/claim-routes.test.mjs +438 -293
  36. package/tests/client-panel.test.mjs +1141 -356
  37. package/tests/distribution-keys.test.mjs +123 -0
  38. package/tests/e2e.test.mjs +388 -353
  39. package/tests/fallback-scrub.test.mjs +105 -0
  40. package/tests/launch-command.test.mjs +68 -0
  41. package/tests/openai-gateway.test.mjs +454 -0
  42. package/tests/pinned-models.test.mjs +505 -497
  43. package/tests/plan-client.test.mjs +582 -222
  44. package/tests/pool.test.mjs +319 -93
  45. package/tests/quota-blackhole.test.mjs +409 -0
  46. package/tests/restart-script.test.mjs +53 -0
  47. package/tests/routing-quota.test.mjs +251 -0
  48. package/tests/support/hanging-stream.mjs +48 -0
  49. package/tests/upstream-error-200.test.mjs +164 -125
  50. package/tests/upstream.test.mjs +330 -250
  51. package/tests/version-probe.test.mjs +172 -0
package/lib/adapter.js CHANGED
@@ -1,449 +1,476 @@
1
- /**
2
- * 两个 llm 适配器:**原生适配器**(默认)与 **pi-ai 适配器**(可选回落)。
3
- *
4
- * ## 为什么是「适配器」而不是代理
5
- *
6
- * DSH 里每个请求都由 `ctx.llm` 分派给某个 adapter;adapter 负责把上游 wire 翻成 DSH 的
7
- * `StreamChunk` 词汇。参考实现(ZCode 插件)是一层本地 HTTP 代理,由 ZCode 自带的
8
- * Anthropic SDK 解析字节流——DSH 侧没有那条通道,所以这里直接实现 adapter:
9
- *
10
- * ```
11
- * NativeZcodeStartPlanAdapter ← 推荐:账号池 / captcha / 切号 / 重试 全在本插件内
12
- * PiAiZcodeStartPlanAdapter ← 可选:沿用 DSH 的 dsh-llm-pi-ai,本插件只做参数注入
13
- * ```
14
- *
15
- * pi-ai 适配器之所以能工作,是因为它只按「provider 名」路由:`llm-pi-ai` 的
16
- * `providers` 配置里可以声明任意自定义 provider(`api: anthropic-messages` +
17
- * `baseURL`),而本插件把自己暴露成 `127.0.0.1:<port>` 上的 Anthropic 兼容端点
18
- * (`lib/local-endpoint.js`)。两条路共用同一套账号池与 captcha 产出器。
19
- */
20
-
21
- import { AnthropicStreamTranslator } from './stream-translator.js'
22
- import { ZCODE_FALLBACK_MODELS } from './upstream.js'
23
- import { parsePinnedModelId } from './pinned-model.js'
24
-
25
- /** 从上游模型目录构造 DSH 的 `LlmModelInfo`。 */
26
- export function toModelInfo(provider, model) {
27
- const info = {
28
- provider,
29
- id: model.id,
30
- name: model.name ?? model.id,
31
- inputModalities: model.supportsImage === false ? ['text'] : ['text', 'image'],
32
- context: { contextWindow: model.contextWindow ?? 1_000_000 },
33
- defaultMaxTokens: model.maxTokens ?? 32_768,
34
- }
35
- if (typeof model.description === 'string' && model.description.length > 0) {
36
- /** 宿主 `listModels` 允许可选的 string description(模型选择器的说明文字)。 */
37
- info.description = model.description
38
- }
39
- if (Array.isArray(model.reasoningLevels) && model.reasoningLevels.length > 0) {
40
- /**
41
- * 思考档位。
42
- *
43
- * ⚠ 每个 effort **必须同时有非空 `id` 和非空 `name`**,且 `id` 不得重复 ——
44
- * `dsh-llm` 的 `normalizeModelInfo` 会逐项校验,缺一个字段就抛
45
- * `INVALID_MODEL_REASONING`("invalid or duplicate reasoning effort metadata"),
46
- * 整个模型在宿主里不可用。
47
- *
48
- * `name` 用档位 id 的展示名(如 `low` → `Low`);`id` 原样透传,
49
- * 因为 `plan-client` 发请求时按上游档位键取值。
50
- */
51
- const efforts = []
52
- const seen = new Set()
53
- for (const level of model.reasoningLevels) {
54
- const id = typeof level === 'string' ? level.trim() : ''
55
- if (id.length === 0 || seen.has(id)) continue
56
- seen.add(id)
57
- efforts.push({ id, name: id.charAt(0).toUpperCase() + id.slice(1) })
58
- }
59
- if (efforts.length > 0) {
60
- info.reasoning = {
61
- efforts,
62
- ...(typeof model.defaultReasoningLevel === 'string' && model.defaultReasoningLevel.length > 0
63
- ? { defaultEffort: model.defaultReasoningLevel }
64
- : {}),
65
- }
66
- }
67
- }
68
- return info
69
- }
70
-
71
- const findModel = (models, id) => models.find((model) => model.id === id)
72
-
73
- /**
74
- * 原生适配器:一次 `stream()` 就是一次 plan-client 调用 + 流翻译。
75
- *
76
- * 只实现 DSH `LlmAdapter` 契约里必需的方法(`providerInfo` / `listModels` /
77
- * `resolveModel` / `stream`);不 `extends` 具体类,避免与宿主版本耦合。
78
- *
79
- * ## 多路由(workbuddy 模式,0.4.0)
80
- *
81
- * **一个 adapter 实例服务一整组 provider 路由**:
82
- *
83
- * ```
84
- * zcode-start-plan ← 统一选号(手动顺序自动换号;可见性可在面板关)
85
- * zcode-start-plan-acct-<id> ← 每个启用账号一栏(「ZCode Start Plan · 主号」),
86
- * 请求固定消耗该账号的额度
87
- * ```
88
- *
89
- * 路由可见性照抄 workbuddy 的实证做法(`@venshell/dsh-workbuddy-connect`):
90
- * provider **无条件注册**,隐藏一个栏位 = 它的 `listModels` 返回**空数组**
91
- * (宿主会过滤掉没有模型的分组)—— 登录/开关发生在启动后也不需要重新注册路由,
92
- * 老会话的路由始终可达。账号增删/启停时由 assemble 用
93
- * `registerAdapter` 返回的 `handle.replace()` 原子换路由。
94
- */
95
- export class NativeZcodeStartPlanAdapter {
96
- #client
97
- #models
98
- #provider
99
- #displayName
100
- #log
101
- #pool
102
- /** 是否为每个启用账号注册独立 provider 栏位(config.accountProviders)。 */
103
- #accountProviders
104
- /** 统一选号栏位当前是否可见(面板开关,assemble 持久化)。 */
105
- #unifiedVisible
106
- /** 被面板隐藏「模型栏位」的账号 id 集合(栏位路由仍注册,靠空目录隐藏)。 */
107
- #hiddenAccounts
108
-
109
- /**
110
- * @param {{
111
- * client: import('./plan-client.js').ZcodePlanClient,
112
- * models: () => Promise<Array<any>>,
113
- * provider?: string,
114
- * displayName?: string,
115
- * log?: (message: string) => void,
116
- * accountProviders?: boolean,
117
- * pool?: import('./pool.js').AccountPool,
118
- * }} options
119
- */
120
- constructor(options) {
121
- this.#client = options.client
122
- this.#models = options.models
123
- this.#provider = options.provider ?? 'zcode-start-plan'
124
- this.#displayName = options.displayName ?? 'ZCode Start Plan(赠送免费 plan)'
125
- this.#log = options.log ?? (() => {})
126
- this.#accountProviders = options.accountProviders !== false
127
- this.#pool = options.pool
128
- /** 统一选号栏位默认可见;面板开关经 setUnifiedVisible() 翻转。 */
129
- this.#unifiedVisible = options.unifiedVisible !== false
130
- this.#hiddenAccounts = new Set(
131
- Array.isArray(options.hiddenAccounts) ? options.hiddenAccounts.filter((id) => typeof id === 'string') : [],
132
- )
133
- }
134
-
135
- /** 面板开关「统一选号」栏位的可见性(重启后由 assemble 恢复)。 */
136
- setUnifiedVisible(visible) {
137
- this.#unifiedVisible = visible === true
138
- }
139
-
140
- /** 面板开关单个账号栏位的可见性(重启后由 assemble 恢复)。 */
141
- setAccountVisible(accountId, visible) {
142
- if (visible === true) this.#hiddenAccounts.delete(accountId)
143
- else this.#hiddenAccounts.add(accountId)
144
- }
145
-
146
- /** 账号栏位当前是否显示(面板展示与持久化用)。 */
147
- isAccountVisible(accountId) {
148
- return !this.#hiddenAccounts.has(accountId)
149
- }
150
-
151
- /**
152
- * 派生 provider 名与账号 id 的互逆映射。
153
- *
154
- * 路由名 = `<统一前缀>-acct-<账号id>`;统一路由本身不可能是账号路由
155
- * (统一路由名来自 config,账号路由多一段 `-acct-` 且账号 id 是 UUID)。
156
- */
157
- static accountRoute(providerBase, accountId) {
158
- return `${providerBase}-acct-${accountId}`
159
- }
160
-
161
- static accountIdFromRoute(providerBase, provider) {
162
- const prefix = `${providerBase}-acct-`
163
- return typeof provider === 'string' && provider.startsWith(prefix) && provider.length > prefix.length
164
- ? provider.slice(prefix.length)
165
- : null
166
- }
167
-
168
- /** 当前「启用账号 × 基础模型」的钉定路由表(assemble 用它算 replace 集合)。 */
169
- async accountRoutes() {
170
- if (this.#accountProviders !== true || this.#pool === undefined) return []
171
- return (await this.#pool.list()).filter((entry) => entry.enabled === true).map((entry) => ({
172
- provider: NativeZcodeStartPlanAdapter.accountRoute(this.#provider, entry.id),
173
- accountId: entry.id,
174
- nickname: entry.nickname,
175
- }))
176
- }
177
-
178
- providerInfo(provider) {
179
- const accountId = NativeZcodeStartPlanAdapter.accountIdFromRoute(this.#provider, provider)
180
- if (accountId !== null) {
181
- const account = this.#pool?.get(accountId)
182
- const nickname = account?.nickname ?? '已删除的账号'
183
- return { id: provider, name: `ZCode Start Plan · ${nickname}` }
184
- }
185
- return { id: provider, name: this.#displayName }
186
- }
187
-
188
- /**
189
- * 重试策略。
190
- *
191
- * ⚠ **必须实现**:`ctx.llm.registerAdapter()` 在 `prepareRoutes` 里会**直接调用**
192
- * `adapter.providerRetryPolicy(provider)`(没有可选调用保护),漏掉它在宿主里报
193
- * `adapter.providerRetryPolicy is not a function`,整条路由注册失败 ——
194
- * 表现为「工具注册成功、模型列表里却没有」。
195
- *
196
- * 返回 `undefined` 表示用宿主默认策略:本插件的重试已由
197
- * `plan-client` 按上游错误表(3009 退避 / 3007 换 captcha / 3012 不重试)编排,
198
- * 不需要宿主再包一层。
199
- *
200
- * @param {string} _provider
201
- * @returns {undefined}
202
- */
203
- providerRetryPolicy(_provider) {
204
- return undefined
205
- }
206
-
207
- /**
208
- * ⚠ **必须实现**:DSH 0.2.1-rc.3 起,token-meter / 压缩链路会**直接调用**
209
- * `adapter.imageRequestPricing(provider, model)`(宿主 `ctx.llm` 的转发处
210
- * 没有可选调用保护),本适配器按 rc.2 契约实现、未继承宿主基类,漏掉它
211
- * 在压缩压力判定时抛 `adapter.imageRequestPricing is not a function`。
212
- * 返回 `undefined` = 该路由不声明图片计价(宿主基类的缺省行为)。
213
- *
214
- * @param {string} _provider
215
- * @param {string} _model
216
- * @returns {undefined}
217
- */
218
- imageRequestPricing(_provider, _model) {
219
- return undefined
220
- }
221
-
222
- /**
223
- * 账号栏位的模型目录:基础模型 × 该账号(description 带额度状态)。
224
- *
225
- * 账号已删除/停用时返回空数组 —— 宿主会隐藏没有模型的分组,这正是
226
- * workbuddy 的可见性机制;路由本身留着,老会话不炸。
227
- */
228
- async #accountModels(provider, accountId) {
229
- const [baseModels, entry] = await Promise.all([this.#models(), Promise.resolve(this.#pool?.get(accountId))])
230
- if (entry === undefined || entry.enabled !== true) return []
231
- const now = Date.now()
232
- return baseModels.map((model) => {
233
- const limitedUntil = entry.model_rate_limits?.[model.id]
234
- const limited = typeof limitedUntil === 'number' && limitedUntil > now
235
- const reset = limited
236
- ? new Date(limitedUntil).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
237
- : ''
238
- const meta = toModelInfo(provider, model)
239
- return {
240
- ...meta,
241
- description: limited
242
- ? `固定使用「${entry.nickname}」的额度(该模型限流至 ${reset})`
243
- : `固定使用「${entry.nickname}」的额度,不自动换号`,
244
- }
245
- })
246
- }
247
-
248
- async listModels(provider) {
249
- const accountId = NativeZcodeStartPlanAdapter.accountIdFromRoute(this.#provider, provider)
250
- /** 账号栏位:只列该账号的模型;面板隐藏/停用/删除 = 空目录 = 隐藏该栏位。 */
251
- if (accountId !== null) {
252
- if (this.#hiddenAccounts.has(accountId)) return []
253
- return this.#accountModels(provider, accountId)
254
- }
255
- /** 统一栏位:面板关掉 = 空目录 = 宿主隐藏分组(路由保留,老会话不炸)。 */
256
- if (this.#unifiedVisible !== true) return []
257
- return (await this.#models()).map((model) => toModelInfo(provider, model))
258
- }
259
-
260
- async resolveModel(provider, model) {
261
- const accountId = NativeZcodeStartPlanAdapter.accountIdFromRoute(this.#provider, provider)
262
- const idPin = parsePinnedModelId(model)
263
- const lookupId = idPin === null ? model : idPin.baseModelId
264
- const found = findModel(await this.#models(), lookupId)
265
- if (found === undefined) return { provider, id: model, name: model }
266
- const meta = toModelInfo(provider, found)
267
- /** 0.3.0 的 @acct: 后缀仍原样放行(id 与请求一致是宿主硬契约)。 */
268
- if (idPin !== null) return { ...meta, id: model }
269
- return meta
270
- }
271
-
272
- /**
273
- * 绑定「精确模型元数据」与「最终派发」。
274
- *
275
- * ⚠ **必须实现**:宿主在真正发起请求前调用 `adapter.prepareCall(provider, model, signal)`。
276
- * 基类 `LlmAdapter` 提供了默认实现,但本适配器**没有 extends 基类**(避免与宿主版本耦合),
277
- * 所以必须自己补 —— 漏掉它表现为
278
- * `registration.adapter.prepareCall is not a function`:**选模型即报错**。
279
- *
280
- * 语义(与宿主基类一致):返回的 `model` 是该模型的精确元数据,
281
- * `stream` 是**同一次准备代际**的流入口。
282
- *
283
- * @param {string} provider
284
- * @param {string} model
285
- * @param {AbortSignal} [signal]
286
- */
287
- async prepareCall(provider, model, signal) {
288
- return {
289
- model: await this.resolveModel(provider, model, signal),
290
- stream: (options) => this.stream(options),
291
- }
292
- }
293
-
294
- /**
295
- * 流式调用。
296
- *
297
- * ⚠ 失败以 **terminal `finish` 错误 chunk** 收尾(DSH 契约:每次流恰好一个终止 chunk),
298
- * 而不是抛异常 —— 抛异常会让 agent-loop 把整步标成插件崩溃。
299
- *
300
- * @param {any} options DSH GenerateOptions
301
- */
302
- stream(options) {
303
- const adapter = this
304
- return (async function* () {
305
- const provider = options.provider ?? adapter.#provider
306
- const translator = new AnthropicStreamTranslator()
307
- let failure
308
- try {
309
- /** 钉定 id 解析回基础模型查元数据(plan-client 内部同样会解析)。 */
310
- const idPin = parsePinnedModelId(options.model)
311
- const lookupId = idPin === null ? options.model : idPin.baseModelId
312
- const resolved = findModel(await adapter.#models(), lookupId)
313
- const result = await adapter.#client.call({
314
- options: { ...options, provider },
315
- /** 账号栏位 → 路由级钉定;@acct: 后缀由 plan-client 自己解析。 */
316
- pinnedAccountId: NativeZcodeStartPlanAdapter.accountIdFromRoute(adapter.#provider, provider) ?? undefined,
317
- model: resolved,
318
- maxTokens: options.maxTokens,
319
- signal: options.signal,
320
- onRetry: (info) => adapter.#log(`[zcode] 重试(${info.reason},第 ${info.attempt + 1} 次):${info.message}`),
321
- })
322
-
323
- /** ① 先消费判定阶段缓冲的事件(含首个内容帧),② 再接续剩余流。 */
324
- for (const event of result.head) {
325
- for (const chunk of translator.push(event)) yield chunk
326
- }
327
- if (result.decoder !== undefined) {
328
- for (;;) {
329
- const next = await result.decoder.read()
330
- if (next.done === true) break
331
- for (const chunk of translator.push(next.value)) yield chunk
332
- }
333
- }
334
- } catch (error) {
335
- failure = {
336
- code: error?.code ?? 'PROVIDER_ERROR',
337
- message: error instanceof Error ? error.message : String(error),
338
- }
339
- adapter.#log(`[zcode] 调用失败(${failure.code}):${failure.message}`)
340
- }
341
-
342
- if (failure !== undefined) {
343
- yield { type: 'usage', usage: { inputTokens: 0, outputTokens: 0 } }
344
- /**
345
- * ⚠ 终止块形状:`{ type: 'finish', reason: { kind, failure } }`。
346
- * `BlockAssembler` 读 `chunk.reason`;kind 放顶层时宿主读到 undefined,
347
- * 会把这次失败静默吞成「正常结束」—— 重试与错误上报全部失效。
348
- */
349
- yield { type: 'finish', reason: { kind: 'error', failure } }
350
- return
351
- }
352
- if (translator.error !== undefined) {
353
- for (const chunk of translator.finish()) yield chunk
354
- return
355
- }
356
- for (const chunk of translator.finish()) yield chunk
357
- })()
358
- }
359
- }
360
-
361
- /**
362
- * pi-ai 回落适配器:只提供 provider 元数据,真正的 wire 由 `dsh-llm-pi-ai` 负责。
363
- *
364
- * 使用条件:profile 里同时启用 `llm-pi-ai`,并给它声明本插件暴露的 provider:
365
- *
366
- * ```yaml
367
- * - id: llm-pi-ai
368
- * name: '@deepseek-ai/dsh-llm-pi-ai'
369
- * config:
370
- * providers:
371
- * zcode-start-plan:
372
- * displayName: ZCode Start Plan
373
- * api: anthropic-messages
374
- * baseURL: http://127.0.0.1:17899
375
- * apiKeyEnv: ZCODE_START_PLAN_LOCAL_TOKEN
376
- * models: [{ id: GLM-5.3-Flash, name: GLM-5.3-Flash }]
377
- * ```
378
- *
379
- * ⚠ 选它就意味着**放弃**本插件的切号/自动 captcha(那些在原生适配器里),
380
- * 只保留「本地端点 + captcha 产出」;默认配置里它是关的。
381
- */
382
- export class PiAiZcodeStartPlanAdapter {
383
- #models
384
- #displayName
385
-
386
- constructor(options) {
387
- this.#models = options.models
388
- this.#displayName = options.displayName ?? 'ZCode Start Plan(pi-ai 路由)'
389
- }
390
-
391
- providerInfo(provider) {
392
- return { id: provider, name: this.#displayName }
393
- }
394
-
395
- /**
396
- * 重试策略。
397
- *
398
- * ⚠ **必须实现**:`ctx.llm.registerAdapter()` 在 `prepareRoutes` 里会**直接调用**
399
- * `adapter.providerRetryPolicy(provider)`(没有可选调用保护),漏掉它在宿主里报
400
- * `adapter.providerRetryPolicy is not a function`,整条路由注册失败 ——
401
- * 表现为「工具注册成功、模型列表里却没有」。
402
- *
403
- * 返回 `undefined` 表示用宿主默认策略:本插件的重试已由
404
- * `plan-client` 按上游错误表(3009 退避 / 3007 换 captcha / 3012 不重试)编排,
405
- * 不需要宿主再包一层。
406
- *
407
- * @param {string} _provider
408
- * @returns {undefined}
409
- */
410
- providerRetryPolicy(_provider) {
411
- return undefined
412
- }
413
-
414
- /**
415
- * ⚠ **必须实现**:DSH 0.2.1-rc.3 起 token-meter / 压缩链路直接调用(同上,
416
- * 见 NativeZcodeStartPlanAdapter.imageRequestPricing 的注释)。
417
- *
418
- * @param {string} _provider
419
- * @param {string} _model
420
- * @returns {undefined}
421
- */
422
- imageRequestPricing(_provider, _model) {
423
- return undefined
424
- }
425
-
426
- async listModels(provider) {
427
- return (await this.#models()).map((model) => toModelInfo(provider, model))
428
- }
429
-
430
- /**
431
- * 绑定「精确模型元数据」与「最终派发」。
432
- *
433
- * ⚠ 必须实现:宿主在真正发起请求前调用 `adapter.prepareCall(provider, model, signal)`;
434
- * 漏掉它表现为 `registration.adapter.prepareCall is not a function`(选模型即报错)。
435
- * 本回落适配器不自己发流(由 `dsh-llm-pi-ai` 负责),故 `stream` 交回宿主默认路径。
436
- *
437
- * @param {string} provider
438
- * @param {string} model
439
- * @param {AbortSignal} [signal]
440
- */
441
- async prepareCall(provider, model, signal) {
442
- const found = findModel(await this.#models(), model)
443
- const resolved = found === undefined ? { provider, id: model, name: model } : toModelInfo(provider, found)
444
- return { model: resolved, stream: undefined }
445
- }
446
- }
447
-
448
- /** 兜底模型表。 */
449
- export { ZCODE_FALLBACK_MODELS }
1
+ /**
2
+ * 两个 llm 适配器:**原生适配器**(默认)与 **pi-ai 适配器**(可选回落)。
3
+ *
4
+ * ## 为什么是「适配器」而不是代理
5
+ *
6
+ * DSH 里每个请求都由 `ctx.llm` 分派给某个 adapter;adapter 负责把上游 wire 翻成 DSH 的
7
+ * `StreamChunk` 词汇。参考实现(ZCode 插件)是一层本地 HTTP 代理,由 ZCode 自带的
8
+ * Anthropic SDK 解析字节流——DSH 侧没有那条通道,所以这里直接实现 adapter:
9
+ *
10
+ * ```
11
+ * NativeZcodeStartPlanAdapter ← 推荐:账号池 / captcha / 切号 / 重试 全在本插件内
12
+ * PiAiZcodeStartPlanAdapter ← 可选:沿用 DSH 的 dsh-llm-pi-ai,本插件只做参数注入
13
+ * ```
14
+ *
15
+ * pi-ai 适配器之所以能工作,是因为它只按「provider 名」路由:`llm-pi-ai` 的
16
+ * `providers` 配置里可以声明任意自定义 provider(`api: anthropic-messages` +
17
+ * `baseURL`),而本插件把自己暴露成 `127.0.0.1:<port>` 上的 Anthropic 兼容端点
18
+ * (`lib/local-endpoint.js`)。两条路共用同一套账号池与 captcha 产出器。
19
+ */
20
+
21
+ import { AnthropicStreamTranslator } from './stream-translator.js'
22
+ import { ZCODE_FALLBACK_MODELS } from './upstream.js'
23
+ import { parsePinnedModelId } from './pinned-model.js'
24
+ import { scrubFailureChunk } from './fallback.js'
25
+
26
+ /** 从上游模型目录构造 DSH 的 `LlmModelInfo`。 */
27
+ export function toModelInfo(provider, model) {
28
+ const info = {
29
+ provider,
30
+ id: model.id,
31
+ name: model.name ?? model.id,
32
+ inputModalities: model.supportsImage === false ? ['text'] : ['text', 'image'],
33
+ context: { contextWindow: model.contextWindow ?? 1_000_000 },
34
+ defaultMaxTokens: model.maxTokens ?? 32_768,
35
+ }
36
+ if (typeof model.description === 'string' && model.description.length > 0) {
37
+ /** 宿主 `listModels` 允许可选的 string description(模型选择器的说明文字)。 */
38
+ info.description = model.description
39
+ }
40
+ if (Array.isArray(model.reasoningLevels) && model.reasoningLevels.length > 0) {
41
+ /**
42
+ * 思考档位。
43
+ *
44
+ * ⚠ 每个 effort **必须同时有非空 `id` 和非空 `name`**,且 `id` 不得重复 ——
45
+ * `dsh-llm` 的 `normalizeModelInfo` 会逐项校验,缺一个字段就抛
46
+ * `INVALID_MODEL_REASONING`("invalid or duplicate reasoning effort metadata"),
47
+ * 整个模型在宿主里不可用。
48
+ *
49
+ * `name` 用档位 id 的展示名(如 `low` → `Low`);`id` 原样透传,
50
+ * 因为 `plan-client` 发请求时按上游档位键取值。
51
+ */
52
+ const efforts = []
53
+ const seen = new Set()
54
+ for (const level of model.reasoningLevels) {
55
+ const id = typeof level === 'string' ? level.trim() : ''
56
+ if (id.length === 0 || seen.has(id)) continue
57
+ seen.add(id)
58
+ efforts.push({ id, name: id.charAt(0).toUpperCase() + id.slice(1) })
59
+ }
60
+ if (efforts.length > 0) {
61
+ info.reasoning = {
62
+ efforts,
63
+ ...(typeof model.defaultReasoningLevel === 'string' && model.defaultReasoningLevel.length > 0
64
+ ? { defaultEffort: model.defaultReasoningLevel }
65
+ : {}),
66
+ }
67
+ }
68
+ }
69
+ return info
70
+ }
71
+
72
+ const findModel = (models, id) => models.find((model) => model.id === id)
73
+
74
+ /**
75
+ * 图片计价的空实现(两个适配器共用)。
76
+ *
77
+ * ⚠ **必须实现**:DSH 0.2.1-rc.3 起,token-meter / 压缩链路会**直接调用**
78
+ * `adapter.imageRequestPricing(provider, model)`(宿主 `ctx.llm` 的转发处
79
+ * 没有可选调用保护),且本文件两个适配器都**不继承宿主基类**(刻意与宿主
80
+ * 版本解耦)——漏掉它在压缩压力判定时抛
81
+ * `adapter.imageRequestPricing is not a function`。
82
+ * 返回 `undefined` = 该路由不声明图片计价(宿主基类的缺省行为)。
83
+ */
84
+ function imageRequestPricingDefault(_provider, _model) {
85
+ return undefined
86
+ }
87
+
88
+ /**
89
+ * 原生适配器:一次 `stream()` 就是一次 plan-client 调用 + 流翻译。
90
+ *
91
+ * 只实现 DSH `LlmAdapter` 契约里必需的方法(`providerInfo` / `listModels` /
92
+ * `resolveModel` / `stream`);不 `extends` 具体类,避免与宿主版本耦合。
93
+ *
94
+ * ## 多路由(workbuddy 模式,0.4.0)
95
+ *
96
+ * **一个 adapter 实例服务一整组 provider 路由**:
97
+ *
98
+ * ```
99
+ * zcode-start-plan ← 统一选号(手动顺序自动换号;可见性可在面板关)
100
+ * zcode-start-plan-acct-<id> ← 每个启用账号一栏(「ZCode Start Plan · 主号」),
101
+ * 请求固定消耗该账号的额度
102
+ * ```
103
+ *
104
+ * 路由可见性照抄 workbuddy 的实证做法(`@venshell/dsh-workbuddy-connect`):
105
+ * provider **无条件注册**,隐藏一个栏位 = 它的 `listModels` 返回**空数组**
106
+ * (宿主会过滤掉没有模型的分组)—— 登录/开关发生在启动后也不需要重新注册路由,
107
+ * 老会话的路由始终可达。账号增删/启停时由 assemble 用
108
+ * `registerAdapter` 返回的 `handle.replace()` 原子换路由。
109
+ */
110
+ export class NativeZcodeStartPlanAdapter {
111
+ #client
112
+ #models
113
+ #provider
114
+ #displayName
115
+ #log
116
+ #pool
117
+ /** 是否为每个启用账号注册独立 provider 栏位(config.accountProviders)。 */
118
+ #accountProviders
119
+ /** 统一选号栏位当前是否可见(面板开关,assemble 持久化)。 */
120
+ #unifiedVisible
121
+ /** 被面板隐藏「模型栏位」的账号 id 集合(栏位路由仍注册,靠空目录隐藏)。 */
122
+ #hiddenAccounts
123
+
124
+ /**
125
+ * @param {{
126
+ * client: import('./plan-client.js').ZcodePlanClient,
127
+ * models: () => Promise<Array<any>>,
128
+ * provider?: string,
129
+ * displayName?: string,
130
+ * log?: (message: string) => void,
131
+ * accountProviders?: boolean,
132
+ * pool?: import('./pool.js').AccountPool,
133
+ * }} options
134
+ */
135
+ constructor(options) {
136
+ this.#client = options.client
137
+ this.#models = options.models
138
+ this.#provider = options.provider ?? 'zcode-start-plan'
139
+ this.#displayName = options.displayName ?? 'ZCode Start Plan(赠送免费 plan)'
140
+ this.#log = options.log ?? (() => {})
141
+ this.#accountProviders = options.accountProviders !== false
142
+ this.#pool = options.pool
143
+ /** 统一选号栏位默认可见;面板开关经 setUnifiedVisible() 翻转。 */
144
+ this.#unifiedVisible = options.unifiedVisible !== false
145
+ this.#hiddenAccounts = new Set(
146
+ Array.isArray(options.hiddenAccounts) ? options.hiddenAccounts.filter((id) => typeof id === 'string') : [],
147
+ )
148
+ }
149
+
150
+ /** 面板开关「统一选号」栏位的可见性(重启后由 assemble 恢复)。 */
151
+ setUnifiedVisible(visible) {
152
+ this.#unifiedVisible = visible === true
153
+ }
154
+
155
+ /** 面板开关单个账号栏位的可见性(重启后由 assemble 恢复)。 */
156
+ setAccountVisible(accountId, visible) {
157
+ if (visible === true) this.#hiddenAccounts.delete(accountId)
158
+ else this.#hiddenAccounts.add(accountId)
159
+ }
160
+
161
+ /** 账号栏位当前是否显示(面板展示与持久化用)。 */
162
+ isAccountVisible(accountId) {
163
+ return !this.#hiddenAccounts.has(accountId)
164
+ }
165
+
166
+ /**
167
+ * 派生 provider 名与账号 id 的互逆映射。
168
+ *
169
+ * 路由名 = `<统一前缀>-acct-<账号id>`;统一路由本身不可能是账号路由
170
+ * (统一路由名来自 config,账号路由多一段 `-acct-` 且账号 id 是 UUID)。
171
+ */
172
+ static accountRoute(providerBase, accountId) {
173
+ return `${providerBase}-acct-${accountId}`
174
+ }
175
+
176
+ static accountIdFromRoute(providerBase, provider) {
177
+ const prefix = `${providerBase}-acct-`
178
+ return typeof provider === 'string' && provider.startsWith(prefix) && provider.length > prefix.length
179
+ ? provider.slice(prefix.length)
180
+ : null
181
+ }
182
+
183
+ /**
184
+ * 当前「启用账号 × 基础模型」的钉定路由表。
185
+ *
186
+ * ⚠ 这是**给测试/诊断用的观测面**:运行时真正的路由集合由
187
+ * `assemble.js` 的 `currentRoutes()` **同步**从 `pool.list()` 直接算,
188
+ * 不经过这里(因为要注册/替换路由,且 `pool.list()` 本身是同步的)。
189
+ *
190
+ * 0.10.0 审计:这里曾经是 `async`,但 `pool.list()` 是同步的 —— 返回 Promise
191
+ * 对任何「同步取路由集合」的调用方都是陷阱(`.filter` 直接抛
192
+ * `routes.filter is not a function`)。改回同步。
193
+ */
194
+ accountRoutes() {
195
+ if (this.#accountProviders !== true || this.#pool === undefined) return []
196
+ return this.#pool.list().filter((entry) => entry.enabled === true).map((entry) => ({
197
+ provider: NativeZcodeStartPlanAdapter.accountRoute(this.#provider, entry.id),
198
+ accountId: entry.id,
199
+ nickname: entry.nickname,
200
+ }))
201
+ }
202
+
203
+ providerInfo(provider) {
204
+ const accountId = NativeZcodeStartPlanAdapter.accountIdFromRoute(this.#provider, provider)
205
+ if (accountId !== null) {
206
+ const account = this.#pool?.get(accountId)
207
+ const nickname = account?.nickname ?? '已删除的账号'
208
+ return { id: provider, name: `ZCode Start Plan · ${nickname}` }
209
+ }
210
+ return { id: provider, name: this.#displayName }
211
+ }
212
+
213
+ /**
214
+ * 重试策略。
215
+ *
216
+ * ⚠ **必须实现**:`ctx.llm.registerAdapter()` 在 `prepareRoutes` 里会**直接调用**
217
+ * `adapter.providerRetryPolicy(provider)`(没有可选调用保护),漏掉它在宿主里报
218
+ * `adapter.providerRetryPolicy is not a function`,整条路由注册失败 ——
219
+ * 表现为「工具注册成功、模型列表里却没有」。
220
+ *
221
+ * 返回 `undefined` 表示用宿主默认策略:本插件的重试已由
222
+ * `plan-client` 按上游错误表(3009 退避 / 3007 换 captcha / 3012 不重试)编排,
223
+ * 不需要宿主再包一层。
224
+ *
225
+ * @param {string} _provider
226
+ * @returns {undefined}
227
+ */
228
+ providerRetryPolicy(_provider) {
229
+ return undefined
230
+ }
231
+
232
+ /**
233
+ * 图片计价:见模块级 `imageRequestPricingDefault`(宿主直调契约 + 空实现语义)。
234
+ *
235
+ * @param {string} _provider
236
+ * @param {string} _model
237
+ * @returns {undefined}
238
+ */
239
+ imageRequestPricing(_provider, _model) {
240
+ return imageRequestPricingDefault(_provider, _model)
241
+ }
242
+
243
+ /**
244
+ * 账号栏位的模型目录:基础模型 × 该账号(description 带额度状态)。
245
+ *
246
+ * 账号已删除/停用时返回空数组 —— 宿主会隐藏没有模型的分组,这正是
247
+ * workbuddy 的可见性机制;路由本身留着,老会话不炸。
248
+ */
249
+ async #accountModels(provider, accountId) {
250
+ const [baseModels, entry] = await Promise.all([this.#models(), Promise.resolve(this.#pool?.get(accountId))])
251
+ if (entry === undefined || entry.enabled !== true) return []
252
+ const now = Date.now()
253
+ return baseModels.map((model) => {
254
+ const limitedUntil = entry.model_rate_limits?.[model.id]
255
+ const limited = typeof limitedUntil === 'number' && limitedUntil > now
256
+ const reset = limited
257
+ ? new Date(limitedUntil).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
258
+ : ''
259
+ const meta = toModelInfo(provider, model)
260
+ return {
261
+ ...meta,
262
+ description: limited
263
+ ? `固定使用「${entry.nickname}」的额度(该模型限流至 ${reset})`
264
+ : `固定使用「${entry.nickname}」的额度,不自动换号`,
265
+ }
266
+ })
267
+ }
268
+
269
+ async listModels(provider) {
270
+ const accountId = NativeZcodeStartPlanAdapter.accountIdFromRoute(this.#provider, provider)
271
+ /** 账号栏位:只列该账号的模型;面板隐藏/停用/删除 = 空目录 = 隐藏该栏位。 */
272
+ if (accountId !== null) {
273
+ if (this.#hiddenAccounts.has(accountId)) return []
274
+ return this.#accountModels(provider, accountId)
275
+ }
276
+ /** 统一栏位:面板关掉 = 空目录 = 宿主隐藏分组(路由保留,老会话不炸)。 */
277
+ if (this.#unifiedVisible !== true) return []
278
+ return (await this.#models()).map((model) => toModelInfo(provider, model))
279
+ }
280
+
281
+ async resolveModel(provider, model) {
282
+ const accountId = NativeZcodeStartPlanAdapter.accountIdFromRoute(this.#provider, provider)
283
+ const idPin = parsePinnedModelId(model)
284
+ const lookupId = idPin === null ? model : idPin.baseModelId
285
+ const found = findModel(await this.#models(), lookupId)
286
+ if (found === undefined) return { provider, id: model, name: model }
287
+ const meta = toModelInfo(provider, found)
288
+ /** 0.3.0 的 @acct: 后缀仍原样放行(id 与请求一致是宿主硬契约)。 */
289
+ if (idPin !== null) return { ...meta, id: model }
290
+ return meta
291
+ }
292
+
293
+ /**
294
+ * 绑定「精确模型元数据」与「最终派发」。
295
+ *
296
+ * ⚠ **必须实现**:宿主在真正发起请求前调用 `adapter.prepareCall(provider, model, signal)`。
297
+ * 基类 `LlmAdapter` 提供了默认实现,但本适配器**没有 extends 基类**(避免与宿主版本耦合),
298
+ * 所以必须自己补 —— 漏掉它表现为
299
+ * `registration.adapter.prepareCall is not a function`:**选模型即报错**。
300
+ *
301
+ * 语义(与宿主基类一致):返回的 `model` 是该模型的精确元数据,
302
+ * `stream` 是**同一次准备代际**的流入口。
303
+ *
304
+ * @param {string} provider
305
+ * @param {string} model
306
+ * @param {AbortSignal} [signal]
307
+ */
308
+ async prepareCall(provider, model, signal) {
309
+ return {
310
+ model: await this.resolveModel(provider, model, signal),
311
+ stream: (options) => this.stream(options),
312
+ }
313
+ }
314
+
315
+ /**
316
+ * 流式调用。
317
+ *
318
+ * ⚠ 失败以 **terminal `finish` 错误 chunk** 收尾(DSH 契约:每次流恰好一个终止 chunk),
319
+ * 而不是抛异常 —— 抛异常会让 agent-loop 把整步标成插件崩溃。
320
+ *
321
+ * @param {any} options DSH GenerateOptions
322
+ */
323
+ stream(options) {
324
+ const adapter = this
325
+ return (async function* () {
326
+ const provider = options.provider ?? adapter.#provider
327
+ const translator = new AnthropicStreamTranslator()
328
+ let failure
329
+ try {
330
+ /** 钉定 id 解析回基础模型查元数据(plan-client 内部同样会解析)。 */
331
+ const idPin = parsePinnedModelId(options.model)
332
+ const lookupId = idPin === null ? options.model : idPin.baseModelId
333
+ const resolved = findModel(await adapter.#models(), lookupId)
334
+ const result = await adapter.#client.call({
335
+ options: { ...options, provider },
336
+ /** 账号栏位 → 路由级钉定;@acct: 后缀由 plan-client 自己解析。 */
337
+ pinnedAccountId: NativeZcodeStartPlanAdapter.accountIdFromRoute(adapter.#provider, provider) ?? undefined,
338
+ model: resolved,
339
+ maxTokens: options.maxTokens,
340
+ signal: options.signal,
341
+ onRetry: (info) => adapter.#log(`[zcode] 重试(${info.reason},第 ${info.attempt + 1} 次):${info.message}`),
342
+ })
343
+
344
+ /** ① 先消费判定阶段缓冲的事件(含首个内容帧),② 再接续剩余流。 */
345
+ for (const event of result.head) {
346
+ for (const chunk of translator.push(event)) yield chunk
347
+ }
348
+ if (result.decoder !== undefined) {
349
+ for (;;) {
350
+ const next = await result.decoder.read()
351
+ if (next.done === true) break
352
+ for (const chunk of translator.push(next.value)) yield chunk
353
+ }
354
+ }
355
+ } catch (error) {
356
+ failure = {
357
+ code: error?.code ?? 'PROVIDER_ERROR',
358
+ message: error instanceof Error ? error.message : String(error),
359
+ }
360
+ adapter.#log(`[zcode] 调用失败(${failure.code}):${failure.message}`)
361
+ }
362
+
363
+ if (failure !== undefined) {
364
+ /**
365
+ * 终止失败块:**先过脱敏闸**(`fallback.js`),再交给宿主。
366
+ *
367
+ * issue #2 的教训:任何一条把上游原文直接送往聊天记录的路径,
368
+ * 都会让用户看到「另一个通道」的业务文案(厂商名、soft_rate、原始 JSON),
369
+ * 排查方向当场被带偏。这里的分支同样可能带出上游文本(黑洞里的原句、
370
+ * 翻译器的失败原因),所以统一走 `scrubFailureChunk` —— code 保真,
371
+ * message 中性,完整原因只留在上方的 `#log`。
372
+ */
373
+ yield { type: 'usage', usage: { inputTokens: 0, outputTokens: 0 } }
374
+ yield scrubFailureChunk({
375
+ type: 'finish',
376
+ reason: { kind: 'error', failure },
377
+ })
378
+ return
379
+ }
380
+ if (translator.error !== undefined) {
381
+ for (const chunk of translator.finish()) yield scrubFailureChunk(chunk)
382
+ return
383
+ }
384
+ for (const chunk of translator.finish()) yield scrubFailureChunk(chunk)
385
+ })()
386
+ }
387
+ }
388
+
389
+ /**
390
+ * pi-ai 回落适配器:只提供 provider 元数据,真正的 wire 由 `dsh-llm-pi-ai` 负责。
391
+ *
392
+ * 使用条件:profile 里同时启用 `llm-pi-ai`,并给它声明本插件暴露的 provider:
393
+ *
394
+ * ```yaml
395
+ * - id: llm-pi-ai
396
+ * name: '@deepseek-ai/dsh-llm-pi-ai'
397
+ * config:
398
+ * providers:
399
+ * zcode-start-plan:
400
+ * displayName: ZCode Start Plan
401
+ * api: anthropic-messages
402
+ * baseURL: http://127.0.0.1:17899
403
+ * apiKeyEnv: ZCODE_START_PLAN_LOCAL_TOKEN
404
+ * models: [{ id: GLM-5.3-Flash, name: GLM-5.3-Flash }]
405
+ * ```
406
+ *
407
+ * ⚠ 选它就意味着**放弃**本插件的切号/自动 captcha(那些在原生适配器里),
408
+ * 只保留「本地端点 + captcha 产出」;默认配置里它是关的。
409
+ */
410
+ export class PiAiZcodeStartPlanAdapter {
411
+ #models
412
+ #displayName
413
+
414
+ constructor(options) {
415
+ this.#models = options.models
416
+ this.#displayName = options.displayName ?? 'ZCode Start Plan(pi-ai 路由)'
417
+ }
418
+
419
+ providerInfo(provider) {
420
+ return { id: provider, name: this.#displayName }
421
+ }
422
+
423
+ /**
424
+ * 重试策略。
425
+ *
426
+ * ⚠ **必须实现**:`ctx.llm.registerAdapter()` 在 `prepareRoutes` 里会**直接调用**
427
+ * `adapter.providerRetryPolicy(provider)`(没有可选调用保护),漏掉它在宿主里报
428
+ * `adapter.providerRetryPolicy is not a function`,整条路由注册失败 ——
429
+ * 表现为「工具注册成功、模型列表里却没有」。
430
+ *
431
+ * 返回 `undefined` 表示用宿主默认策略:本插件的重试已由
432
+ * `plan-client` 按上游错误表(3009 退避 / 3007 换 captcha / 3012 不重试)编排,
433
+ * 不需要宿主再包一层。
434
+ *
435
+ * @param {string} _provider
436
+ * @returns {undefined}
437
+ */
438
+ providerRetryPolicy(_provider) {
439
+ return undefined
440
+ }
441
+
442
+ /**
443
+ * 图片计价:见模块级 `imageRequestPricingDefault`(宿主直调契约 + 空实现语义)。
444
+ *
445
+ * @param {string} _provider
446
+ * @param {string} _model
447
+ * @returns {undefined}
448
+ */
449
+ imageRequestPricing(_provider, _model) {
450
+ return imageRequestPricingDefault(_provider, _model)
451
+ }
452
+
453
+ async listModels(provider) {
454
+ return (await this.#models()).map((model) => toModelInfo(provider, model))
455
+ }
456
+
457
+ /**
458
+ * 绑定「精确模型元数据」与「最终派发」。
459
+ *
460
+ * ⚠ 必须实现:宿主在真正发起请求前调用 `adapter.prepareCall(provider, model, signal)`;
461
+ * 漏掉它表现为 `registration.adapter.prepareCall is not a function`(选模型即报错)。
462
+ * 本回落适配器不自己发流(由 `dsh-llm-pi-ai` 负责),故 `stream` 交回宿主默认路径。
463
+ *
464
+ * @param {string} provider
465
+ * @param {string} model
466
+ * @param {AbortSignal} [signal]
467
+ */
468
+ async prepareCall(provider, model, signal) {
469
+ const found = findModel(await this.#models(), model)
470
+ const resolved = found === undefined ? { provider, id: model, name: model } : toModelInfo(provider, found)
471
+ return { model: resolved, stream: undefined }
472
+ }
473
+ }
474
+
475
+ /** 兜底模型表。 */
476
+ export { ZCODE_FALLBACK_MODELS }