@onigeya/dsh-kanabo-memory 0.1.0 → 0.1.1

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/providers.js ADDED
@@ -0,0 +1,786 @@
1
+ /**
2
+ * 可配置的三件套:向量、重排、decision 模型(判定模型)。
3
+ *
4
+ * 为什么是「三件套」而不是「一个模型」:它们解决三个完全不同的问题,也按三次独立的方向被
5
+ * 校准过——向量负责把文本放进可比的几何空间,重排(cross-encoder)负责给「查询×候选」这一对
6
+ * 打相关度,decision 模型(Hindsight 叫 decision model / Jev System One)负责回答**带类型的判断**
7
+ * (是/否的概率、量表、多选一),它不写文本。把三者混成一个配置项会让「我换了向量模型,重排也
8
+ * 悄悄坏了」变成排查不了的故障。
9
+ *
10
+ * 三件套各自可填 `{ baseURL, model, apiKey }`(外加各自的调节旋钮),来源优先级固定为:
11
+ * 显式 options > 环境变量 > 只读配置文件
12
+ * Key 只留在闭包里:对外给出的描述一律是 `redact(key)`(前 3 位 + 后 4 位),日志、遥测、错误
13
+ * 消息都不得出现原文。这条在探针里被断言(原始 key 不出现在任何输出行里)。
14
+ *
15
+ * 与 Hindsight 的对应关系(`~/references/hindsight/hindsight-api-slim/hindsight_api/engine/`):
16
+ * - `decision_model.py`:`{model, state, questions}` → `<base>/v1/systemone`,三种题(noul/choice/score);
17
+ * - `search/decision_reranker.py` + `decision_rerank_interface.py`:**逐候选**问一个 noul
18
+ * (KEEP_INSTRUCTIONS),按答案排序;`pruned()` 的剪除阈值 `max(0.2, 0.4×最佳)`;去重用
19
+ * `DEDUP_INSTRUCTIONS` 的「A 与 B 是否同一件事」。
20
+ * 本文件把这三处**原文照搬**(措辞是量出来的,翻译会改掉校准),只把传输层换成 fetch。
21
+ *
22
+ * 降级语义(与仓库既有约定一致):客户端**从不 reject**,一律返回 `{ ok:false, error:{code,message} }`;
23
+ * 调用方据此让对应阶段缺席,召回/写入照常完成。唯一例外是 `required:true` 的 decision 阶段——
24
+ * Hindsight 里它**就是** ranker,ranker 坏了召回的排序就是假的,所以那时抛 `KANABO_RECALL_JUDGE`。
25
+ */
26
+
27
+ import { createHash } from 'node:crypto'
28
+ import { existsSync, readFileSync, statSync } from 'node:fs'
29
+ import { homedir } from 'node:os'
30
+ import { join } from 'node:path'
31
+
32
+ export const PROVIDER_KINDS = Object.freeze(['embeddings', 'rerank', 'decision'])
33
+
34
+ /**
35
+ * 已知向量模型的维度表。库路径与 `createTriviumStore({dim})` 必须在打开库**之前**就知道维度,
36
+ * 而「问一下模型」要一次网络请求、离线时问不到。表里没有的模型必须由用户填 `dim`,取不到就抛 `KANABO_PROVIDER_EMBED_DIM`——绝不猜一个维度去开库。
37
+ */
38
+ export const KNOWN_EMBEDDING_DIMS = Object.freeze({
39
+ 'BAAI/bge-m3': 1024,
40
+ 'Pro/BAAI/bge-m3': 1024,
41
+ 'BAAI/bge-large-zh-v1.5': 1024,
42
+ 'BAAI/bge-large-en-v1.5': 1024,
43
+ 'Qwen/Qwen3-Embedding-0.6B': 1024,
44
+ 'Qwen/Qwen3-Embedding-4B': 2560,
45
+ 'Qwen/Qwen3-Embedding-8B': 4096,
46
+ 'text-embedding-3-small': 1536,
47
+ 'text-embedding-3-large': 3072,
48
+ 'text-embedding-ada-002': 1536,
49
+ })
50
+
51
+ export const ENV_NAMES = Object.freeze({
52
+ configPath: 'KANABO_MEMORY_CONFIG',
53
+ embeddings: Object.freeze({
54
+ baseURL: 'KANABO_EMBED_API_URL',
55
+ model: 'KANABO_EMBED_API_MODEL',
56
+ apiKey: 'KANABO_EMBED_API_KEY',
57
+ apiKeyEnv: 'KANABO_EMBED_API_KEY_ENV',
58
+ dim: 'KANABO_EMBED_API_DIM',
59
+ queryPrefix: 'KANABO_EMBED_QUERY_PREFIX',
60
+ passagePrefix: 'KANABO_EMBED_PASSAGE_PREFIX',
61
+ timeoutMs: 'KANABO_EMBED_API_TIMEOUT_MS',
62
+ batchSize: 'KANABO_EMBED_API_BATCH',
63
+ }),
64
+ rerank: Object.freeze({
65
+ baseURL: 'KANABO_RERANK_BASE_URL',
66
+ model: 'KANABO_RERANK_MODEL',
67
+ apiKey: 'KANABO_RERANK_API_KEY',
68
+ apiKeyEnv: 'KANABO_RERANK_API_KEY_ENV',
69
+ maxCandidates: 'KANABO_RERANK_MAX_CANDIDATES',
70
+ weight: 'KANABO_RERANK_WEIGHT',
71
+ minScore: 'KANABO_RERANK_MIN_SCORE',
72
+ timeoutMs: 'KANABO_RERANK_TIMEOUT_MS',
73
+ }),
74
+ decision: Object.freeze({
75
+ baseURL: 'KANABO_DECISION_BASE_URL',
76
+ model: 'KANABO_DECISION_MODEL',
77
+ apiKey: 'KANABO_DECISION_API_KEY',
78
+ apiKeyEnv: 'KANABO_DECISION_API_KEY_ENV',
79
+ protocol: 'KANABO_DECISION_PROTOCOL',
80
+ maxCandidates: 'KANABO_DECISION_MAX_CANDIDATES',
81
+ minProbability: 'KANABO_DECISION_MIN_PROBABILITY',
82
+ keepBest: 'KANABO_DECISION_KEEP_BEST',
83
+ required: 'KANABO_DECISION_REQUIRED',
84
+ dedupe: 'KANABO_DECISION_DEDUPE',
85
+ dedupeMinScore: 'KANABO_DECISION_DEDUPE_MIN_SCORE',
86
+ dedupeThreshold: 'KANABO_DECISION_DEDUPE_THRESHOLD',
87
+ timeoutMs: 'KANABO_DECISION_TIMEOUT_MS',
88
+ }),
89
+ })
90
+
91
+ /** 配置文件搜索顺序(都**只读**):显式路径 → `~/.config/dsh-kanabo/providers.json`。
92
+ * 不读也不写 `~/.dsh`:那个目录是 DSH 自己的,用户的约定是记忆插件不碰它。 */
93
+ export function configPathCandidates(env = process.env) {
94
+ const explicit = env[ENV_NAMES.configPath]
95
+ if (typeof explicit === 'string' && explicit !== '') return [explicit]
96
+ return [join(homedir(), '.config', 'dsh-kanabo', 'providers.json')]
97
+ }
98
+
99
+ /** 去掉末尾斜杠与 `/v1`:内部一律自己拼 `<base>/v1/<path>`,与 Hindsight 的 client 同一种拼法。 */
100
+ export function normalizeBaseURL(raw) {
101
+ const text = String(raw ?? '').trim()
102
+ if (text === '') return ''
103
+ return text.replace(/\/+$/, '').replace(/\/v1$/i, '')
104
+ }
105
+
106
+ /** 只允许前 3 位 + 后 4 位进日志;短 key 只报长度。 */
107
+ export function redact(value) {
108
+ if (typeof value !== 'string' || value.length === 0) return '<none>'
109
+ if (value.length <= 8) return `<short len=${value.length}>`
110
+ return `${value.slice(0, 3)}…${value.slice(-4)}`
111
+ }
112
+
113
+ function providerError(code, message, detail) {
114
+ const error = new Error(message)
115
+ error.code = code
116
+ if (detail !== undefined) error.details = detail
117
+ return error
118
+ }
119
+
120
+ function positiveNumber(value, fallback) {
121
+ const number = Number(value)
122
+ return Number.isFinite(number) && number > 0 ? number : fallback
123
+ }
124
+
125
+ function unitNumber(value, fallback) {
126
+ const number = Number(value)
127
+ return Number.isFinite(number) && number >= 0 && number <= 1 ? number : fallback
128
+ }
129
+
130
+ function boolOf(value, fallback) {
131
+ if (typeof value === 'boolean') return value
132
+ if (value === '1' || value === 'true' || value === 'yes' || value === 'on') return true
133
+ if (value === '0' || value === 'false' || value === 'no' || value === 'off') return false
134
+ return fallback
135
+ }
136
+
137
+ /**
138
+ * 读配置文件(只读)。损坏的 JSON **不静默当空**:配置写错却悄悄退回默认,会让「我明明配了」
139
+ * 变成排查不了的故障,所以这里返回 `{ error }`,由 `resolveProviders` 记进 `source`。
140
+ */
141
+ export function readConfigFile(env = process.env) {
142
+ for (const path of configPathCandidates(env)) {
143
+ if (!existsSync(path)) continue
144
+ try {
145
+ const parsed = JSON.parse(readFileSync(path, 'utf8'))
146
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
147
+ return { path, config: null, error: '配置文件顶层必须是对象' }
148
+ }
149
+ return { path, config: parsed, error: null }
150
+ } catch (error) {
151
+ return { path, config: null, error: `配置文件不是合法 JSON:${error?.message ?? String(error)}` }
152
+ }
153
+ }
154
+ return { path: null, config: null, error: null }
155
+ }
156
+
157
+ function pick(kind, field, envName, options, fileConfig, fallback) {
158
+ const fromOptions = options?.[field]
159
+ if (fromOptions !== undefined && fromOptions !== null && fromOptions !== '') return fromOptions
160
+ const fromEnv = envName === null ? undefined : process.env[envName]
161
+ if (fromEnv !== undefined && fromEnv !== '') return fromEnv
162
+ const fromFile = fileConfig?.[field]
163
+ if (fromFile !== undefined && fromFile !== null && fromFile !== '') return fromFile
164
+ return fallback
165
+ }
166
+
167
+ /**
168
+ * Key 的解析多一步:`apiKeyEnv` 让用户只在配置里写「用哪个环境变量的 key」,密钥本体不进配置文件。
169
+ * 最后一道回退是 `SILICONFLOW_KEY`——只在端点确实是硅基流动时生效(否则把别家的 key 发到别家端点
170
+ * 就是一个真实的凭据外泄)。
171
+ */
172
+ function resolveApiKey(kind, options, fileConfig) {
173
+ const names = ENV_NAMES[kind]
174
+ const explicitEnvName = pick(kind, 'apiKeyEnv', names.apiKeyEnv, options, fileConfig, null)
175
+ const candidates = []
176
+ if (typeof explicitEnvName === 'string' && explicitEnvName !== '') candidates.push(explicitEnvName)
177
+ candidates.push(names.apiKey)
178
+ if (kind === 'embeddings') candidates.push('KANABO_EMBED_API_KEY')
179
+ const direct = options?.apiKey ?? fileConfig?.apiKey
180
+ if (typeof direct === 'string' && direct !== '') {
181
+ return { key: direct, source: 'options/file apiKey' }
182
+ }
183
+ for (const name of candidates) {
184
+ const value = process.env[name]
185
+ if (typeof value === 'string' && value !== '') return { key: value, source: `env ${name}` }
186
+ }
187
+ const baseURL = normalizeBaseURL(pick(kind, 'baseURL', names.baseURL, options, fileConfig, ''))
188
+ if (baseURL.includes('siliconflow')) {
189
+ for (const name of ['SILICONFLOW_KEY', 'SILICONFLOW_API_KEY']) {
190
+ const value = process.env[name]
191
+ if (typeof value === 'string' && value !== '') return { key: value, source: `env ${name}(硅基流动端点)` }
192
+ }
193
+ }
194
+ return { key: '', source: 'missing' }
195
+ }
196
+
197
+ /**
198
+ * 解析三件套配置。返回**纯数据**(不含 key 原文,只有 `redactedKey` 与 `keySource`),
199
+ * 客户端另行用闭包持有 key——这样任何 `JSON.stringify(resolveProviders())` 都不会泄漏凭据。
200
+ *
201
+ * @param {object} [options] 每层的覆盖,形状同配置文件(`{embeddings, rerank, decision}`,或扁平到单层)
202
+ * @param {object} [options.env] 便于探针注入环境
203
+ */
204
+ export function resolveProviders(options = {}) {
205
+ const file = readConfigFile(process.env)
206
+ const layerOf = (kind) => {
207
+ const nested = options[kind]
208
+ return nested !== null && typeof nested === 'object' ? nested : {}
209
+ }
210
+ const fileLayer = (kind) => (file.config?.[kind] !== null && typeof file.config?.[kind] === 'object' ? file.config[kind] : {})
211
+
212
+ const out = { source: { configFile: file.path, configError: file.error }, embeddings: null, rerank: null, decision: null }
213
+
214
+ {
215
+ const o = layerOf('embeddings')
216
+ const f = fileLayer('embeddings')
217
+ const names = ENV_NAMES.embeddings
218
+ const baseURL = normalizeBaseURL(pick('embeddings', 'baseURL', names.baseURL, o, f, ''))
219
+ const model = String(pick('embeddings', 'model', names.model, o, f, ''))
220
+ const key = resolveApiKey('embeddings', o, f)
221
+ const enabled = baseURL !== '' && model !== ''
222
+ const dimRaw = pick('embeddings', 'dim', names.dim, o, f, null)
223
+ const dimConfigured = Number.isInteger(Number(dimRaw)) && Number(dimRaw) > 0 ? Number(dimRaw) : null
224
+ out.embeddings = {
225
+ kind: 'embeddings',
226
+ enabled,
227
+ baseURL,
228
+ model,
229
+ dim: dimConfigured ?? KNOWN_EMBEDDING_DIMS[model] ?? null,
230
+ dimSource: dimConfigured !== null ? 'config' : (KNOWN_EMBEDDING_DIMS[model] !== undefined ? 'known-model' : 'unknown'),
231
+ queryPrefix: String(pick('embeddings', 'queryPrefix', names.queryPrefix, o, f, '')),
232
+ passagePrefix: String(pick('embeddings', 'passagePrefix', names.passagePrefix, o, f, '')),
233
+ batchSize: Math.max(1, Math.floor(positiveNumber(pick('embeddings', 'batchSize', names.batchSize, o, f, 16), 16))),
234
+ timeoutMs: Math.max(1000, Math.floor(positiveNumber(pick('embeddings', 'timeoutMs', names.timeoutMs, o, f, 20_000), 20_000))),
235
+ redactedKey: redact(key.key),
236
+ keySource: key.source,
237
+ hasKey: key.key !== '',
238
+ }
239
+ }
240
+
241
+ {
242
+ const o = layerOf('rerank')
243
+ const f = fileLayer('rerank')
244
+ const names = ENV_NAMES.rerank
245
+ const baseURL = normalizeBaseURL(pick('rerank', 'baseURL', names.baseURL, o, f, ''))
246
+ const model = String(pick('rerank', 'model', names.model, o, f, ''))
247
+ const key = resolveApiKey('rerank', o, f)
248
+ out.rerank = {
249
+ kind: 'rerank',
250
+ enabled: baseURL !== '' && model !== '',
251
+ baseURL,
252
+ model,
253
+ maxCandidates: Math.max(1, Math.floor(positiveNumber(pick('rerank', 'maxCandidates', names.maxCandidates, o, f, 24), 24))),
254
+ weight: unitNumber(pick('rerank', 'weight', names.weight, o, f, 0.6), 0.6),
255
+ minScore: unitNumber(pick('rerank', 'minScore', names.minScore, o, f, 0), 0),
256
+ timeoutMs: Math.max(500, Math.floor(positiveNumber(pick('rerank', 'timeoutMs', names.timeoutMs, o, f, 8_000), 8_000))),
257
+ redactedKey: redact(key.key),
258
+ keySource: key.source,
259
+ hasKey: key.key !== '',
260
+ }
261
+ }
262
+
263
+ {
264
+ const o = layerOf('decision')
265
+ const f = fileLayer('decision')
266
+ const names = ENV_NAMES.decision
267
+ const baseURL = normalizeBaseURL(pick('decision', 'baseURL', names.baseURL, o, f, ''))
268
+ const model = String(pick('decision', 'model', names.model, o, f, ''))
269
+ const key = resolveApiKey('decision', o, f)
270
+ const protocol = String(pick('decision', 'protocol', names.protocol, o, f, 'systemone'))
271
+ out.decision = {
272
+ kind: 'decision',
273
+ enabled: baseURL !== '' && model !== '',
274
+ baseURL,
275
+ model,
276
+ protocol: protocol === 'chat' ? 'chat' : 'systemone',
277
+ maxCandidates: Math.max(1, Math.floor(positiveNumber(pick('decision', 'maxCandidates', names.maxCandidates, o, f, 12), 12))),
278
+ minProbability: unitNumber(pick('decision', 'minProbability', names.minProbability, o, f, 0.2), 0.2),
279
+ keepBest: boolOf(pick('decision', 'keepBest', names.keepBest, o, f, true), true),
280
+ required: boolOf(pick('decision', 'required', names.required, o, f, false), false),
281
+ dedupe: boolOf(pick('decision', 'dedupe', names.dedupe, o, f, true), true),
282
+ dedupeMinScore: unitNumber(pick('decision', 'dedupeMinScore', names.dedupeMinScore, o, f, 0.8), 0.8),
283
+ dedupeThreshold: unitNumber(pick('decision', 'dedupeThreshold', names.dedupeThreshold, o, f, 0.5), 0.5),
284
+ timeoutMs: Math.max(500, Math.floor(positiveNumber(pick('decision', 'timeoutMs', names.timeoutMs, o, f, 8_000), 8_000))),
285
+ redactedKey: redact(key.key),
286
+ keySource: key.source,
287
+ hasKey: key.key !== '',
288
+ }
289
+ }
290
+
291
+ return out
292
+ }
293
+
294
+ /**
295
+ * 向量 profile 的稳定标识:`local-e5-384` 或 `api-<model>-<dim>`。
296
+ *
297
+ * 它同时决定**库文件名的后缀**(见 `store-trivium.js#dbPathFor`):384 维的本地库与 1024 维的
298
+ * API 库绝不能是同一个文件——TriviumDB 用错维度 open 会直接 `TDB_DIMENSION_MISMATCH`,而把两种
299
+ * 维度混进一个库更是灾难。默认(未配置 API)保持 `local-e5-384` 且**不加后缀**,旧库原地可用。
300
+ */
301
+ export function profileOf(embeddings) {
302
+ if (embeddings === null || embeddings === undefined || embeddings.enabled !== true) {
303
+ return { id: 'local-e5-384', provider: 'local', model: 'Xenova/multilingual-e5-small', dim: 384 }
304
+ }
305
+ const dim = embeddings.dim ?? 'auto'
306
+ return { id: `api-${String(embeddings.model)}-${dim}`, provider: 'api', model: embeddings.model, dim: embeddings.dim ?? null }
307
+ }
308
+
309
+ /** 文件名安全的后缀:模型名里的 `/`、`@` 等一律压成 `_`;默认 profile 返回空串(旧文件名不变)。 */
310
+ export function profileSuffix(profile) {
311
+ if (profile === null || profile === undefined || profile.id === 'local-e5-384') return ''
312
+ return `__${String(profile.id).replace(/[^A-Za-z0-9._-]+/g, '_')}`
313
+ }
314
+
315
+ /**
316
+ * 向量维度:API 模式下必须确定(配置 > 已知表);取不到就抛,绝不猜。本地模式恒为 384。
317
+ */
318
+ export function embeddingDimOf(embeddings) {
319
+ const local = 384
320
+ if (embeddings === null || embeddings === undefined || embeddings.enabled !== true) return local
321
+ if (Number.isInteger(embeddings.dim) && embeddings.dim > 0) return embeddings.dim
322
+ throw providerError(
323
+ 'KANABO_PROVIDER_EMBED_DIM',
324
+ `向量模型 ${embeddings.model} 的维度未知:请设置 ${ENV_NAMES.embeddings.dim} 或在配置里写 "dim"。`
325
+ + '(库的向量宽度必须在打开前确定;猜一个维度会让整库不可用,所以这里失败关闭。)',
326
+ { model: embeddings.model, baseURL: embeddings.baseURL })
327
+ }
328
+
329
+ async function postJSON(url, body, { apiKey, timeoutMs, fetchImpl = globalThis.fetch } = {}, label = 'request') {
330
+ if (typeof fetchImpl !== 'function') {
331
+ return { ok: false, error: { code: 'KANABO_PROVIDER_FETCH', message: '当前运行时没有 fetch 实现。' } }
332
+ }
333
+ const started = Date.now()
334
+ const headers = { 'content-type': 'application/json' }
335
+ if (typeof apiKey === 'string' && apiKey !== '') headers.authorization = `Bearer ${apiKey}`
336
+ let response
337
+ try {
338
+ response = await fetchImpl(url, {
339
+ method: 'POST',
340
+ headers,
341
+ body: JSON.stringify(body),
342
+ signal: AbortSignal.timeout(timeoutMs),
343
+ })
344
+ } catch (error) {
345
+ const timedOut = error?.name === 'TimeoutError' || error?.name === 'AbortError'
346
+ return {
347
+ ok: false,
348
+ ms: Date.now() - started,
349
+ error: {
350
+ code: timedOut ? 'KANABO_PROVIDER_TIMEOUT' : 'KANABO_PROVIDER_NETWORK',
351
+ message: `${label} 失败:${error?.message ?? String(error)}`,
352
+ },
353
+ }
354
+ }
355
+ let text = ''
356
+ try {
357
+ text = await response.text()
358
+ } catch (error) {
359
+ return { ok: false, ms: Date.now() - started, httpStatus: response.status, error: { code: 'KANABO_PROVIDER_BODY', message: String(error?.message ?? error) } }
360
+ }
361
+ let payload = null
362
+ try {
363
+ payload = text === '' ? null : JSON.parse(text)
364
+ } catch {
365
+ payload = null
366
+ }
367
+ if (!response.ok) {
368
+ const message = payload?.message ?? payload?.error?.message ?? payload?.detail ?? text.slice(0, 400)
369
+ return {
370
+ ok: false,
371
+ ms: Date.now() - started,
372
+ httpStatus: response.status,
373
+ error: {
374
+ code: response.status === 401 || response.status === 403 ? 'KANABO_PROVIDER_AUTH' : 'KANABO_PROVIDER_HTTP',
375
+ message: `${label} 返回 HTTP ${response.status}:${String(message).slice(0, 400)}`,
376
+ },
377
+ }
378
+ }
379
+ return { ok: true, ms: Date.now() - started, httpStatus: response.status, payload }
380
+ }
381
+
382
+ /**
383
+ * 向量客户端:形状与 `embed.js#createEmbedder` 的 provider **完全同构**
384
+ * (`{ id, dim, load(), embed(texts), close() }`),所以嵌入子进程可以原样换掉本地 ONNX provider。
385
+ *
386
+ * 与 OpenAI 的 `dimensions` 参数刻意分开:有的端点(硅基流动的 bge-m3)收到 `dimensions` 直接 400,
387
+ * 而它本来就不支持降维——只有显式 `sendDimensions:true` 才带上,默认不带。
388
+ */
389
+ export function createEmbeddingProvider(config, options = {}) {
390
+ const baseURL = normalizeBaseURL(config?.baseURL ?? '')
391
+ const model = String(config?.model ?? '')
392
+ const apiKey = String(options.apiKey ?? '')
393
+ const dim = Number.isInteger(config?.dim) && config.dim > 0 ? config.dim : null
394
+ const timeoutMs = Math.max(1000, Math.floor(Number(config?.timeoutMs ?? 20_000)))
395
+ const sendDimensions = options.sendDimensions === true
396
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch
397
+ const label = `${baseURL}/v1/embeddings`
398
+ let observedDim = dim
399
+
400
+ const provider = {
401
+ id: `api:${model}`,
402
+ dim: dim ?? 0,
403
+ modelId: model,
404
+ async load() {
405
+ if (baseURL === '' || model === '') {
406
+ throw providerError('KANABO_EMBED_PROVIDER_UNAVAILABLE', '向量 API 未配置:需要 baseURL 与 model。')
407
+ }
408
+ if (apiKey === '') {
409
+ throw providerError('KANABO_EMBED_PROVIDER_UNAVAILABLE', `向量 API 缺少 key:设置 ${ENV_NAMES.embeddings.apiKey} 或用 apiKeyEnv 指到一个环境变量。`)
410
+ }
411
+ },
412
+ async embed(texts) {
413
+ const body = { model, input: texts }
414
+ if (sendDimensions && provider.dim > 0) body.dimensions = provider.dim
415
+ const result = await postJSON(label, body, { apiKey, timeoutMs, fetchImpl }, 'embeddings')
416
+ if (!result.ok) throw providerError(result.error.code, result.error.message)
417
+ const rows = Array.isArray(result.payload?.data) ? result.payload.data : []
418
+ const vectors = texts.map((_, index) => {
419
+ const embedding = rows[index]?.embedding
420
+ if (!Array.isArray(embedding) || embedding.length === 0) {
421
+ throw providerError('KANABO_EMBED_PROVIDER_ERROR', `向量 API 第 ${index} 条没有 embedding。`)
422
+ }
423
+ return embedding.map((value) => Number(value))
424
+ })
425
+ const width = vectors[0]?.length ?? 0
426
+ if (observedDim === null || observedDim === 0) {
427
+ observedDim = width
428
+ provider.dim = width
429
+ } else if (width !== observedDim) {
430
+ throw providerError(
431
+ 'KANABO_EMBED_DIMENSION_MISMATCH',
432
+ `向量模型 ${model} 返回 ${width} 维,配置/库要求 ${observedDim} 维;拒绝写入错宽向量。`)
433
+ }
434
+ return vectors
435
+ },
436
+ close() {},
437
+ }
438
+ return provider
439
+ }
440
+
441
+ /**
442
+ * 重排客户端:`POST <base>/v1/rerank { model, query, documents, top_n }`。
443
+ * 返回与 `documents` 等长的分数数组(下标对齐输入),**不是**排序后的列表——排序留在召回侧做,
444
+ * 那里才知道 RRF 的顺序(并用它打破平分)。
445
+ */
446
+ export function createRerankClient(config, options = {}) {
447
+ const baseURL = normalizeBaseURL(config?.baseURL ?? '')
448
+ const model = String(config?.model ?? '')
449
+ const apiKey = String(options.apiKey ?? '')
450
+ const timeoutMs = Math.max(500, Math.floor(Number(config?.timeoutMs ?? 8_000)))
451
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch
452
+ const enabled = config?.enabled === true && baseURL !== '' && model !== ''
453
+
454
+ return {
455
+ kind: 'rerank',
456
+ enabled,
457
+ model,
458
+ baseURL,
459
+ /** @returns {Promise<{ok:true, scores:number[], ms:number}|{ok:false, error:object, ms:number}>} */
460
+ async score(query, documents) {
461
+ if (!enabled) return { ok: false, ms: 0, error: { code: 'KANABO_RERANK_DISABLED', message: '重排未配置。' } }
462
+ if (apiKey === '') return { ok: false, ms: 0, error: { code: 'KANABO_RERANK_AUTH', message: '重排缺少 key。' } }
463
+ const docs = documents.map((text) => String(text ?? ''))
464
+ if (docs.length === 0) return { ok: true, scores: [], ms: 0 }
465
+ const result = await postJSON(`${baseURL}/v1/rerank`, {
466
+ model,
467
+ query: String(query ?? ''),
468
+ documents: docs,
469
+ top_n: docs.length,
470
+ return_documents: false,
471
+ }, { apiKey, timeoutMs, fetchImpl }, 'rerank')
472
+ if (!result.ok) return { ok: false, ms: result.ms, error: result.error }
473
+ const rows = Array.isArray(result.payload?.results) ? result.payload.results : []
474
+ if (rows.length === 0) {
475
+ return { ok: false, ms: result.ms, error: { code: 'KANABO_RERANK_SHAPE', message: '重排响应里没有 results。' } }
476
+ }
477
+ const scores = new Array(docs.length).fill(0)
478
+ for (const row of rows) {
479
+ const index = Number(row?.index)
480
+ const score = Number(row?.relevance_score ?? row?.score)
481
+ if (!Number.isInteger(index) || index < 0 || index >= docs.length) continue
482
+ if (!Number.isFinite(score)) continue
483
+ scores[index] = Math.max(0, Math.min(1, score))
484
+ }
485
+ return { ok: true, scores, ms: result.ms }
486
+ },
487
+ }
488
+ }
489
+
490
+ /**
491
+ * Hindsight 的原话(`decision_rerank_interface.py`):逐候选问的「帮不帮忙」问题、去重问题。
492
+ * 措辞是量出来的——`KEEP_INSTRUCTIONS` 在同一个候选池上把想要的候选抬到 0.74(换成
493
+ * 「是否包含回答问题所需的信息」只有 0.59),所以这里原文保留,不翻译。
494
+ */
495
+ export const KEEP_INSTRUCTIONS = 'Showing this memory to someone answering the question would help them, rather than distract them.'
496
+ export const DEDUP_INSTRUCTIONS = 'Memory B is a repeat of Memory A.'
497
+ /** Hindsight 的剪除线:低于 `max(0.2, 0.4×最佳)` 判为「没帮助」;最佳候选永远保留。 */
498
+ export const PRUNE_BELOW = 0.2
499
+ export const PRUNE_BELOW_BEST = 0.4
500
+
501
+ /**
502
+ * decision 模型客户端。两种协议,同一个接口:
503
+ * - `systemone`(Jev / 硅基流动的 SemIf、Kev-4B):`POST <base>/v1/systemone {model, state, questions}`;
504
+ * - `chat`:普通的 `POST <base>/v1/chat/completions`,要求模型只回一个 JSON 对象 `{键: 0..1}`。
505
+ *
506
+ * 为什么两种都要:用户可能配 SemIf(只有 System One),也可能配一个普通聊天模型当判定器。
507
+ * 两者的**调用形状完全不同**,所以协议是配置项而不是猜出来的——猜测的代价是一次 400 和一条
508
+ * 「Model does not exist」,那正是我们调试时踩过的坑。
509
+ */
510
+ export function createDecisionClient(config, options = {}) {
511
+ const baseURL = normalizeBaseURL(config?.baseURL ?? '')
512
+ const model = String(config?.model ?? '')
513
+ const apiKey = String(options.apiKey ?? '')
514
+ const protocol = config?.protocol === 'chat' ? 'chat' : 'systemone'
515
+ const timeoutMs = Math.max(500, Math.floor(Number(config?.timeoutMs ?? 8_000)))
516
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch
517
+ const enabled = config?.enabled === true && baseURL !== '' && model !== ''
518
+
519
+ return {
520
+ kind: 'decision',
521
+ enabled,
522
+ model,
523
+ baseURL,
524
+ protocol,
525
+ /**
526
+ * 问一批 noul 题。
527
+ * @param {string} state 问题与共享上下文(只出现一次;每个候选各自成题)
528
+ * @param {Array<{key:string, instructions:string|object}>} questions
529
+ * @returns {Promise<{ok:true, probabilities:Record<string, number>, ms:number, usage:object|null}|{ok:false, error:object, ms:number}>}
530
+ */
531
+ async judge(state, questions) {
532
+ if (!enabled) return { ok: false, ms: 0, error: { code: 'KANABO_DECISION_DISABLED', message: 'decision 模型未配置。' } }
533
+ if (apiKey === '') return { ok: false, ms: 0, error: { code: 'KANABO_DECISION_AUTH', message: 'decision 缺少 key。' } }
534
+ if (questions.length === 0) return { ok: true, probabilities: {}, ms: 0, usage: null }
535
+ if (protocol === 'chat') return await askChat(state, questions)
536
+ return await askSystemOne(state, questions)
537
+ },
538
+ }
539
+
540
+ async function askSystemOne(state, questions) {
541
+ const body = {
542
+ model,
543
+ state,
544
+ questions: Object.fromEntries(questions.map((q) => [q.key, { type: 'noul', instructions: q.instructions }])),
545
+ }
546
+ const result = await postJSON(`${baseURL}/v1/systemone`, body, { apiKey, timeoutMs, fetchImpl }, 'systemone')
547
+ if (!result.ok) return { ok: false, ms: result.ms, error: result.error }
548
+ const answers = result.payload?.answers
549
+ if (answers === null || typeof answers !== 'object') {
550
+ return { ok: false, ms: result.ms, error: { code: 'KANABO_DECISION_SHAPE', message: 'systemone 响应里没有 answers。' } }
551
+ }
552
+ const probabilities = {}
553
+ let answered = 0
554
+ for (const question of questions) {
555
+ const answer = answers[question.key]
556
+ const value = Number(answer?.noul)
557
+ if (!Number.isFinite(value)) continue
558
+ probabilities[question.key] = Math.max(0, Math.min(1, value))
559
+ answered += 1
560
+ }
561
+ if (answered === 0) {
562
+ return { ok: false, ms: result.ms, error: { code: 'KANABO_DECISION_SHAPE', message: 'systemone 没有返回任何 noul 答案。' } }
563
+ }
564
+ return { ok: true, probabilities, ms: result.ms, usage: result.payload?.usage ?? null }
565
+ }
566
+
567
+ /**
568
+ * 普通聊天模型的判定:一次请求问完所有候选,要求只回 JSON 对象。
569
+ * 解析失败按**整批失败**处理(而不是把缺的键当成 0——那会把「模型没答」说成「不相关」,
570
+ * Hindsight 对此的注释原文:an unanswered question is not a "no")。
571
+ */
572
+ async function askChat(state, questions) {
573
+ const listing = questions
574
+ .map((q) => `- ${q.key}: ${typeof q.instructions === 'string' ? q.instructions : JSON.stringify(q.instructions)}`)
575
+ .join('\n')
576
+ const body = {
577
+ model,
578
+ temperature: 0,
579
+ messages: [
580
+ {
581
+ role: 'system',
582
+ content: 'You answer judgement questions about a memory. Reply with ONE JSON object and nothing else: '
583
+ + 'keys exactly as given, values are probabilities in [0,1] that the answer is "yes".',
584
+ },
585
+ { role: 'user', content: `${state}\n\nQuestions:\n${listing}\n\nReply with the JSON object now.` },
586
+ ],
587
+ }
588
+ const result = await postJSON(`${baseURL}/v1/chat/completions`, body, { apiKey, timeoutMs, fetchImpl }, 'chat')
589
+ if (!result.ok) return { ok: false, ms: result.ms, error: result.error }
590
+ const content = result.payload?.choices?.[0]?.message?.content
591
+ if (typeof content !== 'string') {
592
+ return { ok: false, ms: result.ms, error: { code: 'KANABO_DECISION_SHAPE', message: 'chat 响应里没有文本内容。' } }
593
+ }
594
+ const match = /\{[\s\S]*\}/.exec(content)
595
+ let parsed = null
596
+ try {
597
+ parsed = match === null ? null : JSON.parse(match[0])
598
+ } catch {
599
+ parsed = null
600
+ }
601
+ if (parsed === null || typeof parsed !== 'object') {
602
+ return { ok: false, ms: result.ms, error: { code: 'KANABO_DECISION_SHAPE', message: 'chat 响应不是合法 JSON 对象。' } }
603
+ }
604
+ const probabilities = {}
605
+ for (const question of questions) {
606
+ const value = Number(parsed[question.key])
607
+ if (Number.isFinite(value)) probabilities[question.key] = Math.max(0, Math.min(1, value))
608
+ }
609
+ if (Object.keys(probabilities).length === 0) {
610
+ return { ok: false, ms: result.ms, error: { code: 'KANABO_DECISION_SHAPE', message: 'chat 响应里没有任何已知题号。' } }
611
+ }
612
+ return { ok: true, probabilities, ms: result.ms, usage: result.payload?.usage ?? null }
613
+ }
614
+ }
615
+
616
+ /**
617
+ * Hindsight `scores()` + `pruned()` 的移植:分数是**名次**(最佳 1.0,往下每名少 1/n),
618
+ * 低于 `max(minProbability, 0.4×最佳)` 的判为没帮助,分数记 0(即被剪除),最佳候选永远保留。
619
+ */
620
+ export function rankByKeep(values, options = {}) {
621
+ const n = values.length
622
+ if (n === 0) return { scores: [], order: [], kept: [], dropped: [], floor: 0, best: 0 }
623
+ const order = values.map((_, index) => index)
624
+ .sort((left, right) => (values[right] ?? 0) - (values[left] ?? 0) || left - right)
625
+ const best = values[order[0]] ?? 0
626
+ const floor = Math.max(unitNumber(options.minProbability, PRUNE_BELOW), PRUNE_BELOW_BEST * best)
627
+ const keepBest = options.keepBest !== false
628
+ const scores = new Array(n).fill(0)
629
+ const kept = []
630
+ const dropped = []
631
+ order.forEach((index, position) => {
632
+ scores[index] = (n - position) / n
633
+ if ((keepBest && position === 0) || (values[index] ?? 0) >= floor) {
634
+ kept.push(index)
635
+ } else {
636
+ dropped.push(index)
637
+ scores[index] = 0
638
+ }
639
+ })
640
+ return { scores, order, kept, dropped, floor, best }
641
+ }
642
+
643
+ /** 三件套的一句话摘要(日志与遥测用;key 只有 redacted 形态)。 */
644
+ export function describeProviders(providers) {
645
+ const one = (row) => ({
646
+ enabled: row.enabled === true,
647
+ baseURL: row.baseURL || null,
648
+ model: row.model || null,
649
+ key: row.redactedKey,
650
+ keySource: row.keySource,
651
+ ...(row.dim === undefined ? {} : { dim: row.dim, dimSource: row.dimSource }),
652
+ ...(row.protocol === undefined ? {} : { protocol: row.protocol }),
653
+ })
654
+ return {
655
+ configFile: providers?.source?.configFile ?? null,
656
+ configError: providers?.source?.configError ?? null,
657
+ embeddings: providers?.embeddings === null || providers?.embeddings === undefined ? null : one(providers.embeddings),
658
+ rerank: providers?.rerank === null || providers?.rerank === undefined ? null : one(providers.rerank),
659
+ decision: providers?.decision === null || providers?.decision === undefined ? null : one(providers.decision),
660
+ }
661
+ }
662
+
663
+ export default resolveProviders
664
+ // ---------------------------------------------------------------------------
665
+ // 进程内缓存与当前 profile
666
+ // ---------------------------------------------------------------------------
667
+
668
+ const ALL_ENV_NAMES = [
669
+ ENV_NAMES.configPath,
670
+ ...Object.values(ENV_NAMES.embeddings),
671
+ ...Object.values(ENV_NAMES.rerank),
672
+ ...Object.values(ENV_NAMES.decision),
673
+ ]
674
+
675
+ let CACHED = null
676
+
677
+ function envSignature() {
678
+ const env = ALL_ENV_NAMES.map((name) => `${name}=${process.env[name] ?? ''}`).join('\u0001')
679
+ const path = configPathCandidates()[0] ?? ''
680
+ let stamp = 'none'
681
+ try {
682
+ if (path !== '') stamp = String(statSync(path).mtimeMs)
683
+ } catch {
684
+ stamp = 'missing'
685
+ }
686
+ return createHash('sha256').update(`${env}\u0000${path}\u0000${stamp}`).digest('hex')
687
+ }
688
+
689
+ /** 解析并缓存;环境变量或配置路径一变就重解(探针需要这个语义来在同一进程里切换配置)。 */
690
+ export function activeProviders() {
691
+ const signature = envSignature()
692
+ if (CACHED !== null && CACHED.signature === signature) return CACHED.providers
693
+ CACHED = { signature, providers: resolveProviders() }
694
+ return CACHED.providers
695
+ }
696
+
697
+ /** 当前向量的有效维度;API 模式取不到就抛(失败关闭,绝不猜一个维度去开库)。 */
698
+ export function activeEmbeddingDim() {
699
+ return embeddingDimOf(activeProviders().embeddings)
700
+ }
701
+
702
+ /** 当前向量前缀:本地 e5 是 `query: ` / `passage: `;bge-m3 等 API 模型默认不加前缀。 */
703
+ export function activeEmbeddingPrefixes() {
704
+ const embeddings = activeProviders().embeddings
705
+ if (embeddings === null || embeddings.enabled !== true) return { query: 'query: ', passage: 'passage: ' }
706
+ return { query: embeddings.queryPrefix, passage: embeddings.passagePrefix }
707
+ }
708
+
709
+ /** 当前 profile(库文件名后缀的唯一来源)。 */
710
+ export function activeProfile() {
711
+ return profileOf(activeProviders().embeddings)
712
+ }
713
+
714
+ // ---------------------------------------------------------------------------
715
+ // Hindsight 的题面构造:措辞原文照搬,只把「问谁」换成 systemone 的 questions
716
+ // ---------------------------------------------------------------------------
717
+
718
+ /** 逐候选的 KEEP 题:每个候选单独成题,问题与共享上下文(query)只进 state 一次。 */
719
+ export function keepQuestion(slot, memory) {
720
+ return { key: `m${slot}`, instructions: { task: KEEP_INSTRUCTIONS, memory: String(memory ?? '') } }
721
+ }
722
+
723
+ /** 判定的 state:问题本身 + 共享上下文(recall 的日期与工作区 framing 只出现一次)。 */
724
+ export function judgeState(query, sharedContext = '') {
725
+ const question = String(query ?? '')
726
+ const shared = String(sharedContext ?? '')
727
+ return shared === '' ? `Question: ${question}` : `${shared}\n\nQuestion: ${question}`
728
+ }
729
+
730
+ /** KEEP 答案(probabilities 按 key 索引、order 与候选对齐)→ 名次分与剪除结果。 */
731
+ export function rankAnswers(probabilities, keys, options = {}) {
732
+ const values = keys.map((key) => {
733
+ const value = Number(probabilities?.[key])
734
+ return Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0
735
+ })
736
+ return rankByKeep(values, options)
737
+ }
738
+
739
+
740
+ /** 嵌入子进程的传输配置:本地模式返回 null;API 模式带**原文 key**(只在 spawn 的子进程 env 里传递)。 */
741
+ export function embeddingTransport(config) {
742
+ const embeddings = config ?? activeProviders().embeddings
743
+ if (embeddings === null || embeddings.enabled !== true) return null
744
+ const fileLayer = readConfigFile().config?.embeddings
745
+ const key = resolveApiKey('embeddings', {}, fileLayer !== null && typeof fileLayer === 'object' ? fileLayer : {})
746
+ return {
747
+ kind: 'api',
748
+ baseURL: embeddings.baseURL,
749
+ model: embeddings.model,
750
+ dim: embeddingDimOf(embeddings),
751
+ apiKey: key.key,
752
+ timeoutMs: embeddings.timeoutMs,
753
+ batchSize: embeddings.batchSize,
754
+ queryPrefix: embeddings.queryPrefix,
755
+ passagePrefix: embeddings.passagePrefix,
756
+ }
757
+ }
758
+
759
+
760
+ function fileLayerOf(kind) {
761
+ const config = readConfigFile().config
762
+ const layer = config === null ? null : config[kind]
763
+ return layer !== null && typeof layer === 'object' ? layer : {}
764
+ }
765
+
766
+ /** 三件套客户端:key 只进各自闭包;返回的对象可以安全序列化(只有 model/baseURL/redacted)。 */
767
+ export function createModelClients(config) {
768
+ const providers = config ?? activeProviders()
769
+ const embeddings = providers.embeddings !== null && providers.embeddings.enabled === true
770
+ ? createEmbeddingProvider(providers.embeddings, { apiKey: resolveApiKey('embeddings', {}, fileLayerOf('embeddings')).key })
771
+ : null
772
+ const rerank = providers.rerank !== null && providers.rerank.enabled === true
773
+ ? createRerankClient(providers.rerank, { apiKey: resolveApiKey('rerank', {}, fileLayerOf('rerank')).key })
774
+ : null
775
+ const decision = providers.decision !== null && providers.decision.enabled === true
776
+ ? createDecisionClient(providers.decision, { apiKey: resolveApiKey('decision', {}, fileLayerOf('decision')).key })
777
+ : null
778
+ return {
779
+ embeddings,
780
+ rerank,
781
+ decision,
782
+ described: describeProviders(providers),
783
+ config: providers,
784
+ profile: profileOf(providers.embeddings),
785
+ }
786
+ }