dsh-metabolism 0.2.2 → 0.3.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.
@@ -0,0 +1,53 @@
1
+ /**
2
+ * 摘要块.js —— 三层摘要的格式、预算、分层(2026-11-20 起)。
3
+ *
4
+ * 摘要块是写进会话的一条消息:压掉的那段原文,换成一块 300~500 字的摘要,
5
+ * 带归档地址;七天后折成周块,三十天折成指针。这里只放格式和算账,
6
+ * 不碰会话写入(那是 engine.js 的活)。
7
+ */
8
+
9
+ /** 把一段摘要正文包成上下文里能读的块。 */
10
+ export function renderSummaryBlock({ text, seqFrom, seqTo, archiveName, tokenCount }) {
11
+ const clean = String(text ?? '').trim()
12
+ const lines = [
13
+ `<summary-block seq="${seqFrom}–${seqTo}">`,
14
+ clean,
15
+ `归档:${archiveName}(seq ${seqFrom}–${seqTo},约 ${tokenCount} tokens)`,
16
+ '</summary-block>',
17
+ ]
18
+ return lines.join('\n')
19
+ }
20
+
21
+ /**
22
+ * 估 token:中文按 1.6 字/token,其余按 4 字/token。偏保守,宁多不少。
23
+ * 预算只用来记账和触发折叠,不追求精确,日志里写的是估算口径。
24
+ */
25
+ export function estimateTokens(text) {
26
+ const s = String(text ?? '')
27
+ const cjk = (s.match(/[\u4e00-\u9fff]/g) ?? []).length
28
+ const other = s.length - cjk
29
+ return Math.ceil(cjk / 1.6 + other / 4)
30
+ }
31
+
32
+ /** 按天数分到哪一层:a=原摘要(0–7 天),b=周块(7–30 天),c=指针(30 天以外)。 */
33
+ export function layerOf(ageDays) {
34
+ const days = Number(ageDays) || 0
35
+ if (days <= 7) return 'a'
36
+ if (days <= 30) return 'b'
37
+ return 'c'
38
+ }
39
+
40
+ /** 折叠周块:任务线(来自骨架日摘要)+ 味道(来自原摘要各摘半句)。 */
41
+ export function foldWeekBlock({ taskLines, flavorLines, seqFrom, seqTo, archiveName }) {
42
+ const task = (taskLines ?? []).filter((line) => String(line ?? '').trim().length > 0)
43
+ const flavor = (flavorLines ?? []).filter((line) => String(line ?? '').trim().length > 0)
44
+ const body = []
45
+ if (task.length > 0) body.push(...task)
46
+ if (flavor.length > 0) body.push('—', ...flavor)
47
+ const text = body.join('\n')
48
+ return {
49
+ text,
50
+ tokens: estimateTokens(text),
51
+ block: renderSummaryBlock({ text, seqFrom, seqTo, archiveName, tokenCount: estimateTokens(text) }),
52
+ }
53
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * 时间线.js —— 跨天的因果线(2026-11-20 起)。
3
+ *
4
+ * 一条时间线 = 一天一条(或半天一条),写清哪天、发生了什么、我们之间发生了什么、
5
+ * 当时什么味,带 seq 门牌。文件是 jsonl,只追加不改写;错了就再追加一条更正。
6
+ */
7
+
8
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
9
+ import { dirname, join } from 'node:path'
10
+
11
+ /** 时间线放在茅房上一级:记忆\时间线.jsonl。 */
12
+ export function timelineFile(archiveRoot) {
13
+ return join(dirname(archiveRoot), '时间线.jsonl')
14
+ }
15
+
16
+ /** 追加一条;字段按设计稿:date/from/to/title/what/we/feel/topics/anchors/made。
17
+ * 老的写法用 sources/spanFrom/spanTo,这里统一归一成 anchors,跟手工那 22 条对齐。 */
18
+ export function appendTimeline(entry, archiveRoot) {
19
+ const file = timelineFile(archiveRoot)
20
+ try {
21
+ const normalized = { ...entry }
22
+ if (!Array.isArray(normalized.anchors)) {
23
+ normalized.anchors = (Array.isArray(normalized.sources) ? normalized.sources : [])
24
+ .map((source) => ({ file: String(source ?? ''), day: normalized.date, fromSeq: normalized.spanFrom, toSeq: normalized.spanTo }))
25
+ }
26
+ delete normalized.sources
27
+ delete normalized.spanFrom
28
+ delete normalized.spanTo
29
+ if (!normalized.id) normalized.id = `L-${String(normalized.date ?? '').replace(/-/g, '')}-${Date.now().toString(36).slice(-4)}`
30
+ mkdirSync(dirname(file), { recursive: true })
31
+ appendFileSync(file, `${JSON.stringify(normalized)}\n`, 'utf8')
32
+ return { ok: true, file }
33
+ } catch (error) {
34
+ return { ok: false, error: error?.message ?? String(error) }
35
+ }
36
+ }
37
+
38
+ /** 读全部条目,按日期倒序(新的在前);同一天按 to 时间倒序。 */
39
+ export function readTimeline(archiveRoot) {
40
+ try {
41
+ if (!existsSync(timelineFile(archiveRoot))) return []
42
+ const entries = readFileSync(timelineFile(archiveRoot), 'utf8')
43
+ .split('\n')
44
+ .filter((line) => line.trim() !== '')
45
+ .map((line) => { try { return JSON.parse(line) } catch { return null } })
46
+ .filter((entry) => entry !== null)
47
+ entries.sort((a, b) => {
48
+ const da = `${String(a.date ?? '')} ${String(a.to ?? a.from ?? '00:00')}`
49
+ const db = `${String(b.date ?? '')} ${String(b.to ?? b.from ?? '00:00')}`
50
+ return db.localeCompare(da)
51
+ })
52
+ return entries
53
+ } catch {
54
+ return []
55
+ }
56
+ }
57
+
58
+ /** 某一天是否已经有条目。 */
59
+ export function hasTimelineFor(day, archiveRoot) {
60
+ return readTimeline(archiveRoot).some((entry) => String(entry?.date ?? '') === String(day))
61
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * 浮现:开窗时把「最近两天的日摘要 + 最近几段线索」轻轻送进这一轮,
3
+ * 让我一开窗就知道昨天干到哪,不用等老大先问。
4
+ *
5
+ * 设计约束(三条,都是血的教训):
6
+ * 1. 默认关。开关.json 里 "浮现": true 才动,出岔子改回 false 重启即可。
7
+ * 2. 只在 turn===1 且 step===1 注入一次,不每轮回注——每轮都塞会把前缀搅乱、缓存全失效。
8
+ * 3. 总量封顶 1400 字。宁可少说,不许把上下文顶起来。
9
+ *
10
+ * 入口:由 recall.js 的 apply 顺手带上来(跟骨架工具一样,不单列补丁条目)。
11
+ */
12
+ import { readFileSync } from 'node:fs'
13
+ import { join } from 'node:path'
14
+ import { readTimeline } from './时间线.js'
15
+
16
+ const BUDGET = 1400
17
+
18
+ const readTile = (file) => {
19
+ try {
20
+ return readFileSync(file, 'utf8')
21
+ } catch {
22
+ return ''
23
+ }
24
+ }
25
+
26
+ /** 开关在 记忆\代谢日志\开关.json;读不到就当关着。 */
27
+ function morphEnabled(flagPath) {
28
+ try {
29
+ // 记事本/Out-File 写的 JSON 常带 BOM,JSON.parse 会直接抛,先剥掉
30
+ const raw = readFileSync(flagPath, 'utf8').replace(/^\uFEFF/, '')
31
+ const parsed = JSON.parse(raw)
32
+ return parsed?.浮现 === true
33
+ } catch {
34
+ return false
35
+ }
36
+ }
37
+
38
+ /** 从日摘要里抽「这一天的骨架」:标题行 + 头几条 + 最后几条。 */
39
+ function condenseDay(text, limit) {
40
+ const lines = text
41
+ .split('\n')
42
+ .map((line) => line.trim())
43
+ .filter((line) => line.length > 0)
44
+ // 这几类是压缩检查点和工具结果的残渣,摆上去只是噪音
45
+ .filter((line) => !/^# /.test(line))
46
+ .filter((line) => !/automatically generated check/i.test(line))
47
+ .filter((line) => !line.includes('<path>') && !line.includes('</path>'))
48
+ .filter((line) => !/^-\s*\d{1,2}:\d{2}\s*(Presented|Read|Write|Listed|Edited)\b/.test(line))
49
+ if (lines.length === 0) return ''
50
+ const head = lines.slice(0, Math.min(5, lines.length))
51
+ const tail = lines.length > 9 ? lines.slice(-3) : []
52
+ const picked = head.concat(tail.length > 0 ? ['…'] : [], tail)
53
+ const body = picked.join('\n')
54
+ return body.length > limit ? `${body.slice(0, limit)}…` : body
55
+ }
56
+
57
+ /** 攒出这一轮要送的文字。 */
58
+ function composeBlock(skeletonDir, archiveRoot, now = Date.now()) {
59
+ // 最近三条时间线:只给日期加一行标题,让我一开窗就知道这几天在走哪条路
60
+ const timeline = readTimeline(archiveRoot).slice(0, 3)
61
+ const parts = ['<骨架·开窗>', '这是本地骨架上最近两天的摘要,供接头用;细节要翻再调 metabolism_skeleton。']
62
+ let used = parts.join('\n').length
63
+ if (timeline.length > 0) {
64
+ const tlBlock = ['<时间线·最近>', ...timeline.map((entry) => `${entry.date ?? '?'} ${entry.title ?? ''}`.trim()), '</时间线·最近>'].join('\n')
65
+ parts.push(tlBlock)
66
+ used += tlBlock.length
67
+ }
68
+ const days = []
69
+ for (let back = 0; back <= 1; back += 1) {
70
+ const d = new Date(now - back * 86400000)
71
+ const day = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
72
+ const text = readTile(join(skeletonDir, 'L2', `${day}.md`))
73
+ if (text.length > 0) days.push({ day, text })
74
+ }
75
+ for (const item of days) {
76
+ const chunk = condenseDay(item.text, Math.min(600, BUDGET - used - 60))
77
+ if (chunk.length === 0) continue
78
+ parts.push(`【${item.day}】\n${chunk}`)
79
+ used += chunk.length + 20
80
+ if (used >= BUDGET) break
81
+ }
82
+ if (timeline.length === 0 && days.length === 0) return ''
83
+ parts.push('</骨架·开窗>')
84
+ const block = parts.join('\n')
85
+ return block.length > BUDGET ? `${block.slice(0, BUDGET)}…\n</骨架·开窗>` : block
86
+ }
87
+
88
+ export function apply(ctx, options = {}) {
89
+ const log = (level, message) => {
90
+ try { ctx.logger?.[level]?.(message) } catch { /* 日志失败不抛 */ }
91
+ }
92
+ const archiveRoot = String(options.archiveRoot ?? '')
93
+ if (archiveRoot === '') return
94
+ const skeletonDir = join(archiveRoot, '..', '骨架')
95
+ const flagPath = String(options.flagPath ?? join(archiveRoot, '..', '代谢日志', '开关.json'))
96
+ const sessionSeen = new Set()
97
+
98
+ ctx.effect(() => {
99
+ const off = ctx.on('agent/pre-step', async (payload, next) => {
100
+ const decision = await next()
101
+ try {
102
+ if (decision.kind === 'reject') return decision
103
+ if (!morphEnabled(flagPath)) return decision
104
+ if (payload?.step !== 1) return decision
105
+ const agent = payload?.agent
106
+ const sessionId = String(agent?.session?.id ?? agent?.id ?? '')
107
+ if (sessionId === '' || sessionSeen.has(sessionId)) return decision
108
+ const block = composeBlock(skeletonDir, archiveRoot)
109
+ if (block.length === 0) return decision
110
+ if (typeof agent?.inject !== 'function') return decision
111
+ sessionSeen.add(sessionId)
112
+ agent.inject({
113
+ id: `metabolism-morph-${Date.now()}`,
114
+ role: 'user',
115
+ content: [{ type: 'text', text: block }],
116
+ source: { kind: 'plugin:metabolism' },
117
+ })
118
+ log('info', `骨架浮现:送进 ${block.length} 字(turn ${payload?.turn ?? '?'})`)
119
+ } catch (error) {
120
+ log('warn', `骨架浮现失败(不影响这一轮):${error?.message ?? error}`)
121
+ }
122
+ return decision
123
+ })
124
+ return () => { off?.() }
125
+ })
126
+ }
127
+
128
+ export const inject = []
@@ -0,0 +1,229 @@
1
+ /**
2
+ * 贴条:设计稿 v3.1 第七节的第二层浮现——每轮最多贴一条。
3
+ *
4
+ * 跟开窗那层分工:
5
+ * 开窗(浮现.js):一次,把最近两天的目录铺给我看,让我知道「大概有哪些天」。
6
+ * 每轮(这里):拿老大这句话当查询,命中就贴一条到本轮末尾,告诉「这条跟眼前有关」。
7
+ *
8
+ * 三条硬约束(都是拿钱换来的教训):
9
+ * 1. 默认关。开关.json 里 "每轮一条": true 才动;改回 false 重启即可。
10
+ * 2. 只在命中时贴,没命中一个字都不加;同一条 20 轮内不重复贴。
11
+ * 3. 单条 ≤ 260 字。宁可少贴,不许把上下文顶起来。
12
+ *
13
+ * 为什么敢每轮动:只在请求末尾追加,前面一个字不改,前缀缓存照样命中。
14
+ * 改写前面的内容才是把缓存打碎的元凶。
15
+ *
16
+ * 入口:由 recall.js 的 apply 顺手带上来。
17
+ */
18
+ import { readFileSync } from 'node:fs'
19
+ import { join } from 'node:path'
20
+
21
+ const BUDGET = 260
22
+ const COOLDOWN_TURNS = 20
23
+ const MIN_COVERAGE = 0.16
24
+
25
+ /** 读开关;读不到就当关着。BOM 要剥,不然 JSON.parse 直接抛。 */
26
+ function flagOn(flagPath, key) {
27
+ try {
28
+ const raw = readFileSync(flagPath, 'utf8').replace(/^\uFEFF/, '')
29
+ return JSON.parse(raw)?.[key] === true
30
+ } catch {
31
+ return false
32
+ }
33
+ }
34
+
35
+ /**
36
+ * 白话里的虚词:先摘掉再切词,否则「那天」「到底」「有没有」这些会把命中率稀释掉。
37
+ * 2026-11-19 加的——验收第一版十道题,缺的这四道全是虚词把分拉低了。
38
+ */
39
+ const STOP_WORDS = [
40
+ '那天', '那次', '那次', '这个', '那个', '这些', '那些', '怎么', '什么', '为什么', '到底',
41
+ '有没有', '是不是', '怎么样', '我们', '你们', '他们', '一个', '一下', '一点', '就是',
42
+ '然后', '还是', '可以', '需要', '现在', '时候', '所以', '但是', '如果', '因为', '已经',
43
+ '没有', '不是', '这样', '那样', '多少', '几个', '哪里', '哪个', '咱们', '一下',
44
+ ]
45
+
46
+ /**
47
+ * 把一句话拆成可比对的词:先摘虚词,中文取二字组,英文数字按词。
48
+ * 不追求准,只求快和稳——这是每轮都要跑的东西。
49
+ */
50
+ /** 单字里没信息量的那些。其余单字照收——「壳」「账」「线」这种一字就能定住话题。 */
51
+ const STOP_CHARS = new Set('的了是在和就都很要会能有没不我你他这那上下里个们到去来说做用把被给对从让但而且或与也又还只再'.split(''))
52
+
53
+ export function gramsOf(text) {
54
+ let clean = String(text ?? '').toLowerCase()
55
+ for (const word of STOP_WORDS) clean = clean.split(word).join(' ')
56
+ const out = new Set()
57
+ for (const word of clean.match(/[a-z0-9_]{2,}/g) ?? []) out.add(word)
58
+ // {1,} 不是 {2,}:摘掉虚词后常剩下单字(「壳」「账」),那些恰恰最定得住话题
59
+ for (const run of clean.match(/[\u4e00-\u9fa5]{1,}/g) ?? []) {
60
+ for (let at = 0; at + 2 <= run.length; at += 1) out.add(run.slice(at, at + 2))
61
+ for (const char of run) if (!STOP_CHARS.has(char)) out.add(char)
62
+ }
63
+ return [...out]
64
+ }
65
+
66
+ /** 一条卡能被查到的全部文字。 */
67
+ function haystackOf(entry) {
68
+ return [
69
+ entry.title,
70
+ ...(Array.isArray(entry.keywords) ? entry.keywords : []),
71
+ entry.next,
72
+ // 逐字原话也参与匹配:题多半是他当时的原话,只有摘要碰不上
73
+ ...(Array.isArray(entry.quotes) ? entry.quotes : []),
74
+ ]
75
+ .filter((part) => typeof part === 'string' && part.length > 0)
76
+ .join(' ')
77
+ }
78
+
79
+ /**
80
+ * 在骨架目录里挑一条最相关的。
81
+ * 只查 L1/L2,不扫原文——每轮都扫原文太贵,这层要的是快。
82
+ */
83
+ export function pickOne(entries, query, cooled) {
84
+ const grams = gramsOf(query)
85
+ if (grams.length === 0) return null
86
+ let best = null
87
+ for (const entry of entries) {
88
+ if (entry === null || typeof entry !== 'object') continue
89
+ if (entry.layer !== 1 && entry.layer !== 2) continue
90
+ // 标了噪音的卡(检查点残渣、Presented、路径当标题那类)不参与,占了位子也答不了话
91
+ if (entry.noise === true) continue
92
+ if (typeof entry.id !== 'string' || entry.id.length === 0) continue
93
+ if (cooled.has(entry.id)) continue
94
+ const hay = haystackOf(entry).toLowerCase()
95
+ if (hay.length === 0) continue
96
+ let hit = 0
97
+ for (const gram of grams) {
98
+ if (hay.includes(gram)) hit += 1
99
+ }
100
+ if (hit === 0) continue
101
+ const coverage = hit / grams.length
102
+ if (coverage < MIN_COVERAGE) continue
103
+ // 层浅的优先(L1 比 L2 具体),同分取新的
104
+ const score = coverage * 100 + (entry.layer === 1 ? 10 : 0)
105
+ if (best === null || score > best.score) best = { entry, score, coverage }
106
+ }
107
+ return best
108
+ }
109
+
110
+ /** 从卡里抠「下一步」那行。index 里不存这个,命中时才读一次文件。 */
111
+ function nextOf(l1Dir, id) {
112
+ try {
113
+ const text = readFileSync(join(l1Dir, `${id}.md`), 'utf8')
114
+ const at = text.indexOf('**下一步**')
115
+ if (at === -1) return ''
116
+ const rest = text.slice(at + '**下一步**'.length)
117
+ const end = rest.indexOf('\n**')
118
+ const block = (end === -1 ? rest : rest.slice(0, end))
119
+ .split('\n')
120
+ .map((line) => line.replace(/^[-*·\d.、]+\s*/, '').trim())
121
+ .filter((line) => line.length > 0 && line !== '(这段里没写)')
122
+ return block[0] ?? ''
123
+ } catch {
124
+ return ''
125
+ }
126
+ }
127
+
128
+ /** 拼出要贴的那一条。 */
129
+ export function blockOf(entry, coverage) {
130
+ const day = String(entry.day ?? '').slice(5)
131
+ const clock = String(entry.from ?? '').slice(11, 16)
132
+ const title = String(entry.title ?? '').trim().slice(0, 60)
133
+ const next = String(entry.next ?? '').trim().slice(0, 60)
134
+ const line = `- ${day} ${clock} ${title}${next.length > 0 ? ` | 下一步:${next}` : ''}`
135
+ const ref = entry.seqFrom !== undefined && entry.seqTo !== undefined
136
+ ? `(原文 seq ${entry.seqFrom}–${entry.seqTo},要细节调 metabolism_skeleton 或 metabolism_recall)`
137
+ : ''
138
+ const body = [
139
+ '<骨架·回想>',
140
+ '(下面这条来自以前的归档,不是当前对话;只是提个醒,别当成他说的话)',
141
+ line,
142
+ ref,
143
+ '</骨架·回想>',
144
+ ]
145
+ .filter((part) => part.length > 0)
146
+ .join('\n')
147
+ return body.length > BUDGET ? `${body.slice(0, BUDGET)}…\n</骨架·回想>` : body
148
+ }
149
+
150
+ export function apply(ctx, options = {}) {
151
+ const log = (level, message) => {
152
+ try { ctx.logger?.[level]?.(message) } catch { /* 日志失败不抛 */ }
153
+ }
154
+ const archiveRoot = String(options.archiveRoot ?? '')
155
+ if (archiveRoot === '') return
156
+ const skeletonDir = join(archiveRoot, '..', '骨架')
157
+ const flagPath = String(options.flagPath ?? join(archiveRoot, '..', '代谢日志', '开关.json'))
158
+ const cooled = new Map()
159
+
160
+ ctx.effect(() => {
161
+ const off = ctx.on('agent/pre-step', async (payload, next) => {
162
+ const decision = await next()
163
+ try {
164
+ if (decision.kind === 'reject') return decision
165
+ if (!flagOn(flagPath, '每轮一条')) return decision
166
+ if (payload?.step !== 1) return decision
167
+
168
+ const session = payload?.agent?.session
169
+ if (session === undefined) return decision
170
+
171
+ // 这一轮他说的话:从后往前找最近一条人说的(跳过我们自己注入的)
172
+ let said = ''
173
+ for (let seq = Number(session.seq) - 1; seq >= 0; seq -= 1) {
174
+ const event = session.eventAt(seq)
175
+ if (event === undefined) continue
176
+ if (event.type !== 'user/message') continue
177
+ const kind = String(event.data?.source?.kind ?? '')
178
+ if (kind.startsWith('plugin:') || kind === 'compact-checkpoint') continue
179
+ const blocks = event.data?.content ?? event.data?.message?.content
180
+ if (!Array.isArray(blocks)) continue
181
+ said = blocks.filter((b) => b?.type === 'text').map((b) => b.text).join(' ').trim()
182
+ break
183
+ }
184
+ if (said.length < 4) return decision
185
+
186
+ let index
187
+ try {
188
+ index = JSON.parse(readFileSync(join(skeletonDir, 'index.json'), 'utf8').replace(/^\uFEFF/, ''))
189
+ } catch {
190
+ return decision
191
+ }
192
+ const entries = Array.isArray(index?.entries) ? index.entries : []
193
+ if (entries.length === 0) return decision
194
+
195
+ const pick = pickOne(entries, said, cooled)
196
+ if (pick === null) return decision
197
+
198
+ const agent = payload?.agent
199
+ if (typeof agent?.inject !== 'function') return decision
200
+
201
+ // index 里没有「下一步」,命中才去卡里抠一次
202
+ const entry = { ...pick.entry }
203
+ if (entry.layer === 1) {
204
+ const next = nextOf(join(skeletonDir, 'L1'), entry.id)
205
+ if (next.length > 0) entry.next = next
206
+ }
207
+ const block = blockOf(entry, pick.coverage)
208
+ agent.inject({
209
+ id: `metabolism-recall-${Date.now()}`,
210
+ role: 'user',
211
+ content: [{ type: 'text', text: block }],
212
+ source: { kind: 'plugin:metabolism' },
213
+ })
214
+ cooled.set(pick.entry.id, Number(payload?.turn) || 0)
215
+ // 冷却到期就放开
216
+ for (const [id, turn] of cooled) {
217
+ if ((Number(payload?.turn) || 0) - turn >= COOLDOWN_TURNS) cooled.delete(id)
218
+ }
219
+ log('info', `骨架贴条:${pick.entry.id}(命中 ${Math.round(pick.coverage * 100)}%)`)
220
+ } catch (error) {
221
+ log('warn', `骨架贴条失败(不影响这一轮):${error?.message ?? error}`)
222
+ }
223
+ return decision
224
+ })
225
+ return () => { off?.() }
226
+ })
227
+ }
228
+
229
+ export const inject = []
@@ -0,0 +1,69 @@
1
+ /**
2
+ * 重排层:把词面/向量捞出来的前几十条,跟问题一起喂给一个小模型,让它逐条判断「这条能不能回答这个问题」。
3
+ *
4
+ * 跟向量的区别:向量是分开算、比距离,快但糙;重排是把问题和条目拼在一起看(交叉编码),
5
+ * 慢但准,所以只用在最后十来条候选上。
6
+ *
7
+ * 设计:
8
+ * 1. 模型从镜像下到 记忆\代谢日志\模型,之后离线可用;换模型改 本地配置.json 里的 rerankModel;
9
+ * 2. 模型或依赖不在就返回空,上层按原顺序答——不能因为重排挂了就查不了;
10
+ * 3. 只对前 rerankTopN 条打分,其余保持原顺序。
11
+ *
12
+ * @module dsh-metabolism/重排
13
+ */
14
+ const DEFAULT_MODEL = 'Xenova/bge-reranker-base'
15
+ const MAX_CHARS = 1000
16
+
17
+ let loaded = null
18
+
19
+ function setupEnv(env, workspace) {
20
+ env.cacheDir = `${workspace}\\记忆\\代谢日志\\模型`
21
+ env.allowLocalModels = false
22
+ env.useBrowserCache = false
23
+ env.remoteHost = 'https://hf-mirror.com'
24
+ env.remotePathTemplate = '{model}/resolve/{revision}/'
25
+ }
26
+
27
+ /** 懒加载:tokenizer + 分类头。第一次要下模型,之后常驻。 */
28
+ export async function loadReranker(workspace, model = DEFAULT_MODEL, log = () => {}) {
29
+ if (loaded !== null && loaded.model === model) return loaded
30
+ const url = new URL('./node_modules/@huggingface/transformers/dist/transformers.node.mjs', import.meta.url)
31
+ const mod = await import(url.href)
32
+ setupEnv(mod.env, workspace)
33
+ const started = Date.now()
34
+ const tokenizer = await mod.AutoTokenizer.from_pretrained(model)
35
+ const scorer = await mod.AutoModelForSequenceClassification.from_pretrained(model, { dtype: 'q8' })
36
+ log(`重排模型已加载(${model},${Math.round((Date.now() - started) / 1000)}s)`)
37
+ loaded = { model, tokenizer, scorer }
38
+ return loaded
39
+ }
40
+
41
+ /**
42
+ * 给若干条候选打分。pairs: [{query, doc}] 或直接传 query + docs。
43
+ * 返回与 docs 等长的分数数组(越高越相关);失败返回 null。
44
+ */
45
+ export async function rerankScores(query, docs, workspace, options = {}) {
46
+ if (!Array.isArray(docs) || docs.length === 0) return []
47
+ const model = options.model ?? DEFAULT_MODEL
48
+ const { tokenizer, scorer } = await loadReranker(workspace, model, options.log ?? (() => {}))
49
+ const batch = Math.max(1, Number(options.batch) || 8)
50
+ const scores = []
51
+ for (let at = 0; at < docs.length; at += batch) {
52
+ const slice = docs.slice(at, at + batch)
53
+ // 注意:第二个参数得放进 options.text_pair,直接当第二参数传会被当成配置丢掉,
54
+ // 结果每一条都只编码了问题本身,分数一模一样(2026-11-20 踩过)。
55
+ const inputs = await tokenizer(
56
+ slice.map(() => String(query).slice(0, MAX_CHARS)),
57
+ { text_pair: slice.map((doc) => String(doc).replace(/\s+/g, ' ').slice(0, MAX_CHARS)), padding: true, truncation: true, max_length: 512 },
58
+ )
59
+ const output = await scorer(inputs)
60
+ const data = output.logits.data
61
+ const dims = output.logits.dims
62
+ const width = dims[dims.length - 1]
63
+ for (let row = 0; row < slice.length; row += 1) {
64
+ // 二分类:取「相关」那一类;单输出:取唯一那个值
65
+ scores.push(width >= 2 ? data[row * width + width - 1] : data[row * width])
66
+ }
67
+ }
68
+ return scores
69
+ }