From 001c2551a88576418c90286bde35d5657088c895 Mon Sep 17 00:00:00 2001 From: SerenNoble Date: Wed, 15 Jul 2026 17:16:57 +0800 Subject: [PATCH] =?UTF-8?q?fix(manager-api):=20=E4=BF=AE=E5=A4=8D=E7=BC=96?= =?UTF-8?q?=E8=AF=91=E9=94=99=E8=AF=AF=E5=B9=B6=E5=AE=8C=E5=96=84=20agent-?= =?UTF-8?q?ext-fields=20=E9=83=A8=E7=BD=B2=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GrowthPersonaClient/DingTalkNotifier 改用 jakarta 注解与 StandardCharsets,修复 JDK21 编译错误 - ConfigServiceImpl 补充 DeviceExtService/DeviceExtEntity import - DeviceExtController 返回类型显式 Result - DingTalkNotifier 支持加签(SECRET)模式,webhook/secret 从环境变量注入 - DeviceExtController 增加设备归属校验,防越权篡改孩子信息 - GrowthPersonaClient 改用复制快照读取,解耦 growth_service 的 WAL/只读挂载依赖 - docker-compose 用 ${VAR:-} 注入钉钉与画像库环境变量 --- docker-compose-selfbuild.yml | 7 + .../agent/service/DingTalkNotifier.java | 79 ++++++++++ .../agent/service/GrowthPersonaClient.java | 111 ++++++++++++++ .../service/impl/ConfigServiceImpl.java | 64 +++++++- .../controller/DeviceExtController.java | 77 ++++++++++ .../src/main/resources/application.yml | 138 +++++++++--------- 6 files changed, 407 insertions(+), 69 deletions(-) create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/agent/service/DingTalkNotifier.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/agent/service/GrowthPersonaClient.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceExtController.java diff --git a/docker-compose-selfbuild.yml b/docker-compose-selfbuild.yml index f41d919c2..b19138324 100644 --- a/docker-compose-selfbuild.yml +++ b/docker-compose-selfbuild.yml @@ -75,10 +75,17 @@ services: - SPRING_DATASOURCE_DRUID_PASSWORD=123456 - SPRING_DATA_REDIS_HOST=xiaozhi-esp32-server-redis - 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 volumes: # 上传文件目录 - ./uploadfile:/uploadfile + # 成长服务画像库(只读,manager-api 直读 growth_service.db) + - /var/sqllit:/var/sqllit:ro # 数据库模块 xiaozhi-esp32-server-db: diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/DingTalkNotifier.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/DingTalkNotifier.java new file mode 100644 index 000000000..4e745f939 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/DingTalkNotifier.java @@ -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 text = new HashMap<>(); + text.put("content", content); + Map 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 后追加 ×tamp=...&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; + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/GrowthPersonaClient.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/GrowthPersonaClient.java new file mode 100644 index 000000000..dee41880f --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/GrowthPersonaClient.java @@ -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); + } + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java index 6e0978f7b..4d8c71ee7 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java @@ -43,6 +43,8 @@ import xiaozhi.modules.agent.vo.AgentVoicePrintVO; import xiaozhi.modules.correctword.vo.CorrectWordSimpleVO; import xiaozhi.modules.config.service.ConfigService; 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.model.entity.ModelConfigEntity; import xiaozhi.modules.model.service.ModelConfigService; @@ -71,6 +73,7 @@ public class ConfigServiceImpl implements ConfigService { private final VoiceCloneService cloneVoiceService; private final AgentVoicePrintDao agentVoicePrintDao; private final CorrectWordFileService correctWordFileService; + private final DeviceExtService deviceExtService; @Override public Object getConfig(Boolean isCache) { @@ -228,10 +231,8 @@ public class ConfigServiceImpl implements ConfigService { // 获取声纹信息 buildVoiceprintConfig(agent.getId(), result); - // 解析生效 agent(匹配角色有则覆盖,无则回退设备绑定 agent);prompt + ext 都从生效 agent 取 - AgentEntity effectiveAgent = resolveEffectiveAgent(device, agent); - String prompt = effectiveAgent.getSystemPrompt(); - prompt = applyExtToPrompt(prompt, effectiveAgent.getId()); + // 解析生效 prompt:优先乐宝模板(matched_template_id)+设备ext注入;否则设备绑定agent+agent_ext注入 + String prompt = resolveEffectivePrompt(device, agent); // 构建模块配置 buildModuleConfig( @@ -272,6 +273,61 @@ public class ConfigServiceImpl implements ConfigService { .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。 * prompt 与 ext 都从生效 agent 取,保证话术与其扩展字段同源。 diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceExtController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceExtController.java new file mode 100644 index 000000000..a9e6a416f --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceExtController.java @@ -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 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 saveExt(@PathVariable String id, @RequestBody Map body) { + if (assertOwner(id) == null) { + return new Result().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<>(); + } +} diff --git a/main/manager-api/src/main/resources/application.yml b/main/manager-api/src/main/resources/application.yml index 3daf48a14..82654be26 100644 --- a/main/manager-api/src/main/resources/application.yml +++ b/main/manager-api/src/main/resources/application.yml @@ -1,66 +1,74 @@ -# Tomcat -server: - tomcat: - uri-encoding: UTF-8 - threads: - max: 1000 - min-spare: 30 - port: 8002 - servlet: - context-path: /xiaozhi - session: - cookie: - http-only: true - -spring: - # 环境 dev|test|prod - profiles: - active: dev - messages: - encoding: UTF-8 - basename: i18n/messages - servlet: - multipart: - max-file-size: 100MB - max-request-size: 100MB - enabled: true - main: - allow-bean-definition-overriding: true - -knife4j: - enable: true - basic: - enable: false - username: admin - password: admin - setting: - enableFooter: false - -renren: - redis: - open: true - xss: - enabled: true - exclude-urls: - -#mybatis -mybatis-plus: - mapper-locations: classpath*:/mapper/**/*.xml - #实体扫描,多个package用逗号或者分号分隔 - typeAliasesPackage: xiaozhi.modules.*.entity - global-config: - #数据库相关配置 - db-config: - #主键类型 - id-type: ASSIGN_ID - banner: false - #原生配置 - configuration: - map-underscore-to-camel-case: true - cache-enabled: false - call-setters-on-nulls: true - jdbc-type-for-null: 'null' - configuration-properties: - prefix: - blobType: BLOB +# Tomcat +server: + tomcat: + uri-encoding: UTF-8 + threads: + max: 1000 + min-spare: 30 + port: 8002 + servlet: + context-path: /xiaozhi + session: + cookie: + http-only: true + +spring: + # 环境 dev|test|prod + profiles: + active: dev + messages: + encoding: UTF-8 + basename: i18n/messages + servlet: + multipart: + max-file-size: 100MB + max-request-size: 100MB + enabled: true + main: + allow-bean-definition-overriding: true + +knife4j: + enable: true + basic: + enable: false + username: admin + password: admin + setting: + enableFooter: false + +renren: + redis: + open: true + xss: + enabled: true + 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-plus: + mapper-locations: classpath*:/mapper/**/*.xml + #实体扫描,多个package用逗号或者分号分隔 + typeAliasesPackage: xiaozhi.modules.*.entity + global-config: + #数据库相关配置 + db-config: + #主键类型 + id-type: ASSIGN_ID + banner: false + #原生配置 + configuration: + map-underscore-to-camel-case: true + cache-enabled: false + call-setters-on-nulls: true + jdbc-type-for-null: 'null' + configuration-properties: + prefix: + blobType: BLOB boolValue: TRUE \ No newline at end of file