chatluna-plugin-livingmemory 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +2 -0
  2. package/client/locales/en.yml +1 -2
  3. package/client/locales/zh.yml +1 -2
  4. package/client/page.tsx +13 -14
  5. package/client/preset-actions.tsx +120 -120
  6. package/dist/.vite/manifest.json +1 -1
  7. package/dist/client.css +1 -1
  8. package/dist/client.js +1 -1
  9. package/dist/{page-CQcDlyjD.js → page-kxmLRgbo.js} +2 -2
  10. package/lib/contracts/memory.d.ts +12 -4
  11. package/lib/contracts/memory.d.ts.map +1 -1
  12. package/lib/contracts/webui.d.ts +2 -2
  13. package/lib/contracts/webui.d.ts.map +1 -1
  14. package/lib/contracts/workflows.d.ts +5 -17
  15. package/lib/contracts/workflows.d.ts.map +1 -1
  16. package/lib/index.d.ts.map +1 -1
  17. package/lib/index.js +389 -288
  18. package/lib/index.js.map +1 -1
  19. package/lib/routing.d.ts +2 -0
  20. package/lib/routing.d.ts.map +1 -1
  21. package/lib/service/app/admin_service.d.ts +10 -2
  22. package/lib/service/app/admin_service.d.ts.map +1 -1
  23. package/lib/service/app/mutation_service.d.ts +1 -2
  24. package/lib/service/app/mutation_service.d.ts.map +1 -1
  25. package/lib/service/app/query_projections.d.ts +2 -2
  26. package/lib/service/app/query_projections.d.ts.map +1 -1
  27. package/lib/service/chat_history.d.ts +13 -7
  28. package/lib/service/chat_history.d.ts.map +1 -1
  29. package/lib/service/conversation_hooks.d.ts +25 -14
  30. package/lib/service/conversation_hooks.d.ts.map +1 -1
  31. package/lib/service/memory/conversation_sources.d.ts +20 -0
  32. package/lib/service/memory/conversation_sources.d.ts.map +1 -0
  33. package/lib/service/memory/helpers.d.ts +7 -8
  34. package/lib/service/memory/helpers.d.ts.map +1 -1
  35. package/lib/service/memory/tools/index.d.ts +2 -2
  36. package/lib/service/memory/tools/index.d.ts.map +1 -1
  37. package/lib/service/memory/tools/memory_tools.d.ts +2 -1
  38. package/lib/service/memory/tools/memory_tools.d.ts.map +1 -1
  39. package/lib/service/memory/tools/search_memory_tool.d.ts +2 -2
  40. package/lib/service/memory/tools/search_memory_tool.d.ts.map +1 -1
  41. package/lib/service/memory/tools/tool_runtime.d.ts +13 -1
  42. package/lib/service/memory/tools/tool_runtime.d.ts.map +1 -1
  43. package/lib/service/persistence/entries.d.ts +12 -10
  44. package/lib/service/persistence/entries.d.ts.map +1 -1
  45. package/lib/service/persistence/normalizers.d.ts.map +1 -1
  46. package/lib/service/persistence/repository.d.ts +22 -14
  47. package/lib/service/persistence/repository.d.ts.map +1 -1
  48. package/lib/service/persistence/source_migration.d.ts +6 -0
  49. package/lib/service/persistence/source_migration.d.ts.map +1 -0
  50. package/lib/service/persistence/tables.d.ts +3 -1
  51. package/lib/service/persistence/tables.d.ts.map +1 -1
  52. package/lib/service/prompts/dream.d.ts +2 -2
  53. package/lib/service/prompts/dream.d.ts.map +1 -1
  54. package/lib/service/prompts/memory_entries.d.ts +5 -13
  55. package/lib/service/prompts/memory_entries.d.ts.map +1 -1
  56. package/lib/service/prompts/user_profile.d.ts +2 -3
  57. package/lib/service/prompts/user_profile.d.ts.map +1 -1
  58. package/lib/service/transcript/header.d.ts +4 -0
  59. package/lib/service/transcript/header.d.ts.map +1 -0
  60. package/lib/service/user_profile.d.ts.map +1 -1
  61. package/lib/service/workflows/dream/session/runner.d.ts.map +1 -1
  62. package/lib/service/workflows/extraction/coordinator.d.ts.map +1 -1
  63. package/lib/service/workflows/recall/coordinator.d.ts +2 -2
  64. package/lib/service/workflows/recall/coordinator.d.ts.map +1 -1
  65. package/lib/service.d.ts.map +1 -1
  66. package/package.json +4 -3
  67. package/src/contracts/memory.ts +14 -4
  68. package/src/contracts/webui.ts +2 -2
  69. package/src/contracts/workflows.ts +17 -16
  70. package/lib/service/transcript/origin_context.d.ts +0 -17
  71. package/lib/service/transcript/origin_context.d.ts.map +0 -1
package/lib/index.js CHANGED
@@ -58,7 +58,20 @@ function privateWakeAddress(ctx, sessionId) {
58
58
  isDirect: true
59
59
  };
60
60
  }
61
+ /** 上游的自定义会话键不含地点,可能同时连接多个群或私聊。 */
62
+ const isCustomConversation = (key) => key?.startsWith("custom:") === true;
61
63
  function routeSettings(ctx, key, location, routeId, noticeSessionId) {
64
+ if (isCustomConversation(key)) {
65
+ const route = routeId ?? location?.route;
66
+ const channel = route && ctx.chat_observer.channelStats().find((item) => item.routeId === route);
67
+ const identity = channel && ctx.chat_observer.channelOf(channel.cid)?.identity;
68
+ if (identity) return ctx.routing.resolve(ctx.routing.matchInput({
69
+ ...identity,
70
+ userId: void 0
71
+ }, route)).get("livingmemory");
72
+ const values = ctx.routing.valuesAt({ route }, "livingmemory");
73
+ return ROUTE_SCHEMA.parse(values ?? {});
74
+ }
62
75
  if (key !== void 0 && (!location || location.isDirect && !routeId && !location.route)) {
63
76
  const address = ctx.chat_observer.identityOfConversation(key) ?? privateWakeAddress(ctx, noticeSessionId);
64
77
  if (address && (!routeId || routeId === routeIdOf(address))) {
@@ -380,10 +393,10 @@ var LivingMemoryMutationService = class {
380
393
  return this.repository.listPresetSpeakers(presetId);
381
394
  });
382
395
  }
383
- async appendExtractedMemories(scope, sourceOriginMessages, extracted, sourceLabel, windowSpeakers) {
396
+ async appendExtractedMemories(scope, sourceOriginMessages, extracted, windowSpeakers) {
384
397
  return this.runPresetMutation(scope.presetId, async () => {
385
398
  if (windowSpeakers.length > 0) await this.repository.registerMissingPresetSpeakers(scope.presetId, windowSpeakers);
386
- const records = await this.repository.appendMemories(scope, sourceOriginMessages, extracted, sourceLabel);
399
+ const records = await this.repository.appendMemories(scope, sourceOriginMessages, extracted);
387
400
  return {
388
401
  memories: records,
389
402
  warnings: await this.syncCommittedMemoriesToIndex(scope.presetId, records, [], "提取")
@@ -749,56 +762,39 @@ var LivingMemoryMemoryProviders = class {
749
762
  }
750
763
  };
751
764
  // src/service/prompts/memory_entries.ts
752
- const dreamMemoryFields = [
753
- "id",
754
- "type",
755
- "createdAt",
756
- "updatedAt",
757
- "sentiment",
758
- "importance",
759
- "keywords",
760
- "summary",
761
- "content",
762
- "speakerLabels"
763
- ];
764
- const contextMemoryFields = [
765
- "type",
766
- "updatedAt",
767
- "sentiment",
768
- "sourceLabel",
769
- "content"
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;
765
+ const entrySeparator = "\n\n---\n\n";
766
+ function renderEntry(entry, includeId, details = []) {
767
+ const lines = [`type=${entry.type}`, `updatedAt=${entry.updatedAt.toISOString()}`];
768
+ if (includeId) lines.unshift(`id=${entry.id}`);
769
+ if (entry.sentiment !== null) lines.push(`sentiment=${entry.sentiment}`);
770
+ return [
771
+ ...lines,
772
+ ...details,
773
+ entry.sourceLabel,
774
+ "content:",
775
+ entry.content
776
+ ].join("\n");
777
+ }
778
+ function renderMemoriesForModel(entries, includeIds = false) {
779
+ return entries.map((entry) => renderEntry(entry, includeIds)).join(entrySeparator);
780
+ }
781
+ function renderDreamMemories(entries, speakers) {
782
+ const byKey = new Map(speakers.map((speaker) => [speaker.speakerKey, speaker]));
791
783
  return entries.map((entry) => {
792
- return options.fields.map((field) => formatMemoryField(entry, field, speakers)).filter((line) => line !== null).join("\n");
793
- }).join("\n\n---\n\n");
784
+ const details = [];
785
+ if (entry.importance !== null) details.push(`importance=${entry.importance}`);
786
+ details.push(`keywords=${entry.keywords.join("、")}`);
787
+ if (entry.summary !== null) details.push(`summary=${entry.summary}`);
788
+ const labels = entry.speakerKeys.map((key) => byKey.get(key).speakerLabel);
789
+ return `${renderEntry(entry, true, details)}\nspeakerLabels=${JSON.stringify(labels)}`;
790
+ }).join(entrySeparator);
794
791
  }
795
792
  /**
796
793
  * 来源消息是提取工作流输入与 `<chat_history>` 注入共用的原始格式,
797
794
  * `transcriptLines` 由来源消息序列化时写入并随数据持久化,直接作为模型视图复用。
798
795
  */
799
796
  const renderMemorySourceMessagesForModel = (memory) => {
800
- const header = [`id=${memory.id}`];
801
- if (memory.sourceLabel != null) header.push(`source=${memory.sourceLabel}`);
797
+ const header = [`id=${memory.id}`, memory.sourceLabel];
802
798
  if (memory.sourceOrigins.length === 0) return [...header, "(该记忆没有记录来源消息)"].join("\n");
803
799
  const originCount = memory.sourceOrigins.length;
804
800
  const blocks = memory.sourceOrigins.map((origin, index) => {
@@ -986,8 +982,53 @@ const personaCardResultTool = {
986
982
  description: withParameterDocs(["人设卡片删减工具,当你需要按行删减预设原文内容时使用此工具。"], [["deletedLineNumbers", "要删除的行号列表,编号从 0 开始;保留全部内容时提交空数组。"]]),
987
983
  schema: Schema$1.object({ deletedLineNumbers: Schema$1.array(Schema$1.natural()).required().description("要删除的行号列表,编号从 0 开始;保留全部内容时提交空数组。") })
988
984
  };
985
+ // src/service/memory/helpers.ts
986
+ /** 消费进度按预设、来源路由(自定义会话)和会话区分;重置时按会话整体清除。 */
987
+ const scopeKey = (scope, routeId) => [
988
+ scope.presetId,
989
+ ...routeId ? [routeId] : [],
990
+ scope.conversationId
991
+ ].join("\n");
992
+ /** 宿主自定义会话可以跨地点复用;其它会话键保留个人和分线归属。 */
993
+ function memorySourceId(conversationId, routeId) {
994
+ if (!isCustomConversation(conversationId)) return conversationId;
995
+ if (!routeId) throw new Error("自定义会话缺少本次消息的来源路由。");
996
+ return routeId;
997
+ }
998
+ function snapshotScopeOf({ presetId, conversationId }, settings) {
999
+ return {
1000
+ presetId,
1001
+ conversationId: settings.snapshotScope === "preset" && !settings.enableConversationIsolation ? null : conversationId
1002
+ };
1003
+ }
1004
+ /**
1005
+ * 解析面向 LLM 的助手标签:优先使用 preset 展示名(presetLabel),
1006
+ * 缺省或为空白时回退 presetId。
1007
+ */
1008
+ const resolveScopeAssistantLabel = (scope) => scope.presetLabel?.trim() || scope.presetId;
1009
+ const resolvePresetAssistantLabel = (ctx, presetId) => ctx.presets.get(presetId)?.name.trim() || presetId;
1010
+ /**
1011
+ * 取预设 system 部分的未渲染原文,作为人设卡片的删减来源。不经模板渲染器、
1012
+ * 不取任何变量值:system 部分应为固定人设,写入其中的占位符原样保留。
1013
+ */
1014
+ const resolvePresetPrompt = async (ctx, presetId) => {
1015
+ const record = ctx.presets.get(presetId);
1016
+ if (record === void 0) throw new Error(`preset not found: ${presetId}`);
1017
+ 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();
1018
+ };
989
1019
  // src/service/memory/tools/tool_runtime.ts
990
1020
  const agentOfTool = (agent) => isRecord(agent) && isRecord(agent["options"]) ? agent : void 0;
1021
+ function toolContext(call, resolve) {
1022
+ const agent = agentOfTool(call.agent);
1023
+ const routeId = call.routeId ?? call.location?.route ?? agent?.options.location?.route;
1024
+ return {
1025
+ agent,
1026
+ ...resolve?.(agent, routeId) ?? {
1027
+ isolated: false,
1028
+ routeId
1029
+ }
1030
+ };
1031
+ }
991
1032
  const resolveToolMemoryPresetId = (agent) => {
992
1033
  const presetId = agent?.options.presetId;
993
1034
  if (presetId === void 0 || presetId.trim().length === 0) return {
@@ -1002,7 +1043,7 @@ const resolveToolMemoryPresetId = (agent) => {
1002
1043
  /**
1003
1044
  * 从工具调用的 Agent 读取会话作用域;子代理调用一律拒绝。
1004
1045
  */
1005
- const resolveToolMemoryScope = (agent) => {
1046
+ const resolveToolMemoryScope = (agent, routeId) => {
1006
1047
  const presetIdResolution = resolveToolMemoryPresetId(agent);
1007
1048
  if (presetIdResolution.ok === false) return presetIdResolution;
1008
1049
  if ((agent?.options.permissions?.origin?.length ?? 0) > 0) return {
@@ -1016,7 +1057,7 @@ const resolveToolMemoryScope = (agent) => {
1016
1057
  };
1017
1058
  const location = agent?.options.location;
1018
1059
  const scope = {
1019
- conversationId,
1060
+ conversationId: memorySourceId(conversationId, routeId),
1020
1061
  presetId: presetIdResolution.presetId
1021
1062
  };
1022
1063
  if (location?.platform !== void 0) scope.platform = location.platform;
@@ -1036,7 +1077,7 @@ const describeLivingMemoryToolScopeFailure = (reason) => {
1036
1077
  }
1037
1078
  };
1038
1079
  // src/service/memory/tools/memory_tools.ts
1039
- const createCreateMemoryTool = (creation, maxMemories) => {
1080
+ const createCreateMemoryTool = (creation, maxMemories, resolveRoute) => {
1040
1081
  const doc = memoryCreateTool(maxMemories);
1041
1082
  return defineTool({
1042
1083
  name: doc.name,
@@ -1044,7 +1085,8 @@ const createCreateMemoryTool = (creation, maxMemories) => {
1044
1085
  args: doc.schema,
1045
1086
  traits: { effect: "write" },
1046
1087
  async run(input, call) {
1047
- const resolution = resolveToolMemoryScope(agentOfTool(call.agent));
1088
+ const { agent, routeId } = toolContext(call, resolveRoute);
1089
+ const resolution = resolveToolMemoryScope(agent, routeId);
1048
1090
  if (resolution.ok === false) throw new Error(describeLivingMemoryToolScopeFailure(resolution.reason));
1049
1091
  const createdMemories = [];
1050
1092
  const warnings = [];
@@ -1171,22 +1213,22 @@ const createGetMessagesTool = (sources) => defineTool({
1171
1213
  }
1172
1214
  });
1173
1215
  // src/service/memory/tools/search_memory_tool.ts
1174
- const noMemoryFoundMessage$1 = "没有找到相关记忆。";
1175
1216
  /**
1176
1217
  * 记忆检索工具。检索固定只看活跃记忆;开启会话隔离时把当前会话作为
1177
1218
  * 检索范围,否则在整个预设内检索。
1178
1219
  */
1179
- const createSearchMemoryTool = (searchProvider, includeMemoryIds, isConversationIsolated = () => false) => defineTool({
1220
+ const createSearchMemoryTool = (searchProvider, resolveRoute) => defineTool({
1180
1221
  name: memorySearchTool.name,
1181
1222
  description: memorySearchTool.description,
1182
1223
  args: memorySearchTool.schema,
1183
1224
  traits: { effect: "read" },
1184
1225
  async run(input, call) {
1185
- const agent = agentOfTool(call.agent);
1226
+ const { agent, isolated, routeId } = toolContext(call, resolveRoute);
1186
1227
  let presetId;
1187
1228
  let conversationId;
1188
- if (isConversationIsolated(agent)) {
1189
- const resolution = resolveToolMemoryScope(agent);
1229
+ if (isCustomConversation(agent?.options.conversationKey) && !routeId) throw new Error("自定义会话缺少本次消息的来源路由。");
1230
+ if (isolated) {
1231
+ const resolution = resolveToolMemoryScope(agent, routeId);
1190
1232
  if (resolution.ok === false) throw new Error(describeLivingMemoryToolScopeFailure(resolution.reason));
1191
1233
  presetId = resolution.scope.presetId;
1192
1234
  conversationId = resolution.scope.conversationId;
@@ -1200,13 +1242,9 @@ const createSearchMemoryTool = (searchProvider, includeMemoryIds, isConversation
1200
1242
  memoryTypes: ["all"],
1201
1243
  memoryStatus: "active"
1202
1244
  }, conversationId);
1203
- return formatResults(results, includeMemoryIds);
1245
+ return results.length ? renderMemoriesForModel(results, true) : "没有找到相关记忆。";
1204
1246
  }
1205
1247
  });
1206
- const formatResults = (results, includeMemoryIds) => {
1207
- if (results.length === 0) return noMemoryFoundMessage$1;
1208
- return renderMemoriesForModel(results, { fields: includeMemoryIds ? searchMemoryFields : contextMemoryFields });
1209
- };
1210
1248
  memorySearchTool.name, memoryGetMessagesTool.name, memoryCreateTool(1).name, memoryUpdateTool.name, memoryMergeTool.name, memorySplitTool.name, memoryDeleteTool.name;
1211
1249
  /**
1212
1250
  * 注册记忆工具。只注册配置里启用的工具,未启用时不影响其它能力。
@@ -1215,9 +1253,9 @@ memorySearchTool.name, memoryGetMessagesTool.name, memoryCreateTool(1).name, mem
1215
1253
  const registerLivingMemoryTools = (ctx, providers, options) => {
1216
1254
  const enabled = new Set(options.enabled);
1217
1255
  return [
1218
- createSearchMemoryTool(providers, true, options.isConversationIsolated),
1256
+ createSearchMemoryTool(providers, options.resolveRoute),
1219
1257
  createGetMessagesTool(providers),
1220
- createCreateMemoryTool(providers, options.createToolMaxMemories),
1258
+ createCreateMemoryTool(providers, options.createToolMaxMemories, options.resolveRoute),
1221
1259
  createUpdateMemoryTool(providers),
1222
1260
  createMergeMemoriesTool(providers),
1223
1261
  createSplitMemoryTool(providers),
@@ -1399,8 +1437,8 @@ function defineLivingMemoryTables(ctx) {
1399
1437
  primary: "presetId"
1400
1438
  });
1401
1439
  }
1402
- // src/service/transcript/origin_context.ts
1403
- const formatSource = (peer) => {
1440
+ // src/service/memory/conversation_sources.ts
1441
+ const formatConversationPeer = (peer) => {
1404
1442
  const address = `${peer.kind === "guild" ? "群聊" : "用户"} ID:${peer.id}`;
1405
1443
  return peer.name ? `「${peer.name}」(${address})` : address;
1406
1444
  };
@@ -1413,74 +1451,117 @@ async function peerName(ctx, peer, storedName) {
1413
1451
  const profile = await ctx.routing.peers.profile(peer.key);
1414
1452
  return knownName(peer.id, profile.name);
1415
1453
  }
1416
- function ownsRoute(key, platform, selfId, { kind, id }) {
1417
- if (kind === "user") return routeIdOf({
1418
- platform,
1419
- selfId,
1420
- userId: id,
1421
- isDirect: true
1422
- }) === key;
1423
- const guild = {
1424
- platform,
1425
- selfId,
1426
- userId: "",
1427
- guildId: id,
1428
- isDirect: false
1429
- };
1430
- return routeIdOf(guild) === key || routeIdOf({
1431
- ...guild,
1432
- channelId: id
1433
- }) === key;
1454
+ /** 跨群对话只持久化一个会话头,各消息的实际路由由框架的频道记录提供。 */
1455
+ function observedSourceRoutes(ctx) {
1456
+ const routes = /* @__PURE__ */ new Map();
1457
+ const observer = ctx.get("chat_observer");
1458
+ if (!observer) return routes;
1459
+ for (const { cid, routeId, conversationKey } of observer.channelStats()) {
1460
+ if (!conversationKey.startsWith("custom:")) continue;
1461
+ const identity = observer.channelOf(cid)?.identity;
1462
+ if (!identity) continue;
1463
+ const kind = identity.isDirect ? "user" : "guild";
1464
+ const id = identity.isDirect ? identity.userId : identity.guildId;
1465
+ if (id) routes.set(routeId, `${identity.platform}:${identity.selfId}:${kind}:${id}`);
1466
+ }
1467
+ return routes;
1434
1468
  }
1435
- /** 仅当群/用户本身可生成这条标准路由时才补名称;共享会话记录的是首个联系人。 */
1469
+ /** 标准会话、个人会话和存档都以实际路由开头;自定义会话的首个联系人不能代表整段聊天。 */
1436
1470
  async function resolveConversationSources(ctx, conversationIds) {
1437
1471
  const sources = /* @__PURE__ */ new Map();
1438
- if (conversationIds.length === 0) return sources;
1439
- const rows = await ctx.database.get("chatluna_conversations", { key: [...new Set(conversationIds)] }, ["key", "peer"]);
1440
- const peerKeys = new Set(rows.map((row) => row.peer).filter((key) => key !== null));
1441
- if (peerKeys.size === 0) return sources;
1442
- const peers = await ctx.routing.peers.get([...peerKeys]);
1443
- for (const { key, peer } of rows) {
1444
- if (!peer) continue;
1472
+ const keys = [...new Set(conversationIds.filter((key) => key !== null && /^r-[0-9a-f]{12}(?::|$)/.test(key)))];
1473
+ if (keys.length === 0) return sources;
1474
+ const rows = await ctx.database.get("chatluna_conversations", { key: keys }, ["key", "peer"]);
1475
+ const byRoute = /* @__PURE__ */ new Map();
1476
+ for (const { key, peer } of rows) if (peer) byRoute.set(key, peer);
1477
+ if (byRoute.size < keys.length) {
1478
+ const observed = observedSourceRoutes(ctx);
1479
+ for (const key of keys) {
1480
+ const peer = observed.get(key);
1481
+ if (peer) byRoute.set(key, peer);
1482
+ }
1483
+ }
1484
+ if (!byRoute.size) return sources;
1485
+ const peers = await ctx.routing.peers.get([...new Set(byRoute.values())]);
1486
+ for (const [key, peer] of byRoute) {
1445
1487
  const ref = peers.get(peer);
1446
1488
  if (!ref || ref.kind !== "guild" && ref.kind !== "user") continue;
1447
- const { platform, selfId, kind, id } = ref;
1489
+ const { kind, id } = ref;
1448
1490
  const source = {
1449
1491
  key: ref.key,
1450
1492
  kind,
1451
1493
  id,
1452
1494
  name: ref.name
1453
1495
  };
1454
- if (!ownsRoute(key, platform, selfId, source)) continue;
1455
1496
  source.name = await peerName(ctx, source);
1456
1497
  sources.set(key, source);
1457
1498
  }
1458
1499
  return sources;
1459
1500
  }
1460
- async function resolveTranscriptOrigin(ctx, entries) {
1461
- const peers = /* @__PURE__ */ new Map();
1462
- for (const { source } of entries) {
1463
- if (!source) return {
1464
- header: "以下是本次会话的聊天记录:",
1465
- sourceLabel: null
1501
+ async function withSourceLabels(ctx, entries) {
1502
+ const sources = await resolveConversationSources(ctx, entries.map((entry) => entry.sourceConversationId));
1503
+ return entries.map((entry) => {
1504
+ const source = entry.sourceConversationId ? sources.get(entry.sourceConversationId) : void 0;
1505
+ const sourceLabel = `来源 · ${source?.name ? formatConversationPeer(source) : "unknown"}`;
1506
+ return {
1507
+ ...entry,
1508
+ sourceLabel
1466
1509
  };
1467
- if (knownName(source.id, source.name) || !peers.has(source.key)) peers.set(source.key, source);
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
- };
1510
+ });
1511
+ }
1512
+ // src/service/persistence/source_migration.ts
1513
+ const PEER_ALIAS = /^(?:group|private|[^:]+:(?:guild|user)):.+$/;
1514
+ const LEGACY_KEY = new RegExp(`${PEER_ALIAS.source}|${/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.source}`, "i");
1515
+ const PHYSICAL_ROUTE = /^r-[0-9a-f]{12}$/;
1516
+ const NATIVE_KEY = /^(?:r-[0-9a-f]{12}(?::|$)|custom:)/;
1517
+ /** 有旧群号或用户号时枚举一次普通路由;多个账号或频道匹配同一旧键时归入全局。 */
1518
+ async function resolveImportedSources(ctx, ids) {
1519
+ const wanted = [...new Set(ids.filter((id) => !!id))];
1520
+ const result = /* @__PURE__ */ new Map();
1521
+ if (!wanted.length) return result;
1522
+ const aliases = new Set(wanted.filter((key) => !NATIVE_KEY.test(key) && PEER_ALIAS.test(key)));
1523
+ const exact = { key: wanted };
1524
+ const query = aliases.size ? { $or: [exact, { key: PHYSICAL_ROUTE }] } : exact;
1525
+ const heads = await ctx.database.get("chatluna_conversations", query, ["key", "peer"]);
1526
+ const routes = new Map(observedSourceRoutes(ctx));
1527
+ for (const { key, peer } of heads) if (peer || !routes.has(key)) routes.set(key, peer);
1528
+ if (aliases.size) for (const [route, peer] of routes) {
1529
+ if (!peer || !PHYSICAL_ROUTE.test(route)) continue;
1530
+ const match = /^([^:]+):[^:]+:(guild|user):(.+)$/.exec(peer);
1531
+ if (!match) continue;
1532
+ const [, platform, kind, id] = match;
1533
+ const oldKeys = [`${kind === "guild" ? "group" : "private"}:${id}`, `${platform}:${kind}:${id}`];
1534
+ for (const key of oldKeys) if (aliases.has(key)) result.set(key, result.has(key) ? null : route);
1535
+ }
1536
+ for (const key of wanted) if (routes.has(key)) result.set(key, key);
1537
+ return result;
1538
+ }
1539
+ /** 启动索引对账前更新主库,沿用原有向量,只同步新的会话归属。 */
1540
+ async function migrateLegacySources(ctx) {
1541
+ 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));
1542
+ if (!keys.length) return;
1543
+ const sources = await resolveImportedSources(ctx, keys);
1544
+ await ctx.database.transact(async (db) => {
1545
+ for (const key of keys) {
1546
+ const target = sources.get(key) ?? null;
1547
+ if (key !== target) await db.set("living_memory_entry", { sourceConversationId: key }, { sourceConversationId: target });
1548
+ }
1549
+ });
1483
1550
  }
1551
+ // src/contracts/workflows.ts
1552
+ const dreamEntryFields = [
1553
+ "id",
1554
+ "presetId",
1555
+ "speakerKeys",
1556
+ "type",
1557
+ "content",
1558
+ "keywords",
1559
+ "summary",
1560
+ "sentiment",
1561
+ "importance",
1562
+ "sourceConversationId",
1563
+ "updatedAt"
1564
+ ];
1484
1565
  // src/service/persistence/normalizers.ts
1485
1566
  const normalizeSourceConversationId = (value) => {
1486
1567
  const normalized = value?.trim();
@@ -1493,8 +1574,7 @@ const normalizeEntryRecord = (record) => ({
1493
1574
  summary: normalizeOptionalMemoryText(record.summary),
1494
1575
  sentiment: normalizeOptionalMemoryText(record.sentiment),
1495
1576
  importance: normalizeMemoryImportance(record.importance),
1496
- sourceConversationId: normalizeSourceConversationId(record.sourceConversationId),
1497
- sourceLabel: normalizeOptionalMemoryText(record.sourceLabel)
1577
+ sourceConversationId: normalizeSourceConversationId(record.sourceConversationId)
1498
1578
  });
1499
1579
  const normalizeUserProfileRecord = (record) => ({
1500
1580
  ...record,
@@ -1545,7 +1625,6 @@ const memoryEntryFields = [
1545
1625
  "sentiment",
1546
1626
  "importance",
1547
1627
  "sourceConversationId",
1548
- "sourceLabel",
1549
1628
  "sourceOrigins",
1550
1629
  "createdAt",
1551
1630
  "updatedAt"
@@ -1560,20 +1639,6 @@ const indexSourceFields = [
1560
1639
  "keywords",
1561
1640
  "updatedAt"
1562
1641
  ];
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
1642
  const recallEntryFields = [
1578
1643
  "id",
1579
1644
  "type",
@@ -1583,7 +1648,6 @@ const recallEntryFields = [
1583
1648
  "sentiment",
1584
1649
  "importance",
1585
1650
  "sourceConversationId",
1586
- "sourceLabel",
1587
1651
  "createdAt",
1588
1652
  "updatedAt"
1589
1653
  ];
@@ -1612,8 +1676,8 @@ var LivingMemoryEntryRepository = class {
1612
1676
  "updatedAt"
1613
1677
  ]);
1614
1678
  }
1615
- async listDreamEntriesByPreset(presetId) {
1616
- return await this.database.get("living_memory_entry", {
1679
+ listDreamEntriesByPreset(presetId) {
1680
+ return this.database.get("living_memory_entry", {
1617
1681
  presetId,
1618
1682
  status: "active"
1619
1683
  }, dreamEntryFields);
@@ -1675,12 +1739,11 @@ var LivingMemoryEntryRepository = class {
1675
1739
  id: { $in: ids }
1676
1740
  }, recallEntryFields);
1677
1741
  }
1678
- async appendMemories(scope, sourceOriginMessages, extracted, sourceLabel) {
1742
+ async appendMemories(scope, sourceOriginMessages, extracted) {
1679
1743
  if (extracted.length === 0) return [];
1680
1744
  const now = /* @__PURE__ */ new Date();
1681
1745
  const sourceOrigins = createSourceOriginsFromMessages(sourceOriginMessages);
1682
- const normalizedSourceLabel = normalizeOptionalMemoryText(sourceLabel);
1683
- const records = extracted.map((item) => this.buildMemoryEntry(scope, item, sourceOrigins, normalizedSourceLabel, now, item.speakerKeys));
1746
+ const records = extracted.map((item) => this.buildMemoryEntry(scope, item, sourceOrigins, now, item.speakerKeys));
1684
1747
  await this.transact(async (database) => {
1685
1748
  await database.upsert("living_memory_entry", records);
1686
1749
  await this.replaceActiveMemorySpeakers(database, records);
@@ -1688,14 +1751,14 @@ var LivingMemoryEntryRepository = class {
1688
1751
  return records;
1689
1752
  }
1690
1753
  async createMemory(scope, input, speakerKeys) {
1691
- const record = this.buildMemoryEntry(scope, input, [], null, /* @__PURE__ */ new Date(), speakerKeys ?? resolveScopeSpeakerKeys(scope));
1754
+ const record = this.buildMemoryEntry(scope, input, [], /* @__PURE__ */ new Date(), speakerKeys ?? resolveScopeSpeakerKeys(scope));
1692
1755
  await this.transact(async (database) => {
1693
1756
  await database.create("living_memory_entry", record);
1694
1757
  await this.replaceActiveMemorySpeakers(database, [record]);
1695
1758
  });
1696
1759
  return record;
1697
1760
  }
1698
- buildMemoryEntry(scope, fields, sourceOrigins, sourceLabel, createdAt, speakerKeys) {
1761
+ buildMemoryEntry(scope, fields, sourceOrigins, createdAt, speakerKeys) {
1699
1762
  const content = normalizeMemoryText(fields.content);
1700
1763
  return {
1701
1764
  id: randomUUID(),
@@ -1709,7 +1772,6 @@ var LivingMemoryEntryRepository = class {
1709
1772
  sentiment: normalizeOptionalMemoryText(fields.sentiment),
1710
1773
  importance: normalizeMemoryImportance(fields.importance),
1711
1774
  sourceConversationId: scope.conversationId.trim() || null,
1712
- sourceLabel,
1713
1775
  sourceOrigins,
1714
1776
  createdAt,
1715
1777
  updatedAt: createdAt
@@ -1775,7 +1837,7 @@ var LivingMemoryEntryRepository = class {
1775
1837
  return this.buildMemoryEntry({
1776
1838
  presetId,
1777
1839
  conversationId: source.sourceConversationId ?? ""
1778
- }, memory, source.sourceOrigins, source.sourceLabel, now, memory.speakerKeys);
1840
+ }, memory, source.sourceOrigins, now, memory.speakerKeys);
1779
1841
  });
1780
1842
  await database.upsert("living_memory_entry", records);
1781
1843
  await database.set("living_memory_entry", {
@@ -1813,12 +1875,11 @@ var LivingMemoryEntryRepository = class {
1813
1875
  return entry;
1814
1876
  });
1815
1877
  const sameConversation = sources.every((source) => source.sourceConversationId === sources[0].sourceConversationId);
1816
- const sameLabel = sources.every((source) => source.sourceLabel === sources[0].sourceLabel);
1817
1878
  const now = /* @__PURE__ */ new Date();
1818
1879
  const record = this.buildMemoryEntry({
1819
1880
  presetId,
1820
1881
  conversationId: sameConversation ? sources[0].sourceConversationId ?? "" : ""
1821
- }, memory, mergeMemorySourceOrigins(sources), sameConversation && sameLabel ? sources[0].sourceLabel : null, now, memory.speakerKeys);
1882
+ }, memory, mergeMemorySourceOrigins(sources), now, memory.speakerKeys);
1822
1883
  await database.create("living_memory_entry", record);
1823
1884
  await database.set("living_memory_entry", {
1824
1885
  presetId,
@@ -2331,26 +2392,15 @@ var LivingMemoryRepository = class {
2331
2392
  defineLivingMemoryTables(this.ctx);
2332
2393
  }
2333
2394
  /**
2334
- * 全部事务的唯一入口。单连接数据库无法并发开启事务,因此所有事务共用一条
2395
+ * 运行期仓储事务的入口。单连接数据库无法并发开启事务,因此这些事务共用一条
2335
2396
  * 串行链;这是驱动限制的变通,不是一致性机制本身——一致性来自事务边界,
2336
2397
  * 上层的预设级串行队列不得因此被移除。
2337
2398
  */
2338
2399
  runTransaction(callback) {
2339
2400
  return this.transactions.run(TRANSACTION_QUEUE_KEY, () => this.database.transact(callback));
2340
2401
  }
2341
- async withSourceLabels(entries) {
2342
- const conversationIds = [];
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
- });
2402
+ withSourceLabels(entries) {
2403
+ return withSourceLabels(this.ctx, entries);
2354
2404
  }
2355
2405
  listEntriesByPreset(presetId) {
2356
2406
  return this.entries.listEntriesByPreset(presetId);
@@ -2397,8 +2447,8 @@ var LivingMemoryRepository = class {
2397
2447
  async getSearchEntriesByPresetAndIds(presetId, ids) {
2398
2448
  return this.withSourceLabels(await this.entries.getSearchEntriesByPresetAndIds(presetId, ids));
2399
2449
  }
2400
- appendMemories(scope, sourceOriginMessages, extracted, sourceLabel) {
2401
- return this.entries.appendMemories(scope, sourceOriginMessages, extracted, sourceLabel);
2450
+ appendMemories(scope, sourceOriginMessages, extracted) {
2451
+ return this.entries.appendMemories(scope, sourceOriginMessages, extracted);
2402
2452
  }
2403
2453
  createMemory(scope, input, speakerKeys) {
2404
2454
  return this.entries.createMemory(scope, input, speakerKeys);
@@ -2506,10 +2556,10 @@ var LivingMemoryRepository = class {
2506
2556
  this.userProfiles.listPresetSpeakers(presetId)
2507
2557
  ]);
2508
2558
  return {
2509
- version: 5,
2559
+ version: 6,
2510
2560
  exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
2511
2561
  sourcePresetId: presetId,
2512
- entries: (await this.withSourceLabels(entries)).map((entry) => ({
2562
+ entries: entries.map((entry) => ({
2513
2563
  id: entry.id,
2514
2564
  speakerKeys: [...entry.speakerKeys],
2515
2565
  type: entry.type,
@@ -2520,7 +2570,6 @@ var LivingMemoryRepository = class {
2520
2570
  sentiment: entry.sentiment,
2521
2571
  importance: entry.importance,
2522
2572
  sourceConversationId: entry.sourceConversationId,
2523
- sourceLabel: entry.sourceLabel,
2524
2573
  sourceOrigins: entry.sourceOrigins,
2525
2574
  createdAt: entry.createdAt.toISOString(),
2526
2575
  updatedAt: entry.updatedAt.toISOString()
@@ -2546,7 +2595,8 @@ var LivingMemoryRepository = class {
2546
2595
  };
2547
2596
  }
2548
2597
  async importPresetData(targetPresetId, data) {
2549
- const rows = this.buildPresetImportRows(targetPresetId, data);
2598
+ const sources = await resolveImportedSources(this.ctx, data.entries.map((entry) => entry.sourceConversationId));
2599
+ const rows = this.buildPresetImportRows(targetPresetId, data, sources);
2550
2600
  await this.runTransaction(async (database) => {
2551
2601
  await runPresetImportBatches("entries", rows.entryRows, async (batch) => {
2552
2602
  await database.upsert("living_memory_entry", batch);
@@ -2596,7 +2646,7 @@ var LivingMemoryRepository = class {
2596
2646
  presetSpeakers: data.presetSpeakers.length
2597
2647
  };
2598
2648
  }
2599
- buildPresetImportRows(targetPresetId, data) {
2649
+ buildPresetImportRows(targetPresetId, data, sources) {
2600
2650
  const isCrossPresetImport = targetPresetId !== data.sourcePresetId;
2601
2651
  const resolveImportId = (recordType, sourceId) => {
2602
2652
  if (isCrossPresetImport) return createPresetImportId(recordType, targetPresetId, sourceId);
@@ -2605,7 +2655,7 @@ var LivingMemoryRepository = class {
2605
2655
  const resolveEntryImportId = (sourceId) => {
2606
2656
  return resolveImportId("entry", sourceId);
2607
2657
  };
2608
- const createEntryRow = (entry, speakerKeys, sourceLabel) => {
2658
+ const createEntryRow = (entry, speakerKeys) => {
2609
2659
  return {
2610
2660
  id: resolveEntryImportId(entry.id),
2611
2661
  presetId: targetPresetId,
@@ -2617,17 +2667,13 @@ var LivingMemoryRepository = class {
2617
2667
  summary: entry.summary,
2618
2668
  sentiment: entry.sentiment,
2619
2669
  importance: entry.importance,
2620
- sourceConversationId: entry.sourceConversationId,
2621
- sourceLabel,
2670
+ sourceConversationId: sources.get(entry.sourceConversationId) ?? null,
2622
2671
  sourceOrigins: normalizeMemorySourceOrigins(entry.sourceOrigins),
2623
2672
  createdAt: new Date(entry.createdAt),
2624
2673
  updatedAt: new Date(entry.updatedAt)
2625
2674
  };
2626
2675
  };
2627
- let entryRows;
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));
2676
+ const entryRows = data.version === 1 || data.version === 2 ? data.entries.map((entry) => createEntryRow(entry, [])) : data.entries.map((entry) => createEntryRow(entry, entry.speakerKeys));
2631
2677
  const speakerKeys = [...new Set(data.userProfiles.map((profile) => profile.speakerKey))];
2632
2678
  const userProfileRows = data.userProfiles.map((profile) => ({
2633
2679
  id: resolveImportId("user-profile", profile.id),
@@ -2650,10 +2696,9 @@ var LivingMemoryRepository = class {
2650
2696
  createdAt: new Date(speaker.createdAt),
2651
2697
  updatedAt: new Date(speaker.updatedAt)
2652
2698
  }));
2653
- const entrySpeakerRows = entryRows.flatMap(createActiveMemorySpeakerRows);
2654
2699
  return {
2655
2700
  entryRows,
2656
- entrySpeakerRows,
2701
+ entrySpeakerRows: entryRows.flatMap(createActiveMemorySpeakerRows),
2657
2702
  speakerKeys,
2658
2703
  userProfileRows,
2659
2704
  presetSpeakerRows
@@ -2676,33 +2721,6 @@ var LivingMemoryRepository = class {
2676
2721
  ].map((record) => record.presetId).filter((presetId) => presetId.length > 0))];
2677
2722
  }
2678
2723
  };
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
2724
  // src/service/transcript/element_text.ts
2707
2725
  /**
2708
2726
  * 将聊天内容转为模型可读文本,使用占位说明表示非文本内容。
@@ -2825,6 +2843,7 @@ const formatLivingMemoryMessageTime = (date) => {
2825
2843
  return `${`${date.getFullYear()}-${padDatePart(date.getMonth() + 1)}-${padDatePart(date.getDate())}`} ${`${padDatePart(date.getHours())}:${padDatePart(date.getMinutes())}`}`;
2826
2844
  };
2827
2845
  // src/service/chat_history.ts
2846
+ const historyPageSize = 32;
2828
2847
  /** 只给宿主缓冲对象标记消费位置与回复归属,不持有聊天正文。 */
2829
2848
  var LivingMemoryChatHistory = class {
2830
2849
  observer;
@@ -2835,93 +2854,128 @@ var LivingMemoryChatHistory = class {
2835
2854
  this.observer = observer;
2836
2855
  }
2837
2856
  scopeOf(conversationId, sessionId, presetId) {
2838
- const identity = this.observer.identityOfConversation(conversationId);
2839
- return {
2857
+ const scope = {
2840
2858
  conversationId,
2841
2859
  sessionId,
2842
- presetId,
2843
- ...identity === void 0 ? {} : {
2844
- platform: identity.platform,
2845
- isDirect: identity.isDirect,
2846
- guildId: identity.guildId,
2847
- channelId: identity.channelId,
2848
- userId: identity.userId
2849
- }
2860
+ presetId
2861
+ };
2862
+ if (isCustomConversation(conversationId)) return scope;
2863
+ const identity = this.observer.identityOfConversation(conversationId);
2864
+ if (!identity) return scope;
2865
+ const { platform, isDirect, guildId, channelId, userId } = identity;
2866
+ return {
2867
+ ...scope,
2868
+ platform,
2869
+ isDirect,
2870
+ guildId,
2871
+ channelId,
2872
+ userId
2850
2873
  };
2851
2874
  }
2852
- /** 从尾部按需扩大读取范围;缓冲长度不作为消费进度。 */
2853
- *newest(key) {
2875
+ /** 每次只拉取查询所需的后缀。跨频道时按消费位置合并同样大小的窗口。 */
2876
+ *newest(readers) {
2877
+ if (readers.length === 0) return;
2854
2878
  let seen = 0;
2855
- for (let limit = 32;; limit *= 2) {
2856
- const rows = this.observer.recentOfConversation(key, limit);
2879
+ for (let limit = historyPageSize;; limit *= 2) {
2880
+ 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
2881
  for (let i = rows.length - seen - 1; i >= 0; i--) yield rows[i];
2858
2882
  if (rows.length < limit) return;
2859
2883
  seen = rows.length;
2860
2884
  }
2861
2885
  }
2862
- lastPosition(key) {
2886
+ *positioned(key, routeId) {
2887
+ const sources = isCustomConversation(key) ? this.observer.channelStats().filter((channel) => channel.conversationKey === key).map((channel) => ({
2888
+ route: channel.routeId,
2889
+ read: (limit) => this.observer.recent(channel.cid, { limit })
2890
+ })) : [{
2891
+ route: void 0,
2892
+ read: (limit) => this.observer.recentOfConversation(key, limit)
2893
+ }];
2863
2894
  const added = [];
2864
- let last = -1;
2865
- for (const row of this.newest(key)) {
2866
- const position = this.positions.get(row);
2867
- if (position !== void 0) {
2868
- last = position;
2869
- break;
2895
+ const selected = [];
2896
+ for (const { read, route } of sources) {
2897
+ const tail = read(historyPageSize);
2898
+ const readPage = (limit) => limit === historyPageSize ? tail : read(limit);
2899
+ if (!routeId || !route || route === routeId) selected.push(readPage);
2900
+ let time = Infinity;
2901
+ for (const row of this.newest([readPage])) {
2902
+ if (this.positions.has(row)) break;
2903
+ time = Math.min(time, row.time);
2904
+ added.push({
2905
+ row,
2906
+ time
2907
+ });
2870
2908
  }
2871
- added.push(row);
2872
2909
  }
2873
- for (let i = added.length - 1; i >= 0; i--) {
2874
- last = this.nextPosition++;
2875
- this.positions.set(added[i], last);
2876
- }
2877
- return last;
2910
+ added.reverse();
2911
+ if (sources.length > 1) added.sort((a, b) => a.time - b.time);
2912
+ for (const { row } of added) this.positions.set(row, this.nextPosition++);
2913
+ yield* this.newest(selected);
2914
+ }
2915
+ lastPosition(key) {
2916
+ const last = this.positioned(key).next();
2917
+ return last.done ? -1 : this.positions.get(last.value);
2878
2918
  }
2879
2919
  async head(scope) {
2880
2920
  return this.lastPosition(scope.conversationId);
2881
2921
  }
2882
2922
  /** observed 通知与读取结果可以是两个对象,以框架消息 ID 对应缓冲记录。 */
2883
2923
  locate(key, message, replyScope) {
2884
- this.lastPosition(key);
2885
- for (const row of this.newest(key)) {
2924
+ for (const row of this.positioned(key, message.routeId)) {
2886
2925
  if (row.id !== message.id) continue;
2887
2926
  if (replyScope !== void 0) this.replies.set(row, replyScope);
2888
2927
  return this.positions.get(row);
2889
2928
  }
2890
2929
  }
2891
- async after(scope, position, before = Infinity) {
2892
- this.lastPosition(scope.conversationId);
2930
+ async after(scope, position, before = Infinity, routeId) {
2893
2931
  const entries = [];
2894
- for (const row of this.newest(scope.conversationId)) {
2932
+ for (const row of this.positioned(scope.conversationId, routeId)) {
2895
2933
  const at = this.positions.get(row);
2896
2934
  if (at <= position) break;
2935
+ if (routeId !== void 0 && row.routeId !== routeId) continue;
2897
2936
  if (at >= before || row.backfilled || row.self && this.replies.get(row) !== scope) continue;
2898
2937
  const entry = this.entry(row);
2899
2938
  if (entry !== void 0) entries.push(entry);
2900
2939
  }
2901
2940
  return entries.reverse();
2902
2941
  }
2903
- recent(scope, count, through, after = -1) {
2942
+ recent(scope, count, through, after = -1, routeId) {
2904
2943
  if (count <= 0) return [];
2905
- this.lastPosition(scope.conversationId);
2906
2944
  const entries = [];
2907
- for (const row of this.newest(scope.conversationId)) {
2945
+ for (const row of this.positioned(scope.conversationId, routeId)) {
2908
2946
  const position = this.positions.get(row);
2909
2947
  if (position <= after) break;
2910
- if (position > through) continue;
2948
+ if (position > through || routeId !== void 0 && row.routeId !== routeId) continue;
2911
2949
  const entry = this.entry(row);
2912
2950
  if (entry !== void 0) entries.push(entry);
2913
2951
  if (entries.length === count) break;
2914
2952
  }
2915
2953
  return entries.reverse();
2916
2954
  }
2917
- locateUserPosition(key, message, after = -1) {
2918
- this.lastPosition(key);
2919
- for (const row of this.newest(key)) {
2920
- if (row.id !== message.id && (message.externalId === void 0 || row.platformMessageId !== message.externalId)) continue;
2955
+ locateUser(key, message, after = -1) {
2956
+ let candidate;
2957
+ let ambiguous = false;
2958
+ for (const row of this.positioned(key, message.routeId)) {
2921
2959
  const position = this.positions.get(row);
2922
- if (position > after && !row.self && !row.backfilled) return position;
2923
- return;
2960
+ if (position <= after) break;
2961
+ if (row.self || row.backfilled) continue;
2962
+ if (row.id === message.id) return {
2963
+ position,
2964
+ routeId: row.routeId
2965
+ };
2966
+ if (!message.externalId || row.platformMessageId !== message.externalId) continue;
2967
+ if (message.routeId && row.routeId !== message.routeId) continue;
2968
+ if (message.routeId || !isCustomConversation(key)) return {
2969
+ position,
2970
+ routeId: row.routeId
2971
+ };
2972
+ if (candidate) ambiguous = true;
2973
+ candidate = row;
2924
2974
  }
2975
+ if (candidate && !ambiguous) return {
2976
+ position: this.positions.get(candidate),
2977
+ routeId: candidate.routeId
2978
+ };
2925
2979
  }
2926
2980
  entry(row) {
2927
2981
  if (row.self && !this.replies.has(row)) return;
@@ -4818,7 +4872,7 @@ const createRecallTools = (options) => {
4818
4872
  searchKeywords: input.searchKeywords ?? [],
4819
4873
  results
4820
4874
  });
4821
- return results.length === 0 ? noMemoryFoundMessage : renderMemoriesForModel(results, { fields: contextMemoryFields });
4875
+ return results.length === 0 ? noMemoryFoundMessage : renderMemoriesForModel(results);
4822
4876
  }
4823
4877
  },
4824
4878
  {
@@ -4931,7 +4985,7 @@ var LivingMemoryRecallCoordinator = class {
4931
4985
  this.agenticRecall = agenticRecall;
4932
4986
  this.logger = logger;
4933
4987
  }
4934
- async queue(settings, scope, chatHistory, currentPosition) {
4988
+ async queue(settings, scope, chatHistory, currentPosition, routeId) {
4935
4989
  if (settings.recallIntervalMessages === 0 || !chatHistory.length) return;
4936
4990
  if (this.controller.signal.aborted) return;
4937
4991
  if (!isModelConfigured(this.subModel)) {
@@ -4941,14 +4995,15 @@ var LivingMemoryRecallCoordinator = class {
4941
4995
  }));
4942
4996
  return;
4943
4997
  }
4944
- const key = scopeKey(scope);
4998
+ const sourceId = settings.enableConversationIsolation && isCustomConversation(scope.conversationId) ? memorySourceId(scope.conversationId, routeId) : void 0;
4999
+ const key = scopeKey(scope, sourceId);
4945
5000
  let window = this.windows.get(key);
4946
5001
  if (!window) {
4947
5002
  window = { pending: false };
4948
5003
  this.windows.set(key, window);
4949
5004
  }
4950
5005
  if (window.anchor !== void 0) {
4951
- const messagesSinceRecall = (await this.messageLog.after(scope, window.anchor, currentPosition + 1)).length;
5006
+ const messagesSinceRecall = (await this.messageLog.after(scope, window.anchor, currentPosition + 1, sourceId)).length;
4952
5007
  if (messagesSinceRecall < settings.recallIntervalMessages) {
4953
5008
  this.logger.diagnosticSummary(() => ({
4954
5009
  event: "跳过记忆召回",
@@ -4973,7 +5028,7 @@ var LivingMemoryRecallCoordinator = class {
4973
5028
  const snapshotKey = JSON.stringify([snapshotScope.presetId, snapshotScope.conversationId]);
4974
5029
  const task = this.snapshotUpdates.run(snapshotKey, async () => {
4975
5030
  if (this.windows.get(key) !== window) return;
4976
- await this.run(settings, scope, snapshotScope, input, runLogger);
5031
+ await this.run(settings, scope, snapshotScope, input, runLogger, sourceId);
4977
5032
  }).catch((error) => {
4978
5033
  delete window.anchor;
4979
5034
  if (this.controller.signal.aborted) {
@@ -4996,14 +5051,17 @@ var LivingMemoryRecallCoordinator = class {
4996
5051
  clearByConversation(conversationId) {
4997
5052
  for (const key of this.windows.keys()) if (key.endsWith(`\n${conversationId}`)) this.windows.delete(key);
4998
5053
  }
4999
- async run(settings, scope, snapshotScope, input, logger) {
5054
+ async run(settings, scope, snapshotScope, input, logger, sourceId) {
5000
5055
  this.controller.signal.throwIfAborted();
5001
5056
  const startedAt = /* @__PURE__ */ new Date();
5002
5057
  try {
5003
5058
  const snapshot = await this.repository.getLatestSnapshotByScope(snapshotScope);
5004
5059
  const snapshotText = renderSnapshotText(snapshot?.items ?? []);
5005
5060
  const snapshotLines = snapshotText === "" ? [] : snapshotText.split(/\r?\n/);
5006
- const updatedSnapshot = await this.agenticRecall.run(settings, scope, input, snapshotLines, async (item) => {
5061
+ const updatedSnapshot = await this.agenticRecall.run(settings, sourceId ? {
5062
+ ...scope,
5063
+ conversationId: sourceId
5064
+ } : scope, input, snapshotLines, async (item) => {
5007
5065
  this.controller.signal.throwIfAborted();
5008
5066
  await this.repository.upsertSnapshot(snapshotScope, JSON.stringify(item.toolCallSummary), [item]);
5009
5067
  }, logger, this.controller.signal);
@@ -5368,7 +5426,7 @@ var LivingMemoryExtractionCoordinator = class {
5368
5426
  async queue(scope, options, initialPosition, eligiblePosition) {
5369
5427
  if (options.windowMessages === 0) return;
5370
5428
  if (this.controller.signal.aborted) return;
5371
- const key = scopeKey(scope);
5429
+ const key = scopeKey(scope, options.routeId);
5372
5430
  const state = this.stateByScope.get(key) ?? {
5373
5431
  scope,
5374
5432
  options,
@@ -5464,9 +5522,9 @@ var LivingMemoryExtractionCoordinator = class {
5464
5522
  */
5465
5523
  async drainNextChunk(state, scope, options, runLogger, firstChunk) {
5466
5524
  if (state.chunk === void 0) {
5467
- const entries = await this.messageLog.after(scope, state.cursorPosition, state.eligiblePosition + 1);
5525
+ const entries = await this.messageLog.after(scope, state.cursorPosition, state.eligiblePosition + 1, options.routeId);
5468
5526
  this.controller.signal.throwIfAborted();
5469
- if (this.stateByScope.get(scopeKey(scope)) !== state) return false;
5527
+ if (this.stateByScope.get(scopeKey(scope, options.routeId)) !== state) return false;
5470
5528
  if ((firstChunk || options.includeOverheard) && entries.length < options.windowMessages) {
5471
5529
  runLogger.diagnosticSummary(() => ({
5472
5530
  event: "等待记忆提取",
@@ -5487,8 +5545,8 @@ var LivingMemoryExtractionCoordinator = class {
5487
5545
  const messages = toHistoryTranscriptMessages(batch.scope, chunk);
5488
5546
  try {
5489
5547
  if (messages.length > 0) {
5490
- const origin = await batch.options.resolveTranscriptOrigin(chunk);
5491
- if (!await this.run(batch.scope, messages, origin, batch.options, runLogger)) return false;
5548
+ const header = await batch.options.formatTranscriptHeader(chunk);
5549
+ if (!await this.run(batch.scope, messages, header, batch.options, runLogger)) return false;
5492
5550
  } else runLogger.diagnosticSummary(() => ({
5493
5551
  event: "跳过记忆提取",
5494
5552
  detail: `${formatLogScope(scope)}; 原因:本批消息转写为空`
@@ -5520,10 +5578,10 @@ var LivingMemoryExtractionCoordinator = class {
5520
5578
  delete state.chunk;
5521
5579
  return true;
5522
5580
  }
5523
- async run(scope, messages, origin, options, logger) {
5581
+ async run(scope, messages, header, options, logger) {
5524
5582
  const startedAt = /* @__PURE__ */ new Date();
5525
5583
  const payload = this.formatter.toExtractionPayload(messages);
5526
- const input = `${origin.header}\n\n${payload.input}`;
5584
+ const input = `${header}\n\n${payload.input}`;
5527
5585
  logger.diagnosticSummary(() => ({
5528
5586
  event: "开始记忆提取",
5529
5587
  detail: `${formatLogScope(scope)}; 本批消息:${payload.sourceOriginMessages.length} 条; 输入内容:${input.length} 字符`
@@ -5551,7 +5609,10 @@ var LivingMemoryExtractionCoordinator = class {
5551
5609
  }
5552
5610
  const extracted = result.extracted;
5553
5611
  if (extracted.length > 0) {
5554
- const saved = await this.memoryWriter.appendExtractedMemories(scope, payload.sourceOriginMessages, extracted, origin.sourceLabel, payload.speakers);
5612
+ const saved = await this.memoryWriter.appendExtractedMemories({
5613
+ ...scope,
5614
+ conversationId: memorySourceId(scope.conversationId, options.routeId)
5615
+ }, payload.sourceOriginMessages, extracted, payload.speakers);
5555
5616
  for (const warning of saved.warnings) logger.summary("记忆提取索引同步延期", `${formatLogScope(scope)}; 原因:${warning}`, "warn");
5556
5617
  this.onExtracted(scope.presetId, saved.memories.map((entry) => entry.id), [...new Set(saved.memories.flatMap((entry) => entry.speakerKeys))], options.enableAutoDream);
5557
5618
  }
@@ -5962,7 +6023,7 @@ const buildUserProfilePrompts = (input) => {
5962
6023
  ...formatXmlBlock("existing_profile", input.group.existingProfile?.content ?? "无"),
5963
6024
  "",
5964
6025
  memoryCountNotice,
5965
- ...formatXmlBlock("memory_entries", renderMemoriesForModel(input.group.entries, { fields: contextMemoryFields })),
6026
+ ...formatXmlBlock("memory_entries", renderMemoriesForModel(input.group.entries)),
5966
6027
  "</user_profile_input>"
5967
6028
  ].join("\n")
5968
6029
  };
@@ -6728,13 +6789,10 @@ const createDreamSessionTools = ({ presetId, state, speakers, getEntriesByPreset
6728
6789
  ];
6729
6790
  };
6730
6791
  // src/service/prompts/dream.ts
6731
- const buildDreamMemoryBatchPrompt = (batch, speakers) => {
6792
+ const buildDreamMemoryBatchPrompt = (entries, speakers) => {
6732
6793
  return [
6733
6794
  "<dream_input>",
6734
- ...formatXmlBlock("memory_entries", renderMemoriesForModel(batch.entries, {
6735
- fields: dreamMemoryFields,
6736
- speakers
6737
- })),
6795
+ ...formatXmlBlock("memory_entries", renderDreamMemories(entries, speakers)),
6738
6796
  "</dream_input>"
6739
6797
  ].join("\n");
6740
6798
  };
@@ -6930,7 +6988,9 @@ async function runDreamSession(input) {
6930
6988
  recordDreamSpeakers(state, batch.entries.flatMap((entry) => entry.speakerKeys));
6931
6989
  const batchLogger = logger.with({ batch: batch.id });
6932
6990
  const batchStartedAt = performance.now();
6933
- const batchPrompt = buildDreamMemoryBatchPrompt(batch, [...speakers]);
6991
+ const entries = await withSourceLabels(ctx, batch.entries);
6992
+ signal?.throwIfAborted();
6993
+ const batchPrompt = buildDreamMemoryBatchPrompt(entries, speakers);
6934
6994
  history.startBatch(batchPrompt);
6935
6995
  batchLogger.diagnosticSummary((fields) => ({
6936
6996
  event: "Dream 批次开始",
@@ -8058,7 +8118,7 @@ function toSnapshotView(snapshot, sources) {
8058
8118
  return {
8059
8119
  id: snapshot.id,
8060
8120
  conversationId: snapshot.conversationId,
8061
- conversationLabel: source ? formatSource(source) : null,
8121
+ conversationLabel: source ? formatConversationPeer(source) : null,
8062
8122
  content: renderSnapshotText(snapshot.items),
8063
8123
  searchTexts: [...searchTexts],
8064
8124
  searchKeywords: [...searchKeywords],
@@ -8066,6 +8126,24 @@ function toSnapshotView(snapshot, sources) {
8066
8126
  createdAt: snapshot.createdAt.getTime()
8067
8127
  };
8068
8128
  }
8129
+ // src/service/transcript/header.ts
8130
+ async function formatTranscriptHeader(ctx, entries) {
8131
+ const peers = /* @__PURE__ */ new Map();
8132
+ for (const { source } of entries) {
8133
+ if (!source) return "以下是本次会话的聊天记录:";
8134
+ if (knownName(source.id, source.name) || !peers.has(source.key)) peers.set(source.key, source);
8135
+ }
8136
+ const stored = await ctx.routing.peers.get([...peers.keys()]);
8137
+ const labels = [];
8138
+ for (const peer of peers.values()) {
8139
+ const name = await peerName(ctx, peer, stored.get(peer.key)?.name);
8140
+ labels.push(formatConversationPeer({
8141
+ ...peer,
8142
+ name
8143
+ }));
8144
+ }
8145
+ return `以下是来自${labels.join("、")}的聊天记录:`;
8146
+ }
8069
8147
  // src/service/conversation_hooks.ts
8070
8148
  var LivingMemoryConversationHooks = class {
8071
8149
  ctx;
@@ -8130,9 +8208,9 @@ var LivingMemoryConversationHooks = class {
8130
8208
  this.revisions.clear();
8131
8209
  };
8132
8210
  }
8133
- settingsForTurn(agent) {
8134
- const running = this.turns.get(agent);
8135
- if (running && this.isCurrent(running)) return running.settings;
8211
+ contextForTurn(agent) {
8212
+ const turn = this.turns.get(agent);
8213
+ if (turn && this.isCurrent(turn)) return turn;
8136
8214
  }
8137
8215
  isCurrent({ state }) {
8138
8216
  return this.active && this.conversations.get(state.scope.conversationId) === state;
@@ -8151,16 +8229,29 @@ var LivingMemoryConversationHooks = class {
8151
8229
  }
8152
8230
  captureWindow(agent, key, trigger, noticePosition) {
8153
8231
  const contextStart = this.revisions.get(key)?.contextStart ?? -1;
8154
- const position = trigger?.kind === "chat" ? this.options.history.locateUserPosition(key, trigger, contextStart) : noticePosition;
8155
- const routeId = trigger?.kind === "chat" ? trigger.routeId : void 0;
8232
+ const observed = trigger?.kind === "chat" ? this.options.history.locateUser(key, trigger, contextStart) : void 0;
8233
+ const position = observed?.position ?? noticePosition;
8234
+ const routeId = trigger?.kind === "chat" ? observed?.routeId ?? trigger.routeId : agent.options.location?.route;
8156
8235
  const noticeSessionId = trigger?.kind === "notice" ? String(agent.session.id) : void 0;
8157
8236
  const settings = this.options.settingsOf(key, agent.options.location, routeId, noticeSessionId);
8237
+ const needsHistory = settings.recallIntervalMessages > 0 || settings.enableUserProfileInjection;
8238
+ const custom = isCustomConversation(key);
8239
+ let rows = [];
8240
+ if (needsHistory && position !== void 0) {
8241
+ if (custom && !routeId) this.options.logger.diagnosticSummary(() => ({
8242
+ event: "跳过记忆召回",
8243
+ detail: `会话:${key}; 原因:本次唤醒未指定来源路由,无法确定适用的对话规则`
8244
+ }));
8245
+ else rows = this.options.history.recent({ conversationId: key }, settings.recallHistoryMessages, position, contextStart, custom && settings.enableConversationIsolation ? routeId : void 0);
8246
+ }
8247
+ const presetId = this.agentPreset(agent);
8158
8248
  return {
8159
- rows: (settings.recallIntervalMessages > 0 || settings.enableUserProfileInjection) && position !== void 0 ? this.options.history.recent({ conversationId: key }, settings.recallHistoryMessages, position, contextStart) : [],
8249
+ rows,
8160
8250
  settings,
8161
8251
  position,
8162
- presetId: this.agentPreset(agent),
8163
- contextStart
8252
+ presetId,
8253
+ contextStart,
8254
+ routeId
8164
8255
  };
8165
8256
  }
8166
8257
  agentPreset(agent) {
@@ -8185,13 +8276,14 @@ var LivingMemoryConversationHooks = class {
8185
8276
  const scope = this.options.history.scopeOf(key, String(head.sessionId), presetId);
8186
8277
  const state = this.stateOf(scope, boundary);
8187
8278
  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);
8279
+ if (position !== void 0 && settings.recallIntervalMessages > 0 && chatHistory.length > 0) await this.options.recall.queue(settings, state.scope, chatHistory, position, window.routeId);
8189
8280
  return {
8190
8281
  kind: "ready",
8191
8282
  input: {
8192
8283
  state,
8193
8284
  settings,
8194
- chatHistory
8285
+ chatHistory,
8286
+ routeId: window.routeId
8195
8287
  }
8196
8288
  };
8197
8289
  } catch (error) {
@@ -8223,7 +8315,6 @@ var LivingMemoryConversationHooks = class {
8223
8315
  input.state.deliveries.set(turn, {
8224
8316
  settings: input.settings,
8225
8317
  pendingMessageIds: /* @__PURE__ */ new Set(),
8226
- lastReplyPosition: -1,
8227
8318
  drained: false
8228
8319
  });
8229
8320
  }
@@ -8292,7 +8383,7 @@ var LivingMemoryConversationHooks = class {
8292
8383
  if (!presetId) return;
8293
8384
  state = this.stateOf(this.options.history.scopeOf(key, sessionId, presetId), position - 1);
8294
8385
  }
8295
- if (position > state.boundary && settings.extractionIncludeOverheard) await this.queueExtraction(state, settings, position);
8386
+ if (position > state.boundary && settings.extractionIncludeOverheard) await this.queueExtraction(state, settings, position, event.message.routeId);
8296
8387
  }
8297
8388
  async onObservedReply(event) {
8298
8389
  const key = event.conversationKey;
@@ -8302,8 +8393,11 @@ var LivingMemoryConversationHooks = class {
8302
8393
  for (const [turn, delivery] of state.deliveries) {
8303
8394
  if (!delivery.pendingMessageIds.delete(id)) continue;
8304
8395
  const position = this.options.history.locate(key, event.message, state.scope);
8305
- if (position !== void 0) delivery.lastReplyPosition = Math.max(delivery.lastReplyPosition, position);
8306
- if (delivery.settings.extractionIncludeOverheard && position !== void 0) await this.queueExtraction(state, delivery.settings, position);
8396
+ if (position !== void 0 && (!delivery.lastReply || position > delivery.lastReply.position)) delivery.lastReply = {
8397
+ position,
8398
+ routeId: event.message.routeId
8399
+ };
8400
+ if (delivery.settings.extractionIncludeOverheard && position !== void 0) await this.queueExtraction(state, delivery.settings, position, event.message.routeId);
8307
8401
  await this.finishDeliveryIfReady(state, turn, delivery);
8308
8402
  return;
8309
8403
  }
@@ -8324,15 +8418,16 @@ var LivingMemoryConversationHooks = class {
8324
8418
  async finishDeliveryIfReady(state, turn, delivery) {
8325
8419
  if (!delivery.drained || delivery.pendingMessageIds.size > 0) return;
8326
8420
  state.deliveries.delete(turn);
8327
- if (!delivery.settings.extractionIncludeOverheard && delivery.lastReplyPosition > state.boundary) await this.queueExtraction(state, delivery.settings, delivery.lastReplyPosition);
8421
+ if (!delivery.settings.extractionIncludeOverheard && delivery.lastReply && delivery.lastReply.position > state.boundary) await this.queueExtraction(state, delivery.settings, delivery.lastReply.position, delivery.lastReply.routeId);
8328
8422
  }
8329
- async queueExtraction(state, settings, eligiblePosition) {
8423
+ async queueExtraction(state, settings, eligiblePosition, routeId) {
8330
8424
  if (settings.extractionWindowMessages === 0) return;
8331
8425
  await this.options.extraction.queue(state.scope, {
8426
+ routeId: isCustomConversation(state.scope.conversationId) ? routeId : void 0,
8332
8427
  includeOverheard: settings.extractionIncludeOverheard,
8333
8428
  windowMessages: settings.extractionWindowMessages,
8334
8429
  enableAutoDream: settings.enableAutoDream,
8335
- resolveTranscriptOrigin: (entries) => resolveTranscriptOrigin(this.ctx, entries)
8430
+ formatTranscriptHeader: (entries) => formatTranscriptHeader(this.ctx, entries)
8336
8431
  }, state.boundary, eligiblePosition);
8337
8432
  }
8338
8433
  logScheduleError(conversationId, error) {
@@ -8378,7 +8473,6 @@ function* turnInputs(message) {
8378
8473
  kind: "chat",
8379
8474
  id,
8380
8475
  externalId,
8381
- routeId: source.routeId,
8382
8476
  wake
8383
8477
  };
8384
8478
  }
@@ -8492,10 +8586,16 @@ var LivingmemoryService = class extends Service {
8492
8586
  const tools = registerLivingMemoryTools(this.ctx, this.providers, {
8493
8587
  enabled: this.config.enabledMemoryTools,
8494
8588
  createToolMaxMemories: this.config.memoryCreateToolMaxMemories,
8495
- isConversationIsolated: (agent) => {
8496
- const current = agent && this.conversationHooks.settingsForTurn(agent);
8497
- if (current) return current.enableConversationIsolation;
8498
- return routeSettings(this.ctx, agent?.options.conversationKey, agent?.options.location).enableConversationIsolation;
8589
+ resolveRoute: (agent, routeId) => {
8590
+ const turn = agent && this.conversationHooks.contextForTurn(agent);
8591
+ if (turn) return {
8592
+ routeId: turn.routeId,
8593
+ isolated: turn.settings.enableConversationIsolation
8594
+ };
8595
+ return {
8596
+ routeId,
8597
+ isolated: routeSettings(this.ctx, agent?.options.conversationKey, agent?.options.location, routeId).enableConversationIsolation
8598
+ };
8499
8599
  }
8500
8600
  });
8501
8601
  return () => {
@@ -8552,6 +8652,7 @@ var LivingmemoryService = class extends Service {
8552
8652
  * 先标记上次中断的任务,待工作线程启动后再安排归档清理。
8553
8653
  */
8554
8654
  async start() {
8655
+ await migrateLegacySources(this.ctx);
8555
8656
  await this.maintenance.recoverInterruptedJobs();
8556
8657
  const disposer = this.register();
8557
8658
  const stopMaintenance = this.maintenance.schedule();
@@ -8622,8 +8723,8 @@ const Config = Schema.intersect([
8622
8723
  Schema.object({
8623
8724
  mainModel: modelField("主 LLM 模型,用于提取记忆、Dream 与用户画像。", "chat").label("主模型"),
8624
8725
  subModel: modelField("子 LLM 模型,用于召回记忆。", "chat").label("召回模型"),
8625
- embeddingModel: modelField("将记忆和查询文本转换为向量,供检索和 Dream 比较语义相似度。", "embeddings").label("嵌入模型"),
8626
- rerankModel: modelField("可选。按候选记忆与查询的相关性重新排列检索结果。", "reranker").label("重排序模型")
8726
+ embeddingModel: modelField("将记忆和查询文本转换为向量,供检索和 Dream 比较语义相似度。", "embed").label("嵌入模型"),
8727
+ rerankModel: modelField("可选。按候选记忆与查询的相关性重新排列检索结果。", "rerank").label("重排序模型")
8627
8728
  }).description("模型配置"),
8628
8729
  Schema.object({
8629
8730
  memorySearchToolMaxResults: Schema.number().label("单次检索条数上限").min(1).max(60).step(1).description("每次记忆检索最多返回的记忆条数,召回与 living_memory_search 共用。").default(DEFAULT_CONFIG.memorySearchToolMaxResults),