chatluna-plugin-livingmemory 0.0.2 → 0.0.3

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 (40) hide show
  1. package/README.md +8 -3
  2. package/client/guide-panel.tsx +45 -0
  3. package/client/locales/en.yml +34 -0
  4. package/client/locales/zh.yml +34 -0
  5. package/client/page.tsx +32 -12
  6. package/client/settings-panel.tsx +66 -0
  7. package/dist/.vite/manifest.json +1 -1
  8. package/dist/client.css +1 -1
  9. package/dist/client.js +1 -1
  10. package/dist/page-CQcDlyjD.js +3 -0
  11. package/lib/contracts/memory.d.ts +6 -3
  12. package/lib/contracts/memory.d.ts.map +1 -1
  13. package/lib/contracts/webui.d.ts +1 -1
  14. package/lib/contracts/webui.d.ts.map +1 -1
  15. package/lib/contracts/webui_live.d.ts +4 -0
  16. package/lib/contracts/webui_live.d.ts.map +1 -1
  17. package/lib/contracts/workflows.d.ts +3 -3
  18. package/lib/contracts/workflows.d.ts.map +1 -1
  19. package/lib/index.d.ts.map +1 -1
  20. package/lib/index.js +67 -50
  21. package/lib/index.js.map +1 -1
  22. package/lib/routing.d.ts +2 -0
  23. package/lib/routing.d.ts.map +1 -1
  24. package/lib/service/conversation_hooks.d.ts +1 -0
  25. package/lib/service/conversation_hooks.d.ts.map +1 -1
  26. package/lib/service/memory/helpers.d.ts +3 -1
  27. package/lib/service/memory/helpers.d.ts.map +1 -1
  28. package/lib/service/persistence/repository.d.ts +3 -3
  29. package/lib/service/persistence/repository.d.ts.map +1 -1
  30. package/lib/service/persistence/snapshots.d.ts +3 -3
  31. package/lib/service/persistence/snapshots.d.ts.map +1 -1
  32. package/lib/service/workflows/recall/coordinator.d.ts +3 -10
  33. package/lib/service/workflows/recall/coordinator.d.ts.map +1 -1
  34. package/lib/service.d.ts.map +1 -1
  35. package/package.json +4 -1
  36. package/src/contracts/memory.ts +7 -3
  37. package/src/contracts/webui.ts +1 -1
  38. package/src/contracts/webui_live.ts +1 -0
  39. package/src/contracts/workflows.ts +3 -2
  40. package/dist/page-IsLg0kiw.js +0 -3
package/lib/index.js CHANGED
@@ -24,6 +24,7 @@ const ROUTE_SCHEMA = Schema$1.object({
24
24
  enableAutoDream: Schema$1.boolean().default(true).label("提取后整理新记忆"),
25
25
  recallIntervalMessages: Schema$1.natural().max(200).default(20).label("自动召回间隔").description("首次唤醒时有聊天就召回,之后按新增聊天条数判断;0 表示关闭。"),
26
26
  recallHistoryMessages: Schema$1.natural().min(1).max(200).default(20).label("召回上下文条数").description("唤醒时读取的最近聊天条数。用户发言触发时包含该条;定时或冷场唤醒时只读已有聊天。"),
27
+ snapshotScope: Schema$1.union([Schema$1.const("conversation").description("会话独立快照"), Schema$1.const("preset").description("预设共享快照")]).default("conversation").label("记忆快照范围").description("开启「隔离会话检索」的会话始终使用独立快照。"),
27
28
  snapshotMaxLines: Schema$1.natural().min(5).max(50).default(5).label("快照最大行数"),
28
29
  enableConversationIsolation: Schema$1.boolean().default(false).label("隔离会话检索").description("自动召回与记忆检索工具只检索当前会话和全局记忆。"),
29
30
  enableSnapshotInjection: Schema$1.boolean().default(true).label("注入记忆快照"),
@@ -1284,7 +1285,12 @@ function defineLivingMemoryTables(ctx) {
1284
1285
  ctx.model.extend("living_memory_snapshot", {
1285
1286
  id: "string(64)",
1286
1287
  presetId: "string(255)",
1287
- conversationId: "string(255)",
1288
+ conversationId: {
1289
+ type: "string",
1290
+ length: 255,
1291
+ nullable: true,
1292
+ initial: null
1293
+ },
1288
1294
  query: "text",
1289
1295
  items: {
1290
1296
  type: "json",
@@ -2013,7 +2019,7 @@ var LivingMemorySnapshotRepository = class {
2013
2019
  async loadSortedSnapshotsByScope(scope) {
2014
2020
  return (await this.database.get("living_memory_snapshot", {
2015
2021
  presetId: scope.presetId,
2016
- conversationId: scope.conversationId
2022
+ conversationId: scope.conversationId ?? { $exists: false }
2017
2023
  })).sort((left, right) => +right.createdAt - +left.createdAt);
2018
2024
  }
2019
2025
  async deleteSnapshot(snapshotId) {
@@ -2676,6 +2682,12 @@ var LivingMemoryRepository = class {
2676
2682
  * 提取缓冲、召回锁与说话人标签缓存均以该键隔离数据。
2677
2683
  */
2678
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
+ }
2679
2691
  /**
2680
2692
  * 解析面向 LLM 的助手标签:优先使用 preset 展示名(presetLabel),
2681
2693
  * 缺省或为空白时回退 presetId。
@@ -4904,14 +4916,8 @@ var LivingMemoryRecallCoordinator = class {
4904
4916
  repository;
4905
4917
  agenticRecall;
4906
4918
  logger;
4907
- recallLockByConversation = /* @__PURE__ */ new Set();
4908
- /**
4909
- * 召回窗口锚点:上次实际执行召回时的聊天历史位置。间隔按此后累计
4910
- * 的聊天条数(含闲聊)计;锚点只在召回实际执行时前移,
4911
- * 召回失败时清除,使下次触发立即重试。
4912
- */
4913
- anchorPositionByScope = /* @__PURE__ */ new Map();
4914
- generations = /* @__PURE__ */ new Map();
4919
+ snapshotUpdates = new SerialTaskQueue();
4920
+ windows = /* @__PURE__ */ new Map();
4915
4921
  /**
4916
4922
  * 卸载时取消在途召回:停止接收新触发、中止模型调用、等待任务收尾。
4917
4923
  * 召回不写任务行(只在失败时记一条),因此取消不产生额外记录。
@@ -4935,12 +4941,14 @@ var LivingMemoryRecallCoordinator = class {
4935
4941
  }));
4936
4942
  return;
4937
4943
  }
4938
- const lockKey = scopeKey(scope);
4939
- const generation = this.generations.get(scope.conversationId) ?? {};
4940
- this.generations.set(scope.conversationId, generation);
4941
- const anchorPosition = this.anchorPositionByScope.get(lockKey);
4942
- if (anchorPosition !== void 0) {
4943
- const messagesSinceRecall = (await this.messageLog.after(scope, anchorPosition, currentPosition + 1)).length;
4944
+ const key = scopeKey(scope);
4945
+ let window = this.windows.get(key);
4946
+ if (!window) {
4947
+ window = { pending: false };
4948
+ this.windows.set(key, window);
4949
+ }
4950
+ if (window.anchor !== void 0) {
4951
+ const messagesSinceRecall = (await this.messageLog.after(scope, window.anchor, currentPosition + 1)).length;
4944
4952
  if (messagesSinceRecall < settings.recallIntervalMessages) {
4945
4953
  this.logger.diagnosticSummary(() => ({
4946
4954
  event: "跳过记忆召回",
@@ -4949,8 +4957,8 @@ var LivingMemoryRecallCoordinator = class {
4949
4957
  return;
4950
4958
  }
4951
4959
  }
4952
- if (this.controller.signal.aborted || this.generations.get(scope.conversationId) !== generation) return;
4953
- if (this.recallLockByConversation.has(lockKey)) {
4960
+ if (this.controller.signal.aborted || this.windows.get(key) !== window) return;
4961
+ if (window.pending) {
4954
4962
  this.logger.diagnosticSummary(() => ({
4955
4963
  event: "跳过记忆召回",
4956
4964
  detail: `${formatLogScope(scope)}; 原因:当前召回任务运行中`
@@ -4959,17 +4967,22 @@ var LivingMemoryRecallCoordinator = class {
4959
4967
  }
4960
4968
  const input = renderLivingMemoryTranscript(chatHistory);
4961
4969
  const runLogger = this.logger.with({ ...scope });
4962
- this.recallLockByConversation.add(lockKey);
4963
- this.anchorPositionByScope.set(lockKey, currentPosition);
4964
- const task = this.run(settings, scope, input, runLogger).catch((error) => {
4965
- if (this.generations.get(scope.conversationId) === generation) this.anchorPositionByScope.delete(lockKey);
4970
+ window.pending = true;
4971
+ window.anchor = currentPosition;
4972
+ const snapshotScope = snapshotScopeOf(scope, settings);
4973
+ const snapshotKey = JSON.stringify([snapshotScope.presetId, snapshotScope.conversationId]);
4974
+ const task = this.snapshotUpdates.run(snapshotKey, async () => {
4975
+ if (this.windows.get(key) !== window) return;
4976
+ await this.run(settings, scope, snapshotScope, input, runLogger);
4977
+ }).catch((error) => {
4978
+ delete window.anchor;
4966
4979
  if (this.controller.signal.aborted) {
4967
4980
  runLogger.summary("记忆召回已取消", (fields) => formatLogScope(fields));
4968
4981
  return;
4969
4982
  }
4970
4983
  runLogger.summary("记忆召回失败", (fields) => formatLogScope(fields), "warn", error);
4971
4984
  }).finally(() => {
4972
- this.recallLockByConversation.delete(lockKey);
4985
+ window.pending = false;
4973
4986
  });
4974
4987
  this.tasks.add(task);
4975
4988
  task.finally(() => this.tasks.delete(task));
@@ -4978,25 +4991,21 @@ var LivingMemoryRecallCoordinator = class {
4978
4991
  async stop() {
4979
4992
  this.controller.abort(/* @__PURE__ */ new Error("记忆召回服务正在停止。"));
4980
4993
  await Promise.allSettled([...this.tasks]);
4981
- this.clearAll();
4982
- }
4983
- clearAll() {
4984
- this.anchorPositionByScope.clear();
4985
- this.generations.clear();
4994
+ this.windows.clear();
4986
4995
  }
4987
4996
  clearByConversation(conversationId) {
4988
- this.generations.delete(conversationId);
4989
- for (const key of this.anchorPositionByScope.keys()) if (key.endsWith(`\n${conversationId}`)) this.anchorPositionByScope.delete(key);
4997
+ for (const key of this.windows.keys()) if (key.endsWith(`\n${conversationId}`)) this.windows.delete(key);
4990
4998
  }
4991
- async run(settings, scope, input, logger) {
4999
+ async run(settings, scope, snapshotScope, input, logger) {
5000
+ this.controller.signal.throwIfAborted();
4992
5001
  const startedAt = /* @__PURE__ */ new Date();
4993
5002
  try {
4994
- const snapshot = await this.repository.getLatestSnapshotByScope(scope);
5003
+ const snapshot = await this.repository.getLatestSnapshotByScope(snapshotScope);
4995
5004
  const snapshotText = renderSnapshotText(snapshot?.items ?? []);
4996
5005
  const snapshotLines = snapshotText === "" ? [] : snapshotText.split(/\r?\n/);
4997
5006
  const updatedSnapshot = await this.agenticRecall.run(settings, scope, input, snapshotLines, async (item) => {
4998
5007
  this.controller.signal.throwIfAborted();
4999
- await this.repository.upsertSnapshot(scope, JSON.stringify(item.toolCallSummary), [item]);
5008
+ await this.repository.upsertSnapshot(snapshotScope, JSON.stringify(item.toolCallSummary), [item]);
5000
5009
  }, logger, this.controller.signal);
5001
5010
  this.controller.signal.throwIfAborted();
5002
5011
  if (updatedSnapshot == null) {
@@ -7818,10 +7827,10 @@ const livingMemoryWebUI = (ctx, ui) => {
7818
7827
  }),
7819
7828
  get: async (query) => {
7820
7829
  const result = await ui.admin.listSnapshots(query);
7821
- const sources = await resolveConversationSources(ctx, result.items.map((item) => item.conversationId));
7830
+ const sources = await resolveConversationSources(ctx, result.items.map((item) => item.conversationId).filter((id) => id !== null));
7822
7831
  return {
7823
7832
  presetId: query.presetId,
7824
- snapshots: result.items.map((snapshot) => toSnapshotView(snapshot, sources.get(snapshot.conversationId))),
7833
+ snapshots: result.items.map((snapshot) => toSnapshotView(snapshot, sources)),
7825
7834
  total: result.total,
7826
7835
  page: result.page,
7827
7836
  pageSize: result.pageSize
@@ -8033,7 +8042,8 @@ const toProfileView = (profile) => ({
8033
8042
  sourceMemoryIds: [...profile.sourceMemoryIds],
8034
8043
  updatedAt: profile.updatedAt.getTime()
8035
8044
  });
8036
- function toSnapshotView(snapshot, source) {
8045
+ function toSnapshotView(snapshot, sources) {
8046
+ const source = snapshot.conversationId === null ? void 0 : sources.get(snapshot.conversationId);
8037
8047
  const searchTexts = /* @__PURE__ */ new Set();
8038
8048
  const searchKeywords = /* @__PURE__ */ new Set();
8039
8049
  const matchedMemories = [];
@@ -8221,7 +8231,7 @@ var LivingMemoryConversationHooks = class {
8221
8231
  const { scope } = state;
8222
8232
  const sections = [];
8223
8233
  if (settings.enableSnapshotInjection) {
8224
- const snapshot = await this.options.repository.getLatestSnapshotByScope(scope);
8234
+ const snapshot = await this.options.repository.getLatestSnapshotByScope(snapshotScopeOf(scope, settings));
8225
8235
  const text = renderSnapshotText(snapshot?.items ?? []);
8226
8236
  if (text.length > 0) sections.push(`<memory>\n${text}\n</memory>`);
8227
8237
  }
@@ -8519,6 +8529,13 @@ var LivingmemoryService = class extends Service {
8519
8529
  name: "livingmemory-webui",
8520
8530
  inject: ["chatluna_webui", "permissions"],
8521
8531
  apply: (ctx) => {
8532
+ ctx.chatluna_webui.state("livingmemory.settingsEntry", { get: () => {
8533
+ const entry = this.ctx.fiber.entry;
8534
+ return entry ? {
8535
+ id: entry.id,
8536
+ name: entry.options.name
8537
+ } : null;
8538
+ } });
8522
8539
  ctx.chatluna_webui.addEntry({
8523
8540
  baseUrl: import.meta.url,
8524
8541
  source: "../client/index.ts",
@@ -8601,16 +8618,16 @@ const modelField = (description, modality) => modelAddressSchema({
8601
8618
  * 界面语义与取值范围,避免两处默认值漂移。
8602
8619
  */
8603
8620
  const Config = Schema.intersect([
8604
- Schema.object({ debug: Schema.boolean().description("记录召回、提取、Dream 每次模型调用的完整提示词、原始响应与诊断事件。").default(DEFAULT_CONFIG.debug) }).description("基础配置"),
8621
+ Schema.object({ debug: Schema.boolean().label("调试日志").description("记录召回、提取、Dream 每次模型调用的完整提示词、原始响应与诊断事件。").default(DEFAULT_CONFIG.debug) }).description("基础配置"),
8605
8622
  Schema.object({
8606
- mainModel: modelField("主 LLM 模型,用于提取记忆、Dream 与用户画像。", "chat"),
8607
- subModel: modelField("子 LLM 模型,用于召回记忆。", "chat"),
8608
- embeddingModel: modelField("嵌入模型,用于记忆检索与 Dream。", "embeddings"),
8609
- rerankModel: modelField("Reranker 模型,用于记忆检索结果重排序。", "reranker")
8623
+ mainModel: modelField("主 LLM 模型,用于提取记忆、Dream 与用户画像。", "chat").label("主模型"),
8624
+ subModel: modelField("子 LLM 模型,用于召回记忆。", "chat").label("召回模型"),
8625
+ embeddingModel: modelField("将记忆和查询文本转换为向量,供检索和 Dream 比较语义相似度。", "embeddings").label("嵌入模型"),
8626
+ rerankModel: modelField("可选。按候选记忆与查询的相关性重新排列检索结果。", "reranker").label("重排序模型")
8610
8627
  }).description("模型配置"),
8611
8628
  Schema.object({
8612
- memorySearchToolMaxResults: Schema.number().min(1).max(60).step(1).description("每次记忆检索最多返回的记忆条数,召回与 living_memory_search 共用。").default(DEFAULT_CONFIG.memorySearchToolMaxResults),
8613
- memorySearchMinSimilarity: Schema.number().min(0).max(1).step(.05).description("记忆检索的最低余弦相似度。关键词命中的记忆不受限制;设为 0 表示不限制。").default(DEFAULT_CONFIG.memorySearchMinSimilarity),
8629
+ memorySearchToolMaxResults: Schema.number().label("单次检索条数上限").min(1).max(60).step(1).description("每次记忆检索最多返回的记忆条数,召回与 living_memory_search 共用。").default(DEFAULT_CONFIG.memorySearchToolMaxResults),
8630
+ memorySearchMinSimilarity: Schema.number().label("最低相似度").min(0).max(1).step(.05).description("记忆检索的最低余弦相似度。关键词命中的记忆不受限制;设为 0 表示不限制。").default(DEFAULT_CONFIG.memorySearchMinSimilarity),
8614
8631
  enabledMemoryTools: Schema.array(Schema.union([
8615
8632
  Schema.const("living_memory_search").description("记忆查询工具:通过语义检索查询记忆"),
8616
8633
  Schema.const("living_memory_get_messages").description("来源查看工具:查看记忆来源的聊天消息"),
@@ -8619,14 +8636,14 @@ const Config = Schema.intersect([
8619
8636
  Schema.const("living_memory_merge_memories").description("记忆合并工具:将多条记忆合并为一条"),
8620
8637
  Schema.const("living_memory_split_memory").description("记忆拆分工具:将一条记忆拆分为多条"),
8621
8638
  Schema.const("living_memory_delete_memory").description("记忆删除工具:归档删除记忆")
8622
- ])).role("checkbox").description("选择向 ChatLuna 注册的记忆工具。").default(DEFAULT_CONFIG.enabledMemoryTools),
8623
- memoryCreateToolMaxMemories: Schema.number().min(1).max(60).step(1).description("living_memory_create_memory 单次调用最多创建的记忆条数。").default(DEFAULT_CONFIG.memoryCreateToolMaxMemories)
8639
+ ])).role("checkbox").label("启用的记忆工具").description("选择向 ChatLuna 注册的记忆工具。").default(DEFAULT_CONFIG.enabledMemoryTools),
8640
+ memoryCreateToolMaxMemories: Schema.number().label("单次创建条数上限").min(1).max(60).step(1).description("living_memory_create_memory 单次调用最多创建的记忆条数。").default(DEFAULT_CONFIG.memoryCreateToolMaxMemories)
8624
8641
  }).description("工具配置"),
8625
8642
  Schema.object({
8626
- enableUserProfileGeneration: Schema.boolean().description("进行记忆提取后,生成、更新相关用户画像。").default(DEFAULT_CONFIG.enableUserProfileGeneration),
8627
- enableDreamUserProfileGeneration: Schema.boolean().description("进行 Dream 记忆整理后,生成、更新相关用户画像。").default(DEFAULT_CONFIG.enableDreamUserProfileGeneration),
8628
- userProfileMinMemoryCount: Schema.number().min(1).max(30).step(1).description("生成或更新单个用户画像所需的最少关联活跃记忆条数。").default(DEFAULT_CONFIG.userProfileMinMemoryCount),
8629
- userProfileMemoryLimit: Schema.number().min(5).max(100).step(1).description("生成单个用户画像时可送入模型的相关记忆条数上限。").default(DEFAULT_CONFIG.userProfileMemoryLimit)
8643
+ enableUserProfileGeneration: Schema.boolean().label("提取后更新画像").description("进行记忆提取后,生成、更新相关用户画像。").default(DEFAULT_CONFIG.enableUserProfileGeneration),
8644
+ enableDreamUserProfileGeneration: Schema.boolean().label("Dream 后更新画像").description("进行 Dream 记忆整理后,生成、更新相关用户画像。").default(DEFAULT_CONFIG.enableDreamUserProfileGeneration),
8645
+ userProfileMinMemoryCount: Schema.number().label("生成画像所需记忆数").min(1).max(30).step(1).description("生成或更新单个用户画像所需的最少关联活跃记忆条数。").default(DEFAULT_CONFIG.userProfileMinMemoryCount),
8646
+ userProfileMemoryLimit: Schema.number().label("生成画像时的记忆条数上限").min(5).max(100).step(1).description("生成单个用户画像时可送入模型的相关记忆条数上限。").default(DEFAULT_CONFIG.userProfileMemoryLimit)
8630
8647
  }).description("用户画像配置")
8631
8648
  ]);
8632
8649
  async function apply(ctx, config = DEFAULT_CONFIG) {