@modusensus/dsh-mneme 0.6.7 → 0.6.8

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.
Files changed (117) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +463 -463
  3. package/cordis.patch.yml +15 -15
  4. package/lib/api.js +783 -783
  5. package/lib/client.js +1757 -1757
  6. package/lib/commands.js +64 -64
  7. package/lib/config.js +288 -288
  8. package/lib/dream/clustering.js +118 -118
  9. package/lib/dream/decisions.js +439 -439
  10. package/lib/dream/sleep.js +561 -554
  11. package/lib/dream/tag-extractor.js +156 -156
  12. package/lib/dream.js +935 -929
  13. package/lib/embedding.js +154 -154
  14. package/lib/entities/extractor.js +242 -242
  15. package/lib/hot-memory.js +53 -53
  16. package/lib/index.js +361 -361
  17. package/lib/inject.js +208 -208
  18. package/lib/local-embedder.js +282 -282
  19. package/lib/mirror.js +170 -170
  20. package/lib/parser/tag.js +59 -59
  21. package/lib/parser/wiki-link.js +38 -38
  22. package/lib/quality-filter.js +123 -123
  23. package/lib/reranker.js +218 -218
  24. package/lib/search/adaptive.js +22 -22
  25. package/lib/search/bm25.js +96 -96
  26. package/lib/search/tag-boost.js +61 -61
  27. package/lib/service.js +1726 -1726
  28. package/lib/settings.js +172 -172
  29. package/lib/store.js +2238 -2238
  30. package/lib/summarize.js +236 -236
  31. package/lib/tools.js +290 -290
  32. package/lib/vector-index.js +116 -116
  33. package/package.json +80 -80
  34. package/scripts/benchmark-embed.js +201 -201
  35. package/scripts/benchmark-recall.js +133 -133
  36. package/scripts/benchmark-rerank.js +166 -166
  37. package/scripts/e2e-dsh.js +218 -218
  38. package/scripts/stress-dsh.js +255 -255
  39. package/scripts/sync-lib.js +52 -52
  40. package/src/api.js +783 -783
  41. package/src/commands.js +64 -64
  42. package/src/config.js +288 -288
  43. package/src/dream/clustering.js +118 -118
  44. package/src/dream/decisions.js +439 -439
  45. package/src/dream/sleep.js +561 -554
  46. package/src/dream/tag-extractor.js +156 -156
  47. package/src/dream.js +935 -929
  48. package/src/embedding.js +154 -154
  49. package/src/entities/extractor.js +242 -242
  50. package/src/hot-memory.js +53 -53
  51. package/src/index.js +361 -361
  52. package/src/inject.js +208 -208
  53. package/src/local-embedder.js +282 -282
  54. package/src/mirror.js +170 -170
  55. package/src/parser/tag.js +59 -59
  56. package/src/parser/wiki-link.js +38 -38
  57. package/src/quality-filter.js +123 -123
  58. package/src/reranker.js +218 -218
  59. package/src/search/adaptive.js +22 -22
  60. package/src/search/bm25.js +96 -96
  61. package/src/search/tag-boost.js +61 -61
  62. package/src/service.js +1726 -1726
  63. package/src/settings.js +172 -172
  64. package/src/store.js +2238 -2238
  65. package/src/summarize.js +236 -236
  66. package/src/tools.js +290 -290
  67. package/src/vector-index.js +116 -116
  68. package/test/api.test.js +594 -594
  69. package/test/audit.test.js +448 -448
  70. package/test/benchmark.test.js +35 -35
  71. package/test/boundary-v0625.test.js +82 -82
  72. package/test/client.test.js +368 -368
  73. package/test/clustering.test.js +100 -100
  74. package/test/commands.test.js +69 -69
  75. package/test/config.test.js +50 -50
  76. package/test/conflict-freeze.test.js +290 -290
  77. package/test/directory.test.js +134 -134
  78. package/test/dream.test.js +903 -901
  79. package/test/entities.test.js +522 -522
  80. package/test/epistemic.test.js +298 -298
  81. package/test/fnew-0112.test.js +311 -311
  82. package/test/fnew-03.test.js +422 -422
  83. package/test/graph-api.test.js +175 -175
  84. package/test/helpers/dream-mock.js +82 -82
  85. package/test/hot-memory.test.js +174 -174
  86. package/test/inject.test.js +103 -103
  87. package/test/llm-audit.test.js +279 -279
  88. package/test/local-embedder.test.js +227 -227
  89. package/test/mirror-dirty.test.js +424 -424
  90. package/test/mirror-edit-digest.test.js +187 -187
  91. package/test/mirror-generation.test.js +499 -499
  92. package/test/mirror.test.js +249 -249
  93. package/test/normalize-decisions.test.js +120 -120
  94. package/test/peer-blockers.test.js +190 -190
  95. package/test/policy-epoch.test.js +259 -259
  96. package/test/provenance.test.js +103 -103
  97. package/test/quality-filter.test.js +118 -118
  98. package/test/reasoning-effort.test.js +199 -199
  99. package/test/recall-evals.test.js +235 -235
  100. package/test/recall-layer.test.js +315 -315
  101. package/test/receipt-chain.test.js +451 -451
  102. package/test/reflection.test.js +226 -226
  103. package/test/reranker.test.js +240 -240
  104. package/test/search-fusion.test.js +90 -90
  105. package/test/semantic.test.js +124 -124
  106. package/test/service-search.test.js +199 -199
  107. package/test/service.test.js +435 -435
  108. package/test/settings.test.js +118 -118
  109. package/test/sleep.test.js +365 -365
  110. package/test/store.test.js +436 -436
  111. package/test/stress.test.js +209 -209
  112. package/test/summarize.test.js +191 -191
  113. package/test/tag-boost.test.js +125 -125
  114. package/test/tag.test.js +312 -312
  115. package/test/tools.test.js +285 -285
  116. package/test/vector-index.test.js +221 -221
  117. package/test/wiki-link.test.js +332 -332
@@ -1,242 +1,242 @@
1
- const VALID_TYPES = new Set(["person", "project", "concept", "technology", "organization"]);
2
- const VALID_RELATIONS = new Set(["uses", "depends_on", "part_of", "related_to"]);
3
- const MAX_MEMORY_CHARS = 4000;
4
-
5
- function buildSystemPrompt(config) {
6
- const maxEntities = config.entityExtractionMaxEntities ?? 10;
7
- const maxAttrs = config.entityExtractionMaxAttrs ?? 20;
8
-
9
- return `You are an entity extraction engine. Extract named entities, their attributes, and relations from the given text.
10
-
11
- RULES:
12
- - Entities are concrete people, projects, technologies, concepts, or organizations.
13
- - Attributes are characteristic states of an entity. Only extract attributes explicitly mentioned in the text.
14
- - Do NOT infer, guess, or hallucinate. Only extract what is clearly stated.
15
- - Use canonical names (full name / primary name). Do NOT merge synonyms — different spellings of the same person are different entities.
16
- - Output MUST be strict JSON with this exact structure:
17
- {
18
- "entities": [
19
- {"name": "string", "type": "person|project|concept|technology|organization", "attrs": [{"key": "string", "value": "string", "confidence": 0.9}]}
20
- ],
21
- "relations": [
22
- {"from": "entityName", "to": "entityName", "type": "uses|depends_on|part_of|related_to"}
23
- ]
24
- }
25
-
26
- CONSTRAINTS:
27
- - "type" must be one of: person, project, concept, technology, organization. If unsure, use "concept".
28
- - "relations" from/to must reference entity names from the "entities" list.
29
- - Maximum ${maxEntities} entities. Maximum ${maxAttrs} attributes per entity. Truncate if exceeded.
30
- - Only include entity-related attributes. Ignore irrelevant miscellaneous details.
31
- - Return ONLY the JSON object. No explanations, no markdown, no code fences.`;
32
- }
33
-
34
- function buildUserMessage(memoryText) {
35
- const truncated = memoryText.length > MAX_MEMORY_CHARS
36
- ? memoryText.slice(0, MAX_MEMORY_CHARS) + "..."
37
- : memoryText;
38
- return truncated;
39
- }
40
-
41
- function extractJsonFromText(text) {
42
- if (!text || typeof text !== "string") return null;
43
-
44
- // Try direct parse first
45
- try {
46
- return JSON.parse(text);
47
- } catch {
48
- // fall through
49
- }
50
-
51
- // Try to find first {...} block
52
- const match = text.match(/\{[\s\S]*\}/);
53
- if (match) {
54
- try {
55
- return JSON.parse(match[0]);
56
- } catch {
57
- return null;
58
- }
59
- }
60
-
61
- return null;
62
- }
63
-
64
- function sanitizeType(type) {
65
- if (VALID_TYPES.has(type)) return type;
66
- return "concept";
67
- }
68
-
69
- function sanitizeConfidence(conf) {
70
- const num = Number(conf);
71
- if (Number.isNaN(num)) return 0.9;
72
- return Math.min(1, Math.max(0, num));
73
- }
74
-
75
- function sanitizeRelationType(type) {
76
- if (VALID_RELATIONS.has(type)) return type;
77
- return "related_to";
78
- }
79
-
80
- function sanitizeExtractedData(data, config) {
81
- const maxEntities = config.entityExtractionMaxEntities ?? 10;
82
- const maxAttrs = config.entityExtractionMaxAttrs ?? 20;
83
-
84
- if (!data || !Array.isArray(data.entities)) {
85
- throw new Error("Invalid extraction: missing entities array");
86
- }
87
-
88
- const entities = [];
89
- const seenNames = new Set();
90
-
91
- for (const rawEntity of data.entities.slice(0, maxEntities)) {
92
- if (!rawEntity || typeof rawEntity.name !== "string" || !rawEntity.name.trim()) continue;
93
-
94
- const name = rawEntity.name.trim();
95
- if (seenNames.has(name)) continue;
96
- seenNames.add(name);
97
-
98
- const attrs = [];
99
- if (Array.isArray(rawEntity.attrs)) {
100
- for (const rawAttr of rawEntity.attrs.slice(0, maxAttrs)) {
101
- if (!rawAttr || typeof rawAttr.key !== "string" || typeof rawAttr.value !== "string") continue;
102
- attrs.push({
103
- key: rawAttr.key.trim(),
104
- value: rawAttr.value.trim(),
105
- confidence: sanitizeConfidence(rawAttr.confidence)
106
- });
107
- }
108
- }
109
-
110
- entities.push({
111
- name,
112
- type: sanitizeType(rawEntity.type),
113
- attrs
114
- });
115
- }
116
-
117
- const relations = [];
118
- if (Array.isArray(data.relations)) {
119
- for (const rawRel of data.relations) {
120
- if (!rawRel || typeof rawRel.from !== "string" || typeof rawRel.to !== "string") continue;
121
- if (!seenNames.has(rawRel.from) || !seenNames.has(rawRel.to)) continue;
122
- relations.push({
123
- from: rawRel.from,
124
- to: rawRel.to,
125
- type: sanitizeRelationType(rawRel.type)
126
- });
127
- }
128
- }
129
-
130
- return { entities, relations };
131
- }
132
-
133
- async function resolveEntity(entity, store) {
134
- const existing = store.findEntityByName(entity.name);
135
- if (existing) {
136
- store.updateEntity(existing.id, {});
137
- return existing.id;
138
- }
139
- const created = store.createEntity({ name: entity.name, type: entity.type });
140
- return created.id;
141
- }
142
-
143
- export async function extractEntities(memory, { store, config, callLLM, logger }) {
144
- try {
145
- if (!memory || !memory.content) {
146
- return { ok: false, error: "Invalid memory: missing content" };
147
- }
148
-
149
- const model = config.entityExtractionModel || null;
150
- const systemPrompt = buildSystemPrompt(config);
151
- const userText = buildUserMessage(memory.content);
152
-
153
- const messages = [
154
- { role: "system", content: [{ type: "text", text: systemPrompt }] },
155
- { role: "user", content: [{ type: "text", text: userText }] }
156
- ];
157
-
158
- const options = model ? { model } : {};
159
- const llmResponse = await callLLM(messages, options);
160
-
161
- if (!llmResponse) {
162
- return { ok: false, error: "LLM returned empty response" };
163
- }
164
-
165
- const rawData = extractJsonFromText(llmResponse);
166
- if (!rawData) {
167
- return { ok: false, error: "Failed to parse JSON from LLM response" };
168
- }
169
-
170
- const { entities, relations } = sanitizeExtractedData(rawData, config);
171
-
172
- const resolvedEntities = [];
173
- const entityIdMap = new Map();
174
- let skipCount = 0;
175
-
176
- // Resolve entities
177
- for (const entity of entities) {
178
- try {
179
- const entityId = await resolveEntity(entity, store);
180
- entityIdMap.set(entity.name, entityId);
181
- resolvedEntities.push({ ...entity, entity_id: entityId });
182
- } catch (err) {
183
- skipCount++;
184
- logger?.warn?.(`[extractor] Failed to resolve entity "${entity.name}":`, err.message);
185
- }
186
- }
187
-
188
- // Record attributes
189
- const attrs = [];
190
- for (const entity of resolvedEntities) {
191
- for (const attr of entity.attrs) {
192
- try {
193
- const saved = store.saveAttr({
194
- entity_id: entity.entity_id,
195
- attr_key: attr.key,
196
- attr_value: String(attr.value),
197
- memory_id: memory.id,
198
- confidence: attr.confidence,
199
- source: "llm_extract"
200
- });
201
- attrs.push(saved);
202
- } catch (err) {
203
- skipCount++;
204
- logger?.warn?.(`[extractor] Failed to save attr "${attr.key}" for entity "${entity.name}":`, err.message);
205
- }
206
- }
207
- }
208
-
209
- // Record relations
210
- const savedRelations = [];
211
- for (const rel of relations) {
212
- const fromId = entityIdMap.get(rel.from);
213
- const toId = entityIdMap.get(rel.to);
214
- if (!fromId || !toId) continue;
215
-
216
- try {
217
- const saved = store.saveRelation({
218
- from_entity: fromId,
219
- to_entity: toId,
220
- relation_type: rel.type,
221
- memory_id: memory.id,
222
- metadata: { model: model || "default" }
223
- });
224
- savedRelations.push(saved);
225
- } catch (err) {
226
- skipCount++;
227
- logger?.warn?.(`[extractor] Failed to save relation "${rel.from} -> ${rel.to}":`, err.message);
228
- }
229
- }
230
-
231
- return {
232
- ok: true,
233
- entities: resolvedEntities,
234
- attrs,
235
- relations: savedRelations,
236
- skipped: skipCount
237
- };
238
-
239
- } catch (err) {
240
- return { ok: false, error: String(err) };
241
- }
242
- }
1
+ const VALID_TYPES = new Set(["person", "project", "concept", "technology", "organization"]);
2
+ const VALID_RELATIONS = new Set(["uses", "depends_on", "part_of", "related_to"]);
3
+ const MAX_MEMORY_CHARS = 4000;
4
+
5
+ function buildSystemPrompt(config) {
6
+ const maxEntities = config.entityExtractionMaxEntities ?? 10;
7
+ const maxAttrs = config.entityExtractionMaxAttrs ?? 20;
8
+
9
+ return `You are an entity extraction engine. Extract named entities, their attributes, and relations from the given text.
10
+
11
+ RULES:
12
+ - Entities are concrete people, projects, technologies, concepts, or organizations.
13
+ - Attributes are characteristic states of an entity. Only extract attributes explicitly mentioned in the text.
14
+ - Do NOT infer, guess, or hallucinate. Only extract what is clearly stated.
15
+ - Use canonical names (full name / primary name). Do NOT merge synonyms — different spellings of the same person are different entities.
16
+ - Output MUST be strict JSON with this exact structure:
17
+ {
18
+ "entities": [
19
+ {"name": "string", "type": "person|project|concept|technology|organization", "attrs": [{"key": "string", "value": "string", "confidence": 0.9}]}
20
+ ],
21
+ "relations": [
22
+ {"from": "entityName", "to": "entityName", "type": "uses|depends_on|part_of|related_to"}
23
+ ]
24
+ }
25
+
26
+ CONSTRAINTS:
27
+ - "type" must be one of: person, project, concept, technology, organization. If unsure, use "concept".
28
+ - "relations" from/to must reference entity names from the "entities" list.
29
+ - Maximum ${maxEntities} entities. Maximum ${maxAttrs} attributes per entity. Truncate if exceeded.
30
+ - Only include entity-related attributes. Ignore irrelevant miscellaneous details.
31
+ - Return ONLY the JSON object. No explanations, no markdown, no code fences.`;
32
+ }
33
+
34
+ function buildUserMessage(memoryText) {
35
+ const truncated = memoryText.length > MAX_MEMORY_CHARS
36
+ ? memoryText.slice(0, MAX_MEMORY_CHARS) + "..."
37
+ : memoryText;
38
+ return truncated;
39
+ }
40
+
41
+ function extractJsonFromText(text) {
42
+ if (!text || typeof text !== "string") return null;
43
+
44
+ // Try direct parse first
45
+ try {
46
+ return JSON.parse(text);
47
+ } catch {
48
+ // fall through
49
+ }
50
+
51
+ // Try to find first {...} block
52
+ const match = text.match(/\{[\s\S]*\}/);
53
+ if (match) {
54
+ try {
55
+ return JSON.parse(match[0]);
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ return null;
62
+ }
63
+
64
+ function sanitizeType(type) {
65
+ if (VALID_TYPES.has(type)) return type;
66
+ return "concept";
67
+ }
68
+
69
+ function sanitizeConfidence(conf) {
70
+ const num = Number(conf);
71
+ if (Number.isNaN(num)) return 0.9;
72
+ return Math.min(1, Math.max(0, num));
73
+ }
74
+
75
+ function sanitizeRelationType(type) {
76
+ if (VALID_RELATIONS.has(type)) return type;
77
+ return "related_to";
78
+ }
79
+
80
+ function sanitizeExtractedData(data, config) {
81
+ const maxEntities = config.entityExtractionMaxEntities ?? 10;
82
+ const maxAttrs = config.entityExtractionMaxAttrs ?? 20;
83
+
84
+ if (!data || !Array.isArray(data.entities)) {
85
+ throw new Error("Invalid extraction: missing entities array");
86
+ }
87
+
88
+ const entities = [];
89
+ const seenNames = new Set();
90
+
91
+ for (const rawEntity of data.entities.slice(0, maxEntities)) {
92
+ if (!rawEntity || typeof rawEntity.name !== "string" || !rawEntity.name.trim()) continue;
93
+
94
+ const name = rawEntity.name.trim();
95
+ if (seenNames.has(name)) continue;
96
+ seenNames.add(name);
97
+
98
+ const attrs = [];
99
+ if (Array.isArray(rawEntity.attrs)) {
100
+ for (const rawAttr of rawEntity.attrs.slice(0, maxAttrs)) {
101
+ if (!rawAttr || typeof rawAttr.key !== "string" || typeof rawAttr.value !== "string") continue;
102
+ attrs.push({
103
+ key: rawAttr.key.trim(),
104
+ value: rawAttr.value.trim(),
105
+ confidence: sanitizeConfidence(rawAttr.confidence)
106
+ });
107
+ }
108
+ }
109
+
110
+ entities.push({
111
+ name,
112
+ type: sanitizeType(rawEntity.type),
113
+ attrs
114
+ });
115
+ }
116
+
117
+ const relations = [];
118
+ if (Array.isArray(data.relations)) {
119
+ for (const rawRel of data.relations) {
120
+ if (!rawRel || typeof rawRel.from !== "string" || typeof rawRel.to !== "string") continue;
121
+ if (!seenNames.has(rawRel.from) || !seenNames.has(rawRel.to)) continue;
122
+ relations.push({
123
+ from: rawRel.from,
124
+ to: rawRel.to,
125
+ type: sanitizeRelationType(rawRel.type)
126
+ });
127
+ }
128
+ }
129
+
130
+ return { entities, relations };
131
+ }
132
+
133
+ async function resolveEntity(entity, store) {
134
+ const existing = store.findEntityByName(entity.name);
135
+ if (existing) {
136
+ store.updateEntity(existing.id, {});
137
+ return existing.id;
138
+ }
139
+ const created = store.createEntity({ name: entity.name, type: entity.type });
140
+ return created.id;
141
+ }
142
+
143
+ export async function extractEntities(memory, { store, config, callLLM, logger }) {
144
+ try {
145
+ if (!memory || !memory.content) {
146
+ return { ok: false, error: "Invalid memory: missing content" };
147
+ }
148
+
149
+ const model = config.entityExtractionModel || null;
150
+ const systemPrompt = buildSystemPrompt(config);
151
+ const userText = buildUserMessage(memory.content);
152
+
153
+ const messages = [
154
+ { role: "system", content: [{ type: "text", text: systemPrompt }] },
155
+ { role: "user", content: [{ type: "text", text: userText }] }
156
+ ];
157
+
158
+ const options = model ? { model } : {};
159
+ const llmResponse = await callLLM(messages, options);
160
+
161
+ if (!llmResponse) {
162
+ return { ok: false, error: "LLM returned empty response" };
163
+ }
164
+
165
+ const rawData = extractJsonFromText(llmResponse);
166
+ if (!rawData) {
167
+ return { ok: false, error: "Failed to parse JSON from LLM response" };
168
+ }
169
+
170
+ const { entities, relations } = sanitizeExtractedData(rawData, config);
171
+
172
+ const resolvedEntities = [];
173
+ const entityIdMap = new Map();
174
+ let skipCount = 0;
175
+
176
+ // Resolve entities
177
+ for (const entity of entities) {
178
+ try {
179
+ const entityId = await resolveEntity(entity, store);
180
+ entityIdMap.set(entity.name, entityId);
181
+ resolvedEntities.push({ ...entity, entity_id: entityId });
182
+ } catch (err) {
183
+ skipCount++;
184
+ logger?.warn?.(`[extractor] Failed to resolve entity "${entity.name}":`, err.message);
185
+ }
186
+ }
187
+
188
+ // Record attributes
189
+ const attrs = [];
190
+ for (const entity of resolvedEntities) {
191
+ for (const attr of entity.attrs) {
192
+ try {
193
+ const saved = store.saveAttr({
194
+ entity_id: entity.entity_id,
195
+ attr_key: attr.key,
196
+ attr_value: String(attr.value),
197
+ memory_id: memory.id,
198
+ confidence: attr.confidence,
199
+ source: "llm_extract"
200
+ });
201
+ attrs.push(saved);
202
+ } catch (err) {
203
+ skipCount++;
204
+ logger?.warn?.(`[extractor] Failed to save attr "${attr.key}" for entity "${entity.name}":`, err.message);
205
+ }
206
+ }
207
+ }
208
+
209
+ // Record relations
210
+ const savedRelations = [];
211
+ for (const rel of relations) {
212
+ const fromId = entityIdMap.get(rel.from);
213
+ const toId = entityIdMap.get(rel.to);
214
+ if (!fromId || !toId) continue;
215
+
216
+ try {
217
+ const saved = store.saveRelation({
218
+ from_entity: fromId,
219
+ to_entity: toId,
220
+ relation_type: rel.type,
221
+ memory_id: memory.id,
222
+ metadata: { model: model || "default" }
223
+ });
224
+ savedRelations.push(saved);
225
+ } catch (err) {
226
+ skipCount++;
227
+ logger?.warn?.(`[extractor] Failed to save relation "${rel.from} -> ${rel.to}":`, err.message);
228
+ }
229
+ }
230
+
231
+ return {
232
+ ok: true,
233
+ entities: resolvedEntities,
234
+ attrs,
235
+ relations: savedRelations,
236
+ skipped: skipCount
237
+ };
238
+
239
+ } catch (err) {
240
+ return { ok: false, error: String(err) };
241
+ }
242
+ }
package/src/hot-memory.js CHANGED
@@ -1,53 +1,53 @@
1
- // Session-scoped hot memory (v0.5.0 召回率优化 1.3): a short-term buffer of
2
- // the latest dialogue rounds, kept strictly apart from the long-term memory
3
- // store. The injector renders it ahead of the long-term recall block so the
4
- // agent sees "what we were just talking about" without those rounds ever
5
- // being persisted as memories. Bounded two ways: maxRounds (count) and
6
- // maxTokens (budget) — whichever evicts first.
7
-
8
- // CJK-aware token estimate: one Chinese character ≈ 0.6 tokens (clustering
9
- // behavior of mainstream tokenizers), one ASCII char ≈ 0.25.
10
- export function estimateTokens(text) {
11
- const s = String(text ?? "");
12
- let cjk = 0;
13
- for (const ch of s) if (ch >= "\u4e00" && ch <= "\u9fff") cjk++;
14
- return Math.ceil(cjk * 0.6 + (s.length - cjk) * 0.25);
15
- }
16
-
17
- /**
18
- * @param {{maxRounds?: number, maxTokens?: number}} opts
19
- * @returns {{add(round: {query: string, response?: string}): void,
20
- * getContext(): string,
21
- * rounds(): Array, clear(): void}}
22
- */
23
- export function createHotMemory({ maxRounds = 5, maxTokens = 2000 } = {}) {
24
- // Entry defense: a non-positive or non-integer maxRounds (0, -1, 1.5, NaN,
25
- // null, "2") would make the eviction while-loop unbounded — the buffer can
26
- // never shrink below `buffer.length > maxRounds`, so `add` would spin forever.
27
- // Fall back to the defaults so a hostile/buggy caller can never wedge the
28
- // hot-memory buffer in an infinite loop.
29
- maxRounds = (Number.isInteger(maxRounds) && maxRounds > 0) ? maxRounds : 5;
30
- maxTokens = (Number.isFinite(maxTokens) && maxTokens > 0) ? maxTokens : 2000;
31
- const buffer = [];
32
-
33
- function totalTokens() {
34
- return buffer.reduce(
35
- (sum, r) => sum + estimateTokens(`Q: ${r.query}\nA: ${r.response ?? ""}`),
36
- 0
37
- );
38
- }
39
-
40
- return {
41
- add(round) {
42
- if (!round?.query) return;
43
- buffer.push({ query: String(round.query), response: String(round.response ?? "") });
44
- while (buffer.length > maxRounds) buffer.shift();
45
- while (buffer.length > 1 && totalTokens() > maxTokens) buffer.shift();
46
- },
47
- getContext() {
48
- return buffer.map((r) => `Q: ${r.query}\nA: ${r.response ?? ""}`).join("\n\n");
49
- },
50
- rounds: () => [...buffer],
51
- clear() { buffer.length = 0; }
52
- };
53
- }
1
+ // Session-scoped hot memory (v0.5.0 召回率优化 1.3): a short-term buffer of
2
+ // the latest dialogue rounds, kept strictly apart from the long-term memory
3
+ // store. The injector renders it ahead of the long-term recall block so the
4
+ // agent sees "what we were just talking about" without those rounds ever
5
+ // being persisted as memories. Bounded two ways: maxRounds (count) and
6
+ // maxTokens (budget) — whichever evicts first.
7
+
8
+ // CJK-aware token estimate: one Chinese character ≈ 0.6 tokens (clustering
9
+ // behavior of mainstream tokenizers), one ASCII char ≈ 0.25.
10
+ export function estimateTokens(text) {
11
+ const s = String(text ?? "");
12
+ let cjk = 0;
13
+ for (const ch of s) if (ch >= "\u4e00" && ch <= "\u9fff") cjk++;
14
+ return Math.ceil(cjk * 0.6 + (s.length - cjk) * 0.25);
15
+ }
16
+
17
+ /**
18
+ * @param {{maxRounds?: number, maxTokens?: number}} opts
19
+ * @returns {{add(round: {query: string, response?: string}): void,
20
+ * getContext(): string,
21
+ * rounds(): Array, clear(): void}}
22
+ */
23
+ export function createHotMemory({ maxRounds = 5, maxTokens = 2000 } = {}) {
24
+ // Entry defense: a non-positive or non-integer maxRounds (0, -1, 1.5, NaN,
25
+ // null, "2") would make the eviction while-loop unbounded — the buffer can
26
+ // never shrink below `buffer.length > maxRounds`, so `add` would spin forever.
27
+ // Fall back to the defaults so a hostile/buggy caller can never wedge the
28
+ // hot-memory buffer in an infinite loop.
29
+ maxRounds = (Number.isInteger(maxRounds) && maxRounds > 0) ? maxRounds : 5;
30
+ maxTokens = (Number.isFinite(maxTokens) && maxTokens > 0) ? maxTokens : 2000;
31
+ const buffer = [];
32
+
33
+ function totalTokens() {
34
+ return buffer.reduce(
35
+ (sum, r) => sum + estimateTokens(`Q: ${r.query}\nA: ${r.response ?? ""}`),
36
+ 0
37
+ );
38
+ }
39
+
40
+ return {
41
+ add(round) {
42
+ if (!round?.query) return;
43
+ buffer.push({ query: String(round.query), response: String(round.response ?? "") });
44
+ while (buffer.length > maxRounds) buffer.shift();
45
+ while (buffer.length > 1 && totalTokens() > maxTokens) buffer.shift();
46
+ },
47
+ getContext() {
48
+ return buffer.map((r) => `Q: ${r.query}\nA: ${r.response ?? ""}`).join("\n\n");
49
+ },
50
+ rounds: () => [...buffer],
51
+ clear() { buffer.length = 0; }
52
+ };
53
+ }