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.
package/lib/adapter.js CHANGED
@@ -20,6 +20,7 @@
20
20
 
21
21
  import { AnthropicStreamTranslator } from './stream-translator.js'
22
22
  import { ZCODE_FALLBACK_MODELS } from './upstream.js'
23
+ import { parsePinnedModelId } from './pinned-model.js'
23
24
 
24
25
  /** 从上游模型目录构造 DSH 的 `LlmModelInfo`。 */
25
26
  export function toModelInfo(provider, model) {
@@ -31,6 +32,10 @@ export function toModelInfo(provider, model) {
31
32
  context: { contextWindow: model.contextWindow ?? 1_000_000 },
32
33
  defaultMaxTokens: model.maxTokens ?? 32_768,
33
34
  }
35
+ if (typeof model.description === 'string' && model.description.length > 0) {
36
+ /** 宿主 `listModels` 允许可选的 string description(模型选择器的说明文字)。 */
37
+ info.description = model.description
38
+ }
34
39
  if (Array.isArray(model.reasoningLevels) && model.reasoningLevels.length > 0) {
35
40
  /**
36
41
  * 思考档位。
@@ -70,6 +75,22 @@ const findModel = (models, id) => models.find((model) => model.id === id)
70
75
  *
71
76
  * 只实现 DSH `LlmAdapter` 契约里必需的方法(`providerInfo` / `listModels` /
72
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()` 原子换路由。
73
94
  */
74
95
  export class NativeZcodeStartPlanAdapter {
75
96
  #client
@@ -77,6 +98,13 @@ export class NativeZcodeStartPlanAdapter {
77
98
  #provider
78
99
  #displayName
79
100
  #log
101
+ #pool
102
+ /** 是否为每个启用账号注册独立 provider 栏位(config.accountProviders)。 */
103
+ #accountProviders
104
+ /** 统一选号栏位当前是否可见(面板开关,assemble 持久化)。 */
105
+ #unifiedVisible
106
+ /** 被面板隐藏「模型栏位」的账号 id 集合(栏位路由仍注册,靠空目录隐藏)。 */
107
+ #hiddenAccounts
80
108
 
81
109
  /**
82
110
  * @param {{
@@ -85,6 +113,8 @@ export class NativeZcodeStartPlanAdapter {
85
113
  * provider?: string,
86
114
  * displayName?: string,
87
115
  * log?: (message: string) => void,
116
+ * accountProviders?: boolean,
117
+ * pool?: import('./pool.js').AccountPool,
88
118
  * }} options
89
119
  */
90
120
  constructor(options) {
@@ -93,9 +123,65 @@ export class NativeZcodeStartPlanAdapter {
93
123
  this.#provider = options.provider ?? 'zcode-start-plan'
94
124
  this.#displayName = options.displayName ?? 'ZCode Start Plan(赠送免费 plan)'
95
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
+ }))
96
176
  }
97
177
 
98
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
+ }
99
185
  return { id: provider, name: this.#displayName }
100
186
  }
101
187
 
@@ -118,14 +204,69 @@ export class NativeZcodeStartPlanAdapter {
118
204
  return undefined
119
205
  }
120
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
+
121
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 []
122
257
  return (await this.#models()).map((model) => toModelInfo(provider, model))
123
258
  }
124
259
 
125
260
  async resolveModel(provider, model) {
126
- const found = findModel(await this.#models(), 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)
127
265
  if (found === undefined) return { provider, id: model, name: model }
128
- return toModelInfo(provider, found)
266
+ const meta = toModelInfo(provider, found)
267
+ /** 0.3.0 的 @acct: 后缀仍原样放行(id 与请求一致是宿主硬契约)。 */
268
+ if (idPin !== null) return { ...meta, id: model }
269
+ return meta
129
270
  }
130
271
 
131
272
  /**
@@ -165,9 +306,14 @@ export class NativeZcodeStartPlanAdapter {
165
306
  const translator = new AnthropicStreamTranslator()
166
307
  let failure
167
308
  try {
168
- const resolved = findModel(await adapter.#models(), options.model)
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)
169
313
  const result = await adapter.#client.call({
170
314
  options: { ...options, provider },
315
+ /** 账号栏位 → 路由级钉定;@acct: 后缀由 plan-client 自己解析。 */
316
+ pinnedAccountId: NativeZcodeStartPlanAdapter.accountIdFromRoute(adapter.#provider, provider) ?? undefined,
171
317
  model: resolved,
172
318
  maxTokens: options.maxTokens,
173
319
  signal: options.signal,
@@ -195,7 +341,12 @@ export class NativeZcodeStartPlanAdapter {
195
341
 
196
342
  if (failure !== undefined) {
197
343
  yield { type: 'usage', usage: { inputTokens: 0, outputTokens: 0 } }
198
- yield { type: 'finish', kind: 'error', failure }
344
+ /**
345
+ * ⚠ 终止块形状:`{ type: 'finish', reason: { kind, failure } }`。
346
+ * `BlockAssembler` 读 `chunk.reason`;kind 放顶层时宿主读到 undefined,
347
+ * 会把这次失败静默吞成「正常结束」—— 重试与错误上报全部失效。
348
+ */
349
+ yield { type: 'finish', reason: { kind: 'error', failure } }
199
350
  return
200
351
  }
201
352
  if (translator.error !== undefined) {
@@ -260,6 +411,18 @@ export class PiAiZcodeStartPlanAdapter {
260
411
  return undefined
261
412
  }
262
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
+
263
426
  async listModels(provider) {
264
427
  return (await this.#models()).map((model) => toModelInfo(provider, model))
265
428
  }
@@ -192,14 +192,117 @@ function parseToolArguments(raw) {
192
192
  }
193
193
  }
194
194
 
195
+ /** 单值取第一个字符串字段(工具表列出的键按序尝试)。 */
196
+ function pickString(value, ...keys) {
197
+ if (typeof value !== 'object' || value === null) return undefined
198
+ for (const key of keys) {
199
+ const item = value[key]
200
+ if (typeof item === 'string' && item.length > 0) return item
201
+ }
202
+ return undefined
203
+ }
204
+
205
+ /**
206
+ * 把 DSH 的 `ImageAttachmentRef`(宿主 `ImageBlock.attachment`,持久引用)转成
207
+ * Anthropic 的 base64 image 块。
208
+ *
209
+ * ## 宿主契约(rc.3 实测,这是「图片被静默丢弃」的根因)
210
+ *
211
+ * DSH 传给适配器的 image 块是 `{ type: 'image', attachment: ImageAttachmentRef }`
212
+ * (`dsh-llm/lib/types` 的 `ImageBlock`),**不是** base64。引用形态(实测
213
+ * `attachment-local` 后端):
214
+ *
215
+ * ```
216
+ * { attachmentId: 'sha256:<hex>', mediaType: 'image/png', width, height, bytes, name? }
217
+ * ```
218
+ *
219
+ * 字节要经附件服务 `readImageRequest(ref, target)` 解析(见 `resolveImages`);
220
+ * 这里只做**已解析字节 → wire 块**的纯转换。
221
+ *
222
+ * @param {any} ref DSH 的 ImageAttachmentRef
223
+ * @param {Uint8Array} data 请求图片字节
224
+ * @returns {Record<string, unknown>} Anthropic base64 image 块
225
+ */
226
+ export function imageBlockFromAttachment(ref, data) {
227
+ const base64 =
228
+ typeof Buffer !== 'undefined' && typeof Buffer.from === 'function'
229
+ ? Buffer.from(data).toString('base64')
230
+ : bytesToBase64(data)
231
+ return {
232
+ type: 'image',
233
+ source: {
234
+ type: 'base64',
235
+ media_type: typeof ref?.mediaType === 'string' ? ref.mediaType : 'image/png',
236
+ data: base64,
237
+ },
238
+ }
239
+ }
240
+
241
+ /** 纯 JS base64(无 Node Buffer 的环境兜底)。 */
242
+ function bytesToBase64(bytes) {
243
+ const table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
244
+ let out = ''
245
+ for (let index = 0; index < bytes.length; index += 3) {
246
+ const remaining = bytes.length - index
247
+ const b0 = bytes[index]
248
+ const b1 = remaining > 1 ? bytes[index + 1] : 0
249
+ const b2 = remaining > 2 ? bytes[index + 2] : 0
250
+ out += table[b0 >> 2]
251
+ out += table[((b0 & 0x03) << 4) | (b1 >> 4)]
252
+ out += remaining > 1 ? table[((b1 & 0x0f) << 2) | (b2 >> 6)] : '='
253
+ out += remaining > 2 ? table[b2 & 0x3f] : '='
254
+ }
255
+ return out
256
+ }
257
+
258
+ /**
259
+ * 遍历一条消息 content 里的图片引用(宿主 `ImageBlock` 形态优先,兼容内联 base64)。
260
+ *
261
+ * @param {readonly any[]} blocks
262
+ * @returns {Array<{ index: number, attachmentId: string, ref: any, inline?: { mediaType: string, data: string } }>}
263
+ */
264
+ export function imageOccurrences(blocks) {
265
+ if (!Array.isArray(blocks)) return []
266
+ const found = []
267
+ for (let index = 0; index < blocks.length; index += 1) {
268
+ const block = blocks[index]
269
+ if (block === null || typeof block !== 'object' || block.type !== 'image') continue
270
+ /** 宿主流派:持久引用(attachment + attachmentId)。 */
271
+ const attachmentId = pickString(block.attachment, 'attachmentId', 'attachment_id', 'id')
272
+ if (typeof attachmentId === 'string' && attachmentId.length > 0) {
273
+ found.push({ index, attachmentId, ref: block.attachment })
274
+ continue
275
+ }
276
+ /** 防御:内联 base64(旧测试/其他宿主形态)原样携带,不需要解析。 */
277
+ if (block.source?.type === 'base64' && typeof block.source.data === 'string') {
278
+ found.push({
279
+ index,
280
+ attachmentId: `inline:${index}`,
281
+ ref: null,
282
+ inline: { mediaType: block.source.media_type ?? 'image/png', data: block.source.data },
283
+ })
284
+ }
285
+ }
286
+ return found
287
+ }
288
+
195
289
  /**
196
290
  * DSH content blocks → Anthropic content blocks。
197
291
  *
198
292
  * 支持 text / image / tool-call / tool-result;
199
293
  * 其余块(file 等)在 DSH 侧已被投影成文本或占位,这里保守丢弃并记一条提示。
200
294
  *
295
+ * ## 图片的两种形态
296
+ *
297
+ * 1. **宿主流派(实际形态)**:`{ type: 'image', attachment: ImageAttachmentRef }`
298
+ * —— 持久引用。字节由调用方先经 `resolveImages()` 从附件服务解析好,
299
+ * 以 `resolvedImages: Map<attachmentId, {data, ref}>` 传入;查不到的引用
300
+ * 以占位文本替换(不再静默丢弃——那会让用户以为发了图,模型却什么都看不到)。
301
+ * 2. **内联形态(防御性兼容)**:`{ type: 'image', source: { type: 'base64'|'url', … } }`
302
+ * —— 旧测试与其他宿主形态,原样转换。
303
+ *
201
304
  * @param {readonly any[]} blocks
202
- * @param {{ supportsImages?: boolean }} [options]
305
+ * @param {{ supportsImages?: boolean, resolvedImages?: Map<string, { data: Uint8Array, ref: any }> }} [options]
203
306
  * @returns {Array<any>}
204
307
  */
205
308
  export function convertContent(blocks, options = {}) {
@@ -217,6 +320,21 @@ export function convertContent(blocks, options = {}) {
217
320
  out.push({ type: 'text', text: '[image omitted: this model does not accept image input]' })
218
321
  break
219
322
  }
323
+ /** ① 宿主流派:持久引用 → 已解析字节。 */
324
+ const attachmentId = pickString(block.attachment, 'attachmentId', 'attachment_id', 'id')
325
+ if (typeof attachmentId === 'string' && attachmentId.length > 0) {
326
+ const resolved = options.resolvedImages?.get(attachmentId)
327
+ if (resolved !== undefined) {
328
+ out.push(imageBlockFromAttachment(resolved.ref ?? block.attachment, resolved.data))
329
+ } else {
330
+ out.push({
331
+ type: 'text',
332
+ text: `[image omitted: attachment ${attachmentId.slice(0, 15)}… could not be loaded from the attachment store]`,
333
+ })
334
+ }
335
+ break
336
+ }
337
+ /** ② 防御:内联 base64 / url。 */
220
338
  const source = block.source
221
339
  if (source?.type === 'base64' && typeof source.data === 'string') {
222
340
  out.push({
@@ -258,6 +376,49 @@ export function convertContent(blocks, options = {}) {
258
376
  return out
259
377
  }
260
378
 
379
+ /**
380
+ * 收集一次请求里所有消息的图片引用,并经附件服务解析成请求字节。
381
+ *
382
+ * 这是官方 `dsh-llm-deepseek` 的同款链路:`attachments.readImageRequest(ref, target)`
383
+ * 返回确定性的「请求版本」(`{ data, mediaType, width, height, … }`,超出 target 时
384
+ * 由后端缩放/重编码)。解析失败的引用跳过(`convertContent` 会给出占位文本),
385
+ * 不让一张坏图让整个请求失败。
386
+ *
387
+ * @param {readonly any[]} messages DSH GenerateOptions.messages
388
+ * @param {{ resolveAttachments?: () => any, signal?: AbortSignal }} [deps]
389
+ * @returns {Promise<Map<string, { data: Uint8Array, ref: any }>>} attachmentId → 请求字节
390
+ */
391
+ export async function resolveImages(messages, deps = {}) {
392
+ const attachments = deps.resolveAttachments?.()
393
+ if (attachments === undefined || attachments === null) return new Map()
394
+ const refs = new Map()
395
+ for (const message of Array.isArray(messages) ? messages : []) {
396
+ const blocks = Array.isArray(message?.content) ? message.content : []
397
+ for (const occurrence of imageOccurrences(blocks)) {
398
+ if (occurrence.inline !== undefined) continue
399
+ if (!refs.has(occurrence.attachmentId)) refs.set(occurrence.attachmentId, occurrence.ref)
400
+ }
401
+ }
402
+ const resolved = new Map()
403
+ for (const [attachmentId, ref] of refs) {
404
+ try {
405
+ /** 默认保留归一化尺寸(基类 imageRequestTarget 的语义);不放大也不强制缩。 */
406
+ const target = {
407
+ width: typeof ref.width === 'number' && ref.width > 0 ? ref.width : 1568,
408
+ height: typeof ref.height === 'number' && ref.height > 0 ? ref.height : 1568,
409
+ maxBytes: typeof ref.bytes === 'number' && ref.bytes > 0 ? ref.bytes : 4_194_304,
410
+ }
411
+ const version = await attachments.readImageRequest(ref, target, deps.signal)
412
+ if (version?.data instanceof Uint8Array && version.data.byteLength > 0) {
413
+ resolved.set(attachmentId, { data: version.data, ref: version.attachment ?? ref })
414
+ }
415
+ } catch {
416
+ /** 单张图解析失败只降级为占位文本,不拖垮整条请求。 */
417
+ }
418
+ }
419
+ return resolved
420
+ }
421
+
261
422
  /**
262
423
  * 把 DSH 的 `GenerateOptions` 组装成上游请求体(**纯函数**)。
263
424
  *
@@ -268,6 +429,7 @@ export function convertContent(blocks, options = {}) {
268
429
  * now?: Date,
269
430
  * maxTokens?: number,
270
431
  * supportsImages?: boolean,
432
+ * resolvedImages?: Map<string, { data: Uint8Array, ref: any }>,
271
433
  * }} input
272
434
  * @returns {Record<string, unknown>}
273
435
  */
@@ -281,7 +443,10 @@ export function buildUpstreamBody(input) {
281
443
  .filter((message) => message?.role !== 'system')
282
444
  .map((message) => ({
283
445
  role: message.role === 'assistant' ? 'assistant' : 'user',
284
- content: convertContent(message.content, { supportsImages: input.supportsImages }),
446
+ content: convertContent(message.content, {
447
+ supportsImages: input.supportsImages,
448
+ resolvedImages: input.resolvedImages,
449
+ }),
285
450
  }))
286
451
  .filter((message) => message.content.length > 0)
287
452