|
|
@@ -1,42 +1,33 @@
|
|
|
package com.zsjz.ai.module.ai.service.impl;
|
|
|
|
|
|
-import io.agentscope.core.agent.RuntimeContext;
|
|
|
-import io.agentscope.core.message.Msg;
|
|
|
-import io.agentscope.core.message.MsgRole;
|
|
|
-import io.agentscope.core.message.TextBlock;
|
|
|
-import io.agentscope.core.model.ChatResponse;
|
|
|
-import io.agentscope.core.model.ChatUsage;
|
|
|
-import io.agentscope.core.model.GenerateOptions;
|
|
|
-import io.agentscope.core.model.Model;
|
|
|
-import io.agentscope.harness.agent.workspace.WorkspaceManager;
|
|
|
-import lombok.RequiredArgsConstructor;
|
|
|
-import lombok.extern.slf4j.Slf4j;
|
|
|
+import com.zsjz.ai.common.compat.JsonUtils;
|
|
|
+import com.zsjz.ai.common.compat.ServiceException;
|
|
|
+import com.zsjz.ai.common.compat.StringUtils;
|
|
|
import com.zsjz.ai.module.ai.core.agent.AgentRegistry;
|
|
|
import com.zsjz.ai.module.ai.core.agent.AiRuntimeConfigStore;
|
|
|
import com.zsjz.ai.module.ai.core.agent.AiRuntimeKeys;
|
|
|
-import com.zsjz.ai.module.ai.core.memory.AiMemoryAuditLogger;
|
|
|
-import com.zsjz.ai.module.ai.core.memory.AiMemoryDeclaredStore;
|
|
|
-import com.zsjz.ai.module.ai.core.memory.AiMemoryExtractionService;
|
|
|
-import com.zsjz.ai.module.ai.core.memory.AiMemoryPrompts;
|
|
|
-import com.zsjz.ai.module.ai.core.memory.AiMemorySanitizer;
|
|
|
-import com.zsjz.ai.module.ai.core.memory.AiMemoryVersionStore;
|
|
|
+import com.zsjz.ai.module.ai.core.memory.*;
|
|
|
import com.zsjz.ai.module.ai.core.memory.spi.MemoryBackendStats;
|
|
|
import com.zsjz.ai.module.ai.domain.AiAgent;
|
|
|
import com.zsjz.ai.module.ai.domain.bo.AiMemoryConfigBo;
|
|
|
import com.zsjz.ai.module.ai.domain.bo.AiMemoryContentBo;
|
|
|
import com.zsjz.ai.module.ai.domain.bo.AiMemoryDeclaredBo;
|
|
|
import com.zsjz.ai.module.ai.domain.dto.ChatTokenUsage;
|
|
|
-import com.zsjz.ai.module.ai.domain.vo.AiMemoryContentVo;
|
|
|
-import com.zsjz.ai.module.ai.domain.vo.AiMemoryDeclaredVo;
|
|
|
-import com.zsjz.ai.module.ai.domain.vo.AiMemoryFileVo;
|
|
|
-import com.zsjz.ai.module.ai.domain.vo.AiMemoryQualityVo;
|
|
|
-import com.zsjz.ai.module.ai.domain.vo.AiMemoryVersionVo;
|
|
|
+import com.zsjz.ai.module.ai.domain.vo.*;
|
|
|
import com.zsjz.ai.module.ai.service.IAiAgentService;
|
|
|
import com.zsjz.ai.module.ai.service.IAiMemoryService;
|
|
|
import com.zsjz.ai.module.ai.service.IAiUsageStatService;
|
|
|
-import com.zsjz.ai.common.compat.ServiceException;
|
|
|
-import com.zsjz.ai.common.compat.StringUtils;
|
|
|
-import com.zsjz.ai.common.compat.JsonUtils;
|
|
|
+import io.agentscope.core.agent.RuntimeContext;
|
|
|
+import io.agentscope.core.message.Msg;
|
|
|
+import io.agentscope.core.message.MsgRole;
|
|
|
+import io.agentscope.core.message.TextBlock;
|
|
|
+import io.agentscope.core.model.ChatResponse;
|
|
|
+import io.agentscope.core.model.ChatUsage;
|
|
|
+import io.agentscope.core.model.GenerateOptions;
|
|
|
+import io.agentscope.core.model.Model;
|
|
|
+import io.agentscope.harness.agent.workspace.WorkspaceManager;
|
|
|
+import lombok.RequiredArgsConstructor;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
|
import java.io.IOException;
|
|
|
@@ -44,17 +35,10 @@ import java.nio.charset.StandardCharsets;
|
|
|
import java.nio.file.Files;
|
|
|
import java.nio.file.Path;
|
|
|
import java.nio.file.StandardCopyOption;
|
|
|
-import java.time.Duration;
|
|
|
-import java.time.Instant;
|
|
|
-import java.time.LocalDate;
|
|
|
-import java.time.OffsetDateTime;
|
|
|
-import java.time.ZoneId;
|
|
|
+import java.time.*;
|
|
|
import java.time.format.DateTimeFormatter;
|
|
|
import java.time.format.DateTimeParseException;
|
|
|
-import java.util.ArrayList;
|
|
|
-import java.util.Comparator;
|
|
|
-import java.util.List;
|
|
|
-import java.util.Map;
|
|
|
+import java.util.*;
|
|
|
import java.util.regex.Pattern;
|
|
|
import java.util.stream.Stream;
|
|
|
|
|
|
@@ -126,7 +110,7 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
* 允许读写的工作区相对路径:仅长期记忆与每日流水,避免越权访问其它工作区文件
|
|
|
*/
|
|
|
private static final Pattern ALLOWED_PATH =
|
|
|
- Pattern.compile("^(MEMORY\\.md|memory/[A-Za-z0-9._-]{1,64}\\.md)$");
|
|
|
+ Pattern.compile("^(MEMORY\\.md|memory/[A-Za-z0-9._-]{1,64}\\.md)$");
|
|
|
|
|
|
/**
|
|
|
* 手动合并的最长等待时间
|
|
|
@@ -183,7 +167,7 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
continue;
|
|
|
}
|
|
|
files.add(buildFile(path, fileNameOf(path), "DAILY", dateOf(path),
|
|
|
- readQuietly(workspace, ctx, path)));
|
|
|
+ readQuietly(workspace, ctx, path)));
|
|
|
}
|
|
|
return files;
|
|
|
}
|
|
|
@@ -215,26 +199,26 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
if (memoryFile) {
|
|
|
// 人工编辑 MEMORY.md:覆盖前必须成功留下旧版本,失败则中止本次写入
|
|
|
snapshotMemory(workspace.getMemoryDir(ctx), readMemoryMd(workspace, ctx),
|
|
|
- "PRE_MANUAL", bo.getUserId(), "人工编辑前自动快照", null);
|
|
|
+ "PRE_MANUAL", bo.getUserId(), "人工编辑前自动快照", null);
|
|
|
}
|
|
|
workspace.writeUtf8WorkspaceRelative(ctx, safePath, saved);
|
|
|
if (memoryFile) {
|
|
|
snapshotMemory(workspace.getMemoryDir(ctx), saved, "MANUAL",
|
|
|
- bo.getUserId(), "人工编辑", null);
|
|
|
+ bo.getUserId(), "人工编辑", null);
|
|
|
}
|
|
|
if (sanitized.changed()) {
|
|
|
log.info("长期记忆人工编辑已净化:agent={}, userId={}, path={}, 丢弃 {} 条, 去重 {} 条, "
|
|
|
- + "脱敏 {} 处, 截断 {} 条",
|
|
|
- definition.getAgentCode(), bo.getUserId(), safePath, sanitized.dropped(),
|
|
|
- sanitized.deduped(), sanitized.redacted(), sanitized.truncated());
|
|
|
+ + "脱敏 {} 处, 截断 {} 条",
|
|
|
+ definition.getAgentCode(), bo.getUserId(), safePath, sanitized.dropped(),
|
|
|
+ sanitized.deduped(), sanitized.redacted(), sanitized.truncated());
|
|
|
}
|
|
|
auditLogger.record(definition.getId(), bo.getCaseId(), bo.getUserId(),
|
|
|
- AiMemoryAuditLogger.EVENT_MANUAL_EDIT, "OK",
|
|
|
- Map.of("path", safePath, "charsBefore", content.length(), "charsAfter", saved.length(),
|
|
|
- "dropped", sanitized.dropped(), "deduped", sanitized.deduped(),
|
|
|
- "redacted", sanitized.redacted(), "truncated", sanitized.truncated()));
|
|
|
+ AiMemoryAuditLogger.EVENT_MANUAL_EDIT, "OK",
|
|
|
+ Map.of("path", safePath, "charsBefore", content.length(), "charsAfter", saved.length(),
|
|
|
+ "dropped", sanitized.dropped(), "deduped", sanitized.deduped(),
|
|
|
+ "redacted", sanitized.redacted(), "truncated", sanitized.truncated()));
|
|
|
log.info("长期记忆已更新:agent={}, userId={}, path={}, chars={}",
|
|
|
- definition.getAgentCode(), bo.getUserId(), safePath, saved.length());
|
|
|
+ definition.getAgentCode(), bo.getUserId(), safePath, saved.length());
|
|
|
}
|
|
|
|
|
|
@Override
|
|
|
@@ -255,10 +239,10 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
Path memoryDir = workspace.getMemoryDir(ctx);
|
|
|
Instant previousWatermark = readConsolidationWatermark(memoryDir);
|
|
|
List<DailyLedger> pending = loadPendingLedgers(
|
|
|
- workspace, ctx, definition, caseId, userId, previousWatermark);
|
|
|
+ workspace, ctx, definition, caseId, userId, previousWatermark);
|
|
|
if (pending.isEmpty()) {
|
|
|
log.info("长期记忆合并跳过(无待合并流水):agent={}, userId={}, watermark={}",
|
|
|
- definition.getAgentCode(), userId, formatInstant(previousWatermark));
|
|
|
+ definition.getAgentCode(), userId, formatInstant(previousWatermark));
|
|
|
return;
|
|
|
}
|
|
|
// 在净化回写之后取本轮开始时间:否则回写刷新的 mtime 会晚于水位,
|
|
|
@@ -270,7 +254,7 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
String memoryBefore = StringUtils.defaultString(memoryMd);
|
|
|
// 合并是整文件覆盖:先记录合并前版本,快照失败则中止本次合并
|
|
|
snapshotMemory(memoryDir, memoryMd, "PRE_CONSOLIDATE", userId,
|
|
|
- "合并前自动快照", null);
|
|
|
+ "合并前自动快照", null);
|
|
|
long started = System.currentTimeMillis();
|
|
|
int batches = 0;
|
|
|
int mergedFiles = 0;
|
|
|
@@ -298,10 +282,10 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
memoryMd = mergedContent;
|
|
|
if (merged.changed()) {
|
|
|
auditLogger.record(definition.getId(), caseId, userId,
|
|
|
- AiMemoryAuditLogger.EVENT_SANITIZE, "OK",
|
|
|
- Map.of("stage", "consolidationOutput", "batch", batches + 1,
|
|
|
- "dropped", merged.dropped(), "deduped", merged.deduped(),
|
|
|
- "redacted", merged.redacted(), "truncated", merged.truncated()));
|
|
|
+ AiMemoryAuditLogger.EVENT_SANITIZE, "OK",
|
|
|
+ Map.of("stage", "consolidationOutput", "batch", batches + 1,
|
|
|
+ "dropped", merged.dropped(), "deduped", merged.deduped(),
|
|
|
+ "redacted", merged.redacted(), "truncated", merged.truncated()));
|
|
|
}
|
|
|
int tokens = result.usage() == null ? 0 : result.usage().totalTokens();
|
|
|
recordConsolidationUsage(definition, userId, result.usage());
|
|
|
@@ -315,38 +299,38 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
Instant checkpoint = nextWatermark(pending, index, runStart, previousWatermark);
|
|
|
workspace.writeUtf8WorkspaceRelative(ctx, CONSOLIDATION_STATE_PATH, checkpoint.toString());
|
|
|
log.info("长期记忆合并批次完成:agent={}, userId={}, batch={}, files={}, chars={}, tokens={}",
|
|
|
- definition.getAgentCode(), userId, batches, batch.size(), ledger.length(), tokens);
|
|
|
+ definition.getAgentCode(), userId, batches, batch.size(), ledger.length(), tokens);
|
|
|
}
|
|
|
|
|
|
int remaining = pending.size() - index;
|
|
|
if (remaining > 0) {
|
|
|
log.warn("长期记忆合并达到单轮批次上限,剩余 {} 个流水待下一轮:agent={}, userId={}",
|
|
|
- remaining, definition.getAgentCode(), userId);
|
|
|
+ remaining, definition.getAgentCode(), userId);
|
|
|
}
|
|
|
snapshotMemory(memoryDir, memoryMd, "CONSOLIDATE", userId,
|
|
|
- "合并后自动快照", null);
|
|
|
+ "合并后自动快照", null);
|
|
|
long elapsed = System.currentTimeMillis() - started;
|
|
|
auditLogger.record(definition.getId(), caseId, userId, AiMemoryAuditLogger.EVENT_CONSOLIDATE, "OK",
|
|
|
- Map.of("batches", batches, "files", mergedFiles, "remaining", remaining,
|
|
|
- "ledgerChars", mergedChars, "memoryCharsBefore", memoryBefore.length(),
|
|
|
- "memoryCharsAfter", StringUtils.length(memoryMd), "elapsedMs", elapsed,
|
|
|
- "tokens", totalTokens));
|
|
|
+ Map.of("batches", batches, "files", mergedFiles, "remaining", remaining,
|
|
|
+ "ledgerChars", mergedChars, "memoryCharsBefore", memoryBefore.length(),
|
|
|
+ "memoryCharsAfter", StringUtils.length(memoryMd), "elapsedMs", elapsed,
|
|
|
+ "tokens", totalTokens));
|
|
|
log.info("长期记忆合并完成:agent={}, userId={}, 批次 {}, 文件 {}, 流水 {} 字符, "
|
|
|
- + "MEMORY.md {} 字符 → {} 字符, tokens={}, 耗时={}ms",
|
|
|
- definition.getAgentCode(), userId, batches, mergedFiles, mergedChars,
|
|
|
- memoryBefore.length(), StringUtils.length(memoryMd), totalTokens, elapsed);
|
|
|
+ + "MEMORY.md {} 字符 → {} 字符, tokens={}, 耗时={}ms",
|
|
|
+ definition.getAgentCode(), userId, batches, mergedFiles, mergedChars,
|
|
|
+ memoryBefore.length(), StringUtils.length(memoryMd), totalTokens, elapsed);
|
|
|
} catch (RuntimeException e) {
|
|
|
// 部分批次可能已覆盖 MEMORY.md:尽力记录当前状态,便于恢复
|
|
|
try {
|
|
|
snapshotMemory(memoryDir, readMemoryMd(workspace, ctx), "CONSOLIDATE_PARTIAL", userId,
|
|
|
- "合并中断快照", null);
|
|
|
+ "合并中断快照", null);
|
|
|
} catch (Exception snapshotError) {
|
|
|
log.warn("合并中断版本快照失败:userId={}, err={}", userId, snapshotError.getMessage());
|
|
|
}
|
|
|
auditLogger.record(definition.getId(), caseId, userId,
|
|
|
- AiMemoryAuditLogger.EVENT_CONSOLIDATE, "FAIL",
|
|
|
- Map.of("reason", StringUtils.defaultIfBlank(e.getMessage(), "未知错误"),
|
|
|
- "batches", batches, "files", mergedFiles));
|
|
|
+ AiMemoryAuditLogger.EVENT_CONSOLIDATE, "FAIL",
|
|
|
+ Map.of("reason", StringUtils.defaultIfBlank(e.getMessage(), "未知错误"),
|
|
|
+ "batches", batches, "files", mergedFiles));
|
|
|
throw e;
|
|
|
}
|
|
|
}
|
|
|
@@ -366,9 +350,9 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
int moved = 0;
|
|
|
try (Stream<Path> files = Files.list(memoryDir)) {
|
|
|
List<Path> expired = files.filter(Files::isRegularFile)
|
|
|
- .filter(path -> path.getFileName().toString().endsWith(".md"))
|
|
|
- .filter(path -> isOnOrBefore(path, cutoff))
|
|
|
- .toList();
|
|
|
+ .filter(path -> path.getFileName().toString().endsWith(".md"))
|
|
|
+ .filter(path -> isOnOrBefore(path, cutoff))
|
|
|
+ .toList();
|
|
|
if (!expired.isEmpty()) {
|
|
|
Files.createDirectories(archiveDir);
|
|
|
}
|
|
|
@@ -380,12 +364,12 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
throw new ServiceException("记忆归档失败:" + e.getMessage());
|
|
|
}
|
|
|
log.info("长期记忆归档完成:agent={}, userId={}, 归档 {} 个流水文件(保留 {} 天)",
|
|
|
- definition.getAgentCode(), userId, moved, days);
|
|
|
+ definition.getAgentCode(), userId, moved, days);
|
|
|
if (moved > 0) {
|
|
|
// 无文件搬动时不记审计,避免每个用户每天都产生一条空事件
|
|
|
auditLogger.record(definition.getId(), caseId, userId,
|
|
|
- AiMemoryAuditLogger.EVENT_ARCHIVE, "OK",
|
|
|
- Map.of("moved", moved, "retentionDays", days));
|
|
|
+ AiMemoryAuditLogger.EVENT_ARCHIVE, "OK",
|
|
|
+ Map.of("moved", moved, "retentionDays", days));
|
|
|
}
|
|
|
return moved;
|
|
|
}
|
|
|
@@ -402,7 +386,7 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
removed += deleteExpiredMemoryFiles(memoryDir, dailyCutoff);
|
|
|
// 归档目录使用独立的保留期,避免与每日流水保留期相同导致「归档即删除」
|
|
|
LocalDate archiveCutoff = LocalDate.now()
|
|
|
- .minusDays(Math.max(1, policy.getArchiveRetentionDays()));
|
|
|
+ .minusDays(Math.max(1, policy.getArchiveRetentionDays()));
|
|
|
removed += deleteExpiredMemoryFiles(memoryDir.resolve(ARCHIVE_DIR), archiveCutoff);
|
|
|
// 会话态记忆(工作区 session 日志):按会话保留天数清理
|
|
|
LocalDate sessionCutoff = LocalDate.now().minusDays(Math.max(1, policy.getSessionRetentionDays()));
|
|
|
@@ -411,15 +395,15 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
int prunedWatermarks = extractionService.pruneWatermarks(memoryDir, caseId, userId, sessionCutoff);
|
|
|
// 净化原文备份:按保留期清理,避免敏感原文无限增长
|
|
|
removed += deleteExpiredByMtime(memoryDir.resolve(QUARANTINE_DIR),
|
|
|
- LocalDate.now().minusDays(Math.max(1, policy.getQuarantineRetentionDays())));
|
|
|
+ LocalDate.now().minusDays(Math.max(1, policy.getQuarantineRetentionDays())));
|
|
|
// 审计日志按行时间裁剪,保留近期事件
|
|
|
int auditPruned = pruneAudit(memoryDir.resolve(AiMemoryAuditLogger.AUDIT_FILE),
|
|
|
- LocalDate.now().minusDays(Math.max(1, policy.getAuditRetentionDays())));
|
|
|
+ LocalDate.now().minusDays(Math.max(1, policy.getAuditRetentionDays())));
|
|
|
log.info("长期记忆清理完成:agent={}, userId={}, 删除 {} 个文件(流水 {} 天 / 归档 {} 天 / 会话 {} 天),"
|
|
|
- + "审计裁剪 {} 行(保留 {} 天),抽取水位裁剪 {} 条",
|
|
|
- definition.getAgentCode(), userId, removed, policy.getDailyFileRetentionDays(),
|
|
|
- policy.getArchiveRetentionDays(), policy.getSessionRetentionDays(),
|
|
|
- auditPruned, policy.getAuditRetentionDays(), prunedWatermarks);
|
|
|
+ + "审计裁剪 {} 行(保留 {} 天),抽取水位裁剪 {} 条",
|
|
|
+ definition.getAgentCode(), userId, removed, policy.getDailyFileRetentionDays(),
|
|
|
+ policy.getArchiveRetentionDays(), policy.getSessionRetentionDays(),
|
|
|
+ auditPruned, policy.getAuditRetentionDays(), prunedWatermarks);
|
|
|
return removed;
|
|
|
}
|
|
|
|
|
|
@@ -429,7 +413,11 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
WorkspaceManager workspace = workspaceOf(definition, caseId);
|
|
|
RuntimeContext ctx = contextOf(userId, caseId);
|
|
|
Path memoryDir = workspace.getMemoryDir(ctx);
|
|
|
- deleteRecursively(memoryDir);
|
|
|
+ // 删除前留一份 MEMORY.md 版本快照:误删可从「版本历史」恢复正文;
|
|
|
+ // 快照存放在 memoryDir/history 下,因此下面的清理必须保留该目录
|
|
|
+ String snapshotId = snapshotMemory(memoryDir, readMemoryMd(workspace, ctx), "PRE_DELETE",
|
|
|
+ userId, "删除长期记忆前自动快照", null);
|
|
|
+ deleteMemoryContentKeepingVersions(memoryDir);
|
|
|
try {
|
|
|
Files.deleteIfExists(workspace.resolveRuntimeDataPath(ctx, MEMORY_MD));
|
|
|
} catch (IOException e) {
|
|
|
@@ -437,10 +425,11 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
}
|
|
|
// 清空后写入截止消息 ID:避免下一轮把历史会话重新抽取回来
|
|
|
extractionService.markCleared(memoryDir);
|
|
|
- log.info("长期记忆已删除:caseId={}, agent={}, userId={}", caseId,
|
|
|
- definition.getAgentCode(), userId);
|
|
|
- auditLogger.record(definition.getId(), caseId, userId,
|
|
|
- AiMemoryAuditLogger.EVENT_DELETE, "OK", null);
|
|
|
+ log.info("长期记忆已删除:caseId={}, agent={}, userId={}, snapshot={}", caseId, definition.getAgentCode(), userId,
|
|
|
+ Objects.toString(snapshotId, "(无)"));
|
|
|
+ auditLogger.record(definition.getId(), caseId, userId, AiMemoryAuditLogger.EVENT_DELETE, "OK",
|
|
|
+ Map.of("snapshotId", StringUtils.defaultString(snapshotId)));
|
|
|
+
|
|
|
}
|
|
|
|
|
|
@Override
|
|
|
@@ -455,8 +444,8 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
Instant watermark = readConsolidationWatermark(memoryDir);
|
|
|
try (Stream<Path> files = Files.list(memoryDir)) {
|
|
|
return files.filter(Files::isRegularFile)
|
|
|
- .filter(path -> LEDGER_FILE_PATTERN.matcher(path.getFileName().toString()).matches())
|
|
|
- .anyMatch(path -> lastModified(path).isAfter(watermark));
|
|
|
+ .filter(path -> LEDGER_FILE_PATTERN.matcher(path.getFileName().toString()).matches())
|
|
|
+ .anyMatch(path -> lastModified(path).isAfter(watermark));
|
|
|
} catch (IOException e) {
|
|
|
log.warn("读取待合并流水失败:userId={}, err={}", userId, e.getMessage());
|
|
|
return false;
|
|
|
@@ -473,11 +462,11 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
}
|
|
|
try (Stream<Path> dirs = Files.list(root)) {
|
|
|
return dirs.filter(Files::isDirectory)
|
|
|
- .filter(dir -> dir.getFileName().toString().matches("\\d{1,19}"))
|
|
|
- .filter(this::hasMemoryData)
|
|
|
- .map(dir -> Long.valueOf(dir.getFileName().toString()))
|
|
|
- .sorted()
|
|
|
- .toList();
|
|
|
+ .filter(dir -> dir.getFileName().toString().matches("\\d{1,19}"))
|
|
|
+ .filter(this::hasMemoryData)
|
|
|
+ .map(dir -> Long.valueOf(dir.getFileName().toString()))
|
|
|
+ .sorted()
|
|
|
+ .toList();
|
|
|
} catch (IOException e) {
|
|
|
log.warn("扫描记忆用户目录失败:agent={}, err={}", definition.getAgentCode(), e.getMessage());
|
|
|
return List.of();
|
|
|
@@ -494,11 +483,11 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
int memoryChars = StringUtils.length(memory);
|
|
|
AuditSummary audit = summarizeAudit(memoryDir);
|
|
|
return new MemoryBackendStats(caseId, agentId, userId == null ? 0L : userId, memoryChars,
|
|
|
- memoryChars / CHARS_PER_TOKEN, countLedgerFiles(memoryDir),
|
|
|
- countLedgerFiles(memoryDir.resolve(ARCHIVE_DIR)),
|
|
|
- formatInstant(readConsolidationWatermark(memoryDir)), audit.lastArchivedAt(),
|
|
|
- audit.failedCount(), audit.lastBatches(), audit.lastMergedFiles(),
|
|
|
- audit.lastRemainingFiles());
|
|
|
+ memoryChars / CHARS_PER_TOKEN, countLedgerFiles(memoryDir),
|
|
|
+ countLedgerFiles(memoryDir.resolve(ARCHIVE_DIR)),
|
|
|
+ formatInstant(readConsolidationWatermark(memoryDir)), audit.lastArchivedAt(),
|
|
|
+ audit.failedCount(), audit.lastBatches(), audit.lastMergedFiles(),
|
|
|
+ audit.lastRemainingFiles());
|
|
|
}
|
|
|
|
|
|
@Override
|
|
|
@@ -548,7 +537,7 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
String event = String.valueOf(entryLine.getOrDefault("event", ""));
|
|
|
String result = String.valueOf(entryLine.getOrDefault("result", ""));
|
|
|
Map<String, Object> detail = entryLine.get("detail") instanceof Map<?, ?> map
|
|
|
- ? (Map<String, Object>) map : Map.of();
|
|
|
+ ? (Map<String, Object>) map : Map.of();
|
|
|
if (AiMemoryAuditLogger.EVENT_FLUSH_WRITE.equals(event)) {
|
|
|
if ("FAIL".equals(result)) {
|
|
|
quality.setExtractFailures(quality.getExtractFailures() + 1);
|
|
|
@@ -628,8 +617,8 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
AiAgent definition = agentService.getEnabledAgent(agentId);
|
|
|
Long memoryAgentId = memoryAgentIdOf(definition);
|
|
|
return memoryDeclaredStore.listAll(caseId, memoryAgentId, String.valueOf(userId)).stream()
|
|
|
- .map(this::toDeclaredVo)
|
|
|
- .toList();
|
|
|
+ .map(this::toDeclaredVo)
|
|
|
+ .toList();
|
|
|
}
|
|
|
|
|
|
@Override
|
|
|
@@ -644,11 +633,11 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
String evidence = bo.getEvidence() == null ? "" : sanitizer.sanitizeLedger(bo.getEvidence()).content();
|
|
|
try {
|
|
|
AiMemoryDeclaredStore.DeclaredMemory entry = memoryDeclaredStore.append(
|
|
|
- bo.getCaseId(), memoryAgentId, String.valueOf(bo.getUserId()), fact, evidence);
|
|
|
+ bo.getCaseId(), memoryAgentId, String.valueOf(bo.getUserId()), fact, evidence);
|
|
|
auditLogger.record(definition.getId(), bo.getCaseId(), bo.getUserId(),
|
|
|
- AiMemoryAuditLogger.EVENT_USER_REMEMBER, "OK",
|
|
|
- Map.of("entryId", entry.id(), "chars", entry.fact().length(),
|
|
|
- "redacted", sanitized.redacted()));
|
|
|
+ AiMemoryAuditLogger.EVENT_USER_REMEMBER, "OK",
|
|
|
+ Map.of("entryId", entry.id(), "chars", entry.fact().length(),
|
|
|
+ "redacted", sanitized.redacted()));
|
|
|
return toDeclaredVo(entry);
|
|
|
} catch (IllegalArgumentException | IllegalStateException e) {
|
|
|
throw new ServiceException(e.getMessage());
|
|
|
@@ -662,8 +651,8 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
boolean revoked = memoryDeclaredStore.revoke(caseId, memoryAgentId, String.valueOf(userId), entryId);
|
|
|
if (revoked) {
|
|
|
auditLogger.record(definition.getId(), caseId, userId,
|
|
|
- AiMemoryAuditLogger.EVENT_USER_FORGET, "OK",
|
|
|
- Map.of("entryId", entryId));
|
|
|
+ AiMemoryAuditLogger.EVENT_USER_FORGET, "OK",
|
|
|
+ Map.of("entryId", entryId));
|
|
|
}
|
|
|
return revoked;
|
|
|
}
|
|
|
@@ -692,12 +681,12 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
Path memoryDir = workspace.getMemoryDir(ctx);
|
|
|
String current = readMemoryMd(workspace, ctx);
|
|
|
return memoryVersionStore.list(memoryDir).stream()
|
|
|
- .map(entry -> {
|
|
|
- AiMemoryVersionVo vo = toVersionVo(entry, null, current);
|
|
|
- vo.setCurrent(memoryVersionStore.matches(entry, current));
|
|
|
- return vo;
|
|
|
- })
|
|
|
- .toList();
|
|
|
+ .map(entry -> {
|
|
|
+ AiMemoryVersionVo vo = toVersionVo(entry, null, current);
|
|
|
+ vo.setCurrent(memoryVersionStore.matches(entry, current));
|
|
|
+ return vo;
|
|
|
+ })
|
|
|
+ .toList();
|
|
|
}
|
|
|
|
|
|
@Override
|
|
|
@@ -726,7 +715,7 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
}
|
|
|
// 恢复前先保存当前版本:即使恢复选错,也能再回退
|
|
|
snapshotMemory(memoryDir, current, "PRE_RESTORE", userId,
|
|
|
- StringUtils.defaultIfBlank(note, "恢复前自动快照"), versionId);
|
|
|
+ StringUtils.defaultIfBlank(note, "恢复前自动快照"), versionId);
|
|
|
workspace.writeUtf8WorkspaceRelative(ctx, MEMORY_MD, targetContent);
|
|
|
if ("CONTENT_AND_WATERMARK".equals(mode)) {
|
|
|
if (StringUtils.isBlank(target.watermark())) {
|
|
|
@@ -740,15 +729,15 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
}
|
|
|
}
|
|
|
String newVersionId = snapshotMemory(memoryDir, targetContent, "RESTORE", userId,
|
|
|
- StringUtils.defaultIfBlank(note, "从历史版本恢复"), versionId);
|
|
|
+ StringUtils.defaultIfBlank(note, "从历史版本恢复"), versionId);
|
|
|
auditLogger.record(definition.getId(), caseId, userId, AiMemoryAuditLogger.EVENT_RESTORE, "OK",
|
|
|
- Map.of("versionId", versionId, "mode", mode,
|
|
|
- "newVersionId", StringUtils.defaultString(newVersionId),
|
|
|
- "chars", targetContent.length()));
|
|
|
+ Map.of("versionId", versionId, "mode", mode,
|
|
|
+ "newVersionId", StringUtils.defaultString(newVersionId),
|
|
|
+ "chars", targetContent.length()));
|
|
|
log.info("长期记忆已恢复:agent={}, userId={}, version={}, mode={}, newVersion={}",
|
|
|
- definition.getAgentCode(), userId, versionId, mode, newVersionId);
|
|
|
+ definition.getAgentCode(), userId, versionId, mode, newVersionId);
|
|
|
AiMemoryVersionStore.VersionEntry created = StringUtils.isBlank(newVersionId)
|
|
|
- ? target : memoryVersionStore.read(memoryDir, newVersionId);
|
|
|
+ ? target : memoryVersionStore.read(memoryDir, newVersionId);
|
|
|
return toVersionVo(created, targetContent, targetContent);
|
|
|
}
|
|
|
|
|
|
@@ -770,7 +759,7 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
}
|
|
|
String watermark = formatInstant(readConsolidationWatermark(memoryDir));
|
|
|
return memoryVersionStore.record(memoryDir, content, source, watermark, operatorId,
|
|
|
- note, restoredFrom, runtimeConfigStore.memory().getVersionRetention());
|
|
|
+ note, restoredFrom, runtimeConfigStore.memory().getVersionRetention());
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
@@ -800,7 +789,7 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
*/
|
|
|
private boolean hasMemoryData(Path userDir) {
|
|
|
return Files.isDirectory(userDir.resolve("memory"))
|
|
|
- || Files.isRegularFile(userDir.resolve(MEMORY_MD));
|
|
|
+ || Files.isRegularFile(userDir.resolve(MEMORY_MD));
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
@@ -815,8 +804,8 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
}
|
|
|
try (Stream<Path> files = Files.list(dir)) {
|
|
|
return (int) files.filter(Files::isRegularFile)
|
|
|
- .filter(path -> path.getFileName().toString().endsWith(".md"))
|
|
|
- .count();
|
|
|
+ .filter(path -> path.getFileName().toString().endsWith(".md"))
|
|
|
+ .count();
|
|
|
} catch (IOException e) {
|
|
|
return 0;
|
|
|
}
|
|
|
@@ -881,9 +870,9 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
log.warn("读取记忆审计日志失败:dir={}, err={}", memoryDir, e.getMessage());
|
|
|
}
|
|
|
return new AuditSummary(lastArchivedAt, failed,
|
|
|
- auditInt(lastConsolidation.get("batches")),
|
|
|
- auditInt(lastConsolidation.get("files")),
|
|
|
- auditInt(lastConsolidation.get("remaining")));
|
|
|
+ auditInt(lastConsolidation.get("batches")),
|
|
|
+ auditInt(lastConsolidation.get("files")),
|
|
|
+ auditInt(lastConsolidation.get("remaining")));
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
@@ -916,11 +905,11 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
/**
|
|
|
* 审计摘要(最后归档时间 + 失败事件数)。
|
|
|
*
|
|
|
- * @param lastArchivedAt 最后归档时间(ISO 时间,无记录时为空串)
|
|
|
- * @param failedCount 失败事件数
|
|
|
- * @param lastBatches 最近一次成功合并的批次数
|
|
|
- * @param lastMergedFiles 最近一次成功合并纳入的文件数
|
|
|
- * @param lastRemainingFiles 最近一次成功合并后剩余未处理的文件数
|
|
|
+ * @param lastArchivedAt 最后归档时间(ISO 时间,无记录时为空串)
|
|
|
+ * @param failedCount 失败事件数
|
|
|
+ * @param lastBatches 最近一次成功合并的批次数
|
|
|
+ * @param lastMergedFiles 最近一次成功合并纳入的文件数
|
|
|
+ * @param lastRemainingFiles 最近一次成功合并后剩余未处理的文件数
|
|
|
*/
|
|
|
private record AuditSummary(String lastArchivedAt, int failedCount, int lastBatches,
|
|
|
int lastMergedFiles, int lastRemainingFiles) {
|
|
|
@@ -940,9 +929,9 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
int removed = 0;
|
|
|
try (Stream<Path> files = Files.list(dir)) {
|
|
|
List<Path> expired = files.filter(Files::isRegularFile)
|
|
|
- .filter(path -> path.getFileName().toString().endsWith(".md"))
|
|
|
- .filter(path -> isOnOrBefore(path, cutoff))
|
|
|
- .toList();
|
|
|
+ .filter(path -> path.getFileName().toString().endsWith(".md"))
|
|
|
+ .filter(path -> isOnOrBefore(path, cutoff))
|
|
|
+ .toList();
|
|
|
for (Path file : expired) {
|
|
|
Files.deleteIfExists(file);
|
|
|
removed++;
|
|
|
@@ -968,14 +957,14 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
int removed = 0;
|
|
|
try (Stream<Path> files = Files.list(dir)) {
|
|
|
List<Path> expired = files.filter(Files::isRegularFile)
|
|
|
- .filter(path -> {
|
|
|
- try {
|
|
|
- return Files.getLastModifiedTime(path).toInstant().isBefore(threshold);
|
|
|
- } catch (IOException e) {
|
|
|
- return false;
|
|
|
- }
|
|
|
- })
|
|
|
- .toList();
|
|
|
+ .filter(path -> {
|
|
|
+ try {
|
|
|
+ return Files.getLastModifiedTime(path).toInstant().isBefore(threshold);
|
|
|
+ } catch (IOException e) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ })
|
|
|
+ .toList();
|
|
|
for (Path file : expired) {
|
|
|
Files.deleteIfExists(file);
|
|
|
removed++;
|
|
|
@@ -1025,9 +1014,9 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
if (removed > 0) {
|
|
|
Path temp = auditFile.resolveSibling(auditFile.getFileName() + ".tmp");
|
|
|
Files.writeString(temp, String.join("\n", kept) + (kept.isEmpty() ? "" : "\n"),
|
|
|
- StandardCharsets.UTF_8);
|
|
|
+ StandardCharsets.UTF_8);
|
|
|
Files.move(temp, auditFile, StandardCopyOption.REPLACE_EXISTING,
|
|
|
- StandardCopyOption.ATOMIC_MOVE);
|
|
|
+ StandardCopyOption.ATOMIC_MOVE);
|
|
|
}
|
|
|
return removed;
|
|
|
} catch (Exception e) {
|
|
|
@@ -1053,7 +1042,7 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
continue;
|
|
|
}
|
|
|
LocalDate modified = LocalDate.ofInstant(
|
|
|
- Files.getLastModifiedTime(file).toInstant(), java.time.ZoneId.systemDefault());
|
|
|
+ Files.getLastModifiedTime(file).toInstant(), java.time.ZoneId.systemDefault());
|
|
|
if (!modified.isAfter(cutoff)) {
|
|
|
Files.deleteIfExists(file);
|
|
|
removed++;
|
|
|
@@ -1094,6 +1083,24 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * 删除记忆目录的全部内容,但保留 {@code history/}:删除前快照就存放在这里,
|
|
|
+ * 用于误删后从「版本历史」恢复 MEMORY.md。每日流水等其余内容不保留。
|
|
|
+ */
|
|
|
+ private void deleteMemoryContentKeepingVersions(Path memoryDir) {
|
|
|
+ if (memoryDir == null || !Files.exists(memoryDir)) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ try (Stream<Path> children = Files.list(memoryDir)) {
|
|
|
+ List<Path> victims = children
|
|
|
+ .filter(path -> !AiMemoryVersionStore.HISTORY_DIR.equals(path.getFileName().toString()))
|
|
|
+ .toList();
|
|
|
+ victims.forEach(this::deleteRecursively);
|
|
|
+ } catch (IOException e) {
|
|
|
+ throw new ServiceException("删除记忆目录失败:" + e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* 递归删除目录(不存在时静默返回)。
|
|
|
*/
|
|
|
@@ -1120,21 +1127,21 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
* <p>每个流水文件先净化并就地回写(原文备份到 {@code memory/.quarantine/}),
|
|
|
* 这样无论后续是平台合并还是框架自动合并,读到的都是净化后的内容。</p>
|
|
|
*
|
|
|
- * @param workspace 工作区管理器
|
|
|
- * @param ctx 运行上下文
|
|
|
+ * @param workspace 工作区管理器
|
|
|
+ * @param ctx 运行上下文
|
|
|
* @param definition 智能体定义
|
|
|
- * @param userId 用户主键
|
|
|
- * @param watermark 上一次合并水位
|
|
|
+ * @param userId 用户主键
|
|
|
+ * @param watermark 上一次合并水位
|
|
|
* @return 待合并流水(可能为空)
|
|
|
*/
|
|
|
private List<DailyLedger> loadPendingLedgers(WorkspaceManager workspace, RuntimeContext ctx,
|
|
|
AiAgent definition, Long caseId, Long userId,
|
|
|
Instant watermark) {
|
|
|
List<String> dailyPaths = safeMemoryPaths(workspace, ctx).stream()
|
|
|
- // 只认根目录的 YYYY-MM-DD.md:history/ 版本、archive/、.declared.jsonl 一律不参与合并
|
|
|
- .filter(path -> LEDGER_PATH_PATTERN.matcher(path).matches())
|
|
|
- .sorted(Comparator.comparing(this::fileNameOf))
|
|
|
- .toList();
|
|
|
+ // 只认根目录的 YYYY-MM-DD.md:history/ 版本、archive/、.declared.jsonl 一律不参与合并
|
|
|
+ .filter(path -> LEDGER_PATH_PATTERN.matcher(path).matches())
|
|
|
+ .sorted(Comparator.comparing(this::fileNameOf))
|
|
|
+ .toList();
|
|
|
Path memoryDir = workspace.getMemoryDir(ctx);
|
|
|
List<DailyLedger> pending = new ArrayList<>();
|
|
|
AiMemorySanitizer.SanitizeResult total = AiMemorySanitizer.SanitizeResult.empty("");
|
|
|
@@ -1164,14 +1171,14 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
continue;
|
|
|
}
|
|
|
pending.add(new DailyLedger(path, sanitized.content(), modified,
|
|
|
- sanitizer.countEntries(sanitized.content())));
|
|
|
+ sanitizer.countEntries(sanitized.content())));
|
|
|
}
|
|
|
if (total.changed()) {
|
|
|
auditLogger.record(definition.getId(), caseId, userId,
|
|
|
- AiMemoryAuditLogger.EVENT_SANITIZE, "OK",
|
|
|
- Map.of("dropped", total.dropped(), "deduped", total.deduped(),
|
|
|
- "redacted", total.redacted(), "truncated", total.truncated(),
|
|
|
- "kept", total.kept()));
|
|
|
+ AiMemoryAuditLogger.EVENT_SANITIZE, "OK",
|
|
|
+ Map.of("dropped", total.dropped(), "deduped", total.deduped(),
|
|
|
+ "redacted", total.redacted(), "truncated", total.truncated(),
|
|
|
+ "kept", total.kept()));
|
|
|
}
|
|
|
return pending;
|
|
|
}
|
|
|
@@ -1194,7 +1201,7 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
DailyLedger daily = pending.get(end);
|
|
|
String block = renderBlock(daily);
|
|
|
if (end > start && (chars + block.length() > maxChars
|
|
|
- || entries + daily.entries() > AiMemorySanitizer.MAX_ENTRIES_PER_MERGE)) {
|
|
|
+ || entries + daily.entries() > AiMemorySanitizer.MAX_ENTRIES_PER_MERGE)) {
|
|
|
break;
|
|
|
}
|
|
|
chars += block.length();
|
|
|
@@ -1234,10 +1241,10 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
* <p>水位必须严格小于「下一批最早文件」的修改时间,否则下一轮会把未合并文件误判为已合并。
|
|
|
* 本批处理完所有文件时使用 {@code runStart}:任何在合并开始后新写入的流水仍晚于水位,下一轮继续。</p>
|
|
|
*
|
|
|
- * @param pending 待合并流水(旧→新)
|
|
|
+ * @param pending 待合并流水(旧→新)
|
|
|
* @param nextIndex 下一批起始下标
|
|
|
- * @param runStart 本轮合并开始时间
|
|
|
- * @param previous 本轮开始前的水位
|
|
|
+ * @param runStart 本轮合并开始时间
|
|
|
+ * @param previous 本轮开始前的水位
|
|
|
* @return 应写入的水位
|
|
|
*/
|
|
|
private Instant nextWatermark(List<DailyLedger> pending, int nextIndex, Instant runStart,
|
|
|
@@ -1247,21 +1254,21 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
// (Windows 上时钟精度约 15ms)读到的 mtime 可能晚于 runStart——此时必须把水位
|
|
|
// 压到「本批最新 mtime 之后」,否则下一轮会把刚合并的文件误判为未合并、反复合并
|
|
|
Instant latest = pending.stream()
|
|
|
- .map(DailyLedger::modifiedAt)
|
|
|
- .max(Comparator.naturalOrder())
|
|
|
- .orElse(runStart);
|
|
|
+ .map(DailyLedger::modifiedAt)
|
|
|
+ .max(Comparator.naturalOrder())
|
|
|
+ .orElse(runStart);
|
|
|
return !latest.isBefore(runStart) ? latest.plusNanos(1000) : runStart;
|
|
|
}
|
|
|
Instant nextModified = pending.subList(nextIndex, pending.size()).stream()
|
|
|
- .map(DailyLedger::modifiedAt)
|
|
|
- .min(Comparator.naturalOrder())
|
|
|
- .orElse(runStart);
|
|
|
+ .map(DailyLedger::modifiedAt)
|
|
|
+ .min(Comparator.naturalOrder())
|
|
|
+ .orElse(runStart);
|
|
|
if (Instant.EPOCH.equals(nextModified)) {
|
|
|
// 无法读取下一批文件时间时宁可不推进水位,避免把未合并文件误判为已合并
|
|
|
return previous;
|
|
|
}
|
|
|
Instant candidate = nextModified.isAfter(runStart)
|
|
|
- ? runStart : nextModified.minusNanos(1);
|
|
|
+ ? runStart : nextModified.minusNanos(1);
|
|
|
return candidate.isBefore(previous) ? previous : candidate;
|
|
|
}
|
|
|
|
|
|
@@ -1296,7 +1303,7 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
}
|
|
|
try {
|
|
|
Path backup = memoryDir.resolve(QUARANTINE_DIR)
|
|
|
- .resolve(fileNameOf(path) + "." + BACKUP_TIME_FORMAT.format(java.time.LocalDateTime.now()) + ".bak");
|
|
|
+ .resolve(fileNameOf(path) + "." + BACKUP_TIME_FORMAT.format(java.time.LocalDateTime.now()) + ".bak");
|
|
|
Files.createDirectories(backup.getParent());
|
|
|
Files.copy(file, backup, StandardCopyOption.REPLACE_EXISTING);
|
|
|
Files.writeString(file, content, StandardCharsets.UTF_8);
|
|
|
@@ -1320,15 +1327,15 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
private ConsolidationResult callConsolidationModel(Model model, int maxTokens, String memoryMd,
|
|
|
String ledger) {
|
|
|
String userContent = "Current MEMORY.md content:\n\n"
|
|
|
- + (StringUtils.isBlank(memoryMd) ? "(empty)" : memoryMd)
|
|
|
- + "\n\nNew daily ledger entries to merge:\n\n" + ledger;
|
|
|
+ + (StringUtils.isBlank(memoryMd) ? "(empty)" : memoryMd)
|
|
|
+ + "\n\nNew daily ledger entries to merge:\n\n" + ledger;
|
|
|
List<Msg> messages = List.of(
|
|
|
- Msg.builder().role(MsgRole.SYSTEM).textContent(consolidationPrompt(maxTokens)).build(),
|
|
|
- Msg.builder().role(MsgRole.USER).textContent(userContent).build());
|
|
|
+ Msg.builder().role(MsgRole.SYSTEM).textContent(consolidationPrompt(maxTokens)).build(),
|
|
|
+ Msg.builder().role(MsgRole.USER).textContent(userContent).build());
|
|
|
List<ChatResponse> responses = model
|
|
|
- .stream(messages, null, GenerateOptions.builder().stream(true).build())
|
|
|
- .collectList()
|
|
|
- .block(CONSOLIDATE_TIMEOUT);
|
|
|
+ .stream(messages, null, GenerateOptions.builder().stream(true).build())
|
|
|
+ .collectList()
|
|
|
+ .block(CONSOLIDATE_TIMEOUT);
|
|
|
if (responses == null) {
|
|
|
return new ConsolidationResult("", null);
|
|
|
}
|
|
|
@@ -1345,12 +1352,12 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
continue;
|
|
|
}
|
|
|
response.getContent().stream()
|
|
|
- .filter(TextBlock.class::isInstance)
|
|
|
- .map(TextBlock.class::cast)
|
|
|
- .forEach(block -> merged.append(block.getText()));
|
|
|
+ .filter(TextBlock.class::isInstance)
|
|
|
+ .map(TextBlock.class::cast)
|
|
|
+ .forEach(block -> merged.append(block.getText()));
|
|
|
}
|
|
|
ChatTokenUsage tokens = promptTokens + completionTokens == 0 ? null
|
|
|
- : new ChatTokenUsage(promptTokens, completionTokens, promptTokens + completionTokens);
|
|
|
+ : new ChatTokenUsage(promptTokens, completionTokens, promptTokens + completionTokens);
|
|
|
return new ConsolidationResult(merged.toString().trim(), tokens);
|
|
|
}
|
|
|
|
|
|
@@ -1369,11 +1376,11 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
}
|
|
|
try {
|
|
|
Long modelId = definition.getMemoryModelId() != null
|
|
|
- ? definition.getMemoryModelId() : definition.getModelId();
|
|
|
+ ? definition.getMemoryModelId() : definition.getModelId();
|
|
|
usageStatService.accumulate(userId, definition.getId(), modelId, usage, 0, 1);
|
|
|
} catch (Exception e) {
|
|
|
log.warn("长期记忆合并用量记录失败:agent={}, userId={}, err={}",
|
|
|
- definition.getAgentCode(), userId, e.getMessage());
|
|
|
+ definition.getAgentCode(), userId, e.getMessage());
|
|
|
}
|
|
|
}
|
|
|
|
|
|
@@ -1463,8 +1470,8 @@ public class AiMemoryServiceImpl implements IAiMemoryService {
|
|
|
*/
|
|
|
private RuntimeContext contextOf(Long userId, Long caseId) {
|
|
|
RuntimeContext.Builder builder = RuntimeContext.builder()
|
|
|
- .userId(String.valueOf(userId))
|
|
|
- .sessionId(CONSOLE_SESSION);
|
|
|
+ .userId(String.valueOf(userId))
|
|
|
+ .sessionId(CONSOLE_SESSION);
|
|
|
if (caseId != null) {
|
|
|
builder.put(AiRuntimeKeys.CASE_ID, String.valueOf(caseId));
|
|
|
}
|