@frogmoo/dsh-supermemory 0.0.0-stage → 1.4.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.
@@ -0,0 +1,735 @@
1
+ import { a as dropNote, g as updateMember, i as clipWithNote, p as setTopicSetModel, t as charCount } from "./clip-kqqR05NC.js";
2
+ // src/injection-titles.ts
3
+ /**
4
+ * R56/R57: the ONE registry of context-injection card names.
5
+ *
6
+ * Every card this plugin injects into a model context carries TWO visible names,
7
+ * and both come from the same registry entry:
8
+ *
9
+ * 1. 卡片标题(宿主「上下文注入 <label>」行的 label)= 注入消息的 source.kind
10
+ * = injectionLabel(kind)(不带方括号)。
11
+ * 2. 内容首行标题 = [label] = injectionTitle(kind)(带方括号)。
12
+ *
13
+ * 宿主证据(DSH 0.2.2,详见 DEV-NOTES §70.2):
14
+ * - dsh-client-ui-chat/src/client/conversation-nodes/event-projection.ts:60
15
+ * `contextProducer(source)` 的 default 分支 label = source.kind(宿主注释
16
+ * 明确「keep an unknown producer visible by its durable kind」);
17
+ * - dsh-client-ui-chat/src/client/chat/ContextInjectionRow.tsx:57 折叠行标题是
18
+ * 固定的「上下文注入」(locale `message.contextInjection`,role 'recall' 时
19
+ * 为「跨会话召回」);
20
+ * - 同文件 :69 把 producer.label 渲染成标题里的来源段;:70-73 只对
21
+ * form='notice' 再追加 source.summary。
22
+ * 因此「让每类注入用不同卡片标题」= 让每类注入的 source.kind 不同。
23
+ *
24
+ * ## 命名约定(新增注入卡必须遵守)
25
+ *
26
+ * 1. 所有上下文注入卡名字以 supermemory- 开头。
27
+ * 2. 相关内容类用 supermemory-相关<主题>(话题 / 记忆 / 分支会话 / 能力…):
28
+ * 同族前缀 + 卡片所讲的主题;话题候选是相关话题族的子卡。
29
+ * 3. 功能性卡用 supermemory-<功能>(小写 kebab,如 hub-role / plugin-prompt /
30
+ * notice),保持 ASCII——约定测试锁定
31
+ * ^\[supermemory-(相关.+|[a-z][a-z-]*)\]$ 与同形裸名正则。
32
+ * 4. 禁止在渲染处手写标题字符串:一律 injectionTitle(kind)(枚举用
33
+ * injectionTitles());注入 source 一律 injectionSource(kind, form?)
34
+ * (src/source.ts)——手写 `kind: 'supermemory'` 作为卡片 label 就是回归,
35
+ * R57 冒烟会扫描 prestep.ts / route.ts 判失败。
36
+ * 5. 新增注入卡必须「先登记」:本文件加常量与 kind,再渲染、再测试(精确匹配 +
37
+ * 约定正则 + source.kind 断言)、最后写文档——登记 → 渲染 → 测试 → 文档。
38
+ *
39
+ * ## 例外:relay / 消息传输前缀不是注入卡
40
+ *
41
+ * [supermemory-relay <branch>]、[supermemory-group-relay <group>]、
42
+ * [supermemory-dispatch <id>]、[supermemory-resume <id>]、
43
+ * [supermemory-questions]、[supermemory-panel-reply]、[supermemory-topic-set]
44
+ * 是消息头:在会话之间传输,relay 管线会解析它们并携带 id/载荷。它们不经过本
45
+ * 注册表、不改名,改了会破坏回送。见 DEV-NOTES §69.2。
46
+ *
47
+ * relay 消息的 source.kind 也保持 'supermemory'(observe.ts 用
48
+ * source.deliveryId + kind 'supermemory' 确认投递)——那些卡由插件自己的
49
+ * 客户端卡片渲染,不走宿主的「上下文注入 <label>」行。
50
+ * @module supermemory/injection-titles
51
+ */
52
+ /** 卡片种类 → 裸名(不带方括号)。新增卡片在这里登记一个 kind。 */
53
+ const INJECTION_TITLES = {
54
+ /** 相关话题集(激活话题集的上下文卡)。 */
55
+ topic: "supermemory-相关话题",
56
+ /** 候选话题集——只提示、从不切换(相关话题族的子卡)。 */
57
+ topicCandidate: "supermemory-相关话题候选",
58
+ /** 相关记忆(开场召回卡)。 */
59
+ memory: "supermemory-相关记忆",
60
+ /** 同一请求内后补的相关记忆(过程内补充卡)。 */
61
+ memoryRepeat: "supermemory-相关记忆补充",
62
+ /** 关联分支会话:中枢的分支 + 命中话题集的分支清单。 */
63
+ branch: "supermemory-相关分支会话",
64
+ /** 固化能力精简索引(正文用 sm_cap_doc 按需读取)。 */
65
+ capability: "supermemory-相关能力",
66
+ /** 中枢角色提示(功能性卡)。 */
67
+ hubRole: "supermemory-hub-role",
68
+ /** 插件记忆使用约定(功能性卡)。 */
69
+ pluginPrompt: "supermemory-plugin-prompt",
70
+ /** 中断任务公告(功能性卡)。 */
71
+ notice: "supermemory-notice"
72
+ };
73
+ /** 带方括号的卡片标题(内容首行),例如 [supermemory-相关记忆]。 */
74
+ function injectionTitle(kind) {
75
+ return "[" + INJECTION_TITLES[kind] + "]";
76
+ }
77
+ // src/extract.ts
78
+ const REMEMBER_PATTERNS = [/(?:记住|记一下|请记住|帮忙记住|牢记)[::\s]+(.{2,200})/, /(?:remember|note that|don'?t forget|keep in mind)\b[::\s]+(.{2,200})/i];
79
+ const DEFINITION_PATTERNS = [/^([\w\u4e00-\u9fff][\w\u4e00-\u9fff \-_/.]{1,30}?)(?:是|为|等于)(.{4,200})$/, /^([\w\u4e00-\u9fff][\w\u4e00-\u9fff \-_/.]{1,30}?)\s+(?:is|are)\s+(.{4,200})$/i];
80
+ const STOP_WORDS = /* @__PURE__ */ new Set([
81
+ "the",
82
+ "a",
83
+ "an",
84
+ "is",
85
+ "are",
86
+ "and",
87
+ "or",
88
+ "of",
89
+ "to",
90
+ "in",
91
+ "on",
92
+ "for",
93
+ "with",
94
+ "这个",
95
+ "那个",
96
+ "这些",
97
+ "那些",
98
+ "一下",
99
+ "什么",
100
+ "怎么",
101
+ "如何",
102
+ "请",
103
+ "帮我把",
104
+ "记得",
105
+ "可以",
106
+ "需要",
107
+ "已经",
108
+ "还有",
109
+ "以及",
110
+ "之后",
111
+ "之前",
112
+ "如果",
113
+ "因为",
114
+ "所以",
115
+ "但是",
116
+ "而且",
117
+ "并且",
118
+ "或者",
119
+ "对于",
120
+ "关于",
121
+ "通过",
122
+ "根据",
123
+ "按照",
124
+ "其中",
125
+ "其它",
126
+ "其他",
127
+ "是否",
128
+ "能否",
129
+ "我们",
130
+ "你们",
131
+ "他们",
132
+ "的一",
133
+ "是一",
134
+ "是不",
135
+ "不是"
136
+ ]);
137
+ /**
138
+ * CJK 功能字:CJK 关键词按这些字切段(替代逐字双字滑窗)。滑窗会跨词产出
139
+ * 「本任/务是/是并」式碎片,切段取词至少保证每个关键词落在一个词的内部。
140
+ */
141
+ const CJK_STOP_CHARS = /* @__PURE__ */ new Set([..."的了和是在与及或等之于为以对这那又还就都也只再没不很被把将从向让其呢吗吧呀啊哦之乎者也"]);
142
+ /** 段长上限:更长的段按前几个字截断(避免把整句当一个标签)。 */
143
+ const CJK_SEGMENT_MAX = 4;
144
+ /** CJK 关键词只从前 N 个汉字里取(限制来源,长文不无限产出标签)。 */
145
+ const CJK_SOURCE_CHARS = 120;
146
+ /** CJK 关键词数量上限。 */
147
+ const CJK_KEYWORD_MAX = 8;
148
+ /**
149
+ * 派发/续跑的包装文本与元数据:这些行是插件自己的信封,不是用户结论。
150
+ * (命中任意一条即整条跳过,不再进入任何 pattern。)
151
+ */
152
+ const WRAPPER_PATTERNS = [
153
+ /本任务是并行组/i,
154
+ /并行组的一员/i,
155
+ /只负责这一个任务/i,
156
+ /全部成员到达终态/i,
157
+ /原派发\s*dsp-/i,
158
+ /派发Id/i,
159
+ /dispatchId/i,
160
+ /\bdsp-[a-z0-9]{4,}/i,
161
+ /\bbranch-[a-z0-9]{4,}/i,
162
+ /分支会话[::]/,
163
+ /supermemory-dispatch/i,
164
+ /越界请汇报/i
165
+ ];
166
+ /** 命令行头(纯命令行/版本行判定:整行无汉字且以这些词开头)。 */
167
+ const COMMAND_HEADS = /^(?:git|pnpm|npm|npx|node|python3?|pip3?|cmd|powershell?|bash|sh|zsh|docker|kubectl|adb|tsc|eslint|prettier|vitest|jest|make|curl|wget|ssh|scp|rsync|sudo|cd|ls|cat|echo|grep|find|rm|cp|mv|mkdir|touch|chmod|chown|export|set|source)\b/i;
168
+ /** 纯版本行:v1.2.3 / 1.2.3。 */
169
+ const VERSION_LINE = /^\s*v?\d+(?:\.\d+)+\s*$/;
170
+ /** 疑问句尾巴。 */
171
+ const QUESTION_END = /[??]\s*$/;
172
+ /** 疑问句开头(且句中没有任何陈述动词时才算疑问)。 */
173
+ const QUESTION_HEAD = /^(?:怎么|怎样|如何|为什么|为啥|啥|哪些|哪个|哪几|是否|能不能|可不可以|可不可|请问|我想问|想问|问一下|帮忙问|有没有|是不是)/;
174
+ const STATEMENT_MARK = /(?:是|为|等于|应该是|应当|应该|需要|必须|可以|要用|使用|采用|默认|约定|禁止|不要|支持|一律|务必)/;
175
+ /** 定义主语必须至少有 2 个汉字或 3 个以上拉丁字符(避免 "1"/"12" 当标题)。 */
176
+ function subjectUsable(subject) {
177
+ if ((subject.match(/[\u4e00-\u9fff]/g) ?? []).length >= 2) return true;
178
+ return (subject.match(/[a-z0-9]/gi) ?? []).length >= 3;
179
+ }
180
+ /** 纯命令行 / 版本行:去掉可选的行首编号后整行是 ASCII 且以命令词开头。 */
181
+ function isCommandLine(line) {
182
+ const stripped = line.replace(/^\s*\d{1,2}[.)、]\s*/, "");
183
+ return COMMAND_HEADS.test(stripped) && !/[\u4e00-\u9fff]/.test(stripped);
184
+ }
185
+ /** 非结论文本:派发包装、纯命令行/版本行、疑问句——一律不进记忆。 */
186
+ function isNonConclusion(clean) {
187
+ if (WRAPPER_PATTERNS.some((pattern) => pattern.test(clean))) return true;
188
+ if (isCommandLine(clean)) return true;
189
+ if (VERSION_LINE.test(clean)) return true;
190
+ if (QUESTION_END.test(clean)) return true;
191
+ return QUESTION_HEAD.test(clean.trim()) && !STATEMENT_MARK.test(clean);
192
+ }
193
+ /**
194
+ * Extract keywords from a fact text (latin words + CJK segment words).
195
+ *
196
+ * R27: CJK 取词从「逐字双字滑窗」改为「功能字切段取词」——滑窗会跨功能字产出
197
+ * 「本任/务是」式碎片;切段后每个关键词都落在一个词的内部,并限制来源长度
198
+ * (前 {@link CJK_SOURCE_CHARS} 个汉字)与数量({@link CJK_KEYWORD_MAX} 个)。
199
+ */
200
+ function keywordsOf(text) {
201
+ const body = String(text ?? "");
202
+ const latin = [];
203
+ const lower = body.toLowerCase();
204
+ for (const m of lower.matchAll(/[a-z0-9_+#.\-]{2,}/g)) if (!STOP_WORDS.has(m[0])) latin.push(m[0]);
205
+ const chars = (body.match(/[\u4e00-\u9fff]/g) ?? []).slice(0, CJK_SOURCE_CHARS);
206
+ const cjk = [];
207
+ let segment = "";
208
+ const flush = () => {
209
+ if (segment.length >= 2) cjk.push(segment.slice(0, CJK_SEGMENT_MAX));
210
+ segment = "";
211
+ };
212
+ for (const char of chars) if (CJK_STOP_CHARS.has(char)) flush();
213
+ else segment += char;
214
+ flush();
215
+ return [.../* @__PURE__ */ new Set([...latin.slice(0, 12), ...cjk.slice(0, CJK_KEYWORD_MAX)])].slice(0, 24);
216
+ }
217
+ /**
218
+ * Extract memory-worthy facts from one user message.
219
+ * @param text - the user message's plain text.
220
+ * @returns zero or more facts; empty when nothing is memory-worthy.
221
+ */
222
+ function extractFacts(text) {
223
+ const facts = [];
224
+ const seen = /* @__PURE__ */ new Set();
225
+ const push = (raw) => {
226
+ const clean = raw.trim().replace(/\s+/g, " ").replace(/["'」』]+$/, "").slice(0, 300);
227
+ if (clean.length < 2) return;
228
+ if (isNonConclusion(clean)) return;
229
+ const key = clean.toLowerCase();
230
+ if (seen.has(key)) return;
231
+ seen.add(key);
232
+ facts.push({
233
+ text: clean,
234
+ keywords: keywordsOf(clean)
235
+ });
236
+ };
237
+ for (const pattern of REMEMBER_PATTERNS) {
238
+ const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
239
+ for (const m of text.matchAll(new RegExp(pattern.source, flags))) push(m[1]);
240
+ }
241
+ for (const line of text.split(/\n+/)) {
242
+ const trimmed = line.trim();
243
+ if (!trimmed || trimmed.length > 80) continue;
244
+ for (const pattern of DEFINITION_PATTERNS) {
245
+ const m = trimmed.match(pattern);
246
+ if (m && subjectUsable(m[1])) push(`${m[1].trim()}是${m[2].trim()}`);
247
+ }
248
+ }
249
+ return facts;
250
+ }
251
+ /**
252
+ * R19 需求⑧: a memory is a CONCLUSION, not a transcript.
253
+ *
254
+ * The write path is the last line of defence after the tool description and
255
+ * the hub/system prompts: a body above {@link MEMORY_TEXT_MAX} characters, one
256
+ * that is a wall of numbered steps/commands, or a long fenced command dump is
257
+ * rejected with an actionable message. Everything else (a multi-line
258
+ * conclusion, a bulleted decision list) is accepted — the heuristic is
259
+ * deliberately conservative so a legitimate fact is never lost.
260
+ */
261
+ const MEMORY_TEXT_MAX = 1500;
262
+ /** Step-line markers that signal a process log rather than a conclusion. */
263
+ const STEP_LINE = /^\s*(?:步骤\s*\d+|第[一二三四五六七八九十0-9]+步|step\s*\d+|\d{1,2}[.)、]\s+)/i;
264
+ /** Classify one memory body before it is written. */
265
+ function assessConclusion(input) {
266
+ const text = String(input ?? "").trim();
267
+ if (!text) return {
268
+ ok: false,
269
+ message: "正文不能为空。"
270
+ };
271
+ if (Array.from(text).length > 1500) return {
272
+ ok: false,
273
+ message: `正文过长(${Array.from(text).length} 字,上限 ${MEMORY_TEXT_MAX}):记忆只存结论,请压缩为可复用的事实/决策;过程步骤请留在会话里。`
274
+ };
275
+ const lines = text.split(/\r?\n/);
276
+ if (lines.filter((line) => STEP_LINE.test(line)).length >= 3) return {
277
+ ok: false,
278
+ message: "这段内容像过程流水账(多条编号步骤):记忆只存结论性、可复用的事实/决策,请改写为结论。"
279
+ };
280
+ if (lines.length >= 25) return {
281
+ ok: false,
282
+ message: `正文行数过多(${lines.length} 行):请只保留结论性事实/决策,过程记录不必写入记忆。`
283
+ };
284
+ if (text.includes("```") && Array.from(text).length > 700) return {
285
+ ok: false,
286
+ message: "长代码块看起来是过程材料:记忆只存结论(命令结论、约定、决策),不要粘贴大段输出。"
287
+ };
288
+ return { ok: true };
289
+ }
290
+ /**
291
+ * Derive a human title from a body when the caller supplied none.
292
+ * The first sentence/clause is used (Chinese full stop, semicolon, newline),
293
+ * trimmed to {@link TITLE_MAX} characters, so old-style `memory_remember`
294
+ * calls still produce a scannable index.
295
+ */
296
+ function deriveTitle(body, fallback = "") {
297
+ const clean = String(body ?? "").replace(/\s+/g, " ").trim();
298
+ if (!clean) return fallback.slice(0, 48);
299
+ const clause = clean.split(/[。!?;;.!?\n]/)[0]?.trim() || clean;
300
+ return clause.length <= 48 ? clause : `${clause.slice(0, 47)}…`;
301
+ }
302
+ /** Normalise whatever a caller passed as tags (array, comma text, undefined). */
303
+ function normalizeTags(input) {
304
+ const raw = Array.isArray(input) ? input : typeof input === "string" ? input.split(/[,,、;;|\s]+/) : [];
305
+ const out = [];
306
+ for (const entry of raw) {
307
+ const tag = String(entry ?? "").trim().replace(/^#+/, "");
308
+ if (!tag) continue;
309
+ const capped = tag.slice(0, 24);
310
+ if (out.includes(capped)) continue;
311
+ out.push(capped);
312
+ if (out.length >= 12) break;
313
+ }
314
+ return out;
315
+ }
316
+ /**
317
+ * The record's tag list: the caller's tags when it supplied any, otherwise the
318
+ * auto-extracted keywords of the body.
319
+ *
320
+ * Deliberately NOT a union: the point of the title + tags + body shape is that
321
+ * the tag space stays a human-chosen index. Mixing CJK bigrams into explicitly
322
+ * tagged records made every record look tagged with noise ("新记", "记忆", …)
323
+ * and pushed real tags out of the display. Records with no tags at all still
324
+ * fall back to the body vocabulary, so old flows stay findable.
325
+ */
326
+ function mergeTags(tags, autoKeywords) {
327
+ const explicit = normalizeTags(tags);
328
+ return explicit.length > 0 ? explicit : normalizeTags(autoKeywords);
329
+ }
330
+ /** Tags of a free-form body, normalised (used when a record carries none). */
331
+ function tagsOfBody(body) {
332
+ return normalizeTags(keywordsOf(body));
333
+ }
334
+ /**
335
+ * The card line every UI and the model-facing render share.
336
+ *
337
+ * R22 需求④: an entry may name its memory collection — the collection is part of
338
+ * the record's context (like a topic set for episodes), so the line carries it
339
+ * only when the caller knows it. Existing callers pass nothing and are unchanged.
340
+ */
341
+ function renderRecordLine(record) {
342
+ const title = record.title?.trim();
343
+ const tags = (record.tags ?? []).filter(Boolean);
344
+ const head = title && title !== record.text.trim() ? `【${title}】` : "";
345
+ const tail = tags.length > 0 ? ` |标签: ${tags.join("、")}` : "";
346
+ const collection = record.collection?.trim() ? ` |集合: ${record.collection.trim()}` : "";
347
+ return `${head}${record.text}${tail}${collection}`;
348
+ }
349
+ // src/recall.ts
350
+ /**
351
+ * Rule-based recall: keyword overlap plus time decay (P0 简化版).
352
+ *
353
+ * Tokenisation handles mixed Chinese/Latin text: ASCII word tokens plus CJK
354
+ * character bigrams, so 「构建命令」 and "build command" both produce matchable
355
+ * units without any LLM call. LLM failure can never degrade this path because
356
+ * there is no LLM in it.
357
+ * @module supermemory/recall
358
+ */
359
+ /**
360
+ * Field weights for one record's token bag (R10).
361
+ *
362
+ * The whole point of the title + tags + body shape is that a query can be
363
+ * answered from the index: a title hit is worth four body hits, a tag hit
364
+ * three, so an exact title/tag match outranks a record that merely mentions
365
+ * the word once deep in its prose.
366
+ */
367
+ const TITLE_WEIGHT = 4;
368
+ const TAG_WEIGHT = 3;
369
+ const BODY_WEIGHT = 1;
370
+ const LATIN = /[a-zA-Z0-9_+#.\-]{2,}/g;
371
+ const CJK = /[\u4e00-\u9fff]/g;
372
+ /** Split text into matchable tokens (latin words + CJK bigrams). */
373
+ function tokenize(text) {
374
+ const tokens = [];
375
+ const lower = text.toLowerCase();
376
+ for (const m of lower.matchAll(LATIN)) tokens.push(m[0]);
377
+ const chars = text.match(CJK) ?? [];
378
+ for (let i = 0; i + 1 < chars.length; i++) tokens.push(chars[i] + chars[i + 1]);
379
+ if (chars.length === 1) tokens.push(chars[0]);
380
+ return tokens;
381
+ }
382
+ function decay(createdAt, now, halfLifeDays) {
383
+ const ageDays = Math.max(0, (now - createdAt) / 864e5);
384
+ return Math.pow(.5, ageDays / Math.max(1, halfLifeDays));
385
+ }
386
+ /**
387
+ * Raw match score of one memory against weighted query tokens (no decay).
388
+ * `minScore: 1` therefore means "at least one matched token", independent of
389
+ * the record's age — decay only reorders the survivors.
390
+ */
391
+ function rawScore(memory, queryTokens) {
392
+ if (memory.status !== "active") return 0;
393
+ const fold = (text) => {
394
+ const bag = /* @__PURE__ */ new Map();
395
+ for (const token of tokenize(text)) bag.set(token, (bag.get(token) ?? 0) + 1);
396
+ return bag;
397
+ };
398
+ const titleBag = fold(memory.title ?? "");
399
+ const tagBag = fold((memory.keywords ?? []).join(" "));
400
+ const bodyBag = fold(memory.text ?? "");
401
+ if (titleBag.size + tagBag.size + bodyBag.size === 0) return 0;
402
+ let raw = 0;
403
+ for (const [token, weight] of queryTokens) {
404
+ const titleHits = titleBag.get(token) ?? 0;
405
+ const tagHits = tagBag.get(token) ?? 0;
406
+ const bodyHits = bodyBag.get(token) ?? 0;
407
+ raw += weight * TITLE_WEIGHT * Math.min(titleHits, 2);
408
+ raw += weight * TAG_WEIGHT * Math.min(tagHits, 2);
409
+ raw += weight * BODY_WEIGHT * Math.min(bodyHits, 2);
410
+ }
411
+ return raw;
412
+ }
413
+ /** Query token weights: tokens rarer in the query corpus weigh more. */
414
+ function queryWeights(query) {
415
+ const tokens = tokenize(query);
416
+ const counts = /* @__PURE__ */ new Map();
417
+ for (const token of tokens) counts.set(token, (counts.get(token) ?? 0) + 1);
418
+ const weights = /* @__PURE__ */ new Map();
419
+ for (const [token, count] of counts) weights.set(token, 1 / Math.sqrt(count));
420
+ return weights;
421
+ }
422
+ /** Rank active memories of one workspace against a query. */
423
+ function recallMemories(memories, query, options) {
424
+ const weights = queryWeights(query);
425
+ if (weights.size === 0) return [];
426
+ const scored = [];
427
+ for (const [memoryId, memory] of memories) {
428
+ const raw = rawScore(memory, weights);
429
+ if (raw < options.minScore) continue;
430
+ scored.push({
431
+ memoryId,
432
+ title: memory.title ?? "",
433
+ text: memory.text,
434
+ score: raw * decay(memory.createdAt, options.now, options.halfLifeDays),
435
+ createdAt: memory.createdAt,
436
+ keywords: memory.keywords
437
+ });
438
+ }
439
+ scored.sort((a, b) => b.score - a.score || b.createdAt - a.createdAt);
440
+ return scored.slice(0, options.limit);
441
+ }
442
+ /**
443
+ * R19 需求⑧: when a user need matches memories, surface the topic set those
444
+ * conclusions belong to, so the hub can answer from — or activate — the right
445
+ * set immediately instead of searching again.
446
+ *
447
+ * Matching is the same index-weighted rule as memory recall (title ×3, tags ×2,
448
+ * body ×1), and archived sets are ignored. It is pure and LLM-free.
449
+ */
450
+ function matchTopicSets(topicSets, query, limit = 3) {
451
+ const weights = queryWeights(query);
452
+ if (weights.size === 0) return [];
453
+ const matches = [];
454
+ for (const [id, topicSet] of topicSets) {
455
+ if (topicSet.status && topicSet.status !== "active") continue;
456
+ const fold = (text) => {
457
+ const bag = /* @__PURE__ */ new Map();
458
+ for (const token of tokenize(text)) bag.set(token, (bag.get(token) ?? 0) + 1);
459
+ return bag;
460
+ };
461
+ const titleBag = fold(topicSet.title ?? "");
462
+ const tagBag = fold((topicSet.keywords ?? []).join(" "));
463
+ const bodyBag = fold(topicSet.summary ?? "");
464
+ let score = 0;
465
+ for (const [token, weight] of weights) {
466
+ score += weight * 3 * Math.min(titleBag.get(token) ?? 0, 2);
467
+ score += weight * 2 * Math.min(tagBag.get(token) ?? 0, 2);
468
+ score += weight * 1 * Math.min(bodyBag.get(token) ?? 0, 2);
469
+ }
470
+ if (score <= 0) continue;
471
+ matches.push({
472
+ id,
473
+ title: topicSet.title,
474
+ tags: [...topicSet.keywords ?? []],
475
+ score
476
+ });
477
+ }
478
+ matches.sort((a, b) => b.score - a.score);
479
+ return matches.slice(0, Math.max(1, Math.min(limit, 8)));
480
+ }
481
+ /** The topic-set hint is kept only while this much room remains for records. */
482
+ const HINT_MIN_ROOM = 96;
483
+ /** Build the model-facing recall card text (温和起步, injectStyle 可配置).
484
+ *
485
+ * R47 需求②: `options.budget` makes the card budget-aware instead of letting
486
+ * the caller hard-`slice` it (the old `.slice(0, maxChars)` in prestep.ts cut
487
+ * mid-sentence, mid-tag, with no sign that anything was missing). Degradation
488
+ * is by PRIORITY, never mid-body:
489
+ * 1. the header is paid for first; the topic-set hint is kept only while it
490
+ * still leaves room for a record — a card must not become all preamble;
491
+ * 2. records are kept whole while they fit (score order = relevance order);
492
+ * 3. a record that no longer fits whole has its BODY clipped at a sentence
493
+ * boundary with an explicit omission note (title/tags stay whole);
494
+ * 4. a record whose remaining share cannot hold a meaningful body
495
+ * (`RECALL_BODY_MIN`) is dropped WHOLE, and a later, smaller record may
496
+ * still take its place;
497
+ * 5. the card ends with `…(已省略 k 项…)` when anything was dropped.
498
+ *
499
+ * Accounting counts CODE POINTS and reserves one newline per line, so the
500
+ * assembled card never exceeds `options.budget`; the note is budgeted too (an
501
+ * overflow retries with the note's real length reserved, bounded attempts).
502
+ */
503
+ function renderRecallCard(items, style, topicSets = [], options = {}) {
504
+ if (items.length === 0) return "";
505
+ const budget = options.budget && options.budget > 0 ? Math.floor(options.budget) : 0;
506
+ const header = style === "plain" ? [injectionTitle("memory")] : [
507
+ injectionTitle("memory"),
508
+ "以下记忆可能与本话题相关,仅供参考;与当前指令冲突时以当前指令为准。",
509
+ "记忆只存结论性事实/决策(不是过程流水账)。"
510
+ ];
511
+ const hints = topicSets.length > 0 ? [`相关话题集:${topicSets.map((topicSet) => topicSet.title).join("、")}(命中记忆时可直接激活或派发到该集)`] : [];
512
+ if (!budget) {
513
+ const lines = items.map((item, index) => `${index + 1}. ${renderRecordLine({
514
+ title: item.title,
515
+ text: item.text,
516
+ tags: item.keywords
517
+ })}`);
518
+ return [
519
+ ...header,
520
+ ...lines,
521
+ ...hints
522
+ ].join("\n");
523
+ }
524
+ const minimal = [injectionTitle("memory")];
525
+ if (budget - minimal.reduce((sum, line) => sum + charCount(line) + 1, 0) < 116) {
526
+ header.length = 0;
527
+ header.push(...minimal);
528
+ }
529
+ const headerCost = header.reduce((sum, line) => sum + charCount(line) + 1, 0);
530
+ const hintCostAll = hints.reduce((sum, line) => sum + charCount(line) + 1, 0);
531
+ const compose = (reserve, withHint = true) => {
532
+ const hintLines = budget - headerCost - hintCostAll - reserve >= HINT_MIN_ROOM ? hints : [];
533
+ const hintCost = hintLines.reduce((sum, line) => sum + charCount(line) + 1, 0);
534
+ let remaining = budget - headerCost - hintCost - reserve;
535
+ const lines = [];
536
+ let dropped = 0;
537
+ for (const [index, item] of items.entries()) {
538
+ const prefix = `${index + 1}. `;
539
+ const tail = item.keywords.length > 0 ? ` |标签: ${item.keywords.join("、")}` : "";
540
+ const head = item.title && item.title !== item.text.trim() ? `【${item.title}】` : "";
541
+ const overhead = charCount(prefix) + charCount(head) + charCount(tail) + 1;
542
+ const whole = `${prefix}${head}${item.text}${tail}`;
543
+ const wholeCost = charCount(whole) + 1;
544
+ if (wholeCost <= remaining) {
545
+ lines.push(whole);
546
+ remaining -= wholeCost;
547
+ continue;
548
+ }
549
+ const bodyShare = remaining - overhead;
550
+ if (bodyShare >= 64) {
551
+ const line = `${prefix}${head}${clipWithNote(item.text, bodyShare, item.title ? `复取:memory_recall 「${item.title}」` : void 0)}${tail}`;
552
+ lines.push(line);
553
+ remaining -= charCount(line) + 1;
554
+ if (remaining <= 0) {
555
+ dropped += items.length - index - 1;
556
+ break;
557
+ }
558
+ continue;
559
+ }
560
+ dropped += 1;
561
+ }
562
+ const note = dropNote(dropped, withHint ? options.hint : void 0);
563
+ return {
564
+ text: [
565
+ ...header,
566
+ ...hintLines,
567
+ ...lines,
568
+ ...note ? [note] : []
569
+ ].join("\n"),
570
+ note,
571
+ count: dropped
572
+ };
573
+ };
574
+ let pass = compose(0);
575
+ for (let attempt = 0; attempt < 3 && pass.note; attempt += 1) {
576
+ if (charCount(pass.text) <= budget) break;
577
+ pass = compose(charCount(pass.note) + 1);
578
+ }
579
+ if (charCount(pass.text) > budget && pass.count > 0) {
580
+ pass = compose(charCount(dropNote(pass.count)) + 1, false);
581
+ if (charCount(pass.text) > budget) return "";
582
+ }
583
+ return pass.text;
584
+ }
585
+ // src/model.ts
586
+ /** The hub agent's current selection, when readable. */
587
+ function hubSelection(agent) {
588
+ const current = agent?.model?.current?.();
589
+ if (current?.provider && current?.model) return {
590
+ provider: current.provider,
591
+ model: current.model,
592
+ ...current.reasoningEffort ? { reasoningEffort: current.reasoningEffort } : {}
593
+ };
594
+ }
595
+ /** Runtime enumeration of provider/model options for the question UI. */
596
+ async function enumerateModels(ctx) {
597
+ let llm;
598
+ try {
599
+ llm = ctx.get?.("llm");
600
+ } catch {
601
+ llm = void 0;
602
+ }
603
+ if (!llm) return {
604
+ providers: [],
605
+ models: []
606
+ };
607
+ const providers = llm.listProviders();
608
+ const models = [];
609
+ for (const provider of providers) try {
610
+ const list = await llm.listModels(provider.id);
611
+ for (const m of list) models.push({
612
+ provider: m.provider || provider.id,
613
+ id: m.id,
614
+ name: m.name || m.id
615
+ });
616
+ } catch {}
617
+ return {
618
+ providers,
619
+ models
620
+ };
621
+ }
622
+ /**
623
+ * Ask for a topic-set default model. Falls back to the hub model when the
624
+ * question channel is unavailable (headless / no client).
625
+ */
626
+ async function askDefaultModel(deps, agent) {
627
+ const { ctx, logger } = deps;
628
+ const hub = hubSelection(agent);
629
+ try {
630
+ const { models } = await enumerateModels(ctx);
631
+ const options = [...hub ? [{
632
+ label: "跟随中枢模型",
633
+ description: `${hub.provider}/${hub.model}`
634
+ }] : [], ...models.slice(0, 12).map((m) => ({
635
+ label: `${m.provider}/${m.id}`,
636
+ description: m.name
637
+ }))];
638
+ if (options.length === 0) {
639
+ const answer = await ctx.userQuestions.ask({
640
+ questions: [{
641
+ id: "supermemory-model",
642
+ header: "默认模型",
643
+ question: "该话题集使用哪个默认模型?当前没有可用目录,请直接输入 provider 与 model(如 step step-5-preview)。"
644
+ }],
645
+ ...agent ? { agent } : {}
646
+ });
647
+ return parseFreeInput(answer?.answers?.[0]?.custom ?? answer?.answers?.[0]?.selected?.[0]);
648
+ }
649
+ const answer = await ctx.userQuestions.ask({
650
+ questions: [{
651
+ id: "supermemory-model",
652
+ header: "默认模型",
653
+ question: "该话题集使用哪个默认模型?",
654
+ options
655
+ }],
656
+ ...agent ? { agent } : {}
657
+ });
658
+ const selected = answer?.answers?.[0]?.selected?.[0] ?? "";
659
+ const custom = answer?.answers?.[0]?.custom;
660
+ if (selected === "跟随中枢模型" && hub) return { ...hub };
661
+ const fromSelected = selected.includes("/") ? selected.split("/", 2) : void 0;
662
+ if (fromSelected) return {
663
+ provider: fromSelected[0],
664
+ model: fromSelected[1]
665
+ };
666
+ return parseFreeInput(custom) ?? (hub ? { ...hub } : void 0);
667
+ } catch (error) {
668
+ logger.warn(`supermemory: default-model question unavailable: ${String(error).slice(0, 160)}`);
669
+ return hub ? { ...hub } : void 0;
670
+ }
671
+ }
672
+ function parseFreeInput(raw) {
673
+ if (!raw) return void 0;
674
+ const parts = raw.trim().split(/[\s,,/]+/).filter(Boolean);
675
+ if (parts.length >= 2) return {
676
+ provider: parts[0],
677
+ model: parts[1]
678
+ };
679
+ }
680
+ /** The topic set that lists one session as a branch (undefined when none). */
681
+ function findMemberTopicSet(store, sessionId) {
682
+ for (const [topicSetId, record] of store.topicsets.entries()) if (record.members.some((member) => member.sessionId === sessionId)) return topicSetId;
683
+ }
684
+ /** Apply a model selection to a live agent and/or persist it as an override. */
685
+ async function applyModelSelection(deps, target, selection) {
686
+ const { ctx, store, logger } = deps;
687
+ let live = false;
688
+ if (target.branchSessionId) {
689
+ const agent = ctx.agents.get(target.branchSessionId);
690
+ const owner = (target.topicSetId && store.topicsets.get(target.topicSetId) ? target.topicSetId : void 0) ?? findMemberTopicSet(store, target.branchSessionId);
691
+ if (!agent && !owner) return {
692
+ applied: "",
693
+ live: false
694
+ };
695
+ if (agent) {
696
+ agent.model.select(selection);
697
+ live = true;
698
+ }
699
+ if (owner) await updateMember(store, owner, target.branchSessionId, {
700
+ model: `${selection.provider}/${selection.model}`,
701
+ modelOverridden: true
702
+ });
703
+ return {
704
+ applied: target.branchSessionId,
705
+ live
706
+ };
707
+ }
708
+ if (target.topicSetId) {
709
+ if (!store.topicsets.get(target.topicSetId)) return {
710
+ applied: "",
711
+ live: false
712
+ };
713
+ await setTopicSetModel(store, target.topicSetId, { ...selection });
714
+ const topicSet = store.topicsets.get(target.topicSetId);
715
+ for (const member of topicSet?.members ?? []) {
716
+ if (member.modelOverridden) continue;
717
+ const agent = ctx.agents.get(member.sessionId);
718
+ if (agent) {
719
+ agent.model.select(selection);
720
+ live = true;
721
+ }
722
+ await updateMember(store, target.topicSetId, member.sessionId, { model: `${selection.provider}/${selection.model}` });
723
+ }
724
+ return {
725
+ applied: target.topicSetId,
726
+ live
727
+ };
728
+ }
729
+ logger.warn("supermemory: applyModelSelection without target");
730
+ return {
731
+ applied: "",
732
+ live
733
+ };
734
+ }
735
+ export { tagsOfBody as _, matchTopicSets as a, injectionTitle as b, recallMemories as c, MEMORY_TEXT_MAX as d, assessConclusion as f, renderRecordLine as g, normalizeTags as h, hubSelection as i, renderRecallCard as l, mergeTags as m, askDefaultModel as n, queryWeights as o, deriveTitle as p, enumerateModels as r, rawScore as s, applyModelSelection as t, tokenize as u, extractFacts as v, INJECTION_TITLES as y };