dsh-knit 0.22.0 → 0.23.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/CHANGELOG.md +210 -3
- package/README.en.md +38 -37
- package/README.md +27 -28
- package/SECURITY.md +14 -5
- package/package.json +5 -3
- package/src/client/client.js +575 -132
- package/src/host/context.js +42 -3
- package/src/host/index.js +196 -7
- package/src/host/semantic.js +465 -0
- package/src/host/tool.js +44 -1
- package/test/client.test.mjs +767 -248
- package/test/harness.mjs +3 -1
- package/test/host-http.test.mjs +23 -0
- package/test/hybrid-eval.test.mjs +184 -0
- package/test/hybrid-retrieval.test.mjs +313 -0
- package/test/retrieval-corpus.mjs +379 -0
- package/test/retrieval-eval.mjs +231 -0
- package/test/semantic.test.mjs +257 -0
- package/test/tool.test.mjs +59 -4
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* v0.23 · **可选混合检索**(Phase A)—— provider 接口 + 有界语义候选 + 回退叙事。
|
|
3
|
+
*
|
|
4
|
+
* 这一层回答的问题只有一句:**「在默认词法之外,语义候选能不能被有界地算出来,
|
|
5
|
+
* 而且默认路径一分钱都不花」**。它**不改**三层分层、**不加** `provenance` 新值、
|
|
6
|
+
* **不往包里塞任何东西** —— 那是 Phase B 的事(方案 §11)。
|
|
7
|
+
*
|
|
8
|
+
* 五条硬约束(方案 §3 / §4 / §6):
|
|
9
|
+
*
|
|
10
|
+
* 1. **默认零调用**:没有配置、或调用方要的是词法模式时,**一次 provider 调用都不发**
|
|
11
|
+
* (连探测也不发)—— 判据 1。
|
|
12
|
+
* 2. **有界**:每轮最多新嵌入 `SEM_EMBED_PER_PASS` 篇;候选最多 `SEM_TOPK` 条(判据 4)。
|
|
13
|
+
* 3. **失败明着回退**:任何失败都收敛成一个 `reason`
|
|
14
|
+
* (`no-provider` / `probe-failed` / `timeout` / `bad-response` / `no-query`),
|
|
15
|
+
* 绝不抛进检索路径、绝不伪装成「混合成功」(判据 5)。
|
|
16
|
+
* 4. **零依赖**:只用内置 `fetch`(且**必须**由调用方注入,便于测试 —— 见 §4 的可测接缝)。
|
|
17
|
+
* 5. **不存正文**:嵌入输入只有 `title + summary`(复用路径上 `head`/`body` 都是空串,
|
|
18
|
+
* 方案 §5.1)。向量只活在进程内的有界缓存里;**持久化向量留给 Phase B**。
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { headHashOf } from './index-store.js'
|
|
22
|
+
|
|
23
|
+
/** 存储单元名(与 `knit_control` / `knit_index` 各开各的)。 */
|
|
24
|
+
export const SEMANTIC_UNIT = 'knit_semantic'
|
|
25
|
+
/** 单元版本。 */
|
|
26
|
+
export const SEMANTIC_VERSION = 1
|
|
27
|
+
/** Phase A 只有一张表:provider 配置(全局一条,不按工作区)。 */
|
|
28
|
+
export const SEMANTIC_TABLES = ['config']
|
|
29
|
+
/** 配置记录的键(全局单例;unit 是 `single` 布局,键只是不透明字符串)。 */
|
|
30
|
+
export const SEMANTIC_CONFIG_KEY = 'provider'
|
|
31
|
+
|
|
32
|
+
/** 支持的两种协议(**够用就好**,不做通用适配层)。 */
|
|
33
|
+
export const SEMANTIC_KINDS = ['ollama', 'openai-compatible']
|
|
34
|
+
|
|
35
|
+
/** 每轮最多新嵌入几篇(有界;与 `INDEX_VERIFY_PER_PASS = 8` 同一条纪律)。 */
|
|
36
|
+
export const SEM_EMBED_PER_PASS = 8
|
|
37
|
+
/** 语义候选上限(占位符:**由 Phase C 的消融定**,方案 §5.2 明确「不许先拍一个数」)。 */
|
|
38
|
+
export const SEM_TOPK = 24
|
|
39
|
+
/** 相似度下限(同样只是 Phase A 的计数阈值,不是排序依据)。 */
|
|
40
|
+
export const SEM_MIN_SIM = 0.35
|
|
41
|
+
/** 进程内向量缓存条数上限(Phase A 不落盘)。 */
|
|
42
|
+
export const SEM_CACHE_MAX = 2000
|
|
43
|
+
/** 探测结果在进程内的复用时长。 */
|
|
44
|
+
export const SEM_PROBE_TTL_MS = 60_000
|
|
45
|
+
/** 默认超时(毫秒)。 */
|
|
46
|
+
export const SEM_PROBE_TIMEOUT_MS = 1500
|
|
47
|
+
export const SEM_EMBED_TIMEOUT_MS = 8000
|
|
48
|
+
/** 配置里字符串字段的长度上限(不可信输入的第一道闸门)。 */
|
|
49
|
+
const MAX_FIELD = 512
|
|
50
|
+
|
|
51
|
+
/** 登记表在后端对象上的挂点(与 `control.js` 同一个理由:同进程多次加载只留一个句柄)。 */
|
|
52
|
+
const SEMANTIC_SHARED = Symbol.for('dsh-knit.semantic')
|
|
53
|
+
|
|
54
|
+
/** 进程内有界向量缓存:键 = `root\0rel\0headHash\0providerId\0schemaVersion`。 */
|
|
55
|
+
const vectorCache = new Map()
|
|
56
|
+
|
|
57
|
+
const str = (value, max = MAX_FIELD) => (typeof value === 'string' && value.length > 0 && value.length <= max ? value : null)
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 把任意输入收敛成合法 provider 配置。
|
|
61
|
+
* @param {unknown} value - 来自存储 / HTTP 的任意形状
|
|
62
|
+
* @returns {{kind: string, base: string, model: string}|null} 合法配置或 null
|
|
63
|
+
*/
|
|
64
|
+
export function normalizeProviderConfig(value) {
|
|
65
|
+
if (!value || typeof value !== 'object') return null
|
|
66
|
+
const kind = str(value.kind, 32)
|
|
67
|
+
const base = str(value.base)
|
|
68
|
+
const model = str(value.model, 128)
|
|
69
|
+
if (!kind || !SEMANTIC_KINDS.includes(kind)) return null
|
|
70
|
+
if (!base || !/^https?:\/\/[^\s]+$/.test(base)) return null
|
|
71
|
+
if (!model) return null
|
|
72
|
+
// 去掉尾部斜杠:两种协议都要拼路径,留着会出现 `//`(有的服务端认,有的不认)。
|
|
73
|
+
return { kind, base: base.replace(/\/+$/, ''), model }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** base 是不是本机地址(客户端据此决定要不要披露「内容会发到你配置的服务」)。 */
|
|
77
|
+
export function isLoopbackBase(base) {
|
|
78
|
+
try {
|
|
79
|
+
const host = new URL(base).hostname
|
|
80
|
+
return host === '127.0.0.1' || host === 'localhost' || host === '::1' || host === '[::1]'
|
|
81
|
+
} catch {
|
|
82
|
+
return false
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const providerIdOf = (config) => `${config.kind}|${config.base}|${config.model}`
|
|
87
|
+
/** embedding schema 版本:换协议形状 / 换向量化口径时 +1(Phase A 固定 1)。 */
|
|
88
|
+
export const SEMANTIC_SCHEMA_VERSION = 1
|
|
89
|
+
|
|
90
|
+
/** 余弦相似度(两个等长数值数组;长度不等或全零返回 0)。 */
|
|
91
|
+
export function cosine(a, b) {
|
|
92
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length === 0 || a.length !== b.length) return 0
|
|
93
|
+
let dot = 0
|
|
94
|
+
let na = 0
|
|
95
|
+
let nb = 0
|
|
96
|
+
for (let i = 0; i < a.length; i++) {
|
|
97
|
+
const x = Number(a[i]) || 0
|
|
98
|
+
const y = Number(b[i]) || 0
|
|
99
|
+
dot += x * y
|
|
100
|
+
na += x * x
|
|
101
|
+
nb += y * y
|
|
102
|
+
}
|
|
103
|
+
if (na === 0 || nb === 0) return 0
|
|
104
|
+
return dot / (Math.sqrt(na) * Math.sqrt(nb))
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 取一篇文档的嵌入输入:**只有 title + summary**(两条路径上都有;方案 §5.1)。 */
|
|
108
|
+
export function embedTextOf(doc) {
|
|
109
|
+
const title = typeof doc.title === 'string' ? doc.title : ''
|
|
110
|
+
const summary = typeof doc.summary === 'string' ? doc.summary : ''
|
|
111
|
+
const text = `${title}\n${summary}`.trim()
|
|
112
|
+
return text.length > 0 ? text.slice(0, 2000) : null
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* 把一次 `fetch` 收敛成「成功 / 超时 / 其它失败」三态,**不抛**。
|
|
117
|
+
* @param {Function} fetchImpl - 注入的 fetch
|
|
118
|
+
* @param {string} url
|
|
119
|
+
* @param {object} init - fetch 的第二个参数
|
|
120
|
+
* @param {number} timeoutMs
|
|
121
|
+
* @returns {Promise<{ok: boolean, reason?: string, status?: number, json?: object}>}
|
|
122
|
+
*/
|
|
123
|
+
async function fetchJson(fetchImpl, url, init, timeoutMs) {
|
|
124
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null
|
|
125
|
+
let timer = null
|
|
126
|
+
try {
|
|
127
|
+
if (controller) timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
128
|
+
const res = await fetchImpl(url, controller ? { ...init, signal: controller.signal } : init)
|
|
129
|
+
if (!res || typeof res.status !== 'number') return { ok: false, reason: 'bad-response' }
|
|
130
|
+
if (res.status < 200 || res.status >= 300) return { ok: false, reason: 'probe-failed', status: res.status }
|
|
131
|
+
const json = await res.json()
|
|
132
|
+
if (!json || typeof json !== 'object') return { ok: false, reason: 'bad-response' }
|
|
133
|
+
return { ok: true, status: res.status, json }
|
|
134
|
+
} catch (error) {
|
|
135
|
+
const aborted = error && (error.name === 'AbortError' || /abort/i.test(String(error.message || '')))
|
|
136
|
+
return { ok: false, reason: aborted ? 'timeout' : 'probe-failed' }
|
|
137
|
+
} finally {
|
|
138
|
+
if (timer) clearTimeout(timer)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* provider:两种协议的**唯一**分叉点。
|
|
144
|
+
*
|
|
145
|
+
* @param {object} config - `normalizeProviderConfig()` 的产物
|
|
146
|
+
* @param {{fetchImpl?: Function, probeTimeoutMs?: number, embedTimeoutMs?: number}} [options]
|
|
147
|
+
* @returns {object} provider 句柄(`probe` / `embed` 都**不抛**,失败回 `reason`)
|
|
148
|
+
*/
|
|
149
|
+
export function createSemanticProvider(config, options = {}) {
|
|
150
|
+
const cfg = normalizeProviderConfig(config)
|
|
151
|
+
// ⚠️ `'fetchImpl' in options` 而不是 `||`:显式传 `null` 是「**没有** fetch」的意思
|
|
152
|
+
// (测试用它证明默认路径一个请求都不发);只有**没传**时才回落到全局 `fetch`。
|
|
153
|
+
const fetchImpl = 'fetchImpl' in options ? options.fetchImpl : (typeof fetch === 'function' ? fetch : null)
|
|
154
|
+
const probeTimeoutMs = Number(options.probeTimeoutMs) > 0 ? Number(options.probeTimeoutMs) : SEM_PROBE_TIMEOUT_MS
|
|
155
|
+
const embedTimeoutMs = Number(options.embedTimeoutMs) > 0 ? Number(options.embedTimeoutMs) : SEM_EMBED_TIMEOUT_MS
|
|
156
|
+
|
|
157
|
+
if (!cfg || !fetchImpl) {
|
|
158
|
+
return {
|
|
159
|
+
id: null,
|
|
160
|
+
kind: null,
|
|
161
|
+
model: null,
|
|
162
|
+
base: null,
|
|
163
|
+
schemaVersion: SEMANTIC_SCHEMA_VERSION,
|
|
164
|
+
probe: async () => ({ ok: false, reason: 'no-provider' }),
|
|
165
|
+
embed: async () => ({ ok: false, reason: 'no-provider' }),
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const probe = async () => {
|
|
170
|
+
const url = cfg.kind === 'ollama' ? `${cfg.base}/api/tags` : `${cfg.base}/v1/models`
|
|
171
|
+
const res = await fetchJson(fetchImpl, url, { method: 'GET' }, probeTimeoutMs)
|
|
172
|
+
if (!res.ok) return { ok: false, reason: res.reason }
|
|
173
|
+
// 形状只要「是个对象」就算通:不同版本的 Ollama / 兼容服务返回体差别很大,
|
|
174
|
+
// 这里**不校验模型清单**(真正的判据是下面的 `embed` 能不能给出向量)。
|
|
175
|
+
return { ok: true }
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const embed = async (texts) => {
|
|
179
|
+
const input = (Array.isArray(texts) ? texts : [texts]).filter((t) => typeof t === 'string' && t.length > 0)
|
|
180
|
+
if (input.length === 0) return { ok: false, reason: 'bad-response' }
|
|
181
|
+
const url = cfg.kind === 'ollama' ? `${cfg.base}/api/embed` : `${cfg.base}/v1/embeddings`
|
|
182
|
+
const body = cfg.kind === 'ollama'
|
|
183
|
+
? { model: cfg.model, input }
|
|
184
|
+
: { model: cfg.model, input }
|
|
185
|
+
const res = await fetchJson(fetchImpl, url, {
|
|
186
|
+
method: 'POST',
|
|
187
|
+
headers: { 'content-type': 'application/json' },
|
|
188
|
+
body: JSON.stringify(body),
|
|
189
|
+
}, embedTimeoutMs)
|
|
190
|
+
if (!res.ok) return { ok: false, reason: res.reason }
|
|
191
|
+
const vectors = cfg.kind === 'ollama'
|
|
192
|
+
? (Array.isArray(res.json.embeddings) ? res.json.embeddings : null)
|
|
193
|
+
: (Array.isArray(res.json.data) ? res.json.data.map((row) => row && row.embedding) : null)
|
|
194
|
+
if (!vectors || vectors.length !== input.length) return { ok: false, reason: 'bad-response' }
|
|
195
|
+
for (const vector of vectors) {
|
|
196
|
+
if (!Array.isArray(vector) || vector.length === 0) return { ok: false, reason: 'bad-response' }
|
|
197
|
+
}
|
|
198
|
+
return { ok: true, vectors }
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return { id: providerIdOf(cfg), kind: cfg.kind, model: cfg.model, base: cfg.base, schemaVersion: SEMANTIC_SCHEMA_VERSION, probe, embed }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* 配置的持久化(Phase A 只存配置;向量留在内存里)。
|
|
206
|
+
* 形状照抄 `control.js` 的 `createControlStore`(同一条纪律:**证据到之前不说自己记得**)。
|
|
207
|
+
*
|
|
208
|
+
* @param {{backend?: object|null}} [options]
|
|
209
|
+
* @returns {{persisted: boolean, reason: string, read: Function, write: Function, flush: Function}}
|
|
210
|
+
*/
|
|
211
|
+
export function createSemanticStore(options = {}) {
|
|
212
|
+
const backend = options && options.backend
|
|
213
|
+
const kv = backend && typeof backend === 'object' ? backend.kv : null
|
|
214
|
+
if (!kv || typeof kv.open !== 'function') {
|
|
215
|
+
return {
|
|
216
|
+
persisted: false,
|
|
217
|
+
reason: 'no-storage',
|
|
218
|
+
read: async () => null,
|
|
219
|
+
write: async () => false,
|
|
220
|
+
flush: async () => false,
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
let opening = null
|
|
225
|
+
let writes = Promise.resolve()
|
|
226
|
+
const openUnit = () => {
|
|
227
|
+
if (!opening) {
|
|
228
|
+
opening = Promise.resolve()
|
|
229
|
+
.then(() => kv.open({
|
|
230
|
+
name: SEMANTIC_UNIT,
|
|
231
|
+
version: SEMANTIC_VERSION,
|
|
232
|
+
tables: SEMANTIC_TABLES,
|
|
233
|
+
hasGlobal: false,
|
|
234
|
+
layout: 'single',
|
|
235
|
+
}))
|
|
236
|
+
.catch(() => null)
|
|
237
|
+
}
|
|
238
|
+
return opening
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const store = {
|
|
242
|
+
persisted: false,
|
|
243
|
+
reason: 'unproven',
|
|
244
|
+
read: async () => {
|
|
245
|
+
try {
|
|
246
|
+
const unit = await openUnit()
|
|
247
|
+
if (!unit) {
|
|
248
|
+
store.persisted = false
|
|
249
|
+
store.reason = 'open-failed'
|
|
250
|
+
return null
|
|
251
|
+
}
|
|
252
|
+
const all = await unit.loadAll()
|
|
253
|
+
const tables = (all && all.tables) || {}
|
|
254
|
+
const rows = (tables[SEMANTIC_TABLES[0]] && typeof tables[SEMANTIC_TABLES[0]] === 'object') ? tables[SEMANTIC_TABLES[0]] : {}
|
|
255
|
+
store.persisted = true
|
|
256
|
+
store.reason = 'ok'
|
|
257
|
+
return normalizeProviderConfig(rows[SEMANTIC_CONFIG_KEY])
|
|
258
|
+
} catch {
|
|
259
|
+
store.persisted = false
|
|
260
|
+
store.reason = 'read-failed'
|
|
261
|
+
return null
|
|
262
|
+
}
|
|
263
|
+
},
|
|
264
|
+
write: async (config) => {
|
|
265
|
+
writes = writes.then(async () => {
|
|
266
|
+
const unit = await openUnit()
|
|
267
|
+
if (!unit) {
|
|
268
|
+
store.persisted = false
|
|
269
|
+
store.reason = 'open-failed'
|
|
270
|
+
return false
|
|
271
|
+
}
|
|
272
|
+
const cfg = normalizeProviderConfig(config)
|
|
273
|
+
if (cfg) await unit.putRecord(SEMANTIC_TABLES[0], SEMANTIC_CONFIG_KEY, cfg)
|
|
274
|
+
else await unit.deleteRecord(SEMANTIC_TABLES[0], SEMANTIC_CONFIG_KEY)
|
|
275
|
+
store.persisted = true
|
|
276
|
+
store.reason = 'ok'
|
|
277
|
+
return true
|
|
278
|
+
}).catch(() => {
|
|
279
|
+
store.persisted = false
|
|
280
|
+
store.reason = 'write-failed'
|
|
281
|
+
return false
|
|
282
|
+
})
|
|
283
|
+
return writes
|
|
284
|
+
},
|
|
285
|
+
flush: async () => writes,
|
|
286
|
+
}
|
|
287
|
+
return store
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** 一个后端只留一个配置登记表(同 `sharedControlRegistry` 的理由)。 */
|
|
291
|
+
export function sharedSemanticStore(backend) {
|
|
292
|
+
if (!backend || typeof backend !== 'object') return null
|
|
293
|
+
if (!backend[SEMANTIC_SHARED]) backend[SEMANTIC_SHARED] = createSemanticStore({ backend })
|
|
294
|
+
return backend[SEMANTIC_SHARED]
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* 引擎:把 provider / 配置 / 有界候选串起来。
|
|
299
|
+
*
|
|
300
|
+
* `pass()` 是**唯一**会发请求的地方,且只在「有配置 + 有查询文本」时发。
|
|
301
|
+
*
|
|
302
|
+
* @param {{store?: object|null, fetchImpl?: Function, now?: Function, probeTtlMs?: number,
|
|
303
|
+
* embedPerPass?: number, topK?: number, minSim?: number, timeouts?: object}} [options]
|
|
304
|
+
* @returns {object} 引擎句柄
|
|
305
|
+
*/
|
|
306
|
+
export function createSemanticEngine(options = {}) {
|
|
307
|
+
const store = options.store || null
|
|
308
|
+
const fetchImpl = options.fetchImpl || (typeof fetch === 'function' ? fetch : null)
|
|
309
|
+
const now = typeof options.now === 'function' ? options.now : () => Date.now()
|
|
310
|
+
const probeTtlMs = Number(options.probeTtlMs) > 0 ? Number(options.probeTtlMs) : SEM_PROBE_TTL_MS
|
|
311
|
+
const embedPerPass = Number(options.embedPerPass) > 0 ? Number(options.embedPerPass) : SEM_EMBED_PER_PASS
|
|
312
|
+
const topK = Number(options.topK) > 0 ? Number(options.topK) : SEM_TOPK
|
|
313
|
+
const minSim = Number.isFinite(options.minSim) ? Number(options.minSim) : SEM_MIN_SIM
|
|
314
|
+
|
|
315
|
+
let config = null
|
|
316
|
+
let loaded = false
|
|
317
|
+
let loading = null
|
|
318
|
+
let probe = null // { ok, reason, at }
|
|
319
|
+
|
|
320
|
+
const load = () => {
|
|
321
|
+
if (loaded) return Promise.resolve(config)
|
|
322
|
+
if (!loading) {
|
|
323
|
+
loading = (store ? store.read().catch(() => null) : Promise.resolve(null)).then((cfg) => {
|
|
324
|
+
loaded = true
|
|
325
|
+
if (cfg) config = cfg
|
|
326
|
+
return config
|
|
327
|
+
})
|
|
328
|
+
}
|
|
329
|
+
return loading
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const providerOf = () => createSemanticProvider(config, {
|
|
333
|
+
fetchImpl,
|
|
334
|
+
...(options.timeouts || {}),
|
|
335
|
+
})
|
|
336
|
+
|
|
337
|
+
const probeCached = async () => {
|
|
338
|
+
if (!config) return { ok: false, reason: 'no-provider' }
|
|
339
|
+
if (probe && now() - probe.at < probeTtlMs) return { ok: probe.ok, reason: probe.reason }
|
|
340
|
+
const provider = providerOf()
|
|
341
|
+
const result = await provider.probe()
|
|
342
|
+
probe = { ok: !!result.ok, reason: result.reason, at: now() }
|
|
343
|
+
return { ok: probe.ok, reason: probe.reason }
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
return {
|
|
347
|
+
/**
|
|
348
|
+
* 当前状态(**不发任何请求**;`available` 用进程内探测缓存 —— 没探过就是 null)。
|
|
349
|
+
* @returns {{configured: boolean, provider: object|null, available: boolean|null, reason: string|null}}
|
|
350
|
+
*/
|
|
351
|
+
status() {
|
|
352
|
+
const available = probe ? probe.ok : null
|
|
353
|
+
const reason = !config ? (loaded ? 'no-provider' : null) : (probe && !probe.ok ? probe.reason : null)
|
|
354
|
+
return {
|
|
355
|
+
configured: !!config,
|
|
356
|
+
provider: config ? { kind: config.kind, base: config.base, model: config.model } : null,
|
|
357
|
+
available,
|
|
358
|
+
reason: reason || null,
|
|
359
|
+
}
|
|
360
|
+
},
|
|
361
|
+
/** 首访装载(判据「证据到之前不说自己记得」的对应物)。 */
|
|
362
|
+
async ready() {
|
|
363
|
+
await load()
|
|
364
|
+
return this.status()
|
|
365
|
+
},
|
|
366
|
+
/** 保存配置(空 / null ⇒ 清空)。返回保存后的状态(仍**不探测**)。 */
|
|
367
|
+
async configure(value) {
|
|
368
|
+
const cfg = normalizeProviderConfig(value)
|
|
369
|
+
config = cfg
|
|
370
|
+
loaded = true
|
|
371
|
+
probe = null
|
|
372
|
+
clearVectors()
|
|
373
|
+
if (store) await store.write(cfg)
|
|
374
|
+
return this.status()
|
|
375
|
+
},
|
|
376
|
+
/** 显式探测一次(只有 `POST /api/semantic` 与混合模式会走到这里)。 */
|
|
377
|
+
async check() {
|
|
378
|
+
await load()
|
|
379
|
+
const result = await probeCached()
|
|
380
|
+
return { configured: !!config, provider: config || null, available: result.ok, reason: result.ok ? null : (result.reason || 'probe-failed') }
|
|
381
|
+
},
|
|
382
|
+
/**
|
|
383
|
+
* 有界的一轮语义候选计算。
|
|
384
|
+
*
|
|
385
|
+
* @param {{root: string, query: string, docs: Array<object>}} input
|
|
386
|
+
* @returns {Promise<{available: boolean, reason: string|null, candidates: number,
|
|
387
|
+
* rels: string[], provider: object|null, embedded: number, cacheHits: number, calls: number}>}
|
|
388
|
+
*/
|
|
389
|
+
async pass(input) {
|
|
390
|
+
const root = String((input && input.root) || '')
|
|
391
|
+
const query = typeof (input && input.query) === 'string' ? input.query.trim() : ''
|
|
392
|
+
const docs = Array.isArray(input && input.docs) ? input.docs : []
|
|
393
|
+
await load()
|
|
394
|
+
const base = {
|
|
395
|
+
available: false,
|
|
396
|
+
reason: null,
|
|
397
|
+
candidates: 0,
|
|
398
|
+
rels: [],
|
|
399
|
+
provider: config ? { kind: config.kind, base: config.base, model: config.model } : null,
|
|
400
|
+
embedded: 0,
|
|
401
|
+
cacheHits: 0,
|
|
402
|
+
calls: 0,
|
|
403
|
+
}
|
|
404
|
+
if (!config) return { ...base, reason: 'no-provider' }
|
|
405
|
+
if (!query) return { ...base, reason: 'no-query' }
|
|
406
|
+
const health = await probeCached()
|
|
407
|
+
base.calls = 1
|
|
408
|
+
if (!health.ok) return { ...base, reason: health.reason || 'probe-failed' }
|
|
409
|
+
|
|
410
|
+
const provider = providerOf()
|
|
411
|
+
const queryVector = await provider.embed([query.slice(0, 2000)])
|
|
412
|
+
base.calls += 1
|
|
413
|
+
if (!queryVector.ok) return { ...base, reason: queryVector.reason || 'bad-response' }
|
|
414
|
+
const q = queryVector.vectors[0]
|
|
415
|
+
|
|
416
|
+
// 有界:先复用缓存,再对「还没缓存」的那批做**有上限**的一轮嵌入(按池子顺序,确定性)。
|
|
417
|
+
const pending = []
|
|
418
|
+
const scored = []
|
|
419
|
+
for (const doc of docs) {
|
|
420
|
+
const text = embedTextOf(doc)
|
|
421
|
+
if (!text || typeof doc.rel !== 'string') continue
|
|
422
|
+
const key = `${root}\u0000${doc.rel}\u0000${headHashOf(text)}\u0000${provider.id}\u0000${provider.schemaVersion}`
|
|
423
|
+
const hit = vectorCache.get(key)
|
|
424
|
+
if (hit) {
|
|
425
|
+
base.cacheHits += 1
|
|
426
|
+
scored.push({ rel: doc.rel, sim: cosine(q, hit) })
|
|
427
|
+
} else if (pending.length < embedPerPass) {
|
|
428
|
+
pending.push({ key, rel: doc.rel, text })
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
if (pending.length > 0) {
|
|
432
|
+
const embedded = await provider.embed(pending.map((item) => item.text))
|
|
433
|
+
base.calls += 1
|
|
434
|
+
if (embedded.ok) {
|
|
435
|
+
for (let i = 0; i < pending.length; i++) {
|
|
436
|
+
const vec = embedded.vectors[i]
|
|
437
|
+
vectorCache.set(pending[i].key, vec)
|
|
438
|
+
base.embedded += 1
|
|
439
|
+
scored.push({ rel: pending[i].rel, sim: cosine(q, vec) })
|
|
440
|
+
}
|
|
441
|
+
// 有界缓存:超上限就丢最早的(Map 保持插入序)。
|
|
442
|
+
while (vectorCache.size > SEM_CACHE_MAX) {
|
|
443
|
+
const oldest = vectorCache.keys().next()
|
|
444
|
+
if (oldest.done) break
|
|
445
|
+
vectorCache.delete(oldest.value)
|
|
446
|
+
}
|
|
447
|
+
} else {
|
|
448
|
+
// 嵌入失败 ⇒ 明着回退(但缓存命中那部分仍然如实计数:它们不花新钱)。
|
|
449
|
+
base.reason = embedded.reason || 'bad-response'
|
|
450
|
+
base.available = false
|
|
451
|
+
return { ...base, candidates: 0, rels: [] }
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
scored.sort((a, b) => b.sim - a.sim || (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0))
|
|
456
|
+
const picked = scored.filter((row) => row.sim >= minSim).slice(0, topK)
|
|
457
|
+
return { ...base, available: true, reason: null, candidates: picked.length, rels: picked.map((row) => row.rel) }
|
|
458
|
+
},
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** 测试用:清空进程内向量缓存。 */
|
|
463
|
+
export function clearVectors() {
|
|
464
|
+
vectorCache.clear()
|
|
465
|
+
}
|
package/src/host/tool.js
CHANGED
|
@@ -128,6 +128,19 @@ const PARAMETERS = {
|
|
|
128
128
|
+ 'and how many reads fell outside the pack. Counts only — no scores, no confidence. '
|
|
129
129
|
+ 'Default false.',
|
|
130
130
|
},
|
|
131
|
+
// v0.23:检索模式。**默认 lexical** —— 不传它时这次的入参与返回值与 v0.22 逐字一致
|
|
132
|
+
// (唯一的例外是输出里多了 `retrieval` 那一行,见 `renderToolText()`)。
|
|
133
|
+
// lexical = 纯 BM25(纯本地、零模型调用、零网络出口)
|
|
134
|
+
// hybrid = 在词法之外**可选地**算一层语义候选;需要用户在面板里配好 provider。
|
|
135
|
+
// Phase A 只**计数**,不进三层(`provenance` 也不新增取值)。
|
|
136
|
+
retrieval: {
|
|
137
|
+
type: 'string',
|
|
138
|
+
enum: ['lexical', 'hybrid'],
|
|
139
|
+
description: 'Retrieval mode. "lexical" (default) is pure local BM25 — no model calls, no network. '
|
|
140
|
+
+ '"hybrid" additionally asks the user-configured embedding provider for bounded semantic '
|
|
141
|
+
+ 'candidates; it falls back to lexical (with a stated reason) when no provider is configured '
|
|
142
|
+
+ 'or reachable. Semantic candidates never replace or re-rank the lexical results.',
|
|
143
|
+
},
|
|
131
144
|
},
|
|
132
145
|
}
|
|
133
146
|
|
|
@@ -167,6 +180,9 @@ const ITEM_SCHEMA = {
|
|
|
167
180
|
enum: [
|
|
168
181
|
'direct', 'titleMatch', 'filenameMatch', 'summaryMatch', 'pathMatch', 'bodyMatch',
|
|
169
182
|
'linkTarget', 'linkSource', 'related',
|
|
183
|
+
// v0.23:语义候选补进来的那一条(只在「相关」层)。
|
|
184
|
+
// 它**不是**关键词命中 —— `terms` 恒为空数组,别把两者读成同一件事。
|
|
185
|
+
'semantic',
|
|
170
186
|
],
|
|
171
187
|
},
|
|
172
188
|
// 命中的话题词(没有命中就是空数组 —— 不编造)。
|
|
@@ -184,7 +200,8 @@ const ITEM_SCHEMA = {
|
|
|
184
200
|
// v0.21:**来源**(怎么进的这个包)。与上面的 `source`(文件角色)是两件事,
|
|
185
201
|
// 名字故意不同 —— 把 `source` 的语义换掉会静默打断老调用方。
|
|
186
202
|
// retrieval = 命中当前任务的关键词;relation = 靠关系进来;manual = 用户自己钉的。
|
|
187
|
-
|
|
203
|
+
// v0.23:多一值 `semantic` —— 这条是**语义候选**补进来的(默认词法模式下永远不会出现)。
|
|
204
|
+
provenance: { type: 'string', enum: ['retrieval', 'relation', 'manual', 'semantic'] },
|
|
188
205
|
// v0.21:**这个条目与工作区里别的文件的关系**(需求 §6.7)。
|
|
189
206
|
// 每条都带证据:`other` 是对方 rel,`line` 是**提及所在那一行**(1 起)。
|
|
190
207
|
// dir:'out' ⇒ 本条目提到了 other,`line` 在本条目里
|
|
@@ -275,6 +292,9 @@ const OUTPUT_SCHEMA = {
|
|
|
275
292
|
},
|
|
276
293
|
required: ['matched', 'total'],
|
|
277
294
|
},
|
|
295
|
+
// v0.23:**这一次到底按哪种模式跑的**。只有调用方显式要了 `hybrid` 才出现;
|
|
296
|
+
// 词法回退时写明原因(判据 5:不许让模型以为它拿到的是语义结果)。
|
|
297
|
+
retrieval: { type: 'string' },
|
|
278
298
|
// v0.15:**可选**的一行「使用情况」(只有 `audit: true` 时才有)。
|
|
279
299
|
// 它说的全是计数与事实 —— 没有分数、没有百分比、没有置信度、没有 trajectory。
|
|
280
300
|
// 不传 `audit` 时这个字段根本不出现(而不是给个空串)。
|
|
@@ -577,6 +597,11 @@ export function renderToolText(value, readSnippet) {
|
|
|
577
597
|
})
|
|
578
598
|
|
|
579
599
|
const out = []
|
|
600
|
+
// v0.23:检索模式那一行**紧跟在头部之后** —— 它是「这次结果是怎么来的」的一部分。
|
|
601
|
+
// 只有调用方要了 `hybrid` 才会有(默认词法调用的输出与 v0.22 逐字一致)。
|
|
602
|
+
if (value && typeof value.retrieval === 'string' && value.retrieval) {
|
|
603
|
+
out.push(`Retrieval: ${value.retrieval}`)
|
|
604
|
+
}
|
|
580
605
|
const matched = (value && value.totals && Number.isInteger(value.totals.matched))
|
|
581
606
|
? value.totals.matched : 0
|
|
582
607
|
out.push(`Context for ${topic ? `「${topic}」` : 'the current conversation'}: `
|
|
@@ -627,6 +652,9 @@ function whyText(reason) {
|
|
|
627
652
|
case 'bodyMatch': return terms ? `matched in the body (${terms})` : 'matched in the body'
|
|
628
653
|
case 'linkTarget': return 'referenced by a primary document'
|
|
629
654
|
case 'linkSource': return 'references a primary document'
|
|
655
|
+
// v0.23:语义候选补进来的。**不要把这句话写成「相关」**(那是不可验证的推断):
|
|
656
|
+
// 它进包的唯一依据是「标题 + 摘要」的向量与任务相似,而且**没有任何关键词命中**。
|
|
657
|
+
case 'semantic': return 'semantic candidate (title / summary similarity — no keyword match)'
|
|
630
658
|
default: return 'related in the current workspace'
|
|
631
659
|
}
|
|
632
660
|
}
|
|
@@ -721,11 +749,15 @@ export function knitDocsDefinition(scan, read, contextFor, audit) {
|
|
|
721
749
|
// v0.15:审计是**显式**的(默认 false)。不传它就完全不走 feedback 那条路。
|
|
722
750
|
const auditRequested = !!(args && args.audit === true)
|
|
723
751
|
|
|
752
|
+
// v0.23:`retrieval` 默认 `lexical`(老调用方一个字都不用改)。
|
|
753
|
+
const retrieval = args && args.retrieval === 'hybrid' ? 'hybrid' : 'lexical'
|
|
754
|
+
|
|
724
755
|
const payload = await scan(root, limit, {
|
|
725
756
|
session,
|
|
726
757
|
sessionId,
|
|
727
758
|
sort: 'relevance',
|
|
728
759
|
query,
|
|
760
|
+
retrieval,
|
|
729
761
|
// v0.19:工具的语料是**文档 + 代码**(不给 HTTP 的 `context` 档)。
|
|
730
762
|
// 这一条正是本次版本的核心主张:代码和 Markdown 在**同一套 BM25、同一套分层**
|
|
731
763
|
// 里竞争,谁进 Primary 只由任务检索决定,没人给代码留座位。
|
|
@@ -733,6 +765,15 @@ export function knitDocsDefinition(scan, read, contextFor, audit) {
|
|
|
733
765
|
kind: 'context',
|
|
734
766
|
})
|
|
735
767
|
|
|
768
|
+
// v0.23:把「这一轮实际用了哪种检索」如实带出去。只有要了 `hybrid` 才写,
|
|
769
|
+
// 而且**回退时写明原因** —— 判据 5 的「不许伪装成混合成功」在工具这一面就是这一行。
|
|
770
|
+
const semantic = payload.semantic && typeof payload.semantic === 'object' ? payload.semantic : null
|
|
771
|
+
const retrievalLine = (retrieval !== 'hybrid' || !semantic)
|
|
772
|
+
? null
|
|
773
|
+
: (semantic.mode === 'hybrid'
|
|
774
|
+
? `hybrid (semantic candidates: ${Number(semantic.candidates) || 0})`
|
|
775
|
+
: `lexical — fell back from hybrid (${semantic.reason || 'unavailable'})`)
|
|
776
|
+
|
|
736
777
|
// 命中词用 `scan()` 的 `keywords` —— 它是**语料里真实存在**的那批词
|
|
737
778
|
// (不是原始候选),所以拿它去原文里找段落,必然找得到。
|
|
738
779
|
// 时间序模式下它是空数组 ⇒ terms 为空 ⇒ 不抽段落,正合语义。
|
|
@@ -761,6 +802,7 @@ export function knitDocsDefinition(scan, read, contextFor, audit) {
|
|
|
761
802
|
mode: 'time',
|
|
762
803
|
topic: '',
|
|
763
804
|
total: Number.isInteger(payload.total) ? payload.total : 0,
|
|
805
|
+
...(retrievalLine ? { retrieval: retrievalLine } : {}),
|
|
764
806
|
primary: [],
|
|
765
807
|
supporting: [],
|
|
766
808
|
related: [],
|
|
@@ -849,6 +891,7 @@ export function knitDocsDefinition(scan, read, contextFor, audit) {
|
|
|
849
891
|
mode: 'relevance',
|
|
850
892
|
topic: typeof pack.topic === 'string' ? pack.topic : '',
|
|
851
893
|
total: Number.isInteger(pack.totals && pack.totals.total) ? pack.totals.total : 0,
|
|
894
|
+
...(retrievalLine ? { retrieval: retrievalLine } : {}),
|
|
852
895
|
// `matched` 走 `totals` —— 头部的「N matching documents」靠它。
|
|
853
896
|
// 漏掉这一个字段会让头部永远写「0 matching documents」,而下面明明列着结果
|
|
854
897
|
// (实测踩过一次,是渲染层的一个真实缺陷,不是美观问题)。
|