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/assemble.js CHANGED
@@ -7,6 +7,10 @@
7
7
  * 异步函数里调 `ctx.effect`(那样拿到的是未挂到 fiber 的注册,热重载后不会被撤销)。
8
8
  */
9
9
 
10
+ import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
11
+ import { join, dirname } from 'node:path'
12
+ import { fileURLToPath } from 'node:url'
13
+ import { spawn } from 'node:child_process'
10
14
  import { SqliteStore, AccountPool, resolveDbFile, resolveDataDir } from './pool.js'
11
15
  import { CaptchaMinter } from './captcha/minter.js'
12
16
  import { ZcodePlanClient } from './plan-client.js'
@@ -16,6 +20,50 @@ import { fetchBalance, fetchCaptchaConfig, fetchModels } from './upstream-api.js
16
20
  import { ZCODE_FALLBACK_MODELS } from './upstream.js'
17
21
  import { makeManageRoutes } from './manage-routes.js'
18
22
 
23
+ /**
24
+ * 以调试端口重启宿主的实现(供管理路由的 `/restart-cdp` 调用)。
25
+ *
26
+ * 跑 `scripts/restart-dsh.ps1`,三件事必须同时成立:
27
+ * 1. `detached: true` + `unref()`:脚本要在**本请求返回之后**才杀宿主,
28
+ * 若子进程挂在宿主进程树下,宿主一死它跟着死 → 没人拉起新实例;
29
+ * 2. 用 `powershell.exe`(Windows PowerShell 5.1 一定在)而不是 `pwsh`:
30
+ * 用户机器未必装了 PowerShell 7;
31
+ * 3. `cwd` 指到插件目录,脚本内部的相对路径才成立。
32
+ *
33
+ * @param {{ debugPort: number, waitSeconds: number }} options
34
+ */
35
+ function spawnRestartScript(options) {
36
+ const pluginRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
37
+ const script = join(pluginRoot, 'scripts', 'restart-dsh.ps1')
38
+ const args = [
39
+ '-NoProfile',
40
+ '-ExecutionPolicy', 'Bypass',
41
+ '-File', script,
42
+ '-WaitSeconds', String(options.waitSeconds),
43
+ '-DebugPort', String(options.debugPort),
44
+ ]
45
+ return new Promise((resolve, reject) => {
46
+ let child
47
+ try {
48
+ child = spawn('powershell.exe', args, {
49
+ cwd: pluginRoot,
50
+ detached: true,
51
+ stdio: 'ignore',
52
+ windowsHide: true,
53
+ })
54
+ } catch (error) {
55
+ reject(error)
56
+ return
57
+ }
58
+ child.once('error', reject)
59
+ child.once('spawn', () => {
60
+ /** 分离后立即放掉引用:宿主退出时不要连带杀死它。 */
61
+ child.unref()
62
+ resolve()
63
+ })
64
+ })
65
+ }
66
+
19
67
  /**
20
68
  * 装配并返回运行时句柄。
21
69
  *
@@ -27,6 +75,37 @@ export function assemble(ctx, config, logger) {
27
75
  const { log, warn } = logger
28
76
  const dataDir = config.dataDir.trim().length > 0 ? config.dataDir.trim() : resolveDataDir(process.env)
29
77
 
78
+ /**
79
+ * 面板开关的持久化(settings.json in dataDir)。
80
+ *
81
+ * 只存「非默认的偏好」,坏文件按默认值处理 —— 一个开关状态不该让插件起不来。
82
+ * 字段:
83
+ * - unifiedModelList:统一选号栏位是否显示(默认 true);
84
+ * - hiddenModelLists:被隐藏「模型栏位」的账号 id 数组(默认空 = 全显示)。
85
+ */
86
+ const settingsFile = join(dataDir, 'settings.json')
87
+ const settings = { unifiedModelList: true, hiddenModelLists: [] }
88
+ try {
89
+ const raw = readFileSync(settingsFile, 'utf8')
90
+ const parsed = JSON.parse(raw)
91
+ if (parsed !== null && typeof parsed === 'object') {
92
+ if (typeof parsed.unifiedModelList === 'boolean') settings.unifiedModelList = parsed.unifiedModelList
93
+ if (Array.isArray(parsed.hiddenModelLists)) {
94
+ settings.hiddenModelLists = parsed.hiddenModelLists.filter((id) => typeof id === 'string')
95
+ }
96
+ }
97
+ } catch {
98
+ // 没有文件 / 坏 JSON:全按默认值。
99
+ }
100
+ const saveSettings = () => {
101
+ try {
102
+ mkdirSync(dataDir, { recursive: true })
103
+ writeFileSync(settingsFile, JSON.stringify(settings, null, 2))
104
+ } catch (error) {
105
+ warn(`保存 settings.json 失败(开关状态重启后会丢失):${error instanceof Error ? error.message : String(error)}`)
106
+ }
107
+ }
108
+
30
109
  /** 资源句柄(由 `dispose` 统一释放)。 */
31
110
  const runtime = {
32
111
  pool: undefined,
@@ -39,10 +118,15 @@ export function assemble(ctx, config, logger) {
39
118
  adapterRegistered: false,
40
119
  /** 最近一次致命错误(初始化 / 注册 / 加载)。 */
41
120
  error: undefined,
121
+ /** llm 适配器实例(管理路由的可见性开关要用;`register()` 里建立)。 */
122
+ adapter: undefined,
123
+ /** 账号增删/启停/置顶后原子换路由(由 `register()` 里赋值)。 */
124
+ syncAdapterRoutes: undefined,
42
125
  }
43
126
 
44
127
  /** 模型目录缓存(拉上游一次,失败回退到 config.models + 兜底表)。 */
45
128
  let modelsCache = { at: 0, value: undefined }
129
+
46
130
  const loadModels = async () => {
47
131
  if (modelsCache.value !== undefined && Date.now() - modelsCache.at < config.modelCacheMs) {
48
132
  return modelsCache.value
@@ -63,8 +147,18 @@ export function assemble(ctx, config, logger) {
63
147
  }
64
148
  }
65
149
  } catch (error) {
66
- warn(`拉取模型目录失败(用本地兜底表):${error instanceof Error ? error.message : String(error)}`)
150
+ warn(`拉取模型目录失败:${error instanceof Error ? error.message : String(error)}`)
67
151
  }
152
+ /**
153
+ * 拉取失败时的次序:**先过期缓存,再兜底表**。
154
+ *
155
+ * ⚠ 不能直接跳兜底表:拉取是间歇性的(网络抖动 / 上游过载),而兜底表若是
156
+ * 旧版(无 `reasoningLevels`)会让宿主抛 `UNSUPPORTED_REASONING_EFFORT` ——
157
+ * 用户此刻选档位就报「不支持当前档位」且无输出(2026-10-25 实测踩坑)。
158
+ * 过期缓存虽旧但元数据结构完整,比兜底表安全;兜底表只给冷启动用。
159
+ * 缓存为 undefined(从未成功过)才落兜底,且缓存兜底值以便下次直接命中过期缓存。
160
+ */
161
+ if (modelsCache.value !== undefined) return modelsCache.value
68
162
  modelsCache = { at: Date.now(), value: fallback }
69
163
  return fallback
70
164
  }
@@ -119,6 +213,14 @@ export function assemble(ctx, config, logger) {
119
213
  pool: runtime.pool,
120
214
  minter: runtime.minter,
121
215
  log,
216
+ /**
217
+ * 图片输入:宿主把上传图片存进附件库,适配器只收到持久引用;
218
+ * 这里回调取挂载的附件服务(`ctx.get('attachments')`,沙箱 façade 允许
219
+ * 未声明服务的只读查询),plan-client 据此把引用解析成请求字节
220
+ * (官方 `dsh-llm-deepseek` 同款链路)。⚠ 惰性求值:附件服务可能晚于
221
+ * 本插件初始化挂载;缺席(undefined)时图片降级为占位文本。
222
+ */
223
+ resolveAttachments: typeof ctx.get === 'function' ? () => ctx.get('attachments') : undefined,
122
224
  })
123
225
 
124
226
  if (config.endpoint.enabled === true) {
@@ -161,18 +263,54 @@ export function assemble(ctx, config, logger) {
161
263
  }
162
264
 
163
265
  const doRegister = () => {
164
- /** ① llm 适配器路由。 */
266
+ /** ① llm 适配器路由(统一 + 每账号一栏,workbuddy 模式)。 */
165
267
  const adapter = new NativeZcodeStartPlanAdapter({
166
268
  client: runtime.client,
167
269
  models: loadModels,
168
270
  provider: config.provider,
169
271
  displayName: config.displayName,
170
272
  log,
273
+ /** 每个启用账号一个独立 provider 栏位(config.accountProviders 可关)。 */
274
+ accountProviders: config.accountProviders !== false,
275
+ pool: runtime.pool,
276
+ unifiedVisible: settings.unifiedModelList !== false,
277
+ hiddenAccounts: settings.hiddenModelLists,
171
278
  })
279
+ runtime.adapter = adapter
280
+ /**
281
+ * 当前注册的路由集合(统一栏位 + 启用账号的栏位)。账号增删/启停/
282
+ * 统一栏位开关时用 `handle.replace()` 原子换路由 —— 宿主会在
283
+ * commitRoutes 里自动广播 `llm/adapters-updated`,模型选择器随即重拉。
284
+ */
285
+ let registrationHandle
286
+ const currentRoutes = () => {
287
+ /** 统一栏位永远注册(关掉只是空目录隐藏,路由保留让老会话不炸)。 */
288
+ const routes = [config.provider]
289
+ if (config.accountProviders !== false) {
290
+ for (const entry of runtime.pool.list()) {
291
+ if (entry.enabled === true) {
292
+ routes.push(NativeZcodeStartPlanAdapter.accountRoute(config.provider, entry.id))
293
+ }
294
+ }
295
+ }
296
+ return routes
297
+ }
298
+ const syncRoutes = () => {
299
+ try {
300
+ registrationHandle?.replace?.(currentRoutes())
301
+ } catch (error) {
302
+ warn(`切换 llm 路由失败:${error instanceof Error ? error.message : String(error)}`)
303
+ }
304
+ }
172
305
  try {
173
- addUndo(ctx.llm.registerAdapter([config.provider], adapter))
306
+ registrationHandle = ctx.llm.registerAdapter(currentRoutes(), adapter)
307
+ addUndo(registrationHandle)
174
308
  runtime.adapterRegistered = true
175
- log(`llm 路由已注册:${config.provider}(模型:${config.models.join(', ')})`)
309
+ runtime.syncAdapterRoutes = syncRoutes
310
+ log(
311
+ `llm 路由已注册:${currentRoutes().length} 条` +
312
+ `(统一:${config.provider};账号栏位:${config.accountProviders !== false ? '开' : '关'})`,
313
+ )
176
314
  } catch (error) {
177
315
  runtime.error = `注册 llm 路由失败:${error instanceof Error ? error.message : String(error)}`
178
316
  warn(`${runtime.error}(可能与其他适配器重名);本插件降级为仅提供状态工具。`)
@@ -195,26 +333,26 @@ export function assemble(ctx, config, logger) {
195
333
  warn('timer 服务不可用,跳过每小时限流清理(限流标记仍会在每次请求时自然过期)')
196
334
  }
197
335
 
198
- /** ④ 账号池管理路由(Web UI 用;webServer 未就绪时跳过,不影响其它功能)。 */
199
- if (typeof ctx.webServer?.register === 'function' && runtime.pool !== undefined) {
200
- try {
201
- const routes = makeManageRoutes({
202
- pool: runtime.pool,
203
- fetchBalance: (credential) => fetchBalance(credential),
204
- log,
205
- })
206
- for (const route of routes) addUndo(ctx.webServer.register(route))
207
- log(`管理路由已注册:${routes.length} 条(/api/zcode-start-plan/*)`)
208
- } catch (error) {
209
- warn(`管理路由注册失败(Web UI 不可用,其它功能不受影响):${error instanceof Error ? error.message : String(error)}`)
210
- }
211
- }
336
+ /**
337
+ * ④ 账号池管理路由 —— **不在这里注册**。
338
+ *
339
+ * 路由要挂到 `webServer` 上,而 `webServer` 是可选服务:宿主只把
340
+ * `inject` 声明过的服务挂到 facade 上,把 `webServer` 写进硬 inject
341
+ * 又会让 headless profile 整个 fiber 挂起。两种写法都错过一个版本:
342
+ * - 0.4.4:从 facade 探测 `ctx.webServer` → 永远拿不到 → 静默跳过(面板 404);
343
+ * - 只把 `webServer` 加回 inject → headless 下整插件不加载。
344
+ *
345
+ * 正解在 `index.js` 的 `ctx.inject(['webServer'], …)` 回调里调用
346
+ * `registerManageRoutes(webCtx)`:服务出现才注册、消失则 effect 自动撤销。
347
+ * (`syncRoutes` / `settings` / `log` 都在闭包里,回调直接复用。)
348
+ */
349
+ runtime.syncRoutes = syncRoutes
212
350
  }
213
351
 
214
352
  /**
215
353
  * `inject: ['llm', …]` 已保证 `ctx.llm` 就绪后才 apply,
216
354
  * 所以这里直接注册即可;保留一个兜底分支应对宿主延迟挂载的情况。
217
- * ⚠ 沙箱 façade 上没有 `ctx.inject`,不能用它做兜底。
355
+ * facade 上没有 `ctx.inject`,不能用它做兜底。
218
356
  */
219
357
  if (ctx.llm !== undefined) {
220
358
  doRegister()
@@ -235,7 +373,102 @@ export function assemble(ctx, config, logger) {
235
373
  }
236
374
  }
237
375
 
238
- return { runtime, init, register, dispose, loadModels, dataDir }
376
+ /**
377
+ * ④ 账号池管理路由(由 `index.js` 的 `ctx.inject(['webServer'], …)` 调用)。
378
+ *
379
+ * 之所以单独暴露而不是在 `register()` 里顺手连上:`webServer` 是**可选**
380
+ * 服务,必须用 cordis 的可选注入在它出现时才注册。这里拿到的 `webCtx`
381
+ * 保证带 `webServer`,于是不需要任何探测分支 —— 路由条目多一条都会被
382
+ * 立刻打日志,面板 404 这类症状下次能直接从日志定位。
383
+ *
384
+ * @param {any} webCtx 带 `webServer` 的 context(可选注入回调参数)
385
+ * @returns {() => void} 撤销函数(已用 effect 托管时宿主会再调一次也无害)
386
+ */
387
+ const registerManageRoutes = (webCtx) => {
388
+ const undos = []
389
+ const addUndo = (undo) => {
390
+ if (typeof undo === 'function' && undo !== webCtx) undos.push(undo)
391
+ }
392
+ const undoAll = () => {
393
+ for (const undo of undos.splice(0).reverse()) {
394
+ try {
395
+ undo()
396
+ } catch (error) {
397
+ warn(`撤销管理路由失败:${error instanceof Error ? error.message : String(error)}`)
398
+ }
399
+ }
400
+ }
401
+ if (typeof webCtx?.webServer?.register !== 'function') {
402
+ warn('webServer 服务不可用(预期的可选注入未生效):账号面板路由已跳过')
403
+ return undoAll
404
+ }
405
+ if (runtime.pool === undefined) {
406
+ warn('账号池尚未就绪:账号面板路由已跳过(初始化失败时才会发生)')
407
+ return undoAll
408
+ }
409
+ if (runtime.adapter === undefined) {
410
+ warn('llm 适配器尚未建立:账号面板路由已跳过(初始化失败时才会发生)')
411
+ return undoAll
412
+ }
413
+ const adapter = runtime.adapter
414
+ const routes = makeManageRoutes({
415
+ pool: runtime.pool,
416
+ fetchBalance: (credential) => fetchBalance(credential),
417
+ /**
418
+ * 领取赠送额度要 captcha:复用 plan-client 的**同一份**串行队列与退避闸门,
419
+ * 避免面板点击与推理链路各自起一份 CDP 会话互相踩页面。
420
+ */
421
+ client: runtime.client,
422
+ /** 以调试端口重启宿主(让 captcha 载体可用);失败时面板看到明确错误。 */
423
+ requestRestart: (options) => spawnRestartScript(options),
424
+ /**
425
+ * captcha 载体状态:**每次 /summary 都现探一次**(一次本机 HTTP GET,几毫秒)。
426
+ * 不做缓存 —— 用户点「以调试模式重启」后回来刷新,必须立刻看到新状态。
427
+ * 探测本身失败不影响 summary 其余字段。
428
+ */
429
+ probeCaptcha: async () => {
430
+ const minter = runtime.minter
431
+ const fallback = { mode: config.captcha.mode, debugPort: config.captcha.debugPort, reachable: false }
432
+ if (minter === undefined || typeof minter.probe !== 'function') return fallback
433
+ try {
434
+ const outcome = await minter.probe()
435
+ return {
436
+ ...fallback,
437
+ reachable: outcome?.ok === true,
438
+ ...(outcome?.ok === true ? {} : { reason: outcome?.reason }),
439
+ }
440
+ } catch (error) {
441
+ return { ...fallback, reason: error instanceof Error ? error.message : String(error) }
442
+ }
443
+ },
444
+ log,
445
+ settings,
446
+ onChanged: () => runtime.syncAdapterRoutes?.(),
447
+ onSetUnifiedVisible: (visible) => {
448
+ adapter.setUnifiedVisible(visible)
449
+ settings.unifiedModelList = visible === true
450
+ saveSettings()
451
+ runtime.syncAdapterRoutes?.()
452
+ log(`统一选号栏位${visible === true ? '已显示' : '已隐藏'}`)
453
+ },
454
+ onSetAccountVisible: (accountId, visible) => {
455
+ adapter.setAccountVisible(accountId, visible)
456
+ const hidden = new Set(settings.hiddenModelLists)
457
+ if (visible === true) hidden.delete(accountId)
458
+ else hidden.add(accountId)
459
+ settings.hiddenModelLists = [...hidden]
460
+ saveSettings()
461
+ runtime.syncAdapterRoutes?.()
462
+ const nickname = runtime.pool?.get(accountId)?.nickname ?? accountId.slice(0, 8)
463
+ log(`账号「${nickname}」的模型栏位${visible === true ? '已显示' : '已隐藏'}`)
464
+ },
465
+ })
466
+ for (const route of routes) addUndo(webCtx.webServer.register(route))
467
+ log(`管理路由已注册:${routes.length} 条(/api/zcode-start-plan/*)`)
468
+ return undoAll
469
+ }
470
+
471
+ return { runtime, init, register, registerManageRoutes, dispose, loadModels, dataDir }
239
472
  }
240
473
 
241
474
  /**
@@ -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