@modusensus/dsh-mneme 0.5.0 → 0.5.2

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/lib/inject.js CHANGED
@@ -1,208 +1,208 @@
1
- import { createHotMemory } from "./hot-memory.js";
2
-
3
- // Best-effort extraction of the current user's latest message text from the
4
- // live session, for semantic-first injection (Bug4). The system-prompt
5
- // interpolator renders synchronously, so this walks the already-materialized
6
- // session event log (same event shape summarize.js consumes) and returns the
7
- // most recent human message. Any failure degrades to "" — the injector then
8
- // falls back to the legacy rule-based pick, never breaking the render.
9
- function lastUserQuery(ctx) {
10
- try {
11
- const events = ctx?.agent?.session?.events;
12
- if (!Array.isArray(events) || events.length === 0) return "";
13
- for (let i = events.length - 1; i >= 0; i--) {
14
- const event = events[i];
15
- if (event?.type !== "user/message") continue;
16
- const kind = event.data?.source?.kind;
17
- if (kind !== undefined && kind !== "user") continue;
18
- const parts = event.data?.content;
19
- if (!Array.isArray(parts) || parts.length === 0) continue;
20
- return parts
21
- .map((p) => (typeof p === "string" ? p : p?.text ?? ""))
22
- .filter(Boolean)
23
- .join("\n")
24
- .slice(0, 500);
25
- }
26
- } catch { /* session internals unavailable: degrade to no query */ }
27
- return "";
28
- }
29
-
30
- // Hot-memory round extraction (v0.5.0 1.3): pairs each user/message with the
31
- // next assistant reply from the materialized session log. Tolerates shapes
32
- // where assistant events carry a different type tag — anything whose payload
33
- // has content parts and is not a user message counts as a reply. Best-effort:
34
- // returns [] on any failure, and the hot block simply does not render.
35
- function extractRounds(ctx, maxRounds) {
36
- try {
37
- const events = ctx?.agent?.session?.events;
38
- if (!Array.isArray(events) || events.length === 0) return [];
39
- const rounds = [];
40
- let pendingQuery = null;
41
- const textOf = (event) => {
42
- const parts = event?.data?.content;
43
- if (!Array.isArray(parts)) return "";
44
- return parts
45
- .map((p) => (typeof p === "string" ? p : p?.text ?? ""))
46
- .filter(Boolean)
47
- .join("\n")
48
- .trim();
49
- };
50
- for (const event of events) {
51
- const kind = event?.data?.source?.kind;
52
- const isUser = event?.type === "user/message" && (kind === undefined || kind === "user");
53
- if (isUser) {
54
- if (pendingQuery) rounds.push({ query: pendingQuery, response: "" });
55
- pendingQuery = textOf(event).slice(0, 500);
56
- continue;
57
- }
58
- // Only assistant-originated events close a round; tool/system events
59
- // carrying text must not be mistaken for the model's reply.
60
- const isAssistant = typeof event?.type === "string" && event.type.includes("assistant")
61
- || kind === "assistant";
62
- const body = isAssistant ? textOf(event) : "";
63
- if (!body || !pendingQuery) continue;
64
- rounds.push({ query: pendingQuery, response: body.slice(0, 800) });
65
- pendingQuery = null;
66
- }
67
- if (pendingQuery) rounds.push({ query: pendingQuery, response: "" });
68
- return rounds.slice(-maxRounds);
69
- } catch {
70
- return [];
71
- }
72
- }
73
-
74
- export function createInjector(ctx, service, settings, config) {
75
- const maxItems = config.maxInjectedItems ?? 5;
76
- const threshold = config.importanceThreshold ?? 3;
77
-
78
- // Bug6: bound the injected memory block. Each entry's content is truncated to
79
- // MAX_CONTENT chars (trailing `…`); the whole block gets a MAX_BLOCK budget
80
- // and an entry that would exceed it collapses to its title only, so a long
81
- // memory can never push the injected context past a few thousand chars.
82
- const MAX_CONTENT = 300;
83
- const MAX_BLOCK = 1500;
84
-
85
- // Compressed injection (v0.5.0 2.1): a sleep-demoted row already carries its
86
- // summary in `content` with the original parked in `_full_content` — inject
87
- // the summary verbatim instead of re-truncating the (already short) text.
88
- // Regular long rows keep the hard truncate.
89
- function injectMemory(m, maxLength = MAX_CONTENT) {
90
- if (m?._full_content) return String(m.content ?? "");
91
- const text = String(m?.content ?? "");
92
- return text.length <= maxLength ? text : `${text.slice(0, maxLength)}…`;
93
- }
94
-
95
- // Hot memory (v0.5.0 1.3): the latest rounds of THIS session, rebuilt from
96
- // the materialized event log on every render — stateless, so it survives
97
- // session switches and never persists anywhere.
98
- const hot = createHotMemory({
99
- maxRounds: config.hotMemoryRounds ?? 5,
100
- maxTokens: config.hotMemoryMaxTokens ?? 2000
101
- });
102
-
103
- function renderHotContext(ctx) {
104
- if (config.hotMemoryEnabled === false) return "";
105
- const rounds = extractRounds(ctx, config.hotMemoryRounds ?? 5);
106
- if (!rounds.length) return "";
107
- hot.clear();
108
- for (const r of rounds) hot.add(r);
109
- const body = hot.getContext();
110
- if (!body) return "";
111
- return `[短期上下文] 最近对话(共 ${rounds.length} 轮):\n${body}`;
112
- }
113
-
114
- function render(candidates) {
115
- if (!candidates.length) return "";
116
- const header = "[记忆库] 来自 dsh-mneme 的跨会话记忆(用户偏好与高优先级项目/决策):";
117
- const lines = [header];
118
- let budget = MAX_BLOCK - header.length;
119
- for (const m of candidates) {
120
- // Epistemic trust (v0.4.5): when enabled, measured observations are
121
- // flagged so the agent can weigh them above guesses/opinions.
122
- const verified = config.trustEpistemicWeighting === true && m.epistemic_status === "observation"
123
- ? "[verified] "
124
- : "";
125
- const title = `${m.title}(重要性 ${m.importance})`;
126
- const content = injectMemory(m);
127
- const full = `- [${m.type}] ${verified}${title}:${content}`;
128
- if (budget - full.length >= 0) {
129
- lines.push(full);
130
- budget -= full.length;
131
- } else {
132
- lines.push(`- [${m.type}] ${verified}${title}`);
133
- }
134
- }
135
- return lines.join("\n");
136
- }
137
-
138
- // Bug4: the system-prompt render is synchronous, so the semantic query vector
139
- // must be prefetched asynchronously and cached for the next assembly. The
140
- // first render after a new user message may still fall back to the rule-based
141
- // pick; later assemblies in the same session reuse the cached vector. Bounded
142
- // cache (cap 8, drop oldest) so a long session never grows it unbounded.
143
- const QUERY_VECTOR_CACHE_MAX = 8;
144
- const queryVectorCache = new Map();
145
- let lastPrefetched = "";
146
-
147
- function prefetchQueryVector(query) {
148
- if (!query || query === lastPrefetched || queryVectorCache.has(query)) return;
149
- lastPrefetched = query;
150
- service.embedQuery(query).then((vec) => {
151
- if (Array.isArray(vec) && vec.length) {
152
- queryVectorCache.set(query, vec);
153
- if (queryVectorCache.size > QUERY_VECTOR_CACHE_MAX) {
154
- queryVectorCache.delete(queryVectorCache.keys().next().value);
155
- }
156
- }
157
- }).catch(() => { /* prefetch is best-effort */ });
158
- }
159
-
160
- // User profile + rules: injected ahead of the memory block because they are
161
- // always-relevant instructions the agent should follow every turn.
162
- function renderUserSettings() {
163
- const profile = settings.getProfile().trim();
164
- const rules = settings.getRules();
165
- if (!profile && !rules.length) return "";
166
- const lines = ["[用户设置] 来自 dsh-mneme 的用户画像与规则:"];
167
- if (profile) lines.push(`- 用户画像:${profile}`);
168
- for (const rule of rules) lines.push(`- 规则:${rule}`);
169
- return lines.join("\n");
170
- }
171
-
172
- const disposers = [
173
- ctx.systemPrompt.context({
174
- name: "memory",
175
- order: 90,
176
- text: (ctx) => {
177
- // Bug4: pass the latest user query so injection prefers semantically
178
- // relevant memories; lastUserQuery is best-effort (empty → legacy).
179
- // The query vector is prefetched asynchronously (cached) because the
180
- // render itself must stay synchronous.
181
- const query = lastUserQuery(ctx);
182
- if (query) prefetchQueryVector(query);
183
- const queryVector = queryVectorCache.get(query);
184
- const candidates = service.injectCandidates({ query, queryVector, maxItems, threshold });
185
- // Hot memory (v0.5.0 1.3) leads the single memory block: the agent
186
- // sees the short-term rounds first, then the cross-session recall —
187
- // the documented injection order 1→2. Folding it here (instead of a
188
- // separate context) keeps the prompt assembly stable at two blocks.
189
- const hotText = renderHotContext(ctx);
190
- const body = render(candidates);
191
- if (!hotText) return body;
192
- return body ? `${hotText}\n\n${body}` : hotText;
193
- }
194
- }),
195
- ctx.systemPrompt.context({
196
- name: "user-settings",
197
- order: 85,
198
- text: renderUserSettings
199
- })
200
- ];
201
-
202
- return () => {
203
- queryVectorCache.clear();
204
- for (const dispose of disposers) {
205
- if (typeof dispose === "function") dispose();
206
- }
207
- };
208
- }
1
+ import { createHotMemory } from "./hot-memory.js";
2
+
3
+ // Best-effort extraction of the current user's latest message text from the
4
+ // live session, for semantic-first injection (Bug4). The system-prompt
5
+ // interpolator renders synchronously, so this walks the already-materialized
6
+ // session event log (same event shape summarize.js consumes) and returns the
7
+ // most recent human message. Any failure degrades to "" — the injector then
8
+ // falls back to the legacy rule-based pick, never breaking the render.
9
+ function lastUserQuery(ctx) {
10
+ try {
11
+ const events = ctx?.agent?.session?.events;
12
+ if (!Array.isArray(events) || events.length === 0) return "";
13
+ for (let i = events.length - 1; i >= 0; i--) {
14
+ const event = events[i];
15
+ if (event?.type !== "user/message") continue;
16
+ const kind = event.data?.source?.kind;
17
+ if (kind !== undefined && kind !== "user") continue;
18
+ const parts = event.data?.content;
19
+ if (!Array.isArray(parts) || parts.length === 0) continue;
20
+ return parts
21
+ .map((p) => (typeof p === "string" ? p : p?.text ?? ""))
22
+ .filter(Boolean)
23
+ .join("\n")
24
+ .slice(0, 500);
25
+ }
26
+ } catch { /* session internals unavailable: degrade to no query */ }
27
+ return "";
28
+ }
29
+
30
+ // Hot-memory round extraction (v0.5.0 1.3): pairs each user/message with the
31
+ // next assistant reply from the materialized session log. Tolerates shapes
32
+ // where assistant events carry a different type tag — anything whose payload
33
+ // has content parts and is not a user message counts as a reply. Best-effort:
34
+ // returns [] on any failure, and the hot block simply does not render.
35
+ function extractRounds(ctx, maxRounds) {
36
+ try {
37
+ const events = ctx?.agent?.session?.events;
38
+ if (!Array.isArray(events) || events.length === 0) return [];
39
+ const rounds = [];
40
+ let pendingQuery = null;
41
+ const textOf = (event) => {
42
+ const parts = event?.data?.content;
43
+ if (!Array.isArray(parts)) return "";
44
+ return parts
45
+ .map((p) => (typeof p === "string" ? p : p?.text ?? ""))
46
+ .filter(Boolean)
47
+ .join("\n")
48
+ .trim();
49
+ };
50
+ for (const event of events) {
51
+ const kind = event?.data?.source?.kind;
52
+ const isUser = event?.type === "user/message" && (kind === undefined || kind === "user");
53
+ if (isUser) {
54
+ if (pendingQuery) rounds.push({ query: pendingQuery, response: "" });
55
+ pendingQuery = textOf(event).slice(0, 500);
56
+ continue;
57
+ }
58
+ // Only assistant-originated events close a round; tool/system events
59
+ // carrying text must not be mistaken for the model's reply.
60
+ const isAssistant = typeof event?.type === "string" && event.type.includes("assistant")
61
+ || kind === "assistant";
62
+ const body = isAssistant ? textOf(event) : "";
63
+ if (!body || !pendingQuery) continue;
64
+ rounds.push({ query: pendingQuery, response: body.slice(0, 800) });
65
+ pendingQuery = null;
66
+ }
67
+ if (pendingQuery) rounds.push({ query: pendingQuery, response: "" });
68
+ return rounds.slice(-maxRounds);
69
+ } catch {
70
+ return [];
71
+ }
72
+ }
73
+
74
+ export function createInjector(ctx, service, settings, config) {
75
+ const maxItems = config.maxInjectedItems ?? 5;
76
+ const threshold = config.importanceThreshold ?? 3;
77
+
78
+ // Bug6: bound the injected memory block. Each entry's content is truncated to
79
+ // MAX_CONTENT chars (trailing `…`); the whole block gets a MAX_BLOCK budget
80
+ // and an entry that would exceed it collapses to its title only, so a long
81
+ // memory can never push the injected context past a few thousand chars.
82
+ const MAX_CONTENT = 300;
83
+ const MAX_BLOCK = 1500;
84
+
85
+ // Compressed injection (v0.5.0 2.1): a sleep-demoted row already carries its
86
+ // summary in `content` with the original parked in `_full_content` — inject
87
+ // the summary verbatim instead of re-truncating the (already short) text.
88
+ // Regular long rows keep the hard truncate.
89
+ function injectMemory(m, maxLength = MAX_CONTENT) {
90
+ if (m?._full_content) return String(m.content ?? "");
91
+ const text = String(m?.content ?? "");
92
+ return text.length <= maxLength ? text : `${text.slice(0, maxLength)}…`;
93
+ }
94
+
95
+ // Hot memory (v0.5.0 1.3): the latest rounds of THIS session, rebuilt from
96
+ // the materialized event log on every render — stateless, so it survives
97
+ // session switches and never persists anywhere.
98
+ const hot = createHotMemory({
99
+ maxRounds: config.hotMemoryRounds ?? 5,
100
+ maxTokens: config.hotMemoryMaxTokens ?? 2000
101
+ });
102
+
103
+ function renderHotContext(ctx) {
104
+ if (config.hotMemoryEnabled === false) return "";
105
+ const rounds = extractRounds(ctx, config.hotMemoryRounds ?? 5);
106
+ if (!rounds.length) return "";
107
+ hot.clear();
108
+ for (const r of rounds) hot.add(r);
109
+ const body = hot.getContext();
110
+ if (!body) return "";
111
+ return `[短期上下文] 最近对话(共 ${rounds.length} 轮):\n${body}`;
112
+ }
113
+
114
+ function render(candidates) {
115
+ if (!candidates.length) return "";
116
+ const header = "[记忆库] 来自 dsh-mneme 的跨会话记忆(用户偏好与高优先级项目/决策):";
117
+ const lines = [header];
118
+ let budget = MAX_BLOCK - header.length;
119
+ for (const m of candidates) {
120
+ // Epistemic trust (v0.4.5): when enabled, measured observations are
121
+ // flagged so the agent can weigh them above guesses/opinions.
122
+ const verified = config.trustEpistemicWeighting === true && m.epistemic_status === "observation"
123
+ ? "[verified] "
124
+ : "";
125
+ const title = `${m.title}(重要性 ${m.importance})`;
126
+ const content = injectMemory(m);
127
+ const full = `- [${m.type}] ${verified}${title}:${content}`;
128
+ if (budget - full.length >= 0) {
129
+ lines.push(full);
130
+ budget -= full.length;
131
+ } else {
132
+ lines.push(`- [${m.type}] ${verified}${title}`);
133
+ }
134
+ }
135
+ return lines.join("\n");
136
+ }
137
+
138
+ // Bug4: the system-prompt render is synchronous, so the semantic query vector
139
+ // must be prefetched asynchronously and cached for the next assembly. The
140
+ // first render after a new user message may still fall back to the rule-based
141
+ // pick; later assemblies in the same session reuse the cached vector. Bounded
142
+ // cache (cap 8, drop oldest) so a long session never grows it unbounded.
143
+ const QUERY_VECTOR_CACHE_MAX = 8;
144
+ const queryVectorCache = new Map();
145
+ let lastPrefetched = "";
146
+
147
+ function prefetchQueryVector(query) {
148
+ if (!query || query === lastPrefetched || queryVectorCache.has(query)) return;
149
+ lastPrefetched = query;
150
+ service.embedQuery(query).then((vec) => {
151
+ if (Array.isArray(vec) && vec.length) {
152
+ queryVectorCache.set(query, vec);
153
+ if (queryVectorCache.size > QUERY_VECTOR_CACHE_MAX) {
154
+ queryVectorCache.delete(queryVectorCache.keys().next().value);
155
+ }
156
+ }
157
+ }).catch(() => { /* prefetch is best-effort */ });
158
+ }
159
+
160
+ // User profile + rules: injected ahead of the memory block because they are
161
+ // always-relevant instructions the agent should follow every turn.
162
+ function renderUserSettings() {
163
+ const profile = settings.getProfile().trim();
164
+ const rules = settings.getRules();
165
+ if (!profile && !rules.length) return "";
166
+ const lines = ["[用户设置] 来自 dsh-mneme 的用户画像与规则:"];
167
+ if (profile) lines.push(`- 用户画像:${profile}`);
168
+ for (const rule of rules) lines.push(`- 规则:${rule}`);
169
+ return lines.join("\n");
170
+ }
171
+
172
+ const disposers = [
173
+ ctx.systemPrompt.context({
174
+ name: "memory",
175
+ order: 90,
176
+ text: (ctx) => {
177
+ // Bug4: pass the latest user query so injection prefers semantically
178
+ // relevant memories; lastUserQuery is best-effort (empty → legacy).
179
+ // The query vector is prefetched asynchronously (cached) because the
180
+ // render itself must stay synchronous.
181
+ const query = lastUserQuery(ctx);
182
+ if (query) prefetchQueryVector(query);
183
+ const queryVector = queryVectorCache.get(query);
184
+ const candidates = service.injectCandidates({ query, queryVector, maxItems, threshold });
185
+ // Hot memory (v0.5.0 1.3) leads the single memory block: the agent
186
+ // sees the short-term rounds first, then the cross-session recall —
187
+ // the documented injection order 1→2. Folding it here (instead of a
188
+ // separate context) keeps the prompt assembly stable at two blocks.
189
+ const hotText = renderHotContext(ctx);
190
+ const body = render(candidates);
191
+ if (!hotText) return body;
192
+ return body ? `${hotText}\n\n${body}` : hotText;
193
+ }
194
+ }),
195
+ ctx.systemPrompt.context({
196
+ name: "user-settings",
197
+ order: 85,
198
+ text: renderUserSettings
199
+ })
200
+ ];
201
+
202
+ return () => {
203
+ queryVectorCache.clear();
204
+ for (const dispose of disposers) {
205
+ if (typeof dispose === "function") dispose();
206
+ }
207
+ };
208
+ }