toon-memory 4.4.1 → 4.5.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/README.de.md +47 -9
- package/README.es.md +47 -9
- package/README.fr.md +47 -9
- package/README.ja.md +47 -9
- package/README.ko.md +47 -9
- package/README.md +9 -9
- package/README.pt-br.md +45 -9
- package/README.zh.md +47 -9
- package/bin/toon-memory.js +2 -0
- package/dist/cli/setup.js +261 -117
- package/mcp/server.js +114 -29
- package/package.json +5 -2
- package/src/bin/toon-memory.ts +2 -0
- package/src/cli/ambient.ts +4 -1
- package/src/cli/dense.ts +72 -18
- package/src/cli/setup.ts +1 -1
- package/src/lib/dense.ts +186 -25
- package/src/lib/quality.ts +5 -2
- package/src/mcp/config.ts +2 -0
- package/src/mcp/tools.ts +2 -1
package/src/lib/dense.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createHash } from "crypto"
|
|
1
2
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"
|
|
2
3
|
import { dirname } from "path"
|
|
3
4
|
import { parseEntries } from "../lib/graph"
|
|
@@ -8,22 +9,77 @@ export interface DenseModule {
|
|
|
8
9
|
embed(texts: string[], model?: string): Promise<number[][]>
|
|
9
10
|
}
|
|
10
11
|
|
|
11
|
-
export interface
|
|
12
|
+
export interface VectorMeta {
|
|
13
|
+
model?: string
|
|
14
|
+
hashes?: Map<string, string>
|
|
15
|
+
builtAt?: string
|
|
16
|
+
sourceHash?: string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface StoredVectors extends VectorMeta {
|
|
12
20
|
dim: number
|
|
13
21
|
vectors: Map<string, number[]>
|
|
14
22
|
}
|
|
15
23
|
|
|
16
|
-
export
|
|
24
|
+
export interface RebuildStats {
|
|
25
|
+
written: number
|
|
26
|
+
reused: number
|
|
27
|
+
removed: number
|
|
28
|
+
stale: number
|
|
29
|
+
dim: number
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface DenseDiagnostics {
|
|
33
|
+
enabled: boolean
|
|
34
|
+
model: string
|
|
35
|
+
moduleSpec: string
|
|
36
|
+
moduleLoaded: boolean
|
|
37
|
+
error: string
|
|
38
|
+
vectors: number
|
|
39
|
+
dim: number
|
|
40
|
+
stale: number
|
|
41
|
+
builtAt: string
|
|
42
|
+
sourceHash: string
|
|
43
|
+
boost: number
|
|
44
|
+
autoBuild: boolean
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
type MemoryEntry = { key: string; content: string; status?: string }
|
|
48
|
+
|
|
49
|
+
function activeEntries(data: string): MemoryEntry[] {
|
|
50
|
+
return parseEntries(data).filter((e) => e.status !== "obsolete" && e.status !== "draft")
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function entryHash(entry: MemoryEntry): string {
|
|
54
|
+
return createHash("sha256").update(entry.key).update("\0").update(entry.content).digest("hex")
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function sourceHash(entries: MemoryEntry[]): string {
|
|
58
|
+
const hash = createHash("sha256")
|
|
59
|
+
for (const entry of entries) hash.update(entry.key).update("\0").update(entry.content).update("\n")
|
|
60
|
+
return hash.digest("hex")
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function loadDenseModuleDetailed(): Promise<{
|
|
64
|
+
module: DenseModule | null
|
|
65
|
+
spec: string
|
|
66
|
+
error: string
|
|
67
|
+
}> {
|
|
17
68
|
const spec = process.env.TOON_MEMORY_DENSE_MODULE || "toon-memory-dense"
|
|
18
69
|
try {
|
|
19
70
|
const mod: any = await import(spec)
|
|
20
71
|
const embed = mod?.embed || mod?.default?.embed || mod?.default
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
72
|
+
if (typeof embed !== "function") return { module: null, spec, error: "module does not export embed()" }
|
|
73
|
+
return { module: { embed }, spec, error: "" }
|
|
74
|
+
} catch (error) {
|
|
75
|
+
return { module: null, spec, error: error instanceof Error ? error.message : String(error) }
|
|
24
76
|
}
|
|
25
77
|
}
|
|
26
78
|
|
|
79
|
+
export async function loadDenseModule(): Promise<DenseModule | null> {
|
|
80
|
+
return (await loadDenseModuleDetailed()).module
|
|
81
|
+
}
|
|
82
|
+
|
|
27
83
|
export function cosine(a: number[], b: number[]): number {
|
|
28
84
|
const n = Math.min(a.length, b.length)
|
|
29
85
|
if (n === 0) return 0
|
|
@@ -41,48 +97,79 @@ export function cosine(a: number[], b: number[]): number {
|
|
|
41
97
|
}
|
|
42
98
|
|
|
43
99
|
export function readVectors(): StoredVectors {
|
|
44
|
-
const empty = { dim: 0, vectors: new Map
|
|
100
|
+
const empty: StoredVectors = { dim: 0, vectors: new Map() }
|
|
45
101
|
if (!existsSync(VECTORS_FILE)) return empty
|
|
46
102
|
try {
|
|
47
103
|
const buf = readFileSync(VECTORS_FILE)
|
|
48
104
|
const newline = buf.indexOf(0x0a)
|
|
49
105
|
if (newline === -1) return empty
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
const
|
|
106
|
+
const header = buf.subarray(0, newline).toString("utf-8")
|
|
107
|
+
const v1 = header.match(/^TMVEC1 (\d+)$/)
|
|
108
|
+
const v2 = header.match(/^TMVEC2 (\d+)(?: (\S+))?(?: (\S+))?(?: (\S+))?$/)
|
|
109
|
+
if (!v1 && !v2) return empty
|
|
110
|
+
const dim = Number((v1 || v2)![1])
|
|
53
111
|
if (!Number.isFinite(dim) || dim <= 0) return empty
|
|
112
|
+
const version = v1 ? 1 : 2
|
|
113
|
+
const meta = v2
|
|
114
|
+
? {
|
|
115
|
+
model: v2[2] || "",
|
|
116
|
+
builtAt: v2[3] || "",
|
|
117
|
+
sourceHash: v2[4] || "",
|
|
118
|
+
}
|
|
119
|
+
: {}
|
|
54
120
|
let offset = newline + 1
|
|
55
121
|
const vectors = new Map<string, number[]>()
|
|
122
|
+
const hashes = new Map<string, string>()
|
|
56
123
|
while (offset + 2 <= buf.length) {
|
|
57
124
|
const len = buf.readUInt16BE(offset)
|
|
58
125
|
offset += 2
|
|
59
|
-
if (offset + len
|
|
126
|
+
if (offset + len > buf.length) break
|
|
60
127
|
const key = buf.subarray(offset, offset + len).toString("utf-8")
|
|
61
128
|
offset += len
|
|
129
|
+
if (version === 2) {
|
|
130
|
+
if (offset + 2 > buf.length) break
|
|
131
|
+
const hashLen = buf.readUInt16BE(offset)
|
|
132
|
+
offset += 2
|
|
133
|
+
if (offset + hashLen + dim * 4 > buf.length) break
|
|
134
|
+
hashes.set(key, buf.subarray(offset, offset + hashLen).toString("utf-8"))
|
|
135
|
+
offset += hashLen
|
|
136
|
+
} else if (offset + dim * 4 > buf.length) break
|
|
62
137
|
const vec: number[] = []
|
|
63
138
|
for (let i = 0; i < dim; i++) vec.push(buf.readFloatLE(offset + i * 4))
|
|
64
139
|
offset += dim * 4
|
|
65
140
|
vectors.set(key, vec)
|
|
66
141
|
}
|
|
67
|
-
return { dim, vectors }
|
|
142
|
+
return { dim, vectors, hashes, ...meta }
|
|
68
143
|
} catch {
|
|
69
144
|
return empty
|
|
70
145
|
}
|
|
71
146
|
}
|
|
72
147
|
|
|
73
|
-
export function writeVectors(vectors: Map<string, number[]>, dim: number): number {
|
|
148
|
+
export function writeVectors(vectors: Map<string, number[]>, dim: number, meta: VectorMeta = {}): number {
|
|
74
149
|
const dir = dirname(VECTORS_FILE)
|
|
75
150
|
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
|
|
76
|
-
const
|
|
151
|
+
const version = meta.model || meta.builtAt || meta.sourceHash || meta.hashes ? 2 : 1
|
|
152
|
+
const header = version === 2
|
|
153
|
+
? `TMVEC2 ${dim} ${meta.model || ""} ${meta.builtAt || ""} ${meta.sourceHash || ""}\n`
|
|
154
|
+
: `TMVEC1 ${dim}\n`
|
|
155
|
+
const chunks: Buffer[] = [Buffer.from(header, "utf-8")]
|
|
77
156
|
let written = 0
|
|
78
157
|
for (const [key, vec] of vectors) {
|
|
79
158
|
if (vec.length !== dim) continue
|
|
80
159
|
const keyBuf = Buffer.from(key, "utf-8")
|
|
160
|
+
if (keyBuf.length > 0xffff) continue
|
|
81
161
|
const lenBuf = Buffer.alloc(2)
|
|
82
162
|
lenBuf.writeUInt16BE(keyBuf.length)
|
|
83
163
|
const vecBuf = Buffer.alloc(dim * 4)
|
|
84
164
|
for (let i = 0; i < dim; i++) vecBuf.writeFloatLE(vec[i], i * 4)
|
|
85
|
-
chunks.push(lenBuf, keyBuf
|
|
165
|
+
chunks.push(lenBuf, keyBuf)
|
|
166
|
+
if (version === 2) {
|
|
167
|
+
const hashBuf = Buffer.from(meta.hashes?.get(key) || "", "utf-8")
|
|
168
|
+
const hashLenBuf = Buffer.alloc(2)
|
|
169
|
+
hashLenBuf.writeUInt16BE(hashBuf.length)
|
|
170
|
+
chunks.push(hashLenBuf, hashBuf)
|
|
171
|
+
}
|
|
172
|
+
chunks.push(vecBuf)
|
|
86
173
|
written++
|
|
87
174
|
}
|
|
88
175
|
const out = Buffer.concat(chunks)
|
|
@@ -90,26 +177,100 @@ export function writeVectors(vectors: Map<string, number[]>, dim: number): numbe
|
|
|
90
177
|
return written
|
|
91
178
|
}
|
|
92
179
|
|
|
93
|
-
export
|
|
94
|
-
const entries =
|
|
180
|
+
export function staleVectorCount(data: string, stored: StoredVectors = readVectors()): number {
|
|
181
|
+
const entries = activeEntries(data)
|
|
95
182
|
if (entries.length === 0) return 0
|
|
96
|
-
|
|
97
|
-
const
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
183
|
+
let stale = 0
|
|
184
|
+
for (const entry of entries) {
|
|
185
|
+
const vec = stored.vectors.get(entry.key)
|
|
186
|
+
if (!vec || vec.length !== stored.dim) {
|
|
187
|
+
stale++
|
|
188
|
+
continue
|
|
189
|
+
}
|
|
190
|
+
const hash = stored.hashes?.get(entry.key)
|
|
191
|
+
if (!hash || hash !== entryHash(entry)) stale++
|
|
192
|
+
}
|
|
193
|
+
return stale
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export async function rebuildVectors(
|
|
197
|
+
data: string,
|
|
198
|
+
module: DenseModule,
|
|
199
|
+
model?: string,
|
|
200
|
+
opts: { force?: boolean } = {}
|
|
201
|
+
): Promise<RebuildStats> {
|
|
202
|
+
const entries = activeEntries(data)
|
|
203
|
+
if (entries.length === 0) return { written: 0, reused: 0, removed: 0, stale: 0, dim: 0 }
|
|
204
|
+
const stored = readVectors()
|
|
205
|
+
const hashes = new Map(entries.map((entry) => [entry.key, entryHash(entry)]))
|
|
206
|
+
const source = sourceHash(entries)
|
|
207
|
+
const reused = new Map<string, number[]>()
|
|
208
|
+
if (!opts.force && stored.model === (model || stored.model)) {
|
|
209
|
+
for (const [key, hash] of hashes) {
|
|
210
|
+
const vec = stored.vectors.get(key)
|
|
211
|
+
if (vec?.length === stored.dim && stored.hashes?.get(key) === hash) reused.set(key, vec)
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const stale = entries.filter((entry) => !reused.has(entry.key))
|
|
215
|
+
const embedded = stale.length ? await module.embed(stale.map((entry) => `${entry.key} ${entry.content}`), model) : []
|
|
216
|
+
const dim = reused.values().next().value?.length || embedded.find((vec) => vec?.length)?.length || stored.dim
|
|
217
|
+
if (!dim) return { written: 0, reused: 0, removed: 0, stale: stale.length, dim: 0 }
|
|
218
|
+
const vectors = new Map(reused)
|
|
219
|
+
let written = 0
|
|
220
|
+
stale.forEach((entry, i) => {
|
|
221
|
+
const vec = embedded[i]
|
|
222
|
+
if (vec?.length === dim) {
|
|
223
|
+
vectors.set(entry.key, vec)
|
|
224
|
+
written++
|
|
225
|
+
}
|
|
102
226
|
})
|
|
103
|
-
|
|
227
|
+
const removed = [...stored.vectors.keys()].filter((key) => !hashes.has(key)).length
|
|
228
|
+
for (const key of vectors.keys()) if (!hashes.has(key)) vectors.delete(key)
|
|
229
|
+
writeVectors(vectors, dim, {
|
|
230
|
+
model,
|
|
231
|
+
hashes,
|
|
232
|
+
builtAt: new Date().toISOString(),
|
|
233
|
+
sourceHash: source,
|
|
234
|
+
})
|
|
235
|
+
return { written, reused: reused.size, removed, stale: stale.length, dim }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export async function buildVectors(data: string, module: DenseModule, model?: string): Promise<number> {
|
|
239
|
+
const result = await rebuildVectors(data, module, model, { force: true })
|
|
240
|
+
return result.written
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export async function denseDiagnostics(data: string): Promise<DenseDiagnostics> {
|
|
244
|
+
const config = loadConfig()
|
|
245
|
+
const stored = readVectors()
|
|
246
|
+
const detailed = await loadDenseModuleDetailed()
|
|
247
|
+
return {
|
|
248
|
+
enabled: Boolean(config.dense?.enabled),
|
|
249
|
+
model: config.dense?.model || "",
|
|
250
|
+
moduleSpec: detailed.spec,
|
|
251
|
+
moduleLoaded: Boolean(detailed.module),
|
|
252
|
+
error: detailed.error,
|
|
253
|
+
vectors: stored.vectors.size,
|
|
254
|
+
dim: stored.dim,
|
|
255
|
+
stale: staleVectorCount(data, stored),
|
|
256
|
+
builtAt: stored.builtAt || "",
|
|
257
|
+
sourceHash: stored.sourceHash || "",
|
|
258
|
+
boost: config.dense?.boost ?? 0.25,
|
|
259
|
+
autoBuild: config.dense?.autoBuild !== false,
|
|
260
|
+
}
|
|
104
261
|
}
|
|
105
262
|
|
|
106
263
|
export async function denseScores(query: string, data: string): Promise<Map<string, number>> {
|
|
107
264
|
const config = loadConfig()
|
|
108
265
|
if (!config.dense?.enabled || !query.trim()) return new Map()
|
|
109
266
|
try {
|
|
110
|
-
const
|
|
267
|
+
const detailed = await loadDenseModuleDetailed()
|
|
268
|
+
const module = detailed.module
|
|
111
269
|
if (!module) return new Map()
|
|
112
|
-
|
|
270
|
+
const autoBuild = config.dense.autoBuild !== false
|
|
271
|
+
if (autoBuild && (readVectors().vectors.size === 0 || staleVectorCount(data) > 0)) {
|
|
272
|
+
await rebuildVectors(data, module, config.dense.model)
|
|
273
|
+
}
|
|
113
274
|
const stored = readVectors()
|
|
114
275
|
if (stored.vectors.size === 0) return new Map()
|
|
115
276
|
const [queryVec] = await module.embed([query], config.dense.model)
|
package/src/lib/quality.ts
CHANGED
|
@@ -217,6 +217,8 @@ export function generateSmartRecall(
|
|
|
217
217
|
explain?: boolean
|
|
218
218
|
budgetTokens?: number
|
|
219
219
|
utility?: Map<string, number>
|
|
220
|
+
dense?: Map<string, number>
|
|
221
|
+
denseBoost?: number
|
|
220
222
|
} = {}
|
|
221
223
|
): string {
|
|
222
224
|
const entries = parseEntries(data)
|
|
@@ -305,11 +307,12 @@ export function generateSmartRecall(
|
|
|
305
307
|
const ngBoost = ngMatch ? ngScore * 0.15 : 0
|
|
306
308
|
let combined: number
|
|
307
309
|
const utilityBoost = (opts.utility?.get(e.key) || 0) * 0.25
|
|
310
|
+
const denseBoost = (opts.dense?.get(e.key) || 0) * (opts.denseBoost ?? 0.25)
|
|
308
311
|
if (opts.rrf) {
|
|
309
|
-
combined = (fused?.get(e.key) ?? 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost + evBoost + ngBoost + utilityBoost
|
|
312
|
+
combined = (fused?.get(e.key) ?? 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost + evBoost + ngBoost + utilityBoost + denseBoost
|
|
310
313
|
} else {
|
|
311
314
|
combined =
|
|
312
|
-
bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost + evBoost + utilityBoost
|
|
315
|
+
bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost + evBoost + utilityBoost + denseBoost
|
|
313
316
|
}
|
|
314
317
|
return { entry: e, score: combined, matchesQuery, priority: e.priority, bm25Score }
|
|
315
318
|
})
|
package/src/mcp/config.ts
CHANGED
package/src/mcp/tools.ts
CHANGED
|
@@ -60,6 +60,7 @@ type ToolText = { type: "text"; text: string }
|
|
|
60
60
|
edges?: ActivationEdge[]
|
|
61
61
|
activation?: boolean
|
|
62
62
|
dense?: Map<string, number>
|
|
63
|
+
denseBoost?: number
|
|
63
64
|
}> => {
|
|
64
65
|
const config = loadConfig()
|
|
65
66
|
const edges = config.graph?.activation ? readEdges() : undefined
|
|
@@ -67,7 +68,7 @@ type ToolText = { type: "text"; text: string }
|
|
|
67
68
|
return {
|
|
68
69
|
utility: utilityMap(),
|
|
69
70
|
...(edges && edges.length ? { edges, activation: true } : {}),
|
|
70
|
-
...(dense.size ? { dense } : {}),
|
|
71
|
+
...(dense.size ? { dense, denseBoost: config.dense?.boost ?? 0.25 } : {}),
|
|
71
72
|
}
|
|
72
73
|
}
|
|
73
74
|
|