chatluna-plugin-kb 0.1.1 → 0.1.3

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/README.md CHANGED
@@ -1,20 +1,179 @@
1
- # chatluna-plugin-kb
1
+ # chatluna-kb
2
2
 
3
- ChatLuna v2 knowledge-base plugin: WeKnora REST tools, managed `weknora-lite` engine, and WebUI install wizard.
3
+ ChatLuna v2 的知识库接入插件:通过 WeKnora REST API 提供检索与入库能力,并托管一个仅监听
4
+ `127.0.0.1` 的 weknora-lite 子进程。不依赖 MCP,所有能力以 3 个工具暴露。
4
5
 
5
- ## Install
6
+ ## 功能
7
+
8
+ - 知识库检索:列库、列文档、混合/语义/关键词检索、按标题或分块读取。
9
+ - 内容入库:附件/本地文档、Markdown 文本、网页或文件直链。
10
+ - 文档维护:重新解析、删除(群聊禁止删除)。
11
+ - WebUI:引擎状态、启动/停止/重启、安装向导、权限分流规则编辑。
12
+ - 同源反代 `/kb-proxy/*`,可直接在 WebUI 内嵌 WeKnora 前端。
13
+
14
+ ## 工具与权限
15
+
16
+ | 工具 | 默认加载 | effect | 能力 |
17
+ | --- | --- | --- | --- |
18
+ | `kb_read` | 常驻 | read | `list_kbs` / `list_docs` / `search` / `toc` / `read` |
19
+ | `kb_write` | 按需 | write | `ingest_file` / `ingest_text` / `ingest_url` |
20
+ | `kb_manage` | 按需 | write | `reparse` / `delete` |
21
+
22
+ 兼容别名 `weknora_read` / `weknora_write` / `weknora_manage` 只做参数转发,权限规则与主工具完全一致。
23
+
24
+ 权限按会话分流,规则字段:`match`(scene/platform/guildId/userId/minLevel)、`defaultKb`、
25
+ `readableKbs`、`writableKbs`、`manageableKbs`(`*` 表示全部)。规则存储在
26
+ `<dataDir>/rules.json`(唯一真源,0600);文件缺失或损坏时回退 `chatluna.yml` 的 `rules`。
27
+ 工具每次调用都会把知识库名称/ID 归一到当前可见目录,越权直接抛出 `PermissionError`;
28
+ `list_kbs` 只返回白名单内可见的库。
29
+
30
+ ## 双模式
31
+
32
+ - **managed-lite(默认)**:插件托管 `weknora-lite` 子进程,只监听 `127.0.0.1:<port>`(默认 18891)。
33
+ 启动异步执行,失败只写入状态、不阻塞插件加载;崩溃带指数退避重启。
34
+ - **external**:连接已有 WeKnora 服务(`baseUrl`,默认 `http://127.0.0.1:8891`)。
35
+ 不 spawn 任何进程,也不注册安装路由。`/kb-proxy` 与规则编辑仍可用。
36
+ - **systemd**:由独立 systemd 单元托管(`systemdUnit`,必须为 `*.service`)。插件只做
37
+ `systemctl`/`journalctl` 白名单调用与健康检查,绝不 spawn 或 start/stop 单元。
38
+ 已显式配置 `mode: systemd` 的实例行为不变。
39
+
40
+ `mode` 的 schema 默认值是 `managed-lite`;已有配置里显式写出的 `mode` 永远优先。
41
+
42
+ managed-lite 需要引擎二进制已安装(见下方向导)。未安装时不会启动子进程,状态提示
43
+ “引擎未安装:请在知识库页面完成安装向导”。
44
+
45
+ ## WebUI 安装(4 步)
46
+
47
+ 1. **模式选择**:选择 managed-lite(托管)或 external(连接已有服务)。
48
+ 2. **架构检测与安装包**:向导调用 `/kb-admin/install/status` 与 `detect`,展示平台/架构、
49
+ 已安装版本与校验和,以及 `tesseract`/`pdftoppm`/`tessdata` 探测结果。可自动下载当前平台
50
+ 的 latest 发布包(读 `release.json`,服务端校验 sha256 与 size 后解包)、手动填下载 URL,
51
+ 或上传离线包。
52
+ 3. **Embedding**:复用 ChatLuna 的 Embedding(`baseUrl` / `model` / API key),向导测试
53
+ `POST <baseUrl>/embeddings`(15 秒超时),返回维度与耗时;保存后写入
54
+ `<dataDir>/embedding.json`,重启生效。
55
+ 4. **一键拉起**:安装完成后可直接启动引擎,首次启动自动完成 bootstrap(创建 API key、
56
+ 默认知识库、Embedding 模型)并进入就绪状态。
57
+
58
+ ### 发布清单自动下载
59
+
60
+ - 默认清单地址:
61
+ `https://github.com/yabo083/weknora-lite-kb/releases/latest/download/release.json`
62
+ - 配置项 `releaseManifestUrl` 可覆盖;`installMirrors` 接受带 `{url}` 占位符的镜像,
63
+ 清单与安装包都会按“主地址 → 镜像”顺序回退。
64
+ - 清单形状:`{version, minPluginVersion, platforms: {"linux-amd64": {url, sha256, size}, ...}}`。
65
+ 安装器按 `process.platform`/`arch` 映射到 `linux-amd64` / `linux-arm64`,条目缺失、
66
+ 地址非 http(s)、sha256/size 非法或下载后不匹配都会明确报错,绝不跳过校验。
67
+ - 发布包内嵌 `tessdata/`(与二进制同级)会原样解出;安装器只要求
68
+ `weknora-lite`、`web/index.html`、`config/config.yaml`,额外目录不影响安装。
69
+ - `pluginVersion` 可选;配置后若低于清单 `minPluginVersion` 会拒绝自动安装。
70
+
71
+ ### `kb.detect` 字段
72
+
73
+ 只读探测,不安装、不启动;外部命令均有 2 秒超时,结果 60 秒缓存:
74
+
75
+ ```json
76
+ {
77
+ "platform": "linux",
78
+ "arch": "x64",
79
+ "platformKey": "linux-amd64",
80
+ "installed": true,
81
+ "installedVersion": "0.9.0",
82
+ "release": {"ok": true, "available": true, "version": "0.9.0", "url": "https://…"},
83
+ "tesseractFound": true,
84
+ "pdftoppmFound": true,
85
+ "tessdataDir": "<dataDir>/weknora-lite/tessdata",
86
+ "tessdataReady": true,
87
+ "ocr": {"ready": true, "engine": "tesseract", "tessdataDir": "…", "tesseractFound": true, "pdftoppmFound": true}
88
+ }
89
+ ```
90
+
91
+ 同一组平台/OCR 字段也会出现在 `kb.status` 快照中(`release` 只给清单 URL,不发网络请求)。
92
+
93
+ 安装路由(需 WebUI 登录,见安全边界):
94
+
95
+ - `POST /kb-admin/install/upload`:原始 `tar.gz` 流上传,支持请求头 `x-sha256`(64 位十六进制)
96
+ 与 `x-filename`;默认上限 512 MB,超限 413,空体 400,校验失败 409。
97
+ - `GET /kb-admin/install/status`:返回安装器状态;前端据此展示进度。
98
+
99
+ ## 离线包上传
100
+
101
+ 在向导第 2 步选择“上传离线包”,选择 `weknora-lite-kb-linux-amd64.tar.gz`。浏览器以流方式
102
+ 直接上传,服务端按块计数、不整体驻留内存;可同时提供 sha256 由服务端强制校验。安装目标为
103
+ `<dataDir>/weknora-lite/`,包内根目录 `weknora-lite-kb/` 会被展开到该目录。
104
+
105
+ 同一个包也可用 `kb.install.path` 从服务器本地绝对路径安装(自动下载失败/无外网时使用)。
106
+ 包内 `tessdata/` 与二进制同级,安装后直接可用;额外目录(`migrations/` 等)会被保留。
107
+
108
+ ## 目录布局
109
+
110
+ 默认 `<dataDir>` 为 `/root/chatluna/data/chatluna-kb`:
6
111
 
7
112
  ```
8
- npm install chatluna-plugin-kb
113
+ <dataDir>/
114
+ ├── weknora-lite/ # 安装产物(二进制、web/、config/)
115
+ │ └── weknora-lite
116
+ ├── weknora.db # SQLite 主库
117
+ ├── files/ # 本地文件存储
118
+ ├── rules.json # 权限分流规则(0600)
119
+ ├── embedding.json # 向导保存的 Embedding 配置(0600)
120
+ ├── embedding.key # 向导填写的 Embedding API key(0600)
121
+ ├── setup-token # Lite 初始化 token(0600)
122
+ ├── jwt-secret # 会话签名密钥(0600)
123
+ └── system-aes-key # 系统加密密钥(0600)
9
124
  ```
10
125
 
11
- The plugin defaults to `managed-lite`: it downloads the matching engine package from the release
12
- manifest (`yabo083/weknora-lite-kb`), verifies SHA-256, and manages the process from ChatLuna.
13
- `external` and `systemd` modes remain available for advanced deployments.
126
+ 所有凭据文件权限固定为 `0600`;配置里只出现文件路径,不出现密钥明文。
127
+
128
+ ## 发布与安装(npm)
129
+
130
+ 包名 `chatluna-plugin-kb`,`type: module`,入口 `index.mjs`,`files` 只包含
131
+ `index.mjs`、`src/**/*.mjs`、`web/**` 与 `README.md`(测试与部署产物不会进包)。
132
+ `@chatluna/*` 声明为 peerDependencies,由 ChatLuna 运行时提供;`engines.node >= 24`。
133
+
134
+ ```bash
135
+ npm pack # 本地打包检查内容
136
+ npm publish # 发布(需要 npm 账号与包名权限)
137
+ ```
138
+
139
+ ChatLuna 侧把插件项 `name` 指向本包入口(`index.mjs`)即可;继续用 `file://` 路径加载
140
+ 不受影响。`package.json` 的 `exports` 同时暴露 `web/client.js`,WebUI 静态资源按包根目录
141
+ 解析。
142
+
143
+ 配置里不出现任何密钥:setup token、JWT secret、AES key、API key 都只存在于
144
+ `<dataDir>` 下的 `0600` 文件或进程环境变量中。
145
+
146
+ ## 从 weknora-kb / 外部全量迁移
147
+
148
+ 1. **停旧服务**,备份旧数据目录(至少包含数据库、`files/`、凭据文件)。
149
+ 2. 选择迁移方式:
150
+ - 继续使用已有服务:`mode: external`,把 `baseUrl` 指向它即可,无需搬迁数据。
151
+ - 切到托管:安装引擎后,将旧库文件复制到 `<dataDir>/weknora.db`,旧文件目录复制到
152
+ `<dataDir>/files/`;保留原 `setup-token`、`jwt-secret`、`system-aes-key`(若旧版本使用
153
+ 相同机制),否则首次启动会生成新密钥,旧会话失效但不影响数据。
154
+ 3. 若旧版使用不同的数据库驱动或存储后端,先在旧服务导出/重建知识库,再通过 `kb_write`
155
+ 重新入库;不要直接混用不兼容的数据库文件。
156
+ 4. 迁移后打开 WebUI 检查引擎状态,跑一次检索与一次入库验证读写链路。
157
+
158
+ ## 故障排查
14
159
 
15
- ## Publish (OIDC trusted publishing)
160
+ - **端口 18891 被占用**:托管模式拒绝启动且不会杀掉现有进程。用
161
+ `ss -ltnp | grep 18891` 找到占用者;是旧实例就停掉,或修改配置 `engine.port`。
162
+ - **sha256 校验失败**:确认安装包完整(与 `.sha256` 同目录比对
163
+ `sha256sum -c weknora-lite-kb-linux-amd64.tar.gz.sha256`)。重新下载而不是跳过校验。
164
+ - **Embedding 测试失败**:检查 `baseUrl` 是否能从本机访问、模型名是否存在、API key 文件是否
165
+ 可读;错误信息已脱敏,不会回显 key。测试通过但启动后仍报错时,确认保存的是同一组配置,
166
+ 并重启引擎使其生效。
167
+ - **引擎启动失败**:查看 WebUI 引擎页日志尾部(有界 50 行)与 `lastError`;常见原因是未安装、
168
+ 端口占用、数据目录不可写。
169
+ - **安装后仍提示未安装**:确认二进制位于 `<dataDir>/weknora-lite/weknora-lite` 且可执行。
16
170
 
17
- Configure this repository and workflow (`publish.yml`) as the npm trusted publisher, then run the
18
- workflow manually. The workflow uses `npm publish --provenance --access public` with `id-token: write`.
171
+ ## 安全边界
19
172
 
20
- Local dry run: `npm pack && npm publish --dry-run`.
173
+ - weknora-lite 只绑定 `127.0.0.1`,不对外暴露端口。
174
+ - `/kb-proxy/*` 与 `/kb-admin/*` 都要求 ChatLuna WebUI 登录:`chatluna_session` cookie 或
175
+ 有效 bearer access token;未登录请求在读取请求体之前就返回 401。
176
+ - 管理动作(启动/停止/重启/保存规则/安装)额外要求管理员权限等级。
177
+ - setup token、JWT secret、AES key、API key 只存在于 `0600` 文件或进程环境变量中,
178
+ 不写入 `chatluna.yml`、不打印到日志、不出现在错误响应里。
179
+ - 上传流有字节上限,日志行有长度上限,规则条数与序列化大小均有上限。
package/index.mjs CHANGED
@@ -1208,6 +1208,115 @@ export function apply(ctx, config) {
1208
1208
  return list
1209
1209
  }
1210
1210
 
1211
+ // 规则编辑器的候选目录:只读、脱敏、有上限。任何平台/引擎失败都降级为空数组,
1212
+ // 前端始终保留手动输入兜底,绝不能因为目录拉取失败而卡住规则编辑。
1213
+ async function readRuleOptions() {
1214
+ const limit = 200
1215
+ const bots = (() => {
1216
+ try {
1217
+ const satori = typeof ctx.get === 'function' ? ctx.get('satori') : undefined
1218
+ const list = satori?.bots ?? ctx.bots
1219
+ return list ? [...list].filter((bot) => bot?.hidden !== true).slice(0, 20) : []
1220
+ } catch {
1221
+ return []
1222
+ }
1223
+ })()
1224
+ const platformOf = (bot) =>
1225
+ String(bot?.platform ?? bot?.adapter?.platform ?? '').trim().slice(0, 80)
1226
+ const platforms = []
1227
+ const seenPlatforms = new Set()
1228
+ for (const bot of bots) {
1229
+ const platform = platformOf(bot)
1230
+ if (platform === '' || seenPlatforms.has(platform)) continue
1231
+ seenPlatforms.add(platform)
1232
+ platforms.push(platform)
1233
+ }
1234
+
1235
+ const collect = async (method) => {
1236
+ const out = []
1237
+ const seen = new Set()
1238
+ for (const bot of bots) {
1239
+ if (typeof bot?.[method] !== 'function') continue
1240
+ let list
1241
+ try {
1242
+ const task = Promise.resolve()
1243
+ .then(() => bot[method]())
1244
+ .catch(() => [])
1245
+ list = await Promise.race([
1246
+ task,
1247
+ new Promise((resolve) => setTimeout(() => resolve([]), 1500))
1248
+ ])
1249
+ } catch {
1250
+ continue
1251
+ }
1252
+ const rows = Array.isArray(list) ? list : Array.isArray(list?.data) ? list.data : []
1253
+ const platform = platformOf(bot)
1254
+ for (const item of rows.slice(0, limit)) {
1255
+ const id = String(item?.id ?? item?.guildId ?? item?.userId ?? '').trim()
1256
+ if (id === '') continue
1257
+ const key = `${platform}\u0000${id}`
1258
+ if (seen.has(key)) continue
1259
+ seen.add(key)
1260
+ const name = String(item?.name ?? item?.nick ?? item?.username ?? '').trim().slice(0, 120)
1261
+ out.push(name === '' ? { platform, id } : { platform, id, name })
1262
+ if (out.length >= limit) return out
1263
+ }
1264
+ }
1265
+ return out
1266
+ }
1267
+
1268
+ const [botGuilds, botUsers] = await Promise.all([
1269
+ collect('getGuildList'),
1270
+ collect('getFriendList')
1271
+ ])
1272
+ // routing.peers 记录了历史会话里的群/用户(含 QQ openid 映射后的名称);
1273
+ // 适配器不提供 getGuildList/getFriendList 时,这是唯一可靠的候选来源。
1274
+ const peersOf = async (kind) => {
1275
+ try {
1276
+ const service = typeof ctx.get === 'function' ? ctx.get('routing') : undefined
1277
+ if (typeof service?.peers?.search !== 'function') return []
1278
+ return await service.peers.search({ kind, limit })
1279
+ } catch {
1280
+ return []
1281
+ }
1282
+ }
1283
+ const mergePeers = (target, rows) => {
1284
+ const seen = new Set(target.map((item) => `${item.platform}\u0000${item.id}`))
1285
+ for (const row of Array.isArray(rows) ? rows : []) {
1286
+ const platform = String(row?.platform ?? '').trim().slice(0, 80)
1287
+ const id = String(row?.id ?? '').trim()
1288
+ if (id === '' || seen.has(`${platform}\u0000${id}`)) continue
1289
+ seen.add(`${platform}\u0000${id}`)
1290
+ const name = String(row?.name ?? '').trim().slice(0, 120)
1291
+ target.push(name === '' ? { platform, id } : { platform, id, name })
1292
+ if (target.length >= limit) break
1293
+ }
1294
+ return target
1295
+ }
1296
+ const [guildPeers, userPeers] = await Promise.all([peersOf('guild'), peersOf('user')])
1297
+ const guilds = mergePeers(botGuilds, guildPeers)
1298
+ const users = mergePeers(botUsers, userPeers)
1299
+ for (const item of [...guilds, ...users]) {
1300
+ const platform = String(item?.platform ?? '').trim()
1301
+ if (platform !== '' && !seenPlatforms.has(platform)) {
1302
+ seenPlatforms.add(platform)
1303
+ platforms.push(platform)
1304
+ }
1305
+ }
1306
+ let kbs = []
1307
+ try {
1308
+ const list = await catalog()
1309
+ kbs = list.slice(0, limit).map((kb) => {
1310
+ const id = String(kb?.id ?? '').trim()
1311
+ const name = String(kb?.name ?? '').trim().slice(0, 120)
1312
+ return name === '' ? { id } : { id, name }
1313
+ }).filter((kb) => kb.id !== '')
1314
+ } catch {
1315
+ kbs = []
1316
+ }
1317
+ return { platforms, guilds, users, kbs }
1318
+ }
1319
+
1211
1320
  async function scopeFor(call) {
1212
1321
  await waitReady()
1213
1322
  const scope = await resolveScope(ctx, scopeConfig(), call)
@@ -1574,7 +1683,8 @@ export function apply(ctx, config) {
1574
1683
  // 模型复制:列表已脱敏;导入返回 WeKnora 模型 id/维度,不含密钥。
1575
1684
  listChatlunaModels,
1576
1685
  importChatlunaModel,
1577
- listWeKnoraModels
1686
+ listWeKnoraModels,
1687
+ ruleOptions: readRuleOptions
1578
1688
  })
1579
1689
  } catch (err) {
1580
1690
  logError('webui', err)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chatluna-plugin-kb",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
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",
@@ -148,7 +148,7 @@ async function findEmbeddingModel(http, apiKey, name) {
148
148
  listOf(res.json).find(
149
149
  (model) =>
150
150
  String(model?.name ?? '') === wanted &&
151
- (model?.type === undefined || String(model.type) === 'embedding')
151
+ (model?.type === undefined || String(model.type).toLowerCase() === 'embedding')
152
152
  ) ?? null
153
153
  )
154
154
  } catch {
@@ -182,7 +182,7 @@ async function createEmbeddingModel(http, apiKey, embedding, embeddingKey, logge
182
182
  if (!embedding?.baseUrl) throw new Error('embedding.baseUrl 未配置')
183
183
  const body = {
184
184
  name: embedding.model,
185
- type: 'embedding',
185
+ type: 'Embedding',
186
186
  source: 'remote',
187
187
  display_name: embedding.displayName ?? embedding.model,
188
188
  description: embedding.description ?? 'ChatLuna 自动配置的 Embedding 模型',
@@ -28,7 +28,7 @@ const VALUE_DEPTH_MAX = 8
28
28
  const VALUE_NODES_MAX = 2000
29
29
  const VALUE_ARRAY_MAX = 200
30
30
 
31
- const IMPORT_ROLES = new Set(['embedding', 'vlm'])
31
+ const IMPORT_ROLES = new Set(['embedding', 'chat', 'vlm', 'rerank'])
32
32
  const CONFLICT_CODES = new Set(['CONFLICT', 'ALREADY_EXISTS', 'DUPLICATE', 'MODEL_EXISTS', 'EXISTS'])
33
33
  const VALIDATION_CODES = new Set([
34
34
  'INVALID_ARGUMENT',
@@ -123,6 +123,8 @@ function sanitizeModelEntry(entry) {
123
123
  if (isNonEmptyString(entry.modelId)) out.modelId = clip(entry.modelId, ID_MAX)
124
124
  if (isNonEmptyString(entry.type)) out.type = clip(entry.type, CAPABILITY_MAX)
125
125
  if (isNonEmptyString(entry.baseUrl)) out.baseUrl = clip(entry.baseUrl, URL_MAX)
126
+ if (entry.supportsVision === true) out.supportsVision = true
127
+ if (isNonEmptyString(entry.protocolHint)) out.protocolHint = clip(entry.protocolHint, CAPABILITY_MAX)
126
128
  if (typeof entry.dimension === 'number' && Number.isSafeInteger(entry.dimension) && entry.dimension > 0) {
127
129
  out.dimension = entry.dimension
128
130
  }
@@ -288,7 +290,7 @@ function validateImport(body) {
288
290
  throw new ModelRouteError('INVALID_ARGUMENT', '请求体必须是 JSON 对象')
289
291
  }
290
292
  if (typeof body.role !== 'string' || !IMPORT_ROLES.has(body.role)) {
291
- throw new ModelRouteError('INVALID_ARGUMENT', 'role 必须是 embedding 或 vlm')
293
+ throw new ModelRouteError('INVALID_ARGUMENT', 'role 必须是 embedding、chat、vlm 或 rerank')
292
294
  }
293
295
  return {
294
296
  role: body.role,
@@ -320,7 +322,7 @@ function disposeOf(handle) {
320
322
  * @param {string} [options.prefix='/kb-admin']
321
323
  * @param {(ctx: object, req: object) => boolean | Promise<boolean>} options.authorize
322
324
  * @param {() => unknown | Promise<unknown>} options.listModels
323
- * @param {(input: { role: 'embedding' | 'vlm', providerId: string, modelId: string }) => unknown | Promise<unknown>} options.importModel
325
+ * @param {(input: { role: 'embedding' | 'chat' | 'vlm' | 'rerank', providerId: string, modelId: string }) => unknown | Promise<unknown>} options.importModel
324
326
  * @param {() => unknown | Promise<unknown>} [options.listWeKnoraModels]
325
327
  * @param {object} [options.logger]
326
328
  * @returns {() => void} dispose
@@ -21,7 +21,7 @@ const ROUTE_MODELS_MAX = 512
21
21
  const MESSAGE_MAX = 200
22
22
  const DEFAULT_TIMEOUT_MS = 15_000
23
23
 
24
- const IMPORT_ROLES = new Set(['embedding', 'vlm'])
24
+ const IMPORT_ROLES = new Set(['embedding', 'chat', 'vlm', 'rerank'])
25
25
 
26
26
  export class ModelBridgeError extends Error {
27
27
  constructor(code, message) {
@@ -71,7 +71,7 @@ function validateImportInput(input) {
71
71
  throw new ModelBridgeError('INVALID_ARGUMENT', '模型导入参数必须是对象')
72
72
  }
73
73
  if (typeof input.role !== 'string' || !IMPORT_ROLES.has(input.role)) {
74
- throw new ModelBridgeError('INVALID_ARGUMENT', 'role 必须是 embedding 或 vlm')
74
+ throw new ModelBridgeError('INVALID_ARGUMENT', 'role 必须是 embedding、chat、vlm 或 rerank')
75
75
  }
76
76
  const providerId = textOf(input.providerId, ID_MAX)
77
77
  const modelId = textOf(input.modelId, ID_MAX)
@@ -105,17 +105,105 @@ function capabilitiesOf(model) {
105
105
  return out
106
106
  }
107
107
 
108
- /** embed* → embedding;vision/image/vlm → vlm;其余模型不进入复制清单。 */
109
- export function modelTypeOf(capabilities) {
108
+ const VISION_CAPABILITIES = new Set(['vision', 'vlm'])
109
+
110
+ function normalizedCapabilities(capabilities) {
110
111
  const list = Array.isArray(capabilities) ? capabilities : []
111
- const lower = list.map((item) => (typeof item === 'string' ? item.toLowerCase() : ''))
112
+ return list.map((item) => (typeof item === 'string' ? item.toLowerCase() : ''))
113
+ }
114
+
115
+ /**
116
+ * ChatLuna 能力 → 复制角色。能力是叠加的,不能按「看到 vision 就是 VLM」一刀切:
117
+ * - embed* → embedding
118
+ * - rerank* → rerank
119
+ * - 只有 draw(或 image* 且无 chat)→ 生图模型,不进知识库清单
120
+ * - chat → 对话(KnowledgeQA);同时有 vision 时附带 supportsVision
121
+ * - 仅 vision/vlm 且无 chat/draw → 纯视觉(VLLM)
122
+ */
123
+ export function modelTypeOf(capabilities) {
124
+ const lower = normalizedCapabilities(capabilities)
112
125
  if (lower.some((item) => item.startsWith('embed'))) return 'embedding'
113
- if (lower.some((item) => item === 'vision' || item === 'image' || item === 'vlm' || item.startsWith('image'))) {
114
- return 'vlm'
115
- }
126
+ if (lower.some((item) => item.startsWith('rerank'))) return 'rerank'
127
+ const hasChat = lower.some((item) => item === 'chat' || item === 'knowledgeqa')
128
+ const hasDraw = lower.some((item) => item === 'draw' || item.startsWith('image'))
129
+ if (hasDraw && !hasChat) return null
130
+ if (hasChat) return 'chat'
131
+ if (lower.some((item) => VISION_CAPABILITIES.has(item))) return 'vlm'
116
132
  return null
117
133
  }
118
134
 
135
+ /** 一个模型允许导入的角色;带视觉的对话模型可二选一。 */
136
+ export function modelRolesOf(capabilities) {
137
+ const type = modelTypeOf(capabilities)
138
+ if (type === null) return []
139
+ const lower = normalizedCapabilities(capabilities)
140
+ if (type === 'chat' && lower.some((item) => VISION_CAPABILITIES.has(item))) {
141
+ return ['chat', 'vlm']
142
+ }
143
+ return [type]
144
+ }
145
+
146
+ export function modelSupportsVision(capabilities) {
147
+ const lower = normalizedCapabilities(capabilities)
148
+ return lower.some((item) => VISION_CAPABILITIES.has(item))
149
+ }
150
+
151
+ /** 复合路由把端点按协议拆分;按模型角色选择能用的 baseUrl。 */
152
+ export function routeBaseUrlOf(route, role = '') {
153
+ if (route === null || typeof route !== 'object') return ''
154
+ const candidates =
155
+ role === 'rerank'
156
+ ? [route.rerank, route.baseURL, route.baseUrl, route.chat, route.responses]
157
+ : [route.baseURL, route.baseUrl, route.chat, route.responses]
158
+ for (const candidate of candidates) {
159
+ const value = textOf(candidate, URL_MAX)
160
+ if (value !== '') return value.replace(/\/+$/, '')
161
+ }
162
+ return ''
163
+ }
164
+
165
+ /**
166
+ * 从路由的 apiKey 池里选出该模型实际使用的一把 key。
167
+ * ChatLuna 的 `route.apiKey` 可能是逗号/空白分隔的多把 key(splitApiKeys 去重保序),
168
+ * `model.keys` 是这些 key 的下标数组;取第一个有效下标,否则回退第 0 把。
169
+ */
170
+ function splitApiKeys(value) {
171
+ if (typeof value !== 'string' || value === '') return []
172
+ const keys = []
173
+ const seen = new Set()
174
+ for (const part of value.split(/[\s,]+/)) {
175
+ if (part === '' || seen.has(part)) continue
176
+ seen.add(part)
177
+ keys.push(part)
178
+ }
179
+ return keys
180
+ }
181
+
182
+ export function selectRouteApiKey(routeApiKey, modelKeys) {
183
+ const keys = splitApiKeys(routeApiKey)
184
+ if (keys.length === 0) return ''
185
+ const indexes = Array.isArray(modelKeys) ? modelKeys : []
186
+ for (const index of indexes) {
187
+ if (!Number.isSafeInteger(index) || index < 0 || index >= keys.length) continue
188
+ return keys[index]
189
+ }
190
+ return keys[0]
191
+ }
192
+
193
+ function protocolHintOf(route, baseUrl) {
194
+ const pkg = textOf(route?.packageName, ID_MAX)
195
+ if (baseUrl === '') return undefined
196
+ if (pkg === '@ai-sdk/anthropic' && !/\/openai(?:\/|$)/i.test(baseUrl)) return 'anthropic'
197
+ if (
198
+ pkg === '@ai-sdk/google' &&
199
+ /generativelanguage\.googleapis\.com/i.test(baseUrl) &&
200
+ !/\/openai(?:\/|$)/i.test(baseUrl)
201
+ ) {
202
+ return 'google'
203
+ }
204
+ return undefined
205
+ }
206
+
119
207
  function dimensionOf(model) {
120
208
  const raw = model?.embedding?.dimension ?? model?.dimension
121
209
  const value = Number(raw)
@@ -149,7 +237,6 @@ export function collectChatlunaModels(entries) {
149
237
  for (const route of routesOf(entry)) {
150
238
  if (!isPlainObject(route)) continue
151
239
  const routeId = textOf(route.id, ID_MAX)
152
- const baseUrl = textOf(route.baseURL ?? route.baseUrl, URL_MAX)
153
240
  for (const model of modelsOf(route)) {
154
241
  if (!isPlainObject(model)) continue
155
242
  const modelId = textOf(model.id, ID_MAX)
@@ -160,7 +247,10 @@ export function collectChatlunaModels(entries) {
160
247
  const key = `${providerId}\u0000${routeId}\u0000${modelId}\u0000${type}`
161
248
  if (seen.has(key)) continue
162
249
  seen.add(key)
163
- out.push({
250
+ const baseUrl = routeBaseUrlOf(route, type)
251
+ const supportsVision = modelSupportsVision(capabilities)
252
+ const protocolHint = protocolHintOf(route, baseUrl)
253
+ const card = {
164
254
  providerId,
165
255
  providerLabel:
166
256
  textOf(entry.label, LABEL_MAX) || textOf(route.displayName, LABEL_MAX) || providerId,
@@ -170,7 +260,10 @@ export function collectChatlunaModels(entries) {
170
260
  baseUrl,
171
261
  dimension: dimensionOf(model),
172
262
  capabilities
173
- })
263
+ }
264
+ if (supportsVision) card.supportsVision = true
265
+ if (protocolHint !== undefined) card.protocolHint = protocolHint
266
+ out.push(card)
174
267
  if (out.length >= MODELS_MAX) return out
175
268
  }
176
269
  }
@@ -191,16 +284,17 @@ export function findChatlunaModel(entries, input) {
191
284
  for (const model of modelsOf(route)) {
192
285
  if (!isPlainObject(model) || textOf(model.id, ID_MAX) !== wanted.modelId) continue
193
286
  const capabilities = capabilitiesOf(model)
194
- const type = modelTypeOf(capabilities)
195
- if (type !== wanted.role) continue
287
+ if (!modelRolesOf(capabilities).includes(wanted.role)) continue
196
288
  return {
197
289
  input: wanted,
198
290
  entry,
199
291
  route,
200
292
  model,
201
- type,
202
- baseUrl: textOf(route.baseURL ?? route.baseUrl, URL_MAX),
293
+ type: wanted.role,
294
+ baseUrl: routeBaseUrlOf(route, wanted.role),
203
295
  dimension: dimensionOf(model),
296
+ supportsVision: modelSupportsVision(capabilities),
297
+ protocolHint: protocolHintOf(route, routeBaseUrlOf(route, wanted.role)),
204
298
  displayName:
205
299
  textOf(model.displayName, NAME_MAX) ||
206
300
  textOf(model.name, NAME_MAX) ||
@@ -231,25 +325,49 @@ function sessionTokenOf(login) {
231
325
  }
232
326
 
233
327
  /** POST body 构造单独导出,测试可以断言明文 key 只出现在 parameters.api_key。 */
234
- export function buildModelCreateBody({ role, baseUrl, apiKey, modelId, displayName, dimension }) {
328
+ export function buildModelCreateBody({
329
+ role,
330
+ baseUrl,
331
+ apiKey,
332
+ modelId,
333
+ displayName,
334
+ dimension,
335
+ supportsVision = false,
336
+ protocolHint = ''
337
+ }) {
235
338
  const embedding = role === 'embedding'
339
+ const chat = role === 'chat'
340
+ const rerank = role === 'rerank'
341
+ const provider = rerank
342
+ ? 'generic'
343
+ : protocolHint === 'anthropic'
344
+ ? 'anthropic'
345
+ : protocolHint === 'google'
346
+ ? 'gemini'
347
+ : 'openai'
236
348
  const body = {
237
349
  name: textOf(modelId, ID_MAX),
238
350
  display_name: textOf(displayName, NAME_MAX) || textOf(modelId, ID_MAX),
239
- type: embedding ? 'Embedding' : 'VLLM',
351
+ type: embedding ? 'Embedding' : chat ? 'KnowledgeQA' : rerank ? 'Rerank' : 'VLLM',
240
352
  source: 'remote',
241
- description: embedding ? '从 ChatLuna 复制的 Embedding 模型' : '从 ChatLuna 复制的视觉模型',
353
+ description: embedding
354
+ ? '从 ChatLuna 复制的 Embedding 模型'
355
+ : chat
356
+ ? '从 ChatLuna 复制的对话模型'
357
+ : rerank
358
+ ? '从 ChatLuna 复制的 ReRank 模型'
359
+ : '从 ChatLuna 复制的视觉模型',
242
360
  parameters: {
243
361
  base_url: textOf(baseUrl, URL_MAX),
244
362
  api_key: typeof apiKey === 'string' ? apiKey : '',
245
363
  interface_type: 'openai',
246
- provider: 'openai'
364
+ provider
247
365
  }
248
366
  }
249
367
  if (embedding && Number.isSafeInteger(dimension) && dimension > 0) {
250
368
  body.parameters.embedding_parameters = { dimension }
251
369
  }
252
- if (!embedding) body.supports_vision = true
370
+ if (supportsVision || role === 'vlm') body.parameters.supports_vision = true
253
371
  return body
254
372
  }
255
373
 
@@ -369,21 +487,24 @@ export function createModelBridge(options = {}) {
369
487
  const materializedRoute =
370
488
  (index >= 0 ? routes[index] : undefined) ??
371
489
  routes.find((route) => isPlainObject(route) && route.id === found.route.id)
372
- const apiKey = textOf(materializedRoute?.apiKey, 8192)
490
+ const keyPool = textOf(materializedRoute?.apiKey, 8192)
491
+ const apiKey = selectRouteApiKey(keyPool, found.model?.keys)
373
492
  if (apiKey === '') {
374
493
  throw new ModelBridgeError('MISSING_CREDENTIAL', '该模型配置缺少可用的 API Key')
375
494
  }
376
495
 
377
496
  const token = await tokenOf()
378
- // 密钥只进这一次请求体;后续错误与返回值都按 secrets 擦除。
379
- const secrets = [apiKey, token]
497
+ // 密钥只进这一次请求体;错误按整池、单 key 与 token 一起擦除。
498
+ const secrets = [keyPool, ...splitApiKeys(keyPool), apiKey, token]
380
499
  const body = buildModelCreateBody({
381
500
  role: found.type,
382
501
  baseUrl: found.baseUrl,
383
502
  apiKey,
384
503
  modelId: found.input.modelId,
385
504
  displayName: found.displayName,
386
- dimension: found.dimension
505
+ dimension: found.dimension,
506
+ supportsVision: found.supportsVision,
507
+ protocolHint: found.protocolHint
387
508
  })
388
509
 
389
510
  let response
@@ -419,6 +540,7 @@ export function createModelBridge(options = {}) {
419
540
  ? declaredDimension
420
541
  : found.dimension
421
542
  }
543
+ if (found.supportsVision === true) result.supportsVision = true
422
544
  if (onChange !== null) {
423
545
  try {
424
546
  onChange()