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.
package/cordis.patch.yml CHANGED
@@ -4,6 +4,7 @@
4
4
  #
5
5
  # provider / displayName DSH 里的路由名与展示名(与 llm-pi-ai 的路由不能重名)
6
6
  # models 暴露给 DSH 的模型 id(与上游目录求交集)
7
+ # accountProviders true = 每个启用账号一个独立 provider 栏位(可在面板关统一栏)
7
8
  # captcha.debugPort 宿主 Electron 的 CDP 端口(DSH 桌面端需以
8
9
  # --remote-debugging-port=9229 启动;captcha 用它产出)
9
10
  # captcha.mode cdp = 自动产出;manual = 只认人工粘贴(见 CLI)
@@ -18,6 +19,7 @@
18
19
  models:
19
20
  - GLM-5.3-Flash
20
21
  - GLM-5.3
22
+ accountProviders: true
21
23
  dataDir: ''
22
24
  modelCacheMs: 600000
23
25
  captcha:
package/index.js CHANGED
@@ -44,6 +44,10 @@ export const name = 'zcode-start-plan'
44
44
  * - `tools` 注册 `zcode_start_plan_status` 状态工具
45
45
  * - `timer` 每小时清理过期的「账号×模型」限流标记
46
46
  * - `webServer` 注册账号池管理路由(Web UI 面板的数据通道;可选增强)
47
+ *
48
+ * ⚠ 图片输入**不**走 inject:cordis 的 inject 是硬依赖(声明的服务缺席时整个
49
+ * fiber 挂起,插件完全不加载)。附件服务经沙箱 façade 的 `ctx.get('attachments')`
50
+ * 探测(宿主允许未声明查询),缺席时图片消息降级为占位文本,主功能不受影响。
47
51
  */
48
52
  export const inject = ['llm', 'tools', 'timer', 'webServer']
49
53
 
@@ -56,6 +60,13 @@ const DEFAULT_CONFIG = Object.freeze({
56
60
  displayName: 'ZCode Start Plan(赠送免费 plan)',
57
61
  /** 暴露给 DSH 的模型 id 列表(与上游模型目录求交集;拉不到时直接用这份)。 */
58
62
  models: DEFAULT_MODELS,
63
+ /**
64
+ * 为每个启用账号注册一个独立的 provider 栏位(像 workbuddy 一样一栏一个
65
+ * 账号,路由名 `<provider>-acct-<账号id>`、显示名「ZCode Start Plan · 昵称」),
66
+ * 选中即只消耗该账号的额度,不自动换号。关闭后只有统一选号栏位。
67
+ * (0.3.0 的 `pinnedAccounts` 同义更名,旧值仍被接受。)
68
+ */
69
+ accountProviders: true,
59
70
  /** 上游模型目录缓存时长(毫秒)。 */
60
71
  modelCacheMs: 10 * 60_000,
61
72
  /** 数据目录(空 = ~/.dsh/zcode-start-plan)。 */
@@ -101,6 +112,10 @@ export function resolveConfig(raw) {
101
112
  out.endpoint = { ...DEFAULT_CONFIG.endpoint, ...(src.endpoint ?? {}) }
102
113
  if (src.models === undefined || src.models === null) out.models = [...DEFAULT_CONFIG.models]
103
114
  else if (Array.isArray(src.models)) out.models = src.models.length > 0 ? src.models.slice() : [...DEFAULT_CONFIG.models]
115
+ /** 0.3.0 的 `pinnedAccounts` 同义更名:旧名仍被接受,新名优先。 */
116
+ if (src.accountProviders === undefined && typeof src.pinnedAccounts === 'boolean') {
117
+ out.accountProviders = src.pinnedAccounts
118
+ }
104
119
  return out
105
120
  }
106
121
 
@@ -181,6 +196,9 @@ export function validateConfig(value) {
181
196
  if (!Array.isArray(out.models) || !out.models.every((id) => typeof id === 'string')) {
182
197
  throw new Error('config.models 必须是字符串数组')
183
198
  }
199
+ if (typeof out.accountProviders !== 'boolean') {
200
+ throw new Error('config.accountProviders 必须是布尔值')
201
+ }
184
202
  if (!Number.isInteger(out.modelCacheMs) || out.modelCacheMs < 0) {
185
203
  throw new Error('config.modelCacheMs 必须是非负整数')
186
204
  }
@@ -213,6 +231,7 @@ export const Config = makeConfigSchema(validateConfig, {
213
231
  provider: PROVIDER,
214
232
  displayName: 'ZCode Start Plan(赠送免费 plan)',
215
233
  models: [...DEFAULT_MODELS],
234
+ accountProviders: true,
216
235
  modelCacheMs: 10 * 60_000,
217
236
  dataDir: '',
218
237
  channel: 'cn',
@@ -235,6 +254,9 @@ export const Config = makeConfigSchema(validateConfig, {
235
254
  * 因此:**用到哪个服务就必须在 `inject` 里声明**。本插件用到
236
255
  * `llm`(注册适配器)、`tools`(状态工具)、`timer`(定期清理)、
237
256
  * `webServer`(账号池管理路由,供插件 Web UI 面板调用)。
257
+ * 后两处都有容错(服务不可用时面板路由跳过 / 图片降级占位文本)。
258
+ * 图片输入的附件服务**刻意不进 inject**(硬依赖会把插件整体挂起),
259
+ * 由 assemble 在建资源时用 `ctx.get('attachments')` 探测。
238
260
  *
239
261
  * 另外 `ctx.effect` 在沙箱里可用(它不是服务,是 ctx 动词),
240
262
  * 而 `ctx.emit` / `ctx.on` / `ctx.setInterval` **不可用** ——
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,54 @@ export class NativeZcodeStartPlanAdapter {
118
204
  return undefined
119
205
  }
120
206
 
207
+ /**
208
+ * 账号栏位的模型目录:基础模型 × 该账号(description 带额度状态)。
209
+ *
210
+ * 账号已删除/停用时返回空数组 —— 宿主会隐藏没有模型的分组,这正是
211
+ * workbuddy 的可见性机制;路由本身留着,老会话不炸。
212
+ */
213
+ async #accountModels(provider, accountId) {
214
+ const [baseModels, entry] = await Promise.all([this.#models(), Promise.resolve(this.#pool?.get(accountId))])
215
+ if (entry === undefined || entry.enabled !== true) return []
216
+ const now = Date.now()
217
+ return baseModels.map((model) => {
218
+ const limitedUntil = entry.model_rate_limits?.[model.id]
219
+ const limited = typeof limitedUntil === 'number' && limitedUntil > now
220
+ const reset = limited
221
+ ? new Date(limitedUntil).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
222
+ : ''
223
+ const meta = toModelInfo(provider, model)
224
+ return {
225
+ ...meta,
226
+ description: limited
227
+ ? `固定使用「${entry.nickname}」的额度(该模型限流至 ${reset})`
228
+ : `固定使用「${entry.nickname}」的额度,不自动换号`,
229
+ }
230
+ })
231
+ }
232
+
121
233
  async listModels(provider) {
234
+ const accountId = NativeZcodeStartPlanAdapter.accountIdFromRoute(this.#provider, provider)
235
+ /** 账号栏位:只列该账号的模型;面板隐藏/停用/删除 = 空目录 = 隐藏该栏位。 */
236
+ if (accountId !== null) {
237
+ if (this.#hiddenAccounts.has(accountId)) return []
238
+ return this.#accountModels(provider, accountId)
239
+ }
240
+ /** 统一栏位:面板关掉 = 空目录 = 宿主隐藏分组(路由保留,老会话不炸)。 */
241
+ if (this.#unifiedVisible !== true) return []
122
242
  return (await this.#models()).map((model) => toModelInfo(provider, model))
123
243
  }
124
244
 
125
245
  async resolveModel(provider, model) {
126
- const found = findModel(await this.#models(), model)
246
+ const accountId = NativeZcodeStartPlanAdapter.accountIdFromRoute(this.#provider, provider)
247
+ const idPin = parsePinnedModelId(model)
248
+ const lookupId = idPin === null ? model : idPin.baseModelId
249
+ const found = findModel(await this.#models(), lookupId)
127
250
  if (found === undefined) return { provider, id: model, name: model }
128
- return toModelInfo(provider, found)
251
+ const meta = toModelInfo(provider, found)
252
+ /** 0.3.0 的 @acct: 后缀仍原样放行(id 与请求一致是宿主硬契约)。 */
253
+ if (idPin !== null) return { ...meta, id: model }
254
+ return meta
129
255
  }
130
256
 
131
257
  /**
@@ -165,9 +291,14 @@ export class NativeZcodeStartPlanAdapter {
165
291
  const translator = new AnthropicStreamTranslator()
166
292
  let failure
167
293
  try {
168
- const resolved = findModel(await adapter.#models(), options.model)
294
+ /** 钉定 id 解析回基础模型查元数据(plan-client 内部同样会解析)。 */
295
+ const idPin = parsePinnedModelId(options.model)
296
+ const lookupId = idPin === null ? options.model : idPin.baseModelId
297
+ const resolved = findModel(await adapter.#models(), lookupId)
169
298
  const result = await adapter.#client.call({
170
299
  options: { ...options, provider },
300
+ /** 账号栏位 → 路由级钉定;@acct: 后缀由 plan-client 自己解析。 */
301
+ pinnedAccountId: NativeZcodeStartPlanAdapter.accountIdFromRoute(adapter.#provider, provider) ?? undefined,
171
302
  model: resolved,
172
303
  maxTokens: options.maxTokens,
173
304
  signal: options.signal,
@@ -195,7 +326,12 @@ export class NativeZcodeStartPlanAdapter {
195
326
 
196
327
  if (failure !== undefined) {
197
328
  yield { type: 'usage', usage: { inputTokens: 0, outputTokens: 0 } }
198
- yield { type: 'finish', kind: 'error', failure }
329
+ /**
330
+ * ⚠ 终止块形状:`{ type: 'finish', reason: { kind, failure } }`。
331
+ * `BlockAssembler` 读 `chunk.reason`;kind 放顶层时宿主读到 undefined,
332
+ * 会把这次失败静默吞成「正常结束」—— 重试与错误上报全部失效。
333
+ */
334
+ yield { type: 'finish', reason: { kind: 'error', failure } }
199
335
  return
200
336
  }
201
337
  if (translator.error !== undefined) {
@@ -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
 
package/lib/assemble.js CHANGED
@@ -7,6 +7,8 @@
7
7
  * 异步函数里调 `ctx.effect`(那样拿到的是未挂到 fiber 的注册,热重载后不会被撤销)。
8
8
  */
9
9
 
10
+ import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
11
+ import { join } from 'node:path'
10
12
  import { SqliteStore, AccountPool, resolveDbFile, resolveDataDir } from './pool.js'
11
13
  import { CaptchaMinter } from './captcha/minter.js'
12
14
  import { ZcodePlanClient } from './plan-client.js'
@@ -27,6 +29,37 @@ export function assemble(ctx, config, logger) {
27
29
  const { log, warn } = logger
28
30
  const dataDir = config.dataDir.trim().length > 0 ? config.dataDir.trim() : resolveDataDir(process.env)
29
31
 
32
+ /**
33
+ * 面板开关的持久化(settings.json in dataDir)。
34
+ *
35
+ * 只存「非默认的偏好」,坏文件按默认值处理 —— 一个开关状态不该让插件起不来。
36
+ * 字段:
37
+ * - unifiedModelList:统一选号栏位是否显示(默认 true);
38
+ * - hiddenModelLists:被隐藏「模型栏位」的账号 id 数组(默认空 = 全显示)。
39
+ */
40
+ const settingsFile = join(dataDir, 'settings.json')
41
+ const settings = { unifiedModelList: true, hiddenModelLists: [] }
42
+ try {
43
+ const raw = readFileSync(settingsFile, 'utf8')
44
+ const parsed = JSON.parse(raw)
45
+ if (parsed !== null && typeof parsed === 'object') {
46
+ if (typeof parsed.unifiedModelList === 'boolean') settings.unifiedModelList = parsed.unifiedModelList
47
+ if (Array.isArray(parsed.hiddenModelLists)) {
48
+ settings.hiddenModelLists = parsed.hiddenModelLists.filter((id) => typeof id === 'string')
49
+ }
50
+ }
51
+ } catch {
52
+ // 没有文件 / 坏 JSON:全按默认值。
53
+ }
54
+ const saveSettings = () => {
55
+ try {
56
+ mkdirSync(dataDir, { recursive: true })
57
+ writeFileSync(settingsFile, JSON.stringify(settings, null, 2))
58
+ } catch (error) {
59
+ warn(`保存 settings.json 失败(开关状态重启后会丢失):${error instanceof Error ? error.message : String(error)}`)
60
+ }
61
+ }
62
+
30
63
  /** 资源句柄(由 `dispose` 统一释放)。 */
31
64
  const runtime = {
32
65
  pool: undefined,
@@ -63,8 +96,18 @@ export function assemble(ctx, config, logger) {
63
96
  }
64
97
  }
65
98
  } catch (error) {
66
- warn(`拉取模型目录失败(用本地兜底表):${error instanceof Error ? error.message : String(error)}`)
99
+ warn(`拉取模型目录失败:${error instanceof Error ? error.message : String(error)}`)
67
100
  }
101
+ /**
102
+ * 拉取失败时的次序:**先过期缓存,再兜底表**。
103
+ *
104
+ * ⚠ 不能直接跳兜底表:拉取是间歇性的(网络抖动 / 上游过载),而兜底表若是
105
+ * 旧版(无 `reasoningLevels`)会让宿主抛 `UNSUPPORTED_REASONING_EFFORT` ——
106
+ * 用户此刻选档位就报「不支持当前档位」且无输出(2026-10-25 实测踩坑)。
107
+ * 过期缓存虽旧但元数据结构完整,比兜底表安全;兜底表只给冷启动用。
108
+ * 缓存为 undefined(从未成功过)才落兜底,且缓存兜底值以便下次直接命中过期缓存。
109
+ */
110
+ if (modelsCache.value !== undefined) return modelsCache.value
68
111
  modelsCache = { at: Date.now(), value: fallback }
69
112
  return fallback
70
113
  }
@@ -119,6 +162,14 @@ export function assemble(ctx, config, logger) {
119
162
  pool: runtime.pool,
120
163
  minter: runtime.minter,
121
164
  log,
165
+ /**
166
+ * 图片输入:宿主把上传图片存进附件库,适配器只收到持久引用;
167
+ * 这里回调取挂载的附件服务(`ctx.get('attachments')`,沙箱 façade 允许
168
+ * 未声明服务的只读查询),plan-client 据此把引用解析成请求字节
169
+ * (官方 `dsh-llm-deepseek` 同款链路)。⚠ 惰性求值:附件服务可能晚于
170
+ * 本插件初始化挂载;缺席(undefined)时图片降级为占位文本。
171
+ */
172
+ resolveAttachments: typeof ctx.get === 'function' ? () => ctx.get('attachments') : undefined,
122
173
  })
123
174
 
124
175
  if (config.endpoint.enabled === true) {
@@ -161,18 +212,53 @@ export function assemble(ctx, config, logger) {
161
212
  }
162
213
 
163
214
  const doRegister = () => {
164
- /** ① llm 适配器路由。 */
215
+ /** ① llm 适配器路由(统一 + 每账号一栏,workbuddy 模式)。 */
165
216
  const adapter = new NativeZcodeStartPlanAdapter({
166
217
  client: runtime.client,
167
218
  models: loadModels,
168
219
  provider: config.provider,
169
220
  displayName: config.displayName,
170
221
  log,
222
+ /** 每个启用账号一个独立 provider 栏位(config.accountProviders 可关)。 */
223
+ accountProviders: config.accountProviders !== false,
224
+ pool: runtime.pool,
225
+ unifiedVisible: settings.unifiedModelList !== false,
226
+ hiddenAccounts: settings.hiddenModelLists,
171
227
  })
228
+ /**
229
+ * 当前注册的路由集合(统一栏位 + 启用账号的栏位)。账号增删/启停/
230
+ * 统一栏位开关时用 `handle.replace()` 原子换路由 —— 宿主会在
231
+ * commitRoutes 里自动广播 `llm/adapters-updated`,模型选择器随即重拉。
232
+ */
233
+ let registrationHandle
234
+ const currentRoutes = () => {
235
+ /** 统一栏位永远注册(关掉只是空目录隐藏,路由保留让老会话不炸)。 */
236
+ const routes = [config.provider]
237
+ if (config.accountProviders !== false) {
238
+ for (const entry of runtime.pool.list()) {
239
+ if (entry.enabled === true) {
240
+ routes.push(NativeZcodeStartPlanAdapter.accountRoute(config.provider, entry.id))
241
+ }
242
+ }
243
+ }
244
+ return routes
245
+ }
246
+ const syncRoutes = () => {
247
+ try {
248
+ registrationHandle?.replace?.(currentRoutes())
249
+ } catch (error) {
250
+ warn(`切换 llm 路由失败:${error instanceof Error ? error.message : String(error)}`)
251
+ }
252
+ }
172
253
  try {
173
- addUndo(ctx.llm.registerAdapter([config.provider], adapter))
254
+ registrationHandle = ctx.llm.registerAdapter(currentRoutes(), adapter)
255
+ addUndo(registrationHandle)
174
256
  runtime.adapterRegistered = true
175
- log(`llm 路由已注册:${config.provider}(模型:${config.models.join(', ')})`)
257
+ runtime.syncAdapterRoutes = syncRoutes
258
+ log(
259
+ `llm 路由已注册:${currentRoutes().length} 条` +
260
+ `(统一:${config.provider};账号栏位:${config.accountProviders !== false ? '开' : '关'})`,
261
+ )
176
262
  } catch (error) {
177
263
  runtime.error = `注册 llm 路由失败:${error instanceof Error ? error.message : String(error)}`
178
264
  warn(`${runtime.error}(可能与其他适配器重名);本插件降级为仅提供状态工具。`)
@@ -202,6 +288,31 @@ export function assemble(ctx, config, logger) {
202
288
  pool: runtime.pool,
203
289
  fetchBalance: (credential) => fetchBalance(credential),
204
290
  log,
291
+ settings,
292
+ /**
293
+ * 账号变更(增删/启停/置顶/改名)与「统一选号」开关都会改变
294
+ * provider 路由集合或目录可见性:`syncAdapterRoutes` 用
295
+ * `handle.replace()` 原子换路由(宿主自动广播 llm/adapters-updated)。
296
+ */
297
+ onChanged: () => syncRoutes(),
298
+ onSetUnifiedVisible: (visible) => {
299
+ adapter.setUnifiedVisible(visible)
300
+ settings.unifiedModelList = visible === true
301
+ saveSettings()
302
+ syncRoutes()
303
+ log(`统一选号栏位${visible === true ? '已显示' : '已隐藏'}`)
304
+ },
305
+ onSetAccountVisible: (accountId, visible) => {
306
+ adapter.setAccountVisible(accountId, visible)
307
+ const hidden = new Set(settings.hiddenModelLists)
308
+ if (visible === true) hidden.delete(accountId)
309
+ else hidden.add(accountId)
310
+ settings.hiddenModelLists = [...hidden]
311
+ saveSettings()
312
+ syncRoutes()
313
+ const nickname = runtime.pool.get(accountId)?.nickname ?? accountId.slice(0, 8)
314
+ log(`账号「${nickname}」的模型栏位${visible === true ? '已显示' : '已隐藏'}`)
315
+ },
205
316
  })
206
317
  for (const route of routes) addUndo(ctx.webServer.register(route))
207
318
  log(`管理路由已注册:${routes.length} 条(/api/zcode-start-plan/*)`)