chatluna-plugin-kb 0.1.7 → 0.2.7

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.
@@ -1,3 +1,5 @@
1
+ import { readFile, writeFile } from 'node:fs/promises'
2
+
1
3
  // ChatLuna → WeKnora 模型桥接。
2
4
  //
3
5
  // 不变量(改代码前必读):
@@ -20,9 +22,19 @@ const ROUTES_MAX = 64
20
22
  const ROUTE_MODELS_MAX = 512
21
23
  const MESSAGE_MAX = 200
22
24
  const DEFAULT_TIMEOUT_MS = 15_000
25
+ const SYNC_MAX_ITEMS = 32
26
+ const SYNC_CONCURRENCY = 3
23
27
 
24
28
  const IMPORT_ROLES = new Set(['embedding', 'chat', 'vlm', 'rerank'])
25
29
 
30
+ // ChatLuna 角色 → WeKnora 模型类型。同步时用它与已有模型做幂等匹配。
31
+ const WEKNORA_TYPE_BY_ROLE = Object.freeze({
32
+ embedding: 'Embedding',
33
+ chat: 'KnowledgeQA',
34
+ vlm: 'VLLM',
35
+ rerank: 'Rerank'
36
+ })
37
+
26
38
  export class ModelBridgeError extends Error {
27
39
  constructor(code, message) {
28
40
  super(message)
@@ -294,6 +306,9 @@ export function findChatlunaModel(entries, input) {
294
306
  baseUrl: routeBaseUrlOf(route, wanted.role),
295
307
  dimension: dimensionOf(model),
296
308
  supportsVision: modelSupportsVision(capabilities),
309
+ capabilities,
310
+ contextWindow: safePositiveInt(model?.contextWindow),
311
+ maxOutputTokens: safePositiveInt(model?.maxOutputTokens),
297
312
  protocolHint: protocolHintOf(route, routeBaseUrlOf(route, wanted.role)),
298
313
  displayName:
299
314
  textOf(model.displayName, NAME_MAX) ||
@@ -324,6 +339,326 @@ function sessionTokenOf(login) {
324
339
  return typeof token === 'string' ? token.trim() : ''
325
340
  }
326
341
 
342
+ // ---- 批量同步 -------------------------------------------------------------
343
+
344
+ /** 归一化 baseUrl 用于幂等匹配:去首尾空白、去尾部斜杠、统一小写。 */
345
+ export function normalizeModelBaseUrl(value) {
346
+ const text = typeof value === 'string' ? value.trim() : ''
347
+ if (text === '') return ''
348
+ return text.replace(/\/+$/, '').toLowerCase()
349
+ }
350
+
351
+ /** ChatLuna 角色 → WeKnora 模型类型;未知角色返回空串。 */
352
+ export function weknoraTypeForRole(role) {
353
+ return WEKNORA_TYPE_BY_ROLE[role] ?? ''
354
+ }
355
+
356
+ function validateSyncInput(input) {
357
+ if (!isPlainObject(input)) {
358
+ throw new ModelBridgeError('INVALID_ARGUMENT', '批量同步参数必须是对象')
359
+ }
360
+ const raw = input.items
361
+ if (!Array.isArray(raw) || raw.length === 0) {
362
+ throw new ModelBridgeError('INVALID_ARGUMENT', 'items 必须是非空数组')
363
+ }
364
+ if (raw.length > SYNC_MAX_ITEMS) {
365
+ throw new ModelBridgeError('INVALID_ARGUMENT', `items 不能超过 ${SYNC_MAX_ITEMS} 条`)
366
+ }
367
+ const items = []
368
+ const seen = new Set()
369
+ for (let index = 0; index < raw.length; index += 1) {
370
+ let parsed
371
+ try {
372
+ parsed = validateImportInput(raw[index])
373
+ } catch (error) {
374
+ throw new ModelBridgeError(
375
+ 'INVALID_ARGUMENT',
376
+ `items[${index}]:${errorMessage(error) || '参数无效'}`
377
+ )
378
+ }
379
+ const key = `${parsed.providerId}\u0000${parsed.modelId}\u0000${parsed.role}`
380
+ if (seen.has(key)) continue
381
+ seen.add(key)
382
+ items.push(parsed)
383
+ }
384
+ return { items, bindDefaultKb: input.bindDefaultKb === true }
385
+ }
386
+
387
+ function existingModelKey(modelId, baseUrl, type) {
388
+ return [
389
+ typeof modelId === 'string' ? modelId.trim() : '',
390
+ normalizeModelBaseUrl(baseUrl),
391
+ typeof type === 'string' ? type.toLowerCase() : ''
392
+ ].join('\u0000')
393
+ }
394
+
395
+ /** 把 WeKnora 模型列表摊平成匹配索引;`name` 是导入时写下的模型 id。 */
396
+ function toExistingModelIndex(list) {
397
+ const source = Array.isArray(list) ? list : Array.isArray(list?.models) ? list.models : []
398
+ const index = new Map()
399
+ for (const raw of source) {
400
+ if (!isPlainObject(raw)) continue
401
+ const modelId = textOf(raw.modelId ?? raw.name, ID_MAX)
402
+ if (modelId === '') continue
403
+ const id = textOf(raw.id, ID_MAX) || modelId
404
+ const key = existingModelKey(modelId, raw.baseUrl ?? raw.base_url, raw.type)
405
+ if (!index.has(key)) index.set(key, { id })
406
+ }
407
+ return index
408
+ }
409
+
410
+ function failedSyncResult(item, error) {
411
+ const code = typeof error?.code === 'string' ? error.code : ''
412
+ const reason = sanitizeMessage(
413
+ errorMessage(error) || (code !== '' ? `${code}:模型同步失败` : '模型同步失败')
414
+ )
415
+ return {
416
+ providerId: item.providerId,
417
+ modelId: item.modelId,
418
+ role: item.role,
419
+ status: 'failed',
420
+ reason
421
+ }
422
+ }
423
+
424
+ /** 同 key 的导入串行化,避免两个不同 provider 的相同模型并发重复创建。 */
425
+ function keyedLock() {
426
+ const chains = new Map()
427
+ return (key, run) => {
428
+ const previous = chains.get(key) ?? Promise.resolve()
429
+ const next = previous.then(run, run)
430
+ chains.set(
431
+ key,
432
+ next.then(
433
+ () => undefined,
434
+ () => undefined
435
+ )
436
+ )
437
+ return next
438
+ }
439
+ }
440
+
441
+ /**
442
+ * 批量同步 ChatLuna 模型到 WeKnora。
443
+ *
444
+ * 输入 `{ items: [{ providerId, modelId, role }], bindDefaultKb?: true }`:
445
+ * - items 非空且 <= 32 条,按 (providerId, modelId, role) 去重;
446
+ * - 先读取 WeKnora 已有模型,按 `modelId + 归一化 baseUrl + 目标类型` 幂等跳过;
447
+ * - 单项导入失败不中断整批,并发度 <= 3;
448
+ * - bindDefaultKb 为 true 时,把成功/复用的 embedding 模型绑定到默认知识库,
449
+ * 并尝试回写 bootstrap.json。
450
+ *
451
+ * `options` 依赖注入(均由 createModelBridge 提供):
452
+ * - importChatlunaModel(input) 必填,返回值至少含 `modelId`;
453
+ * - listWeKnoraModels() 可选,返回 WeKnora 模型数组;
454
+ * - findModel(input) 可选,默认用 options.entries + findChatlunaModel;
455
+ * - bindKb:{ getDefaultKb, bindEmbedding, persistEmbedding },默认知识库绑定钩子。
456
+ *
457
+ * @returns {Promise<{total: number, imported: number, skipped: number, failed: number,
458
+ * boundEmbeddingModelId: string|null,
459
+ * results: Array<{providerId: string, modelId: string, role: string, status: string,
460
+ * createdModelId?: string, reason?: string}>,
461
+ * bindWarning?: string}>}
462
+ */
463
+ export async function syncChatlunaModels(input, options = {}) {
464
+ const { items, bindDefaultKb } = validateSyncInput(input)
465
+ const importChatlunaModel = options.importChatlunaModel
466
+ if (typeof importChatlunaModel !== 'function') {
467
+ throw new ModelBridgeError('INVALID_ARGUMENT', '缺少模型导入实现')
468
+ }
469
+ const listWeKnoraModels =
470
+ typeof options.listWeKnoraModels === 'function' ? options.listWeKnoraModels : null
471
+ const resolveModel =
472
+ typeof options.findModel === 'function'
473
+ ? options.findModel
474
+ : (item) => findChatlunaModel(Array.isArray(options.entries) ? options.entries : [], item)
475
+
476
+ let existing = new Map()
477
+ if (listWeKnoraModels !== null) {
478
+ try {
479
+ existing = toExistingModelIndex(await listWeKnoraModels())
480
+ } catch (error) {
481
+ // 列表失败不阻断同步:按“无已有模型”继续,最坏由 WeKnora 侧冲突兜底。
482
+ options.logger?.warn?.(`models: cannot list WeKnora models for sync: ${sanitizeMessage(errorMessage(error))}`)
483
+ existing = new Map()
484
+ }
485
+ }
486
+
487
+ const withKeyLock = keyedLock()
488
+ const processItem = async (item) => {
489
+ let found
490
+ try {
491
+ found = resolveModel(item)
492
+ } catch (error) {
493
+ return failedSyncResult(item, error)
494
+ }
495
+ if (found === null || found === undefined) {
496
+ return failedSyncResult(
497
+ item,
498
+ new ModelBridgeError('MODEL_NOT_FOUND', 'ChatLuna 中找不到该模型配置')
499
+ )
500
+ }
501
+ const targetType = weknoraTypeForRole(item.role)
502
+ const displayName = textOf(found.displayName, NAME_MAX) || item.modelId
503
+ const key = existingModelKey(item.modelId, found.baseUrl ?? '', targetType)
504
+ return withKeyLock(key, async () => {
505
+ const hit = existing.get(key)
506
+ if (hit !== undefined) {
507
+ return {
508
+ providerId: item.providerId,
509
+ modelId: item.modelId,
510
+ role: item.role,
511
+ status: 'skipped',
512
+ createdModelId: hit.id,
513
+ name: displayName,
514
+ reason: '知识库已存在相同模型'
515
+ }
516
+ }
517
+ try {
518
+ const result = await importChatlunaModel(item)
519
+ const createdModelId = textOf(result?.modelId ?? result?.id, ID_MAX)
520
+ if (createdModelId === '') {
521
+ throw new ModelBridgeError('IMPORT_FAILED', '模型同步失败:未返回模型 id')
522
+ }
523
+ existing.set(key, { id: createdModelId })
524
+ return {
525
+ providerId: item.providerId,
526
+ modelId: item.modelId,
527
+ role: item.role,
528
+ status: 'imported',
529
+ createdModelId,
530
+ name: displayName
531
+ }
532
+ } catch (error) {
533
+ return failedSyncResult(item, error)
534
+ }
535
+ })
536
+ }
537
+
538
+ const results = new Array(items.length)
539
+ let cursor = 0
540
+ const worker = async () => {
541
+ for (;;) {
542
+ const index = cursor
543
+ cursor += 1
544
+ if (index >= items.length) return
545
+ results[index] = await processItem(items[index])
546
+ }
547
+ }
548
+ await Promise.all(
549
+ Array.from({ length: Math.min(SYNC_CONCURRENCY, items.length) }, () => worker())
550
+ )
551
+
552
+ let imported = 0
553
+ let skipped = 0
554
+ let failed = 0
555
+ for (const result of results) {
556
+ if (result.status === 'imported') imported += 1
557
+ else if (result.status === 'skipped') skipped += 1
558
+ else failed += 1
559
+ }
560
+
561
+ let boundEmbeddingModelId = null
562
+ let boundEmbeddingModelName = ''
563
+ let boundSummaryModelId = null
564
+ let boundSummaryModelName = ''
565
+ let bindWarning
566
+ if (bindDefaultKb) {
567
+ const embedding = results.find(
568
+ (result) =>
569
+ result.role === 'embedding' &&
570
+ typeof result.createdModelId === 'string' &&
571
+ result.createdModelId !== ''
572
+ )
573
+ const chatModel = results.find(
574
+ (result) =>
575
+ (result.role === 'chat' || result.role === 'vlm') &&
576
+ typeof result.createdModelId === 'string' &&
577
+ result.createdModelId !== ''
578
+ )
579
+ // skipped 结果同时带 createdModelId;失败结果不带,因此只需看 createdModelId。
580
+ const bind = options.bindKb
581
+ if (embedding !== undefined) {
582
+ if (bind === null || typeof bind !== 'object' || typeof bind.getDefaultKb !== 'function') {
583
+ bindWarning = '未配置默认知识库绑定能力,未绑定 Embedding 模型'
584
+ } else {
585
+ try {
586
+ const kb = await bind.getDefaultKb()
587
+ const kbId = textOf(kb?.id, ID_MAX)
588
+ if (kbId === '') {
589
+ bindWarning = '没有可绑定的默认知识库'
590
+ } else {
591
+ const bound = textOf(kb?.embeddingModelId ?? kb?.embedding_model_id, ID_MAX)
592
+ const boundSummary = textOf(kb?.summaryModelId ?? kb?.summary_model_id, ID_MAX)
593
+ const summaryId =
594
+ boundSummary === '' && chatModel !== undefined
595
+ ? textOf(chatModel.createdModelId, ID_MAX)
596
+ : ''
597
+ if (bound === '' || summaryId !== '') {
598
+ const update =
599
+ typeof bind.bindEmbedding === 'function'
600
+ ? await bind.bindEmbedding(kbId, embedding.createdModelId, summaryId)
601
+ : { ok: true }
602
+ if (update !== null && typeof update === 'object' && update.ok === false) {
603
+ bindWarning = sanitizeMessage(update.reason ?? '绑定默认知识库失败')
604
+ } else {
605
+ if (bound === '') {
606
+ boundEmbeddingModelId = embedding.createdModelId
607
+ boundEmbeddingModelName = textOf(embedding.name, NAME_MAX) || embedding.modelId
608
+ }
609
+ if (summaryId !== '') {
610
+ boundSummaryModelId = summaryId
611
+ boundSummaryModelName = textOf(chatModel.name, NAME_MAX) || chatModel.modelId
612
+ }
613
+ if (bound === '' && typeof bind.persistEmbedding === 'function') {
614
+ const saved = await bind.persistEmbedding(boundEmbeddingModelId)
615
+ if (saved !== null && typeof saved === 'object' && saved.ok === false) {
616
+ bindWarning = sanitizeMessage(saved.reason ?? 'bootstrap.json 未更新')
617
+ }
618
+ }
619
+ }
620
+ }
621
+ }
622
+ } catch (error) {
623
+ bindWarning = sanitizeMessage(
624
+ `绑定默认知识库失败:${errorMessage(error) || '未知错误'}`
625
+ )
626
+ }
627
+ }
628
+ }
629
+ }
630
+
631
+ const result = {
632
+ total: items.length,
633
+ imported,
634
+ skipped,
635
+ failed,
636
+ boundEmbeddingModelId,
637
+ boundEmbeddingModelName,
638
+ boundSummaryModelId,
639
+ boundSummaryModelName,
640
+ results
641
+ }
642
+ if (bindWarning !== undefined) result.bindWarning = bindWarning
643
+ return result
644
+ }
645
+
646
+ /** 正整数读取;超出安全范围/非正数返回 null,避免把脏配置写进引擎。 */
647
+ function safePositiveInt(value) {
648
+ const n = Number(value)
649
+ return Number.isSafeInteger(n) && n > 0 ? n : null
650
+ }
651
+
652
+ /** ChatLuna 能力 → WeKnora spec.input 白名单。 */
653
+ function modelInputs(capabilities) {
654
+ const lower = (Array.isArray(capabilities) ? capabilities : [])
655
+ .map((item) => (typeof item === 'string' ? item.toLowerCase() : ''))
656
+ const inputs = ['text']
657
+ if (lower.some((item) => item === 'vision' || item === 'vlm')) inputs.push('image')
658
+ if (lower.some((item) => item === 'audio' || item === 'listen')) inputs.push('audio')
659
+ return inputs
660
+ }
661
+
327
662
  /** POST body 构造单独导出,测试可以断言明文 key 只出现在 parameters.api_key。 */
328
663
  export function buildModelCreateBody({
329
664
  role,
@@ -333,7 +668,10 @@ export function buildModelCreateBody({
333
668
  displayName,
334
669
  dimension,
335
670
  supportsVision = false,
336
- protocolHint = ''
671
+ protocolHint = '',
672
+ capabilities = [],
673
+ contextWindow = null,
674
+ maxOutputTokens = null
337
675
  }) {
338
676
  const embedding = role === 'embedding'
339
677
  const chat = role === 'chat'
@@ -351,12 +689,12 @@ export function buildModelCreateBody({
351
689
  type: embedding ? 'Embedding' : chat ? 'KnowledgeQA' : rerank ? 'Rerank' : 'VLLM',
352
690
  source: 'remote',
353
691
  description: embedding
354
- ? '从 ChatLuna 复制的 Embedding 模型'
692
+ ? '从 ChatLuna 同步的 Embedding 模型'
355
693
  : chat
356
- ? '从 ChatLuna 复制的对话模型'
694
+ ? '从 ChatLuna 同步的对话模型'
357
695
  : rerank
358
- ? '从 ChatLuna 复制的 ReRank 模型'
359
- : '从 ChatLuna 复制的视觉模型',
696
+ ? '从 ChatLuna 同步的 ReRank 模型'
697
+ : '从 ChatLuna 同步的视觉模型',
360
698
  parameters: {
361
699
  base_url: textOf(baseUrl, URL_MAX),
362
700
  api_key: typeof apiKey === 'string' ? apiKey : '',
@@ -368,6 +706,29 @@ export function buildModelCreateBody({
368
706
  body.parameters.embedding_parameters = { dimension }
369
707
  }
370
708
  if (supportsVision || role === 'vlm') body.parameters.supports_vision = true
709
+ // 保留 ChatLuna 的能力元数据:WeKnora 模型响应从 parameters.spec 重建
710
+ // input/context_window/max_output_tokens/reasoning,否则导入后能力全丢。
711
+ const ctxWindow = safePositiveInt(contextWindow)
712
+ const outputTokens = safePositiveInt(maxOutputTokens)
713
+ if (ctxWindow !== null) {
714
+ body.parameters.context_window = ctxWindow
715
+ body.parameters.spec = { ...(body.parameters.spec ?? {}), context_window: ctxWindow }
716
+ }
717
+ if (outputTokens !== null) {
718
+ body.parameters.max_output_tokens = outputTokens
719
+ body.parameters.spec = { ...(body.parameters.spec ?? {}), max_output_tokens: outputTokens }
720
+ }
721
+ if (chat || role === 'vlm') {
722
+ const inputs = modelInputs(capabilities)
723
+ const reasoning = (Array.isArray(capabilities) ? capabilities : []).some(
724
+ (item) => typeof item === 'string' && item.toLowerCase() === 'reasoning'
725
+ )
726
+ body.parameters.spec = {
727
+ ...(body.parameters.spec ?? {}),
728
+ input: inputs,
729
+ ...(reasoning ? { reasoning: true } : {})
730
+ }
731
+ }
371
732
  return body
372
733
  }
373
734
 
@@ -379,8 +740,11 @@ export function buildModelCreateBody({
379
740
  * fetchImpl?: typeof fetch,
380
741
  * timeoutMs?: number,
381
742
  * logger?: { warn?: Function, error?: Function },
382
- * onChange?: () => void
743
+ * onChange?: () => void,
744
+ * bootstrapFile?: string,
745
+ * defaultKbId?: string
383
746
  * }} options
747
+ * `bootstrapFile` 指向 <dataDir>/bootstrap.json;`defaultKbId` 可覆盖从 bootstrap 读取的默认知识库。
384
748
  */
385
749
  export function createModelBridge(options = {}) {
386
750
  const ctx = options.ctx
@@ -394,6 +758,12 @@ export function createModelBridge(options = {}) {
394
758
  Number.isFinite(Number(options.timeoutMs)) && Number(options.timeoutMs) > 0
395
759
  ? Math.trunc(Number(options.timeoutMs))
396
760
  : DEFAULT_TIMEOUT_MS
761
+ const bootstrapFile =
762
+ typeof options.bootstrapFile === 'string' && options.bootstrapFile.trim() !== ''
763
+ ? options.bootstrapFile.trim()
764
+ : ''
765
+ const configuredKbId =
766
+ typeof options.defaultKbId === 'string' ? options.defaultKbId.trim() : ''
397
767
 
398
768
  const entries = () => {
399
769
  try {
@@ -469,7 +839,7 @@ export function createModelBridge(options = {}) {
469
839
  throw new ModelBridgeError('MODEL_NOT_FOUND', 'ChatLuna 中找不到该模型配置')
470
840
  }
471
841
  if (found.baseUrl === '') {
472
- throw new ModelBridgeError('MODEL_NOT_FOUND', '该模型路由缺少 baseURL,无法复制')
842
+ throw new ModelBridgeError('MODEL_NOT_FOUND', '该模型路由缺少 baseURL,无法同步')
473
843
  }
474
844
 
475
845
  let materializedConfig
@@ -504,6 +874,9 @@ export function createModelBridge(options = {}) {
504
874
  displayName: found.displayName,
505
875
  dimension: found.dimension,
506
876
  supportsVision: found.supportsVision,
877
+ capabilities: found.capabilities,
878
+ contextWindow: found.contextWindow,
879
+ maxOutputTokens: found.maxOutputTokens,
507
880
  protocolHint: found.protocolHint
508
881
  })
509
882
 
@@ -513,7 +886,7 @@ export function createModelBridge(options = {}) {
513
886
  } catch (error) {
514
887
  throw new ModelBridgeError(
515
888
  'IMPORT_FAILED',
516
- sanitizeMessage(`复制模型失败:${errorMessage(error)}`, secrets)
889
+ sanitizeMessage(`同步模型失败:${errorMessage(error)}`, secrets)
517
890
  )
518
891
  }
519
892
  if (!response.res.ok) {
@@ -521,13 +894,13 @@ export function createModelBridge(options = {}) {
521
894
  response.res.status === 409 ? 'CONFLICT' : response.res.status >= 500 ? 'IMPORT_FAILED' : 'INVALID_ARGUMENT'
522
895
  throw new ModelBridgeError(
523
896
  code,
524
- sanitizeMessage(`复制模型失败:HTTP ${response.res.status} ${clip(response.text, 160)}`, secrets)
897
+ sanitizeMessage(`同步模型失败:HTTP ${response.res.status} ${clip(response.text, 160)}`, secrets)
525
898
  )
526
899
  }
527
900
  const payload = response.json?.data ?? response.json ?? {}
528
901
  const id = payload?.id ?? payload?.model_id ?? response.json?.id
529
902
  if (id === undefined || id === null || String(id).trim() === '') {
530
- throw new ModelBridgeError('IMPORT_FAILED', '复制模型失败:WeKnora 未返回模型 id')
903
+ throw new ModelBridgeError('IMPORT_FAILED', '同步模型失败:WeKnora 未返回模型 id')
531
904
  }
532
905
  const declaredDimension = Number(payload?.parameters?.embedding_parameters?.dimension ?? payload?.dimension)
533
906
  const result = {
@@ -577,6 +950,13 @@ export function createModelBridge(options = {}) {
577
950
  if (source !== '') item.source = source
578
951
  const status = textOf(raw.status, CAPABILITY_MAX)
579
952
  if (status !== '') item.status = status
953
+ const displayName = textOf(raw.display_name ?? raw.displayName, NAME_MAX)
954
+ if (displayName !== '') item.displayName = displayName
955
+ const baseUrl = textOf(
956
+ raw.parameters?.base_url ?? raw.base_url ?? raw.baseUrl,
957
+ URL_MAX
958
+ )
959
+ if (baseUrl !== '') item.baseUrl = baseUrl
580
960
  if (typeof raw.is_default === 'boolean') item.is_default = raw.is_default
581
961
  out.push(item)
582
962
  if (out.length >= MODELS_MAX) break
@@ -588,5 +968,105 @@ export function createModelBridge(options = {}) {
588
968
  }
589
969
  }
590
970
 
591
- return { listChatlunaModels, importChatlunaModel, listWeKnoraModels }
971
+ const readBootstrap = async () => {
972
+ if (bootstrapFile === '') return null
973
+ try {
974
+ const raw = await readFile(bootstrapFile, 'utf8')
975
+ const parsed = JSON.parse(raw)
976
+ return isPlainObject(parsed) ? parsed : null
977
+ } catch {
978
+ return null
979
+ }
980
+ }
981
+
982
+ const getDefaultKb = async () => {
983
+ const token = await tokenOf()
984
+ const { res, json } = await request('GET', '/api/v1/knowledge-bases', { token })
985
+ if (!res.ok) {
986
+ throw new ModelBridgeError('IMPORT_FAILED', `读取默认知识库失败:HTTP ${res.status}`)
987
+ }
988
+ const list = parseList(json).filter((item) => isPlainObject(item) && item.id !== undefined)
989
+ const persisted = await readBootstrap()
990
+ const wanted = configuredKbId !== '' ? configuredKbId : textOf(persisted?.kbId, ID_MAX)
991
+ let kb = null
992
+ if (wanted !== '') {
993
+ kb = list.find((item) => String(item.id) === wanted) ?? null
994
+ }
995
+ if (kb === null) kb = list[0] ?? null
996
+ if (kb === null) return null
997
+ return {
998
+ id: textOf(kb.id, ID_MAX),
999
+ name: textOf(kb.name, NAME_MAX),
1000
+ embeddingModelId: textOf(kb.embedding_model_id ?? kb.embeddingModelId, ID_MAX),
1001
+ summaryModelId: textOf(kb.summary_model_id ?? kb.summaryModelId, ID_MAX)
1002
+ }
1003
+ }
1004
+
1005
+ const bindDefaultKbEmbedding = async (kbId, modelId, summaryModelId = '') => {
1006
+ const token = await tokenOf()
1007
+ // 走 PATCH:UpdateKnowledgeBase(PUT)要求 name 必填且不接收 embedding_model_id;
1008
+ // PatchKnowledgeBase 明确支持只改 embedding_model_id / summary_model_id。
1009
+ const body = { embedding_model_id: modelId }
1010
+ if (summaryModelId !== '') body.summary_model_id = summaryModelId
1011
+ const { res, text } = await request(
1012
+ 'PATCH',
1013
+ `/api/v1/knowledge-bases/${encodeURIComponent(kbId)}`,
1014
+ { token, body }
1015
+ )
1016
+ if (!res.ok) {
1017
+ return { ok: false, reason: `绑定默认知识库失败:HTTP ${res.status} ${clip(text, 160)}` }
1018
+ }
1019
+ return { ok: true }
1020
+ }
1021
+
1022
+ const persistBootstrapEmbedding = async (modelId) => {
1023
+ if (bootstrapFile === '') {
1024
+ return { ok: false, reason: '未配置 bootstrap.json 路径,未写入' }
1025
+ }
1026
+ let previous
1027
+ try {
1028
+ const raw = await readFile(bootstrapFile, 'utf8')
1029
+ previous = JSON.parse(raw)
1030
+ if (!isPlainObject(previous)) throw new Error('内容不是 JSON 对象')
1031
+ } catch (error) {
1032
+ return {
1033
+ ok: false,
1034
+ reason: `bootstrap.json 未更新:${sanitizeMessage(errorMessage(error))}`
1035
+ }
1036
+ }
1037
+ const record = {
1038
+ ...previous,
1039
+ embeddingModelId: modelId,
1040
+ updatedAt: new Date().toISOString()
1041
+ }
1042
+ try {
1043
+ await writeFile(bootstrapFile, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 })
1044
+ } catch (error) {
1045
+ return {
1046
+ ok: false,
1047
+ reason: `bootstrap.json 未更新:${sanitizeMessage(errorMessage(error))}`
1048
+ }
1049
+ }
1050
+ return { ok: true }
1051
+ }
1052
+
1053
+ const syncChatlunaModelsInBridge = (input) =>
1054
+ syncChatlunaModels(input, {
1055
+ importChatlunaModel,
1056
+ listWeKnoraModels,
1057
+ findModel: (item) => findChatlunaModel(entries(), item),
1058
+ logger,
1059
+ bindKb: {
1060
+ getDefaultKb,
1061
+ bindEmbedding: bindDefaultKbEmbedding,
1062
+ persistEmbedding: persistBootstrapEmbedding
1063
+ }
1064
+ })
1065
+
1066
+ return {
1067
+ listChatlunaModels,
1068
+ importChatlunaModel,
1069
+ listWeKnoraModels,
1070
+ syncChatlunaModels: syncChatlunaModelsInBridge
1071
+ }
592
1072
  }