chatluna-plugin-livingmemory 0.0.4 → 0.0.6
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.md +16 -14
- package/client/guide-panel.tsx +60 -37
- package/client/locales/en.yml +15 -6
- package/client/locales/zh.yml +21 -12
- package/client/page.tsx +41 -14
- package/client/preset-actions.tsx +120 -120
- package/dist/.vite/manifest.json +1 -1
- package/dist/client.css +1 -1
- package/dist/client.js +1 -1
- package/dist/page-EGG2hcC3.js +3 -0
- package/lib/contracts/memory.d.ts +12 -4
- package/lib/contracts/memory.d.ts.map +1 -1
- package/lib/contracts/webui.d.ts +3 -2
- package/lib/contracts/webui.d.ts.map +1 -1
- package/lib/contracts/workflows.d.ts +5 -17
- package/lib/contracts/workflows.d.ts.map +1 -1
- package/lib/index.js +620 -479
- package/lib/index.js.map +1 -1
- package/lib/routing.d.ts +2 -0
- package/lib/routing.d.ts.map +1 -1
- package/lib/service/app/admin_service.d.ts +10 -2
- package/lib/service/app/admin_service.d.ts.map +1 -1
- package/lib/service/app/mutation_service.d.ts +1 -2
- package/lib/service/app/mutation_service.d.ts.map +1 -1
- package/lib/service/app/query_projections.d.ts +2 -2
- package/lib/service/app/query_projections.d.ts.map +1 -1
- package/lib/service/app/webui.d.ts.map +1 -1
- package/lib/service/chat_history.d.ts +13 -7
- package/lib/service/chat_history.d.ts.map +1 -1
- package/lib/service/conversation_hooks.d.ts +25 -14
- package/lib/service/conversation_hooks.d.ts.map +1 -1
- package/lib/service/logging/logger.d.ts +2 -4
- package/lib/service/logging/logger.d.ts.map +1 -1
- package/lib/service/logging/model_calls.d.ts +11 -0
- package/lib/service/logging/model_calls.d.ts.map +1 -1
- package/lib/service/memory/conversation_sources.d.ts +20 -0
- package/lib/service/memory/conversation_sources.d.ts.map +1 -0
- package/lib/service/memory/helpers.d.ts +7 -8
- package/lib/service/memory/helpers.d.ts.map +1 -1
- package/lib/service/memory/tools/index.d.ts +2 -2
- package/lib/service/memory/tools/index.d.ts.map +1 -1
- package/lib/service/memory/tools/memory_tools.d.ts +2 -1
- package/lib/service/memory/tools/memory_tools.d.ts.map +1 -1
- package/lib/service/memory/tools/search_memory_tool.d.ts +2 -2
- package/lib/service/memory/tools/search_memory_tool.d.ts.map +1 -1
- package/lib/service/memory/tools/tool_runtime.d.ts +13 -1
- package/lib/service/memory/tools/tool_runtime.d.ts.map +1 -1
- package/lib/service/persistence/entries.d.ts +12 -10
- package/lib/service/persistence/entries.d.ts.map +1 -1
- package/lib/service/persistence/normalizers.d.ts.map +1 -1
- package/lib/service/persistence/repository.d.ts +22 -14
- package/lib/service/persistence/repository.d.ts.map +1 -1
- package/lib/service/persistence/source_migration.d.ts +6 -0
- package/lib/service/persistence/source_migration.d.ts.map +1 -0
- package/lib/service/persistence/tables.d.ts +3 -1
- package/lib/service/persistence/tables.d.ts.map +1 -1
- package/lib/service/prompts/dream.d.ts +2 -2
- package/lib/service/prompts/dream.d.ts.map +1 -1
- package/lib/service/prompts/memory_entries.d.ts +5 -13
- package/lib/service/prompts/memory_entries.d.ts.map +1 -1
- package/lib/service/prompts/user_profile.d.ts +2 -3
- package/lib/service/prompts/user_profile.d.ts.map +1 -1
- package/lib/service/shared/utils.d.ts +0 -4
- package/lib/service/shared/utils.d.ts.map +1 -1
- package/lib/service/transcript/header.d.ts +4 -0
- package/lib/service/transcript/header.d.ts.map +1 -0
- package/lib/service/user_profile.d.ts.map +1 -1
- package/lib/service/workflows/dream/session/history.d.ts +4 -4
- package/lib/service/workflows/dream/session/history.d.ts.map +1 -1
- package/lib/service/workflows/dream/session/runner.d.ts.map +1 -1
- package/lib/service/workflows/extraction/coordinator.d.ts.map +1 -1
- package/lib/service/workflows/extraction/extractor.d.ts +0 -4
- package/lib/service/workflows/extraction/extractor.d.ts.map +1 -1
- package/lib/service/workflows/recall/coordinator.d.ts +2 -2
- package/lib/service/workflows/recall/coordinator.d.ts.map +1 -1
- package/lib/service/workflows/structured_output.d.ts +10 -14
- package/lib/service/workflows/structured_output.d.ts.map +1 -1
- package/lib/service/workflows/tool_loop.d.ts +10 -21
- package/lib/service/workflows/tool_loop.d.ts.map +1 -1
- package/lib/service.d.ts.map +1 -1
- package/package.json +2 -1
- package/src/contracts/memory.ts +14 -4
- package/src/contracts/webui.ts +3 -2
- package/src/contracts/workflows.ts +17 -16
- package/dist/page-CQcDlyjD.js +0 -3
- package/lib/service/transcript/origin_context.d.ts +0 -17
- package/lib/service/transcript/origin_context.d.ts.map +0 -1
package/lib/index.js
CHANGED
|
@@ -14,21 +14,22 @@ import { setImmediate, setTimeout } from "node:timers/promises";
|
|
|
14
14
|
import { performance as performance$1 } from "node:perf_hooks";
|
|
15
15
|
import { Worker } from "node:worker_threads";
|
|
16
16
|
import { fileURLToPath } from "node:url";
|
|
17
|
-
import { ModelError, NoModelError
|
|
17
|
+
import { ModelError, NoModelError } from "@chatluna/ai";
|
|
18
|
+
import { addAbortListener } from "node:events";
|
|
18
19
|
import { requireActionLevel } from "@chatluna/ui-server";
|
|
19
20
|
import { ChatMessage } from "@chatluna/message";
|
|
20
21
|
// src/routing.ts
|
|
21
22
|
const ROUTE_SCHEMA = Schema$1.object({
|
|
22
|
-
extractionWindowMessages: Schema$1.natural().max(360).default(60).label("
|
|
23
|
-
extractionIncludeOverheard: Schema$1.boolean().default(false).label("
|
|
24
|
-
enableAutoDream: Schema$1.boolean().default(true).label("
|
|
25
|
-
recallIntervalMessages: Schema$1.natural().max(200).default(20).label("
|
|
26
|
-
recallHistoryMessages: Schema$1.natural().min(1).max(200).default(20).label("
|
|
27
|
-
snapshotScope: Schema$1.union([Schema$1.const("conversation").description("
|
|
28
|
-
snapshotMaxLines: Schema$1.natural().min(5).max(50).default(5).label("
|
|
29
|
-
enableConversationIsolation: Schema$1.boolean().default(false).label("
|
|
30
|
-
enableSnapshotInjection: Schema$1.boolean().default(true).label("注入记忆快照"),
|
|
31
|
-
enableUserProfileInjection: Schema$1.boolean().default(false).label("注入用户画像")
|
|
23
|
+
extractionWindowMessages: Schema$1.natural().max(360).default(60).label("从聊天中提取记忆的间隔").description("累计多少条消息后从聊天中提取记忆;0 表示关闭记忆提取。"),
|
|
24
|
+
extractionIncludeOverheard: Schema$1.boolean().default(false).label("允许群友闲聊触发记忆提取").description("开启后,bot 未参与的群友闲聊也会触发记忆提取。"),
|
|
25
|
+
enableAutoDream: Schema$1.boolean().default(true).label("是否在提取新记忆后进行 Dream 整理"),
|
|
26
|
+
recallIntervalMessages: Schema$1.natural().max(200).default(20).label("记忆自动召回的间隔").description("累计多少条消息后唤醒 bot 会自动召回记忆;0 表示关闭记忆召回。"),
|
|
27
|
+
recallHistoryMessages: Schema$1.natural().min(1).max(200).default(20).label("用于召回记忆的聊天消息数").description("使用多少条聊天信息作为上下文来召回记忆,建议与记忆自动召回的间隔保持一致。"),
|
|
28
|
+
snapshotScope: Schema$1.union([Schema$1.const("conversation").description("每一个会话拥有独立记忆快照"), Schema$1.const("preset").description("所有会话共享一个记忆快照")]).default("conversation").label("记忆快照的使用范围").description("开启「会话记忆隔离」时所有会话始终拥有一个独立记忆快照。"),
|
|
29
|
+
snapshotMaxLines: Schema$1.natural().min(5).max(50).default(5).label("记忆快照的最大行数"),
|
|
30
|
+
enableConversationIsolation: Schema$1.boolean().default(false).label("会话记忆隔离").description("记忆召回与记忆检索工具只检索来源于当前会话的记忆和全局记忆。"),
|
|
31
|
+
enableSnapshotInjection: Schema$1.boolean().default(true).label("向 bot 注入记忆快照"),
|
|
32
|
+
enableUserProfileInjection: Schema$1.boolean().default(false).label("向 bot 注入用户画像")
|
|
32
33
|
});
|
|
33
34
|
function registerRouteSettings(ctx) {
|
|
34
35
|
return ctx.schemas.section({
|
|
@@ -58,7 +59,20 @@ function privateWakeAddress(ctx, sessionId) {
|
|
|
58
59
|
isDirect: true
|
|
59
60
|
};
|
|
60
61
|
}
|
|
62
|
+
/** 上游的自定义会话键不含地点,可能同时连接多个群或私聊。 */
|
|
63
|
+
const isCustomConversation = (key) => key?.startsWith("custom:") === true;
|
|
61
64
|
function routeSettings(ctx, key, location, routeId, noticeSessionId) {
|
|
65
|
+
if (isCustomConversation(key)) {
|
|
66
|
+
const route = routeId ?? location?.route;
|
|
67
|
+
const channel = route && ctx.chat_observer.channelStats().find((item) => item.routeId === route);
|
|
68
|
+
const identity = channel && ctx.chat_observer.channelOf(channel.cid)?.identity;
|
|
69
|
+
if (identity) return ctx.routing.resolve(ctx.routing.matchInput({
|
|
70
|
+
...identity,
|
|
71
|
+
userId: void 0
|
|
72
|
+
}, route)).get("livingmemory");
|
|
73
|
+
const values = ctx.routing.valuesAt({ route }, "livingmemory");
|
|
74
|
+
return ROUTE_SCHEMA.parse(values ?? {});
|
|
75
|
+
}
|
|
62
76
|
if (key !== void 0 && (!location || location.isDirect && !routeId && !location.route)) {
|
|
63
77
|
const address = ctx.chat_observer.identityOfConversation(key) ?? privateWakeAddress(ctx, noticeSessionId);
|
|
64
78
|
if (address && (!routeId || routeId === routeIdOf(address))) {
|
|
@@ -201,21 +215,10 @@ const formatErrorDetails = (error) => {
|
|
|
201
215
|
return JSON.stringify(error);
|
|
202
216
|
};
|
|
203
217
|
/** 将任意抛出值规范为 Error,非 Error 值包装为消息。 */
|
|
204
|
-
const toError
|
|
218
|
+
const toError = (error) => {
|
|
205
219
|
if (error instanceof Error) return error;
|
|
206
220
|
return new Error(String(error));
|
|
207
221
|
};
|
|
208
|
-
/**
|
|
209
|
-
* 提取模型消息正文的纯文本:多分片内容仅拼接 text 分片,其余形式序列化为 JSON。
|
|
210
|
-
*/
|
|
211
|
-
const stringifyModelContent = (content) => {
|
|
212
|
-
if (typeof content === "string") return content;
|
|
213
|
-
if (Array.isArray(content)) return content.map((part) => {
|
|
214
|
-
if (part != null && typeof part === "object" && part.type === "text" && typeof part.text === "string") return part.text;
|
|
215
|
-
return "";
|
|
216
|
-
}).join("");
|
|
217
|
-
return JSON.stringify(content) ?? "";
|
|
218
|
-
};
|
|
219
222
|
// src/service/vector_index/errors.ts
|
|
220
223
|
var LivingMemoryVectorIndexError = class extends Error {
|
|
221
224
|
code;
|
|
@@ -251,8 +254,6 @@ const formatLogScope = (scope) => {
|
|
|
251
254
|
return details.join("; ");
|
|
252
255
|
};
|
|
253
256
|
const credentialKeyPattern = /(?:authorization|api[-_]?key|access[-_]?token|refresh[-_]?token|(?:^|[-_])token(?:$|[-_])|password|secret)/iu;
|
|
254
|
-
const bareValuePattern = /^[\p{L}\p{N}._:/@*+-]+$/u;
|
|
255
|
-
const toError = (error) => error instanceof Error ? error : new Error(String(error));
|
|
256
257
|
const normalizeValue = (value, key, seen) => {
|
|
257
258
|
if (credentialKeyPattern.test(key)) return "[REDACTED]";
|
|
258
259
|
if (value == null || typeof value === "boolean" || typeof value === "string") return value;
|
|
@@ -280,26 +281,13 @@ const normalizeValue = (value, key, seen) => {
|
|
|
280
281
|
seen.delete(objectValue);
|
|
281
282
|
}
|
|
282
283
|
};
|
|
283
|
-
|
|
284
|
-
const normalized = normalizeValue(value,
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
const formatBlockValue = (value, key) => stringifyNormalized(value, key, {
|
|
291
|
-
indent: 2,
|
|
292
|
-
bareStringsOnly: false
|
|
293
|
-
});
|
|
294
|
-
const formatFields = (fields) => Object.entries(fields).filter(([, value]) => value !== void 0).map(([key, value]) => `${key}:${formatValue(value, key)}`).join("; ");
|
|
295
|
-
const formatBlock = (block) => {
|
|
296
|
-
const title = block.title.replace(/\r?\n/gu, " ");
|
|
297
|
-
const detail = formatFields(block.fields ?? {});
|
|
298
|
-
const lines = [`========${detail.length > 0 ? `${title} ${detail}` : title}========`];
|
|
299
|
-
if (block.subtitle != null) lines.push(block.subtitle.replace(/\r?\n/gu, " "));
|
|
300
|
-
lines.push(formatBlockValue(block.value, block.key ?? ""));
|
|
301
|
-
return lines.join("\n");
|
|
302
|
-
};
|
|
284
|
+
function formatLogJson(value, indent) {
|
|
285
|
+
const normalized = normalizeValue(value, "", /* @__PURE__ */ new WeakSet());
|
|
286
|
+
return JSON.stringify(normalized, null, indent);
|
|
287
|
+
}
|
|
288
|
+
function formatBlock({ title, value }) {
|
|
289
|
+
return `========${title}========\n${typeof value === "string" ? value : formatLogJson(value, 2)}`;
|
|
290
|
+
}
|
|
303
291
|
var LivingMemoryLogger = class LivingMemoryLogger {
|
|
304
292
|
sink;
|
|
305
293
|
isDebugEnabled;
|
|
@@ -320,9 +308,7 @@ var LivingMemoryLogger = class LivingMemoryLogger {
|
|
|
320
308
|
diagnosticSummary(render) {
|
|
321
309
|
if (!this.isDebugEnabled()) return;
|
|
322
310
|
try {
|
|
323
|
-
const
|
|
324
|
-
if (rendered === void 0) return;
|
|
325
|
-
const { event, detail, blocks } = rendered;
|
|
311
|
+
const { event, detail, blocks } = render(this.context);
|
|
326
312
|
let content = detail;
|
|
327
313
|
if (blocks?.length) content += "\n" + blocks.map(formatBlock).join("\n\n");
|
|
328
314
|
this.summary(event, content);
|
|
@@ -380,10 +366,10 @@ var LivingMemoryMutationService = class {
|
|
|
380
366
|
return this.repository.listPresetSpeakers(presetId);
|
|
381
367
|
});
|
|
382
368
|
}
|
|
383
|
-
async appendExtractedMemories(scope, sourceOriginMessages, extracted,
|
|
369
|
+
async appendExtractedMemories(scope, sourceOriginMessages, extracted, windowSpeakers) {
|
|
384
370
|
return this.runPresetMutation(scope.presetId, async () => {
|
|
385
371
|
if (windowSpeakers.length > 0) await this.repository.registerMissingPresetSpeakers(scope.presetId, windowSpeakers);
|
|
386
|
-
const records = await this.repository.appendMemories(scope, sourceOriginMessages, extracted
|
|
372
|
+
const records = await this.repository.appendMemories(scope, sourceOriginMessages, extracted);
|
|
387
373
|
return {
|
|
388
374
|
memories: records,
|
|
389
375
|
warnings: await this.syncCommittedMemoriesToIndex(scope.presetId, records, [], "提取")
|
|
@@ -749,56 +735,39 @@ var LivingMemoryMemoryProviders = class {
|
|
|
749
735
|
}
|
|
750
736
|
};
|
|
751
737
|
// src/service/prompts/memory_entries.ts
|
|
752
|
-
const
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
];
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
];
|
|
771
|
-
const searchMemoryFields = ["id", ...contextMemoryFields];
|
|
772
|
-
const formatMemoryField = (entry, field, speakers) => {
|
|
773
|
-
switch (field) {
|
|
774
|
-
case "createdAt":
|
|
775
|
-
case "updatedAt": return `${field}=${entry[field].toISOString()}`;
|
|
776
|
-
case "keywords": return `keywords=${entry.keywords.join("、")}`;
|
|
777
|
-
case "content": return `content:\n${entry.content}`;
|
|
778
|
-
case "speakerLabels": {
|
|
779
|
-
const labels = entry.speakerKeys.map((key) => speakers.get(key).speakerLabel);
|
|
780
|
-
return `speakerLabels=${JSON.stringify(labels)}`;
|
|
781
|
-
}
|
|
782
|
-
default: {
|
|
783
|
-
const value = entry[field];
|
|
784
|
-
if (value === null) return null;
|
|
785
|
-
return `${field === "sourceLabel" ? "source" : field}=${value}`;
|
|
786
|
-
}
|
|
787
|
-
}
|
|
788
|
-
};
|
|
789
|
-
function renderMemoriesForModel(entries, options) {
|
|
790
|
-
const speakers = options.fields.includes("speakerLabels") ? new Map(options.speakers.map((speaker) => [speaker.speakerKey, speaker])) : void 0;
|
|
738
|
+
const entrySeparator = "\n\n---\n\n";
|
|
739
|
+
function renderEntry(entry, includeId, details = []) {
|
|
740
|
+
const lines = [`type=${entry.type}`, `updatedAt=${entry.updatedAt.toISOString()}`];
|
|
741
|
+
if (includeId) lines.unshift(`id=${entry.id}`);
|
|
742
|
+
if (entry.sentiment !== null) lines.push(`sentiment=${entry.sentiment}`);
|
|
743
|
+
return [
|
|
744
|
+
...lines,
|
|
745
|
+
...details,
|
|
746
|
+
entry.sourceLabel,
|
|
747
|
+
"content:",
|
|
748
|
+
entry.content
|
|
749
|
+
].join("\n");
|
|
750
|
+
}
|
|
751
|
+
function renderMemoriesForModel(entries, includeIds = false) {
|
|
752
|
+
return entries.map((entry) => renderEntry(entry, includeIds)).join(entrySeparator);
|
|
753
|
+
}
|
|
754
|
+
function renderDreamMemories(entries, speakers) {
|
|
755
|
+
const byKey = new Map(speakers.map((speaker) => [speaker.speakerKey, speaker]));
|
|
791
756
|
return entries.map((entry) => {
|
|
792
|
-
|
|
793
|
-
|
|
757
|
+
const details = [];
|
|
758
|
+
if (entry.importance !== null) details.push(`importance=${entry.importance}`);
|
|
759
|
+
details.push(`keywords=${entry.keywords.join("、")}`);
|
|
760
|
+
if (entry.summary !== null) details.push(`summary=${entry.summary}`);
|
|
761
|
+
const labels = entry.speakerKeys.map((key) => byKey.get(key).speakerLabel);
|
|
762
|
+
return `${renderEntry(entry, true, details)}\nspeakerLabels=${JSON.stringify(labels)}`;
|
|
763
|
+
}).join(entrySeparator);
|
|
794
764
|
}
|
|
795
765
|
/**
|
|
796
766
|
* 来源消息是提取工作流输入与 `<chat_history>` 注入共用的原始格式,
|
|
797
767
|
* `transcriptLines` 由来源消息序列化时写入并随数据持久化,直接作为模型视图复用。
|
|
798
768
|
*/
|
|
799
769
|
const renderMemorySourceMessagesForModel = (memory) => {
|
|
800
|
-
const header = [`id=${memory.id}
|
|
801
|
-
if (memory.sourceLabel != null) header.push(`source=${memory.sourceLabel}`);
|
|
770
|
+
const header = [`id=${memory.id}`, memory.sourceLabel];
|
|
802
771
|
if (memory.sourceOrigins.length === 0) return [...header, "(该记忆没有记录来源消息)"].join("\n");
|
|
803
772
|
const originCount = memory.sourceOrigins.length;
|
|
804
773
|
const blocks = memory.sourceOrigins.map((origin, index) => {
|
|
@@ -986,8 +955,53 @@ const personaCardResultTool = {
|
|
|
986
955
|
description: withParameterDocs(["人设卡片删减工具,当你需要按行删减预设原文内容时使用此工具。"], [["deletedLineNumbers", "要删除的行号列表,编号从 0 开始;保留全部内容时提交空数组。"]]),
|
|
987
956
|
schema: Schema$1.object({ deletedLineNumbers: Schema$1.array(Schema$1.natural()).required().description("要删除的行号列表,编号从 0 开始;保留全部内容时提交空数组。") })
|
|
988
957
|
};
|
|
958
|
+
// src/service/memory/helpers.ts
|
|
959
|
+
/** 消费进度按预设、来源路由(自定义会话)和会话区分;重置时按会话整体清除。 */
|
|
960
|
+
const scopeKey = (scope, routeId) => [
|
|
961
|
+
scope.presetId,
|
|
962
|
+
...routeId ? [routeId] : [],
|
|
963
|
+
scope.conversationId
|
|
964
|
+
].join("\n");
|
|
965
|
+
/** 宿主自定义会话可以跨地点复用;其它会话键保留个人和分线归属。 */
|
|
966
|
+
function memorySourceId(conversationId, routeId) {
|
|
967
|
+
if (!isCustomConversation(conversationId)) return conversationId;
|
|
968
|
+
if (!routeId) throw new Error("自定义会话缺少本次消息的来源路由。");
|
|
969
|
+
return routeId;
|
|
970
|
+
}
|
|
971
|
+
function snapshotScopeOf({ presetId, conversationId }, settings) {
|
|
972
|
+
return {
|
|
973
|
+
presetId,
|
|
974
|
+
conversationId: settings.snapshotScope === "preset" && !settings.enableConversationIsolation ? null : conversationId
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
/**
|
|
978
|
+
* 解析面向 LLM 的助手标签:优先使用 preset 展示名(presetLabel),
|
|
979
|
+
* 缺省或为空白时回退 presetId。
|
|
980
|
+
*/
|
|
981
|
+
const resolveScopeAssistantLabel = (scope) => scope.presetLabel?.trim() || scope.presetId;
|
|
982
|
+
const resolvePresetAssistantLabel = (ctx, presetId) => ctx.presets.get(presetId)?.name.trim() || presetId;
|
|
983
|
+
/**
|
|
984
|
+
* 取预设 system 部分的未渲染原文,作为人设卡片的删减来源。不经模板渲染器、
|
|
985
|
+
* 不取任何变量值:system 部分应为固定人设,写入其中的占位符原样保留。
|
|
986
|
+
*/
|
|
987
|
+
const resolvePresetPrompt = async (ctx, presetId) => {
|
|
988
|
+
const record = ctx.presets.get(presetId);
|
|
989
|
+
if (record === void 0) throw new Error(`preset not found: ${presetId}`);
|
|
990
|
+
return (ctx.presets.blocks(record) ?? []).filter((block) => block.zone === "system" && (block.role === void 0 || block.role === "system") && typeof block.content === "string").sort((left, right) => (left.order ?? 0) - (right.order ?? 0)).map((block) => block.content.trim()).filter((content) => content.length > 0).join("\n\n").trim();
|
|
991
|
+
};
|
|
989
992
|
// src/service/memory/tools/tool_runtime.ts
|
|
990
993
|
const agentOfTool = (agent) => isRecord(agent) && isRecord(agent["options"]) ? agent : void 0;
|
|
994
|
+
function toolContext(call, resolve) {
|
|
995
|
+
const agent = agentOfTool(call.agent);
|
|
996
|
+
const routeId = call.routeId ?? call.location?.route ?? agent?.options.location?.route;
|
|
997
|
+
return {
|
|
998
|
+
agent,
|
|
999
|
+
...resolve?.(agent, routeId) ?? {
|
|
1000
|
+
isolated: false,
|
|
1001
|
+
routeId
|
|
1002
|
+
}
|
|
1003
|
+
};
|
|
1004
|
+
}
|
|
991
1005
|
const resolveToolMemoryPresetId = (agent) => {
|
|
992
1006
|
const presetId = agent?.options.presetId;
|
|
993
1007
|
if (presetId === void 0 || presetId.trim().length === 0) return {
|
|
@@ -1002,7 +1016,7 @@ const resolveToolMemoryPresetId = (agent) => {
|
|
|
1002
1016
|
/**
|
|
1003
1017
|
* 从工具调用的 Agent 读取会话作用域;子代理调用一律拒绝。
|
|
1004
1018
|
*/
|
|
1005
|
-
const resolveToolMemoryScope = (agent) => {
|
|
1019
|
+
const resolveToolMemoryScope = (agent, routeId) => {
|
|
1006
1020
|
const presetIdResolution = resolveToolMemoryPresetId(agent);
|
|
1007
1021
|
if (presetIdResolution.ok === false) return presetIdResolution;
|
|
1008
1022
|
if ((agent?.options.permissions?.origin?.length ?? 0) > 0) return {
|
|
@@ -1016,7 +1030,7 @@ const resolveToolMemoryScope = (agent) => {
|
|
|
1016
1030
|
};
|
|
1017
1031
|
const location = agent?.options.location;
|
|
1018
1032
|
const scope = {
|
|
1019
|
-
conversationId,
|
|
1033
|
+
conversationId: memorySourceId(conversationId, routeId),
|
|
1020
1034
|
presetId: presetIdResolution.presetId
|
|
1021
1035
|
};
|
|
1022
1036
|
if (location?.platform !== void 0) scope.platform = location.platform;
|
|
@@ -1036,7 +1050,7 @@ const describeLivingMemoryToolScopeFailure = (reason) => {
|
|
|
1036
1050
|
}
|
|
1037
1051
|
};
|
|
1038
1052
|
// src/service/memory/tools/memory_tools.ts
|
|
1039
|
-
const createCreateMemoryTool = (creation, maxMemories) => {
|
|
1053
|
+
const createCreateMemoryTool = (creation, maxMemories, resolveRoute) => {
|
|
1040
1054
|
const doc = memoryCreateTool(maxMemories);
|
|
1041
1055
|
return defineTool({
|
|
1042
1056
|
name: doc.name,
|
|
@@ -1044,7 +1058,8 @@ const createCreateMemoryTool = (creation, maxMemories) => {
|
|
|
1044
1058
|
args: doc.schema,
|
|
1045
1059
|
traits: { effect: "write" },
|
|
1046
1060
|
async run(input, call) {
|
|
1047
|
-
const
|
|
1061
|
+
const { agent, routeId } = toolContext(call, resolveRoute);
|
|
1062
|
+
const resolution = resolveToolMemoryScope(agent, routeId);
|
|
1048
1063
|
if (resolution.ok === false) throw new Error(describeLivingMemoryToolScopeFailure(resolution.reason));
|
|
1049
1064
|
const createdMemories = [];
|
|
1050
1065
|
const warnings = [];
|
|
@@ -1171,22 +1186,22 @@ const createGetMessagesTool = (sources) => defineTool({
|
|
|
1171
1186
|
}
|
|
1172
1187
|
});
|
|
1173
1188
|
// src/service/memory/tools/search_memory_tool.ts
|
|
1174
|
-
const noMemoryFoundMessage$1 = "没有找到相关记忆。";
|
|
1175
1189
|
/**
|
|
1176
1190
|
* 记忆检索工具。检索固定只看活跃记忆;开启会话隔离时把当前会话作为
|
|
1177
1191
|
* 检索范围,否则在整个预设内检索。
|
|
1178
1192
|
*/
|
|
1179
|
-
const createSearchMemoryTool = (searchProvider,
|
|
1193
|
+
const createSearchMemoryTool = (searchProvider, resolveRoute) => defineTool({
|
|
1180
1194
|
name: memorySearchTool.name,
|
|
1181
1195
|
description: memorySearchTool.description,
|
|
1182
1196
|
args: memorySearchTool.schema,
|
|
1183
1197
|
traits: { effect: "read" },
|
|
1184
1198
|
async run(input, call) {
|
|
1185
|
-
const agent =
|
|
1199
|
+
const { agent, isolated, routeId } = toolContext(call, resolveRoute);
|
|
1186
1200
|
let presetId;
|
|
1187
1201
|
let conversationId;
|
|
1188
|
-
if (
|
|
1189
|
-
|
|
1202
|
+
if (isCustomConversation(agent?.options.conversationKey) && !routeId) throw new Error("自定义会话缺少本次消息的来源路由。");
|
|
1203
|
+
if (isolated) {
|
|
1204
|
+
const resolution = resolveToolMemoryScope(agent, routeId);
|
|
1190
1205
|
if (resolution.ok === false) throw new Error(describeLivingMemoryToolScopeFailure(resolution.reason));
|
|
1191
1206
|
presetId = resolution.scope.presetId;
|
|
1192
1207
|
conversationId = resolution.scope.conversationId;
|
|
@@ -1200,13 +1215,9 @@ const createSearchMemoryTool = (searchProvider, includeMemoryIds, isConversation
|
|
|
1200
1215
|
memoryTypes: ["all"],
|
|
1201
1216
|
memoryStatus: "active"
|
|
1202
1217
|
}, conversationId);
|
|
1203
|
-
return
|
|
1218
|
+
return results.length ? renderMemoriesForModel(results, true) : "没有找到相关记忆。";
|
|
1204
1219
|
}
|
|
1205
1220
|
});
|
|
1206
|
-
const formatResults = (results, includeMemoryIds) => {
|
|
1207
|
-
if (results.length === 0) return noMemoryFoundMessage$1;
|
|
1208
|
-
return renderMemoriesForModel(results, { fields: includeMemoryIds ? searchMemoryFields : contextMemoryFields });
|
|
1209
|
-
};
|
|
1210
1221
|
memorySearchTool.name, memoryGetMessagesTool.name, memoryCreateTool(1).name, memoryUpdateTool.name, memoryMergeTool.name, memorySplitTool.name, memoryDeleteTool.name;
|
|
1211
1222
|
/**
|
|
1212
1223
|
* 注册记忆工具。只注册配置里启用的工具,未启用时不影响其它能力。
|
|
@@ -1215,9 +1226,9 @@ memorySearchTool.name, memoryGetMessagesTool.name, memoryCreateTool(1).name, mem
|
|
|
1215
1226
|
const registerLivingMemoryTools = (ctx, providers, options) => {
|
|
1216
1227
|
const enabled = new Set(options.enabled);
|
|
1217
1228
|
return [
|
|
1218
|
-
createSearchMemoryTool(providers,
|
|
1229
|
+
createSearchMemoryTool(providers, options.resolveRoute),
|
|
1219
1230
|
createGetMessagesTool(providers),
|
|
1220
|
-
createCreateMemoryTool(providers, options.createToolMaxMemories),
|
|
1231
|
+
createCreateMemoryTool(providers, options.createToolMaxMemories, options.resolveRoute),
|
|
1221
1232
|
createUpdateMemoryTool(providers),
|
|
1222
1233
|
createMergeMemoriesTool(providers),
|
|
1223
1234
|
createSplitMemoryTool(providers),
|
|
@@ -1399,8 +1410,8 @@ function defineLivingMemoryTables(ctx) {
|
|
|
1399
1410
|
primary: "presetId"
|
|
1400
1411
|
});
|
|
1401
1412
|
}
|
|
1402
|
-
// src/service/
|
|
1403
|
-
const
|
|
1413
|
+
// src/service/memory/conversation_sources.ts
|
|
1414
|
+
const formatConversationPeer = (peer) => {
|
|
1404
1415
|
const address = `${peer.kind === "guild" ? "群聊" : "用户"} ID:${peer.id}`;
|
|
1405
1416
|
return peer.name ? `「${peer.name}」(${address})` : address;
|
|
1406
1417
|
};
|
|
@@ -1413,74 +1424,117 @@ async function peerName(ctx, peer, storedName) {
|
|
|
1413
1424
|
const profile = await ctx.routing.peers.profile(peer.key);
|
|
1414
1425
|
return knownName(peer.id, profile.name);
|
|
1415
1426
|
}
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
userId:
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
return routeIdOf(guild) === key || routeIdOf({
|
|
1431
|
-
...guild,
|
|
1432
|
-
channelId: id
|
|
1433
|
-
}) === key;
|
|
1427
|
+
/** 跨群对话只持久化一个会话头,各消息的实际路由由框架的频道记录提供。 */
|
|
1428
|
+
function observedSourceRoutes(ctx) {
|
|
1429
|
+
const routes = /* @__PURE__ */ new Map();
|
|
1430
|
+
const observer = ctx.get("chat_observer");
|
|
1431
|
+
if (!observer) return routes;
|
|
1432
|
+
for (const { cid, routeId, conversationKey } of observer.channelStats()) {
|
|
1433
|
+
if (!conversationKey.startsWith("custom:")) continue;
|
|
1434
|
+
const identity = observer.channelOf(cid)?.identity;
|
|
1435
|
+
if (!identity) continue;
|
|
1436
|
+
const kind = identity.isDirect ? "user" : "guild";
|
|
1437
|
+
const id = identity.isDirect ? identity.userId : identity.guildId;
|
|
1438
|
+
if (id) routes.set(routeId, `${identity.platform}:${identity.selfId}:${kind}:${id}`);
|
|
1439
|
+
}
|
|
1440
|
+
return routes;
|
|
1434
1441
|
}
|
|
1435
|
-
/**
|
|
1442
|
+
/** 标准会话、个人会话和存档都以实际路由开头;自定义会话的首个联系人不能代表整段聊天。 */
|
|
1436
1443
|
async function resolveConversationSources(ctx, conversationIds) {
|
|
1437
1444
|
const sources = /* @__PURE__ */ new Map();
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
const
|
|
1441
|
-
|
|
1442
|
-
const
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
+
const keys = [...new Set(conversationIds.filter((key) => key !== null && /^r-[0-9a-f]{12}(?::|$)/.test(key)))];
|
|
1446
|
+
if (keys.length === 0) return sources;
|
|
1447
|
+
const rows = await ctx.database.get("chatluna_conversations", { key: keys }, ["key", "peer"]);
|
|
1448
|
+
const byRoute = /* @__PURE__ */ new Map();
|
|
1449
|
+
for (const { key, peer } of rows) if (peer) byRoute.set(key, peer);
|
|
1450
|
+
if (byRoute.size < keys.length) {
|
|
1451
|
+
const observed = observedSourceRoutes(ctx);
|
|
1452
|
+
for (const key of keys) {
|
|
1453
|
+
const peer = observed.get(key);
|
|
1454
|
+
if (peer) byRoute.set(key, peer);
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
if (!byRoute.size) return sources;
|
|
1458
|
+
const peers = await ctx.routing.peers.get([...new Set(byRoute.values())]);
|
|
1459
|
+
for (const [key, peer] of byRoute) {
|
|
1445
1460
|
const ref = peers.get(peer);
|
|
1446
1461
|
if (!ref || ref.kind !== "guild" && ref.kind !== "user") continue;
|
|
1447
|
-
const {
|
|
1462
|
+
const { kind, id } = ref;
|
|
1448
1463
|
const source = {
|
|
1449
1464
|
key: ref.key,
|
|
1450
1465
|
kind,
|
|
1451
1466
|
id,
|
|
1452
1467
|
name: ref.name
|
|
1453
1468
|
};
|
|
1454
|
-
if (!ownsRoute(key, platform, selfId, source)) continue;
|
|
1455
1469
|
source.name = await peerName(ctx, source);
|
|
1456
1470
|
sources.set(key, source);
|
|
1457
1471
|
}
|
|
1458
1472
|
return sources;
|
|
1459
1473
|
}
|
|
1460
|
-
async function
|
|
1461
|
-
const
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1474
|
+
async function withSourceLabels(ctx, entries) {
|
|
1475
|
+
const sources = await resolveConversationSources(ctx, entries.map((entry) => entry.sourceConversationId));
|
|
1476
|
+
return entries.map((entry) => {
|
|
1477
|
+
const source = entry.sourceConversationId ? sources.get(entry.sourceConversationId) : void 0;
|
|
1478
|
+
const sourceLabel = `来源 · ${source?.name ? formatConversationPeer(source) : "unknown"}`;
|
|
1479
|
+
return {
|
|
1480
|
+
...entry,
|
|
1481
|
+
sourceLabel
|
|
1466
1482
|
};
|
|
1467
|
-
|
|
1468
|
-
}
|
|
1469
|
-
const stored = await ctx.routing.peers.get([...peers.keys()]);
|
|
1470
|
-
const labels = [];
|
|
1471
|
-
for (const peer of peers.values()) {
|
|
1472
|
-
const name = await peerName(ctx, peer, stored.get(peer.key)?.name);
|
|
1473
|
-
labels.push(formatSource({
|
|
1474
|
-
...peer,
|
|
1475
|
-
name
|
|
1476
|
-
}));
|
|
1477
|
-
}
|
|
1478
|
-
const sourceLabel = labels.join("、");
|
|
1479
|
-
return {
|
|
1480
|
-
header: `以下是来自${sourceLabel}的聊天记录:`,
|
|
1481
|
-
sourceLabel
|
|
1482
|
-
};
|
|
1483
|
+
});
|
|
1483
1484
|
}
|
|
1485
|
+
// src/service/persistence/source_migration.ts
|
|
1486
|
+
const PEER_ALIAS = /^(?:group|private|[^:]+:(?:guild|user)):.+$/;
|
|
1487
|
+
const LEGACY_KEY = new RegExp(`${PEER_ALIAS.source}|${/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.source}`, "i");
|
|
1488
|
+
const PHYSICAL_ROUTE = /^r-[0-9a-f]{12}$/;
|
|
1489
|
+
const NATIVE_KEY = /^(?:r-[0-9a-f]{12}(?::|$)|custom:)/;
|
|
1490
|
+
/** 有旧群号或用户号时枚举一次普通路由;多个账号或频道匹配同一旧键时归入全局。 */
|
|
1491
|
+
async function resolveImportedSources(ctx, ids) {
|
|
1492
|
+
const wanted = [...new Set(ids.filter((id) => !!id))];
|
|
1493
|
+
const result = /* @__PURE__ */ new Map();
|
|
1494
|
+
if (!wanted.length) return result;
|
|
1495
|
+
const aliases = new Set(wanted.filter((key) => !NATIVE_KEY.test(key) && PEER_ALIAS.test(key)));
|
|
1496
|
+
const exact = { key: wanted };
|
|
1497
|
+
const query = aliases.size ? { $or: [exact, { key: PHYSICAL_ROUTE }] } : exact;
|
|
1498
|
+
const heads = await ctx.database.get("chatluna_conversations", query, ["key", "peer"]);
|
|
1499
|
+
const routes = new Map(observedSourceRoutes(ctx));
|
|
1500
|
+
for (const { key, peer } of heads) if (peer || !routes.has(key)) routes.set(key, peer);
|
|
1501
|
+
if (aliases.size) for (const [route, peer] of routes) {
|
|
1502
|
+
if (!peer || !PHYSICAL_ROUTE.test(route)) continue;
|
|
1503
|
+
const match = /^([^:]+):[^:]+:(guild|user):(.+)$/.exec(peer);
|
|
1504
|
+
if (!match) continue;
|
|
1505
|
+
const [, platform, kind, id] = match;
|
|
1506
|
+
const oldKeys = [`${kind === "guild" ? "group" : "private"}:${id}`, `${platform}:${kind}:${id}`];
|
|
1507
|
+
for (const key of oldKeys) if (aliases.has(key)) result.set(key, result.has(key) ? null : route);
|
|
1508
|
+
}
|
|
1509
|
+
for (const key of wanted) if (routes.has(key)) result.set(key, key);
|
|
1510
|
+
return result;
|
|
1511
|
+
}
|
|
1512
|
+
/** 启动索引对账前更新主库,沿用原有向量,只同步新的会话归属。 */
|
|
1513
|
+
async function migrateLegacySources(ctx) {
|
|
1514
|
+
const keys = (await ctx.database.select("living_memory_entry", { sourceConversationId: { $regex: LEGACY_KEY } }).groupBy("sourceConversationId").execute(["sourceConversationId"])).map((row) => row.sourceConversationId).filter((key) => !!key && !NATIVE_KEY.test(key));
|
|
1515
|
+
if (!keys.length) return;
|
|
1516
|
+
const sources = await resolveImportedSources(ctx, keys);
|
|
1517
|
+
await ctx.database.transact(async (db) => {
|
|
1518
|
+
for (const key of keys) {
|
|
1519
|
+
const target = sources.get(key) ?? null;
|
|
1520
|
+
if (key !== target) await db.set("living_memory_entry", { sourceConversationId: key }, { sourceConversationId: target });
|
|
1521
|
+
}
|
|
1522
|
+
});
|
|
1523
|
+
}
|
|
1524
|
+
// src/contracts/workflows.ts
|
|
1525
|
+
const dreamEntryFields = [
|
|
1526
|
+
"id",
|
|
1527
|
+
"presetId",
|
|
1528
|
+
"speakerKeys",
|
|
1529
|
+
"type",
|
|
1530
|
+
"content",
|
|
1531
|
+
"keywords",
|
|
1532
|
+
"summary",
|
|
1533
|
+
"sentiment",
|
|
1534
|
+
"importance",
|
|
1535
|
+
"sourceConversationId",
|
|
1536
|
+
"updatedAt"
|
|
1537
|
+
];
|
|
1484
1538
|
// src/service/persistence/normalizers.ts
|
|
1485
1539
|
const normalizeSourceConversationId = (value) => {
|
|
1486
1540
|
const normalized = value?.trim();
|
|
@@ -1493,8 +1547,7 @@ const normalizeEntryRecord = (record) => ({
|
|
|
1493
1547
|
summary: normalizeOptionalMemoryText(record.summary),
|
|
1494
1548
|
sentiment: normalizeOptionalMemoryText(record.sentiment),
|
|
1495
1549
|
importance: normalizeMemoryImportance(record.importance),
|
|
1496
|
-
sourceConversationId: normalizeSourceConversationId(record.sourceConversationId)
|
|
1497
|
-
sourceLabel: normalizeOptionalMemoryText(record.sourceLabel)
|
|
1550
|
+
sourceConversationId: normalizeSourceConversationId(record.sourceConversationId)
|
|
1498
1551
|
});
|
|
1499
1552
|
const normalizeUserProfileRecord = (record) => ({
|
|
1500
1553
|
...record,
|
|
@@ -1545,7 +1598,6 @@ const memoryEntryFields = [
|
|
|
1545
1598
|
"sentiment",
|
|
1546
1599
|
"importance",
|
|
1547
1600
|
"sourceConversationId",
|
|
1548
|
-
"sourceLabel",
|
|
1549
1601
|
"sourceOrigins",
|
|
1550
1602
|
"createdAt",
|
|
1551
1603
|
"updatedAt"
|
|
@@ -1560,20 +1612,6 @@ const indexSourceFields = [
|
|
|
1560
1612
|
"keywords",
|
|
1561
1613
|
"updatedAt"
|
|
1562
1614
|
];
|
|
1563
|
-
const dreamEntryFields = [
|
|
1564
|
-
"id",
|
|
1565
|
-
"presetId",
|
|
1566
|
-
"speakerKeys",
|
|
1567
|
-
"type",
|
|
1568
|
-
"content",
|
|
1569
|
-
"keywords",
|
|
1570
|
-
"summary",
|
|
1571
|
-
"sentiment",
|
|
1572
|
-
"importance",
|
|
1573
|
-
"sourceLabel",
|
|
1574
|
-
"createdAt",
|
|
1575
|
-
"updatedAt"
|
|
1576
|
-
];
|
|
1577
1615
|
const recallEntryFields = [
|
|
1578
1616
|
"id",
|
|
1579
1617
|
"type",
|
|
@@ -1583,7 +1621,6 @@ const recallEntryFields = [
|
|
|
1583
1621
|
"sentiment",
|
|
1584
1622
|
"importance",
|
|
1585
1623
|
"sourceConversationId",
|
|
1586
|
-
"sourceLabel",
|
|
1587
1624
|
"createdAt",
|
|
1588
1625
|
"updatedAt"
|
|
1589
1626
|
];
|
|
@@ -1612,8 +1649,8 @@ var LivingMemoryEntryRepository = class {
|
|
|
1612
1649
|
"updatedAt"
|
|
1613
1650
|
]);
|
|
1614
1651
|
}
|
|
1615
|
-
|
|
1616
|
-
return
|
|
1652
|
+
listDreamEntriesByPreset(presetId) {
|
|
1653
|
+
return this.database.get("living_memory_entry", {
|
|
1617
1654
|
presetId,
|
|
1618
1655
|
status: "active"
|
|
1619
1656
|
}, dreamEntryFields);
|
|
@@ -1675,12 +1712,11 @@ var LivingMemoryEntryRepository = class {
|
|
|
1675
1712
|
id: { $in: ids }
|
|
1676
1713
|
}, recallEntryFields);
|
|
1677
1714
|
}
|
|
1678
|
-
async appendMemories(scope, sourceOriginMessages, extracted
|
|
1715
|
+
async appendMemories(scope, sourceOriginMessages, extracted) {
|
|
1679
1716
|
if (extracted.length === 0) return [];
|
|
1680
1717
|
const now = /* @__PURE__ */ new Date();
|
|
1681
1718
|
const sourceOrigins = createSourceOriginsFromMessages(sourceOriginMessages);
|
|
1682
|
-
const
|
|
1683
|
-
const records = extracted.map((item) => this.buildMemoryEntry(scope, item, sourceOrigins, normalizedSourceLabel, now, item.speakerKeys));
|
|
1719
|
+
const records = extracted.map((item) => this.buildMemoryEntry(scope, item, sourceOrigins, now, item.speakerKeys));
|
|
1684
1720
|
await this.transact(async (database) => {
|
|
1685
1721
|
await database.upsert("living_memory_entry", records);
|
|
1686
1722
|
await this.replaceActiveMemorySpeakers(database, records);
|
|
@@ -1688,14 +1724,14 @@ var LivingMemoryEntryRepository = class {
|
|
|
1688
1724
|
return records;
|
|
1689
1725
|
}
|
|
1690
1726
|
async createMemory(scope, input, speakerKeys) {
|
|
1691
|
-
const record = this.buildMemoryEntry(scope, input, [],
|
|
1727
|
+
const record = this.buildMemoryEntry(scope, input, [], /* @__PURE__ */ new Date(), speakerKeys ?? resolveScopeSpeakerKeys(scope));
|
|
1692
1728
|
await this.transact(async (database) => {
|
|
1693
1729
|
await database.create("living_memory_entry", record);
|
|
1694
1730
|
await this.replaceActiveMemorySpeakers(database, [record]);
|
|
1695
1731
|
});
|
|
1696
1732
|
return record;
|
|
1697
1733
|
}
|
|
1698
|
-
buildMemoryEntry(scope, fields, sourceOrigins,
|
|
1734
|
+
buildMemoryEntry(scope, fields, sourceOrigins, createdAt, speakerKeys) {
|
|
1699
1735
|
const content = normalizeMemoryText(fields.content);
|
|
1700
1736
|
return {
|
|
1701
1737
|
id: randomUUID(),
|
|
@@ -1709,7 +1745,6 @@ var LivingMemoryEntryRepository = class {
|
|
|
1709
1745
|
sentiment: normalizeOptionalMemoryText(fields.sentiment),
|
|
1710
1746
|
importance: normalizeMemoryImportance(fields.importance),
|
|
1711
1747
|
sourceConversationId: scope.conversationId.trim() || null,
|
|
1712
|
-
sourceLabel,
|
|
1713
1748
|
sourceOrigins,
|
|
1714
1749
|
createdAt,
|
|
1715
1750
|
updatedAt: createdAt
|
|
@@ -1775,7 +1810,7 @@ var LivingMemoryEntryRepository = class {
|
|
|
1775
1810
|
return this.buildMemoryEntry({
|
|
1776
1811
|
presetId,
|
|
1777
1812
|
conversationId: source.sourceConversationId ?? ""
|
|
1778
|
-
}, memory, source.sourceOrigins,
|
|
1813
|
+
}, memory, source.sourceOrigins, now, memory.speakerKeys);
|
|
1779
1814
|
});
|
|
1780
1815
|
await database.upsert("living_memory_entry", records);
|
|
1781
1816
|
await database.set("living_memory_entry", {
|
|
@@ -1813,12 +1848,11 @@ var LivingMemoryEntryRepository = class {
|
|
|
1813
1848
|
return entry;
|
|
1814
1849
|
});
|
|
1815
1850
|
const sameConversation = sources.every((source) => source.sourceConversationId === sources[0].sourceConversationId);
|
|
1816
|
-
const sameLabel = sources.every((source) => source.sourceLabel === sources[0].sourceLabel);
|
|
1817
1851
|
const now = /* @__PURE__ */ new Date();
|
|
1818
1852
|
const record = this.buildMemoryEntry({
|
|
1819
1853
|
presetId,
|
|
1820
1854
|
conversationId: sameConversation ? sources[0].sourceConversationId ?? "" : ""
|
|
1821
|
-
}, memory, mergeMemorySourceOrigins(sources),
|
|
1855
|
+
}, memory, mergeMemorySourceOrigins(sources), now, memory.speakerKeys);
|
|
1822
1856
|
await database.create("living_memory_entry", record);
|
|
1823
1857
|
await database.set("living_memory_entry", {
|
|
1824
1858
|
presetId,
|
|
@@ -2331,26 +2365,15 @@ var LivingMemoryRepository = class {
|
|
|
2331
2365
|
defineLivingMemoryTables(this.ctx);
|
|
2332
2366
|
}
|
|
2333
2367
|
/**
|
|
2334
|
-
*
|
|
2368
|
+
* 运行期仓储事务的入口。单连接数据库无法并发开启事务,因此这些事务共用一条
|
|
2335
2369
|
* 串行链;这是驱动限制的变通,不是一致性机制本身——一致性来自事务边界,
|
|
2336
2370
|
* 上层的预设级串行队列不得因此被移除。
|
|
2337
2371
|
*/
|
|
2338
2372
|
runTransaction(callback) {
|
|
2339
2373
|
return this.transactions.run(TRANSACTION_QUEUE_KEY, () => this.database.transact(callback));
|
|
2340
2374
|
}
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
for (const entry of entries) if (entry.sourceConversationId) conversationIds.push(entry.sourceConversationId);
|
|
2344
|
-
const sources = await resolveConversationSources(this.ctx, conversationIds);
|
|
2345
|
-
return entries.map((entry) => {
|
|
2346
|
-
if (!entry.sourceConversationId) return entry;
|
|
2347
|
-
const source = sources.get(entry.sourceConversationId);
|
|
2348
|
-
if (!source?.name) return entry;
|
|
2349
|
-
return {
|
|
2350
|
-
...entry,
|
|
2351
|
-
sourceLabel: formatSource(source)
|
|
2352
|
-
};
|
|
2353
|
-
});
|
|
2375
|
+
withSourceLabels(entries) {
|
|
2376
|
+
return withSourceLabels(this.ctx, entries);
|
|
2354
2377
|
}
|
|
2355
2378
|
listEntriesByPreset(presetId) {
|
|
2356
2379
|
return this.entries.listEntriesByPreset(presetId);
|
|
@@ -2397,8 +2420,8 @@ var LivingMemoryRepository = class {
|
|
|
2397
2420
|
async getSearchEntriesByPresetAndIds(presetId, ids) {
|
|
2398
2421
|
return this.withSourceLabels(await this.entries.getSearchEntriesByPresetAndIds(presetId, ids));
|
|
2399
2422
|
}
|
|
2400
|
-
appendMemories(scope, sourceOriginMessages, extracted
|
|
2401
|
-
return this.entries.appendMemories(scope, sourceOriginMessages, extracted
|
|
2423
|
+
appendMemories(scope, sourceOriginMessages, extracted) {
|
|
2424
|
+
return this.entries.appendMemories(scope, sourceOriginMessages, extracted);
|
|
2402
2425
|
}
|
|
2403
2426
|
createMemory(scope, input, speakerKeys) {
|
|
2404
2427
|
return this.entries.createMemory(scope, input, speakerKeys);
|
|
@@ -2506,10 +2529,10 @@ var LivingMemoryRepository = class {
|
|
|
2506
2529
|
this.userProfiles.listPresetSpeakers(presetId)
|
|
2507
2530
|
]);
|
|
2508
2531
|
return {
|
|
2509
|
-
version:
|
|
2532
|
+
version: 6,
|
|
2510
2533
|
exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2511
2534
|
sourcePresetId: presetId,
|
|
2512
|
-
entries:
|
|
2535
|
+
entries: entries.map((entry) => ({
|
|
2513
2536
|
id: entry.id,
|
|
2514
2537
|
speakerKeys: [...entry.speakerKeys],
|
|
2515
2538
|
type: entry.type,
|
|
@@ -2520,7 +2543,6 @@ var LivingMemoryRepository = class {
|
|
|
2520
2543
|
sentiment: entry.sentiment,
|
|
2521
2544
|
importance: entry.importance,
|
|
2522
2545
|
sourceConversationId: entry.sourceConversationId,
|
|
2523
|
-
sourceLabel: entry.sourceLabel,
|
|
2524
2546
|
sourceOrigins: entry.sourceOrigins,
|
|
2525
2547
|
createdAt: entry.createdAt.toISOString(),
|
|
2526
2548
|
updatedAt: entry.updatedAt.toISOString()
|
|
@@ -2546,7 +2568,8 @@ var LivingMemoryRepository = class {
|
|
|
2546
2568
|
};
|
|
2547
2569
|
}
|
|
2548
2570
|
async importPresetData(targetPresetId, data) {
|
|
2549
|
-
const
|
|
2571
|
+
const sources = await resolveImportedSources(this.ctx, data.entries.map((entry) => entry.sourceConversationId));
|
|
2572
|
+
const rows = this.buildPresetImportRows(targetPresetId, data, sources);
|
|
2550
2573
|
await this.runTransaction(async (database) => {
|
|
2551
2574
|
await runPresetImportBatches("entries", rows.entryRows, async (batch) => {
|
|
2552
2575
|
await database.upsert("living_memory_entry", batch);
|
|
@@ -2596,7 +2619,7 @@ var LivingMemoryRepository = class {
|
|
|
2596
2619
|
presetSpeakers: data.presetSpeakers.length
|
|
2597
2620
|
};
|
|
2598
2621
|
}
|
|
2599
|
-
buildPresetImportRows(targetPresetId, data) {
|
|
2622
|
+
buildPresetImportRows(targetPresetId, data, sources) {
|
|
2600
2623
|
const isCrossPresetImport = targetPresetId !== data.sourcePresetId;
|
|
2601
2624
|
const resolveImportId = (recordType, sourceId) => {
|
|
2602
2625
|
if (isCrossPresetImport) return createPresetImportId(recordType, targetPresetId, sourceId);
|
|
@@ -2605,7 +2628,7 @@ var LivingMemoryRepository = class {
|
|
|
2605
2628
|
const resolveEntryImportId = (sourceId) => {
|
|
2606
2629
|
return resolveImportId("entry", sourceId);
|
|
2607
2630
|
};
|
|
2608
|
-
const createEntryRow = (entry, speakerKeys
|
|
2631
|
+
const createEntryRow = (entry, speakerKeys) => {
|
|
2609
2632
|
return {
|
|
2610
2633
|
id: resolveEntryImportId(entry.id),
|
|
2611
2634
|
presetId: targetPresetId,
|
|
@@ -2617,17 +2640,13 @@ var LivingMemoryRepository = class {
|
|
|
2617
2640
|
summary: entry.summary,
|
|
2618
2641
|
sentiment: entry.sentiment,
|
|
2619
2642
|
importance: entry.importance,
|
|
2620
|
-
sourceConversationId: entry.sourceConversationId,
|
|
2621
|
-
sourceLabel,
|
|
2643
|
+
sourceConversationId: sources.get(entry.sourceConversationId) ?? null,
|
|
2622
2644
|
sourceOrigins: normalizeMemorySourceOrigins(entry.sourceOrigins),
|
|
2623
2645
|
createdAt: new Date(entry.createdAt),
|
|
2624
2646
|
updatedAt: new Date(entry.updatedAt)
|
|
2625
2647
|
};
|
|
2626
2648
|
};
|
|
2627
|
-
|
|
2628
|
-
if (data.version === 1 || data.version === 2) entryRows = data.entries.map((entry) => createEntryRow(entry, [], null));
|
|
2629
|
-
else if (data.version === 3) entryRows = data.entries.map((entry) => createEntryRow(entry, entry.speakerKeys, null));
|
|
2630
|
-
else entryRows = data.entries.map((entry) => createEntryRow(entry, entry.speakerKeys, entry.sourceLabel));
|
|
2649
|
+
const entryRows = data.version === 1 || data.version === 2 ? data.entries.map((entry) => createEntryRow(entry, [])) : data.entries.map((entry) => createEntryRow(entry, entry.speakerKeys));
|
|
2631
2650
|
const speakerKeys = [...new Set(data.userProfiles.map((profile) => profile.speakerKey))];
|
|
2632
2651
|
const userProfileRows = data.userProfiles.map((profile) => ({
|
|
2633
2652
|
id: resolveImportId("user-profile", profile.id),
|
|
@@ -2650,10 +2669,9 @@ var LivingMemoryRepository = class {
|
|
|
2650
2669
|
createdAt: new Date(speaker.createdAt),
|
|
2651
2670
|
updatedAt: new Date(speaker.updatedAt)
|
|
2652
2671
|
}));
|
|
2653
|
-
const entrySpeakerRows = entryRows.flatMap(createActiveMemorySpeakerRows);
|
|
2654
2672
|
return {
|
|
2655
2673
|
entryRows,
|
|
2656
|
-
entrySpeakerRows,
|
|
2674
|
+
entrySpeakerRows: entryRows.flatMap(createActiveMemorySpeakerRows),
|
|
2657
2675
|
speakerKeys,
|
|
2658
2676
|
userProfileRows,
|
|
2659
2677
|
presetSpeakerRows
|
|
@@ -2676,33 +2694,6 @@ var LivingMemoryRepository = class {
|
|
|
2676
2694
|
].map((record) => record.presetId).filter((presetId) => presetId.length > 0))];
|
|
2677
2695
|
}
|
|
2678
2696
|
};
|
|
2679
|
-
// src/service/memory/helpers.ts
|
|
2680
|
-
/**
|
|
2681
|
-
* 作用域唯一键:presetId 与 conversationId 以换行符拼接。
|
|
2682
|
-
* 提取缓冲、召回锁与说话人标签缓存均以该键隔离数据。
|
|
2683
|
-
*/
|
|
2684
|
-
const scopeKey = (scope) => `${scope.presetId}\n${scope.conversationId}`;
|
|
2685
|
-
function snapshotScopeOf({ presetId, conversationId }, settings) {
|
|
2686
|
-
return {
|
|
2687
|
-
presetId,
|
|
2688
|
-
conversationId: settings.snapshotScope === "preset" && !settings.enableConversationIsolation ? null : conversationId
|
|
2689
|
-
};
|
|
2690
|
-
}
|
|
2691
|
-
/**
|
|
2692
|
-
* 解析面向 LLM 的助手标签:优先使用 preset 展示名(presetLabel),
|
|
2693
|
-
* 缺省或为空白时回退 presetId。
|
|
2694
|
-
*/
|
|
2695
|
-
const resolveScopeAssistantLabel = (scope) => scope.presetLabel?.trim() || scope.presetId;
|
|
2696
|
-
const resolvePresetAssistantLabel = (ctx, presetId) => ctx.presets.get(presetId)?.name.trim() || presetId;
|
|
2697
|
-
/**
|
|
2698
|
-
* 取预设 system 部分的未渲染原文,作为人设卡片的删减来源。不经模板渲染器、
|
|
2699
|
-
* 不取任何变量值:system 部分应为固定人设,写入其中的占位符原样保留。
|
|
2700
|
-
*/
|
|
2701
|
-
const resolvePresetPrompt = async (ctx, presetId) => {
|
|
2702
|
-
const record = ctx.presets.get(presetId);
|
|
2703
|
-
if (record === void 0) throw new Error(`preset not found: ${presetId}`);
|
|
2704
|
-
return (ctx.presets.blocks(record) ?? []).filter((block) => block.zone === "system" && (block.role === void 0 || block.role === "system") && typeof block.content === "string").sort((left, right) => (left.order ?? 0) - (right.order ?? 0)).map((block) => block.content.trim()).filter((content) => content.length > 0).join("\n\n").trim();
|
|
2705
|
-
};
|
|
2706
2697
|
// src/service/transcript/element_text.ts
|
|
2707
2698
|
/**
|
|
2708
2699
|
* 将聊天内容转为模型可读文本,使用占位说明表示非文本内容。
|
|
@@ -2825,6 +2816,7 @@ const formatLivingMemoryMessageTime = (date) => {
|
|
|
2825
2816
|
return `${`${date.getFullYear()}-${padDatePart(date.getMonth() + 1)}-${padDatePart(date.getDate())}`} ${`${padDatePart(date.getHours())}:${padDatePart(date.getMinutes())}`}`;
|
|
2826
2817
|
};
|
|
2827
2818
|
// src/service/chat_history.ts
|
|
2819
|
+
const historyPageSize = 32;
|
|
2828
2820
|
/** 只给宿主缓冲对象标记消费位置与回复归属,不持有聊天正文。 */
|
|
2829
2821
|
var LivingMemoryChatHistory = class {
|
|
2830
2822
|
observer;
|
|
@@ -2835,93 +2827,128 @@ var LivingMemoryChatHistory = class {
|
|
|
2835
2827
|
this.observer = observer;
|
|
2836
2828
|
}
|
|
2837
2829
|
scopeOf(conversationId, sessionId, presetId) {
|
|
2838
|
-
const
|
|
2839
|
-
return {
|
|
2830
|
+
const scope = {
|
|
2840
2831
|
conversationId,
|
|
2841
2832
|
sessionId,
|
|
2842
|
-
presetId
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
|
|
2833
|
+
presetId
|
|
2834
|
+
};
|
|
2835
|
+
if (isCustomConversation(conversationId)) return scope;
|
|
2836
|
+
const identity = this.observer.identityOfConversation(conversationId);
|
|
2837
|
+
if (!identity) return scope;
|
|
2838
|
+
const { platform, isDirect, guildId, channelId, userId } = identity;
|
|
2839
|
+
return {
|
|
2840
|
+
...scope,
|
|
2841
|
+
platform,
|
|
2842
|
+
isDirect,
|
|
2843
|
+
guildId,
|
|
2844
|
+
channelId,
|
|
2845
|
+
userId
|
|
2850
2846
|
};
|
|
2851
2847
|
}
|
|
2852
|
-
/**
|
|
2853
|
-
*newest(
|
|
2848
|
+
/** 每次只拉取查询所需的后缀。跨频道时按消费位置合并同样大小的窗口。 */
|
|
2849
|
+
*newest(readers) {
|
|
2850
|
+
if (readers.length === 0) return;
|
|
2854
2851
|
let seen = 0;
|
|
2855
|
-
for (let limit =
|
|
2856
|
-
const rows =
|
|
2852
|
+
for (let limit = historyPageSize;; limit *= 2) {
|
|
2853
|
+
const rows = readers.length === 1 ? readers[0](limit) : readers.flatMap((read) => read(limit)).sort((a, b) => this.positions.get(a) - this.positions.get(b)).slice(-limit);
|
|
2857
2854
|
for (let i = rows.length - seen - 1; i >= 0; i--) yield rows[i];
|
|
2858
2855
|
if (rows.length < limit) return;
|
|
2859
2856
|
seen = rows.length;
|
|
2860
2857
|
}
|
|
2861
2858
|
}
|
|
2862
|
-
|
|
2859
|
+
*positioned(key, routeId) {
|
|
2860
|
+
const sources = isCustomConversation(key) ? this.observer.channelStats().filter((channel) => channel.conversationKey === key).map((channel) => ({
|
|
2861
|
+
route: channel.routeId,
|
|
2862
|
+
read: (limit) => this.observer.recent(channel.cid, { limit })
|
|
2863
|
+
})) : [{
|
|
2864
|
+
route: void 0,
|
|
2865
|
+
read: (limit) => this.observer.recentOfConversation(key, limit)
|
|
2866
|
+
}];
|
|
2863
2867
|
const added = [];
|
|
2864
|
-
|
|
2865
|
-
for (const
|
|
2866
|
-
const
|
|
2867
|
-
|
|
2868
|
-
|
|
2869
|
-
|
|
2868
|
+
const selected = [];
|
|
2869
|
+
for (const { read, route } of sources) {
|
|
2870
|
+
const tail = read(historyPageSize);
|
|
2871
|
+
const readPage = (limit) => limit === historyPageSize ? tail : read(limit);
|
|
2872
|
+
if (!routeId || !route || route === routeId) selected.push(readPage);
|
|
2873
|
+
let time = Infinity;
|
|
2874
|
+
for (const row of this.newest([readPage])) {
|
|
2875
|
+
if (this.positions.has(row)) break;
|
|
2876
|
+
time = Math.min(time, row.time);
|
|
2877
|
+
added.push({
|
|
2878
|
+
row,
|
|
2879
|
+
time
|
|
2880
|
+
});
|
|
2870
2881
|
}
|
|
2871
|
-
added.push(row);
|
|
2872
|
-
}
|
|
2873
|
-
for (let i = added.length - 1; i >= 0; i--) {
|
|
2874
|
-
last = this.nextPosition++;
|
|
2875
|
-
this.positions.set(added[i], last);
|
|
2876
2882
|
}
|
|
2877
|
-
|
|
2883
|
+
added.reverse();
|
|
2884
|
+
if (sources.length > 1) added.sort((a, b) => a.time - b.time);
|
|
2885
|
+
for (const { row } of added) this.positions.set(row, this.nextPosition++);
|
|
2886
|
+
yield* this.newest(selected);
|
|
2887
|
+
}
|
|
2888
|
+
lastPosition(key) {
|
|
2889
|
+
const last = this.positioned(key).next();
|
|
2890
|
+
return last.done ? -1 : this.positions.get(last.value);
|
|
2878
2891
|
}
|
|
2879
2892
|
async head(scope) {
|
|
2880
2893
|
return this.lastPosition(scope.conversationId);
|
|
2881
2894
|
}
|
|
2882
2895
|
/** observed 通知与读取结果可以是两个对象,以框架消息 ID 对应缓冲记录。 */
|
|
2883
2896
|
locate(key, message, replyScope) {
|
|
2884
|
-
this.
|
|
2885
|
-
for (const row of this.newest(key)) {
|
|
2897
|
+
for (const row of this.positioned(key, message.routeId)) {
|
|
2886
2898
|
if (row.id !== message.id) continue;
|
|
2887
2899
|
if (replyScope !== void 0) this.replies.set(row, replyScope);
|
|
2888
2900
|
return this.positions.get(row);
|
|
2889
2901
|
}
|
|
2890
2902
|
}
|
|
2891
|
-
async after(scope, position, before = Infinity) {
|
|
2892
|
-
this.lastPosition(scope.conversationId);
|
|
2903
|
+
async after(scope, position, before = Infinity, routeId) {
|
|
2893
2904
|
const entries = [];
|
|
2894
|
-
for (const row of this.
|
|
2905
|
+
for (const row of this.positioned(scope.conversationId, routeId)) {
|
|
2895
2906
|
const at = this.positions.get(row);
|
|
2896
2907
|
if (at <= position) break;
|
|
2908
|
+
if (routeId !== void 0 && row.routeId !== routeId) continue;
|
|
2897
2909
|
if (at >= before || row.backfilled || row.self && this.replies.get(row) !== scope) continue;
|
|
2898
2910
|
const entry = this.entry(row);
|
|
2899
2911
|
if (entry !== void 0) entries.push(entry);
|
|
2900
2912
|
}
|
|
2901
2913
|
return entries.reverse();
|
|
2902
2914
|
}
|
|
2903
|
-
recent(scope, count, through, after = -1) {
|
|
2915
|
+
recent(scope, count, through, after = -1, routeId) {
|
|
2904
2916
|
if (count <= 0) return [];
|
|
2905
|
-
this.lastPosition(scope.conversationId);
|
|
2906
2917
|
const entries = [];
|
|
2907
|
-
for (const row of this.
|
|
2918
|
+
for (const row of this.positioned(scope.conversationId, routeId)) {
|
|
2908
2919
|
const position = this.positions.get(row);
|
|
2909
2920
|
if (position <= after) break;
|
|
2910
|
-
if (position > through) continue;
|
|
2921
|
+
if (position > through || routeId !== void 0 && row.routeId !== routeId) continue;
|
|
2911
2922
|
const entry = this.entry(row);
|
|
2912
2923
|
if (entry !== void 0) entries.push(entry);
|
|
2913
2924
|
if (entries.length === count) break;
|
|
2914
2925
|
}
|
|
2915
2926
|
return entries.reverse();
|
|
2916
2927
|
}
|
|
2917
|
-
|
|
2918
|
-
|
|
2919
|
-
|
|
2920
|
-
|
|
2928
|
+
locateUser(key, message, after = -1) {
|
|
2929
|
+
let candidate;
|
|
2930
|
+
let ambiguous = false;
|
|
2931
|
+
for (const row of this.positioned(key, message.routeId)) {
|
|
2921
2932
|
const position = this.positions.get(row);
|
|
2922
|
-
if (position
|
|
2923
|
-
|
|
2933
|
+
if (position <= after) break;
|
|
2934
|
+
if (row.self || row.backfilled) continue;
|
|
2935
|
+
if (row.id === message.id) return {
|
|
2936
|
+
position,
|
|
2937
|
+
routeId: row.routeId
|
|
2938
|
+
};
|
|
2939
|
+
if (!message.externalId || row.platformMessageId !== message.externalId) continue;
|
|
2940
|
+
if (message.routeId && row.routeId !== message.routeId) continue;
|
|
2941
|
+
if (message.routeId || !isCustomConversation(key)) return {
|
|
2942
|
+
position,
|
|
2943
|
+
routeId: row.routeId
|
|
2944
|
+
};
|
|
2945
|
+
if (candidate) ambiguous = true;
|
|
2946
|
+
candidate = row;
|
|
2924
2947
|
}
|
|
2948
|
+
if (candidate && !ambiguous) return {
|
|
2949
|
+
position: this.positions.get(candidate),
|
|
2950
|
+
routeId: candidate.routeId
|
|
2951
|
+
};
|
|
2925
2952
|
}
|
|
2926
2953
|
entry(row) {
|
|
2927
2954
|
if (row.self && !this.replies.has(row)) return;
|
|
@@ -3918,7 +3945,7 @@ var LivingMemoryVectorIndexWorkerClient = class {
|
|
|
3918
3945
|
try {
|
|
3919
3946
|
await this.sendRequest({ type: "dispose" });
|
|
3920
3947
|
} catch (error) {
|
|
3921
|
-
disposeError = toError
|
|
3948
|
+
disposeError = toError(error);
|
|
3922
3949
|
await this.worker.terminate();
|
|
3923
3950
|
}
|
|
3924
3951
|
const exitCode = await this.exitPromise;
|
|
@@ -3944,7 +3971,7 @@ var LivingMemoryVectorIndexWorkerClient = class {
|
|
|
3944
3971
|
}, commandTransferList(command));
|
|
3945
3972
|
} catch (error) {
|
|
3946
3973
|
this.pending.delete(id);
|
|
3947
|
-
reject(toError
|
|
3974
|
+
reject(toError(error));
|
|
3948
3975
|
}
|
|
3949
3976
|
});
|
|
3950
3977
|
}
|
|
@@ -4053,7 +4080,7 @@ var LivingMemoryVectorIndexService = class {
|
|
|
4053
4080
|
try {
|
|
4054
4081
|
this.generation = await acquireVectorIndexGeneration(generationKey);
|
|
4055
4082
|
} catch (error) {
|
|
4056
|
-
const failure = toError
|
|
4083
|
+
const failure = toError(error);
|
|
4057
4084
|
this.status.markUnavailable(failure.message);
|
|
4058
4085
|
this.logger.summary("向量索引启动失败", "状态:暂停检索", "error", failure);
|
|
4059
4086
|
throw error;
|
|
@@ -4075,7 +4102,7 @@ var LivingMemoryVectorIndexService = class {
|
|
|
4075
4102
|
}
|
|
4076
4103
|
});
|
|
4077
4104
|
} catch (error) {
|
|
4078
|
-
const failure = toError
|
|
4105
|
+
const failure = toError(error);
|
|
4079
4106
|
this.status.markUnavailable(failure.message);
|
|
4080
4107
|
this.logger.summary("向量索引启动失败", "状态:暂停检索", "error", failure);
|
|
4081
4108
|
try {
|
|
@@ -4267,7 +4294,7 @@ var LivingMemoryVectorIndexService = class {
|
|
|
4267
4294
|
return this.embeddingContext;
|
|
4268
4295
|
}
|
|
4269
4296
|
async markMutationFailed(presetId, indexedCount, error) {
|
|
4270
|
-
const failure = toError
|
|
4297
|
+
const failure = toError(error);
|
|
4271
4298
|
const expectedCount = await this.repository.countEntriesByPreset(presetId);
|
|
4272
4299
|
if (this.worker !== null && this.workerFailure === null) {
|
|
4273
4300
|
await this.worker.markPresetState({
|
|
@@ -4349,7 +4376,7 @@ var LivingMemoryVectorIndexService = class {
|
|
|
4349
4376
|
this.assertPresetReady(presetId);
|
|
4350
4377
|
}
|
|
4351
4378
|
async handleMaintenanceFailure(error) {
|
|
4352
|
-
const failure = toError
|
|
4379
|
+
const failure = toError(error);
|
|
4353
4380
|
let state = "unavailable";
|
|
4354
4381
|
if (this.workerFailure === null && error instanceof LivingMemoryVectorIndexError) state = error.state;
|
|
4355
4382
|
await this.inspectAfterFailure();
|
|
@@ -4577,10 +4604,63 @@ const buildSnapshotRecallPrompts = (params) => {
|
|
|
4577
4604
|
const modelStageLabels = {
|
|
4578
4605
|
recall: "召回",
|
|
4579
4606
|
dream: "Dream",
|
|
4607
|
+
"dream-compression": "Dream 上下文压缩",
|
|
4580
4608
|
"memory-extraction": "记忆提取",
|
|
4581
4609
|
"persona-card": "人设卡片",
|
|
4582
4610
|
"user-profile": "人物画像"
|
|
4583
4611
|
};
|
|
4612
|
+
const formatCall = (call) => `${call.toolName}(${formatLogJson(call.input)})`;
|
|
4613
|
+
function formatLogMessage({ role, content }, displayText = (text) => text) {
|
|
4614
|
+
const lines = [];
|
|
4615
|
+
for (const block of content) {
|
|
4616
|
+
if (block.type === "text" && role !== "assistant") lines.push(displayText(block.text));
|
|
4617
|
+
if (block.type === "tool-call") lines.push(formatCall(block));
|
|
4618
|
+
if (block.type === "tool-result" && block.output.type === "text") lines.push(`${block.toolName} 返回:${block.output.value}`);
|
|
4619
|
+
}
|
|
4620
|
+
return lines.join("\n");
|
|
4621
|
+
}
|
|
4622
|
+
function modelCallLogging(logger, stage, step, displayText = (text) => text) {
|
|
4623
|
+
const label = modelStageLabels[stage];
|
|
4624
|
+
const beforeDispatch = (params, resolved) => {
|
|
4625
|
+
logger.diagnosticSummary((fields) => {
|
|
4626
|
+
const blocks = [];
|
|
4627
|
+
const system = displayText(params.system ?? "");
|
|
4628
|
+
if (system) blocks.push({
|
|
4629
|
+
title: "系统提示词",
|
|
4630
|
+
value: system
|
|
4631
|
+
});
|
|
4632
|
+
for (const [index, message] of params.messages.entries()) {
|
|
4633
|
+
const value = formatLogMessage(message, displayText);
|
|
4634
|
+
if (value) blocks.push({
|
|
4635
|
+
title: `消息 ${index + 1} · ${message.role}`,
|
|
4636
|
+
value
|
|
4637
|
+
});
|
|
4638
|
+
}
|
|
4639
|
+
return {
|
|
4640
|
+
event: `${label}模型调用`,
|
|
4641
|
+
detail: `${formatLogScope(fields)}; 模型:${resolved.provider}:${resolved.model}; 调用序号:${step}`,
|
|
4642
|
+
blocks
|
|
4643
|
+
};
|
|
4644
|
+
});
|
|
4645
|
+
};
|
|
4646
|
+
function response(result) {
|
|
4647
|
+
logger.diagnosticSummary((fields) => {
|
|
4648
|
+
const output = stage === "dream-compression" ? result.text : result.toolCalls.map(formatCall).join("\n");
|
|
4649
|
+
return {
|
|
4650
|
+
event: `${label}模型响应`,
|
|
4651
|
+
detail: `${formatLogScope(fields)}; 调用序号:${step}; 结束原因:${result.finish.kind}`,
|
|
4652
|
+
blocks: output ? [{
|
|
4653
|
+
title: "模型输出",
|
|
4654
|
+
value: output
|
|
4655
|
+
}] : []
|
|
4656
|
+
};
|
|
4657
|
+
});
|
|
4658
|
+
}
|
|
4659
|
+
return {
|
|
4660
|
+
beforeDispatch,
|
|
4661
|
+
response
|
|
4662
|
+
};
|
|
4663
|
+
}
|
|
4584
4664
|
// src/service/workflows/tool_call.ts
|
|
4585
4665
|
const unknownToolMessage = (name) => `未知工具:${name}`;
|
|
4586
4666
|
const invalidToolArgsMessage = (name, reason) => `工具 ${name} 的参数不合法:${reason}。请修正参数后重新提交。`;
|
|
@@ -4641,11 +4721,10 @@ var LivingMemoryToolLoop = class {
|
|
|
4641
4721
|
toolsByName;
|
|
4642
4722
|
constructor(options) {
|
|
4643
4723
|
this.options = options;
|
|
4644
|
-
this.history = options.history
|
|
4645
|
-
if (options.history === void 0) this.history.messages.push({
|
|
4724
|
+
this.history = "history" in options ? options.history : { messages: [{
|
|
4646
4725
|
role: "user",
|
|
4647
4726
|
content: textBlocks(options.input)
|
|
4648
|
-
}
|
|
4727
|
+
}] };
|
|
4649
4728
|
this.specs = options.tools.map((tool) => ({
|
|
4650
4729
|
name: tool.name,
|
|
4651
4730
|
description: tool.description,
|
|
@@ -4662,13 +4741,10 @@ var LivingMemoryToolLoop = class {
|
|
|
4662
4741
|
async runRound(step) {
|
|
4663
4742
|
const { signal, prepareMessages, onModelCall } = this.options;
|
|
4664
4743
|
signal?.throwIfAborted();
|
|
4665
|
-
const messages = await prepareMessages
|
|
4744
|
+
const messages = prepareMessages ? await prepareMessages() : this.history.messages;
|
|
4666
4745
|
const fold = await this.callModel(messages, step);
|
|
4667
4746
|
signal?.throwIfAborted();
|
|
4668
|
-
onModelCall?.(
|
|
4669
|
-
fold,
|
|
4670
|
-
step
|
|
4671
|
-
});
|
|
4747
|
+
onModelCall?.(fold);
|
|
4672
4748
|
if (fold.toolCalls.length === 0) {
|
|
4673
4749
|
this.history.messages.push({
|
|
4674
4750
|
role: "user",
|
|
@@ -4691,6 +4767,14 @@ var LivingMemoryToolLoop = class {
|
|
|
4691
4767
|
for (const call of fold.toolCalls) {
|
|
4692
4768
|
signal?.throwIfAborted();
|
|
4693
4769
|
const outcome = await runLivingMemoryToolCall(this.toolsByName.get(call.toolName), call);
|
|
4770
|
+
this.options.logger.diagnosticSummary((fields) => ({
|
|
4771
|
+
event: `${modelStageLabels[this.options.stage]}工具结果`,
|
|
4772
|
+
detail: `${formatLogScope(fields)}; 调用序号:${step}; 工具:${call.toolName}`,
|
|
4773
|
+
blocks: [{
|
|
4774
|
+
title: outcome.ok ? "执行成功" : "执行失败",
|
|
4775
|
+
value: outcome.text
|
|
4776
|
+
}]
|
|
4777
|
+
}));
|
|
4694
4778
|
signal?.throwIfAborted();
|
|
4695
4779
|
if (outcome.ok) successfulTools.push(call.toolName);
|
|
4696
4780
|
this.history.messages.push({
|
|
@@ -4710,35 +4794,20 @@ var LivingMemoryToolLoop = class {
|
|
|
4710
4794
|
}
|
|
4711
4795
|
async callModel(messages, step) {
|
|
4712
4796
|
const { ctx, model, logger } = this.options;
|
|
4713
|
-
const
|
|
4714
|
-
logger.diagnosticSummary((fields) => ({
|
|
4715
|
-
event: `${stage}模型调用`,
|
|
4716
|
-
detail: `${formatLogScope(fields)}; 模型:${model}; 调用序号:${step}`
|
|
4717
|
-
}));
|
|
4797
|
+
const log = modelCallLogging(logger, this.options.stage, step);
|
|
4718
4798
|
try {
|
|
4719
4799
|
const fold = await ctx.chatluna.chat({
|
|
4720
4800
|
model,
|
|
4721
4801
|
system: this.options.system,
|
|
4722
4802
|
messages: [...messages],
|
|
4723
|
-
toolSpecs: this.specs
|
|
4724
|
-
|
|
4725
|
-
logger.diagnosticSummary((fields) => {
|
|
4726
|
-
if (fold.toolCalls.length === 0) return void 0;
|
|
4727
|
-
return {
|
|
4728
|
-
event: `${stage}模型响应`,
|
|
4729
|
-
detail: `${formatLogScope(fields)}; 工具调用:${fold.toolCalls.map((call) => call.toolName).join("、")}`,
|
|
4730
|
-
blocks: fold.toolCalls.map((call) => ({
|
|
4731
|
-
title: "工具调用",
|
|
4732
|
-
subtitle: `${call.toolName}:${call.toolCallId}`,
|
|
4733
|
-
key: "args",
|
|
4734
|
-
value: call.input
|
|
4735
|
-
}))
|
|
4736
|
-
};
|
|
4803
|
+
toolSpecs: this.specs,
|
|
4804
|
+
beforeDispatch: log.beforeDispatch
|
|
4737
4805
|
});
|
|
4806
|
+
log.response(fold);
|
|
4738
4807
|
return fold;
|
|
4739
4808
|
} catch (error) {
|
|
4740
4809
|
logger.diagnosticSummary((fields) => ({
|
|
4741
|
-
event: `${stage}模型调用失败`,
|
|
4810
|
+
event: `${modelStageLabels[this.options.stage]}模型调用失败`,
|
|
4742
4811
|
detail: `${formatLogScope(fields)}; 模型:${model}; 调用序号:${step}; 原因:${formatErrorDetails(error)}`
|
|
4743
4812
|
}));
|
|
4744
4813
|
throw error;
|
|
@@ -4818,7 +4887,7 @@ const createRecallTools = (options) => {
|
|
|
4818
4887
|
searchKeywords: input.searchKeywords ?? [],
|
|
4819
4888
|
results
|
|
4820
4889
|
});
|
|
4821
|
-
return results.length === 0 ? noMemoryFoundMessage : renderMemoriesForModel(results
|
|
4890
|
+
return results.length === 0 ? noMemoryFoundMessage : renderMemoriesForModel(results);
|
|
4822
4891
|
}
|
|
4823
4892
|
},
|
|
4824
4893
|
{
|
|
@@ -4931,7 +5000,7 @@ var LivingMemoryRecallCoordinator = class {
|
|
|
4931
5000
|
this.agenticRecall = agenticRecall;
|
|
4932
5001
|
this.logger = logger;
|
|
4933
5002
|
}
|
|
4934
|
-
async queue(settings, scope, chatHistory, currentPosition) {
|
|
5003
|
+
async queue(settings, scope, chatHistory, currentPosition, routeId) {
|
|
4935
5004
|
if (settings.recallIntervalMessages === 0 || !chatHistory.length) return;
|
|
4936
5005
|
if (this.controller.signal.aborted) return;
|
|
4937
5006
|
if (!isModelConfigured(this.subModel)) {
|
|
@@ -4941,14 +5010,15 @@ var LivingMemoryRecallCoordinator = class {
|
|
|
4941
5010
|
}));
|
|
4942
5011
|
return;
|
|
4943
5012
|
}
|
|
4944
|
-
const
|
|
5013
|
+
const sourceId = settings.enableConversationIsolation && isCustomConversation(scope.conversationId) ? memorySourceId(scope.conversationId, routeId) : void 0;
|
|
5014
|
+
const key = scopeKey(scope, sourceId);
|
|
4945
5015
|
let window = this.windows.get(key);
|
|
4946
5016
|
if (!window) {
|
|
4947
5017
|
window = { pending: false };
|
|
4948
5018
|
this.windows.set(key, window);
|
|
4949
5019
|
}
|
|
4950
5020
|
if (window.anchor !== void 0) {
|
|
4951
|
-
const messagesSinceRecall = (await this.messageLog.after(scope, window.anchor, currentPosition + 1)).length;
|
|
5021
|
+
const messagesSinceRecall = (await this.messageLog.after(scope, window.anchor, currentPosition + 1, sourceId)).length;
|
|
4952
5022
|
if (messagesSinceRecall < settings.recallIntervalMessages) {
|
|
4953
5023
|
this.logger.diagnosticSummary(() => ({
|
|
4954
5024
|
event: "跳过记忆召回",
|
|
@@ -4973,7 +5043,7 @@ var LivingMemoryRecallCoordinator = class {
|
|
|
4973
5043
|
const snapshotKey = JSON.stringify([snapshotScope.presetId, snapshotScope.conversationId]);
|
|
4974
5044
|
const task = this.snapshotUpdates.run(snapshotKey, async () => {
|
|
4975
5045
|
if (this.windows.get(key) !== window) return;
|
|
4976
|
-
await this.run(settings, scope, snapshotScope, input, runLogger);
|
|
5046
|
+
await this.run(settings, scope, snapshotScope, input, runLogger, sourceId);
|
|
4977
5047
|
}).catch((error) => {
|
|
4978
5048
|
delete window.anchor;
|
|
4979
5049
|
if (this.controller.signal.aborted) {
|
|
@@ -4996,14 +5066,17 @@ var LivingMemoryRecallCoordinator = class {
|
|
|
4996
5066
|
clearByConversation(conversationId) {
|
|
4997
5067
|
for (const key of this.windows.keys()) if (key.endsWith(`\n${conversationId}`)) this.windows.delete(key);
|
|
4998
5068
|
}
|
|
4999
|
-
async run(settings, scope, snapshotScope, input, logger) {
|
|
5069
|
+
async run(settings, scope, snapshotScope, input, logger, sourceId) {
|
|
5000
5070
|
this.controller.signal.throwIfAborted();
|
|
5001
5071
|
const startedAt = /* @__PURE__ */ new Date();
|
|
5002
5072
|
try {
|
|
5003
5073
|
const snapshot = await this.repository.getLatestSnapshotByScope(snapshotScope);
|
|
5004
5074
|
const snapshotText = renderSnapshotText(snapshot?.items ?? []);
|
|
5005
5075
|
const snapshotLines = snapshotText === "" ? [] : snapshotText.split(/\r?\n/);
|
|
5006
|
-
const updatedSnapshot = await this.agenticRecall.run(settings,
|
|
5076
|
+
const updatedSnapshot = await this.agenticRecall.run(settings, sourceId ? {
|
|
5077
|
+
...scope,
|
|
5078
|
+
conversationId: sourceId
|
|
5079
|
+
} : scope, input, snapshotLines, async (item) => {
|
|
5007
5080
|
this.controller.signal.throwIfAborted();
|
|
5008
5081
|
await this.repository.upsertSnapshot(snapshotScope, JSON.stringify(item.toolCallSummary), [item]);
|
|
5009
5082
|
}, logger, this.controller.signal);
|
|
@@ -5100,62 +5173,112 @@ const buildExtractionPrompts = (params) => {
|
|
|
5100
5173
|
};
|
|
5101
5174
|
// src/service/workflows/structured_output.ts
|
|
5102
5175
|
const structuredOutputMaxModelCalls = 3;
|
|
5176
|
+
function readSubmission({ tool, validateResult, stringifiedArrayField }, calls) {
|
|
5177
|
+
if (calls.length !== 1) return {
|
|
5178
|
+
value: null,
|
|
5179
|
+
parseError: `应调用 ${tool.name} 一次,实际收到 ${calls.length} 个工具调用`
|
|
5180
|
+
};
|
|
5181
|
+
const call = calls[0];
|
|
5182
|
+
if (call.toolName !== tool.name) return {
|
|
5183
|
+
value: null,
|
|
5184
|
+
parseError: `调用了 ${call.toolName},应调用 ${tool.name}`
|
|
5185
|
+
};
|
|
5186
|
+
const parsed = tool.schema.safeParse(call.input);
|
|
5187
|
+
if (parsed.success) {
|
|
5188
|
+
const error = validateResult?.(parsed.data);
|
|
5189
|
+
return error === void 0 ? {
|
|
5190
|
+
value: parsed.data,
|
|
5191
|
+
parseError: null
|
|
5192
|
+
} : {
|
|
5193
|
+
value: null,
|
|
5194
|
+
parseError: error
|
|
5195
|
+
};
|
|
5196
|
+
}
|
|
5197
|
+
if (stringifiedArrayField && isRecord(call.input) && typeof call.input[stringifiedArrayField] === "string") return {
|
|
5198
|
+
value: null,
|
|
5199
|
+
parseError: `参数 ${stringifiedArrayField} 要传数组;空数组用 [],不要写成字符串 "[]"`
|
|
5200
|
+
};
|
|
5201
|
+
const reason = parsed.error instanceof Error ? parsed.error.message : String(parsed.error);
|
|
5202
|
+
return {
|
|
5203
|
+
value: null,
|
|
5204
|
+
parseError: `${tool.name} 参数无效:${reason}`
|
|
5205
|
+
};
|
|
5206
|
+
}
|
|
5103
5207
|
/**
|
|
5104
|
-
*
|
|
5105
|
-
* 模型自身错误原样抛出——只有解析与校验失败才会带着修正提示重试。
|
|
5208
|
+
* 每次只接受一个指定工具提交的结果。提交不合格时将原因反馈给模型;调用错误和取消直接退出。
|
|
5106
5209
|
*/
|
|
5107
5210
|
async function invokeStructuredOutput(options) {
|
|
5108
|
-
const
|
|
5109
|
-
const
|
|
5110
|
-
|
|
5111
|
-
|
|
5112
|
-
|
|
5113
|
-
|
|
5114
|
-
|
|
5211
|
+
const { logging: { logger, stage }, signal, tool } = options;
|
|
5212
|
+
const toolSpecs = [{
|
|
5213
|
+
name: tool.name,
|
|
5214
|
+
description: tool.description,
|
|
5215
|
+
parameters: schemasteryToJsonSchemaNode(tool.schema)
|
|
5216
|
+
}];
|
|
5217
|
+
const input = {
|
|
5218
|
+
role: "user",
|
|
5219
|
+
content: textBlocks(options.inputPrompt)
|
|
5220
|
+
};
|
|
5221
|
+
let messages = [input];
|
|
5222
|
+
for (let attempt = 1;; attempt++) {
|
|
5223
|
+
signal?.throwIfAborted();
|
|
5224
|
+
const log = modelCallLogging(logger, stage, attempt);
|
|
5225
|
+
const run = options.ctx.chatluna.chat({
|
|
5226
|
+
system: options.systemPrompt,
|
|
5227
|
+
messages,
|
|
5228
|
+
toolSpecs,
|
|
5229
|
+
toolChoice: "required",
|
|
5230
|
+
...options.model === void 0 ? {} : { model: options.model },
|
|
5231
|
+
beforeDispatch: log.beforeDispatch
|
|
5232
|
+
});
|
|
5233
|
+
using cancellation = signal && addAbortListener(signal, () => run.abort(signal.reason));
|
|
5234
|
+
let fold;
|
|
5115
5235
|
try {
|
|
5116
|
-
|
|
5117
|
-
|
|
5118
|
-
|
|
5119
|
-
...options.model === void 0 ? {} : { model: options.model },
|
|
5120
|
-
...options.signal === void 0 ? {} : { signal: options.signal }
|
|
5121
|
-
});
|
|
5122
|
-
options.signal?.throwIfAborted();
|
|
5123
|
-
outputs.push(`[attempt ${attempt}]\n${JSON.stringify(value, null, 2)}`);
|
|
5124
|
-
const validationError = options.validateResult?.(value);
|
|
5125
|
-
if (validationError === void 0) return {
|
|
5126
|
-
value,
|
|
5127
|
-
output: outputs.join("\n\n"),
|
|
5128
|
-
parseError: null
|
|
5129
|
-
};
|
|
5130
|
-
lastError = validationError;
|
|
5131
|
-
} catch (error) {
|
|
5132
|
-
options.signal?.throwIfAborted();
|
|
5133
|
-
if (!(error instanceof ProtocolError)) throw error;
|
|
5134
|
-
lastError = formatErrorDetails(error);
|
|
5135
|
-
outputs.push(`[attempt ${attempt}]\n${lastError}`);
|
|
5236
|
+
fold = await run;
|
|
5237
|
+
} finally {
|
|
5238
|
+
signal?.throwIfAborted();
|
|
5136
5239
|
}
|
|
5137
|
-
|
|
5138
|
-
|
|
5240
|
+
if (fold.finish.kind === "error" || fold.finish.kind === "aborted") throw new ModelError(fold.finish.failure);
|
|
5241
|
+
log.response(fold);
|
|
5242
|
+
const submission = readSubmission(options, fold.toolCalls);
|
|
5243
|
+
if (submission.parseError === null) return submission;
|
|
5244
|
+
logger.diagnosticSummary((fields) => ({
|
|
5245
|
+
event: `${modelStageLabels[stage]}结果解析失败`,
|
|
5139
5246
|
detail: [
|
|
5140
5247
|
formatLogScope(fields),
|
|
5141
5248
|
`调用序号:${attempt}`,
|
|
5142
|
-
`原因:${
|
|
5249
|
+
`原因:${submission.parseError}`
|
|
5143
5250
|
].filter(Boolean).join("; ")
|
|
5144
5251
|
}));
|
|
5145
|
-
|
|
5252
|
+
if (attempt === structuredOutputMaxModelCalls) return submission;
|
|
5253
|
+
const correction = `提交失败:${submission.parseError}。请调用 ${tool.name} 一次,通过工具参数提交结果。`;
|
|
5254
|
+
if (fold.toolCalls.length === 0) {
|
|
5255
|
+
messages = [input, {
|
|
5256
|
+
role: "user",
|
|
5257
|
+
content: textBlocks(correction)
|
|
5258
|
+
}];
|
|
5259
|
+
continue;
|
|
5260
|
+
}
|
|
5261
|
+
messages = [
|
|
5262
|
+
input,
|
|
5263
|
+
{
|
|
5264
|
+
role: "assistant",
|
|
5265
|
+
content: fold.content
|
|
5266
|
+
},
|
|
5267
|
+
{
|
|
5268
|
+
role: "tool",
|
|
5269
|
+
content: fold.toolCalls.map((call) => ({
|
|
5270
|
+
type: "tool-result",
|
|
5271
|
+
toolCallId: call.toolCallId,
|
|
5272
|
+
toolName: call.toolName,
|
|
5273
|
+
output: {
|
|
5274
|
+
type: "text",
|
|
5275
|
+
value: correction
|
|
5276
|
+
}
|
|
5277
|
+
}))
|
|
5278
|
+
}
|
|
5279
|
+
];
|
|
5146
5280
|
}
|
|
5147
|
-
return {
|
|
5148
|
-
value: null,
|
|
5149
|
-
output: outputs.join("\n\n"),
|
|
5150
|
-
parseError: lastError
|
|
5151
|
-
};
|
|
5152
5281
|
}
|
|
5153
|
-
const formatCorrection = (error, stringifiedArrayField) => {
|
|
5154
|
-
const instructions = [`结构化结果无效:${error}。`, "必须只输出符合 schema 的 JSON,并完整修正所有字段。"];
|
|
5155
|
-
if (stringifiedArrayField != null) instructions.push(`${stringifiedArrayField} 必须直接传 JSON 数组:正确 {"${stringifiedArrayField}":[]};错误 {"${stringifiedArrayField}":"[]"}。`);
|
|
5156
|
-
instructions.push("不要在 JSON 之外输出解释性文本。");
|
|
5157
|
-
return instructions.join(" ");
|
|
5158
|
-
};
|
|
5159
5282
|
// src/service/workflows/extraction/extractor.ts
|
|
5160
5283
|
var LivingMemoryExtractor = class {
|
|
5161
5284
|
ctx;
|
|
@@ -5168,25 +5291,23 @@ var LivingMemoryExtractor = class {
|
|
|
5168
5291
|
signal?.throwIfAborted();
|
|
5169
5292
|
if (!isModelConfigured(this.mainModel)) return {
|
|
5170
5293
|
extracted: [],
|
|
5171
|
-
prompt: null,
|
|
5172
|
-
output: null,
|
|
5173
5294
|
skippedReason: "model-not-configured",
|
|
5174
5295
|
parseError: null
|
|
5175
5296
|
};
|
|
5176
5297
|
if (!await this.isModelAvailable()) return {
|
|
5177
5298
|
extracted: [],
|
|
5178
|
-
prompt: null,
|
|
5179
|
-
output: null,
|
|
5180
5299
|
skippedReason: "model-unavailable",
|
|
5181
5300
|
parseError: null
|
|
5182
5301
|
};
|
|
5183
|
-
const prompt = this.buildPrompt(input, context);
|
|
5184
5302
|
const result = await invokeStructuredOutput({
|
|
5185
5303
|
ctx: this.ctx,
|
|
5186
5304
|
model: this.mainModel,
|
|
5187
|
-
|
|
5188
|
-
|
|
5189
|
-
|
|
5305
|
+
tool: extractionResultTool,
|
|
5306
|
+
...buildExtractionPrompts({
|
|
5307
|
+
chatHistory: input,
|
|
5308
|
+
assistantLabel: resolveScopeAssistantLabel(context),
|
|
5309
|
+
presetPrompt: context.presetPrompt
|
|
5310
|
+
}),
|
|
5190
5311
|
...signal === void 0 ? {} : { signal },
|
|
5191
5312
|
validateResult: ({ memories }) => {
|
|
5192
5313
|
try {
|
|
@@ -5214,8 +5335,6 @@ var LivingMemoryExtractor = class {
|
|
|
5214
5335
|
speakerKeys: resolveSpeakerKeysByLabels(item.speakerLabels, context.speakers)
|
|
5215
5336
|
};
|
|
5216
5337
|
}) ?? [],
|
|
5217
|
-
prompt,
|
|
5218
|
-
output: result.output,
|
|
5219
5338
|
skippedReason: null,
|
|
5220
5339
|
parseError: result.parseError
|
|
5221
5340
|
};
|
|
@@ -5229,14 +5348,6 @@ var LivingMemoryExtractor = class {
|
|
|
5229
5348
|
throw error;
|
|
5230
5349
|
}
|
|
5231
5350
|
}
|
|
5232
|
-
buildPrompt(input, context) {
|
|
5233
|
-
const assistantLabel = resolveScopeAssistantLabel(context);
|
|
5234
|
-
return buildExtractionPrompts({
|
|
5235
|
-
chatHistory: input,
|
|
5236
|
-
assistantLabel,
|
|
5237
|
-
presetPrompt: context.presetPrompt
|
|
5238
|
-
});
|
|
5239
|
-
}
|
|
5240
5351
|
};
|
|
5241
5352
|
// src/service/workflows/extraction/coordinator.ts
|
|
5242
5353
|
const EXTRACTION_FAIL_STREAK_LIMIT = 3;
|
|
@@ -5368,7 +5479,7 @@ var LivingMemoryExtractionCoordinator = class {
|
|
|
5368
5479
|
async queue(scope, options, initialPosition, eligiblePosition) {
|
|
5369
5480
|
if (options.windowMessages === 0) return;
|
|
5370
5481
|
if (this.controller.signal.aborted) return;
|
|
5371
|
-
const key = scopeKey(scope);
|
|
5482
|
+
const key = scopeKey(scope, options.routeId);
|
|
5372
5483
|
const state = this.stateByScope.get(key) ?? {
|
|
5373
5484
|
scope,
|
|
5374
5485
|
options,
|
|
@@ -5464,9 +5575,9 @@ var LivingMemoryExtractionCoordinator = class {
|
|
|
5464
5575
|
*/
|
|
5465
5576
|
async drainNextChunk(state, scope, options, runLogger, firstChunk) {
|
|
5466
5577
|
if (state.chunk === void 0) {
|
|
5467
|
-
const entries = await this.messageLog.after(scope, state.cursorPosition, state.eligiblePosition + 1);
|
|
5578
|
+
const entries = await this.messageLog.after(scope, state.cursorPosition, state.eligiblePosition + 1, options.routeId);
|
|
5468
5579
|
this.controller.signal.throwIfAborted();
|
|
5469
|
-
if (this.stateByScope.get(scopeKey(scope)) !== state) return false;
|
|
5580
|
+
if (this.stateByScope.get(scopeKey(scope, options.routeId)) !== state) return false;
|
|
5470
5581
|
if ((firstChunk || options.includeOverheard) && entries.length < options.windowMessages) {
|
|
5471
5582
|
runLogger.diagnosticSummary(() => ({
|
|
5472
5583
|
event: "等待记忆提取",
|
|
@@ -5487,8 +5598,8 @@ var LivingMemoryExtractionCoordinator = class {
|
|
|
5487
5598
|
const messages = toHistoryTranscriptMessages(batch.scope, chunk);
|
|
5488
5599
|
try {
|
|
5489
5600
|
if (messages.length > 0) {
|
|
5490
|
-
const
|
|
5491
|
-
if (!await this.run(batch.scope, messages,
|
|
5601
|
+
const header = await batch.options.formatTranscriptHeader(chunk);
|
|
5602
|
+
if (!await this.run(batch.scope, messages, header, batch.options, runLogger)) return false;
|
|
5492
5603
|
} else runLogger.diagnosticSummary(() => ({
|
|
5493
5604
|
event: "跳过记忆提取",
|
|
5494
5605
|
detail: `${formatLogScope(scope)}; 原因:本批消息转写为空`
|
|
@@ -5520,10 +5631,10 @@ var LivingMemoryExtractionCoordinator = class {
|
|
|
5520
5631
|
delete state.chunk;
|
|
5521
5632
|
return true;
|
|
5522
5633
|
}
|
|
5523
|
-
async run(scope, messages,
|
|
5634
|
+
async run(scope, messages, header, options, logger) {
|
|
5524
5635
|
const startedAt = /* @__PURE__ */ new Date();
|
|
5525
5636
|
const payload = this.formatter.toExtractionPayload(messages);
|
|
5526
|
-
const input = `${
|
|
5637
|
+
const input = `${header}\n\n${payload.input}`;
|
|
5527
5638
|
logger.diagnosticSummary(() => ({
|
|
5528
5639
|
event: "开始记忆提取",
|
|
5529
5640
|
detail: `${formatLogScope(scope)}; 本批消息:${payload.sourceOriginMessages.length} 条; 输入内容:${input.length} 字符`
|
|
@@ -5551,7 +5662,10 @@ var LivingMemoryExtractionCoordinator = class {
|
|
|
5551
5662
|
}
|
|
5552
5663
|
const extracted = result.extracted;
|
|
5553
5664
|
if (extracted.length > 0) {
|
|
5554
|
-
const saved = await this.memoryWriter.appendExtractedMemories(
|
|
5665
|
+
const saved = await this.memoryWriter.appendExtractedMemories({
|
|
5666
|
+
...scope,
|
|
5667
|
+
conversationId: memorySourceId(scope.conversationId, options.routeId)
|
|
5668
|
+
}, payload.sourceOriginMessages, extracted, payload.speakers);
|
|
5555
5669
|
for (const warning of saved.warnings) logger.summary("记忆提取索引同步延期", `${formatLogScope(scope)}; 原因:${warning}`, "warn");
|
|
5556
5670
|
this.onExtracted(scope.presetId, saved.memories.map((entry) => entry.id), [...new Set(saved.memories.flatMap((entry) => entry.speakerKeys))], options.enableAutoDream);
|
|
5557
5671
|
}
|
|
@@ -5830,7 +5944,7 @@ var LivingMemoryPresetPersonaService = class {
|
|
|
5830
5944
|
structuredResult = await invokeStructuredOutput({
|
|
5831
5945
|
ctx: this.ctx,
|
|
5832
5946
|
model: this.config.mainModel,
|
|
5833
|
-
|
|
5947
|
+
tool: personaCardResultTool,
|
|
5834
5948
|
...buildPersonaCardPrompts({ lines }),
|
|
5835
5949
|
validateResult: ({ deletedLineNumbers }) => {
|
|
5836
5950
|
const invalid = deletedLineNumbers.filter((lineNumber) => lineNumber >= lines.length);
|
|
@@ -5962,7 +6076,7 @@ const buildUserProfilePrompts = (input) => {
|
|
|
5962
6076
|
...formatXmlBlock("existing_profile", input.group.existingProfile?.content ?? "无"),
|
|
5963
6077
|
"",
|
|
5964
6078
|
memoryCountNotice,
|
|
5965
|
-
...formatXmlBlock("memory_entries", renderMemoriesForModel(input.group.entries
|
|
6079
|
+
...formatXmlBlock("memory_entries", renderMemoriesForModel(input.group.entries)),
|
|
5966
6080
|
"</user_profile_input>"
|
|
5967
6081
|
].join("\n")
|
|
5968
6082
|
};
|
|
@@ -6137,7 +6251,7 @@ var LivingMemoryUserProfileService = class {
|
|
|
6137
6251
|
structuredResult = await invokeStructuredOutput({
|
|
6138
6252
|
ctx: this.ctx,
|
|
6139
6253
|
model: this.config.mainModel,
|
|
6140
|
-
|
|
6254
|
+
tool: userProfileResultTool,
|
|
6141
6255
|
...prompts,
|
|
6142
6256
|
signal,
|
|
6143
6257
|
validateResult: ({ action, content }) => {
|
|
@@ -6728,13 +6842,10 @@ const createDreamSessionTools = ({ presetId, state, speakers, getEntriesByPreset
|
|
|
6728
6842
|
];
|
|
6729
6843
|
};
|
|
6730
6844
|
// src/service/prompts/dream.ts
|
|
6731
|
-
const buildDreamMemoryBatchPrompt = (
|
|
6845
|
+
const buildDreamMemoryBatchPrompt = (entries, speakers) => {
|
|
6732
6846
|
return [
|
|
6733
6847
|
"<dream_input>",
|
|
6734
|
-
...formatXmlBlock("memory_entries",
|
|
6735
|
-
fields: dreamMemoryFields,
|
|
6736
|
-
speakers
|
|
6737
|
-
})),
|
|
6848
|
+
...formatXmlBlock("memory_entries", renderDreamMemories(entries, speakers)),
|
|
6738
6849
|
"</dream_input>"
|
|
6739
6850
|
].join("\n");
|
|
6740
6851
|
};
|
|
@@ -6802,21 +6913,16 @@ var DreamSessionHistory = class {
|
|
|
6802
6913
|
ctx;
|
|
6803
6914
|
model;
|
|
6804
6915
|
logger;
|
|
6805
|
-
|
|
6806
|
-
|
|
6916
|
+
messages = [];
|
|
6917
|
+
systemTokens;
|
|
6918
|
+
batchStart = 0;
|
|
6807
6919
|
inputTokens;
|
|
6808
6920
|
compressions = 0;
|
|
6809
6921
|
constructor(ctx, model, systemPrompt, logger) {
|
|
6810
6922
|
this.ctx = ctx;
|
|
6811
6923
|
this.model = model;
|
|
6812
6924
|
this.logger = logger;
|
|
6813
|
-
this.
|
|
6814
|
-
role: "system",
|
|
6815
|
-
content: textBlocks(systemPrompt)
|
|
6816
|
-
});
|
|
6817
|
-
}
|
|
6818
|
-
get messages() {
|
|
6819
|
-
return this.history.messages;
|
|
6925
|
+
this.systemTokens = estimateMessageTokens({ content: textBlocks(systemPrompt) });
|
|
6820
6926
|
}
|
|
6821
6927
|
/** 记录上一轮模型上报的输入量;缺失或无效时保留上一次有效值。 */
|
|
6822
6928
|
recordUsage(usage) {
|
|
@@ -6845,42 +6951,42 @@ var DreamSessionHistory = class {
|
|
|
6845
6951
|
signal?.throwIfAborted();
|
|
6846
6952
|
if (this.inputTokens !== void 0 && this.inputTokens >= 2e5) await this.summarizeEarlierBatches(this.inputTokens, signal);
|
|
6847
6953
|
signal?.throwIfAborted();
|
|
6848
|
-
const tokens = this.messages.reduce((total, message) => total + estimateMessageTokens(message),
|
|
6954
|
+
const tokens = this.messages.reduce((total, message) => total + estimateMessageTokens(message), this.systemTokens);
|
|
6849
6955
|
if (tokens > maxTokenLimit) throw new Error(`Dream 输入超过模型可用预算:${tokens} tokens。`);
|
|
6850
|
-
return
|
|
6956
|
+
return this.messages;
|
|
6851
6957
|
}
|
|
6852
6958
|
async summarizeEarlierBatches(tokensBefore, signal) {
|
|
6853
|
-
if (this.batchStart
|
|
6854
|
-
const
|
|
6959
|
+
if (this.batchStart === 0) throw new Error("当前 Dream 批次已达到 200k,且没有可压缩的更早批次。");
|
|
6960
|
+
const earlier = this.messages.slice(0, this.batchStart);
|
|
6855
6961
|
const attempt = ++this.compressions;
|
|
6856
6962
|
this.logger.diagnosticSummary((fields) => ({
|
|
6857
6963
|
event: "Dream 上下文压缩开始",
|
|
6858
6964
|
detail: `${formatLogScope(fields)}; 压缩序号:${attempt}; 压缩前输入量:${tokensBefore} tokens`
|
|
6859
6965
|
}));
|
|
6860
|
-
const prompt = buildDreamHistorySummaryPrompts(
|
|
6966
|
+
const prompt = buildDreamHistorySummaryPrompts(JSON.stringify(earlier));
|
|
6861
6967
|
signal?.throwIfAborted();
|
|
6968
|
+
const visibleHistory = () => earlier.map((message) => formatLogMessage(message)).filter(Boolean).join("\n");
|
|
6969
|
+
const log = modelCallLogging(this.logger, "dream-compression", attempt, (text) => text.replace(prompt.inputPrompt, visibleHistory));
|
|
6862
6970
|
const run = this.ctx.chatluna.chat({
|
|
6863
6971
|
model: this.model,
|
|
6864
6972
|
system: prompt.systemPrompt,
|
|
6865
6973
|
messages: [{
|
|
6866
6974
|
role: "user",
|
|
6867
6975
|
content: textBlocks(prompt.inputPrompt)
|
|
6868
|
-
}]
|
|
6976
|
+
}],
|
|
6977
|
+
beforeDispatch: log.beforeDispatch
|
|
6869
6978
|
});
|
|
6870
|
-
|
|
6979
|
+
using cancellation = signal && addAbortListener(signal, () => run.abort(signal.reason));
|
|
6871
6980
|
const fold = await run;
|
|
6981
|
+
log.response(fold);
|
|
6872
6982
|
signal?.throwIfAborted();
|
|
6873
|
-
const summary =
|
|
6983
|
+
const summary = fold.text.trim();
|
|
6874
6984
|
if (!summary) throw new Error("Dream 历史压缩未返回有效摘要。");
|
|
6875
|
-
this.
|
|
6876
|
-
|
|
6877
|
-
|
|
6878
|
-
|
|
6879
|
-
|
|
6880
|
-
},
|
|
6881
|
-
...this.messages.slice(this.batchStart)
|
|
6882
|
-
];
|
|
6883
|
-
this.batchStart = 2;
|
|
6985
|
+
this.messages = [{
|
|
6986
|
+
role: "user",
|
|
6987
|
+
content: textBlocks(formatXmlBlock("dream_history_summary", summary).join("\n"))
|
|
6988
|
+
}, ...this.messages.slice(this.batchStart)];
|
|
6989
|
+
this.batchStart = 1;
|
|
6884
6990
|
this.inputTokens = void 0;
|
|
6885
6991
|
this.logger.diagnosticSummary((fields) => ({
|
|
6886
6992
|
event: "Dream 上下文压缩完成",
|
|
@@ -6900,14 +7006,6 @@ async function runDreamSession(input) {
|
|
|
6900
7006
|
signal?.throwIfAborted();
|
|
6901
7007
|
const systemPrompt = buildDreamSystemPrompt(input.assistantLabel, input.presetPrompt);
|
|
6902
7008
|
const history = new DreamSessionHistory(ctx, model, systemPrompt, logger);
|
|
6903
|
-
logger.diagnosticSummary((fields) => ({
|
|
6904
|
-
event: "Dream 会话开始",
|
|
6905
|
-
detail: formatLogScope(fields),
|
|
6906
|
-
blocks: [{
|
|
6907
|
-
title: "系统消息",
|
|
6908
|
-
value: systemPrompt
|
|
6909
|
-
}]
|
|
6910
|
-
}));
|
|
6911
7009
|
while (advanceDreamBatch(state) !== void 0) {
|
|
6912
7010
|
signal?.throwIfAborted();
|
|
6913
7011
|
let speakers = input.speakers;
|
|
@@ -6930,28 +7028,25 @@ async function runDreamSession(input) {
|
|
|
6930
7028
|
recordDreamSpeakers(state, batch.entries.flatMap((entry) => entry.speakerKeys));
|
|
6931
7029
|
const batchLogger = logger.with({ batch: batch.id });
|
|
6932
7030
|
const batchStartedAt = performance.now();
|
|
6933
|
-
const
|
|
7031
|
+
const entries = await withSourceLabels(ctx, batch.entries);
|
|
7032
|
+
signal?.throwIfAborted();
|
|
7033
|
+
const batchPrompt = buildDreamMemoryBatchPrompt(entries, speakers);
|
|
6934
7034
|
history.startBatch(batchPrompt);
|
|
6935
7035
|
batchLogger.diagnosticSummary((fields) => ({
|
|
6936
7036
|
event: "Dream 批次开始",
|
|
6937
|
-
detail: `${formatLogScope(fields)}; 批次:${batch.id}; 总批次:${state.batches.length}; 记忆:${batch.entries.length}
|
|
6938
|
-
blocks: [{
|
|
6939
|
-
title: "用户消息",
|
|
6940
|
-
value: batchPrompt
|
|
6941
|
-
}]
|
|
7037
|
+
detail: `${formatLogScope(fields)}; 批次:${batch.id}; 总批次:${state.batches.length}; 记忆:${batch.entries.length} 条`
|
|
6942
7038
|
}));
|
|
6943
7039
|
const loop = new LivingMemoryToolLoop({
|
|
6944
7040
|
ctx,
|
|
6945
7041
|
model,
|
|
6946
7042
|
system: systemPrompt,
|
|
6947
|
-
input: batchPrompt,
|
|
6948
7043
|
tools,
|
|
6949
7044
|
logger: batchLogger,
|
|
6950
7045
|
stage: "dream",
|
|
6951
7046
|
multipleToolCalls: "sequential",
|
|
6952
|
-
history
|
|
7047
|
+
history,
|
|
6953
7048
|
prepareMessages: () => history.prepareMessages(maxTokenLimit, signal),
|
|
6954
|
-
onModelCall: (
|
|
7049
|
+
onModelCall: (fold) => history.recordUsage(fold.usage),
|
|
6955
7050
|
...signal === void 0 ? {} : { signal }
|
|
6956
7051
|
});
|
|
6957
7052
|
let ineffectiveRounds = 0;
|
|
@@ -7193,7 +7288,7 @@ var LivingMemoryDreamWorkerClient = class {
|
|
|
7193
7288
|
}, transferList);
|
|
7194
7289
|
} catch (error) {
|
|
7195
7290
|
this.pending.delete(id);
|
|
7196
|
-
reject(toError
|
|
7291
|
+
reject(toError(error));
|
|
7197
7292
|
}
|
|
7198
7293
|
});
|
|
7199
7294
|
}
|
|
@@ -7841,10 +7936,14 @@ const livingMemoryWebUI = (ctx, ui) => {
|
|
|
7841
7936
|
ctx.chatluna_webui.state("livingmemory.status", {
|
|
7842
7937
|
get: async () => ({
|
|
7843
7938
|
...ui.admin.status,
|
|
7844
|
-
presets: await ui.admin.listPresetIds()
|
|
7939
|
+
presets: await ui.admin.listPresetIds(),
|
|
7940
|
+
nativeMemoryActive: ctx.get("memory") !== void 0
|
|
7845
7941
|
}),
|
|
7846
7942
|
refreshOn
|
|
7847
7943
|
});
|
|
7944
|
+
ctx.on("internal/service", (name) => {
|
|
7945
|
+
if (name === "memory") ctx.chatluna_webui.refresh("livingmemory.status");
|
|
7946
|
+
});
|
|
7848
7947
|
ctx.chatluna_webui.action("livingmemory.create", { input: Schema$1.object({
|
|
7849
7948
|
presetId: Schema$1.string().required(),
|
|
7850
7949
|
conversationId: Schema$1.string(),
|
|
@@ -8058,7 +8157,7 @@ function toSnapshotView(snapshot, sources) {
|
|
|
8058
8157
|
return {
|
|
8059
8158
|
id: snapshot.id,
|
|
8060
8159
|
conversationId: snapshot.conversationId,
|
|
8061
|
-
conversationLabel: source ?
|
|
8160
|
+
conversationLabel: source ? formatConversationPeer(source) : null,
|
|
8062
8161
|
content: renderSnapshotText(snapshot.items),
|
|
8063
8162
|
searchTexts: [...searchTexts],
|
|
8064
8163
|
searchKeywords: [...searchKeywords],
|
|
@@ -8066,6 +8165,24 @@ function toSnapshotView(snapshot, sources) {
|
|
|
8066
8165
|
createdAt: snapshot.createdAt.getTime()
|
|
8067
8166
|
};
|
|
8068
8167
|
}
|
|
8168
|
+
// src/service/transcript/header.ts
|
|
8169
|
+
async function formatTranscriptHeader(ctx, entries) {
|
|
8170
|
+
const peers = /* @__PURE__ */ new Map();
|
|
8171
|
+
for (const { source } of entries) {
|
|
8172
|
+
if (!source) return "以下是本次会话的聊天记录:";
|
|
8173
|
+
if (knownName(source.id, source.name) || !peers.has(source.key)) peers.set(source.key, source);
|
|
8174
|
+
}
|
|
8175
|
+
const stored = await ctx.routing.peers.get([...peers.keys()]);
|
|
8176
|
+
const labels = [];
|
|
8177
|
+
for (const peer of peers.values()) {
|
|
8178
|
+
const name = await peerName(ctx, peer, stored.get(peer.key)?.name);
|
|
8179
|
+
labels.push(formatConversationPeer({
|
|
8180
|
+
...peer,
|
|
8181
|
+
name
|
|
8182
|
+
}));
|
|
8183
|
+
}
|
|
8184
|
+
return `以下是来自${labels.join("、")}的聊天记录:`;
|
|
8185
|
+
}
|
|
8069
8186
|
// src/service/conversation_hooks.ts
|
|
8070
8187
|
var LivingMemoryConversationHooks = class {
|
|
8071
8188
|
ctx;
|
|
@@ -8130,9 +8247,9 @@ var LivingMemoryConversationHooks = class {
|
|
|
8130
8247
|
this.revisions.clear();
|
|
8131
8248
|
};
|
|
8132
8249
|
}
|
|
8133
|
-
|
|
8134
|
-
const
|
|
8135
|
-
if (
|
|
8250
|
+
contextForTurn(agent) {
|
|
8251
|
+
const turn = this.turns.get(agent);
|
|
8252
|
+
if (turn && this.isCurrent(turn)) return turn;
|
|
8136
8253
|
}
|
|
8137
8254
|
isCurrent({ state }) {
|
|
8138
8255
|
return this.active && this.conversations.get(state.scope.conversationId) === state;
|
|
@@ -8151,16 +8268,29 @@ var LivingMemoryConversationHooks = class {
|
|
|
8151
8268
|
}
|
|
8152
8269
|
captureWindow(agent, key, trigger, noticePosition) {
|
|
8153
8270
|
const contextStart = this.revisions.get(key)?.contextStart ?? -1;
|
|
8154
|
-
const
|
|
8155
|
-
const
|
|
8271
|
+
const observed = trigger?.kind === "chat" ? this.options.history.locateUser(key, trigger, contextStart) : void 0;
|
|
8272
|
+
const position = observed?.position ?? noticePosition;
|
|
8273
|
+
const routeId = trigger?.kind === "chat" ? observed?.routeId ?? trigger.routeId : agent.options.location?.route;
|
|
8156
8274
|
const noticeSessionId = trigger?.kind === "notice" ? String(agent.session.id) : void 0;
|
|
8157
8275
|
const settings = this.options.settingsOf(key, agent.options.location, routeId, noticeSessionId);
|
|
8276
|
+
const needsHistory = settings.recallIntervalMessages > 0 || settings.enableUserProfileInjection;
|
|
8277
|
+
const custom = isCustomConversation(key);
|
|
8278
|
+
let rows = [];
|
|
8279
|
+
if (needsHistory && position !== void 0) {
|
|
8280
|
+
if (custom && !routeId) this.options.logger.diagnosticSummary(() => ({
|
|
8281
|
+
event: "跳过记忆召回",
|
|
8282
|
+
detail: `会话:${key}; 原因:本次唤醒未指定来源路由,无法确定适用的对话规则`
|
|
8283
|
+
}));
|
|
8284
|
+
else rows = this.options.history.recent({ conversationId: key }, settings.recallHistoryMessages, position, contextStart, custom && settings.enableConversationIsolation ? routeId : void 0);
|
|
8285
|
+
}
|
|
8286
|
+
const presetId = this.agentPreset(agent);
|
|
8158
8287
|
return {
|
|
8159
|
-
rows
|
|
8288
|
+
rows,
|
|
8160
8289
|
settings,
|
|
8161
8290
|
position,
|
|
8162
|
-
presetId
|
|
8163
|
-
contextStart
|
|
8291
|
+
presetId,
|
|
8292
|
+
contextStart,
|
|
8293
|
+
routeId
|
|
8164
8294
|
};
|
|
8165
8295
|
}
|
|
8166
8296
|
agentPreset(agent) {
|
|
@@ -8185,13 +8315,14 @@ var LivingMemoryConversationHooks = class {
|
|
|
8185
8315
|
const scope = this.options.history.scopeOf(key, String(head.sessionId), presetId);
|
|
8186
8316
|
const state = this.stateOf(scope, boundary);
|
|
8187
8317
|
const chatHistory = toHistoryTranscriptMessages(state.scope, window.rows);
|
|
8188
|
-
if (position !== void 0 && settings.recallIntervalMessages > 0) await this.options.recall.queue(settings, state.scope, chatHistory, position);
|
|
8318
|
+
if (position !== void 0 && settings.recallIntervalMessages > 0 && chatHistory.length > 0) await this.options.recall.queue(settings, state.scope, chatHistory, position, window.routeId);
|
|
8189
8319
|
return {
|
|
8190
8320
|
kind: "ready",
|
|
8191
8321
|
input: {
|
|
8192
8322
|
state,
|
|
8193
8323
|
settings,
|
|
8194
|
-
chatHistory
|
|
8324
|
+
chatHistory,
|
|
8325
|
+
routeId: window.routeId
|
|
8195
8326
|
}
|
|
8196
8327
|
};
|
|
8197
8328
|
} catch (error) {
|
|
@@ -8223,7 +8354,6 @@ var LivingMemoryConversationHooks = class {
|
|
|
8223
8354
|
input.state.deliveries.set(turn, {
|
|
8224
8355
|
settings: input.settings,
|
|
8225
8356
|
pendingMessageIds: /* @__PURE__ */ new Set(),
|
|
8226
|
-
lastReplyPosition: -1,
|
|
8227
8357
|
drained: false
|
|
8228
8358
|
});
|
|
8229
8359
|
}
|
|
@@ -8292,7 +8422,7 @@ var LivingMemoryConversationHooks = class {
|
|
|
8292
8422
|
if (!presetId) return;
|
|
8293
8423
|
state = this.stateOf(this.options.history.scopeOf(key, sessionId, presetId), position - 1);
|
|
8294
8424
|
}
|
|
8295
|
-
if (position > state.boundary && settings.extractionIncludeOverheard) await this.queueExtraction(state, settings, position);
|
|
8425
|
+
if (position > state.boundary && settings.extractionIncludeOverheard) await this.queueExtraction(state, settings, position, event.message.routeId);
|
|
8296
8426
|
}
|
|
8297
8427
|
async onObservedReply(event) {
|
|
8298
8428
|
const key = event.conversationKey;
|
|
@@ -8302,8 +8432,11 @@ var LivingMemoryConversationHooks = class {
|
|
|
8302
8432
|
for (const [turn, delivery] of state.deliveries) {
|
|
8303
8433
|
if (!delivery.pendingMessageIds.delete(id)) continue;
|
|
8304
8434
|
const position = this.options.history.locate(key, event.message, state.scope);
|
|
8305
|
-
if (position !== void 0
|
|
8306
|
-
|
|
8435
|
+
if (position !== void 0 && (!delivery.lastReply || position > delivery.lastReply.position)) delivery.lastReply = {
|
|
8436
|
+
position,
|
|
8437
|
+
routeId: event.message.routeId
|
|
8438
|
+
};
|
|
8439
|
+
if (delivery.settings.extractionIncludeOverheard && position !== void 0) await this.queueExtraction(state, delivery.settings, position, event.message.routeId);
|
|
8307
8440
|
await this.finishDeliveryIfReady(state, turn, delivery);
|
|
8308
8441
|
return;
|
|
8309
8442
|
}
|
|
@@ -8324,15 +8457,16 @@ var LivingMemoryConversationHooks = class {
|
|
|
8324
8457
|
async finishDeliveryIfReady(state, turn, delivery) {
|
|
8325
8458
|
if (!delivery.drained || delivery.pendingMessageIds.size > 0) return;
|
|
8326
8459
|
state.deliveries.delete(turn);
|
|
8327
|
-
if (!delivery.settings.extractionIncludeOverheard && delivery.
|
|
8460
|
+
if (!delivery.settings.extractionIncludeOverheard && delivery.lastReply && delivery.lastReply.position > state.boundary) await this.queueExtraction(state, delivery.settings, delivery.lastReply.position, delivery.lastReply.routeId);
|
|
8328
8461
|
}
|
|
8329
|
-
async queueExtraction(state, settings, eligiblePosition) {
|
|
8462
|
+
async queueExtraction(state, settings, eligiblePosition, routeId) {
|
|
8330
8463
|
if (settings.extractionWindowMessages === 0) return;
|
|
8331
8464
|
await this.options.extraction.queue(state.scope, {
|
|
8465
|
+
routeId: isCustomConversation(state.scope.conversationId) ? routeId : void 0,
|
|
8332
8466
|
includeOverheard: settings.extractionIncludeOverheard,
|
|
8333
8467
|
windowMessages: settings.extractionWindowMessages,
|
|
8334
8468
|
enableAutoDream: settings.enableAutoDream,
|
|
8335
|
-
|
|
8469
|
+
formatTranscriptHeader: (entries) => formatTranscriptHeader(this.ctx, entries)
|
|
8336
8470
|
}, state.boundary, eligiblePosition);
|
|
8337
8471
|
}
|
|
8338
8472
|
logScheduleError(conversationId, error) {
|
|
@@ -8357,7 +8491,8 @@ function* turnInputs(message) {
|
|
|
8357
8491
|
};
|
|
8358
8492
|
return;
|
|
8359
8493
|
}
|
|
8360
|
-
if (message.role !== "user" || source.kind !== "user" || form === "snapshot"
|
|
8494
|
+
if (message.role !== "user" || source.kind !== "user" || form === "snapshot") return;
|
|
8495
|
+
if (meta && "backfill" in meta && meta.backfill) return;
|
|
8361
8496
|
const envelopes = message.content.filter((block) => block.type === "envelope");
|
|
8362
8497
|
if (!envelopes.length) {
|
|
8363
8498
|
if (source.routeId !== void 0 || meta?.externalId !== void 0) yield {
|
|
@@ -8378,7 +8513,6 @@ function* turnInputs(message) {
|
|
|
8378
8513
|
kind: "chat",
|
|
8379
8514
|
id,
|
|
8380
8515
|
externalId,
|
|
8381
|
-
routeId: source.routeId,
|
|
8382
8516
|
wake
|
|
8383
8517
|
};
|
|
8384
8518
|
}
|
|
@@ -8492,10 +8626,16 @@ var LivingmemoryService = class extends Service {
|
|
|
8492
8626
|
const tools = registerLivingMemoryTools(this.ctx, this.providers, {
|
|
8493
8627
|
enabled: this.config.enabledMemoryTools,
|
|
8494
8628
|
createToolMaxMemories: this.config.memoryCreateToolMaxMemories,
|
|
8495
|
-
|
|
8496
|
-
const
|
|
8497
|
-
if (
|
|
8498
|
-
|
|
8629
|
+
resolveRoute: (agent, routeId) => {
|
|
8630
|
+
const turn = agent && this.conversationHooks.contextForTurn(agent);
|
|
8631
|
+
if (turn) return {
|
|
8632
|
+
routeId: turn.routeId,
|
|
8633
|
+
isolated: turn.settings.enableConversationIsolation
|
|
8634
|
+
};
|
|
8635
|
+
return {
|
|
8636
|
+
routeId,
|
|
8637
|
+
isolated: routeSettings(this.ctx, agent?.options.conversationKey, agent?.options.location, routeId).enableConversationIsolation
|
|
8638
|
+
};
|
|
8499
8639
|
}
|
|
8500
8640
|
});
|
|
8501
8641
|
return () => {
|
|
@@ -8552,6 +8692,7 @@ var LivingmemoryService = class extends Service {
|
|
|
8552
8692
|
* 先标记上次中断的任务,待工作线程启动后再安排归档清理。
|
|
8553
8693
|
*/
|
|
8554
8694
|
async start() {
|
|
8695
|
+
await migrateLegacySources(this.ctx);
|
|
8555
8696
|
await this.maintenance.recoverInterruptedJobs();
|
|
8556
8697
|
const disposer = this.register();
|
|
8557
8698
|
const stopMaintenance = this.maintenance.schedule();
|
|
@@ -8618,9 +8759,9 @@ const modelField = (description, modality) => modelAddressSchema({
|
|
|
8618
8759
|
* 界面语义与取值范围,避免两处默认值漂移。
|
|
8619
8760
|
*/
|
|
8620
8761
|
const Config = Schema.intersect([
|
|
8621
|
-
Schema.object({ debug: Schema.boolean().label("调试日志").description("
|
|
8762
|
+
Schema.object({ debug: Schema.boolean().label("调试日志").description("记录 LivingMemory 每次调用对话模型时的提示词、消息和模型响应。").default(DEFAULT_CONFIG.debug) }).description("基础配置"),
|
|
8622
8763
|
Schema.object({
|
|
8623
|
-
mainModel: modelField("
|
|
8764
|
+
mainModel: modelField("选择支持工具调用的模型,用于提取记忆、整理记忆、更新人物画像和人设卡。", "chat").label("主模型"),
|
|
8624
8765
|
subModel: modelField("子 LLM 模型,用于召回记忆。", "chat").label("召回模型"),
|
|
8625
8766
|
embeddingModel: modelField("将记忆和查询文本转换为向量,供检索和 Dream 比较语义相似度。", "embed").label("嵌入模型"),
|
|
8626
8767
|
rerankModel: modelField("可选。按候选记忆与查询的相关性重新排列检索结果。", "rerank").label("重排序模型")
|