chatluna-plugin-kb 0.0.0-stage → 0.1.0

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 ADDED
@@ -0,0 +1,1587 @@
1
+ // chatluna-kb — WeKnora 知识库的 ChatLuna v2 接入点(REST,无 MCP)。
2
+ //
3
+ // 工具面(3 个工具,按风险分层):
4
+ // kb_read 常驻 deferred:false,effect=read list_kbs / list_docs / search / toc / read
5
+ // kb_write 按需 deferred:true, effect=write ingest_file / ingest_text / ingest_url
6
+ // kb_manage 按需 deferred:true, effect=write reparse / delete
7
+ // 兼容别名 weknora_read / weknora_write / weknora_manage 仅做 forward,永不直接执行。
8
+ //
9
+ // 权限不变量(改代码前先读):
10
+ // - 每次 run(input, call) 第一步 `scopeFor(call)`:先 resolveScope,再用 60s 缓存的库目录把
11
+ // 三类白名单归一到知识库 ID(WeKnora 文档 meta 的 knowledge_base_name 为空),后续访问均以该 scope 为准。
12
+ // - list_kbs 只返回 filterKbs 后的可见库,连不可见库的名称/数量都不暴露。
13
+ // - 传入的 knowledge_base 必须经 resolveKbTarget + assertKb;knowledge_id 必须先 getKnowledge
14
+ // 再按 meta.knowledge_base_id 做 assertKnowledge,杜绝跨库 IDOR 越权。
15
+ // - search 的 knowledge_ids 先经 assertKnowledgeIDs 整体校验,任一越权即整次拒绝。
16
+ // - 群聊 delete 一律先 canDelete 拒绝,再进行文档级鉴权。
17
+ // - PermissionError 原样向上抛,绝不吞掉或改写为普通错误。
18
+ // - 工具输出有界:list_kbs ≤50;其余上限由 client 层统一保证(search ≤30/≤700 字,read ≤8000 字)。
19
+ //
20
+ // 运行模式(Phase 3;schema 默认 managed-lite):
21
+ // - managed-lite(默认):插件托管 weknora-lite 子进程(仅 127.0.0.1:port)。启动在 ctx.effect 里异步执行,
22
+ // 不阻塞插件加载;任何启动/引导失败只写 runtime.lastError,绝不向 apply 抛出。
23
+ // - external:只连 config.baseUrl,绝不 spawn 子进程;WebUI 反代与写权限规则文件仍可用。
24
+ // - 客户端惰性构造(getClient):baseUrl / apiKeyFile / kbId 每次变化后重建,external 用配置值,
25
+ // managed 用 ensureBootstrap 的结果(baseUrl + 凭据文件 + 默认知识库)。
26
+ // - 规则单一真源:<dataDir>/rules.json 存在即优先,缺失/损坏回退 config.rules;saveRules 原子写 0600。
27
+ //
28
+ // 安装向导(Phase 4,仅 managed-lite):
29
+ // - 安装器 createInstaller 负责下载/校验/解包到 <dataDir>/weknora-lite;未安装时 bootEngine 不 spawn。
30
+ // - /kb-admin/* 提供上传与状态端点,鉴权与 /kb-proxy 一致(cookie 或 bearer)。
31
+ // - Embedding 由向导测试并写入 <dataDir>/embedding.json(0600,密钥单独 0600 文件),重启生效。
32
+ import { randomBytes } from 'node:crypto'
33
+ import { accessSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
34
+ import { access, chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises'
35
+ import { dirname, isAbsolute, join } from 'node:path'
36
+ import { Schema } from '@chatluna/schema'
37
+ import { defineTool } from '@chatluna/tool'
38
+ import { createClient } from './src/client.mjs'
39
+ import { createEngineManager } from './src/engine/manager.mjs'
40
+ import { createSystemdController } from './src/engine/systemd.mjs'
41
+ import { ensureBootstrap } from './src/engine/bootstrap.mjs'
42
+ import { registerKbProxy } from './src/proxy/webui-proxy.mjs'
43
+ import { registerKbWebUI } from './src/webui/server.mjs'
44
+ import { registerInstallRoutes } from './src/webui/install-routes.mjs'
45
+ import { registerModelRoutes } from './src/webui/model-routes.mjs'
46
+ import { createModelBridge } from './src/webui/models.mjs'
47
+ import { createInstaller, DEFAULT_RELEASE_MANIFEST_URL, platformInfo } from './src/engine/installer.mjs'
48
+ import { detectEnvironment } from './src/engine/runtime-probe.mjs'
49
+ import { resolveScope } from './src/policy/scope.mjs'
50
+ import {
51
+ denied,
52
+ filterKbs,
53
+ assertKb,
54
+ assertKnowledge,
55
+ assertKnowledgeIDs,
56
+ resolveKbTarget,
57
+ canDelete
58
+ } from './src/policy/acl.mjs'
59
+
60
+ export const name = 'chatluna-kb'
61
+ export const inject = ['tools', 'permissions']
62
+
63
+ const LIST_MAX = 50
64
+ const CATALOG_TTL_MS = 60_000
65
+ const DEFAULT_DATA_DIR = '/root/chatluna/data/chatluna-kb'
66
+ const DEFAULT_BINARY_PATH = DEFAULT_DATA_DIR + '/weknora-lite/weknora-lite'
67
+ // chatluna.yml 残留的旧 8891 时代默认值:只有配置仍等于这些历史值时才允许 dataDir 覆盖。
68
+ const HISTORICAL_API_KEY_FILE = '/root/.weknora-ingest-key'
69
+ const HISTORICAL_KB_ID = '711dabcf-90e5-4b40-bf81-62c26b7eccf3'
70
+ const HEALTH_TTL_MS = 5_000
71
+ const HEALTH_TIMEOUT_MS = 2_000
72
+ const LOG_MAX = 200
73
+ const RULES_TTL_MS = 5_000
74
+ /** 安装进度事件;安装器状态变化时 emit,WebUI 状态订阅据此重推。 */
75
+ const INSTALL_EVENT = 'chatluna-kb/install'
76
+ /** 离线包上传上限(流式落盘,超过即拒绝)。 */
77
+ const INSTALL_UPLOAD_MAX = 512 * 1024 * 1024
78
+ /** Embedding 连通性测试超时。 */
79
+ const EMBEDDING_TEST_TIMEOUT_MS = 15_000
80
+
81
+ const oneLine = (err) => {
82
+ const text = (err instanceof Error ? err.message : String(err ?? '')).replace(/\s+/g, ' ').trim()
83
+ return text.length <= LOG_MAX ? text : text.slice(0, LOG_MAX - 1) + '…'
84
+ }
85
+ const normalizeBaseUrl = (value) => String(value ?? '').trim().replace(/\/+$/, '')
86
+
87
+ const clip = (text, max) => {
88
+ const value = typeof text === 'string' ? text : ''
89
+ return value.length <= max ? value : value.slice(0, max) + '…'
90
+ }
91
+
92
+ function headerOf(req, name) {
93
+ const headers = req?.headers
94
+ if (headers === undefined || headers === null) return null
95
+ if (typeof headers.get === 'function') return headers.get(name)
96
+ const lower = name.toLowerCase()
97
+ for (const key of Object.keys(headers)) if (key.toLowerCase() === lower) return headers[key]
98
+ return null
99
+ }
100
+
101
+ // 复用 WebUI 登录判定(与 /kb-proxy 一致):cookie 会话优先,其次 access token。
102
+ // 只返回布尔值;token/cookie 绝不写日志。
103
+ function isWebuiAuthorized(context, req, logger) {
104
+ const server = context?.chatluna_server
105
+ if (server === undefined || server === null) return false
106
+ try {
107
+ if (server.verifyCookie(req)) return true
108
+ } catch {
109
+ // 畸形 cookie 回退到 bearer 判定
110
+ }
111
+ const authorization = headerOf(req, 'authorization')
112
+ if (typeof authorization !== 'string') return false
113
+ const match = /^bearer\s+(.+)$/i.exec(authorization.trim())
114
+ if (match === null) return false
115
+ const token = match[1].trim()
116
+ if (token === '') return false
117
+ const from = req?._req?.socket?.remoteAddress ?? ''
118
+ try {
119
+ if (server.auth.verify(token)) return true
120
+ } catch {}
121
+ try {
122
+ if (server.auth.check(token, from)) return true
123
+ } catch (err) {
124
+ logger?.warn?.(`kb-admin: access token rejected (${err?.code ?? 'invalid-token'})`)
125
+ }
126
+ return false
127
+ }
128
+
129
+ // 阶段错误只回一行、≤200 字;显式擦除密钥与常见 sk- 形态。
130
+ function sanitizeError(err, secret) {
131
+ let text = oneLine(err)
132
+ if (typeof secret === 'string' && secret !== '') text = text.split(secret).join('***')
133
+ text = text.replace(/sk-[A-Za-z0-9_-]{8,}/g, 'sk-***')
134
+ return clip(text, 200)
135
+ }
136
+
137
+ // WeKnora returns knowledge_base_name="" on document metadata, so a rule written
138
+ // with a KB name can never match meta.knowledge_base_id. Canonicalize every spec
139
+ // to catalog IDs before it reaches filterKbs/assert*: '*' stays '*', IDs survive,
140
+ // names become the matching ID, anything absent from the catalog is dropped.
141
+ // Catalog caching is 60s: a KB created after a load stays invisible for at most
142
+ // one minute (and resolveKbTarget re-lists, so writes resolve fresh).
143
+ function canonicalizeSpec(spec, catalog) {
144
+ const list = Array.isArray(catalog) ? catalog : []
145
+ const entries = Array.isArray(spec) ? spec : spec === undefined || spec === null ? [] : [spec]
146
+ const out = []
147
+ const seen = new Set()
148
+ for (const entry of entries) {
149
+ const text = String(entry ?? '').trim()
150
+ if (text === '') continue
151
+ if (text === '*') return ['*']
152
+ let kb = list.find((item) => String(item?.id ?? '').trim() === text)
153
+ if (kb === undefined) {
154
+ const lower = text.toLowerCase()
155
+ kb = list.find((item) => String(item?.name ?? '').trim().toLowerCase() === lower)
156
+ }
157
+ if (kb === undefined) continue
158
+ const id = String(kb.id ?? '').trim()
159
+ if (id === '' || seen.has(id)) continue
160
+ seen.add(id)
161
+ out.push(id)
162
+ }
163
+ return out
164
+ }
165
+
166
+ // ---- Embedding 覆盖配置:<dataDir>/embedding.json 由安装向导写入,优先于 chatluna.yml ----
167
+ function normalizeEmbedding(value) {
168
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined
169
+ const out = {}
170
+ for (const key of ['baseUrl', 'model', 'apiKeyFile']) {
171
+ const text = String(value[key] ?? '').trim()
172
+ if (text !== '') out[key] = text
173
+ }
174
+ const dimension = Number(value.dimension)
175
+ if (Number.isFinite(dimension) && dimension > 0) out.dimension = Math.trunc(dimension)
176
+ return Object.keys(out).length === 0 ? undefined : out
177
+ }
178
+
179
+ function readEmbeddingOverride(dataDir) {
180
+ try {
181
+ return normalizeEmbedding(JSON.parse(readFileSync(join(dataDir, 'embedding.json'), 'utf8')))
182
+ } catch {
183
+ return undefined
184
+ }
185
+ }
186
+
187
+ /** 只读探测:文件可读才视为可用凭据,不跟随写入,也不改变权限。 */
188
+ function isReadableFile(path) {
189
+ try {
190
+ accessSync(path, constants.R_OK)
191
+ return statSync(path).isFile()
192
+ } catch {
193
+ return false
194
+ }
195
+ }
196
+
197
+ /** 读取 install/bootstrap 产物;缺失或损坏一律返回 null,不抛给 apply。 */
198
+ function readBootstrapRecord(file) {
199
+ try {
200
+ const parsed = JSON.parse(readFileSync(file, 'utf8'))
201
+ return parsed !== null && typeof parsed === 'object' ? parsed : null
202
+ } catch {
203
+ return null
204
+ }
205
+ }
206
+
207
+ export const Config = Schema.object({
208
+ mode: Schema.union([Schema.const('external'), Schema.const('managed-lite'), Schema.const('systemd')])
209
+ .default('managed-lite')
210
+ .label('运行模式(external 连已有 WeKnora;managed-lite 由插件托管;systemd 由独立 systemd 服务托管)'),
211
+ systemdUnit: Schema.string()
212
+ .default('weknora-lite-kb.service')
213
+ .label('systemd 独立服务 unit(仅 mode=systemd,必须为白名单内的 *.service)'),
214
+ releaseManifestUrl: Schema.string()
215
+ .default(DEFAULT_RELEASE_MANIFEST_URL)
216
+ .label('安装包发布清单 URL(release.json;默认 GitHub releases latest)'),
217
+ installMirrors: Schema.array(Schema.string())
218
+ .default([])
219
+ .label('安装包/清单镜像列表(可含 {url} 占位符)'),
220
+ pluginVersion: Schema.string()
221
+ .default('')
222
+ .label('插件版本(可选;用于校验发布清单 minPluginVersion)'),
223
+ tessdataDir: Schema.string()
224
+ .default('')
225
+ .label('Tesseract tessdata 目录(可选;默认取引擎目录下 tessdata)'),
226
+ engine: Schema.object({
227
+ binaryPath: Schema.string().default(DEFAULT_BINARY_PATH).label('Lite 二进制路径(默认取 dataDir 下的安装产物)'),
228
+ cwd: Schema.string().label('Lite 子进程工作目录(可选,默认继承插件进程)'),
229
+ dataDir: Schema.string().default(DEFAULT_DATA_DIR).label('Lite 数据目录'),
230
+ port: Schema.natural().default(18891).label('Lite 监听端口(仅 127.0.0.1)'),
231
+ startupTimeoutMs: Schema.natural().default(60_000).label('启动就绪超时 ms'),
232
+ shutdownTimeoutMs: Schema.natural().default(15_000).label('优雅退出超时 ms'),
233
+ restartBaseMs: Schema.natural().default(1_000).label('崩溃重启退避基数 ms'),
234
+ restartMaxMs: Schema.natural().default(30_000).label('崩溃重启退避上限 ms')
235
+ }).default({
236
+ binaryPath: DEFAULT_BINARY_PATH,
237
+ dataDir: DEFAULT_DATA_DIR,
238
+ port: 18891,
239
+ startupTimeoutMs: 60_000,
240
+ shutdownTimeoutMs: 15_000,
241
+ restartBaseMs: 1_000,
242
+ restartMaxMs: 30_000
243
+ }).label('Lite 引擎托管参数'),
244
+ embedding: Schema.object({
245
+ baseUrl: Schema.string().label('Embedding Base URL'),
246
+ model: Schema.string().label('Embedding 模型名'),
247
+ apiKeyFile: Schema.string().role('secret').label('Embedding API key 文件'),
248
+ dimension: Schema.natural().label('Embedding 维度')
249
+ }).label('托管模式 bootstrap 使用的 Embedding 模型(全可选)'),
250
+ setupTokenFile: Schema.string().role('secret').label('Lite setup token 文件(可选,默认从数据目录推断)'),
251
+ externalSessionTokenFile: Schema.string().role('secret').label('external 模式 WebUI 免登 token 文件(可选)'),
252
+ baseUrl: Schema.string().default('http://127.0.0.1:8891').label('WeKnora 后端'),
253
+ knowledgeBaseId: Schema.string().default('711dabcf-90e5-4b40-bf81-62c26b7eccf3').label('默认知识库 ID'),
254
+ apiKeyFile: Schema.string().default('/root/.weknora-ingest-key').label('API key 文件').role('secret'),
255
+ mediaDir: Schema.string().default('/root/chatluna/data/chatluna/platform-media').label('媒体目录'),
256
+ extraRoots: Schema.array(Schema.string()).default([]).label('额外允许目录'),
257
+ maxMb: Schema.natural().default(50).label('单文件上限 MB'),
258
+ folder: Schema.string().default('bot').label('入库子目录'),
259
+ timeoutMs: Schema.natural().default(15_000).label('请求超时 ms'),
260
+ connectTimeoutMs: Schema.natural().default(3000).label('连接超时 ms'),
261
+ uploadTimeoutMs: Schema.natural().default(180_000).label('上传超时 ms'),
262
+ publicKbs: Schema.array(Schema.string()).default([]).label('公开知识库(无规则时的默认可读白名单)'),
263
+ rules: Schema.array(
264
+ Schema.object({
265
+ id: Schema.string().description('规则标识,仅用于匹配结果回显'),
266
+ match: Schema.object({
267
+ scene: Schema.union([Schema.const('all'), Schema.const('direct'), Schema.const('group')]).description('会话场景'),
268
+ platform: Schema.string().description('平台名,如 onebot / discord'),
269
+ guildId: Schema.string().description('群号'),
270
+ userId: Schema.string().description('用户 ID'),
271
+ minLevel: Schema.natural().description('最低权限等级 0-5')
272
+ }),
273
+ defaultKb: Schema.string().description('该场景的默认知识库(名称或 ID)'),
274
+ readableKbs: Schema.array(Schema.string()).default([]).description('可读库白名单,* 表示全部'),
275
+ writableKbs: Schema.array(Schema.string()).default([]).description('可写库白名单,空数组=只读'),
276
+ manageableKbs: Schema.array(Schema.string()).default([]).description('可管理(重解析/删除)库白名单')
277
+ })
278
+ ).default([]).label('路由级权限分流规则')
279
+ })
280
+
281
+ const kbArg = Schema.string().description(
282
+ 'knowledge base name or id. Must be inside the caller\'s allowed whitelist; omitted falls back to the route default.'
283
+ )
284
+
285
+ const readArgs = Schema.object({
286
+ action: Schema.union([
287
+ Schema.const('list_kbs').description('list accessible knowledge bases'),
288
+ Schema.const('list_docs').description('list documents of a KB (page/page_size/keyword/parse_status)'),
289
+ Schema.const('search').description('retrieve chunks in a KB (query_text, mode, limit, knowledge_ids)'),
290
+ Schema.const('toc').description('outline a document by knowledge_id (headings and chunk ranges)'),
291
+ Schema.const('read').description('read one document by knowledge_id (section or offset/limit, optional query)')
292
+ ]).required().description('Which read operation to run.'),
293
+ knowledge_base: kbArg,
294
+ knowledge_id: Schema.string().description('toc/read: document id from list_docs or search.'),
295
+ query_text: Schema.string().description('search: retrieval text (required there).'),
296
+ query: Schema.string().description('read: in-document keyword filter; degrades to retrieval, not a full scan.'),
297
+ mode: Schema.union([Schema.const('hybrid'), Schema.const('semantic'), Schema.const('keyword')]).description('search: retrieval mode, default hybrid.'),
298
+ limit: Schema.natural().description('search: 1-30 hits; read: 1-20 chunks.'),
299
+ offset: Schema.natural().description('read: chunk offset, default 0.'),
300
+ section: Schema.string().description('read: heading title to read exactly that section (falls back to offset when omitted).'),
301
+ knowledge_ids: Schema.array(Schema.string()).description('search: restrict to these document ids (each must be readable).'),
302
+ keyword: Schema.string().description('list_docs: filename/title filter.'),
303
+ parse_status: Schema.union([Schema.const('pending'), Schema.const('processing'), Schema.const('completed'), Schema.const('failed')]).description('list_docs: parse status filter.'),
304
+ page: Schema.natural().description('list_docs: 1-based page, default 1.'),
305
+ page_size: Schema.natural().description('list_docs: 1-50 per page, default 20.')
306
+ })
307
+
308
+ const writeArgs = Schema.object({
309
+ action: Schema.union([
310
+ Schema.const('ingest_file').description('store an attachment/local document (file/title/folder)'),
311
+ Schema.const('ingest_text').description('store Markdown text verbatim (title/content)'),
312
+ Schema.const('ingest_url').description('import a web page or direct file URL (url/title)')
313
+ ]).required().description('Which write operation to run.'),
314
+ file: Schema.string().description('ingest_file: attachment name from the current message (/api/platform/media/<hash>.pdf or <hash>.pdf) or an absolute path inside the allowed roots.'),
315
+ title: Schema.string().description('ingest_file/text/url: title or filename to store.'),
316
+ folder: Schema.string().description('ingest_file: folder under the KB root, max 3 levels.'),
317
+ content: Schema.string().description('ingest_text: Markdown body, stored verbatim.'),
318
+ url: Schema.string().description('ingest_url: http(s) URL to import.'),
319
+ knowledge_base: kbArg
320
+ })
321
+
322
+ const manageArgs = Schema.object({
323
+ action: Schema.union([
324
+ Schema.const('reparse').description('re-run parsing for one or more documents'),
325
+ Schema.const('delete').description('delete a document (irreversible, async)'),
326
+ Schema.const('create_kb').description('create a knowledge base (direct chat owner only: name, description)')
327
+ ]).required().description('Which management operation to run.'),
328
+ knowledge_id: Schema.string().description('reparse/delete: single document id.'),
329
+ knowledge_ids: Schema.array(Schema.string()).description('reparse: batch document ids (max 200).'),
330
+ name: Schema.string().description('create_kb: knowledge base name (required).'),
331
+ description: Schema.string().description('create_kb: optional description.'),
332
+ knowledge_base: kbArg
333
+ })
334
+
335
+ const need = (action, value, field) => {
336
+ if (typeof value === 'string' && value.trim() !== '') return value.trim()
337
+ throw new Error(`action=${action} 需要 ${field}`)
338
+ }
339
+
340
+ export function apply(ctx, config) {
341
+ const mode = config.mode === 'external' || config.mode === 'systemd' || config.mode === 'managed-lite'
342
+ ? config.mode
343
+ : 'managed-lite'
344
+ const managed = mode === 'managed-lite'
345
+ const systemd = mode === 'systemd'
346
+ const logger = typeof ctx.logger === 'function' ? ctx.logger('chatluna-kb') : (ctx.logger ?? console)
347
+ const dataDir = String(config.engine?.dataDir ?? '').trim() || DEFAULT_DATA_DIR
348
+ const runtime = {
349
+ mode: systemd ? 'systemd' : managed ? 'managed-lite' : 'external',
350
+ baseUrl: managed ? '' : normalizeBaseUrl(config.baseUrl),
351
+ kbId: String(config.knowledgeBaseId ?? '').trim(),
352
+ apiKeyFile: managed ? '' : String(config.apiKeyFile ?? '').trim(),
353
+ embeddingModelId: '',
354
+ tenantId: '',
355
+ lastError: '',
356
+ readyAt: 0
357
+ }
358
+
359
+ // bootstrap 读扁平键(dataDir/setupTokenFile/embedding/...),与 manager 共用同一份合并配置。
360
+ const enginePort = Number(config.engine?.port) > 0 ? Math.trunc(Number(config.engine.port)) : 18891
361
+ // systemd 单元固定监听 enginePort(默认 18891);schema 的历史默认 8891 是旧 WeKnora 服务,
362
+ // 未显式覆盖时不能沿用到独立单元模式。
363
+ const configuredBaseUrl = normalizeBaseUrl(config.baseUrl)
364
+ const systemdBaseUrl =
365
+ configuredBaseUrl === '' || configuredBaseUrl === 'http://127.0.0.1:8891'
366
+ ? `http://127.0.0.1:${enginePort}`
367
+ : configuredBaseUrl
368
+ if (systemd) runtime.baseUrl = systemdBaseUrl
369
+ // systemd 独立服务的凭据与引导产物落在 <dataDir>:初始化与 bootSystemd 各同步一次。
370
+ // 只读文件,绝不 spawn/systemctl start;显式新配置(非历史默认)一律优先,不覆盖。
371
+ function resolveSystemdRuntime() {
372
+ if (!systemd) return
373
+ const keyFile = join(dataDir, 'api-key')
374
+ if (
375
+ (runtime.apiKeyFile === '' || runtime.apiKeyFile === HISTORICAL_API_KEY_FILE) &&
376
+ isReadableFile(keyFile)
377
+ ) {
378
+ runtime.apiKeyFile = keyFile
379
+ }
380
+ const boot = readBootstrapRecord(join(dataDir, 'bootstrap.json'))
381
+ if (boot === null) return
382
+ const bootKbId = String(boot.kbId ?? '').trim()
383
+ if (bootKbId !== '' && (runtime.kbId === '' || runtime.kbId === HISTORICAL_KB_ID)) {
384
+ runtime.kbId = bootKbId
385
+ }
386
+ const bootEmbedding = String(boot.embeddingModelId ?? '').trim()
387
+ if (bootEmbedding !== '' && runtime.embeddingModelId === '') runtime.embeddingModelId = bootEmbedding
388
+ const bootTenant = String(boot.tenantId ?? '').trim()
389
+ if (bootTenant !== '' && runtime.tenantId === '') runtime.tenantId = bootTenant
390
+ }
391
+ resolveSystemdRuntime()
392
+ // 默认二进制跟随 dataDir(安装器目标);显式配置(含历史上的 dist 路径)一律优先。
393
+ const configuredBinary = String(config.engine?.binaryPath ?? '').trim()
394
+ const binaryPath = configuredBinary !== '' && configuredBinary !== DEFAULT_BINARY_PATH
395
+ ? configuredBinary
396
+ : join(dataDir, 'weknora-lite', 'weknora-lite')
397
+ const engineConfig = { ...config, ...(config.engine ?? {}), binaryPath }
398
+ // 安装向导写出的 <dataDir>/embedding.json 优先于 chatluna.yml 的 config.embedding,
399
+ // 只有重启(restartManaged 重新 ensureBootstrap)才会读取新值。
400
+ let embeddingOverride = readEmbeddingOverride(dataDir)
401
+ const currentEmbedding = () => embeddingOverride ?? normalizeEmbedding(config.embedding)
402
+ let bootConfig = { ...engineConfig, embedding: currentEmbedding() }
403
+
404
+ let manager = null
405
+ let startPromise = null
406
+ let clientCache = null
407
+ let rulesCache = { at: 0, mtimeMs: -1, rules: null }
408
+
409
+ // 所有错误只落一行、截断 200 字;调用方不得传入 key/token 或响应体。
410
+ const logError = (scope, err) => {
411
+ const line = oneLine(err)
412
+ try {
413
+ if (typeof logger?.error === 'function') logger.error(`[${scope}] ${line}`)
414
+ else console.error(`[chatluna-kb:${scope}] ${line}`)
415
+ } catch {}
416
+ return line
417
+ }
418
+
419
+ const emitStatus = () => {
420
+ try {
421
+ ctx.emit('chatluna-kb/status')
422
+ } catch {}
423
+ }
424
+
425
+ const emitInstall = () => {
426
+ try {
427
+ ctx.emit(INSTALL_EVENT)
428
+ } catch {}
429
+ }
430
+
431
+ // ---- 安装器(仅 managed:负责下载/校验/解包到 <dataDir>/weknora-lite) ----
432
+ let installer = null
433
+ if (managed) {
434
+ try {
435
+ installer = createInstaller({
436
+ dataDir,
437
+ binaryDir: dirname(binaryPath),
438
+ maxBytes: INSTALL_UPLOAD_MAX,
439
+ releaseManifestUrl: config.releaseManifestUrl || DEFAULT_RELEASE_MANIFEST_URL,
440
+ mirrors: Array.isArray(config.installMirrors) ? config.installMirrors : [],
441
+ pluginVersion: String(config.pluginVersion ?? '').trim(),
442
+ onStatus: () => {
443
+ emitInstall()
444
+ },
445
+ logger
446
+ })
447
+ } catch (err) {
448
+ installer = null
449
+ runtime.lastError = logError('installer', err)
450
+ }
451
+ }
452
+ const installStatus = () =>
453
+ installer !== null
454
+ ? installer.status()
455
+ : { supported: false, state: 'unavailable', installed: existsSync(binaryPath) }
456
+
457
+ // ---- 运行环境探测(只读、60s 缓存;状态快照与 kb.detect 共用) ----------
458
+ const ENV_PROBE_TTL_MS = 60_000
459
+ const envProbe = { key: '', at: 0, promise: null }
460
+ const tessdataConfig = String(config.tessdataDir ?? '').trim()
461
+ function probeEnvironment() {
462
+ const key = [binaryPath, dataDir, tessdataConfig].join('|')
463
+ if (envProbe.promise !== null && envProbe.key === key && Date.now() - envProbe.at < ENV_PROBE_TTL_MS) {
464
+ return envProbe.promise
465
+ }
466
+ const pending = detectEnvironment({
467
+ binaryPath,
468
+ dataDir,
469
+ tessdataDir: tessdataConfig
470
+ }).catch((err) => {
471
+ // 探测失败只降级为未知字段,绝不影响状态/安装动作。
472
+ runtime.lastError = runtime.lastError || logError('probe', err)
473
+ const fallback = platformInfo(process.platform, process.arch)
474
+ return {
475
+ platform: process.platform,
476
+ arch: process.arch,
477
+ platformKey: fallback.key,
478
+ supported: fallback.supported,
479
+ binary: { path: binaryPath, installed: existsSync(binaryPath), executable: false, version: null },
480
+ engineInstalled: existsSync(binaryPath),
481
+ tesseractFound: false,
482
+ pdftoppmFound: false,
483
+ tessdataDir: tessdataConfig,
484
+ tessdataReady: false,
485
+ tessdataLanguages: [],
486
+ ocr: {
487
+ ready: false,
488
+ engine: 'tesseract',
489
+ tessdataDir: tessdataConfig,
490
+ tesseractFound: false,
491
+ pdftoppmFound: false
492
+ }
493
+ }
494
+ })
495
+ envProbe.key = key
496
+ envProbe.at = Date.now()
497
+ envProbe.promise = pending
498
+ return pending
499
+ }
500
+
501
+ // ---- 独立 systemd 单元控制器(仅 systemd:不 spawn,只做白名单 systemctl/journalctl) ----
502
+ let systemdController = null
503
+ if (systemd) {
504
+ const unit = String(config.systemdUnit ?? '').trim() || 'weknora-lite-kb.service'
505
+ try {
506
+ systemdController = createSystemdController(
507
+ { unit, baseUrl: systemdBaseUrl, allowedUnits: [unit], healthTimeoutMs: 3_000, logsLimit: 100 },
508
+ { logger }
509
+ )
510
+ } catch (err) {
511
+ systemdController = null
512
+ runtime.lastError = logError('systemd', err)
513
+ }
514
+ }
515
+
516
+ // ---- 惰性客户端:baseUrl / 凭据文件 / 默认库变化时才重建 ---------------
517
+ function getClient() {
518
+ if (runtime.baseUrl === '') {
519
+ throw new Error(`知识库引擎尚未就绪${runtime.lastError ? `:${runtime.lastError}` : ''}`)
520
+ }
521
+ const keyFile = runtime.apiKeyFile || config.apiKeyFile
522
+ const kbId = runtime.kbId || config.knowledgeBaseId
523
+ if (
524
+ clientCache !== null &&
525
+ clientCache.baseUrl === runtime.baseUrl &&
526
+ clientCache.apiKeyFile === keyFile &&
527
+ clientCache.kbId === kbId
528
+ ) {
529
+ return clientCache.client
530
+ }
531
+ clientCache = {
532
+ baseUrl: runtime.baseUrl,
533
+ apiKeyFile: keyFile,
534
+ kbId,
535
+ client: createClient(ctx, {
536
+ ...config,
537
+ baseUrl: runtime.baseUrl,
538
+ apiKeyFile: keyFile,
539
+ knowledgeBaseId: kbId
540
+ })
541
+ }
542
+ return clientCache.client
543
+ }
544
+ // 工具里直接调 client.<method>;Proxy 保证真实客户端只在第一次使用时构造。
545
+ const client = new Proxy({}, { get: (_target, prop) => getClient()[prop] })
546
+
547
+ // ---- 权限规则:rules.json 为唯一真源,缺失/损坏回退 config.rules --------
548
+ // 规则文件恒落在 dataDir(两种模式一致),首次保存时懒创建目录。
549
+ const rulesFile = () => join(dataDir, 'rules.json')
550
+ const fallbackRules = () => (Array.isArray(config.rules) ? config.rules : [])
551
+
552
+ function readRules() {
553
+ const file = rulesFile()
554
+ let stat = null
555
+ try {
556
+ stat = statSync(file)
557
+ } catch {}
558
+ if (stat === null) {
559
+ rulesCache = { at: 0, mtimeMs: -1, rules: null }
560
+ return fallbackRules()
561
+ }
562
+ if (
563
+ rulesCache.rules !== null &&
564
+ rulesCache.mtimeMs === stat.mtimeMs &&
565
+ Date.now() - rulesCache.at < RULES_TTL_MS
566
+ ) {
567
+ return rulesCache.rules
568
+ }
569
+ try {
570
+ const parsed = JSON.parse(readFileSync(file, 'utf8'))
571
+ const list = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.rules) ? parsed.rules : null
572
+ if (list === null) throw new Error('rules.json 顶层必须是数组或 { rules: [] }')
573
+ rulesCache = { at: Date.now(), mtimeMs: stat.mtimeMs, rules: list }
574
+ return list
575
+ } catch (err) {
576
+ logError('rules', new Error(`读取 ${file} 失败,回退 config.rules:${oneLine(err)}`))
577
+ rulesCache = { at: 0, mtimeMs: -1, rules: null }
578
+ return fallbackRules()
579
+ }
580
+ }
581
+
582
+ async function saveRules(next) {
583
+ if (!Array.isArray(next)) throw new Error('rules 必须是数组')
584
+ const file = rulesFile()
585
+ await mkdir(dirname(file), { recursive: true })
586
+ const body = JSON.stringify({ version: 1, updatedAt: new Date().toISOString(), rules: next }, null, 2) + '\n'
587
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`
588
+ await writeFile(tmp, body, { mode: 0o600 })
589
+ await chmod(tmp, 0o600)
590
+ await rename(tmp, file)
591
+ let mtimeMs = -1
592
+ try {
593
+ mtimeMs = statSync(file).mtimeMs
594
+ } catch {}
595
+ rulesCache = { at: Date.now(), mtimeMs, rules: next }
596
+ emitStatus()
597
+ return next
598
+ }
599
+
600
+ const scopeConfig = () => ({
601
+ ...config,
602
+ rules: readRules(),
603
+ knowledgeBaseId: runtime.kbId || config.knowledgeBaseId
604
+ })
605
+
606
+ // ---- 状态快照:external 的 /health 5 秒缓存,绝不每帧打后端 -------------
607
+ const healthCache = { baseUrl: '', at: 0, value: null }
608
+ async function probeHealth() {
609
+ const base = runtime.baseUrl
610
+ if (base === '') return { ok: false, status: 0, at: Date.now() }
611
+ if (healthCache.baseUrl === base && Date.now() - healthCache.at < HEALTH_TTL_MS) return healthCache.value
612
+ let value
613
+ try {
614
+ const res = await fetch(`${base}/health`, { signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS) })
615
+ value = { ok: res.ok, status: res.status, at: Date.now() }
616
+ } catch (err) {
617
+ value = { ok: false, status: 0, at: Date.now(), error: oneLine(err) }
618
+ }
619
+ healthCache.baseUrl = base
620
+ healthCache.at = Date.now()
621
+ healthCache.value = value
622
+ return value
623
+ }
624
+
625
+ async function statusSnapshot() {
626
+ const env = await probeEnvironment()
627
+ const shared = {
628
+ mode: runtime.mode,
629
+ managed: managed || systemd,
630
+ baseUrl: runtime.baseUrl,
631
+ kbId: runtime.kbId,
632
+ apiKeyFile: runtime.apiKeyFile,
633
+ embeddingModelId: runtime.embeddingModelId,
634
+ tenantId: runtime.tenantId,
635
+ lastError: runtime.lastError,
636
+ readyAt: runtime.readyAt,
637
+ installed: existsSync(binaryPath),
638
+ install: installStatus(),
639
+ // 运行环境/OCR 只读探测:字段与 kb.detect 保持一致,60s 缓存。
640
+ platform: env.platform,
641
+ arch: env.arch,
642
+ platformKey: env.platformKey,
643
+ tesseractFound: env.tesseractFound,
644
+ pdftoppmFound: env.pdftoppmFound,
645
+ tessdataDir: env.tessdataDir,
646
+ tessdataReady: env.tessdataReady,
647
+ tessdataLanguages: env.tessdataLanguages,
648
+ ocr: env.ocr,
649
+ releaseManifestUrl: String(config.releaseManifestUrl || DEFAULT_RELEASE_MANIFEST_URL),
650
+ // 只读安装器清单缓存(detect/安装后刷新),状态快照本身不发网络请求。
651
+ release: installer !== null
652
+ ? installer.releaseSnapshot()
653
+ : {
654
+ manifestUrl: String(config.releaseManifestUrl || DEFAULT_RELEASE_MANIFEST_URL),
655
+ cached: false,
656
+ ok: null,
657
+ available: null,
658
+ code: 'INSTALLER_UNAVAILABLE'
659
+ },
660
+ // 向导 Embedding 步骤读取;只含 baseUrl/model/apiKeyFile/dimension,无 key 字节。
661
+ embedding: currentEmbedding() ?? null
662
+ }
663
+ if (systemd) {
664
+ const unit = String(config.systemdUnit ?? '').trim() || 'weknora-lite-kb.service'
665
+ let engineStatus
666
+ if (systemdController === null) {
667
+ engineStatus = {
668
+ mode: 'systemd',
669
+ unit,
670
+ running: false,
671
+ healthy: false,
672
+ logs: [],
673
+ lastError: runtime.lastError || 'systemd controller 不可用'
674
+ }
675
+ } else {
676
+ engineStatus = await systemdController.status()
677
+ }
678
+ // 状态来自 systemctl;失败时保留一行脱敏错误供工具与 WebUI 展示。
679
+ if (!engineStatus.running) runtime.lastError = engineStatus.lastError || '独立服务未运行'
680
+ else runtime.lastError = engineStatus.lastError || ''
681
+ return {
682
+ ...shared,
683
+ ...engineStatus,
684
+ mode: 'systemd',
685
+ managed: true,
686
+ baseUrl: runtime.baseUrl || engineStatus.baseUrl || '',
687
+ port: enginePort,
688
+ unit: engineStatus.unit || unit,
689
+ logs: Array.isArray(engineStatus.logs) ? engineStatus.logs : [],
690
+ updatedAt: Date.now()
691
+ }
692
+ }
693
+ if (!managed) {
694
+ const health = await probeHealth()
695
+ return { ...shared, running: health.ok, health, logs: [], updatedAt: Date.now() }
696
+ }
697
+ const engineStatus = typeof manager?.status === 'function' ? (manager.status() ?? {}) : {}
698
+ // 日志尾部给 WebUI 引擎页看;manager 的 ring 本身有上限,50 行是有界视图。
699
+ let logs = []
700
+ try {
701
+ const tail = manager?.logs?.(50)
702
+ if (Array.isArray(tail)) logs = tail
703
+ } catch {}
704
+ return {
705
+ ...engineStatus,
706
+ ...shared,
707
+ baseUrl: runtime.baseUrl || normalizeBaseUrl(engineStatus.baseUrl),
708
+ running: engineStatus.running === true || runtime.baseUrl !== '',
709
+ logs,
710
+ updatedAt: Date.now()
711
+ }
712
+ }
713
+
714
+ // ---- 托管生命周期(仅 managed-lite) ----------------------------------
715
+ // weknora-lite 只认环境变量:数据目录、sqlite、本地存储、setup token 与签名密钥都在这里
716
+ // 定死并由 manager 透传。秘密只落 <dataDir>/*.secret 形式的 0600 文件,不写 config、不打印。
717
+ function liteEnv() {
718
+ mkdirSync(dataDir, { recursive: true })
719
+ const readOrCreate = (path, bytes) => {
720
+ try {
721
+ const value = readFileSync(path, 'utf8').trim()
722
+ if (value !== '') return value
723
+ } catch {}
724
+ const value = randomBytes(bytes).toString('hex')
725
+ mkdirSync(dirname(path), { recursive: true })
726
+ writeFileSync(path, value + '\n', { mode: 0o600 })
727
+ try {
728
+ chmodSync(path, 0o600)
729
+ } catch {}
730
+ return value
731
+ }
732
+ const configuredSetupFile = String(config.setupTokenFile ?? '').trim()
733
+ const setupToken = readOrCreate(configuredSetupFile === '' ? join(dataDir, 'setup-token') : configuredSetupFile, 32)
734
+ return {
735
+ WEKNORA_KB_ONLY: 'true',
736
+ DB_DRIVER: 'sqlite',
737
+ DB_PATH: join(dataDir, 'weknora.db'),
738
+ RETRIEVE_DRIVER: 'sqlite',
739
+ STORAGE_TYPE: 'local',
740
+ LOCAL_STORAGE_BASE_DIR: join(dataDir, 'files'),
741
+ STREAM_MANAGER_TYPE: 'memory',
742
+ SERVER_HOST: '127.0.0.1',
743
+ SERVER_PORT: String(enginePort),
744
+ WEKNORA_LITE_SETUP_TOKEN: setupToken,
745
+ JWT_SECRET: readOrCreate(join(dataDir, 'jwt-secret'), 32),
746
+ SYSTEM_AES_KEY: readOrCreate(join(dataDir, 'system-aes-key'), 32)
747
+ }
748
+ }
749
+
750
+ function applyBootstrap(boot) {
751
+ const current = typeof manager?.status === 'function' ? (manager.status() ?? {}) : {}
752
+ const base = normalizeBaseUrl(boot?.baseUrl || current.baseUrl || runtime.baseUrl)
753
+ if (base !== '') runtime.baseUrl = base
754
+ const kbId = String(boot?.kbId ?? '').trim()
755
+ if (kbId !== '') runtime.kbId = kbId
756
+ const keyFile = String(boot?.apiKeyFile ?? '').trim()
757
+ if (keyFile !== '') runtime.apiKeyFile = keyFile
758
+ if (boot?.embeddingModelId !== undefined && boot?.embeddingModelId !== null) {
759
+ runtime.embeddingModelId = String(boot.embeddingModelId)
760
+ }
761
+ if (boot?.tenantId !== undefined && boot?.tenantId !== null) runtime.tenantId = String(boot.tenantId)
762
+ runtime.readyAt = Date.now()
763
+ }
764
+
765
+ async function bootEngine() {
766
+ // 未安装时绝不 spawn,也不进入 ensureBootstrap:向导装好后再点启动/自动拉起。
767
+ if (!existsSync(binaryPath)) {
768
+ runtime.lastError = '引擎未安装:请在知识库页面完成安装向导'
769
+ emitStatus()
770
+ return
771
+ }
772
+ try {
773
+ await manager.start()
774
+ const boot = await ensureBootstrap({ manager, config: bootConfig, logger })
775
+ applyBootstrap(boot)
776
+ runtime.lastError = ''
777
+ healthCache.at = 0
778
+ } catch (err) {
779
+ // 绝不向 apply 抛出:引擎起不来时插件仍可加载,工具调用给出明确错误。
780
+ runtime.lastError = logError('engine', err)
781
+ } finally {
782
+ emitStatus()
783
+ }
784
+ }
785
+
786
+ // systemd 模式:启动时只确认独立服务健康,绝不 systemctl start/stop(生命周期归 systemd)。
787
+ async function bootSystemd() {
788
+ resolveSystemdRuntime()
789
+ if (systemdController === null) {
790
+ runtime.lastError = runtime.lastError || 'systemd controller 不可用'
791
+ emitStatus()
792
+ return
793
+ }
794
+ try {
795
+ const status = await systemdController.status()
796
+ if (status.baseUrl) runtime.baseUrl = normalizeBaseUrl(status.baseUrl) || runtime.baseUrl
797
+ if (status.healthy) {
798
+ runtime.lastError = ''
799
+ runtime.readyAt = Date.now()
800
+ } else if (status.running) {
801
+ runtime.lastError = status.lastError || '独立服务已运行但健康检查失败'
802
+ } else {
803
+ runtime.lastError = status.lastError || `独立服务未运行(${status.unit})`
804
+ }
805
+ } catch (err) {
806
+ runtime.lastError = logError('systemd', err)
807
+ } finally {
808
+ // bootstrap/api-key 可能由外部引导在启动窗口内补齐,收尾再同步一次。
809
+ resolveSystemdRuntime()
810
+ emitStatus()
811
+ }
812
+ }
813
+
814
+ function startEngine() {
815
+ if (!managed || manager === null) return Promise.resolve()
816
+ if (startPromise !== null) return startPromise
817
+ startPromise = bootEngine().finally(() => {
818
+ startPromise = null
819
+ })
820
+ return startPromise
821
+ }
822
+
823
+ async function waitReady() {
824
+ if (!managed || runtime.baseUrl !== '') return
825
+ if (startPromise !== null) {
826
+ try {
827
+ await startPromise
828
+ } catch {}
829
+ }
830
+ if (runtime.baseUrl === '') {
831
+ throw new Error(
832
+ `知识库引擎尚未就绪${runtime.lastError ? `:${runtime.lastError}` : '(正在启动,请稍后重试)'}`
833
+ )
834
+ }
835
+ }
836
+
837
+ const notManaged = (action) => new Error(`外部模式不支持${action}(mode=external 只连接已有 WeKnora 服务)`)
838
+
839
+ function requireSystemd(action) {
840
+ if (systemdController === null) {
841
+ throw new Error(`systemd 控制器不可用,无法${action}${runtime.lastError ? `:${runtime.lastError}` : ''}`)
842
+ }
843
+ return systemdController
844
+ }
845
+
846
+ async function startManaged() {
847
+ if (systemd) {
848
+ const result = await requireSystemd('启动引擎').start()
849
+ healthCache.at = 0
850
+ emitStatus()
851
+ return result
852
+ }
853
+ if (!managed) throw notManaged('启动引擎')
854
+ if (runtime.baseUrl !== '' && startPromise === null) return { ok: true }
855
+ await startEngine()
856
+ if (runtime.baseUrl === '') throw new Error(runtime.lastError || '引擎启动失败')
857
+ return { ok: true }
858
+ }
859
+
860
+ async function stopManaged() {
861
+ if (systemd) {
862
+ const result = await requireSystemd('停止引擎').stop()
863
+ runtime.readyAt = 0
864
+ healthCache.at = 0
865
+ emitStatus()
866
+ return result
867
+ }
868
+ if (!managed) throw notManaged('停止引擎')
869
+ if (typeof manager?.stop === 'function') await manager.stop()
870
+ runtime.baseUrl = ''
871
+ runtime.readyAt = 0
872
+ healthCache.at = 0
873
+ emitStatus()
874
+ return { ok: true }
875
+ }
876
+
877
+ async function restartManaged() {
878
+ if (systemd) {
879
+ const controller = requireSystemd('重启引擎')
880
+ const result = await controller.restart()
881
+ healthCache.at = 0
882
+ const status = await controller.status()
883
+ runtime.lastError = status.running ? '' : status.lastError || '独立服务未运行'
884
+ emitStatus()
885
+ return result
886
+ }
887
+ if (!managed) throw notManaged('重启引擎')
888
+ if (typeof manager?.restart === 'function') {
889
+ await manager.restart()
890
+ } else {
891
+ await manager.stop()
892
+ await manager.start()
893
+ }
894
+ try {
895
+ applyBootstrap(await ensureBootstrap({ manager, config: bootConfig, logger }))
896
+ runtime.lastError = ''
897
+ } catch (err) {
898
+ runtime.lastError = logError('engine', err)
899
+ }
900
+ healthCache.at = 0
901
+ emitStatus()
902
+ if (runtime.baseUrl === '') throw new Error(runtime.lastError || '引擎重启失败')
903
+ return { ok: true }
904
+ }
905
+
906
+ // ---- 安装向导依赖 ------------------------------------------------------
907
+ // 安装成功只广播状态,绝不自动启动:向导第 4 步由用户点击 kb.start 拉起并初始化。
908
+ const requireInstaller = (action) => {
909
+ if (!managed || installer === null) throw notManaged(action)
910
+ return installer
911
+ }
912
+
913
+ async function detect() {
914
+ const env = await probeEnvironment()
915
+ const manifestUrl = String(config.releaseManifestUrl || DEFAULT_RELEASE_MANIFEST_URL)
916
+ const base = installer !== null
917
+ ? installer.detect()
918
+ : {
919
+ os: process.platform,
920
+ arch: process.arch,
921
+ key: env.platformKey,
922
+ supported: env.supported,
923
+ existing: { installed: existsSync(binaryPath), version: env.binary?.version ?? null },
924
+ manifestUrl,
925
+ pluginVersion: String(config.pluginVersion ?? '').trim() || null
926
+ }
927
+ let release
928
+ if (installer === null) {
929
+ release = {
930
+ manifestUrl,
931
+ platform: base.key,
932
+ platformSupported: base.supported,
933
+ ok: false,
934
+ available: false,
935
+ code: 'INSTALLER_UNAVAILABLE',
936
+ error: `INSTALLER_UNAVAILABLE: ${runtime.mode} 模式不提供安装器`
937
+ }
938
+ } else {
939
+ try {
940
+ release = await installer.releaseStatus({
941
+ manifestUrl: base.manifestUrl,
942
+ platform: base.os,
943
+ arch: base.arch
944
+ })
945
+ } catch (err) {
946
+ release = {
947
+ manifestUrl,
948
+ platform: base.key,
949
+ ok: false,
950
+ available: false,
951
+ code: 'MANIFEST_FETCH_FAILED',
952
+ error: sanitizeError(err)
953
+ }
954
+ }
955
+ }
956
+ return {
957
+ mode: runtime.mode,
958
+ // supported 保持旧语义:可安装 = 有安装器且平台受支持;平台自身能力另有字段。
959
+ supported: installer !== null && base.supported,
960
+ platformSupported: base.supported,
961
+ installSupported: installer !== null,
962
+ platform: base.os,
963
+ arch: base.arch,
964
+ platformKey: base.key,
965
+ installed: base.existing.installed,
966
+ installedVersion: base.existing.version,
967
+ binaryPath,
968
+ release,
969
+ tesseractFound: env.tesseractFound,
970
+ pdftoppmFound: env.pdftoppmFound,
971
+ tessdataDir: env.tessdataDir,
972
+ tessdataReady: env.tessdataReady,
973
+ tessdataLanguages: env.tessdataLanguages,
974
+ ocr: env.ocr
975
+ }
976
+ }
977
+
978
+ async function installRelease() {
979
+ const engineInstaller = requireInstaller('自动安装')
980
+ try {
981
+ const result = await engineInstaller.installFromRelease()
982
+ emitInstall()
983
+ emitStatus()
984
+ return result ?? { ok: true }
985
+ } catch (err) {
986
+ emitInstall()
987
+ emitStatus()
988
+ throw new Error(sanitizeError(err))
989
+ }
990
+ }
991
+
992
+ async function installUrl(input) {
993
+ const engineInstaller = requireInstaller('在线安装')
994
+ const url = String(input?.url ?? '').trim()
995
+ if (!/^https?:\/\//i.test(url)) throw new Error('下载地址必须是 http(s) URL')
996
+ try {
997
+ const options = typeof input?.sha256 === 'string' && input.sha256 !== '' ? { sha256: input.sha256 } : {}
998
+ const result = await engineInstaller.installFromUrl(url, options)
999
+ emitInstall()
1000
+ emitStatus()
1001
+ return result ?? { ok: true }
1002
+ } catch (err) {
1003
+ emitInstall()
1004
+ emitStatus()
1005
+ throw new Error(sanitizeError(err))
1006
+ }
1007
+ }
1008
+
1009
+ async function installPath(input) {
1010
+ const engineInstaller = requireInstaller('离线安装')
1011
+ const path = String(input?.path ?? '').trim()
1012
+ if (path === '' || !isAbsolute(path)) throw new Error('离线包必须是绝对路径')
1013
+ try {
1014
+ await access(path, constants.R_OK)
1015
+ } catch {
1016
+ throw new Error('离线包不存在或不可读')
1017
+ }
1018
+ try {
1019
+ const options = typeof input?.sha256 === 'string' && input.sha256 !== '' ? { sha256: input.sha256 } : {}
1020
+ const result = await engineInstaller.installFromFile(path, options)
1021
+ emitInstall()
1022
+ emitStatus()
1023
+ return result ?? { ok: true }
1024
+ } catch (err) {
1025
+ emitInstall()
1026
+ emitStatus()
1027
+ throw new Error(sanitizeError(err))
1028
+ }
1029
+ }
1030
+
1031
+ async function cancelInstall() {
1032
+ const engineInstaller = requireInstaller('取消安装')
1033
+ return engineInstaller.cancel()
1034
+ }
1035
+
1036
+ // 解析测试/保存用的合并配置:显式入参 > embedding.json > chatluna.yml。
1037
+ const mergeEmbedding = (input) => ({
1038
+ ...(currentEmbedding() ?? {}),
1039
+ ...(normalizeEmbedding(input) ?? {})
1040
+ })
1041
+
1042
+ async function testEmbedding(input) {
1043
+ const raw = input !== null && typeof input === 'object' ? input : {}
1044
+ const merged = mergeEmbedding(raw)
1045
+ const baseUrl = String(raw.baseUrl ?? merged.baseUrl ?? '').trim().replace(/\/+$/, '')
1046
+ const model = String(raw.model ?? merged.model ?? '').trim()
1047
+ if (!/^https?:\/\//i.test(baseUrl)) return { ok: false, error: 'Embedding baseUrl 必须是 http(s) 地址' }
1048
+ if (model === '') return { ok: false, error: '缺少 Embedding 模型名' }
1049
+ let apiKey = typeof raw.apiKey === 'string' ? raw.apiKey.trim() : ''
1050
+ const keyFile = String(raw.apiKeyFile ?? merged.apiKeyFile ?? '').trim()
1051
+ if (apiKey === '') {
1052
+ if (keyFile === '') return { ok: false, error: '缺少 API key 或 apiKeyFile' }
1053
+ try {
1054
+ apiKey = (await readFile(keyFile, 'utf8')).trim()
1055
+ } catch {
1056
+ return { ok: false, error: 'API key 文件不可读' }
1057
+ }
1058
+ }
1059
+ if (apiKey === '') return { ok: false, error: 'API key 为空' }
1060
+ const startedAt = Date.now()
1061
+ try {
1062
+ const res = await fetch(`${baseUrl}/embeddings`, {
1063
+ method: 'POST',
1064
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },
1065
+ body: JSON.stringify({ model, input: 'ping' }),
1066
+ signal: AbortSignal.timeout(EMBEDDING_TEST_TIMEOUT_MS)
1067
+ })
1068
+ const text = await res.text()
1069
+ const ms = Date.now() - startedAt
1070
+ if (!res.ok) return { ok: false, error: sanitizeError(`HTTP ${res.status} ${clip(text, 160)}`, apiKey), ms }
1071
+ let json = null
1072
+ try {
1073
+ json = JSON.parse(text)
1074
+ } catch {}
1075
+ const vector = json?.data?.[0]?.embedding
1076
+ const declared = Number(json?.dimension)
1077
+ const dimension = Array.isArray(vector)
1078
+ ? vector.length
1079
+ : Number.isFinite(declared) && declared > 0
1080
+ ? Math.trunc(declared)
1081
+ : 0
1082
+ if (dimension <= 0) return { ok: false, error: '响应缺少 embedding 向量', ms }
1083
+ return { ok: true, dimension, ms }
1084
+ } catch (err) {
1085
+ return { ok: false, error: sanitizeError(err, apiKey), ms: Date.now() - startedAt }
1086
+ }
1087
+ }
1088
+
1089
+ async function saveEmbedding(input) {
1090
+ const raw = input !== null && typeof input === 'object' ? input : {}
1091
+ const saved = currentEmbedding() ?? {}
1092
+ const baseUrl = String(raw.baseUrl ?? '').trim().replace(/\/+$/, '')
1093
+ const model = String(raw.model ?? saved.model ?? '').trim()
1094
+ if (!/^https?:\/\//i.test(baseUrl)) throw new Error('Embedding baseUrl 必须是 http(s) 地址')
1095
+ if (model === '') throw new Error('缺少 Embedding 模型名')
1096
+ await mkdir(dataDir, { recursive: true })
1097
+ let apiKeyFile = String(raw.apiKeyFile ?? saved.apiKeyFile ?? '').trim()
1098
+ const apiKey = typeof raw.apiKey === 'string' ? raw.apiKey.trim() : ''
1099
+ // 向导直接填 key 时落独立 0600 文件;配置与日志永远只出现路径。
1100
+ if (apiKey !== '') {
1101
+ apiKeyFile = join(dataDir, 'embedding.key')
1102
+ await writeFile(apiKeyFile, apiKey + '\n', { mode: 0o600 })
1103
+ await chmod(apiKeyFile, 0o600)
1104
+ }
1105
+ if (apiKeyFile === '') throw new Error('缺少 Embedding API key 或 apiKeyFile')
1106
+ try {
1107
+ await access(apiKeyFile, constants.R_OK)
1108
+ } catch {
1109
+ throw new Error('API key 文件不可读')
1110
+ }
1111
+ const record = { baseUrl, model, apiKeyFile }
1112
+ const dimension = Number(raw.dimension ?? saved.dimension)
1113
+ if (Number.isFinite(dimension) && dimension > 0) record.dimension = Math.trunc(dimension)
1114
+ const file = join(dataDir, 'embedding.json')
1115
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`
1116
+ await writeFile(tmp, JSON.stringify(record, null, 2) + '\n', { mode: 0o600 })
1117
+ await chmod(tmp, 0o600)
1118
+ await rename(tmp, file)
1119
+ embeddingOverride = record
1120
+ bootConfig = { ...bootConfig, embedding: currentEmbedding() }
1121
+ emitStatus()
1122
+ return { ok: true, embedding: record }
1123
+ }
1124
+
1125
+ // ---- WebUI 免登桥接:managed 用 setup token 换 JWT,external 读可选 token --
1126
+ async function readSetupToken() {
1127
+ const files = []
1128
+ const configured = String(config.setupTokenFile ?? '').trim()
1129
+ if (configured !== '') files.push(configured)
1130
+ files.push(
1131
+ join(dataDir, 'setup-token'),
1132
+ join(dataDir, 'weknora-lite', 'setup-token'),
1133
+ join(dataDir, 'lite', 'setup-token')
1134
+ )
1135
+ for (const file of files) {
1136
+ try {
1137
+ const token = (await readFile(file, 'utf8')).trim()
1138
+ if (token !== '') return token
1139
+ } catch {}
1140
+ }
1141
+ const status = typeof manager?.status === 'function' ? (manager.status() ?? {}) : {}
1142
+ const candidate = status.setupToken ?? manager?.setupToken
1143
+ return typeof candidate === 'string' && candidate.trim() !== '' ? candidate.trim() : ''
1144
+ }
1145
+
1146
+ async function session() {
1147
+ if (!managed && !systemd) {
1148
+ const file = String(config.externalSessionTokenFile ?? '').trim()
1149
+ if (file === '') return null
1150
+ try {
1151
+ const token = (await readFile(file, 'utf8')).trim()
1152
+ return token === '' ? null : { success: true, token }
1153
+ } catch (err) {
1154
+ logError('session', err)
1155
+ return null
1156
+ }
1157
+ }
1158
+ const engineStatus = typeof manager?.status === 'function' ? (manager.status() ?? {}) : {}
1159
+ const base = runtime.baseUrl || normalizeBaseUrl(engineStatus.baseUrl)
1160
+ if (base === '') return null
1161
+ const token = await readSetupToken()
1162
+ if (token === '') return null
1163
+ try {
1164
+ const res = await fetch(`${base}/api/v1/auth/auto-setup`, {
1165
+ method: 'POST',
1166
+ headers: { 'X-WeKnora-Desktop-Token': token, 'Content-Type': 'application/json' },
1167
+ body: '{}',
1168
+ signal: AbortSignal.timeout(10_000)
1169
+ })
1170
+ if (!res.ok) {
1171
+ logError('session', new Error(`auto-setup 失败(HTTP ${res.status})`))
1172
+ return null
1173
+ }
1174
+ const json = JSON.parse(await res.text())
1175
+ return json !== null && typeof json === 'object' ? json : null
1176
+ } catch (err) {
1177
+ logError('session', err)
1178
+ return null
1179
+ }
1180
+ }
1181
+
1182
+ let catalogCache = null
1183
+ // ---- ChatLuna → WeKnora 模型复制桥:列表只读元数据,导入时临时物化密钥 ----
1184
+ const modelBridge = createModelBridge({
1185
+ ctx,
1186
+ baseUrl: () => {
1187
+ if (runtime.baseUrl !== '') return runtime.baseUrl
1188
+ const engineStatus = typeof manager?.status === 'function' ? (manager.status() ?? {}) : {}
1189
+ return normalizeBaseUrl(engineStatus.baseUrl)
1190
+ },
1191
+ session,
1192
+ logger,
1193
+ onChange: () => {
1194
+ try {
1195
+ ctx.emit('chatluna-kb/models')
1196
+ } catch {}
1197
+ }
1198
+ })
1199
+ // 命名函数让 WebUI/路由的 deps 保持与契约一致。
1200
+ const listChatlunaModels = () => modelBridge.listChatlunaModels()
1201
+ const importChatlunaModel = (input) => modelBridge.importChatlunaModel(input)
1202
+ const listWeKnoraModels = () => modelBridge.listWeKnoraModels()
1203
+ async function catalog() {
1204
+ if (catalogCache !== null && Date.now() - catalogCache.at < CATALOG_TTL_MS) return catalogCache.list
1205
+ const list = await client.listKbsRaw()
1206
+ if (!Array.isArray(list)) throw new Error('知识库目录格式异常:listKbsRaw 未返回数组')
1207
+ catalogCache = { at: Date.now(), list }
1208
+ return list
1209
+ }
1210
+
1211
+ async function scopeFor(call) {
1212
+ await waitReady()
1213
+ const scope = await resolveScope(ctx, scopeConfig(), call)
1214
+ const list = await catalog()
1215
+ return {
1216
+ ...scope,
1217
+ readableKbs: canonicalizeSpec(scope.readableKbs, list),
1218
+ writableKbs: canonicalizeSpec(scope.writableKbs, list),
1219
+ manageableKbs: canonicalizeSpec(scope.manageableKbs, list)
1220
+ }
1221
+ }
1222
+
1223
+ // Resolve a requested KB against the caller's whitelist; resolveKbTarget already
1224
+ // searches only visible entries, assertKb re-checks and gives the action name.
1225
+ async function target(requested, scope, action) {
1226
+ const entry = await resolveKbTarget({
1227
+ requested,
1228
+ defaultKb: scope.defaultKb,
1229
+ spec: scope.readableKbs,
1230
+ client
1231
+ })
1232
+ assertKb(scope.readableKbs, entry, action)
1233
+ return entry
1234
+ }
1235
+
1236
+ async function writeTarget(requested, scope, action) {
1237
+ const entry = await resolveKbTarget({
1238
+ requested,
1239
+ defaultKb: scope.defaultKb,
1240
+ spec: scope.writableKbs,
1241
+ client
1242
+ })
1243
+ assertKb(scope.writableKbs, entry, action)
1244
+ return entry
1245
+ }
1246
+
1247
+ async function manageTarget(requested, scope, action) {
1248
+ const entry = await resolveKbTarget({
1249
+ requested,
1250
+ defaultKb: scope.defaultKb,
1251
+ spec: scope.manageableKbs,
1252
+ client
1253
+ })
1254
+ assertKb(scope.manageableKbs, entry, action)
1255
+ return entry
1256
+ }
1257
+
1258
+ const readTool = defineTool({
1259
+ name: 'kb_read',
1260
+ description: 'Read-only knowledge base access, limited to the caller\'s permitted KBs. action=list_kbs lists visible knowledge bases; action=list_docs lists documents of a KB; action=search retrieves chunks (hybrid/semantic/keyword, limit 1-30) with chunk_id, knowledge_id, title, score and a truncated snippet; action=toc returns a document\'s heading tree with chunk ranges; action=read returns a document\'s chunks from `offset` (next_offset included), a named `section`, or, when `query` is set, the best-matching chunks inside that document. Never writes.',
1261
+ locales: {
1262
+ zh: {
1263
+ description:
1264
+ '知识库只读入口,仅限当前会话有权限的知识库。action=list_kbs 列出可见知识库(已按权限过滤);list_docs 列某库文档;search 在库内检索(hybrid/semantic/keyword,limit 1-30),返回 chunk_id、knowledge_id、标题、score 与截断片段;toc 返回文档标题树及分块范围;read 支持 section 按标题读整节、offset/limit 顺序翻页(带 next_offset),或传 query 做文档内关键词召回。不写任何数据。'
1265
+ }
1266
+ },
1267
+ args: readArgs,
1268
+ traits: { effect: 'read', deferred: false },
1269
+ async run(input, call) {
1270
+ const scope = await scopeFor(call)
1271
+ switch (input.action) {
1272
+ case 'list_kbs': {
1273
+ // Same catalog as scopeFor (60s TTL), filtered by the canonical ID spec.
1274
+ const kbs = await catalog()
1275
+ const visible = filterKbs(kbs, scope.readableKbs)
1276
+ return {
1277
+ total: visible.length,
1278
+ truncated: visible.length > LIST_MAX,
1279
+ knowledge_bases: visible.slice(0, LIST_MAX).map((kb) => ({
1280
+ id: kb.id,
1281
+ name: kb.name,
1282
+ description: clip(kb.description, 120)
1283
+ }))
1284
+ }
1285
+ }
1286
+ case 'list_docs': {
1287
+ const entry = await target(input.knowledge_base, scope, 'list_docs')
1288
+ return client.listDocs({ ...input, knowledge_base: entry.id })
1289
+ }
1290
+ case 'search': {
1291
+ const entry = await target(input.knowledge_base, scope, 'search')
1292
+ const ids = Array.isArray(input.knowledge_ids)
1293
+ ? input.knowledge_ids.map((id) => String(id).trim()).filter((id) => id !== '')
1294
+ : []
1295
+ if (ids.length > 0) await assertKnowledgeIDs(ids, scope.readableKbs, client, 'search')
1296
+ return client.search({ ...input, knowledge_base: entry.id })
1297
+ }
1298
+ case 'toc': {
1299
+ const id = need('toc', input.knowledge_id, 'knowledge_id')
1300
+ const meta = await client.getKnowledge(id)
1301
+ assertKnowledge(meta, scope.readableKbs, 'toc')
1302
+ return client.toc(id)
1303
+ }
1304
+ case 'read': {
1305
+ const id = need('read', input.knowledge_id, 'knowledge_id')
1306
+ const meta = await client.getKnowledge(id)
1307
+ assertKnowledge(meta, scope.readableKbs, 'read')
1308
+ return client.readDoc({ ...input, knowledge_id: id })
1309
+ }
1310
+ default:
1311
+ throw new Error(`未知 action:${input.action}(可用 list_kbs / list_docs / search / toc / read)`)
1312
+ }
1313
+ }
1314
+ })
1315
+
1316
+ const writeTool = defineTool({
1317
+ name: 'kb_write',
1318
+ description: 'Add content to a knowledge base the caller may write. action=ingest_file stores an attachment/local document (PDF/Office/HTML, images for OCR, .xmind/.mhtml, and source/config files such as .json/.yaml/.py/.js/.go/.sql/.css, duplicates reported as duplicate); action=ingest_text stores Markdown verbatim; action=ingest_url imports a page or direct file URL. Only call it when the user sends a file, pastes text worth keeping, or asks to remember a link.',
1319
+ locales: {
1320
+ zh: {
1321
+ description:
1322
+ '往有写权限的知识库里写内容。action=ingest_file 入库附件/本地文档(PDF/Office/HTML、图片 OCR、.xmind/.mhtml,以及 .json/.yaml/.py/.js/.go/.sql/.css 等源码/配置,重复内容返回 duplicate);ingest_text 原文存 Markdown;ingest_url 导入网页或文件直链。只在用户发来文件、贴出值得留存的内容或要求记住链接时调用;目标库必须在当前会话的可写白名单内。'
1323
+ }
1324
+ },
1325
+ args: writeArgs,
1326
+ traits: { effect: 'write', deferred: true },
1327
+ async run(input, call) {
1328
+ const scope = await scopeFor(call)
1329
+ switch (input.action) {
1330
+ case 'ingest_file': {
1331
+ need('ingest_file', input.file, 'file')
1332
+ const entry = await writeTarget(input.knowledge_base, scope, 'ingest_file')
1333
+ return client.uploadFile({ ...input, knowledge_base: entry.id })
1334
+ }
1335
+ case 'ingest_text': {
1336
+ need('ingest_text', input.title, 'title')
1337
+ need('ingest_text', input.content, 'content')
1338
+ const entry = await writeTarget(input.knowledge_base, scope, 'ingest_text')
1339
+ return client.ingestText({ ...input, knowledge_base: entry.id })
1340
+ }
1341
+ case 'ingest_url': {
1342
+ need('ingest_url', input.url, 'url')
1343
+ const entry = await writeTarget(input.knowledge_base, scope, 'ingest_url')
1344
+ return client.ingestUrl({ ...input, knowledge_base: entry.id })
1345
+ }
1346
+ default:
1347
+ throw new Error(`未知 action:${input.action}(可用 ingest_file / ingest_text / ingest_url)`)
1348
+ }
1349
+ }
1350
+ })
1351
+
1352
+ const manageTool = defineTool({
1353
+ name: 'kb_manage',
1354
+ description: 'Maintenance on knowledge bases the caller may manage. action=reparse re-runs parsing for one document (knowledge_id) or a batch (knowledge_ids + knowledge_base); action=delete removes one document (knowledge_id) asynchronously and irreversibly — group chats cannot delete, and you must confirm the document title with the user first; action=create_kb creates a new knowledge base (name required, description optional) with the engine default embedding/summary models — direct chat with full manage permission only, always refused in groups.',
1355
+ locales: {
1356
+ zh: {
1357
+ description:
1358
+ '维护有管理权限的知识库。action=reparse 重新解析单份(knowledge_id)或批量(knowledge_ids + knowledge_base);action=delete 异步删除单份文档(不可恢复)——群聊一律禁止删除,且必须在用户明确要求并确认标题后才调用;action=create_kb 新建知识库(name 必填,description 可选),自动绑定引擎默认 Embedding/摘要模型,仅限私聊且具备全库管理权限,群聊一律拒绝。目标库必须在当前会话的可管理白名单内。'
1359
+ }
1360
+ },
1361
+ args: manageArgs,
1362
+ traits: { effect: 'write', deferred: true },
1363
+ async run(input, call) {
1364
+ const scope = await scopeFor(call)
1365
+ switch (input.action) {
1366
+ case 'reparse': {
1367
+ const ids = Array.isArray(input.knowledge_ids)
1368
+ ? input.knowledge_ids.map((id) => String(id).trim()).filter((id) => id !== '')
1369
+ : []
1370
+ const single =
1371
+ typeof input.knowledge_id === 'string' && input.knowledge_id.trim() !== ''
1372
+ ? input.knowledge_id.trim()
1373
+ : ''
1374
+ if (ids.length === 0 && single === '') throw new Error('action=reparse 需要 knowledge_id 或 knowledge_ids')
1375
+ // Single document with no KB hint: derive its KB from metadata and check that.
1376
+ if (ids.length === 0 && String(input.knowledge_base ?? '').trim() === '') {
1377
+ const meta = await client.getKnowledge(single)
1378
+ assertKnowledge(meta, scope.manageableKbs, 'reparse')
1379
+ return client.reparse({ ...input, knowledge_id: single })
1380
+ }
1381
+ const entry = await manageTarget(input.knowledge_base, scope, 'reparse')
1382
+ return client.reparse({ ...input, knowledge_base: entry.id })
1383
+ }
1384
+ case 'delete': {
1385
+ const id = need('delete', input.knowledge_id, 'knowledge_id')
1386
+ if (!canDelete(scope.isDirect)) throw denied('delete is not allowed in group chats')
1387
+ const meta = await client.getKnowledge(id)
1388
+ assertKnowledge(meta, scope.manageableKbs, 'delete')
1389
+ return client.remove({ knowledge_id: id })
1390
+ }
1391
+ case 'create_kb': {
1392
+ // 高危:仅私聊主人(管理白名单含 '*')可建库;群聊/受限规则一律拒绝。
1393
+ if (scope.isDirect !== true) throw denied('create_kb is not allowed in group chats')
1394
+ if (!Array.isArray(scope.manageableKbs) || !scope.manageableKbs.includes('*')) {
1395
+ throw denied('create_kb requires manage permission for all knowledge bases')
1396
+ }
1397
+ const name = need('create_kb', input.name, 'name')
1398
+ const created = await client.createKb({
1399
+ name,
1400
+ description: input.description,
1401
+ embedding_model_id: runtime.embeddingModelId
1402
+ })
1403
+ // 立即失效目录缓存,下一次 list_kbs 必须能看到新库(不等 60s TTL)。
1404
+ catalogCache = null
1405
+ return created
1406
+ }
1407
+ default:
1408
+ throw new Error(`未知 action:${input.action}(可用 reparse / delete / create_kb)`)
1409
+ }
1410
+ }
1411
+ })
1412
+
1413
+ // Compatibility aliases: same schema, always deferred, never executed directly.
1414
+ const alias = (aliasName, targetName, args, locales) =>
1415
+ defineTool({
1416
+ name: aliasName,
1417
+ description: `Compatibility alias for ${targetName}; arguments are forwarded as-is.`,
1418
+ locales,
1419
+ args,
1420
+ traits: { effect: targetName === 'kb_read' ? 'read' : 'write', deferred: true },
1421
+ forward: (forwarded) => ({ name: targetName, args: forwarded }),
1422
+ run() {
1423
+ throw new Error(`${aliasName} 只是 ${targetName} 的兼容别名,应转发执行`)
1424
+ }
1425
+ })
1426
+
1427
+ const readAlias = alias('weknora_read', 'kb_read', readArgs, {
1428
+ zh: { description: 'weknora_read 是 kb_read 的兼容别名,参数原样转发;权限规则与 kb_read 完全一致。' }
1429
+ })
1430
+ const writeAlias = alias('weknora_write', 'kb_write', writeArgs, {
1431
+ zh: { description: 'weknora_write 是 kb_write 的兼容别名,参数原样转发;权限规则与 kb_write 完全一致。' }
1432
+ })
1433
+ const manageAlias = alias('weknora_manage', 'kb_manage', manageArgs, {
1434
+ zh: { description: 'weknora_manage 是 kb_manage 的兼容别名,参数原样转发;权限规则与 kb_manage 完全一致。' }
1435
+ })
1436
+
1437
+ for (const tool of [readTool, writeTool, manageTool, readAlias, writeAlias, manageAlias]) {
1438
+ ctx.effect(() => ctx.tools.define(tool))
1439
+ }
1440
+
1441
+ // ---- 引擎托管(仅 managed-lite):启动异步、失败不抛出到插件加载 --------
1442
+ if (managed) {
1443
+ try {
1444
+ // manager 读扁平键(binaryPath/dataDir/port/...),engine 子对象原样保留以兼容两种读法。
1445
+ // env 由这里统一生成并透传,二进制只监听 127.0.0.1。
1446
+ const env = {
1447
+ ...liteEnv(),
1448
+ ...(config.engine?.env && typeof config.engine.env === 'object' ? config.engine.env : {}),
1449
+ // 端口只认 schema 配置,避免 env 覆盖出监听面。
1450
+ SERVER_PORT: String(enginePort)
1451
+ }
1452
+ manager = createEngineManager(ctx, { ...engineConfig, env })
1453
+ } catch (err) {
1454
+ manager = null
1455
+ runtime.lastError = logError('engine', err)
1456
+ }
1457
+ if (manager !== null) {
1458
+ ctx.effect(() => {
1459
+ void startEngine()
1460
+ })
1461
+ if (typeof ctx.on === 'function') {
1462
+ ctx.on('dispose', () => {
1463
+ try {
1464
+ const pending = manager?.stop?.()
1465
+ if (pending !== null && typeof pending?.catch === 'function') {
1466
+ pending.catch((err) => logError('engine', err))
1467
+ }
1468
+ } catch (err) {
1469
+ logError('engine', err)
1470
+ }
1471
+ })
1472
+ }
1473
+ }
1474
+ }
1475
+
1476
+ // ---- 独立 systemd 服务(仅 systemd):只做健康确认与控制器释放 -----------
1477
+ // 启动时不 systemctl start,插件退出时不 systemctl stop:服务生命周期完全归 systemd。
1478
+ if (systemd) {
1479
+ ctx.effect(() => {
1480
+ void bootSystemd()
1481
+ })
1482
+ if (typeof ctx.on === 'function') {
1483
+ ctx.on('dispose', () => {
1484
+ try {
1485
+ systemdController?.dispose()
1486
+ } catch (err) {
1487
+ logError('systemd', err)
1488
+ }
1489
+ })
1490
+ }
1491
+ }
1492
+
1493
+ // ---- 同源反代 /kb-proxy/* 与 WebUI 状态/操作注册 ------------------------
1494
+ ctx.effect(() => {
1495
+ let dispose
1496
+ try {
1497
+ dispose = registerKbProxy(ctx, {
1498
+ prefix: '/kb-proxy',
1499
+ baseUrl: () => runtime.baseUrl,
1500
+ session,
1501
+ logger
1502
+ })
1503
+ } catch (err) {
1504
+ logError('proxy', err)
1505
+ }
1506
+ return () => {
1507
+ if (typeof dispose === 'function') dispose()
1508
+ }
1509
+ })
1510
+
1511
+ // ---- 安装路由 /kb-admin/*(仅 managed:上传/下载/取消/校验) --------------
1512
+ if (installer !== null) {
1513
+ ctx.effect(() => {
1514
+ let dispose
1515
+ try {
1516
+ dispose = registerInstallRoutes(ctx, {
1517
+ prefix: '/kb-admin',
1518
+ installer,
1519
+ authorize: (context, req) => isWebuiAuthorized(context ?? ctx, req, logger),
1520
+ maxBytes: INSTALL_UPLOAD_MAX,
1521
+ logger
1522
+ })
1523
+ } catch (err) {
1524
+ logError('install-routes', err)
1525
+ }
1526
+ return () => {
1527
+ if (typeof dispose === 'function') dispose()
1528
+ }
1529
+ })
1530
+ }
1531
+
1532
+ // ---- 模型复制路由 /kb-admin/*(ChatLuna 模型列表 / 一次性导入 / WeKnora 列表) ----
1533
+ ctx.effect(() => {
1534
+ let dispose
1535
+ try {
1536
+ dispose = registerModelRoutes(ctx, {
1537
+ prefix: '/kb-admin',
1538
+ authorize: (context, req) => isWebuiAuthorized(context ?? ctx, req, logger),
1539
+ listModels: listChatlunaModels,
1540
+ importModel: importChatlunaModel,
1541
+ listWeKnoraModels,
1542
+ logger
1543
+ })
1544
+ } catch (err) {
1545
+ logError('model-routes', err)
1546
+ }
1547
+ return () => {
1548
+ if (typeof dispose === 'function') dispose()
1549
+ }
1550
+ })
1551
+
1552
+ ctx.effect(() => {
1553
+ let dispose
1554
+ try {
1555
+ dispose = registerKbWebUI(ctx, {
1556
+ // addEntry 需要字符串根 URL(web/client.js 与 index.mjs 同根目录),不是引擎地址。
1557
+ baseUrl: import.meta.url,
1558
+ status: statusSnapshot,
1559
+ rules: readRules,
1560
+ saveRules,
1561
+ start: startManaged,
1562
+ stop: stopManaged,
1563
+ restart: restartManaged,
1564
+ isManaged: () => managed || systemd,
1565
+ // 安装向导(阶段 4):external 只有 detect/saveEmbedding 可用,安装动作会抛 notManaged。
1566
+ installStatus,
1567
+ detect,
1568
+ installRelease,
1569
+ installUrl,
1570
+ installPath,
1571
+ cancelInstall,
1572
+ testEmbedding,
1573
+ saveEmbedding,
1574
+ // 模型复制:列表已脱敏;导入返回 WeKnora 模型 id/维度,不含密钥。
1575
+ listChatlunaModels,
1576
+ importChatlunaModel,
1577
+ listWeKnoraModels
1578
+ })
1579
+ } catch (err) {
1580
+ logError('webui', err)
1581
+ }
1582
+ return () => {
1583
+ if (typeof dispose === 'function') dispose()
1584
+ }
1585
+ })
1586
+ }
1587
+