chatluna-plugin-kb 0.1.8 → 0.2.8

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/index.mjs CHANGED
@@ -46,6 +46,7 @@ import { registerModelRoutes } from './src/webui/model-routes.mjs'
46
46
  import { createModelBridge } from './src/webui/models.mjs'
47
47
  import { createInstaller, DEFAULT_RELEASE_MANIFEST_URL, platformInfo } from './src/engine/installer.mjs'
48
48
  import { detectEnvironment } from './src/engine/runtime-probe.mjs'
49
+ import { ensureLocalOcrDeps } from './src/engine/deps-installer.mjs'
49
50
  import { resolveScope } from './src/policy/scope.mjs'
50
51
  import {
51
52
  denied,
@@ -462,6 +463,33 @@ export function apply(ctx, config) {
462
463
  ? installer.status()
463
464
  : { supported: false, state: 'unavailable', installed: existsSync(binaryPath) }
464
465
 
466
+ // 本地 OCR 系统组件补齐:非阻塞;失败只返回警告,绝不把核心引擎安装标为失败。
467
+ // 成功后清空探测缓存并广播 status,让向导/引擎状态页立刻看到 OCR 变绿。
468
+ async function installDeps() {
469
+ let result
470
+ try {
471
+ result = await ensureLocalOcrDeps({
472
+ probe: () => probeEnvironment(),
473
+ logger
474
+ })
475
+ } catch (err) {
476
+ result = {
477
+ ok: false,
478
+ skipped: false,
479
+ ready: false,
480
+ missing: ['tesseract', 'pdftoppm'],
481
+ manager: null,
482
+ message: `本地 OCR 组件安装失败:${sanitizeError(err)}`,
483
+ code: 'INSTALL_FAILED'
484
+ }
485
+ }
486
+ envProbe.key = ''
487
+ envProbe.at = 0
488
+ envProbe.promise = null
489
+ emitStatus()
490
+ return result
491
+ }
492
+
465
493
  // ---- 运行环境探测(只读、60s 缓存;状态快照与 kb.detect 共用) ----------
466
494
  const ENV_PROBE_TTL_MS = 60_000
467
495
  const envProbe = { key: '', at: 0, promise: null }
@@ -1185,6 +1213,8 @@ export function apply(ctx, config) {
1185
1213
  // ---- ChatLuna → WeKnora 模型复制桥:列表只读元数据,导入时临时物化密钥 ----
1186
1214
  const modelBridge = createModelBridge({
1187
1215
  ctx,
1216
+ bootstrapFile: join(dataDir, 'bootstrap.json'),
1217
+ defaultKbId: runtime.kbId,
1188
1218
  baseUrl: () => {
1189
1219
  if (runtime.baseUrl !== '') return runtime.baseUrl
1190
1220
  const engineStatus = typeof manager?.status === 'function' ? (manager.status() ?? {}) : {}
@@ -1202,6 +1232,7 @@ export function apply(ctx, config) {
1202
1232
  const listChatlunaModels = () => modelBridge.listChatlunaModels()
1203
1233
  const importChatlunaModel = (input) => modelBridge.importChatlunaModel(input)
1204
1234
  const listWeKnoraModels = () => modelBridge.listWeKnoraModels()
1235
+ const syncChatlunaModels = (input) => modelBridge.syncChatlunaModels(input)
1205
1236
  async function catalog() {
1206
1237
  if (catalogCache !== null && Date.now() - catalogCache.at < CATALOG_TTL_MS) return catalogCache.list
1207
1238
  const list = await client.listKbsRaw()
@@ -1650,6 +1681,7 @@ export function apply(ctx, config) {
1650
1681
  authorize: (context, req) => isWebuiAuthorized(context ?? ctx, req, logger),
1651
1682
  listModels: listChatlunaModels,
1652
1683
  importModel: importChatlunaModel,
1684
+ syncModels: syncChatlunaModels,
1653
1685
  listWeKnoraModels,
1654
1686
  logger
1655
1687
  })
@@ -1683,9 +1715,11 @@ export function apply(ctx, config) {
1683
1715
  cancelInstall,
1684
1716
  testEmbedding,
1685
1717
  saveEmbedding,
1718
+ installDeps,
1686
1719
  // 模型复制:列表已脱敏;导入返回 WeKnora 模型 id/维度,不含密钥。
1687
1720
  listChatlunaModels,
1688
1721
  importChatlunaModel,
1722
+ syncChatlunaModels,
1689
1723
  listWeKnoraModels,
1690
1724
  ruleOptions: readRuleOptions
1691
1725
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chatluna-plugin-kb",
3
- "version": "0.1.8",
3
+ "version": "0.2.8",
4
4
  "description": "ChatLuna v2 knowledge base plugin: WeKnora REST tools, managed weknora-lite engine and WebUI install wizard",
5
5
  "type": "module",
6
6
  "main": "index.mjs",
@@ -0,0 +1,410 @@
1
+ // 本地 OCR 系统依赖补齐(向导安装步骤 / 引擎状态页「一键补齐」共用)。
2
+ //
3
+ // 不变量(改代码前先读):
4
+ // - 全程 execFile + 固定白名单参数数组:绝不使用 shell 字符串拼接,命令与参数都由本模块常量给出。
5
+ // - 绝不 throw:无权限、未知发行版、未知平台、无包管理器、断网、包管理器失败、超时/取消
6
+ // 一律返回 { ok:false, ... } 的非阻塞降级结果,由调用方继续推进核心引擎安装。
7
+ // - 有界执行:每次外部命令都有超时,整体硬超时默认 180s;每一步都按剩余预算设置 timeout,
8
+ // 并透传 AbortSignal(向导「取消安装」),超时只降级不重试。
9
+ // - 提权最小化:仅 Linux 非 root 时探测 `sudo -n true`;失败即放弃,绝不尝试交互式 sudo 或密码。
10
+ // - 先探测后安装:tesseract / pdftoppm 已就绪直接跳过;安装成功后重新探测,以探测结果为准。
11
+ // - 日志只记录阶段与包管理器名称:绝不打印环境变量、命令输出或任何凭据。
12
+ import { execFile } from 'node:child_process'
13
+
14
+ import { detectEnvironment } from './runtime-probe.mjs'
15
+
16
+ const DEFAULT_TIMEOUT_MS = 180_000
17
+ const COMMAND_EXISTS_TIMEOUT_MS = 2_000
18
+ const SUDO_CHECK_TIMEOUT_MS = 5_000
19
+ const MAX_BUFFER_BYTES = 256 * 1024
20
+
21
+ const DEP_LABELS = ['tesseract', 'pdftoppm']
22
+
23
+ // 白名单:命令 + 参数数组。env 只用于强制非交互,绝不从外部输入拼接。
24
+ const MANAGERS = {
25
+ 'apt-get': {
26
+ label: 'apt-get',
27
+ manual: 'sudo apt-get update && sudo apt-get install -y --no-install-recommends tesseract-ocr poppler-utils',
28
+ steps: () => [
29
+ { args: ['update'], env: { DEBIAN_FRONTEND: 'noninteractive' } },
30
+ {
31
+ args: ['install', '-y', '--no-install-recommends', 'tesseract-ocr', 'poppler-utils'],
32
+ env: { DEBIAN_FRONTEND: 'noninteractive' }
33
+ }
34
+ ]
35
+ },
36
+ apk: {
37
+ label: 'apk',
38
+ manual: 'sudo apk add --no-cache tesseract-ocr poppler-utils',
39
+ steps: () => [{ args: ['add', '--no-cache', 'tesseract-ocr', 'poppler-utils'] }]
40
+ },
41
+ dnf: {
42
+ label: 'dnf',
43
+ manual: 'sudo dnf install -y tesseract poppler-utils',
44
+ steps: () => [{ args: ['install', '-y', 'tesseract', 'poppler-utils'] }]
45
+ },
46
+ yum: {
47
+ label: 'yum',
48
+ manual: 'sudo yum install -y tesseract poppler-utils',
49
+ steps: () => [{ args: ['install', '-y', 'tesseract', 'poppler-utils'] }]
50
+ },
51
+ pacman: {
52
+ label: 'pacman',
53
+ manual: 'sudo pacman -Sy --noconfirm --needed tesseract poppler',
54
+ steps: () => [{ args: ['-Sy', '--noconfirm', '--needed', 'tesseract', 'poppler'] }]
55
+ },
56
+ brew: {
57
+ label: 'brew',
58
+ manual: 'brew install tesseract poppler',
59
+ steps: () => [{ args: ['install', 'tesseract', 'poppler'] }]
60
+ }
61
+ }
62
+
63
+ const LINUX_MANAGER_ORDER = ['apt-get', 'apk', 'dnf', 'yum', 'pacman']
64
+
65
+ function int(value, min, max, fallback) {
66
+ const n = Number(value)
67
+ if (!Number.isFinite(n)) return fallback
68
+ return Math.min(max, Math.max(min, Math.trunc(n)))
69
+ }
70
+
71
+ function safeLog(logger, level, message) {
72
+ try {
73
+ const fn = logger?.[level]
74
+ if (typeof fn === 'function') fn.call(logger, message)
75
+ } catch {
76
+ // 日志失败绝不影响安装流程。
77
+ }
78
+ }
79
+
80
+ function result({ ok, skipped, ready, missing, manager, message, code }) {
81
+ return { ok, skipped, ready, missing, manager, message, code }
82
+ }
83
+
84
+ // 探测结果归一化:接受 detectEnvironment 的完整快照或最小 { tesseractFound, pdftoppmFound }。
85
+ function normalizeProbe(value) {
86
+ const tesseractFound = value?.tesseractFound === true || value?.ocr?.tesseractFound === true
87
+ const pdftoppmFound = value?.pdftoppmFound === true || value?.ocr?.pdftoppmFound === true
88
+ const missing = []
89
+ if (!tesseractFound) missing.push('tesseract')
90
+ if (!pdftoppmFound) missing.push('pdftoppm')
91
+ return { ready: missing.length === 0, missing }
92
+ }
93
+
94
+ function createRunCommand(execFileImpl, deadline, externalSignal) {
95
+ return function runCommand(command, args, { timeoutMs, env } = {}) {
96
+ const remaining = Math.min(timeoutMs ?? DEFAULT_TIMEOUT_MS, deadline - Date.now())
97
+ return new Promise((resolvePromise) => {
98
+ const signal = externalSignal
99
+ if (signal?.aborted) {
100
+ resolvePromise({ ok: false, code: 'ABORTED' })
101
+ return
102
+ }
103
+ if (remaining <= 0) {
104
+ resolvePromise({ ok: false, code: 'TIMEOUT' })
105
+ return
106
+ }
107
+
108
+ const options = {
109
+ timeout: remaining,
110
+ killSignal: 'SIGKILL',
111
+ maxBuffer: MAX_BUFFER_BYTES,
112
+ windowsHide: true
113
+ }
114
+ if (env && typeof env === 'object') options.env = env
115
+ if (signal) options.signal = signal
116
+
117
+ let settled = false
118
+ let timer = null
119
+ const finish = (outcome) => {
120
+ if (settled) return
121
+ settled = true
122
+ clearTimeout(timer)
123
+ if (signal && typeof signal.removeEventListener === 'function') {
124
+ signal.removeEventListener('abort', onAbort)
125
+ }
126
+ resolvePromise(outcome)
127
+ }
128
+ function onAbort() {
129
+ finish({ ok: false, code: 'ABORTED' })
130
+ }
131
+ if (signal && typeof signal.addEventListener === 'function') {
132
+ signal.addEventListener('abort', onAbort, { once: true })
133
+ }
134
+ timer = setTimeout(() => finish({ ok: false, code: 'TIMEOUT' }), remaining)
135
+ timer.unref?.()
136
+
137
+ try {
138
+ execFileImpl(command, args, options, (err, stdout, stderr) => {
139
+ if (!err) {
140
+ finish({ ok: true, code: 'OK', stdout, stderr })
141
+ return
142
+ }
143
+ const code = err.code === 'ENOENT' ? 'ENOENT' : 'FAILED'
144
+ finish({ ok: false, code, error: err, stdout, stderr })
145
+ })
146
+ } catch (err) {
147
+ finish({ ok: false, code: err?.code === 'ENOENT' ? 'ENOENT' : 'FAILED', error: err })
148
+ }
149
+ })
150
+ }
151
+ }
152
+
153
+ function baseEnv(env) {
154
+ if (env && typeof env === 'object') return env
155
+ return process.env
156
+ }
157
+
158
+ function stepEnv(step, env) {
159
+ if (!step.env) return env && typeof env === 'object' ? env : undefined
160
+ return { ...baseEnv(env), ...step.env }
161
+ }
162
+
163
+ function isRoot(getuid) {
164
+ try {
165
+ return typeof getuid === 'function' && getuid() === 0
166
+ } catch {
167
+ return false
168
+ }
169
+ }
170
+
171
+ export async function ensureLocalOcrDeps(options = {}) {
172
+ const execFileImpl = typeof options.execFileImpl === 'function' ? options.execFileImpl : execFile
173
+ const platform = options.platform ?? process.platform
174
+ const getuid = options.getuid === undefined ? process.getuid : options.getuid
175
+ const logger = options.logger ?? null
176
+ const timeoutMs = int(options.timeoutMs, 100, 3_600_000, DEFAULT_TIMEOUT_MS)
177
+ const force = options.force === true
178
+ const externalSignal = options.signal ?? null
179
+ const env = options.env && typeof options.env === 'object' ? options.env : undefined
180
+
181
+ let initialMissing = [...DEP_LABELS]
182
+ let manager = null
183
+ let useSudo = false
184
+
185
+ try {
186
+ if (externalSignal?.aborted) {
187
+ return result({
188
+ ok: false,
189
+ skipped: false,
190
+ ready: false,
191
+ missing: initialMissing,
192
+ manager: null,
193
+ message: '已取消本地 OCR 组件安装',
194
+ code: 'CANCELLED'
195
+ })
196
+ }
197
+
198
+ const deadline = Date.now() + timeoutMs
199
+ const runCommand = createRunCommand(execFileImpl, deadline, externalSignal)
200
+
201
+ const probe =
202
+ typeof options.probe === 'function'
203
+ ? options.probe
204
+ : () => detectEnvironment({ platform, env })
205
+
206
+ const probeOnce = async () => normalizeProbe(await probe())
207
+ const first = await probeOnce()
208
+ initialMissing = first.missing
209
+
210
+ if (first.ready && !force) {
211
+ return result({
212
+ ok: true,
213
+ skipped: true,
214
+ ready: true,
215
+ missing: [],
216
+ manager: null,
217
+ message: '本地 OCR 组件已就绪(tesseract / pdftoppm)',
218
+ code: 'ALREADY_READY'
219
+ })
220
+ }
221
+
222
+ const commandExists = async (command) => {
223
+ const res = await runCommand(command, ['--version'], { timeoutMs: COMMAND_EXISTS_TIMEOUT_MS })
224
+ return res.code !== 'ENOENT' && res.code !== 'ABORTED' && res.code !== 'TIMEOUT'
225
+ ? res.ok || res.code === 'FAILED'
226
+ : false
227
+ }
228
+
229
+ if (platform === 'linux') {
230
+ for (const candidate of LINUX_MANAGER_ORDER) {
231
+ if (await commandExists(candidate)) {
232
+ manager = candidate
233
+ break
234
+ }
235
+ }
236
+ } else if (platform === 'darwin') {
237
+ if (await commandExists('brew')) manager = 'brew'
238
+ } else {
239
+ return result({
240
+ ok: false,
241
+ skipped: false,
242
+ ready: false,
243
+ missing: initialMissing,
244
+ manager: null,
245
+ message: `当前平台(${platform})不支持自动安装本地 OCR 组件,如需扫描件 OCR 请手动安装 tesseract 与 poppler`,
246
+ code: 'UNSUPPORTED_PLATFORM'
247
+ })
248
+ }
249
+
250
+ if (externalSignal?.aborted) {
251
+ return result({
252
+ ok: false,
253
+ skipped: false,
254
+ ready: false,
255
+ missing: initialMissing,
256
+ manager,
257
+ message: '已取消本地 OCR 组件安装',
258
+ code: 'CANCELLED'
259
+ })
260
+ }
261
+
262
+ if (manager === null) {
263
+ return result({
264
+ ok: false,
265
+ skipped: false,
266
+ ready: false,
267
+ missing: initialMissing,
268
+ manager: null,
269
+ message: '未检测到受支持的包管理器(apt-get / apk / dnf / yum / pacman / brew),如需扫描件 OCR 请手动安装 tesseract 与 poppler',
270
+ code: 'NO_PACKAGE_MANAGER'
271
+ })
272
+ }
273
+
274
+ if (platform === 'linux' && !isRoot(getuid)) {
275
+ let sudoOk
276
+ if (typeof options.sudoCheck === 'boolean') {
277
+ sudoOk = options.sudoCheck
278
+ } else if (typeof options.sudoCheck === 'function') {
279
+ try {
280
+ sudoOk = (await options.sudoCheck()) === true
281
+ } catch {
282
+ sudoOk = false
283
+ }
284
+ } else {
285
+ const check = await runCommand('sudo', ['-n', 'true'], { timeoutMs: SUDO_CHECK_TIMEOUT_MS })
286
+ sudoOk = check.ok
287
+ }
288
+ if (!sudoOk) {
289
+ const hint = MANAGERS[manager].manual
290
+ return result({
291
+ ok: false,
292
+ skipped: false,
293
+ ready: false,
294
+ missing: initialMissing,
295
+ manager,
296
+ message: `本地 OCR 系统组件未能自动安装(原因:无系统包管理权限);如需扫描件 OCR,请手动运行:${hint}`,
297
+ code: 'NO_PERMISSION'
298
+ })
299
+ }
300
+ useSudo = true
301
+ }
302
+
303
+ safeLog(logger, 'info', `正在补齐本地 OCR 组件(${MANAGERS[manager].label})…`)
304
+
305
+ const steps = MANAGERS[manager].steps()
306
+ for (const step of steps) {
307
+ if (externalSignal?.aborted) {
308
+ return result({
309
+ ok: false,
310
+ skipped: false,
311
+ ready: false,
312
+ missing: initialMissing,
313
+ manager,
314
+ message: '已取消本地 OCR 组件安装',
315
+ code: 'CANCELLED'
316
+ })
317
+ }
318
+ const remaining = deadline - Date.now()
319
+ if (remaining <= 0) {
320
+ safeLog(logger, 'warn', `补齐本地 OCR 组件超时(${MANAGERS[manager].label})`)
321
+ return result({
322
+ ok: false,
323
+ skipped: false,
324
+ ready: false,
325
+ missing: initialMissing,
326
+ manager,
327
+ message: `本地 OCR 系统组件安装超时(${Math.round(timeoutMs / 1000)}s),已跳过,不影响文本 / Markdown / Office 解析`,
328
+ code: 'TIMEOUT'
329
+ })
330
+ }
331
+ const command = useSudo ? 'sudo' : manager
332
+ const args = useSudo ? ['-n', manager, ...step.args] : step.args
333
+ const res = await runCommand(command, args, {
334
+ timeoutMs: remaining,
335
+ env: stepEnv(step, env)
336
+ })
337
+ if (res.code === 'ABORTED') {
338
+ return result({
339
+ ok: false,
340
+ skipped: false,
341
+ ready: false,
342
+ missing: initialMissing,
343
+ manager,
344
+ message: '已取消本地 OCR 组件安装',
345
+ code: 'CANCELLED'
346
+ })
347
+ }
348
+ if (res.code === 'TIMEOUT') {
349
+ safeLog(logger, 'warn', `补齐本地 OCR 组件超时(${MANAGERS[manager].label})`)
350
+ return result({
351
+ ok: false,
352
+ skipped: false,
353
+ ready: false,
354
+ missing: initialMissing,
355
+ manager,
356
+ message: `本地 OCR 系统组件安装超时(${Math.round(timeoutMs / 1000)}s),已跳过,不影响文本 / Markdown / Office 解析`,
357
+ code: 'TIMEOUT'
358
+ })
359
+ }
360
+ if (!res.ok) {
361
+ safeLog(logger, 'warn', `补齐本地 OCR 组件失败(${MANAGERS[manager].label})`)
362
+ return result({
363
+ ok: false,
364
+ skipped: false,
365
+ ready: false,
366
+ missing: initialMissing,
367
+ manager,
368
+ message: `本地 OCR 系统组件安装失败(${MANAGERS[manager].label}),已跳过,不影响文本 / Markdown / Office 解析;如需扫描件 OCR,请手动运行:${MANAGERS[manager].manual}`,
369
+ code: 'INSTALL_FAILED'
370
+ })
371
+ }
372
+ }
373
+
374
+ const after = await probeOnce()
375
+ if (after.ready) {
376
+ safeLog(logger, 'info', `本地 OCR 组件已安装(${MANAGERS[manager].label})`)
377
+ return result({
378
+ ok: true,
379
+ skipped: false,
380
+ ready: true,
381
+ missing: [],
382
+ manager,
383
+ message: '本地 OCR 组件已安装(tesseract / pdftoppm)',
384
+ code: 'INSTALLED'
385
+ })
386
+ }
387
+
388
+ safeLog(logger, 'warn', '本地 OCR 组件安装命令已执行,但重新探测仍未就绪')
389
+ return result({
390
+ ok: false,
391
+ skipped: false,
392
+ ready: false,
393
+ missing: after.missing,
394
+ manager,
395
+ message: `安装命令已执行,但仍未检测到 ${after.missing.join(' / ')},请手动检查;文本 / Markdown / Office 解析不受影响`,
396
+ code: 'VERIFY_FAILED'
397
+ })
398
+ } catch (err) {
399
+ safeLog(logger, 'warn', '补齐本地 OCR 组件时发生内部错误,已降级跳过')
400
+ return result({
401
+ ok: false,
402
+ skipped: false,
403
+ ready: false,
404
+ missing: initialMissing,
405
+ manager,
406
+ message: '本地 OCR 系统组件补齐过程发生内部错误,已跳过,不影响文本 / Markdown / Office 解析',
407
+ code: 'INTERNAL_ERROR'
408
+ })
409
+ }
410
+ }
@@ -3,6 +3,7 @@
3
3
  //
4
4
  // GET <prefix>/chatluna-models ChatLuna 已配置模型(脱敏)
5
5
  // POST <prefix>/models/import-from-chatluna 一次性复制 { role, providerId, modelId }
6
+ // POST <prefix>/models/sync-from-chatluna 批量同步 { items, bindDefaultKb }
6
7
  // GET <prefix>/models WeKnora 当前模型(可选回调)
7
8
  //
8
9
  // 不变量(改动前必读):
@@ -29,6 +30,7 @@ const VALUE_NODES_MAX = 2000
29
30
  const VALUE_ARRAY_MAX = 200
30
31
 
31
32
  const IMPORT_ROLES = new Set(['embedding', 'chat', 'vlm', 'rerank'])
33
+ const SYNC_MAX_ITEMS = 32
32
34
  const CONFLICT_CODES = new Set(['CONFLICT', 'ALREADY_EXISTS', 'DUPLICATE', 'MODEL_EXISTS', 'EXISTS'])
33
35
  const VALIDATION_CODES = new Set([
34
36
  'INVALID_ARGUMENT',
@@ -299,6 +301,29 @@ function validateImport(body) {
299
301
  }
300
302
  }
301
303
 
304
+ function validateSync(body) {
305
+ if (!isPlainObject(body)) {
306
+ throw new ModelRouteError('INVALID_ARGUMENT', '请求体必须是 JSON 对象')
307
+ }
308
+ if (!Array.isArray(body.items) || body.items.length === 0) {
309
+ throw new ModelRouteError('INVALID_ARGUMENT', 'items 必须是非空数组')
310
+ }
311
+ if (body.items.length > SYNC_MAX_ITEMS) {
312
+ throw new ModelRouteError('INVALID_ARGUMENT', `items 不能超过 ${SYNC_MAX_ITEMS} 条`)
313
+ }
314
+ const items = body.items.map((item, index) => {
315
+ try {
316
+ return validateImport(item)
317
+ } catch (error) {
318
+ throw new ModelRouteError(
319
+ 'INVALID_ARGUMENT',
320
+ `items[${index}]:${error instanceof Error ? error.message : '参数无效'}`
321
+ )
322
+ }
323
+ })
324
+ return { items, bindDefaultKb: body.bindDefaultKb === true }
325
+ }
326
+
302
327
  function statusForError(error) {
303
328
  const status = Number(error?.status ?? error?.statusCode)
304
329
  if (status === 409) return 409
@@ -323,6 +348,7 @@ function disposeOf(handle) {
323
348
  * @param {(ctx: object, req: object) => boolean | Promise<boolean>} options.authorize
324
349
  * @param {() => unknown | Promise<unknown>} options.listModels
325
350
  * @param {(input: { role: 'embedding' | 'chat' | 'vlm' | 'rerank', providerId: string, modelId: string }) => unknown | Promise<unknown>} options.importModel
351
+ * @param {(input: { items: Array<{ role: 'embedding' | 'chat' | 'vlm' | 'rerank', providerId: string, modelId: string }>, bindDefaultKb: boolean }) => unknown | Promise<unknown>} [options.syncModels]
326
352
  * @param {() => unknown | Promise<unknown>} [options.listWeKnoraModels]
327
353
  * @param {object} [options.logger]
328
354
  * @returns {() => void} dispose
@@ -350,6 +376,7 @@ export function registerModelRoutes(ctx, options = {}) {
350
376
  const authorize = options.authorize
351
377
  const listModels = options.listModels
352
378
  const importModel = options.importModel
379
+ const syncModels = typeof options.syncModels === 'function' ? options.syncModels : null
353
380
  const listWeKnoraModels =
354
381
  typeof options.listWeKnoraModels === 'function' ? options.listWeKnoraModels : null
355
382
 
@@ -413,6 +440,47 @@ export function registerModelRoutes(ctx, options = {}) {
413
440
  sendJson(res, 200, { success: true, data: sanitizeValue(result ?? null) })
414
441
  }
415
442
 
443
+ const syncHandler = async (req, res) => {
444
+ if (!(await allowed(req))) {
445
+ sendError(res, 401, 'UNAUTHORIZED', '需要 ChatLuna WebUI 管理员登录')
446
+ return
447
+ }
448
+ if (syncModels === null) {
449
+ sendError(res, 501, 'NOT_IMPLEMENTED', '当前部署未提供批量模型同步')
450
+ return
451
+ }
452
+
453
+ let input
454
+ try {
455
+ input = validateSync(await readJsonBody(req, maxBytes))
456
+ } catch (error) {
457
+ if (error instanceof ModelRouteError) {
458
+ const status = error.code === 'PAYLOAD_TOO_LARGE' ? 413 : 400
459
+ sendError(res, status, error.code, clipMessage(error.message, '请求无效'))
460
+ return
461
+ }
462
+ logger.error?.('model-routes: cannot read sync body: %s', clipMessage(error?.message, 'error'))
463
+ sendError(res, 400, 'INVALID_ARGUMENT', '请求体无法解析')
464
+ return
465
+ }
466
+
467
+ let result
468
+ try {
469
+ result = await syncModels(input)
470
+ } catch (error) {
471
+ const status = statusForError(error)
472
+ const code =
473
+ status === 500
474
+ ? 'SYNC_FAILED'
475
+ : safeCode(error?.code, status === 409 ? 'CONFLICT' : 'INVALID_ARGUMENT')
476
+ logger.error?.('model-routes: sync failed (status %d): %s', status, clipMessage(error?.message, code))
477
+ const message = status === 500 ? '模型同步失败' : clipMessage(error?.message, '模型同步失败')
478
+ sendError(res, status, code, message)
479
+ return
480
+ }
481
+ sendJson(res, 200, { success: true, data: sanitizeValue(result ?? null) })
482
+ }
483
+
416
484
  const weknoraModelsHandler = async (req, res) => {
417
485
  if (!(await allowed(req))) {
418
486
  sendError(res, 401, 'UNAUTHORIZED', '需要 ChatLuna WebUI 管理员登录')
@@ -437,6 +505,7 @@ export function registerModelRoutes(ctx, options = {}) {
437
505
  try {
438
506
  registered.push(ctx.server.get(`${prefix}/chatluna-models`, chatlunaModelsHandler))
439
507
  registered.push(ctx.server.post(`${prefix}/models/import-from-chatluna`, importHandler))
508
+ registered.push(ctx.server.post(`${prefix}/models/sync-from-chatluna`, syncHandler))
440
509
  registered.push(ctx.server.get(`${prefix}/models`, weknoraModelsHandler))
441
510
  } catch (error) {
442
511
  for (const handle of registered) {