chatluna-plugin-livingmemory 0.0.5 → 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.
Files changed (33) hide show
  1. package/README.md +14 -14
  2. package/client/guide-panel.tsx +60 -37
  3. package/client/locales/en.yml +14 -4
  4. package/client/locales/zh.yml +20 -10
  5. package/client/page.tsx +28 -0
  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-EGG2hcC3.js +3 -0
  10. package/lib/contracts/webui.d.ts +1 -0
  11. package/lib/contracts/webui.d.ts.map +1 -1
  12. package/lib/index.js +233 -193
  13. package/lib/index.js.map +1 -1
  14. package/lib/service/app/webui.d.ts.map +1 -1
  15. package/lib/service/logging/logger.d.ts +2 -4
  16. package/lib/service/logging/logger.d.ts.map +1 -1
  17. package/lib/service/logging/model_calls.d.ts +11 -0
  18. package/lib/service/logging/model_calls.d.ts.map +1 -1
  19. package/lib/service/shared/utils.d.ts +0 -4
  20. package/lib/service/shared/utils.d.ts.map +1 -1
  21. package/lib/service/workflows/dream/session/history.d.ts +4 -4
  22. package/lib/service/workflows/dream/session/history.d.ts.map +1 -1
  23. package/lib/service/workflows/dream/session/runner.d.ts.map +1 -1
  24. package/lib/service/workflows/extraction/coordinator.d.ts.map +1 -1
  25. package/lib/service/workflows/extraction/extractor.d.ts +0 -4
  26. package/lib/service/workflows/extraction/extractor.d.ts.map +1 -1
  27. package/lib/service/workflows/structured_output.d.ts +10 -14
  28. package/lib/service/workflows/structured_output.d.ts.map +1 -1
  29. package/lib/service/workflows/tool_loop.d.ts +10 -21
  30. package/lib/service/workflows/tool_loop.d.ts.map +1 -1
  31. package/package.json +2 -1
  32. package/src/contracts/webui.ts +1 -0
  33. package/dist/page-kxmLRgbo.js +0 -3
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, ProtocolError } from "@chatluna/ai";
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("自动提取间隔").description("累计多少条聊天后提取;0 表示关闭。"),
23
- extractionIncludeOverheard: Schema$1.boolean().default(false).label("提取旁听消息").description("允许单独提取机器人未参与的闲聊。"),
24
- enableAutoDream: Schema$1.boolean().default(true).label("提取后整理新记忆"),
25
- recallIntervalMessages: Schema$1.natural().max(200).default(20).label("自动召回间隔").description("首次唤醒时有聊天就召回,之后按新增聊天条数判断;0 表示关闭。"),
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("开启「隔离会话检索」的会话始终使用独立快照。"),
28
- snapshotMaxLines: Schema$1.natural().min(5).max(50).default(5).label("快照最大行数"),
29
- enableConversationIsolation: Schema$1.boolean().default(false).label("隔离会话检索").description("自动召回与记忆检索工具只检索当前会话和全局记忆。"),
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({
@@ -214,21 +215,10 @@ const formatErrorDetails = (error) => {
214
215
  return JSON.stringify(error);
215
216
  };
216
217
  /** 将任意抛出值规范为 Error,非 Error 值包装为消息。 */
217
- const toError$1 = (error) => {
218
+ const toError = (error) => {
218
219
  if (error instanceof Error) return error;
219
220
  return new Error(String(error));
220
221
  };
221
- /**
222
- * 提取模型消息正文的纯文本:多分片内容仅拼接 text 分片,其余形式序列化为 JSON。
223
- */
224
- const stringifyModelContent = (content) => {
225
- if (typeof content === "string") return content;
226
- if (Array.isArray(content)) return content.map((part) => {
227
- if (part != null && typeof part === "object" && part.type === "text" && typeof part.text === "string") return part.text;
228
- return "";
229
- }).join("");
230
- return JSON.stringify(content) ?? "";
231
- };
232
222
  // src/service/vector_index/errors.ts
233
223
  var LivingMemoryVectorIndexError = class extends Error {
234
224
  code;
@@ -264,8 +254,6 @@ const formatLogScope = (scope) => {
264
254
  return details.join("; ");
265
255
  };
266
256
  const credentialKeyPattern = /(?:authorization|api[-_]?key|access[-_]?token|refresh[-_]?token|(?:^|[-_])token(?:$|[-_])|password|secret)/iu;
267
- const bareValuePattern = /^[\p{L}\p{N}._:/@*+-]+$/u;
268
- const toError = (error) => error instanceof Error ? error : new Error(String(error));
269
257
  const normalizeValue = (value, key, seen) => {
270
258
  if (credentialKeyPattern.test(key)) return "[REDACTED]";
271
259
  if (value == null || typeof value === "boolean" || typeof value === "string") return value;
@@ -293,26 +281,13 @@ const normalizeValue = (value, key, seen) => {
293
281
  seen.delete(objectValue);
294
282
  }
295
283
  };
296
- const stringifyNormalized = (value, key, options) => {
297
- const normalized = normalizeValue(value, key, /* @__PURE__ */ new WeakSet());
298
- if (typeof normalized === "string" && (!options.bareStringsOnly || bareValuePattern.test(normalized))) return normalized;
299
- const serialized = JSON.stringify(normalized, null, options.indent);
300
- return serialized === void 0 ? "\"[unserializable]\"" : serialized;
301
- };
302
- const formatValue = (value, key) => stringifyNormalized(value, key, { bareStringsOnly: true });
303
- const formatBlockValue = (value, key) => stringifyNormalized(value, key, {
304
- indent: 2,
305
- bareStringsOnly: false
306
- });
307
- const formatFields = (fields) => Object.entries(fields).filter(([, value]) => value !== void 0).map(([key, value]) => `${key}:${formatValue(value, key)}`).join("; ");
308
- const formatBlock = (block) => {
309
- const title = block.title.replace(/\r?\n/gu, " ");
310
- const detail = formatFields(block.fields ?? {});
311
- const lines = [`========${detail.length > 0 ? `${title} ${detail}` : title}========`];
312
- if (block.subtitle != null) lines.push(block.subtitle.replace(/\r?\n/gu, " "));
313
- lines.push(formatBlockValue(block.value, block.key ?? ""));
314
- return lines.join("\n");
315
- };
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
+ }
316
291
  var LivingMemoryLogger = class LivingMemoryLogger {
317
292
  sink;
318
293
  isDebugEnabled;
@@ -333,9 +308,7 @@ var LivingMemoryLogger = class LivingMemoryLogger {
333
308
  diagnosticSummary(render) {
334
309
  if (!this.isDebugEnabled()) return;
335
310
  try {
336
- const rendered = render(this.context);
337
- if (rendered === void 0) return;
338
- const { event, detail, blocks } = rendered;
311
+ const { event, detail, blocks } = render(this.context);
339
312
  let content = detail;
340
313
  if (blocks?.length) content += "\n" + blocks.map(formatBlock).join("\n\n");
341
314
  this.summary(event, content);
@@ -3972,7 +3945,7 @@ var LivingMemoryVectorIndexWorkerClient = class {
3972
3945
  try {
3973
3946
  await this.sendRequest({ type: "dispose" });
3974
3947
  } catch (error) {
3975
- disposeError = toError$1(error);
3948
+ disposeError = toError(error);
3976
3949
  await this.worker.terminate();
3977
3950
  }
3978
3951
  const exitCode = await this.exitPromise;
@@ -3998,7 +3971,7 @@ var LivingMemoryVectorIndexWorkerClient = class {
3998
3971
  }, commandTransferList(command));
3999
3972
  } catch (error) {
4000
3973
  this.pending.delete(id);
4001
- reject(toError$1(error));
3974
+ reject(toError(error));
4002
3975
  }
4003
3976
  });
4004
3977
  }
@@ -4107,7 +4080,7 @@ var LivingMemoryVectorIndexService = class {
4107
4080
  try {
4108
4081
  this.generation = await acquireVectorIndexGeneration(generationKey);
4109
4082
  } catch (error) {
4110
- const failure = toError$1(error);
4083
+ const failure = toError(error);
4111
4084
  this.status.markUnavailable(failure.message);
4112
4085
  this.logger.summary("向量索引启动失败", "状态:暂停检索", "error", failure);
4113
4086
  throw error;
@@ -4129,7 +4102,7 @@ var LivingMemoryVectorIndexService = class {
4129
4102
  }
4130
4103
  });
4131
4104
  } catch (error) {
4132
- const failure = toError$1(error);
4105
+ const failure = toError(error);
4133
4106
  this.status.markUnavailable(failure.message);
4134
4107
  this.logger.summary("向量索引启动失败", "状态:暂停检索", "error", failure);
4135
4108
  try {
@@ -4321,7 +4294,7 @@ var LivingMemoryVectorIndexService = class {
4321
4294
  return this.embeddingContext;
4322
4295
  }
4323
4296
  async markMutationFailed(presetId, indexedCount, error) {
4324
- const failure = toError$1(error);
4297
+ const failure = toError(error);
4325
4298
  const expectedCount = await this.repository.countEntriesByPreset(presetId);
4326
4299
  if (this.worker !== null && this.workerFailure === null) {
4327
4300
  await this.worker.markPresetState({
@@ -4403,7 +4376,7 @@ var LivingMemoryVectorIndexService = class {
4403
4376
  this.assertPresetReady(presetId);
4404
4377
  }
4405
4378
  async handleMaintenanceFailure(error) {
4406
- const failure = toError$1(error);
4379
+ const failure = toError(error);
4407
4380
  let state = "unavailable";
4408
4381
  if (this.workerFailure === null && error instanceof LivingMemoryVectorIndexError) state = error.state;
4409
4382
  await this.inspectAfterFailure();
@@ -4631,10 +4604,63 @@ const buildSnapshotRecallPrompts = (params) => {
4631
4604
  const modelStageLabels = {
4632
4605
  recall: "召回",
4633
4606
  dream: "Dream",
4607
+ "dream-compression": "Dream 上下文压缩",
4634
4608
  "memory-extraction": "记忆提取",
4635
4609
  "persona-card": "人设卡片",
4636
4610
  "user-profile": "人物画像"
4637
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
+ }
4638
4664
  // src/service/workflows/tool_call.ts
4639
4665
  const unknownToolMessage = (name) => `未知工具:${name}`;
4640
4666
  const invalidToolArgsMessage = (name, reason) => `工具 ${name} 的参数不合法:${reason}。请修正参数后重新提交。`;
@@ -4695,11 +4721,10 @@ var LivingMemoryToolLoop = class {
4695
4721
  toolsByName;
4696
4722
  constructor(options) {
4697
4723
  this.options = options;
4698
- this.history = options.history ?? { messages: [] };
4699
- if (options.history === void 0) this.history.messages.push({
4724
+ this.history = "history" in options ? options.history : { messages: [{
4700
4725
  role: "user",
4701
4726
  content: textBlocks(options.input)
4702
- });
4727
+ }] };
4703
4728
  this.specs = options.tools.map((tool) => ({
4704
4729
  name: tool.name,
4705
4730
  description: tool.description,
@@ -4716,13 +4741,10 @@ var LivingMemoryToolLoop = class {
4716
4741
  async runRound(step) {
4717
4742
  const { signal, prepareMessages, onModelCall } = this.options;
4718
4743
  signal?.throwIfAborted();
4719
- const messages = await prepareMessages?.(this.history.messages, step) ?? this.history.messages;
4744
+ const messages = prepareMessages ? await prepareMessages() : this.history.messages;
4720
4745
  const fold = await this.callModel(messages, step);
4721
4746
  signal?.throwIfAborted();
4722
- onModelCall?.({
4723
- fold,
4724
- step
4725
- });
4747
+ onModelCall?.(fold);
4726
4748
  if (fold.toolCalls.length === 0) {
4727
4749
  this.history.messages.push({
4728
4750
  role: "user",
@@ -4745,6 +4767,14 @@ var LivingMemoryToolLoop = class {
4745
4767
  for (const call of fold.toolCalls) {
4746
4768
  signal?.throwIfAborted();
4747
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
+ }));
4748
4778
  signal?.throwIfAborted();
4749
4779
  if (outcome.ok) successfulTools.push(call.toolName);
4750
4780
  this.history.messages.push({
@@ -4764,35 +4794,20 @@ var LivingMemoryToolLoop = class {
4764
4794
  }
4765
4795
  async callModel(messages, step) {
4766
4796
  const { ctx, model, logger } = this.options;
4767
- const stage = modelStageLabels[this.options.stage];
4768
- logger.diagnosticSummary((fields) => ({
4769
- event: `${stage}模型调用`,
4770
- detail: `${formatLogScope(fields)}; 模型:${model}; 调用序号:${step}`
4771
- }));
4797
+ const log = modelCallLogging(logger, this.options.stage, step);
4772
4798
  try {
4773
4799
  const fold = await ctx.chatluna.chat({
4774
4800
  model,
4775
4801
  system: this.options.system,
4776
4802
  messages: [...messages],
4777
- toolSpecs: this.specs
4778
- });
4779
- logger.diagnosticSummary((fields) => {
4780
- if (fold.toolCalls.length === 0) return void 0;
4781
- return {
4782
- event: `${stage}模型响应`,
4783
- detail: `${formatLogScope(fields)}; 工具调用:${fold.toolCalls.map((call) => call.toolName).join("、")}`,
4784
- blocks: fold.toolCalls.map((call) => ({
4785
- title: "工具调用",
4786
- subtitle: `${call.toolName}:${call.toolCallId}`,
4787
- key: "args",
4788
- value: call.input
4789
- }))
4790
- };
4803
+ toolSpecs: this.specs,
4804
+ beforeDispatch: log.beforeDispatch
4791
4805
  });
4806
+ log.response(fold);
4792
4807
  return fold;
4793
4808
  } catch (error) {
4794
4809
  logger.diagnosticSummary((fields) => ({
4795
- event: `${stage}模型调用失败`,
4810
+ event: `${modelStageLabels[this.options.stage]}模型调用失败`,
4796
4811
  detail: `${formatLogScope(fields)}; 模型:${model}; 调用序号:${step}; 原因:${formatErrorDetails(error)}`
4797
4812
  }));
4798
4813
  throw error;
@@ -5158,62 +5173,112 @@ const buildExtractionPrompts = (params) => {
5158
5173
  };
5159
5174
  // src/service/workflows/structured_output.ts
5160
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
+ }
5161
5207
  /**
5162
- * 调用结构化输出。取消信号在每次调用前检查,取消不进入修正重试。
5163
- * 模型自身错误原样抛出——只有解析与校验失败才会带着修正提示重试。
5208
+ * 每次只接受一个指定工具提交的结果。提交不合格时将原因反馈给模型;调用错误和取消直接退出。
5164
5209
  */
5165
5210
  async function invokeStructuredOutput(options) {
5166
- const outputs = [];
5167
- const { logging } = options;
5168
- let correction;
5169
- let lastError = "structured output failed";
5170
- for (let attempt = 1; attempt <= structuredOutputMaxModelCalls; attempt++) {
5171
- options.signal?.throwIfAborted();
5172
- const prompt = correction === void 0 ? options.inputPrompt : `${options.inputPrompt}\n\n${correction}`;
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;
5173
5235
  try {
5174
- const value = await options.ctx.chatluna.extract(options.schema, {
5175
- prompt,
5176
- system: options.systemPrompt,
5177
- ...options.model === void 0 ? {} : { model: options.model },
5178
- ...options.signal === void 0 ? {} : { signal: options.signal }
5179
- });
5180
- options.signal?.throwIfAborted();
5181
- outputs.push(`[attempt ${attempt}]\n${JSON.stringify(value, null, 2)}`);
5182
- const validationError = options.validateResult?.(value);
5183
- if (validationError === void 0) return {
5184
- value,
5185
- output: outputs.join("\n\n"),
5186
- parseError: null
5187
- };
5188
- lastError = validationError;
5189
- } catch (error) {
5190
- options.signal?.throwIfAborted();
5191
- if (!(error instanceof ProtocolError)) throw error;
5192
- lastError = formatErrorDetails(error);
5193
- outputs.push(`[attempt ${attempt}]\n${lastError}`);
5236
+ fold = await run;
5237
+ } finally {
5238
+ signal?.throwIfAborted();
5194
5239
  }
5195
- logging?.logger.diagnosticSummary((fields) => ({
5196
- event: `${modelStageLabels[logging.stage]}结果解析失败`,
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]}结果解析失败`,
5197
5246
  detail: [
5198
5247
  formatLogScope(fields),
5199
5248
  `调用序号:${attempt}`,
5200
- `原因:${lastError}`
5249
+ `原因:${submission.parseError}`
5201
5250
  ].filter(Boolean).join("; ")
5202
5251
  }));
5203
- correction = formatCorrection(lastError, options.stringifiedArrayField);
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
+ ];
5204
5280
  }
5205
- return {
5206
- value: null,
5207
- output: outputs.join("\n\n"),
5208
- parseError: lastError
5209
- };
5210
5281
  }
5211
- const formatCorrection = (error, stringifiedArrayField) => {
5212
- const instructions = [`结构化结果无效:${error}。`, "必须只输出符合 schema 的 JSON,并完整修正所有字段。"];
5213
- if (stringifiedArrayField != null) instructions.push(`${stringifiedArrayField} 必须直接传 JSON 数组:正确 {"${stringifiedArrayField}":[]};错误 {"${stringifiedArrayField}":"[]"}。`);
5214
- instructions.push("不要在 JSON 之外输出解释性文本。");
5215
- return instructions.join(" ");
5216
- };
5217
5282
  // src/service/workflows/extraction/extractor.ts
5218
5283
  var LivingMemoryExtractor = class {
5219
5284
  ctx;
@@ -5226,25 +5291,23 @@ var LivingMemoryExtractor = class {
5226
5291
  signal?.throwIfAborted();
5227
5292
  if (!isModelConfigured(this.mainModel)) return {
5228
5293
  extracted: [],
5229
- prompt: null,
5230
- output: null,
5231
5294
  skippedReason: "model-not-configured",
5232
5295
  parseError: null
5233
5296
  };
5234
5297
  if (!await this.isModelAvailable()) return {
5235
5298
  extracted: [],
5236
- prompt: null,
5237
- output: null,
5238
5299
  skippedReason: "model-unavailable",
5239
5300
  parseError: null
5240
5301
  };
5241
- const prompt = this.buildPrompt(input, context);
5242
5302
  const result = await invokeStructuredOutput({
5243
5303
  ctx: this.ctx,
5244
5304
  model: this.mainModel,
5245
- schema: extractionResultTool.schema,
5246
- systemPrompt: prompt.systemPrompt,
5247
- inputPrompt: prompt.inputPrompt,
5305
+ tool: extractionResultTool,
5306
+ ...buildExtractionPrompts({
5307
+ chatHistory: input,
5308
+ assistantLabel: resolveScopeAssistantLabel(context),
5309
+ presetPrompt: context.presetPrompt
5310
+ }),
5248
5311
  ...signal === void 0 ? {} : { signal },
5249
5312
  validateResult: ({ memories }) => {
5250
5313
  try {
@@ -5272,8 +5335,6 @@ var LivingMemoryExtractor = class {
5272
5335
  speakerKeys: resolveSpeakerKeysByLabels(item.speakerLabels, context.speakers)
5273
5336
  };
5274
5337
  }) ?? [],
5275
- prompt,
5276
- output: result.output,
5277
5338
  skippedReason: null,
5278
5339
  parseError: result.parseError
5279
5340
  };
@@ -5287,14 +5348,6 @@ var LivingMemoryExtractor = class {
5287
5348
  throw error;
5288
5349
  }
5289
5350
  }
5290
- buildPrompt(input, context) {
5291
- const assistantLabel = resolveScopeAssistantLabel(context);
5292
- return buildExtractionPrompts({
5293
- chatHistory: input,
5294
- assistantLabel,
5295
- presetPrompt: context.presetPrompt
5296
- });
5297
- }
5298
5351
  };
5299
5352
  // src/service/workflows/extraction/coordinator.ts
5300
5353
  const EXTRACTION_FAIL_STREAK_LIMIT = 3;
@@ -5891,7 +5944,7 @@ var LivingMemoryPresetPersonaService = class {
5891
5944
  structuredResult = await invokeStructuredOutput({
5892
5945
  ctx: this.ctx,
5893
5946
  model: this.config.mainModel,
5894
- schema: personaCardResultTool.schema,
5947
+ tool: personaCardResultTool,
5895
5948
  ...buildPersonaCardPrompts({ lines }),
5896
5949
  validateResult: ({ deletedLineNumbers }) => {
5897
5950
  const invalid = deletedLineNumbers.filter((lineNumber) => lineNumber >= lines.length);
@@ -6198,7 +6251,7 @@ var LivingMemoryUserProfileService = class {
6198
6251
  structuredResult = await invokeStructuredOutput({
6199
6252
  ctx: this.ctx,
6200
6253
  model: this.config.mainModel,
6201
- schema: userProfileResultTool.schema,
6254
+ tool: userProfileResultTool,
6202
6255
  ...prompts,
6203
6256
  signal,
6204
6257
  validateResult: ({ action, content }) => {
@@ -6860,21 +6913,16 @@ var DreamSessionHistory = class {
6860
6913
  ctx;
6861
6914
  model;
6862
6915
  logger;
6863
- history = { messages: [] };
6864
- batchStart = 1;
6916
+ messages = [];
6917
+ systemTokens;
6918
+ batchStart = 0;
6865
6919
  inputTokens;
6866
6920
  compressions = 0;
6867
6921
  constructor(ctx, model, systemPrompt, logger) {
6868
6922
  this.ctx = ctx;
6869
6923
  this.model = model;
6870
6924
  this.logger = logger;
6871
- this.history.messages.push({
6872
- role: "system",
6873
- content: textBlocks(systemPrompt)
6874
- });
6875
- }
6876
- get messages() {
6877
- return this.history.messages;
6925
+ this.systemTokens = estimateMessageTokens({ content: textBlocks(systemPrompt) });
6878
6926
  }
6879
6927
  /** 记录上一轮模型上报的输入量;缺失或无效时保留上一次有效值。 */
6880
6928
  recordUsage(usage) {
@@ -6903,42 +6951,42 @@ var DreamSessionHistory = class {
6903
6951
  signal?.throwIfAborted();
6904
6952
  if (this.inputTokens !== void 0 && this.inputTokens >= 2e5) await this.summarizeEarlierBatches(this.inputTokens, signal);
6905
6953
  signal?.throwIfAborted();
6906
- const tokens = this.messages.reduce((total, message) => total + estimateMessageTokens(message), 0);
6954
+ const tokens = this.messages.reduce((total, message) => total + estimateMessageTokens(message), this.systemTokens);
6907
6955
  if (tokens > maxTokenLimit) throw new Error(`Dream 输入超过模型可用预算:${tokens} tokens。`);
6908
- return [...this.messages];
6956
+ return this.messages;
6909
6957
  }
6910
6958
  async summarizeEarlierBatches(tokensBefore, signal) {
6911
- if (this.batchStart <= 1) throw new Error("当前 Dream 批次已达到 200k,且没有可压缩的更早批次。");
6912
- const transcript = JSON.stringify(this.messages.slice(1, this.batchStart));
6959
+ if (this.batchStart === 0) throw new Error("当前 Dream 批次已达到 200k,且没有可压缩的更早批次。");
6960
+ const earlier = this.messages.slice(0, this.batchStart);
6913
6961
  const attempt = ++this.compressions;
6914
6962
  this.logger.diagnosticSummary((fields) => ({
6915
6963
  event: "Dream 上下文压缩开始",
6916
6964
  detail: `${formatLogScope(fields)}; 压缩序号:${attempt}; 压缩前输入量:${tokensBefore} tokens`
6917
6965
  }));
6918
- const prompt = buildDreamHistorySummaryPrompts(transcript);
6966
+ const prompt = buildDreamHistorySummaryPrompts(JSON.stringify(earlier));
6919
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));
6920
6970
  const run = this.ctx.chatluna.chat({
6921
6971
  model: this.model,
6922
6972
  system: prompt.systemPrompt,
6923
6973
  messages: [{
6924
6974
  role: "user",
6925
6975
  content: textBlocks(prompt.inputPrompt)
6926
- }]
6976
+ }],
6977
+ beforeDispatch: log.beforeDispatch
6927
6978
  });
6928
- if (signal !== void 0) signal.addEventListener("abort", () => run.abort(), { once: true });
6979
+ using cancellation = signal && addAbortListener(signal, () => run.abort(signal.reason));
6929
6980
  const fold = await run;
6981
+ log.response(fold);
6930
6982
  signal?.throwIfAborted();
6931
- const summary = stringifyModelContent(fold.content).trim();
6983
+ const summary = fold.text.trim();
6932
6984
  if (!summary) throw new Error("Dream 历史压缩未返回有效摘要。");
6933
- this.history.messages = [
6934
- this.messages[0],
6935
- {
6936
- role: "user",
6937
- content: textBlocks(formatXmlBlock("dream_history_summary", summary).join("\n"))
6938
- },
6939
- ...this.messages.slice(this.batchStart)
6940
- ];
6941
- 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;
6942
6990
  this.inputTokens = void 0;
6943
6991
  this.logger.diagnosticSummary((fields) => ({
6944
6992
  event: "Dream 上下文压缩完成",
@@ -6958,14 +7006,6 @@ async function runDreamSession(input) {
6958
7006
  signal?.throwIfAborted();
6959
7007
  const systemPrompt = buildDreamSystemPrompt(input.assistantLabel, input.presetPrompt);
6960
7008
  const history = new DreamSessionHistory(ctx, model, systemPrompt, logger);
6961
- logger.diagnosticSummary((fields) => ({
6962
- event: "Dream 会话开始",
6963
- detail: formatLogScope(fields),
6964
- blocks: [{
6965
- title: "系统消息",
6966
- value: systemPrompt
6967
- }]
6968
- }));
6969
7009
  while (advanceDreamBatch(state) !== void 0) {
6970
7010
  signal?.throwIfAborted();
6971
7011
  let speakers = input.speakers;
@@ -6994,24 +7034,19 @@ async function runDreamSession(input) {
6994
7034
  history.startBatch(batchPrompt);
6995
7035
  batchLogger.diagnosticSummary((fields) => ({
6996
7036
  event: "Dream 批次开始",
6997
- detail: `${formatLogScope(fields)}; 批次:${batch.id}; 总批次:${state.batches.length}; 记忆:${batch.entries.length} 条`,
6998
- blocks: [{
6999
- title: "用户消息",
7000
- value: batchPrompt
7001
- }]
7037
+ detail: `${formatLogScope(fields)}; 批次:${batch.id}; 总批次:${state.batches.length}; 记忆:${batch.entries.length} 条`
7002
7038
  }));
7003
7039
  const loop = new LivingMemoryToolLoop({
7004
7040
  ctx,
7005
7041
  model,
7006
7042
  system: systemPrompt,
7007
- input: batchPrompt,
7008
7043
  tools,
7009
7044
  logger: batchLogger,
7010
7045
  stage: "dream",
7011
7046
  multipleToolCalls: "sequential",
7012
- history: history.history,
7047
+ history,
7013
7048
  prepareMessages: () => history.prepareMessages(maxTokenLimit, signal),
7014
- onModelCall: ({ fold }) => history.recordUsage(fold.usage),
7049
+ onModelCall: (fold) => history.recordUsage(fold.usage),
7015
7050
  ...signal === void 0 ? {} : { signal }
7016
7051
  });
7017
7052
  let ineffectiveRounds = 0;
@@ -7253,7 +7288,7 @@ var LivingMemoryDreamWorkerClient = class {
7253
7288
  }, transferList);
7254
7289
  } catch (error) {
7255
7290
  this.pending.delete(id);
7256
- reject(toError$1(error));
7291
+ reject(toError(error));
7257
7292
  }
7258
7293
  });
7259
7294
  }
@@ -7901,10 +7936,14 @@ const livingMemoryWebUI = (ctx, ui) => {
7901
7936
  ctx.chatluna_webui.state("livingmemory.status", {
7902
7937
  get: async () => ({
7903
7938
  ...ui.admin.status,
7904
- presets: await ui.admin.listPresetIds()
7939
+ presets: await ui.admin.listPresetIds(),
7940
+ nativeMemoryActive: ctx.get("memory") !== void 0
7905
7941
  }),
7906
7942
  refreshOn
7907
7943
  });
7944
+ ctx.on("internal/service", (name) => {
7945
+ if (name === "memory") ctx.chatluna_webui.refresh("livingmemory.status");
7946
+ });
7908
7947
  ctx.chatluna_webui.action("livingmemory.create", { input: Schema$1.object({
7909
7948
  presetId: Schema$1.string().required(),
7910
7949
  conversationId: Schema$1.string(),
@@ -8452,7 +8491,8 @@ function* turnInputs(message) {
8452
8491
  };
8453
8492
  return;
8454
8493
  }
8455
- if (message.role !== "user" || source.kind !== "user" || form === "snapshot" || meta?.backfill) return;
8494
+ if (message.role !== "user" || source.kind !== "user" || form === "snapshot") return;
8495
+ if (meta && "backfill" in meta && meta.backfill) return;
8456
8496
  const envelopes = message.content.filter((block) => block.type === "envelope");
8457
8497
  if (!envelopes.length) {
8458
8498
  if (source.routeId !== void 0 || meta?.externalId !== void 0) yield {
@@ -8719,9 +8759,9 @@ const modelField = (description, modality) => modelAddressSchema({
8719
8759
  * 界面语义与取值范围,避免两处默认值漂移。
8720
8760
  */
8721
8761
  const Config = Schema.intersect([
8722
- Schema.object({ debug: Schema.boolean().label("调试日志").description("记录召回、提取、Dream 每次模型调用的完整提示词、原始响应与诊断事件。").default(DEFAULT_CONFIG.debug) }).description("基础配置"),
8762
+ Schema.object({ debug: Schema.boolean().label("调试日志").description("记录 LivingMemory 每次调用对话模型时的提示词、消息和模型响应。").default(DEFAULT_CONFIG.debug) }).description("基础配置"),
8723
8763
  Schema.object({
8724
- mainModel: modelField("主 LLM 模型,用于提取记忆、Dream 与用户画像。", "chat").label("主模型"),
8764
+ mainModel: modelField("选择支持工具调用的模型,用于提取记忆、整理记忆、更新人物画像和人设卡。", "chat").label("主模型"),
8725
8765
  subModel: modelField("子 LLM 模型,用于召回记忆。", "chat").label("召回模型"),
8726
8766
  embeddingModel: modelField("将记忆和查询文本转换为向量,供检索和 Dream 比较语义相似度。", "embed").label("嵌入模型"),
8727
8767
  rerankModel: modelField("可选。按候选记忆与查询的相关性重新排列检索结果。", "rerank").label("重排序模型")