fix(manager-api): 修复编译错误并完善 agent-ext-fields 部署配置

- GrowthPersonaClient/DingTalkNotifier 改用 jakarta 注解与 StandardCharsets,修复 JDK21 编译错误
- ConfigServiceImpl 补充 DeviceExtService/DeviceExtEntity import
- DeviceExtController 返回类型显式 Result<Void>
- DingTalkNotifier 支持加签(SECRET)模式,webhook/secret 从环境变量注入
- DeviceExtController 增加设备归属校验,防越权篡改孩子信息
- GrowthPersonaClient 改用复制快照读取,解耦 growth_service 的 WAL/只读挂载依赖
- docker-compose 用 ${VAR:-} 注入钉钉与画像库环境变量
This commit is contained in:
SerenNoble 2026-07-15 17:16:57 +08:00
parent e3b288cf29
commit 001c2551a8
6 changed files with 407 additions and 69 deletions

View file

@ -75,10 +75,17 @@ services:
- SPRING_DATASOURCE_DRUID_PASSWORD=123456 - SPRING_DATASOURCE_DRUID_PASSWORD=123456
- SPRING_DATA_REDIS_HOST=xiaozhi-esp32-server-redis - SPRING_DATA_REDIS_HOST=xiaozhi-esp32-server-redis
- SPRING_DATA_REDIS_PASSWORD= - SPRING_DATA_REDIS_PASSWORD=
# 钉钉兜底通知(从宿主机环境变量注入,不写死密钥)
- DINGTALK_WEBHOOK=${DINGTALK_WEBHOOK:-}
- DINGTALK_SECRET=${DINGTALK_SECRET:-}
# 成长服务画像库路径(容器内经 :ro 挂载)
- GROWTH_PROFILE_DB_PATH=/var/sqllit/growth_service.db
- SPRING_DATA_REDIS_PORT=6379 - SPRING_DATA_REDIS_PORT=6379
volumes: volumes:
# 上传文件目录 # 上传文件目录
- ./uploadfile:/uploadfile - ./uploadfile:/uploadfile
# 成长服务画像库(只读,manager-api 直读 growth_service.db)
- /var/sqllit:/var/sqllit:ro
# 数据库模块 # 数据库模块
xiaozhi-esp32-server-db: xiaozhi-esp32-server-db:

View file

@ -0,0 +1,79 @@
package xiaozhi.modules.agent.service;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
/**
* 钉钉群机器人通知:角色不足兜底时通知管理员扩库。
* webhook / secret 从 application.yml(growth.dingtalk-webhook / growth.dingtalk-secret)读取,
* 该值通过环境变量 DINGTALK_WEBHOOK / DINGTALK_SECRET 注入(不落库明文)。
* 安全模式:优先「加签」(secret 非空时按 HmacSHA256 生成 timestamp+sign 追加到 URL);
* secret 为空则按「自定义关键字」模式直发(webhook 需已配关键字「角色匹配」)。
* webhook 未配置则跳过,不阻塞主流程。
*/
@Slf4j
@Component
public class DingTalkNotifier {
@Value("${growth.dingtalk-webhook:}")
private String webhook;
@Value("${growth.dingtalk-secret:}")
private String secret;
/**
* 发送钉钉文本通知。webhook 未配置则跳过(不抛异常)。
*/
public void notify(String content) {
if (webhook == null || webhook.isBlank()) {
log.warn("[dingtalk] webhook 未配置,跳过通知:{}", content);
return;
}
try {
Map<String, Object> text = new HashMap<>();
text.put("content", content);
Map<String, Object> body = new HashMap<>();
body.put("msgtype", "text");
body.put("text", text);
String postUrl = buildSignedUrl(webhook, secret);
String resp = HttpUtil.post(postUrl, JSONUtil.toJsonStr(body));
log.info("[dingtalk] 通知已发送,响应:{}", resp);
} catch (Exception e) {
log.warn("[dingtalk] 通知发送失败:{}", e.getMessage());
}
}
/**
* 加签:secret 非空时在 webhook 后追加 &timestamp=...&sign=...
* 算法:stringToSign = timestamp + "\n" + secret;sign = Base64(HmacSHA256(stringToSign, secret))
*/
private String buildSignedUrl(String webhook, String secret) throws NoSuchAlgorithmException, InvalidKeyException {
if (secret == null || secret.isBlank()) {
return webhook; // 关键字模式
}
long timestamp = System.currentTimeMillis();
String stringToSign = timestamp + "\n" + secret;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
String sign = Base64.getEncoder().encodeToString(signData);
String encodedSign = URLEncoder.encode(sign, StandardCharsets.UTF_8);
String sep = webhook.contains("?") ? "&" : "?";
return webhook + sep + "timestamp=" + timestamp + "&sign=" + encodedSign;
}
}

View file

@ -0,0 +1,111 @@
package xiaozhi.modules.agent.service;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
/**
* 成长服务画像客户端:读取成长服务 growth_service.db 的 profile_enrichment 表,
* 取某设备最新 13 维儿童画像(extension_fields JSON)。
*
* 读取策略:把源库(+WAL 若有)复制成本地只读快照(临时目录)再查询。
* 这样彻底解耦对成长服务日志模式的依赖——无论对方用 WAL 还是 DELETE 模式、无论源库以 :ro 挂载,
* 快照在可写临时目录,SQLite 总能正常打开并应用 WAL 帧,读到最新画像。
* 快照带 5 分钟 TTL 缓存,限制复制 IO(周期任务按用户调用也不会频繁拷贝)。
*
* 读取失败(库不存在/设备无画像/复制失败)降级返回 null,绝不抛异常阻断主流程。
*/
@Slf4j
@Component
public class GrowthPersonaClient {
@Value("${growth.profile-db-path:}")
private String dbPath;
private static final long SNAPSHOT_TTL_MS = 5 * 60 * 1000L;
private final Object snapshotLock = new Object();
private volatile long lastCopyTs = 0L;
private volatile String snapshotDbPath;
@PostConstruct
public void init() {
String tmp = System.getProperty("java.io.tmpdir");
File dir = new File(tmp, "growth_persona_snapshot");
dir.mkdirs();
snapshotDbPath = new File(dir, "growth_service.db").getAbsolutePath();
}
/**
* 按 deviceId 取最新画像 extension_fields JSON;无则 null。
*/
public String getProfileJson(String deviceId) {
if (deviceId == null || deviceId.isBlank() || dbPath == null || dbPath.isBlank()) {
return null;
}
// 优先用快照(复制失败则退而直读源库,最差降级 null)
try {
ensureSnapshot();
} catch (Exception e) {
log.warn("[growth-persona] 快照复制失败,尝试直读源库:{}", e.getMessage());
}
String path = (snapshotDbPath != null && new File(snapshotDbPath).exists()) ? snapshotDbPath : dbPath;
// 只读连接(SQLITE_OPEN_READONLY=1),busy_timeout 避免并发读短暂锁等待
String url = "jdbc:sqlite:" + path;
Properties props = new Properties();
props.setProperty("open_mode", "1");
props.setProperty("busy_timeout", "3000");
String sql = "SELECT extension_fields FROM profile_enrichment WHERE device_id = ? ORDER BY updated_at DESC LIMIT 1";
try (Connection conn = DriverManager.getConnection(url, props);
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, deviceId);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getString("extension_fields");
}
}
} catch (Exception e) {
log.warn("[growth-persona] 读画像失败 device={}:{}", deviceId, e.getMessage());
}
return null;
}
/** 复制源库(含 -wal)到本地快照;TTL 内复用 */
private void ensureSnapshot() throws Exception {
long now = System.currentTimeMillis();
if (snapshotDbPath != null && new File(snapshotDbPath).exists() && (now - lastCopyTs) < SNAPSHOT_TTL_MS) {
return;
}
synchronized (snapshotLock) {
if (snapshotDbPath != null && new File(snapshotDbPath).exists() && (now - lastCopyTs) < SNAPSHOT_TTL_MS) {
return;
}
File src = new File(dbPath);
if (!src.exists()) {
return;
}
File dst = new File(snapshotDbPath);
Files.copy(src.toPath(), dst.toPath(), StandardCopyOption.REPLACE_EXISTING);
// 复制 -wal(若存在),保证 WAL 帧一并带入快照,读到最新画像
File srcWal = new File(dbPath + "-wal");
if (srcWal.exists()) {
Files.copy(srcWal.toPath(), new File(snapshotDbPath + "-wal").toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
lastCopyTs = System.currentTimeMillis();
log.debug("[growth-persona] 快照已刷新:{}", snapshotDbPath);
}
}
}

View file

@ -43,6 +43,8 @@ import xiaozhi.modules.agent.vo.AgentVoicePrintVO;
import xiaozhi.modules.correctword.vo.CorrectWordSimpleVO; import xiaozhi.modules.correctword.vo.CorrectWordSimpleVO;
import xiaozhi.modules.config.service.ConfigService; import xiaozhi.modules.config.service.ConfigService;
import xiaozhi.modules.device.entity.DeviceEntity; import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.device.entity.DeviceExtEntity;
import xiaozhi.modules.device.service.DeviceExtService;
import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.device.service.DeviceService;
import xiaozhi.modules.model.entity.ModelConfigEntity; import xiaozhi.modules.model.entity.ModelConfigEntity;
import xiaozhi.modules.model.service.ModelConfigService; import xiaozhi.modules.model.service.ModelConfigService;
@ -71,6 +73,7 @@ public class ConfigServiceImpl implements ConfigService {
private final VoiceCloneService cloneVoiceService; private final VoiceCloneService cloneVoiceService;
private final AgentVoicePrintDao agentVoicePrintDao; private final AgentVoicePrintDao agentVoicePrintDao;
private final CorrectWordFileService correctWordFileService; private final CorrectWordFileService correctWordFileService;
private final DeviceExtService deviceExtService;
@Override @Override
public Object getConfig(Boolean isCache) { public Object getConfig(Boolean isCache) {
@ -228,10 +231,8 @@ public class ConfigServiceImpl implements ConfigService {
// 获取声纹信息 // 获取声纹信息
buildVoiceprintConfig(agent.getId(), result); buildVoiceprintConfig(agent.getId(), result);
// 解析生效 agent(匹配角色有则覆盖,无则回退设备绑定 agent);prompt + ext 都从生效 agent 取 // 解析生效 prompt:优先乐宝模板(matched_template_id)+设备ext注入;否则设备绑定agent+agent_ext注入
AgentEntity effectiveAgent = resolveEffectiveAgent(device, agent); String prompt = resolveEffectivePrompt(device, agent);
String prompt = effectiveAgent.getSystemPrompt();
prompt = applyExtToPrompt(prompt, effectiveAgent.getId());
// 构建模块配置 // 构建模块配置
buildModuleConfig( buildModuleConfig(
@ -272,6 +273,61 @@ public class ConfigServiceImpl implements ConfigService {
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
/**
* 解析生效 prompt:优先乐宝模板(matched_template_id)+ 设备ext注入;
* 否则回退设备绑定 agent(现有 resolveEffectiveAgent)+ agent_ext 注入。
* 模板路径追加个性化设定块 {{ext.*}} 由设备ext填充;agent 路径沿用现有 agent_ext。
*/
private String resolveEffectivePrompt(DeviceEntity device, AgentEntity fallbackAgent) {
if (device != null && device.getUserId() != null) {
UserPersonaAssignmentEntity a = userPersonaAssignmentService.getByUserId(device.getUserId());
if (a != null && a.getMatchedTemplateId() != null && !a.getMatchedTemplateId().isBlank()) {
AgentTemplateEntity tpl = agentTemplateService.getById(a.getMatchedTemplateId());
if (tpl != null && tpl.getSystemPrompt() != null && !tpl.getSystemPrompt().isBlank()) {
String prompt = appendPersonalizationBlock(tpl.getSystemPrompt());
return applyDeviceExtToPrompt(prompt, device.getId());
}
}
}
// 回退:设备绑定 agent(prompt + agent_ext 注入,现有行为)
AgentEntity effective = resolveEffectiveAgent(device, fallbackAgent);
return applyExtToPrompt(effective.getSystemPrompt(), effective.getId());
}
/**
* 给乐宝模板 prompt 追加个性化设定块(不改原 prompt),占位符由设备ext填充。
*/
private String appendPersonalizationBlock(String prompt) {
return prompt + "\n\n【个性化设定】\n"
+ "- 孩子年龄段:{{ext.childAgeRange}}\n"
+ "- 孩子性格:{{ext.childPersonality}}\n"
+ "- 家长期望:{{ext.parentGoals}}\n"
+ "- 家长关注:{{ext.parentConcerns}}\n"
+ "- 内容偏好:{{ext.contentPreference}}";
}
/**
* 从 ai_device_ext 取值替换 {{ext.key}}(设备级扩展字段:孩子信息+家长期望)。
* 没值的占位符清空,避免漏给 LLM。
*/
private String applyDeviceExtToPrompt(String prompt, String deviceId) {
if (prompt == null || deviceId == null) {
return prompt;
}
DeviceExtEntity ext = deviceExtService.getByDeviceId(deviceId);
if (ext != null && ext.getExtJson() != null && !ext.getExtJson().isBlank()) {
try {
JSONObject m = JSONUtil.parseObj(ext.getExtJson());
for (String k : m.keySet()) {
prompt = prompt.replace("{{ext." + k + "}}", m.getStr(k));
}
} catch (Exception ignore) {
// ext_json 解析失败:当无 ext 处理,不影响主流程
}
}
return prompt.replaceAll("\\{\\{ext\\.[^}]*\\}\\}", "");
}
/** /**
* 解析「生效 agent」:匹配角色(有且有效)则用它,否则回退设备绑定 agent。 * 解析「生效 agent」:匹配角色(有且有效)则用它,否则回退设备绑定 agent。
* prompt 与 ext 都从生效 agent 取,保证话术与其扩展字段同源。 * prompt 与 ext 都从生效 agent 取,保证话术与其扩展字段同源。

View file

@ -0,0 +1,77 @@
package xiaozhi.modules.device.controller;
import java.util.Map;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.hutool.json.JSONUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import xiaozhi.common.utils.Result;
import xiaozhi.modules.agent.service.PersonaMatcherService;
import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.device.entity.DeviceExtEntity;
import xiaozhi.modules.device.service.DeviceExtService;
import xiaozhi.modules.device.service.DeviceService;
import xiaozhi.modules.security.user.SecurityUser;
@Slf4j
@Tag(name = "设备扩展字段")
@RestController
@RequestMapping("/device")
@AllArgsConstructor
public class DeviceExtController {
private final DeviceExtService deviceExtService;
private final DeviceService deviceService;
private final PersonaMatcherService personaMatcherService;
/** 校验设备存在且归属当前用户;越权时返回 null(调用方据此返回错误) */
private DeviceEntity assertOwner(String id) {
DeviceEntity device = deviceService.selectById(id);
Long curUid = SecurityUser.getUserId();
if (device == null || device.getUserId() == null || !device.getUserId().equals(curUid)) {
return null;
}
return device;
}
@GetMapping("/{id}/ext")
@Operation(summary = "取设备扩展字段(JSON 对象:孩子信息+家长期望)")
@RequiresPermissions("sys:role:normal")
public Result<Object> getExt(@PathVariable String id) {
if (assertOwner(id) == null) {
return new Result<>().error("设备不存在");
}
DeviceExtEntity e = deviceExtService.getByDeviceId(id);
Object obj = (e != null && e.getExtJson() != null && !e.getExtJson().isBlank())
? JSONUtil.parseObj(e.getExtJson())
: JSONUtil.parseObj("{}");
return new Result<>().ok(obj);
}
@PutMapping("/{id}/ext")
@Operation(summary = "整体覆盖设备扩展字段(body=JSON 对象)。保存后异步触发冷启动匹配(若该设备无 manual 锁定)")
@RequiresPermissions("sys:role:normal")
public Result<Void> saveExt(@PathVariable String id, @RequestBody Map<String, Object> body) {
if (assertOwner(id) == null) {
return new Result<Void>().error("设备不存在");
}
deviceExtService.saveOrUpdate(id, JSONUtil.toJsonStr(body));
// 异步触发冷启动匹配(@Async 在 PersonaMatcherService 内生效,不阻塞本次请求)
try {
personaMatcherService.matchColdStart(id);
} catch (Exception e) {
log.warn("[device-ext] 触发冷启动匹配失败 device={}:{}", id, e.getMessage());
}
return new Result<>();
}
}

View file

@ -43,6 +43,14 @@ renren:
enabled: true enabled: true
exclude-urls: exclude-urls:
# 成长服务画像库(宿主机 /var/sqllit/growth_service.db,容器内只读挂载)
growth:
profile-db-path: ${GROWTH_PROFILE_DB_PATH:/var/sqllit/growth_service.db}
# 钉钉群机器人(角色不足兜底通知)。webhook/secret 通过环境变量注入,不落库明文。
# 安全模式:secret 非空=加签(自动追加 timestamp+sign);为空=自定义关键字「角色匹配」。
dingtalk-webhook: ${DINGTALK_WEBHOOK:}
dingtalk-secret: ${DINGTALK_SECRET:}
#mybatis #mybatis
mybatis-plus: mybatis-plus:
mapper-locations: classpath*:/mapper/**/*.xml mapper-locations: classpath*:/mapper/**/*.xml